@stacksjs/ts-cloud 0.16.21 → 0.16.22

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 (194) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/aws/xml-result.d.ts +20 -0
  3. package/dist/{chunk-g6g33pt9.js → bin/chunk-09d5qe73.js} +7 -7
  4. package/dist/bin/chunk-0cefbrxg.js +1 -0
  5. package/dist/bin/{chunk-ys5n5c84.js → chunk-12q8xrct.js} +5 -5
  6. package/dist/bin/chunk-1srmd473.js +1 -0
  7. package/dist/bin/{chunk-mxvekmdx.js → chunk-24njmb7d.js} +114 -114
  8. package/dist/bin/chunk-27ka240w.js +1 -0
  9. package/dist/bin/{chunk-ngyqqy6d.js → chunk-2gd8kqzq.js} +5 -5
  10. package/dist/bin/{chunk-djjj62c0.js → chunk-330kytpm.js} +2 -2
  11. package/dist/bin/{chunk-h1rb8qvt.js → chunk-3425j97b.js} +2 -2
  12. package/dist/bin/chunk-3bq69jqk.js +1 -0
  13. package/dist/bin/chunk-4pysr1ky.js +1 -0
  14. package/dist/bin/chunk-56zfvf7e.js +1 -0
  15. package/dist/bin/chunk-59nav625.js +1 -0
  16. package/dist/bin/{chunk-6kx50dyc.js → chunk-5bsknbr7.js} +1 -1
  17. package/dist/bin/{chunk-t10e32an.js → chunk-636jsmnz.js} +6 -6
  18. package/dist/bin/chunk-7kj8f72p.js +2 -0
  19. package/dist/bin/{chunk-e55fdn0r.js → chunk-7xr71hnt.js} +3 -3
  20. package/dist/bin/chunk-87f5d9qj.js +2 -0
  21. package/dist/bin/{chunk-tq172j2x.js → chunk-8agf66wn.js} +3 -3
  22. package/dist/bin/chunk-8fjzcr2w.js +1 -0
  23. package/dist/bin/{chunk-apnhhfkj.js → chunk-8wnkx3jf.js} +2 -2
  24. package/dist/bin/{chunk-z1dtdw3j.js → chunk-95v6ry1x.js} +5 -5
  25. package/dist/bin/chunk-9fq0bezb.js +1 -0
  26. package/dist/bin/chunk-9wpy7r9f.js +1 -0
  27. package/dist/bin/{chunk-5a7sxtwn.js → chunk-a0me5fed.js} +2 -2
  28. package/dist/bin/{chunk-148x1zq8.js → chunk-and7khsv.js} +2 -2
  29. package/dist/bin/{chunk-6wqjk007.js → chunk-ardzx4dw.js} +130 -130
  30. package/dist/bin/{chunk-0trtkv9g.js → chunk-c04dygzg.js} +6 -6
  31. package/dist/bin/chunk-eetz9jgy.js +1 -0
  32. package/dist/bin/chunk-eg6156wp.js +1 -0
  33. package/dist/bin/chunk-ezpz96kp.js +1 -0
  34. package/dist/bin/chunk-f2qpsrrj.js +1 -0
  35. package/dist/bin/chunk-f3sbq7pw.js +2 -0
  36. package/dist/bin/chunk-gmabk4qn.js +1 -0
  37. package/dist/bin/{chunk-9vmtm7nq.js → chunk-hmnaen1z.js} +2 -2
  38. package/dist/bin/{chunk-x63yz8xg.js → chunk-jp23ed1q.js} +1 -1
  39. package/dist/bin/{chunk-0f1qpmd6.js → chunk-k6apknm8.js} +5 -5
  40. package/dist/bin/{chunk-2mv692y4.js → chunk-k97ms0bs.js} +5 -5
  41. package/dist/bin/chunk-kr51h4gk.js +1 -0
  42. package/dist/bin/{chunk-290bzm2m.js → chunk-m51vpvr6.js} +3 -3
  43. package/dist/bin/{chunk-mx9ppkmn.js → chunk-mbqwrs7a.js} +4 -4
  44. package/dist/bin/{chunk-rbtt23vx.js → chunk-mz2jbtcs.js} +3 -3
  45. package/dist/bin/{chunk-dyh0vndw.js → chunk-n7hmjzgd.js} +4 -4
  46. package/dist/bin/{chunk-dmdg23a5.js → chunk-n8dsby4k.js} +2 -2
  47. package/dist/bin/chunk-nx8gpr90.js +34 -0
  48. package/dist/bin/chunk-q62ggp3g.js +1 -0
  49. package/dist/bin/chunk-q957s44c.js +1 -0
  50. package/dist/bin/{chunk-k7wh1wr5.js → chunk-qqqx70g6.js} +2 -2
  51. package/dist/bin/{chunk-gfr2215x.js → chunk-rm59bcnw.js} +60 -60
  52. package/dist/bin/chunk-rm6qnyce.js +2 -0
  53. package/dist/bin/chunk-rxehseyz.js +1 -0
  54. package/dist/bin/chunk-tfz7djw9.js +1 -0
  55. package/dist/bin/chunk-tr8901hb.js +1 -0
  56. package/dist/bin/{chunk-3n733cgx.js → chunk-v5bjbyve.js} +2 -2
  57. package/dist/bin/{chunk-90102shh.js → chunk-v980gs11.js} +2 -2
  58. package/dist/bin/chunk-vqb80dyg.js +1 -0
  59. package/dist/bin/{chunk-1j8b1d58.js → chunk-vskhr9qy.js} +2 -2
  60. package/dist/bin/{chunk-e24bscb0.js → chunk-wqydambz.js} +17 -17
  61. package/dist/bin/chunk-wysyyysg.js +1 -0
  62. package/dist/bin/chunk-xfs7rscr.js +1 -0
  63. package/dist/bin/cli.js +356 -356
  64. package/dist/bin/dashboard-server.js +1 -1
  65. package/dist/chunk-2ap78e1s.js +5 -0
  66. package/dist/{chunk-k53agv2m.js → chunk-2dextjqf.js} +2 -2
  67. package/dist/chunk-2fa9cdyf.js +1 -0
  68. package/dist/{chunk-z3wynefj.js → chunk-3jkc3s8c.js} +19 -19
  69. package/dist/chunk-3zzm5f28.js +92 -0
  70. package/dist/{chunk-e8e1h2h9.js → chunk-5dz6bzdj.js} +2 -2
  71. package/dist/chunk-6d5e10md.js +1 -0
  72. package/dist/chunk-9gypn8w9.js +1 -0
  73. package/dist/{chunk-hyeeqga9.js → chunk-9p89msvs.js} +6 -6
  74. package/dist/{chunk-31tvc877.js → chunk-9s24pbbc.js} +18 -18
  75. package/dist/chunk-badb5mf3.js +34 -0
  76. package/dist/{chunk-w9jhyy09.js → chunk-cfrv8110.js} +4 -4
  77. package/dist/{bin/chunk-8jbkphmg.js → chunk-dv1jkay7.js} +6 -6
  78. package/dist/{chunk-e52me1c6.js → chunk-ezgpamw6.js} +1 -1
  79. package/dist/chunk-j6a577hr.js +1 -0
  80. package/dist/chunk-jt49qs0f.js +2 -0
  81. package/dist/{chunk-aw1tp3p3.js → chunk-khatwx29.js} +99 -99
  82. package/dist/{chunk-v2p7c7s4.js → chunk-kpyhx96m.js} +133 -133
  83. package/dist/{chunk-3rahpgb9.js → chunk-kw852q5m.js} +164 -164
  84. package/dist/{chunk-3m9ghthh.js → chunk-mgg0psgc.js} +2 -2
  85. package/dist/{chunk-9wmer0zx.js → chunk-ms4dnha2.js} +2 -2
  86. package/dist/{chunk-qcaqc5b8.js → chunk-np8vgbv0.js} +3 -3
  87. package/dist/chunk-p0b08g9f.js +114 -0
  88. package/dist/{chunk-srrscggm.js → chunk-pcns0kz4.js} +5 -5
  89. package/dist/{chunk-kczzc599.js → chunk-pffebjr8.js} +31 -31
  90. package/dist/{chunk-vs0qrm09.js → chunk-pwywwdq2.js} +1 -1
  91. package/dist/{chunk-5far81q7.js → chunk-w4s3rswa.js} +2 -2
  92. package/dist/chunk-whdbz3h8.js +1 -0
  93. package/dist/{chunk-bxrzsth8.js → chunk-x60w04y3.js} +2 -2
  94. package/dist/{chunk-zx8ecz8b.js → chunk-y6k0vwfn.js} +4 -4
  95. package/dist/deploy/index.js +1 -1
  96. package/dist/dns/index.js +1 -1
  97. package/dist/drivers/index.js +1 -1
  98. package/dist/index.js +85 -85
  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 +1 -1
  109. package/dist/ui/data/backups.html +5 -5
  110. package/dist/ui/data/services.html +5 -5
  111. package/dist/ui/data/volumes.html +6 -6
  112. package/dist/ui/index.html +6 -6
  113. package/dist/ui/infrastructure/topology.html +6 -6
  114. package/dist/ui/integrations.html +1 -1
  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 +5 -5
  118. package/dist/ui/operations/maintenance.html +6 -6
  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 +6 -6
  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 +2 -2
  129. package/dist/ui/server/capacity.html +5 -5
  130. package/dist/ui/server/database.html +6 -6
  131. package/dist/ui/server/deployments.html +5 -5
  132. package/dist/ui/server/diagnostics.html +2 -2
  133. package/dist/ui/server/firewall.html +6 -6
  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 +5 -5
  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 +6 -6
  142. package/dist/ui/server/terminal.html +2 -2
  143. package/dist/ui/serverless/alarms.html +6 -6
  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 +1 -1
  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 +5 -5
  155. package/dist/ui/serverless.html +6 -6
  156. package/package.json +3 -3
  157. package/dist/bin/chunk-0h6cggyt.js +0 -1
  158. package/dist/bin/chunk-2g2zrtjs.js +0 -2
  159. package/dist/bin/chunk-35rkh66r.js +0 -1
  160. package/dist/bin/chunk-4cs098d1.js +0 -1
  161. package/dist/bin/chunk-52fhq35h.js +0 -1
  162. package/dist/bin/chunk-6se7ygxa.js +0 -1
  163. package/dist/bin/chunk-72g1hr4z.js +0 -1
  164. package/dist/bin/chunk-840arz58.js +0 -34
  165. package/dist/bin/chunk-c7vxdwth.js +0 -1
  166. package/dist/bin/chunk-e0c3agf2.js +0 -1
  167. package/dist/bin/chunk-egn33pr9.js +0 -2
  168. package/dist/bin/chunk-gf7yavs5.js +0 -1
  169. package/dist/bin/chunk-gp5w7e4c.js +0 -1
  170. package/dist/bin/chunk-gt7g41js.js +0 -1
  171. package/dist/bin/chunk-hagakkgm.js +0 -1
  172. package/dist/bin/chunk-hr3vbg6y.js +0 -1
  173. package/dist/bin/chunk-hyb5v8wr.js +0 -1
  174. package/dist/bin/chunk-nqb1faqj.js +0 -1
  175. package/dist/bin/chunk-p831sptd.js +0 -1
  176. package/dist/bin/chunk-qxx1a51w.js +0 -1
  177. package/dist/bin/chunk-sh248v2y.js +0 -1
  178. package/dist/bin/chunk-swfmx4f8.js +0 -1
  179. package/dist/bin/chunk-vjkyj3xy.js +0 -2
  180. package/dist/bin/chunk-w78chy9x.js +0 -1
  181. package/dist/bin/chunk-w8k1gyzr.js +0 -1
  182. package/dist/bin/chunk-wagzxm7z.js +0 -1
  183. package/dist/bin/chunk-xdxk6baf.js +0 -1
  184. package/dist/bin/chunk-ysv52qcc.js +0 -1
  185. package/dist/chunk-07rjctzz.js +0 -1
  186. package/dist/chunk-49vvjfrd.js +0 -1
  187. package/dist/chunk-6kcmbymp.js +0 -1
  188. package/dist/chunk-7xnwa0s8.js +0 -5
  189. package/dist/chunk-89p8mshq.js +0 -114
  190. package/dist/chunk-9asn5fpt.js +0 -92
  191. package/dist/chunk-d46p0h6t.js +0 -34
  192. package/dist/chunk-dak9hfrd.js +0 -1
  193. package/dist/chunk-ptq9v346.js +0 -2
  194. package/dist/chunk-z4xzd43p.js +0 -1
package/dist/index.js CHANGED
@@ -1,17 +1,17 @@
1
- import{rg,_,ng,Xf,oI,Yf,aI,cI,dI,lI,uI,pI,gI,mI,hI,fI,ig,sg,hd,fd,io,O,d,Ad,og,x,yd,p,Zf,bi,Id,Sd,le,Cd,yI,r,t,II,SI,g,CI,EI,bI,vI,TI,Ut,Ed,so,eA,wI,RI,ve,Ge,bd,ag,cg,DI,dg,lg,ug,vd,pg,Te,Fr,Qt,Td,Ht,ue,tA,wd,oo,gg,mg,hg,fg,Rd,PI,L,I,a,f,qe,m,rA,Ve,M,pt,NI,nA,F,Dd,we,Gt,ao,Y,Pd,Z,iA,co,U,Q,D,vi,b,qt,gt,H,e,lo,kI,Ag,Nd,BI,_I,OI,xI,kd,LI,$I,MI,FI,UI,QI,HI,GI,qI,VI,jI,zI,sA,oA,aA,cA,dA,lA,uA,Vt,yg,Ig,Ur,Ti,KI,Sg,WI,JI,Qr,XI,YI,ZI,eS,tS,rS,pA,gA,mA,hA,fA,uo,nS,AA,yA,IA,G,iS,je,po,jt,SA,Cg,CA,EA,bA,Eg,ee,sS,oS,aS,cS,vA,dS,q,lS,uS,pS,bg,vg,gS,Tg,wg,mS,hS,fS,AS,yS,TA,Bd,IS,SS,CS,ES,bS,wA,RA,vS,TS,wS,RS,DS,PS,NS,kS,BS,Rg,_d,_S,OS,xS,LS,Dg,Pg,Ng,$S,kg,MS,FS,US,QS,Bg,HS,GS,qS,VS,jS,zS,KS,WS,DA,PA,NA,kA,_g,JS,XS,YS,ZS,eC,tC,rC,nC,iC,BA,_A,OA,xA,sC,oC,Og,aC,xg,Lg,$g,Mg,cC,dC,lC,uC,Re,wi,pC,gC,mC,hC,fC,AC,yC,IC,LA,SC,CC,Fg,Ug,EC,bC,$A,vC,TC,wC,RC,DC,PC,NC,kC,BC,_C,OC,xC,LC,$C,MC,FC,UC,QC,HC,GC,qC,Qg,VC,Hg,jC,Gg,zC,qg,KC,Vg,WC,Hr,JC,jg,XC,go,YC,zg,ZC,Kg,eE,Wg,tE,Jg,rE,Xg,nE,Gr,iE,Yg,sE,Zg,oE,em,aE,tm,cE,rm,dE,nm,lE,im,uE,sm,pE,om,gE,am,mE,cm,hE,dm,fE,lm,AE,um,yE,pm,IE,gm,SE,mm,CE,hm,EE,fm,bE,Am,vE,ym,TE,Im,wE,Sm,RE,Cm,DE,Em,PE,MA,FA,UA,QA,bm,NE,vm,kE,Tm,BE,wm,_E,Ri,HA,GA,mo,Od,qr,qA,ho,zt,xd,Ld,VA,jA,Rm,zA,$d,Dm,OE,xE,fo,Ao,yo,Md,Di,Fd,Ud,Io,Qd,Hd,Pm,KA,WA,JA,LE,XA,YA,$E,ZA,Nm,ey,ty,ry,ME,ny,Pi,Gd,iy,FE,sy,So,Co,qd,km,UE,Bm,QE,_m,HE,Om,GE,xm,qE}from"./chunk-v2p7c7s4.js";import{Ro,Lm,Xd,ay,_i,Yd,Do,$m,Mm,Vr,Po,Zd,ze,el,tl,rl,Oi,jr,Fm,Ke,nl,No,ko,Bo,il,sl,ol,xi,_o,al,zr,Li,Oo,mt,Um,cl,dl,Qm,ll,xo,Kt,ul,pl,gl,ml,We,Hm,hl,Wt,Lo,$o,Mo,$i,Mi,Kr,fl,Fi,Fo,Uo,Wr,Al,Jr,Gm,qm,ht,Xr,Qo,Vm,yl,Il,Ho,Sl,Cl,El,cy,te,bl,dy,ly,Ui,Qi,uy,pe,jm,ft,De,Pe,At,vl,Tl,wl,Rl,zm,Km,Go,Wm,Jm,qo,Dl,Pl,Xm,re,Ym,Nl,ge,Vo,Je,yt,It,Yr,Hi,kl,py,jo,Zm,eh,th,rh,zo,Ko,Bl,Zr,Wo,_l,Gi,Ol,Jo,Xo,Yo,Zo,ea,ta,ra,na,xl,Jt,ia,Ll,en,$l,sa,oa,Ml,Xt,aa,ca,nh,gy,qi,my,hy,fy,da,la,Fl,ih,ua,tn,Ul,Vi,Ql,Hl,Gl,pa,sh,ga,ql,oh,ma,ah,rn,nn,Vl,ji,Xl,tu,ru,nu,iu,su,Ki,Yt,fa,sn,on,Zt,Xe,hh,ya,fh,Ah,cu,Ia,Ji,du,Sa,Ct,ke,lu,Ca,Ea,uu,ba,va,Ta,wa,pu,gu,cn,Ra,Da,Pa,Na,mu,Xi,dn,Yi,ka}from"./chunk-3rahpgb9.js";import{B,Tr,Nc,_s,u,Np,kp}from"./chunk-3m9ghthh.js";import{at,Pc,oi,ai,ci,Pp}from"./chunk-w9jhyy09.js";import{Jh,Xh,Yh,lp,up,pp,Zh,gp,mp,ef,tf,hp,rf,nf,Rc,fp,sf,of,Ap,af,cf,df,lf,uf,pf,gf,si,Dc,yp,Ip,Sp,Cp,Ep,bp,vp,Tp,wp,Rp,Dp,mf,hf,ff,Af,yf,If,Sf}from"./chunk-z3wynefj.js";import{Ue,kc,de,_t,Bc,w,Ot,ct,_c,Os,bf,Bp,Oc,s,di,xs,wr,xc,Lc,Rr,vf,$c,rI,nI,Ls,iI,sI,Mc,Fc,li,$s,X,c,Ms,Qe,Dr,Tf,wf,Uc,xt,Rf,Fs,Df,Pf,Us,Qc,Pr,Qs,Nf,Hc,_p,Lt,Nr,kf,Hs,Bf,R,_f,Gc,Op,Gs,Of,xf,Lf,qc,ui,qs,Vc,$t,dt,$f,kr,Mf,jc,xp,Lp,Vs,zc,Kc,lt,$p,pi,Wc,js,Br,Mp,gi,Jc,Xc,mi,Fp,Yc,Zc,ed,td,zs,Up,Qp,Ff,Hp,rd,hi,Gp,qp,Ks,_r,Ws,Js,Xs,nd,Vp,id,Ys,Uf,Mt,Qf,sd,Or,od,Hf,ad,jp,fi,xr,Zs,Ai,He,Gf,zp,Kp,Ft,cd,dd,ld,yi,Ii,Si,qf,Vf,ut,eo,jf,Lr,Wp,to,zf,Jp,Xp,Yp,Kf,Zp,eg,Wf,i,Jf,Ci,ro,no}from"./chunk-kczzc599.js";import{n}from"./chunk-zx8ecz8b.js";import{o}from"./chunk-9asn5fpt.js";import{me,ss,os,Au,La,$a,as,Ma,Ye,V,Ze,ne,C,he,gn,Fa,Be,Ua,mn,hn,fn,Et,bt,vt,An,tr,Qa,rr,nr,et,yn,Ga,Tt,ir,In,Va,Cu,Eu,ja,sr}from"./chunk-89p8mshq.js";import{rt,se,Oe,bu,Cn,za,Ka,ds,Ae,wt,En,ls,us,or,ar,bn,cr,ps,gs,ms,hs,z,fs,As,ys,Is,oe,Ss,Cs,Es,T,Wa,vn,Ja,ae,dr}from"./chunk-e8e1h2h9.js";import{fe,tt,Sn}from"./chunk-d46p0h6t.js";import{j}from"./chunk-k53agv2m.js";import{vu,Xa,ye,Ya,Tn,Tu,Za,wu,Ru,Ph,Rn,vs,Dn,Pn,Nn,K,xe,N,mr,Bn,hr,ce,rc,_n,nc,Ar,xn,Ts,Ln,$n,Mn,Un,yr,cc,Le,W,$e,Me,it,Ce,Ir,Ee,Gn,qn,Vn,jn,zn,Kn,Wn,Sr,k,Ds,Yu,hc,Xn,Yn,Zn,ei,Ec,Ps,bc,kt,ti,Ns,ks,vc,ri,Tc}from"./chunk-aw1tp3p3.js";import{Vd,Eo,Ni,ki,bo,jd,zd,Bi,vo,To,Wd,Jd,wo}from"./chunk-e52me1c6.js";import{Ba,ln,un,Zi,es,ts,rs,_a,Oa}from"./chunk-hyeeqga9.js";import{xa}from"./chunk-7xnwa0s8.js";import{A}from"./chunk-31tvc877.js";import{_e}from"./chunk-5far81q7.js";import{y}from"./chunk-9wmer0zx.js";import{J,ni,Bs,wc,ii,dp}from"./chunk-srrscggm.js";import{Er,be}from"./chunk-qcaqc5b8.js";import{h}from"./chunk-ptq9v346.js";import{zh,Fe}from"./chunk-bxrzsth8.js";import{ud,$r,pd,gd,md,Ei,tg,Mr}from"./chunk-g6g33pt9.js";import{createHmac as lc,createSign as jl,timingSafeEqual as Zl}from"node:crypto";function Aa(l){let S=l instanceof Date?l.getTime():l;if(!Number.isFinite(S))throw TypeError("Media access timestamp must be finite");return Math.floor(S/1000)}function dc(l){return Buffer.from(l).toString("base64").replaceAll("+","-").replaceAll("=","_").replaceAll("/","~")}function Jl(l){return Buffer.from(l).toString("base64url")}function uc(l,S=!1){if(!l||/[\r\n]/.test(l))throw TypeError("Media resource is invalid");let P=S?l.replaceAll("*","wildcard"):l,v=new URL(P);if(!["http:","https:"].includes(v.protocol))throw TypeError("Media resource must use HTTP or HTTPS");if(!S&&l.includes("*"))throw TypeError("Canned policies cannot contain wildcards")}function pc(l,S){let P=jl("RSA-SHA1");return P.update(l),P.end(),dc(P.sign(S))}function mc(l){uc(l.resource,!0);let P={DateLessThan:{"AWS:EpochTime":Aa(l.expiresAt)}};if(l.activeAt!==void 0)P.DateGreaterThan={"AWS:EpochTime":Aa(l.activeAt)};if(l.ipAddress)P.IpAddress={"AWS:SourceIp":l.ipAddress};return JSON.stringify({Statement:[{Resource:l.resource,Condition:P}]})}function Ku(l,S,P){uc(l);let v=Aa(S),E=l.includes("?")?"&":"?",ot=mc({resource:l,expiresAt:S}),Ie=pc(ot,P.privateKey);return`${l}${E}Expires=${v}&Signature=${encodeURIComponent(Ie)}&Key-Pair-Id=${encodeURIComponent(P.keyPairId)}`}function ju(l,S){let P=mc(l);return{"CloudFront-Key-Pair-Id":S.keyPairId,"CloudFront-Policy":dc(Buffer.from(P)),"CloudFront-Signature":pc(P,S.privateKey)}}function Zu(l){if(!l.resource||/[\r\n]/.test(l.resource))throw TypeError("Media resource is invalid");let S=Jl(Buffer.from(JSON.stringify({resource:l.resource,expiresAt:Aa(l.expiresAt),...l.keyId?{keyId:l.keyId}:{},...l.audience?{audience:l.audience}:{}}))),P=lc("sha256",l.secret).update(S).digest("base64url");return`${S}.${P}`}function qu(l,S){let[P,v,E]=l.split(".");if(!P||!v||E)return null;let ot=lc("sha256",S.secret).update(P).digest(),Ie;try{Ie=Buffer.from(v,"base64url")}catch{return null}if(ot.length!==Ie.length||!Zl(ot,Ie))return null;try{let Ne=JSON.parse(Buffer.from(P,"base64url").toString("utf8")),nt=Aa(S.now??Date.now());if(!Ne.resource||!Number.isSafeInteger(Ne.expiresAt)||Ne.expiresAt<=nt)return null;if(S.resource&&Ne.resource!==S.resource)return null;if(S.audience&&Ne.audience!==S.audience)return null;return Ne}catch{return null}}function Ju(l,S=!1){let P=new URL(l,"https://media.invalid").pathname.toLowerCase(),v=/\.(?:m3u8|mpd|vtt|json)$/.test(P),E=/\.(?:key|license)$/.test(P)||P.includes("/keys/")||P.includes("/licenses/");return{"Accept-Ranges":"bytes","Cache-Control":S&&(v||E)?"private, no-store":v?"public, max-age=5, s-maxage=30, stale-while-revalidate=30":"public, max-age=31536000, immutable","Cross-Origin-Resource-Policy":"cross-origin","X-Content-Type-Options":"nosniff"}}function Xu(l){if(!/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(l.bucket))throw TypeError("Media bucket is invalid");if(!/^[a-z0-9-]+$/.test(l.region))throw TypeError("Media bucket region is invalid");let S=l.prefix?`/${l.prefix.replace(/^\/+|\/+$/g,"")}`:"",P=l.protected??!1,v="public, max-age=31536000, immutable",E=P?"private, no-store":"public, max-age=5, s-maxage=30, stale-while-revalidate=30";return{originDomain:`${l.bucket}.s3.${l.region}.amazonaws.com`,originPath:S,domain:l.domain,trustedKeyGroupIds:[...new Set(l.trustedKeyGroupIds??[])],behaviors:[{pathPattern:"*.m3u8",cacheControl:E,compress:!0,signed:P},{pathPattern:"*.mpd",cacheControl:E,compress:!0,signed:P},{pathPattern:"*.vtt",cacheControl:E,compress:!0,signed:P},{pathPattern:"*",cacheControl:v,compress:!1,signed:P}],responseHeaders:{"Access-Control-Allow-Headers":"Range, If-Range","Access-Control-Allow-Methods":"GET, HEAD, OPTIONS","Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"Accept-Ranges, Content-Length, Content-Range, ETag","X-Content-Type-Options":"nosniff"}}}class Yl{builder;config;environment;mergedConfig;serverEipLogicalIds=new Map;storageFailoverReplicas=[];constructor(l){this.config=l.config,this.environment=l.environment,this.builder=new Cd(`${this.config.project.name} - ${this.environment}`),this.mergedConfig=this.mergeEnvironmentConfig()}mergeEnvironmentConfig(){let S=this.config.environments[this.environment]?.infrastructure;if(!S)return this.config;return{...this.config,infrastructure:{...this.config.infrastructure,...S,compute:{...this.config.infrastructure?.compute,...S.compute},storage:{...this.config.infrastructure?.storage,...S.storage},functions:{...this.config.infrastructure?.functions,...S.functions},servers:{...this.config.infrastructure?.servers,...S.servers},databases:{...this.config.infrastructure?.databases,...S.databases},cdn:{...this.config.infrastructure?.cdn,...S.cdn},sftp:S.sftp??this.config.infrastructure?.sftp,queues:{...this.config.infrastructure?.queues,...S.queues},redirects:{...this.config.infrastructure?.redirects,...S.redirects},realtime:{...this.config.infrastructure?.realtime,...S.realtime},cache:{...this.config.infrastructure?.cache,...S.cache},fileSystem:{...this.config.infrastructure?.fileSystem,...S.fileSystem},email:{...this.config.infrastructure?.email,...S.email},search:{...this.config.infrastructure?.search,...S.search},ai:{...this.config.infrastructure?.ai,...S.ai}}}}shouldDeploy(l){if(l.environments&&!l.environments.includes(this.environment))return!1;if(l.requiresFeatures){let S=this.config.features||{};if(!l.requiresFeatures.every((v)=>S[v]===!0))return!1}if(l.regions){let S=this.config.environments[this.environment]?.region||this.config.project.region;if(!l.regions.includes(S))return!1}if(l.condition&&typeof l.condition==="function")return l.condition(this.config,this.environment);return!0}resolveApiOriginPort(){let l=this.mergedConfig.infrastructure?.api?.port??this.mergedConfig.ports?.api,S=Number(l||3008);return Number.isFinite(S)&&S>0?S:3008}defaultComputeCachePathPatterns(){return["/api/*","/auth/*","/publisher/api/*","/publisher/*","/publish","/publish/*","/analytics/*","/packages/*","/npm/*","/zig/*","/php/*","/commits/*","/health","/dashboard/*","/search","/login","/logout","/signup","/account","/account/*"]}shouldRouteStorageBucketToCompute(l,S){return l==="public"||S.routeCompute===!0}storageBucketName(l,S,P){return this.mergedConfig.infrastructure?.storage?.[P]?.bucket??`${l}-${S}-${P}`}fileSystemLogicalId(l,S,P){return t(r({slug:`${l}-${P}`,environment:S,resourceType:"efs"}))}resolveSftpStorage(l,S,P){let v=l.storage;if(v?.type==="efs"&&v.fileSystem){if(!this.mergedConfig.infrastructure?.fileSystem?.[v.fileSystem])throw Error(`sftp: storage.fileSystem "${v.fileSystem}" is not defined in infrastructure.fileSystem`);return{type:"efs",fileSystemId:{Ref:this.fileSystemLogicalId(S,P,v.fileSystem)},posixProfile:v.posixProfile}}if(v?.type==="s3"&&v.storageBucket){if(!this.mergedConfig.infrastructure?.storage?.[v.storageBucket])throw Error(`sftp: storage.storageBucket "${v.storageBucket}" is not defined in infrastructure.storage`);return{type:"s3",bucket:this.storageBucketName(S,P,v.storageBucket)}}return}resolveComputeCachePathPatterns(l){if(l&&l.length>0)return l;return this.defaultComputeCachePathPatterns()}createComputeCacheBehavior(l,S){return{PathPattern:l,TargetOriginId:S,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],CachedMethods:["GET","HEAD"],Compress:!0,CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac"}}appendComputeAppOrigin(l,S,P,v,E,ot){let Ie=this.serverEipLogicalIds.get("app"),Ne=this.serverEipLogicalIds.get("appInstance");if(!Ie)return;let nt=`EC2-${v}-${E}-api`,Pt=this.mergedConfig.infrastructure?.servers?.app?.region||this.mergedConfig.project?.region||"us-east-1",st=Pt==="us-east-1"?".compute-1.amazonaws.com":`.${Pt}.compute.amazonaws.com`,ur={"Fn::Join":["",["ec2-",{"Fn::Join":["-",{"Fn::Split":[".",{Ref:Ie}]}]},st]]},pr=this.resolveApiOriginPort();if(l.push({Id:nt,DomainName:ur,CustomOriginConfig:{HTTPPort:pr,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}),P.push(Ie),Ne)P.push(Ne);for(let gr of ot)S.push(this.createComputeCacheBehavior(gr,nt))}buildCaddyfile(l){let S=l.filter(([,E])=>typeof E.domain==="string"&&E.domain&&typeof E.port==="number");if(S.length===0)return;let P=new Map;for(let[,E]of S){let ot=P.get(E.domain)??[];ot.push({port:E.port,path:E.path}),P.set(E.domain,ot)}let v=[];for(let[E,ot]of P){let Ne=[...ot].sort((nt,Pt)=>{let st=!nt.path||nt.path==="/",ur=!Pt.path||Pt.path==="/";if(st&&!ur)return 1;if(!st&&ur)return-1;return(Pt.path?.length??0)-(nt.path?.length??0)}).map((nt)=>{let Pt=!nt.path||nt.path==="/",st=`reverse_proxy localhost:${nt.port}`;return Pt?` handle {
2
- ${st}
3
- }`:` handle ${nt.path} {
4
- ${st}
5
- }`});v.push(`${E} {
6
- ${Ne.join(`
1
+ import{sg,x,og,eA,dI,tA,lI,uI,pI,gI,mI,hI,fI,yI,II,SI,ag,cg,yd,Id,oo,O,d,Sd,dg,L,Cd,p,rA,Ti,Ed,bd,ue,vd,CI,r,t,EI,bI,g,vI,TI,wI,RI,DI,Ht,Td,ao,nA,PI,NI,Te,qe,wd,lg,ug,kI,pg,gg,mg,Rd,hg,we,Qr,Gt,Dd,qt,pe,iA,Pd,co,fg,Ag,yg,Ig,Nd,BI,M,S,a,A,Ve,m,sA,je,F,mt,_I,oA,U,kd,Re,Vt,lo,Z,Bd,ee,aA,uo,Q,H,P,wi,v,jt,ht,G,e,po,xI,Sg,_d,OI,LI,$I,MI,xd,FI,UI,QI,HI,GI,qI,VI,jI,zI,KI,WI,JI,cA,dA,lA,uA,pA,gA,mA,zt,Cg,Eg,Hr,Ri,XI,bg,YI,ZI,Gr,eS,tS,rS,nS,iS,sS,hA,fA,AA,yA,IA,go,oS,SA,CA,EA,q,aS,ze,mo,Kt,bA,vg,vA,TA,wA,Tg,te,cS,dS,lS,uS,RA,pS,V,gS,mS,hS,wg,Rg,fS,Dg,Pg,AS,yS,IS,SS,CS,DA,Od,ES,bS,vS,TS,wS,PA,NA,RS,DS,PS,NS,kS,BS,_S,xS,OS,Ng,Ld,LS,$S,MS,FS,kg,Bg,_g,US,xg,QS,HS,GS,qS,Og,VS,jS,zS,KS,WS,JS,XS,YS,kA,BA,_A,xA,Lg,ZS,eC,tC,rC,nC,iC,sC,oC,aC,OA,LA,$A,MA,cC,dC,$g,lC,Mg,Fg,Ug,Qg,uC,pC,gC,mC,De,Di,hC,fC,AC,yC,IC,SC,CC,EC,FA,bC,vC,Hg,Gg,TC,wC,UA,RC,DC,PC,NC,kC,BC,_C,xC,OC,LC,$C,MC,FC,UC,QC,HC,GC,qC,VC,jC,zC,qg,KC,Vg,WC,jg,JC,zg,XC,Kg,YC,qr,ZC,Wg,eE,ho,tE,Jg,rE,Xg,nE,Yg,iE,Zg,sE,em,oE,Vr,aE,tm,cE,rm,dE,nm,lE,im,uE,sm,pE,om,gE,am,mE,cm,hE,dm,fE,lm,AE,um,yE,pm,IE,gm,SE,mm,CE,hm,EE,fm,bE,Am,vE,ym,TE,Im,wE,Sm,RE,Cm,DE,Em,PE,bm,NE,vm,kE,Tm,BE,QA,HA,GA,qA,wm,_E,Rm,xE,Dm,OE,Pm,LE,Pi,VA,jA,fo,$d,jr,zA,Ao,Wt,Md,Fd,KA,WA,Nm,JA,Ud,km,$E,ME,yo,Io,So,Qd,Ni,Hd,Gd,Co,qd,Vd,Bm,XA,YA,ZA,FE,ey,ty,UE,ry,_m,ny,iy,sy,QE,oy,ki,jd,ay,HE,cy,Eo,bo,zd,xm,GE,Om,qE,Lm,VE,$m,jE,Mm,zE}from"./chunk-kpyhx96m.js";import{Po,Fm,el,ly,Oi,tl,No,Um,Qm,zr,ko,rl,Ke,nl,il,sl,Li,Kr,Hm,We,ol,Bo,_o,xo,al,cl,dl,$i,Oo,ll,Wr,Mi,Lo,ft,Gm,ul,pl,qm,gl,$o,Jt,ml,hl,fl,Al,Je,Vm,yl,Xt,Mo,Fo,Uo,Fi,Ui,Jr,Il,Qi,Qo,Ho,Xr,Sl,Yr,jm,zm,At,Zr,Go,Km,Cl,El,qo,bl,vl,Tl,uy,re,wl,py,gy,Hi,Gi,my,ge,Wm,yt,Pe,Ne,It,Rl,Dl,Pl,Nl,Jm,Xm,Vo,Ym,Zm,jo,kl,Bl,eh,ne,th,_l,me,zo,Xe,St,Ct,en,qi,xl,hy,Ko,rh,nh,ih,sh,Wo,Jo,Ol,tn,Xo,Ll,Vi,$l,Yo,Zo,ea,ta,ra,na,ia,sa,Ml,Yt,oa,Fl,rn,Ul,aa,ca,Ql,Zt,da,la,oh,fy,ji,Ay,yy,Iy,ua,pa,Hl,ah,ga,nn,Gl,zi,ql,Vl,jl,ma,ch,ha,zl,dh,fa,lh,sn,on,Kl,Ki,eu,iu,su,ou,au,cu,Ji,er,ya,an,cn,tr,Ye,yh,Sa,Ih,Sh,uu,Ca,Yi,pu,Ea,bt,Be,gu,ba,va,mu,Ta,wa,Ra,Da,hu,fu,ln,Pa,Na,ka,Ba,Au,Zi,un,es,_a}from"./chunk-kw852q5m.js";import{_,Rr,_c,Os,u,_p,xp}from"./chunk-mgg0psgc.js";import{dt,Bc,ci,di,li,Bp}from"./chunk-cfrv8110.js";import{Zh,ef,tf,gp,mp,hp,rf,fp,Ap,nf,sf,yp,of,af,Nc,Ip,cf,df,Sp,lf,uf,pf,gf,mf,hf,ff,ai,kc,Cp,Ep,bp,vp,Tp,wp,Rp,Dp,Pp,Np,kp,Af,yf,If,Sf,Cf,Ef,bf}from"./chunk-3jkc3s8c.js";import{Qe,xc,le,Ot,Oc,R,Lt,lt,Lc,Ls,wf,Op,$c,s,ui,$s,Dr,Mc,Fc,Pr,Rf,Uc,sI,oI,Ms,aI,cI,Qc,Hc,pi,Fs,Y,c,Us,He,Nr,Df,Pf,Gc,$t,Nf,Qs,kf,Bf,Hs,qc,kr,Gs,_f,Vc,Lp,Mt,Br,xf,qs,Of,D,Lf,jc,$p,Vs,$f,Mf,Ff,zc,gi,js,Kc,Ft,ut,Uf,_r,Qf,Wc,Mp,Fp,zs,Jc,Xc,pt,Up,mi,Yc,Ks,xr,Qp,hi,Zc,ed,fi,Hp,td,rd,nd,id,Ws,Gp,qp,Hf,Vp,sd,Ai,jp,zp,Js,Or,Xs,Ys,Zs,od,Kp,ad,eo,Gf,Ut,qf,cd,Lr,dd,Vf,ld,Wp,yi,$r,to,Ii,Ge,jf,Jp,Xp,Qt,ud,pd,gd,Si,Ci,Ei,zf,Kf,gt,ro,Wf,Mr,Yp,no,Jf,Zp,eg,tg,Xf,rg,ng,Yf,i,Zf,bi,io,so}from"./chunk-pffebjr8.js";import{n}from"./chunk-y6k0vwfn.js";import{o}from"./chunk-3zzm5f28.js";import{he,as,cs,Su,Ma,Fa,ds,Ua,Ze,j,et,ie,E,fe,hn,Qa,_e,Ha,fn,An,yn,vt,Tt,wt,In,nr,Ga,ir,sr,tt,Sn,Va,Rt,or,Cn,za,vu,Tu,Ka,ar}from"./chunk-p0b08g9f.js";import{nt,oe,Oe,wu,bn,Wa,Ja,us,ye,Dt,vn,ps,gs,cr,dr,Tn,lr,ms,hs,fs,As,K,ys,Is,Ss,Cs,ae,Es,bs,vs,w,Xa,wn,Ya,ce,ur}from"./chunk-5dz6bzdj.js";import{Ae,rt,En}from"./chunk-badb5mf3.js";import{z}from"./chunk-2dextjqf.js";import{Ru,Za,Ie,ec,Rn,Du,tc,Pu,Nu,Bh,Pn,ws,Nn,kn,Bn,W,Le,k,fr,xn,Ar,de,ic,On,sc,Ir,$n,Rs,Mn,Un,Qn,Hn,Sr,lc,$e,J,Me,Fe,st,Ee,Cr,be,Vn,jn,zn,Kn,Wn,Jn,Xn,Er,B,Ns,tp,Ac,Zn,ei,ti,ri,vc,ks,Tc,_t,ni,Bs,_s,wc,ii,Rc}from"./chunk-khatwx29.js";import{Kd,vo,Bi,_i,To,Wd,Jd,xi,wo,Ro,Yd,Zd,Do}from"./chunk-ezgpamw6.js";import{xa,pn,gn,ts,rs,ns,is,Oa,La}from"./chunk-9p89msvs.js";import{$a}from"./chunk-2ap78e1s.js";import{y}from"./chunk-9s24pbbc.js";import{xe}from"./chunk-w4s3rswa.js";import{I}from"./chunk-ms4dnha2.js";import{X,si,xs,Dc,oi,pp}from"./chunk-pcns0kz4.js";import{vr,ve}from"./chunk-np8vgbv0.js";import{h}from"./chunk-jt49qs0f.js";import{Jh,Ue}from"./chunk-x60w04y3.js";import{md,Fr,hd,fd,Ad,vi,ig,Ur}from"./chunk-dv1jkay7.js";import{createHmac as cc,createSign as Wl,timingSafeEqual as Zl}from"node:crypto";function Yn(l){let f=l instanceof Date?l.getTime():l;if(!Number.isFinite(f))throw TypeError("Media access timestamp must be finite");return Math.floor(f/1000)}function dc(l){return Buffer.from(l).toString("base64").replaceAll("+","-").replaceAll("=","_").replaceAll("/","~")}function Jl(l){return Buffer.from(l).toString("base64url")}function uc(l,f=!1){if(!l||/[\r\n]/.test(l))throw TypeError("Media resource is invalid");let C=f?l.replaceAll("*","wildcard"):l,b=new URL(C);if(!["http:","https:"].includes(b.protocol))throw TypeError("Media resource must use HTTP or HTTPS");if(!f&&l.includes("*"))throw TypeError("Canned policies cannot contain wildcards")}function pc(l,f){let C=Wl("RSA-SHA1");return C.update(l),C.end(),dc(C.sign(f))}function mc(l){uc(l.resource,!0);let C={DateLessThan:{"AWS:EpochTime":Yn(l.expiresAt)}};if(l.activeAt!==void 0)C.DateGreaterThan={"AWS:EpochTime":Yn(l.activeAt)};if(l.ipAddress)C.IpAddress={"AWS:SourceIp":l.ipAddress};return JSON.stringify({Statement:[{Resource:l.resource,Condition:C}]})}function Ku(l,f,C){uc(l);let b=Yn(f),T=l.includes("?")?"&":"?",it=mc({resource:l,expiresAt:f}),Ce=pc(it,C.privateKey);return`${l}${T}Expires=${b}&Signature=${encodeURIComponent(Ce)}&Key-Pair-Id=${encodeURIComponent(C.keyPairId)}`}function ju(l,f){let C=mc(l);return{"CloudFront-Key-Pair-Id":f.keyPairId,"CloudFront-Policy":dc(Buffer.from(C)),"CloudFront-Signature":pc(C,f.privateKey)}}function Zu(l){if(!l.resource||/[\r\n]/.test(l.resource))throw TypeError("Media resource is invalid");let f=Jl(Buffer.from(JSON.stringify({resource:l.resource,expiresAt:Yn(l.expiresAt),...l.keyId?{keyId:l.keyId}:{},...l.audience?{audience:l.audience}:{}}))),C=cc("sha256",l.secret).update(f).digest("base64url");return`${f}.${C}`}function qu(l,f){let[C,b,T]=l.split(".");if(!C||!b||T)return null;let it=cc("sha256",f.secret).update(C).digest(),Ce;try{Ce=Buffer.from(b,"base64url")}catch{return null}if(it.length!==Ce.length||!Zl(it,Ce))return null;try{let Se=JSON.parse(Buffer.from(C,"base64url").toString("utf8")),ke=Yn(f.now??Date.now());if(!Se.resource||!Number.isSafeInteger(Se.expiresAt)||Se.expiresAt<=ke)return null;if(f.resource&&Se.resource!==f.resource)return null;if(f.audience&&Se.audience!==f.audience)return null;return Se}catch{return null}}function Ju(l,f=!1){let C=new URL(l,"https://media.invalid").pathname.toLowerCase(),b=/\.(?:m3u8|mpd|vtt|json)$/.test(C),T=/\.(?:key|license)$/.test(C)||C.includes("/keys/")||C.includes("/licenses/");return{"Accept-Ranges":"bytes","Cache-Control":f&&(b||T)?"private, no-store":b?"public, max-age=5, s-maxage=30, stale-while-revalidate=30":"public, max-age=31536000, immutable","Cross-Origin-Resource-Policy":"cross-origin","X-Content-Type-Options":"nosniff"}}function Yu(l){if(!/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(l.bucket))throw TypeError("Media bucket is invalid");if(!/^[a-z0-9-]+$/.test(l.region))throw TypeError("Media bucket region is invalid");let f=l.prefix?`/${l.prefix.replace(/^\/+|\/+$/g,"")}`:"",C=l.protected??!1,b="public, max-age=31536000, immutable",T=C?"private, no-store":"public, max-age=5, s-maxage=30, stale-while-revalidate=30";return{originDomain:`${l.bucket}.s3.${l.region}.amazonaws.com`,originPath:f,domain:l.domain,trustedKeyGroupIds:[...new Set(l.trustedKeyGroupIds??[])],behaviors:[{pathPattern:"*.m3u8",cacheControl:T,compress:!0,signed:C},{pathPattern:"*.mpd",cacheControl:T,compress:!0,signed:C},{pathPattern:"*.vtt",cacheControl:T,compress:!0,signed:C},{pathPattern:"*",cacheControl:b,compress:!1,signed:C}],responseHeaders:{"Access-Control-Allow-Headers":"Range, If-Range","Access-Control-Allow-Methods":"GET, HEAD, OPTIONS","Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"Accept-Ranges, Content-Length, Content-Range, ETag","X-Content-Type-Options":"nosniff"}}}class Yl{builder;config;environment;mergedConfig;serverEipLogicalIds=new Map;storageFailoverReplicas=[];constructor(l){this.config=l.config,this.environment=l.environment,this.builder=new vd(`${this.config.project.name} - ${this.environment}`),this.mergedConfig=this.mergeEnvironmentConfig()}mergeEnvironmentConfig(){let f=this.config.environments[this.environment]?.infrastructure;if(!f)return this.config;return{...this.config,infrastructure:{...this.config.infrastructure,...f,compute:{...this.config.infrastructure?.compute,...f.compute},storage:{...this.config.infrastructure?.storage,...f.storage},functions:{...this.config.infrastructure?.functions,...f.functions},servers:{...this.config.infrastructure?.servers,...f.servers},databases:{...this.config.infrastructure?.databases,...f.databases},cdn:{...this.config.infrastructure?.cdn,...f.cdn},sftp:f.sftp??this.config.infrastructure?.sftp,queues:{...this.config.infrastructure?.queues,...f.queues},redirects:{...this.config.infrastructure?.redirects,...f.redirects},realtime:{...this.config.infrastructure?.realtime,...f.realtime},cache:{...this.config.infrastructure?.cache,...f.cache},fileSystem:{...this.config.infrastructure?.fileSystem,...f.fileSystem},email:{...this.config.infrastructure?.email,...f.email},search:{...this.config.infrastructure?.search,...f.search},ai:{...this.config.infrastructure?.ai,...f.ai}}}}shouldDeploy(l){if(l.environments&&!l.environments.includes(this.environment))return!1;if(l.requiresFeatures){let f=this.config.features||{};if(!l.requiresFeatures.every((b)=>f[b]===!0))return!1}if(l.regions){let f=this.config.environments[this.environment]?.region||this.config.project.region;if(!l.regions.includes(f))return!1}if(l.condition&&typeof l.condition==="function")return l.condition(this.config,this.environment);return!0}resolveApiOriginPort(){let l=this.mergedConfig.infrastructure?.api?.port??this.mergedConfig.ports?.api,f=Number(l||3008);return Number.isFinite(f)&&f>0?f:3008}defaultComputeCachePathPatterns(){return["/api/*","/auth/*","/publisher/api/*","/publisher/*","/publish","/publish/*","/analytics/*","/packages/*","/npm/*","/zig/*","/php/*","/commits/*","/health","/dashboard/*","/search","/login","/logout","/signup","/account","/account/*"]}shouldRouteStorageBucketToCompute(l,f){return l==="public"||f.routeCompute===!0}storageBucketName(l,f,C){return this.mergedConfig.infrastructure?.storage?.[C]?.bucket??`${l}-${f}-${C}`}fileSystemLogicalId(l,f,C){return t(r({slug:`${l}-${C}`,environment:f,resourceType:"efs"}))}resolveSftpStorage(l,f,C){let b=l.storage;if(b?.type==="efs"&&b.fileSystem){if(!this.mergedConfig.infrastructure?.fileSystem?.[b.fileSystem])throw Error(`sftp: storage.fileSystem "${b.fileSystem}" is not defined in infrastructure.fileSystem`);return{type:"efs",fileSystemId:{Ref:this.fileSystemLogicalId(f,C,b.fileSystem)},posixProfile:b.posixProfile}}if(b?.type==="s3"&&b.storageBucket){if(!this.mergedConfig.infrastructure?.storage?.[b.storageBucket])throw Error(`sftp: storage.storageBucket "${b.storageBucket}" is not defined in infrastructure.storage`);return{type:"s3",bucket:this.storageBucketName(f,C,b.storageBucket)}}return}resolveComputeCachePathPatterns(l){if(l&&l.length>0)return l;return this.defaultComputeCachePathPatterns()}createComputeCacheBehavior(l,f){return{PathPattern:l,TargetOriginId:f,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],CachedMethods:["GET","HEAD"],Compress:!0,CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac"}}appendComputeAppOrigin(l,f,C,b,T,it){let Ce=this.serverEipLogicalIds.get("app"),Se=this.serverEipLogicalIds.get("appInstance");if(!Ce)return;let ke=`EC2-${b}-${T}-api`,Pt=this.mergedConfig.infrastructure?.servers?.app?.region||this.mergedConfig.project?.region||"us-east-1",ot=Pt==="us-east-1"?".compute-1.amazonaws.com":`.${Pt}.compute.amazonaws.com`,rr={"Fn::Join":["",["ec2-",{"Fn::Join":["-",{"Fn::Split":[".",{Ref:Ce}]}]},ot]]},pr=this.resolveApiOriginPort();if(l.push({Id:ke,DomainName:rr,CustomOriginConfig:{HTTPPort:pr,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}),C.push(Ce),Se)C.push(Se);for(let gr of it)f.push(this.createComputeCacheBehavior(gr,ke))}buildCaddyfile(l){let f=l.filter(([,T])=>typeof T.domain==="string"&&T.domain&&typeof T.port==="number");if(f.length===0)return;let C=new Map;for(let[,T]of f){let it=C.get(T.domain)??[];it.push({port:T.port,path:T.path}),C.set(T.domain,it)}let b=[];for(let[T,it]of C){let Se=[...it].sort((ke,Pt)=>{let ot=!ke.path||ke.path==="/",rr=!Pt.path||Pt.path==="/";if(ot&&!rr)return 1;if(!ot&&rr)return-1;return(Pt.path?.length??0)-(ke.path?.length??0)}).map((ke)=>{let Pt=!ke.path||ke.path==="/",ot=`reverse_proxy localhost:${ke.port}`;return Pt?` handle {
2
+ ${ot}
3
+ }`:` handle ${ke.path} {
4
+ ${ot}
5
+ }`});b.push(`${T} {
6
+ ${Se.join(`
7
7
  `)}
8
- }`)}return v.join(`
8
+ }`)}return b.join(`
9
9
 
10
- `)}normalizeMountPath(l){let S=l?.mountPath||l?.path;if(!S||S==="/")return;let P=`/${S}`.replace(/\/+/g,"/").replace(/\/$/,"");return P==="/"?void 0:P}storageBucketLogicalId(l,S,P){return`${l}-${S}-s3-${P}`.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((v)=>v.charAt(0).toUpperCase()+v.slice(1)).join("")}pathMountRewriteFunctionCode(l,S="directory"){return`function handler(event) { var request = event.request; var prefix = ${JSON.stringify(l)}; var rewriteStyle = ${JSON.stringify(S)}; var uri = request.uri; if (uri === prefix) { uri = '/'; } else if (uri.indexOf(prefix + '/') === 0) { uri = uri.substring(prefix.length); } if (uri === '' || uri === '/') { request.uri = '/index.html'; return request; } if (uri.endsWith('/')) { request.uri = uri + 'index.html'; return request; } var lastSegment = uri.substring(uri.lastIndexOf('/') + 1); if (lastSegment.indexOf('.') === -1) { request.uri = rewriteStyle === 'flat' ? uri + '.html' : uri + '/index.html'; return request; } request.uri = uri; return request; }`}generate(){let l=this.mergedConfig.project.slug,S=this.environment,P=!!(this.mergedConfig.infrastructure?.functions&&Object.keys(this.mergedConfig.infrastructure.functions).length>0||this.mergedConfig.infrastructure?.api),v=!!(this.mergedConfig.infrastructure?.servers&&Object.keys(this.mergedConfig.infrastructure.servers).length>0),E=!!this.mergedConfig.infrastructure?.compute;if(!!((this.mergedConfig.mode||"server")==="serverless"&&this.mergedConfig.infrastructure?.containers&&Object.keys(this.mergedConfig.infrastructure.containers).length>0))this.generateNetworkInfrastructure(l,S),this.generateContainerInfrastructure(l,S);if(P)this.generateServerless(l,S);if(v)this.generateServer(l,S);if(E)this.generateComputeApp(l,S);if(this.mergedConfig.infrastructure?.jumpBox)this.generateJumpBox(l,S);if(this.storageFailoverReplicas=[],this.generateSharedInfrastructure(l,S),this.storageFailoverReplicas.length>0)this.builder.addMetadata(wd,this.storageFailoverReplicas);if(this.config.tags)this.applyGlobalTags(this.config.tags);return this}getStorageFailoverReplicas(){return[...this.storageFailoverReplicas]}applyGlobalTags(l){}generateNetworkInfrastructure(l,S){if(this.builder.hasResource("VPC"))return;let v=this.mergedConfig.infrastructure?.network?.cidr||"10.0.0.0/16",{vpc:E,logicalId:ot}=f.createVpc({slug:l,environment:S,cidr:v,enableDnsHostnames:!0,enableDnsSupport:!0});this.builder.addResource("VPC",E);let Ie=`${l}${S}IGW`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Ie,{Type:"AWS::EC2::InternetGateway",Properties:{Tags:[{Key:"Name",Value:`${l}-${S}-igw`},{Key:"Environment",Value:S}]}});let Ne=`${l}${S}IGWAttach`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Ne,{Type:"AWS::EC2::VPCGatewayAttachment",Properties:{VpcId:{Ref:"VPC"},InternetGatewayId:{Ref:Ie}}});let nt=`${l}${S}PublicRT`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(nt,{Type:"AWS::EC2::RouteTable",Properties:{VpcId:{Ref:"VPC"},Tags:[{Key:"Name",Value:`${l}-${S}-public-rt`},{Key:"Environment",Value:S}]}}),this.builder.addResource(`${l}${S}PublicRoute`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::EC2::Route",Properties:{RouteTableId:{Ref:nt},DestinationCidrBlock:"0.0.0.0/0",GatewayId:{Ref:Ie}},DependsOn:Ne});let Pt=this.mergedConfig.environments[S]?.region||this.mergedConfig.project.region||"us-east-1",st=["a","b"];for(let ur=0;ur<2;ur++){let pr=`PublicSubnet${ur+1}`;this.builder.addResource(pr,{Type:"AWS::EC2::Subnet",Properties:{VpcId:{Ref:"VPC"},CidrBlock:`10.0.${ur}.0/24`,AvailabilityZone:`${Pt}${st[ur]}`,MapPublicIpOnLaunch:!0,Tags:[{Key:"Name",Value:`${l}-${S}-public-${st[ur]}`},{Key:"Environment",Value:S}]}}),this.builder.addResource(`${pr}RTAssoc`,{Type:"AWS::EC2::SubnetRouteTableAssociation",Properties:{SubnetId:{Ref:pr},RouteTableId:{Ref:nt}}})}}generateContainerInfrastructure(l,S){let P=this.mergedConfig.infrastructure?.containers;if(!P)return;let v=this.mergedConfig.infrastructure?.loadBalancer,E=this.mergedConfig.infrastructure?.ssl,ot=this.mergedConfig.infrastructure?.dns,Ie;if(E?.enabled&&E.domains?.length)if(E.certificateArn);else{let st=E.domains[0],ur=E.domains.slice(1).map((Dt)=>{if(Dt.includes(".")&&Dt.endsWith(st))return Dt.replace(`.${st}`,"");return Dt}),{certificate:pr,logicalId:gr}=I.createCertificate({domain:st,subdomains:ur,slug:l,environment:S,validationMethod:"DNS",hostedZoneId:ot?.hostedZoneId});Ie=gr,this.builder.addResource(gr,pr)}let Ne="ECSCluster";this.builder.addResource(Ne,{Type:"AWS::ECS::Cluster",Properties:{ClusterName:`${l}-${S}`,ClusterSettings:[{Name:"containerInsights",Value:"enabled"}],Tags:[{Key:"Name",Value:`${l}-${S}`},{Key:"Environment",Value:S}]}});let nt=`${l}${S}ALBSecurityGroup`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(nt,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`ALB security group for ${l}-${S}`,VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:80,ToPort:80,CidrIp:"0.0.0.0/0",Description:"HTTP"},{IpProtocol:"tcp",FromPort:443,ToPort:443,CidrIp:"0.0.0.0/0",Description:"HTTPS"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0",Description:"Allow all outbound"}],Tags:[{Key:"Name",Value:`${l}-${S}-alb-sg`},{Key:"Environment",Value:S}]}});let Pt=`${l}${S}ECSSecurityGroup`.replace(/[^a-zA-Z0-9]/g,"");for(let[st,ur]of Object.entries(P)){let pr=ur.port||3000;this.builder.addResource(Pt,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`ECS tasks security group for ${l}-${S}`,VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:pr,ToPort:pr,SourceSecurityGroupId:{Ref:nt},Description:"Allow traffic from ALB"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0",Description:"Allow all outbound"}],Tags:[{Key:"Name",Value:`${l}-${S}-ecs-sg`},{Key:"Environment",Value:S}]}});let gr=`${l}${S}TaskExecRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(gr,{Type:"AWS::IAM::Role",Properties:{RoleName:`${l}-${S}-ecs-exec-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"],Policies:[{PolicyName:"ECRPullPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["ecr:GetAuthorizationToken","ecr:BatchCheckLayerAvailability","ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","logs:CreateLogStream","logs:PutLogEvents"],Resource:"*"}]}}]}});let Dt=`${l}${S}TaskRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Dt,{Type:"AWS::IAM::Role",Properties:{RoleName:`${l}-${S}-ecs-task-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"TaskPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogStream","logs:PutLogEvents"],Resource:"*"},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:ListBucket"],Resource:"*"}]}}]}});let St=`${l}${S}${st}LogGroup`.replace(/[^a-zA-Z0-9]/g,""),Se=`/ecs/${l}-${S}-${st}`;this.builder.addResource(St,{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:Se,RetentionInDays:30}});let Bt=`${l}${S}${st}TaskDef`.replace(/[^a-zA-Z0-9]/g,""),ie=String(ur.cpu||512),Rt=String(ur.memory||1024);this.builder.addResource(Bt,{Type:"AWS::ECS::TaskDefinition",Properties:{Family:`${l}-${S}-${st}`,NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:ie,Memory:Rt,ExecutionRoleArn:{"Fn::GetAtt":[gr,"Arn"]},TaskRoleArn:{"Fn::GetAtt":[Dt,"Arn"]},ContainerDefinitions:[{Name:st,Image:{"Fn::Sub":`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${l}:latest`},Essential:!0,PortMappings:[{ContainerPort:pr,Protocol:"tcp"}],LogConfiguration:{LogDriver:"awslogs",Options:{"awslogs-group":Se,"awslogs-region":{Ref:"AWS::Region"},"awslogs-stream-prefix":st}},HealthCheck:{Command:["CMD-SHELL",`curl -f http://localhost:${pr}${ur.healthCheck||"/health"} || exit 1`],Interval:30,Timeout:5,Retries:3,StartPeriod:60}}],Tags:[{Key:"Name",Value:`${l}-${S}-${st}`},{Key:"Environment",Value:S}]},DependsOn:[gr,Dt,St]});let Nt=`${l}${S}ALB`.replace(/[^a-zA-Z0-9]/g,"");if(v?.enabled!==!1){this.builder.addResource(Nt,{Type:"AWS::ElasticLoadBalancingV2::LoadBalancer",Properties:{Name:`${l}-${S}-alb`,Scheme:"internet-facing",Type:"application",Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],SecurityGroups:[{Ref:nt}],Tags:[{Key:"Name",Value:`${l}-${S}-alb`},{Key:"Environment",Value:S}]}});let er=`${l}${S}TargetGroup`.replace(/[^a-zA-Z0-9]/g,""),lr=v?.healthCheck?.path||ur.healthCheck||"/health";this.builder.addResource(er,{Type:"AWS::ElasticLoadBalancingV2::TargetGroup",Properties:{Name:`${l}-${S}-tg`,Port:pr,Protocol:"HTTP",VpcId:{Ref:"VPC"},TargetType:"ip",HealthCheckPath:lr,HealthCheckIntervalSeconds:v?.healthCheck?.interval||30,HealthyThresholdCount:v?.healthCheck?.healthyThreshold||2,UnhealthyThresholdCount:v?.healthCheck?.unhealthyThreshold||5,HealthCheckTimeoutSeconds:10,Tags:[{Key:"Name",Value:`${l}-${S}-tg`},{Key:"Environment",Value:S}]}});let fr=`${l}${S}HTTPListener`.replace(/[^a-zA-Z0-9]/g,"");if(E?.enabled&&E?.redirectHttp)this.builder.addResource(fr,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:Nt},Port:80,Protocol:"HTTP",DefaultActions:[{Type:"redirect",RedirectConfig:{Protocol:"HTTPS",Port:"443",StatusCode:"HTTP_301"}}]}});else this.builder.addResource(fr,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:Nt},Port:80,Protocol:"HTTP",DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:er}}]}});if(E?.enabled){let br=E.certificateArn||(Ie?{Ref:Ie}:void 0);if(br){let Wi=`${l}${S}HTTPSListener`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Wi,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:Nt},Port:443,Protocol:"HTTPS",Certificates:[{CertificateArn:br}],DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:er}}],SslPolicy:"ELBSecurityPolicy-TLS13-1-2-2021-06"}})}}let Cr=`${l}${S}${st}Service`.replace(/[^a-zA-Z0-9]/g,""),vr=ur.desiredCount||1;this.builder.addResource(Cr,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${l}-${S}-${st}`,Cluster:{Ref:Ne},TaskDefinition:{Ref:Bt},DesiredCount:vr,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:Pt}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},LoadBalancers:[{ContainerName:st,ContainerPort:pr,TargetGroupArn:{Ref:er}}],HealthCheckGracePeriodSeconds:120,Tags:[{Key:"Name",Value:`${l}-${S}-${st}`},{Key:"Environment",Value:S}]},DependsOn:[Bt,fr,er]});let an=ur.autoScaling;if(an){let br=`${l}${S}${st}ScalableTarget`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(br,{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{MaxCapacity:an.max||10,MinCapacity:an.min||1,ResourceId:{"Fn::Sub":`service/\${${Ne}}/${l}-${S}-${st}`},ScalableDimension:"ecs:service:DesiredCount",ServiceNamespace:"ecs",RoleARN:{"Fn::Sub":"arn:aws:iam::${AWS::AccountId}:role/aws-service-role/ecs.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_ECSService"}},DependsOn:Cr}),an.targetCpuUtilization)this.builder.addResource(`${l}${S}${st}CPUScaling`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${l}-${S}-${st}-cpu-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:br},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},TargetValue:an.targetCpuUtilization,ScaleInCooldown:300,ScaleOutCooldown:60}}});if(an.targetMemoryUtilization)this.builder.addResource(`${l}${S}${st}MemoryScaling`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${l}-${S}-${st}-memory-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:br},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageMemoryUtilization"},TargetValue:an.targetMemoryUtilization,ScaleInCooldown:300,ScaleOutCooldown:60}}})}if(ot?.domain&&ot?.hostedZoneId)this.builder.addResource(`${l}${S}ApiDnsRecord`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:ot.hostedZoneId,Name:`api.${ot.domain}`,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":[Nt,"DNSName"]},HostedZoneId:{"Fn::GetAtt":[Nt,"CanonicalHostedZoneID"]}}}});this.builder.addOutput("ECSClusterArn",{Description:"ECS Cluster ARN",Value:{"Fn::GetAtt":[Ne,"Arn"]},Export:{Name:{"Fn::Sub":"${AWS::StackName}-ecs-cluster-arn"}}}),this.builder.addOutput("ECSServiceName",{Description:"ECS Service Name",Value:`${l}-${S}-${st}`,Export:{Name:{"Fn::Sub":"${AWS::StackName}-ecs-service-name"}}}),this.builder.addOutput("LoadBalancerDNS",{Description:"Application Load Balancer DNS Name",Value:{"Fn::GetAtt":[Nt,"DNSName"]},Export:{Name:{"Fn::Sub":"${AWS::StackName}-alb-dns"}}})}else{let er=`${l}${S}${st}Service`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(er,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${l}-${S}-${st}`,Cluster:{Ref:Ne},TaskDefinition:{Ref:Bt},DesiredCount:ur.desiredCount||1,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:Pt}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},Tags:[{Key:"Name",Value:`${l}-${S}-${st}`},{Key:"Environment",Value:S}]},DependsOn:[Bt]})}break}}generateServerless(l,S){if(this.mergedConfig.infrastructure?.functions)for(let[P,v]of Object.entries(this.mergedConfig.infrastructure.functions)){if(!this.shouldDeploy(v))continue;let{role:E,logicalId:ot}=Y.createRole({slug:l,environment:S,roleName:`${l}-${S}-${P}-role`,servicePrincipal:"lambda.amazonaws.com",managedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]});this.builder.addResource(ot,E);let{lambdaFunction:Ie,logicalId:Ne}=a.createLambdaFunction({slug:l,environment:S,functionName:`${l}-${S}-${P}`,handler:v.handler||"index.handler",runtime:v.runtime||"nodejs20.x",code:{zipFile:v.code||"export const handler = async () => ({ statusCode: 200 });"},role:ot,timeout:v.timeout,memorySize:v.memorySize});this.builder.addResource(Ne,Ie)}if(this.mergedConfig.infrastructure?.api){let{restApi:P,logicalId:v}=Pd.createRestApi({slug:l,environment:S,apiName:`${l}-${S}-api`});this.builder.addResource(v,P)}}generateServer(l,S){if(!this.mergedConfig.infrastructure?.servers)return;let P=this.mergedConfig.infrastructure.servers,v=this.mergedConfig.infrastructure?.compute,E=this.mergedConfig.infrastructure?.ssl;if(Object.values(P).some((Ie)=>!Ie.privateNetwork||Ie.privateNetwork==="create"))this.generateNetworkInfrastructure(l,S);for(let[Ie,Ne]of Object.entries(P)){let nt=Ne.instanceType||Ne.size||v?.size,st=(nt?a.InstanceSize.specs[nt]:void 0)?.instanceType||nt||"t3.micro",ur=Ne.type||"app",pr=Ne.userData||Ne.startupScript;if(!pr)pr=a.UserData.generateAppServerScript({runtime:"bun",runtimeVersion:Ne.bunVersion||"latest",webServer:"none",domain:Ne.domain,enableSsl:!!E?.enabled,sslEmail:E?.letsEncrypt?.email,installRedis:ur==="cache",installDatabaseClients:!!Ne.database});let gr=Ne.privateNetwork&&Ne.privateNetwork!=="create"?Ne.privateNetwork:{Ref:"VPC"},Dt=Ne.subnet||{Ref:"PublicSubnet1"},Se=!!this.mergedConfig.infrastructure?.email?.server?.enabled,Bt=[22,80,443,this.resolveApiOriginPort()];if(Se)Bt.push(25,465,587,143,993);let ie=a.createServerModeStack({slug:`${l}-${Ie}`,environment:S,vpcId:gr,subnetId:Dt,instanceType:st,keyName:Ne.keyName||`${l}-${S}`,domain:Ne.domain,userData:pr,volumeSize:Ne.diskSize||20,imageId:Ne.image,allowedPorts:Bt});for(let[Rt,Nt]of Object.entries(ie.resources))this.builder.addResource(Rt,Nt);this.serverEipLogicalIds.set(Ie,ie.outputs.eipLogicalId),this.serverEipLogicalIds.set(`${Ie}Instance`,ie.outputs.instanceLogicalId),this.builder.addOutput(`${Ie}InstanceId`,{Value:{Ref:ie.outputs.instanceLogicalId},Description:`Instance ID for ${Ie} server`}),this.builder.addOutput(`${Ie}PublicIp`,{Value:{Ref:ie.outputs.eipLogicalId},Description:`Public IP for ${Ie} server`})}}generateComputeApp(l,S){let P=this.mergedConfig.infrastructure?.compute;if(!P)return;let v=this.mergedConfig.sites||{},E=Object.entries(v),Ie=this.mergedConfig.infrastructure?.dns?.domain,Ne=this.mergedConfig.infrastructure?.database,nt=P.size,st=(nt?a.InstanceSize.specs[nt]:void 0)?.instanceType||nt||"t3.micro";if(!this.builder.hasResource("VPC"))this.generateNetworkInfrastructure(l,S);let ur=this.buildCaddyfile(E),pr=a.UserData.generateBunAppScript({runtime:P.runtime||"bun",runtimeVersion:P.runtimeVersion||"latest",systemPackages:P.systemPackages,database:Ne,caddyfile:ur}),gr=vs(P.appUpdates),Dt=gr.length>0?`${pr}
10
+ `)}normalizeMountPath(l){let f=l?.mountPath||l?.path;if(!f||f==="/")return;let C=`/${f}`.replace(/\/+/g,"/").replace(/\/$/,"");return C==="/"?void 0:C}storageBucketLogicalId(l,f,C){return`${l}-${f}-s3-${C}`.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((b)=>b.charAt(0).toUpperCase()+b.slice(1)).join("")}pathMountRewriteFunctionCode(l,f="directory"){return`function handler(event) { var request = event.request; var prefix = ${JSON.stringify(l)}; var rewriteStyle = ${JSON.stringify(f)}; var uri = request.uri; if (uri === prefix) { uri = '/'; } else if (uri.indexOf(prefix + '/') === 0) { uri = uri.substring(prefix.length); } if (uri === '' || uri === '/') { request.uri = '/index.html'; return request; } if (uri.endsWith('/')) { request.uri = uri + 'index.html'; return request; } var lastSegment = uri.substring(uri.lastIndexOf('/') + 1); if (lastSegment.indexOf('.') === -1) { request.uri = rewriteStyle === 'flat' ? uri + '.html' : uri + '/index.html'; return request; } request.uri = uri; return request; }`}generate(){let l=this.mergedConfig.project.slug,f=this.environment,C=!!(this.mergedConfig.infrastructure?.functions&&Object.keys(this.mergedConfig.infrastructure.functions).length>0||this.mergedConfig.infrastructure?.api),b=!!(this.mergedConfig.infrastructure?.servers&&Object.keys(this.mergedConfig.infrastructure.servers).length>0),T=!!this.mergedConfig.infrastructure?.compute;if(!!((this.mergedConfig.mode||"server")==="serverless"&&this.mergedConfig.infrastructure?.containers&&Object.keys(this.mergedConfig.infrastructure.containers).length>0))this.generateNetworkInfrastructure(l,f),this.generateContainerInfrastructure(l,f);if(C)this.generateServerless(l,f);if(b)this.generateServer(l,f);if(T)this.generateComputeApp(l,f);if(this.mergedConfig.infrastructure?.jumpBox)this.generateJumpBox(l,f);if(this.storageFailoverReplicas=[],this.generateSharedInfrastructure(l,f),this.storageFailoverReplicas.length>0)this.builder.addMetadata(Pd,this.storageFailoverReplicas);if(this.config.tags)this.applyGlobalTags(this.config.tags);return this}getStorageFailoverReplicas(){return[...this.storageFailoverReplicas]}applyGlobalTags(l){}generateNetworkInfrastructure(l,f){if(this.builder.hasResource("VPC"))return;let b=this.mergedConfig.infrastructure?.network?.cidr||"10.0.0.0/16",{vpc:T,logicalId:it}=A.createVpc({slug:l,environment:f,cidr:b,enableDnsHostnames:!0,enableDnsSupport:!0});this.builder.addResource("VPC",T);let Ce=`${l}${f}IGW`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Ce,{Type:"AWS::EC2::InternetGateway",Properties:{Tags:[{Key:"Name",Value:`${l}-${f}-igw`},{Key:"Environment",Value:f}]}});let Se=`${l}${f}IGWAttach`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Se,{Type:"AWS::EC2::VPCGatewayAttachment",Properties:{VpcId:{Ref:"VPC"},InternetGatewayId:{Ref:Ce}}});let ke=`${l}${f}PublicRT`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(ke,{Type:"AWS::EC2::RouteTable",Properties:{VpcId:{Ref:"VPC"},Tags:[{Key:"Name",Value:`${l}-${f}-public-rt`},{Key:"Environment",Value:f}]}}),this.builder.addResource(`${l}${f}PublicRoute`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::EC2::Route",Properties:{RouteTableId:{Ref:ke},DestinationCidrBlock:"0.0.0.0/0",GatewayId:{Ref:Ce}},DependsOn:Se});let Pt=this.mergedConfig.environments[f]?.region||this.mergedConfig.project.region||"us-east-1",ot=["a","b"];for(let rr=0;rr<2;rr++){let pr=`PublicSubnet${rr+1}`;this.builder.addResource(pr,{Type:"AWS::EC2::Subnet",Properties:{VpcId:{Ref:"VPC"},CidrBlock:`10.0.${rr}.0/24`,AvailabilityZone:`${Pt}${ot[rr]}`,MapPublicIpOnLaunch:!0,Tags:[{Key:"Name",Value:`${l}-${f}-public-${ot[rr]}`},{Key:"Environment",Value:f}]}}),this.builder.addResource(`${pr}RTAssoc`,{Type:"AWS::EC2::SubnetRouteTableAssociation",Properties:{SubnetId:{Ref:pr},RouteTableId:{Ref:ke}}})}}generateContainerInfrastructure(l,f){let C=this.mergedConfig.infrastructure?.containers;if(!C)return;let b=this.mergedConfig.infrastructure?.loadBalancer,T=this.mergedConfig.infrastructure?.ssl,it=this.mergedConfig.infrastructure?.dns,Ce;if(T?.enabled&&T.domains?.length)if(T.certificateArn);else{let ot=T.domains[0],rr=T.domains.slice(1).map((Et)=>{if(Et.includes(".")&&Et.endsWith(ot))return Et.replace(`.${ot}`,"");return Et}),{certificate:pr,logicalId:gr}=S.createCertificate({domain:ot,subdomains:rr,slug:l,environment:f,validationMethod:"DNS",hostedZoneId:it?.hostedZoneId});Ce=gr,this.builder.addResource(gr,pr)}let Se="ECSCluster";this.builder.addResource(Se,{Type:"AWS::ECS::Cluster",Properties:{ClusterName:`${l}-${f}`,ClusterSettings:[{Name:"containerInsights",Value:"enabled"}],Tags:[{Key:"Name",Value:`${l}-${f}`},{Key:"Environment",Value:f}]}});let ke=`${l}${f}ALBSecurityGroup`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(ke,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`ALB security group for ${l}-${f}`,VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:80,ToPort:80,CidrIp:"0.0.0.0/0",Description:"HTTP"},{IpProtocol:"tcp",FromPort:443,ToPort:443,CidrIp:"0.0.0.0/0",Description:"HTTPS"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0",Description:"Allow all outbound"}],Tags:[{Key:"Name",Value:`${l}-${f}-alb-sg`},{Key:"Environment",Value:f}]}});let Pt=`${l}${f}ECSSecurityGroup`.replace(/[^a-zA-Z0-9]/g,"");for(let[ot,rr]of Object.entries(C)){let pr=rr.port||3000;this.builder.addResource(Pt,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`ECS tasks security group for ${l}-${f}`,VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:pr,ToPort:pr,SourceSecurityGroupId:{Ref:ke},Description:"Allow traffic from ALB"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0",Description:"Allow all outbound"}],Tags:[{Key:"Name",Value:`${l}-${f}-ecs-sg`},{Key:"Environment",Value:f}]}});let gr=`${l}${f}TaskExecRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(gr,{Type:"AWS::IAM::Role",Properties:{RoleName:`${l}-${f}-ecs-exec-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"],Policies:[{PolicyName:"ECRPullPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["ecr:GetAuthorizationToken","ecr:BatchCheckLayerAvailability","ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","logs:CreateLogStream","logs:PutLogEvents"],Resource:"*"}]}}]}});let Et=`${l}${f}TaskRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Et,{Type:"AWS::IAM::Role",Properties:{RoleName:`${l}-${f}-ecs-task-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"TaskPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogStream","logs:PutLogEvents"],Resource:"*"},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:ListBucket"],Resource:"*"}]}}]}});let at=`${l}${f}${ot}LogGroup`.replace(/[^a-zA-Z0-9]/g,""),se=`/ecs/${l}-${f}-${ot}`;this.builder.addResource(at,{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:se,RetentionInDays:30}});let kt=`${l}${f}${ot}TaskDef`.replace(/[^a-zA-Z0-9]/g,""),N=String(rr.cpu||512),ct=String(rr.memory||1024);this.builder.addResource(kt,{Type:"AWS::ECS::TaskDefinition",Properties:{Family:`${l}-${f}-${ot}`,NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:N,Memory:ct,ExecutionRoleArn:{"Fn::GetAtt":[gr,"Arn"]},TaskRoleArn:{"Fn::GetAtt":[Et,"Arn"]},ContainerDefinitions:[{Name:ot,Image:{"Fn::Sub":`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${l}:latest`},Essential:!0,PortMappings:[{ContainerPort:pr,Protocol:"tcp"}],LogConfiguration:{LogDriver:"awslogs",Options:{"awslogs-group":se,"awslogs-region":{Ref:"AWS::Region"},"awslogs-stream-prefix":ot}},HealthCheck:{Command:["CMD-SHELL",`curl -f http://localhost:${pr}${rr.healthCheck||"/health"} || exit 1`],Interval:30,Timeout:5,Retries:3,StartPeriod:60}}],Tags:[{Key:"Name",Value:`${l}-${f}-${ot}`},{Key:"Environment",Value:f}]},DependsOn:[gr,Et,at]});let Nt=`${l}${f}ALB`.replace(/[^a-zA-Z0-9]/g,"");if(b?.enabled!==!1){this.builder.addResource(Nt,{Type:"AWS::ElasticLoadBalancingV2::LoadBalancer",Properties:{Name:`${l}-${f}-alb`,Scheme:"internet-facing",Type:"application",Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],SecurityGroups:[{Ref:ke}],Tags:[{Key:"Name",Value:`${l}-${f}-alb`},{Key:"Environment",Value:f}]}});let xt=`${l}${f}TargetGroup`.replace(/[^a-zA-Z0-9]/g,""),Bt=b?.healthCheck?.path||rr.healthCheck||"/health";this.builder.addResource(xt,{Type:"AWS::ElasticLoadBalancingV2::TargetGroup",Properties:{Name:`${l}-${f}-tg`,Port:pr,Protocol:"HTTP",VpcId:{Ref:"VPC"},TargetType:"ip",HealthCheckPath:Bt,HealthCheckIntervalSeconds:b?.healthCheck?.interval||30,HealthyThresholdCount:b?.healthCheck?.healthyThreshold||2,UnhealthyThresholdCount:b?.healthCheck?.unhealthyThreshold||5,HealthCheckTimeoutSeconds:10,Tags:[{Key:"Name",Value:`${l}-${f}-tg`},{Key:"Environment",Value:f}]}});let mr=`${l}${f}HTTPListener`.replace(/[^a-zA-Z0-9]/g,"");if(T?.enabled&&T?.redirectHttp)this.builder.addResource(mr,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:Nt},Port:80,Protocol:"HTTP",DefaultActions:[{Type:"redirect",RedirectConfig:{Protocol:"HTTPS",Port:"443",StatusCode:"HTTP_301"}}]}});else this.builder.addResource(mr,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:Nt},Port:80,Protocol:"HTTP",DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:xt}}]}});if(T?.enabled){let yr=T.certificateArn||(Ce?{Ref:Ce}:void 0);if(yr){let Tr=`${l}${f}HTTPSListener`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Tr,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:Nt},Port:443,Protocol:"HTTPS",Certificates:[{CertificateArn:yr}],DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:xt}}],SslPolicy:"ELBSecurityPolicy-TLS13-1-2-2021-06"}})}}let hr=`${l}${f}${ot}Service`.replace(/[^a-zA-Z0-9]/g,""),br=rr.desiredCount||1;this.builder.addResource(hr,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${l}-${f}-${ot}`,Cluster:{Ref:Se},TaskDefinition:{Ref:kt},DesiredCount:br,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:Pt}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},LoadBalancers:[{ContainerName:ot,ContainerPort:pr,TargetGroupArn:{Ref:xt}}],HealthCheckGracePeriodSeconds:120,Tags:[{Key:"Name",Value:`${l}-${f}-${ot}`},{Key:"Environment",Value:f}]},DependsOn:[kt,mr,xt]});let Wi=rr.autoScaling;if(Wi){let yr=`${l}${f}${ot}ScalableTarget`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(yr,{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{MaxCapacity:Wi.max||10,MinCapacity:Wi.min||1,ResourceId:{"Fn::Sub":`service/\${${Se}}/${l}-${f}-${ot}`},ScalableDimension:"ecs:service:DesiredCount",ServiceNamespace:"ecs",RoleARN:{"Fn::Sub":"arn:aws:iam::${AWS::AccountId}:role/aws-service-role/ecs.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_ECSService"}},DependsOn:hr}),Wi.targetCpuUtilization)this.builder.addResource(`${l}${f}${ot}CPUScaling`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${l}-${f}-${ot}-cpu-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:yr},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},TargetValue:Wi.targetCpuUtilization,ScaleInCooldown:300,ScaleOutCooldown:60}}});if(Wi.targetMemoryUtilization)this.builder.addResource(`${l}${f}${ot}MemoryScaling`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${l}-${f}-${ot}-memory-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:yr},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageMemoryUtilization"},TargetValue:Wi.targetMemoryUtilization,ScaleInCooldown:300,ScaleOutCooldown:60}}})}if(it?.domain&&it?.hostedZoneId)this.builder.addResource(`${l}${f}ApiDnsRecord`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:it.hostedZoneId,Name:`api.${it.domain}`,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":[Nt,"DNSName"]},HostedZoneId:{"Fn::GetAtt":[Nt,"CanonicalHostedZoneID"]}}}});this.builder.addOutput("ECSClusterArn",{Description:"ECS Cluster ARN",Value:{"Fn::GetAtt":[Se,"Arn"]},Export:{Name:{"Fn::Sub":"${AWS::StackName}-ecs-cluster-arn"}}}),this.builder.addOutput("ECSServiceName",{Description:"ECS Service Name",Value:`${l}-${f}-${ot}`,Export:{Name:{"Fn::Sub":"${AWS::StackName}-ecs-service-name"}}}),this.builder.addOutput("LoadBalancerDNS",{Description:"Application Load Balancer DNS Name",Value:{"Fn::GetAtt":[Nt,"DNSName"]},Export:{Name:{"Fn::Sub":"${AWS::StackName}-alb-dns"}}})}else{let xt=`${l}${f}${ot}Service`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(xt,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${l}-${f}-${ot}`,Cluster:{Ref:Se},TaskDefinition:{Ref:kt},DesiredCount:rr.desiredCount||1,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:Pt}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},Tags:[{Key:"Name",Value:`${l}-${f}-${ot}`},{Key:"Environment",Value:f}]},DependsOn:[kt]})}break}}generateServerless(l,f){if(this.mergedConfig.infrastructure?.functions)for(let[C,b]of Object.entries(this.mergedConfig.infrastructure.functions)){if(!this.shouldDeploy(b))continue;let{role:T,logicalId:it}=Z.createRole({slug:l,environment:f,roleName:`${l}-${f}-${C}-role`,servicePrincipal:"lambda.amazonaws.com",managedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]});this.builder.addResource(it,T);let{lambdaFunction:Ce,logicalId:Se}=a.createLambdaFunction({slug:l,environment:f,functionName:`${l}-${f}-${C}`,handler:b.handler||"index.handler",runtime:b.runtime||"nodejs20.x",code:{zipFile:b.code||"export const handler = async () => ({ statusCode: 200 });"},role:it,timeout:b.timeout,memorySize:b.memorySize});this.builder.addResource(Se,Ce)}if(this.mergedConfig.infrastructure?.api){let{restApi:C,logicalId:b}=Bd.createRestApi({slug:l,environment:f,apiName:`${l}-${f}-api`});this.builder.addResource(b,C)}}generateServer(l,f){if(!this.mergedConfig.infrastructure?.servers)return;let C=this.mergedConfig.infrastructure.servers,b=this.mergedConfig.infrastructure?.compute,T=this.mergedConfig.infrastructure?.ssl;if(Object.values(C).some((Ce)=>!Ce.privateNetwork||Ce.privateNetwork==="create"))this.generateNetworkInfrastructure(l,f);for(let[Ce,Se]of Object.entries(C)){let ke=Se.instanceType||Se.size||b?.size,ot=(ke?a.InstanceSize.specs[ke]:void 0)?.instanceType||ke||"t3.micro",rr=Se.type||"app",pr=Se.userData||Se.startupScript;if(!pr)pr=a.UserData.generateAppServerScript({runtime:"bun",runtimeVersion:Se.bunVersion||"latest",webServer:"none",domain:Se.domain,enableSsl:!!T?.enabled,sslEmail:T?.letsEncrypt?.email,installRedis:rr==="cache",installDatabaseClients:!!Se.database});let gr=Se.privateNetwork&&Se.privateNetwork!=="create"?Se.privateNetwork:{Ref:"VPC"},Et=Se.subnet||{Ref:"PublicSubnet1"},se=!!this.mergedConfig.infrastructure?.email?.server?.enabled,kt=[22,80,443,this.resolveApiOriginPort()];if(se)kt.push(25,465,587,143,993);let N=a.createServerModeStack({slug:`${l}-${Ce}`,environment:f,vpcId:gr,subnetId:Et,instanceType:ot,keyName:Se.keyName||`${l}-${f}`,domain:Se.domain,userData:pr,volumeSize:Se.diskSize||20,imageId:Se.image,allowedPorts:kt});for(let[ct,Nt]of Object.entries(N.resources))this.builder.addResource(ct,Nt);this.serverEipLogicalIds.set(Ce,N.outputs.eipLogicalId),this.serverEipLogicalIds.set(`${Ce}Instance`,N.outputs.instanceLogicalId),this.builder.addOutput(`${Ce}InstanceId`,{Value:{Ref:N.outputs.instanceLogicalId},Description:`Instance ID for ${Ce} server`}),this.builder.addOutput(`${Ce}PublicIp`,{Value:{Ref:N.outputs.eipLogicalId},Description:`Public IP for ${Ce} server`})}}generateComputeApp(l,f){let C=this.mergedConfig.infrastructure?.compute;if(!C)return;let b=this.mergedConfig.sites||{},T=Object.entries(b),Ce=this.mergedConfig.infrastructure?.dns?.domain,Se=this.mergedConfig.infrastructure?.database,ke=C.size,ot=(ke?a.InstanceSize.specs[ke]:void 0)?.instanceType||ke||"t3.micro";if(!this.builder.hasResource("VPC"))this.generateNetworkInfrastructure(l,f);let rr=this.buildCaddyfile(T),pr=a.UserData.generateBunAppScript({runtime:C.runtime||"bun",runtimeVersion:C.runtimeVersion||"latest",systemPackages:C.systemPackages,database:Se,caddyfile:rr}),gr=ws(C.appUpdates),Et=gr.length>0?`${pr}
11
11
  ${gr.join(`
12
12
  `)}
13
- `:pr,St=E.map(([,lr])=>lr.port).filter((lr)=>typeof lr==="number"&&![80,443].includes(lr)),Se=this.resolveApiOriginPort(),Bt=`${l}${S}DeployBucket`.replace(/[^a-zA-Z0-9]/g,""),ie=`${l}-${S}-deploy`;this.builder.addResource(Bt,{Type:"AWS::S3::Bucket",Properties:{BucketName:ie,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},LifecycleConfiguration:{Rules:[{Id:"expire-old-releases",Status:"Enabled",ExpirationInDays:7,Prefix:"releases/"}]},Tags:[{Key:"Project",Value:l},{Key:"Environment",Value:S},{Key:"ManagedBy",Value:"ts-cloud"}]}});let Rt=a.createServerModeStack({slug:`${l}-app`,environment:S,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},instanceType:st,keyName:P.allowSsh?`${l}-${S}`:void 0,domain:Ie,userData:Dt,volumeSize:P.disk?.size||20,imageId:P.image,allowedPorts:[...P.allowSsh?[22]:[],80,443,Se,...St]}),Nt=Rt.resources[Rt.outputs.instanceLogicalId];if(Nt?.Properties){let lr=Nt.Properties.Tags||[];Nt.Properties.Tags=[...lr,{Key:"Project",Value:l},{Key:"Environment",Value:S},{Key:"Role",Value:"app"},{Key:"ManagedBy",Value:"ts-cloud"}]}let er=Rt.resources[Rt.outputs.roleLogicalId];if(er?.Properties)er.Properties.Policies=er.Properties.Policies||[],er.Properties.Policies.push({PolicyName:"DeployBucketRead",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:GetObject","s3:ListBucket"],Resource:[`arn:aws:s3:::${ie}`,`arn:aws:s3:::${ie}/*`]}]}});for(let[lr,fr]of Object.entries(Rt.resources))this.builder.addResource(lr,fr);this.builder.addOutput("deployBucketName",{Value:{Ref:Bt},Description:"S3 bucket where release tarballs are uploaded"}),this.builder.addOutput("appInstanceId",{Value:{Ref:Rt.outputs.instanceLogicalId},Description:"EC2 instance ID for the app server"}),this.builder.addOutput("appPublicIp",{Value:{Ref:Rt.outputs.eipLogicalId},Description:"Public IP for the app server"}),this.serverEipLogicalIds.set("app",Rt.outputs.eipLogicalId),this.serverEipLogicalIds.set("appInstance",Rt.outputs.instanceLogicalId)}generateJumpBox(l,S){let P=this.mergedConfig.infrastructure?.jumpBox;if(!P)return;let v=P===!0?{}:P;if(v.enabled===!1)return;this.generateNetworkInfrastructure(l,S);let E=v.size||"micro",Ie=a.InstanceSize.specs[E]?.instanceType||E||"t3.micro",Ne;if(v.mountEfs)Ne={fileSystemId:typeof v.mountEfs==="string"?v.mountEfs:{Ref:"FileSystem"},mountPath:v.mountPath||"/mnt/efs"};let nt;if(v.databaseTools)nt=a.JumpBox.withDatabaseTools({slug:l,environment:S,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:v.keyName||`${l}-${S}`,allowedCidrs:v.allowedCidrs});else if(Ne)nt=a.JumpBox.withEfsMount({slug:l,environment:S,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:v.keyName||`${l}-${S}`,fileSystemId:Ne.fileSystemId,mountPath:Ne.mountPath,allowedCidrs:v.allowedCidrs});else nt=a.createJumpBox({slug:l,environment:S,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:v.keyName||`${l}-${S}`,instanceType:Ie,allowedCidrs:v.allowedCidrs,mountEfs:Ne});for(let[Pt,st]of Object.entries(nt.resources))this.builder.addResource(Pt,st);this.builder.addOutput("JumpBoxInstanceId",{Value:{Ref:nt.instanceLogicalId},Description:"The ID of the JumpBox EC2 instance (use with SSM Session Manager or SSH)"})}generateSharedInfrastructure(l,S){let P=this.mergedConfig.infrastructure?.ssl,v=this.mergedConfig.infrastructure?.dns,E=v?.domain,ot=v?.hostedZoneId,Ie=[],Ne,nt;if(P?.certificateArn)nt=P.certificateArn;else if(P?.enabled&&E&&ot){let St=P.domains||[E],Se=St[0],Bt=St.slice(1).map((Nt)=>{if(Nt.includes(".")&&Nt.endsWith(Se))return Nt.replace(`.${Se}`,"");return Nt}),{certificate:ie,logicalId:Rt}=I.createCertificate({domain:Se,subdomains:Bt,slug:l,environment:S,validationMethod:"DNS",hostedZoneId:ot});Ne=Rt,this.builder.addResource(Rt,ie)}if(this.mergedConfig.infrastructure?.storage){let St=Object.entries(this.mergedConfig.infrastructure.storage).some(([,ie])=>ie.website),Se;if(St&&(Ne||nt))Se=`${l}${S}CloudFrontOAC`.replace(/[^a-zA-Z0-9]/g,""),this.builder.addResource(Se,{Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${l}-${S}-s3-oac`,Description:`OAC for ${l} ${S} S3 website buckets`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}});let Bt=Object.entries(this.mergedConfig.infrastructure.storage).map(([ie,Rt])=>({name:ie,config:Rt,mountPath:this.normalizeMountPath(Rt),rewriteStyle:Rt.pathRewriteStyle||"directory",logicalId:this.storageBucketLogicalId(l,S,ie)})).filter((ie)=>ie.name!=="public"&&ie.config.website&&ie.mountPath);for(let[ie,Rt]of Object.entries(this.mergedConfig.infrastructure.storage)){let Nt=!!(Rt.website&&Se),er=this.storageBucketName(l,S,ie),{bucket:lr,logicalId:fr}=ve.createBucket({slug:l,name:ie,environment:S,bucketName:er,versioning:Rt.versioning,encryption:Rt.encryption,public:Nt?!1:Rt.public}),Cr=this.normalizeMountPath(Rt),vr;if(Rt.failover){let br=`infrastructure.storage.${ie}`;if(!Nt||!E||Cr&&ie!=="public")throw Error(`${br}.failover needs this bucket to be served by its own CloudFront distribution: a website bucket (website: true), not mounted under the path of another site, with infrastructure.dns.domain set and SSL configured (infrastructure.ssl.certificateArn, or ssl.enabled with dns.hostedZoneId).`);if(vr=gg({failover:Rt.failover,primaryBucket:er,primaryRegion:this.mergedConfig.project.region||"us-east-1",where:br}),vr.replicate&&lr.Properties){let Wi=`${fr}FailoverReplicationRole`;this.builder.addResource(Wi,hg({primaryBucket:er,replicaBucket:vr.replicaBucket}));let wn=lr.Properties;wn.VersioningConfiguration={Status:"Enabled"},wn.ReplicationConfiguration=fg({replicaBucket:vr.replicaBucket,roleArn:{"Fn::GetAtt":[Wi,"Arn"]}})}}if(Nt&&lr.Properties)lr.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1};if(this.builder.addResource(fr,lr),Rt.website){let br=typeof Rt.website==="object"?Rt.website:{},Wi=ve.enableWebsiteHosting(lr,br.indexDocument||"index.html",br.errorDocument);this.builder.addResource(fr,Wi)}let an=this.normalizeMountPath(Rt);if(Nt&&Se&&E&&!(an&&ie!=="public")){let br=`${l}${S}${ie}CDN`.replace(/[^a-zA-Z0-9]/g,""),Wi=[];if(Rt.aliases&&Rt.aliases.length>0)Wi.push(...Rt.aliases);else if(ie==="public"){if(Wi.push(E),P?.domains?.includes(`www.${E}`))Wi.push(`www.${E}`)}else if(ie==="docs")Wi.push(`docs.${E}`);else if(ie==="blog")Wi.push(`blog.${E}`);let wn=typeof Rt.website==="object"?Rt.website:{},Fn=Rt.spa===!0,On=wn.errorDocument||(Fn?"index.html":"404.html"),pn=[];if(Fn)pn.push({ErrorCode:403,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:300});else pn.push({ErrorCode:403,ResponseCode:404,ResponsePagePath:`/${On}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${On}`,ErrorCachingMinTTL:300});let Hn=nt&&Wi.length>0?{AcmCertificateArn:nt,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:Ne&&Wi.length>0?{AcmCertificateArn:{Ref:Ne},SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},Jn=`S3-${l}-${S}-${ie}`,bs=this.mergedConfig.project.region||"us-east-1",Qn;if(!Fn)Qn=`${l}${S}${ie}UrlRewrite`.replace(/[^a-zA-Z0-9]/g,""),this.builder.addResource(Qn,{Type:"AWS::CloudFront::Function",Properties:{Name:`${l}-${S}-${ie}-url-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`URL rewrite for ${l} ${S} ${ie} - appends .html to extensionless paths`,Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) { var request = event.request; var uri = request.uri; if (uri.endsWith('/')) { request.uri += 'index.html'; }
14
- else if (!uri.includes('.')) { request.uri += '.html'; } return request; }`}});let ha=[{Id:Jn,DomainName:{"Fn::Sub":`\${${fr}}.s3.${bs}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:Se}}],qa=[],Rs=[];if(this.shouldRouteStorageBucketToCompute(ie,Rt)){this.appendComputeAppOrigin(ha,qa,Rs,l,S,this.resolveComputeCachePathPatterns(Rt.computeRoutes));for(let zi of Bt){let ns=`S3-${l}-${S}-${zi.name}`,ec=`${l}${S}${zi.name}PathMountRewrite`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(ec,{Type:"AWS::CloudFront::Function",Properties:{Name:`${l}-${S}-${zi.name}-path-mount-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`Path mount rewrite for ${l} ${S} ${zi.name} at ${zi.mountPath}`,Runtime:"cloudfront-js-2.0"},FunctionCode:this.pathMountRewriteFunctionCode(zi.mountPath,zi.rewriteStyle)}}),ha.push({Id:ns,DomainName:{"Fn::Sub":`\${${zi.logicalId}}.s3.${bs}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:Se}}),Rs.push(zi.logicalId,ec);for(let Kl of[zi.mountPath,`${zi.mountPath}/*`])qa.push({PathPattern:Kl,TargetOriginId:ns,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[ec,"FunctionARN"]}}]})}}let is,sc=Jn;if(vr){let zi=`${Jn}-failover`;Object.assign(ha[0],vr.primaryConnection),ha.push({Id:zi,DomainName:mg(vr.replicaBucket,vr.replicaRegion),OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:Se}}),is=Fr({primaryOriginId:Jn,secondaryOriginId:zi,statusCodes:vr.statusCodes}),sc=is.Items[0].Id}let ws={Type:"AWS::CloudFront::Distribution",DependsOn:[fr,Se,...Qn?[Qn]:[],...Rs],Properties:{DistributionConfig:{Enabled:!0,Comment:`${l} ${S} ${ie} site`,DefaultRootObject:"index.html",Origins:ha,...is?{OriginGroups:is}:{},DefaultCacheBehavior:{TargetOriginId:sc,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",...Qn?{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[Qn,"FunctionARN"]}}]}:{}},...qa.length>0?{CacheBehaviors:qa}:{},...Wi.length>0?{Aliases:Wi}:{},ViewerCertificate:Hn,PriceClass:"PriceClass_100",HttpVersion:"http2and3",IPV6Enabled:!0,CustomErrorResponses:pn}}};if(Ne)ws.DependsOn.push(Ne);if(vr)Ht(ws.Properties.DistributionConfig,`infrastructure.storage.${ie}`),this.storageFailoverReplicas.push({name:ie,primaryBucket:er,primaryRegion:bs,replicaBucket:vr.replicaBucket,replicaRegion:vr.replicaRegion,replicate:vr.replicate,distributionArnOutput:`${ie}CloudFrontDistributionArn`}),this.builder.addOutput(`${ie}CloudFrontDistributionArn`,{Value:{"Fn::Sub":`arn:\${AWS::Partition}:cloudfront::\${AWS::AccountId}:distribution/\${${br}}`},Description:`CloudFront distribution ARN for ${ie} (scopes the bucket policy of the failover replica)`}),this.builder.addOutput(`${ie}FailoverBucketName`,{Value:vr.replicaBucket,Description:`Failover replica bucket for ${ie} (${vr.replicaRegion}), outside this stack`});this.builder.addResource(br,ws);let zl=`${fr}CloudFrontPolicy`;if(this.builder.addResource(zl,{Type:"AWS::S3::BucketPolicy",DependsOn:[fr,br],Properties:{Bucket:{Ref:fr},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":`arn:aws:s3:::\${${fr}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${br}}`}}}}]}}}),this.shouldRouteStorageBucketToCompute(ie,Rt))for(let zi of Bt){let ns=`${zi.logicalId}CloudFrontPolicy`;this.builder.addResource(ns,{Type:"AWS::S3::BucketPolicy",DependsOn:[zi.logicalId,br],Properties:{Bucket:{Ref:zi.logicalId},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":`arn:aws:s3:::\${${zi.logicalId}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${br}}`}}}}]}}})}if(Wi.length>0)Ie.push({name:ie,bucketLogicalId:fr,distLogicalId:br,oacLogicalId:Se,aliases:Wi});this.builder.addOutput(`${ie}CloudFrontDomain`,{Value:{"Fn::GetAtt":[br,"DomainName"]},Description:`CloudFront domain for ${ie}`}),this.builder.addOutput(`${ie}CloudFrontDistributionId`,{Value:{Ref:br},Description:`CloudFront distribution ID for ${ie}`})}if(this.builder.addOutput(`${ie}BucketName`,{Value:{Ref:fr},Description:`S3 bucket name for ${ie}`}),ie==="public")this.builder.addOutput("FrontendBucketName",{Value:{Ref:fr},Description:"Frontend S3 bucket name"});if(ie==="docs")this.builder.addOutput("DocsBucketName",{Value:{Ref:fr},Description:"Documentation S3 bucket name"});if(ie==="blog")this.builder.addOutput("BlogBucketName",{Value:{Ref:fr},Description:"Blog S3 bucket name"})}}if(this.mergedConfig.infrastructure?.sftp){let St=this.mergedConfig.infrastructure.sftp,Se=Dd.create({...St,storage:this.resolveSftpStorage(St,l,S)??St.storage,slug:l,environment:S});for(let[Bt,ie]of Object.entries(Se.resources))this.builder.addResource(Bt,ie);this.builder.addOutput("SftpServerId",{Value:{Ref:Se.serverLogicalId},Description:"AWS Transfer Family SFTP server ID"}),this.builder.addOutput("SftpEndpoint",{Value:{"Fn::Sub":`\${${Se.serverLogicalId}}.server.transfer.\${AWS::Region}.amazonaws.com`},Description:"AWS Transfer Family SFTP endpoint"}),this.builder.addOutput("SftpStorageDomain",{Value:Se.domain,Description:"Storage backing the SFTP server (EFS or S3)"})}if(ot&&Ie.length>0)for(let{name:St,distLogicalId:Se,aliases:Bt}of Ie)for(let ie of Bt){let Rt=ie.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${Rt}ARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[Se],Properties:{HostedZoneId:ot,Name:ie,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":[Se,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}}),this.builder.addResource(`${Rt}AAAARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[Se],Properties:{HostedZoneId:ot,Name:ie,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":[Se,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}})}if(this.mergedConfig.infrastructure?.databases){for(let[St,Se]of Object.entries(this.mergedConfig.infrastructure.databases))if(Se.engine==="dynamodb"){let{table:Bt,logicalId:ie}=Gt.createTable({slug:l,environment:S,tableName:`${l}-${S}-${St}`,partitionKey:Se.partitionKey||{name:"id",type:"S"},sortKey:Se.sortKey});this.builder.addResource(ie,Bt)}else if(Se.engine==="postgres"){let{dbInstance:Bt,logicalId:ie}=Gt.createPostgres({slug:l,environment:S,dbInstanceIdentifier:`${l}-${S}-${St}`,masterUsername:Se.username||"admin",masterUserPassword:Se.password||"changeme123",allocatedStorage:Se.storage||20,dbInstanceClass:Se.instanceClass||"db.t3.micro"});this.builder.addResource(ie,Bt)}else if(Se.engine==="mysql"){let{dbInstance:Bt,logicalId:ie}=Gt.createMysql({slug:l,environment:S,dbInstanceIdentifier:`${l}-${S}-${St}`,masterUsername:Se.username||"admin",masterUserPassword:Se.password||"changeme123",allocatedStorage:Se.storage||20,dbInstanceClass:Se.instanceClass||"db.t3.micro"});this.builder.addResource(ie,Bt)}}if(this.mergedConfig.infrastructure?.cdn)for(let[St,Se]of Object.entries(this.mergedConfig.infrastructure.cdn)){if(!Se.origin)continue;let Bt=typeof Se.customDomain==="string"?Se.customDomain:Se.customDomain?.domain||Se.domain,ie=typeof Se.customDomain==="object"?Se.customDomain?.certificateArn:Se.certificateArn,Rt=ie||nt,Nt=`${l}${S}${St}CDN`.replace(/[^a-zA-Z0-9]/g,""),er=`S3-${l}-${S}-${St}-cdn`,lr=[{Id:er,DomainName:Se.origin,OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginShield:Se.originShield?{Enabled:!0,OriginShieldRegion:Se.originShieldRegion||this.mergedConfig.environments[S]?.region||this.mergedConfig.project.region||"us-east-1"}:{Enabled:!1},...Te(Se,`infrastructure.cdn.${St}`)}],fr=[],Cr=[],vr=["GET","HEAD","OPTIONS"],an=er,br;if(Se.failoverOrigin){Qt(vr,`the default cache behavior of infrastructure.cdn.${St}`);let On=`${er}-failover`,pn=typeof Se.failoverOrigin==="string"?{domain:Se.failoverOrigin}:Se.failoverOrigin;if(!pn.domain)throw Error(`infrastructure.cdn.${St}.failoverOrigin.domain is required`);if(pn.domain===Se.origin)throw Error(`infrastructure.cdn.${St}: failoverOrigin must differ from origin (both are ${Se.origin})`);lr.push({Id:On,DomainName:pn.domain,OriginPath:pn.originPath||"",...Td(pn.domain)?{S3OriginConfig:{OriginAccessIdentity:""}}:{CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"}},OriginShield:{Enabled:!1},...Te(pn,`infrastructure.cdn.${St}.failoverOrigin`)}),br=Fr({primaryOriginId:er,secondaryOriginId:On,statusCodes:Se.failoverStatusCodes}),an=br.Items[0].Id}else if(Se.failoverStatusCodes)throw Error(`infrastructure.cdn.${St}: failoverStatusCodes needs failoverOrigin to fail over to`);if(Se.routeCompute)this.appendComputeAppOrigin(lr,fr,Cr,l,S,this.resolveComputeCachePathPatterns(Se.computeRoutes));let Wi=Rt&&Bt?{AcmCertificateArn:Ne&&!ie?{Ref:Ne}:Rt,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},wn=[...Cr];if(Ne&&!ie&&Bt)wn.push(Ne);let Fn={Type:"AWS::CloudFront::Distribution",...wn.length>0?{DependsOn:wn}:{},Properties:{DistributionConfig:{Enabled:!0,Comment:`${l} ${S} ${St} CDN`,DefaultRootObject:"index.html",Origins:lr,...br?{OriginGroups:br}:{},DefaultCacheBehavior:{TargetOriginId:an,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:vr,CachedMethods:["GET","HEAD","OPTIONS"],Compress:Se.compress!==!1,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},...fr.length>0?{CacheBehaviors:fr}:{},...Bt&&Rt?{Aliases:[Bt]}:{},ViewerCertificate:Wi,PriceClass:"PriceClass_100",HttpVersion:Se.http3?"http2and3":"http2"}}};if(Ht(Fn.Properties.DistributionConfig,`infrastructure.cdn.${St}`),this.builder.addResource(Nt,Fn),ot&&Bt&&Rt){let On=Bt.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${On}CdnARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[Nt,...Ne&&!ie?[Ne]:[]],Properties:{HostedZoneId:ot,Name:Bt,Type:"A",AliasTarget:{HostedZoneId:"Z2FDTNDATAQYW2",DNSName:{"Fn::GetAtt":[Nt,"DomainName"]}}}})}}if(this.mergedConfig.infrastructure?.queues)for(let[St,Se]of Object.entries(this.mergedConfig.infrastructure.queues)){if(!this.shouldDeploy(Se))continue;let{queue:Bt,logicalId:ie}=M.createQueue({slug:l,environment:S,name:`${l}-${S}-${St}`,fifo:Se.fifo,visibilityTimeout:Se.visibilityTimeout,messageRetentionPeriod:Se.messageRetentionPeriod,delaySeconds:Se.delaySeconds,maxMessageSize:Se.maxMessageSize,receiveMessageWaitTime:Se.receiveMessageWaitTime,contentBasedDeduplication:Se.contentBasedDeduplication,encrypted:Se.encrypted,kmsKeyId:Se.kmsKeyId});this.builder.addResource(ie,Bt);let Rt;if(Se.deadLetterQueue){let{deadLetterQueue:Nt,updatedSourceQueue:er,deadLetterLogicalId:lr}=M.createDeadLetterQueue(ie,{slug:l,environment:S,maxReceiveCount:Se.maxReceiveCount});Rt=lr,this.builder.addResource(lr,Nt);let Cr=this.builder.getResources()[ie];if(Cr?.Properties)Cr.Properties.RedrivePolicy=er.Properties?.RedrivePolicy}if(Se.trigger){let Nt=Se.trigger,er=`${l}${S}${Nt.functionName}`.replace(/[^a-zA-Z0-9]/g,""),lr={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:{"Fn::GetAtt":[ie,"Arn"]},FunctionName:{Ref:er},BatchSize:Nt.batchSize||10,MaximumBatchingWindowInSeconds:Nt.batchWindow||0,Enabled:!0,...Nt.reportBatchItemFailures!==!1&&{FunctionResponseTypes:["ReportBatchItemFailures"]},...Nt.maxConcurrency&&{ScalingConfig:{MaximumConcurrency:Nt.maxConcurrency}},...Nt.filterPattern&&{FilterCriteria:{Filters:[{Pattern:JSON.stringify(Nt.filterPattern)}]}}},DependsOn:[ie,er]};this.builder.addResource(`${ie}Trigger`,lr)}if(Se.alarms?.enabled){let Nt=Se.alarms,er=Nt.notificationTopicArn;if(!er&&Nt.notificationEmails?.length){let Cr=`${ie}AlarmTopic`;this.builder.addResource(Cr,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${l}-${S}-${St}-alarms`,DisplayName:`${St} Queue Alarms`}}),Nt.notificationEmails.forEach((vr,an)=>{this.builder.addResource(`${Cr}Sub${an}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:Cr},Protocol:"email",Endpoint:vr}})}),er={Ref:Cr}}let lr=Nt.queueDepthThreshold||1000;this.builder.addResource(`${ie}DepthAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-${St}-queue-depth`,AlarmDescription:`Queue ${St} depth exceeds ${lr} messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:lr,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[ie,"QueueName"]}}],...er&&{AlarmActions:[er],OKActions:[er]}}});let fr=Nt.messageAgeThreshold||3600;if(this.builder.addResource(`${ie}AgeAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-${St}-message-age`,AlarmDescription:`Queue ${St} oldest message exceeds ${fr} seconds`,MetricName:"ApproximateAgeOfOldestMessage",Namespace:"AWS/SQS",Statistic:"Maximum",Period:300,EvaluationPeriods:2,Threshold:fr,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[ie,"QueueName"]}}],...er&&{AlarmActions:[er],OKActions:[er]}}}),Rt&&Nt.dlqAlarm!==!1)this.builder.addResource(`${Rt}Alarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-${St}-dlq-messages`,AlarmDescription:`Dead letter queue for ${St} has messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Sum",Period:300,EvaluationPeriods:1,Threshold:0,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[Rt,"QueueName"]}}],...er&&{AlarmActions:[er]}}})}if(Se.subscribe){let Nt=Se.subscribe,er=Nt.topicArn;if(!er&&Nt.topicName)er={Ref:Nt.topicName};if(er){this.builder.addResource(`${ie}SnsPolicy`,{Type:"AWS::SQS::QueuePolicy",Properties:{Queues:[{Ref:ie}],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"sns.amazonaws.com"},Action:"sqs:SendMessage",Resource:{"Fn::GetAtt":[ie,"Arn"]},Condition:{ArnEquals:{"aws:SourceArn":er}}}]}}});let lr={TopicArn:er,Protocol:"sqs",Endpoint:{"Fn::GetAtt":[ie,"Arn"]},RawMessageDelivery:Nt.rawMessageDelivery||!1};if(Nt.filterPolicy)lr.FilterPolicy=Nt.filterPolicy,lr.FilterPolicyScope=Nt.filterPolicyScope||"MessageAttributes";this.builder.addResource(`${ie}SnsSub`,{Type:"AWS::SNS::Subscription",Properties:lr,DependsOn:`${ie}SnsPolicy`})}}}if(this.mergedConfig.infrastructure?.realtime?.enabled)if((this.mergedConfig.infrastructure.realtime.mode||"serverless")==="server")this.generateRealtimeServerResources(l,S);else this.generateRealtimeResources(l,S);let Pt=this.mergedConfig.infrastructure?.redirects;if(Pt){let St=Pt.target||this.mergedConfig.infrastructure?.dns?.domain||"",Se=Pt.protocol||"https";if(Pt.domains?.length&&St)for(let Bt of Pt.domains){let{bucket:ie,bucketPolicy:Rt,logicalId:Nt,policyLogicalId:er}=gt.createDomainRedirectBucket({slug:l,environment:S,sourceDomain:Bt,targetDomain:St,protocol:Se});this.builder.addResource(Nt,ie),this.builder.addResource(er,Rt)}if(Pt.paths&&Object.keys(Pt.paths).length>0){let Bt=gt.fromMapping(Pt.paths,{statusCode:Pt.statusCode||301}),{function:ie,logicalId:Rt}=gt.createPathRedirectFunction({slug:l,environment:S,rules:Bt});this.builder.addResource(Rt,ie)}}if(this.mergedConfig.infrastructure?.monitoring?.alarms)for(let[St,Se]of Object.entries(this.mergedConfig.infrastructure.monitoring.alarms)){let{alarm:Bt,logicalId:ie}=co.createAlarm({slug:l,environment:S,alarmName:`${l}-${S}-${St}`,metricName:Se.metricName||"Errors",namespace:Se.namespace||"AWS/Lambda",threshold:Se.threshold||1,comparisonOperator:Se.comparisonOperator||"GreaterThanThreshold"});this.builder.addResource(ie,Bt)}let st=this.mergedConfig.infrastructure?.cache;if(st){let St=st.type||"redis";if(St==="redis"){this.generateNetworkInfrastructure(l,S);let Se=st.redis||{},{replicationGroup:Bt,subnetGroup:ie,logicalId:Rt,subnetGroupId:Nt}=ao.createRedis({slug:l,environment:S,nodeType:Se.nodeType||st.nodeType||"cache.t3.micro",engineVersion:Se.engineVersion||"7.1",port:Se.port||6379,numCacheClusters:Se.numCacheNodes||2,automaticFailover:Se.automaticFailoverEnabled!==!1,atRestEncryption:!0,transitEncryption:!0,snapshotRetentionDays:Se.snapshotRetentionLimit||7,snapshotWindow:Se.snapshotWindow,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(Rt,Bt),ie&&Nt)this.builder.addResource(Nt,ie);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[Rt,"PrimaryEndPoint.Address"]},Description:"Redis primary endpoint address"}),this.builder.addOutput("CachePort",{Value:{"Fn::GetAtt":[Rt,"PrimaryEndPoint.Port"]},Description:"Redis primary endpoint port"})}else if(St==="memcached"){this.generateNetworkInfrastructure(l,S);let Se=st.elasticache||{},{cluster:Bt,subnetGroup:ie,logicalId:Rt,subnetGroupId:Nt}=ao.createMemcached({slug:l,environment:S,nodeType:Se.nodeType||st.nodeType||"cache.t3.micro",engineVersion:Se.engineVersion||"1.6.22",numCacheNodes:Se.numCacheNodes||2,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(Rt,Bt),ie&&Nt)this.builder.addResource(Nt,ie);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[Rt,"ConfigurationEndpoint.Address"]},Description:"Memcached configuration endpoint address"})}}let ur=this.mergedConfig.infrastructure?.email;if(ur){let St=ur.domain||this.mergedConfig.infrastructure?.dns?.domain;if(St){let{emailIdentity:Se,logicalId:Bt}=m.verifyDomain({domain:St,slug:l,environment:S,enableDkim:ur.enableDkim!==!1,dkimKeyLength:ur.dkimKeyLength||"RSA_2048_BIT"});if(this.builder.addResource(Bt,Se),ur.configurationSet!==!1){let{configurationSet:Nt,logicalId:er}=m.createConfigurationSet({slug:l,environment:S});this.builder.addResource(er,Nt)}let ie=ur.hostedZoneId||this.mergedConfig.infrastructure?.dns?.hostedZoneId;if(ie){if(ur.enableDkim!==!1)for(let Cr=1;Cr<=3;Cr++){let vr=`DkimRecord${Cr}${St.replace(/\./g,"")}`;this.builder.addResource(vr,{Type:"AWS::Route53::RecordSet",DependsOn:[Bt],Properties:{HostedZoneId:ie,Name:{"Fn::GetAtt":[Bt,`DkimDNSTokenName${Cr}`]},Type:"CNAME",TTL:1800,ResourceRecords:[{"Fn::GetAtt":[Bt,`DkimDNSTokenValue${Cr}`]}]}})}let{record:Nt,logicalId:er}=m.createSpfRecord(St,ie);this.builder.addResource(er,Nt);let{record:lr,logicalId:fr}=m.createDmarcRecord(St,ie,{policy:"none",reportingEmail:ur.dmarcReportingEmail||`dmarc-reports@${St}`});this.builder.addResource(fr,lr)}this.builder.addOutput("EmailDomain",{Value:St,Description:"SES verified email domain"});let Rt=ur.server;if(Rt?.enabled&&ie){let Nt=this.mergedConfig.environments[S]?.region||this.mergedConfig.project.region||"us-east-1",er=`${l}-${S}-email`,{role:lr,policy:fr,roleLogicalId:Cr,policyLogicalId:vr}=m.createEmailLambdaRole({slug:l,environment:S,s3BucketArn:`arn:aws:s3:::${er}`,sesIdentityArn:`arn:aws:ses:${Nt}:*:identity/${St}`});this.builder.addResource(Cr,lr),this.builder.addResource(vr,fr);let{function:an,permission:br,logicalId:Wi,permissionLogicalId:wn}=m.createInboundEmailLambda({slug:l,environment:S,roleArn:{"Fn::GetAtt":[Cr,"Arn"]},s3BucketName:er,organizedPrefix:"mailboxes/"});this.builder.addResource(Wi,an),this.builder.addResource(wn,br);let Fn=m.createInboundEmailSetup({slug:l,environment:S,domain:St,s3BucketName:er,s3KeyPrefix:"inbox/",region:Nt,hostedZoneId:ie,lambdaFunctionArn:{"Fn::GetAtt":[Wi,"Arn"]}});for(let[pn,Hn]of Object.entries(Fn.resources)){if(Hn.Type==="AWS::SES::ReceiptRule")Hn.DependsOn=[wn,Wi];this.builder.addResource(pn,Hn)}this.builder.addOutput("InboundEmailLambda",{Value:{Ref:Wi},Description:"Inbound email processing Lambda function"}),this.builder.addOutput("EmailBucket",{Value:er,Description:"S3 bucket for email storage"});let On=this.serverEipLogicalIds.get("app");if(On&&ie){let Hn=`${Rt?.subdomain||"mail"}.${St}`,Jn=Hn.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${Jn}ARecord`,{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:ie,Name:Hn,Type:"A",TTL:"300",ResourceRecords:[{Ref:On}]}})}this.builder.addOutput("MailHost",{Value:`mail.${St}`,Description:"Mail server hostname for SMTP/IMAP clients"})}}}let pr=this.mergedConfig.infrastructure?.search;if(pr){let St=pr.vpc?{subnetIds:[{Ref:"PublicSubnet1"}],securityGroupIds:[]}:void 0;if(St)this.generateNetworkInfrastructure(l,S);let{domain:Se,logicalId:Bt}=qt.createDomain({slug:l,environment:S,engineVersion:pr.engineVersion||"OpenSearch_2.11",instanceType:pr.instanceType||"t3.small.search",instanceCount:pr.instanceCount||1,volumeSize:pr.volumeSize||10,volumeType:pr.volumeType||"gp3",dedicatedMaster:pr.dedicatedMaster||!1,dedicatedMasterType:pr.dedicatedMasterType,dedicatedMasterCount:pr.dedicatedMasterCount||3,multiAz:pr.multiAz||!1,encryption:pr.encryption||{atRest:!0,nodeToNode:!0},advancedSecurity:pr.advancedSecurity,autoTune:pr.autoTune!==!1,vpc:St});this.builder.addResource(Bt,Se),this.builder.addOutput("SearchDomainEndpoint",{Value:{"Fn::GetAtt":[Bt,"DomainEndpoint"]},Description:"OpenSearch domain endpoint"}),this.builder.addOutput("SearchDomainArn",{Value:{"Fn::GetAtt":[Bt,"Arn"]},Description:"OpenSearch domain ARN"})}let gr=this.mergedConfig.infrastructure?.fileSystem;if(gr&&Object.keys(gr).length>0){this.generateNetworkInfrastructure(l,S);for(let[St,Se]of Object.entries(gr)){let{fileSystem:Bt,logicalId:ie}=qe.createFileSystem({slug:`${l}-${St}`,environment:S,encrypted:Se.encrypted!==!1,performanceMode:Se.performanceMode||"generalPurpose",throughputMode:Se.throughputMode||"bursting",enableBackup:!0});this.builder.addResource(ie,Bt);let{securityGroup:Rt,logicalId:Nt}=qe.createEfsSecurityGroup({slug:`${l}-${St}`,environment:S,vpcId:{Ref:"VPC"},sourceCidrBlocks:["10.0.0.0/16"]});this.builder.addResource(Nt,Rt);let{mountTargets:er,logicalIds:lr}=qe.createMultiAzMountTargets(ie,{slug:`${l}-${St}`,environment:S,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],securityGroupId:{Ref:Nt}});for(let fr=0;fr<er.length;fr++)this.builder.addResource(lr[fr],er[fr]);this.builder.addOutput(`${St}FileSystemId`,{Value:{Ref:ie},Description:`EFS file system ID for ${St}`})}}let Dt=this.mergedConfig.infrastructure?.ai;if(Dt){let St=Dt.service||"ecs",Se=Dt.models||["*"],Bt=Dt.allowStreaming!==!1,ie;if(St==="ecs")ie=we.enableBedrockForEcs({slug:l,environment:S,models:Se,allowStreaming:Bt});else if(St==="ec2")ie=we.enableBedrockForEc2({slug:l,environment:S,models:Se,allowStreaming:Bt});else if(St==="lambda")ie=we.enableBedrockForLambda({slug:l,environment:S,models:Se,allowStreaming:Bt});else ie=we.createBedrockRole(St,{slug:l,environment:S,models:Se,allowStreaming:Bt});if(this.builder.addResource(ie.logicalId,ie.role),Dt.allowAsync){let{policy:Rt,logicalId:Nt}=we.createBedrockPolicy({slug:l,environment:S,models:Se,allowStreaming:Bt,allowAsync:!0});this.builder.addResource(Nt,Rt)}this.builder.addOutput("BedrockRoleArn",{Value:{"Fn::GetAtt":[ie.logicalId,"Arn"]},Description:"IAM role ARN with Bedrock permissions"})}}generateRealtimeResources(l,S){let P=this.mergedConfig.infrastructure?.realtime;if(!P)return;let v=P.name||`${l}-${S}-realtime`,E=P.scaling||{},ot=P.storage||{type:"dynamodb"},Ie=E.handlerMemory||256,Ne=E.handlerTimeout||30,nt=`${l}${S}RealtimeConnections`.replace(/[^a-zA-Z0-9]/g,""),Pt=`${l}${S}RealtimeChannels`.replace(/[^a-zA-Z0-9]/g,"");if(ot.type==="dynamodb"){let lr=ot.dynamodb||{},fr=lr.billingMode||"PAY_PER_REQUEST";this.builder.addResource(nt,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${l}-${S}-realtime-connections`,BillingMode:fr,AttributeDefinitions:[{AttributeName:"connectionId",AttributeType:"S"},{AttributeName:"userId",AttributeType:"S"}],KeySchema:[{AttributeName:"connectionId",KeyType:"HASH"}],GlobalSecondaryIndexes:[{IndexName:"userId-index",KeySchema:[{AttributeName:"userId",KeyType:"HASH"}],Projection:{ProjectionType:"ALL"},...fr==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:lr.readCapacity||5,WriteCapacityUnits:lr.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...fr==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:lr.readCapacity||5,WriteCapacityUnits:lr.writeCapacity||5}},...lr.pointInTimeRecovery&&{PointInTimeRecoverySpecification:{PointInTimeRecoveryEnabled:!0}},Tags:[{Key:"Name",Value:`${l}-${S}-realtime-connections`},{Key:"Environment",Value:S}]}}),this.builder.addResource(Pt,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${l}-${S}-realtime-channels`,BillingMode:fr,AttributeDefinitions:[{AttributeName:"channel",AttributeType:"S"},{AttributeName:"connectionId",AttributeType:"S"}],KeySchema:[{AttributeName:"channel",KeyType:"HASH"},{AttributeName:"connectionId",KeyType:"RANGE"}],GlobalSecondaryIndexes:[{IndexName:"connectionId-index",KeySchema:[{AttributeName:"connectionId",KeyType:"HASH"}],Projection:{ProjectionType:"ALL"},...fr==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:lr.readCapacity||5,WriteCapacityUnits:lr.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...fr==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:lr.readCapacity||5,WriteCapacityUnits:lr.writeCapacity||5}},Tags:[{Key:"Name",Value:`${l}-${S}-realtime-channels`},{Key:"Environment",Value:S}]}})}let st=`${l}${S}RealtimeRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(st,{Type:"AWS::IAM::Role",Properties:{RoleName:`${l}-${S}-realtime-handler-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:"RealtimeHandlerPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan","dynamodb:UpdateItem"],Resource:[{"Fn::GetAtt":[nt,"Arn"]},{"Fn::Sub":`\${${nt}.Arn}/index/*`},{"Fn::GetAtt":[Pt,"Arn"]},{"Fn::Sub":`\${${Pt}.Arn}/index/*`}]},{Effect:"Allow",Action:"execute-api:ManageConnections",Resource:{"Fn::Sub":"arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:*/*"}}]}}]}});let ur=`${l}${S}RealtimeConnect`.replace(/[^a-zA-Z0-9]/g,""),pr=`${l}${S}RealtimeDisconnect`.replace(/[^a-zA-Z0-9]/g,""),gr=`${l}${S}RealtimeMessage`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(ur,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${l}-${S}-realtime-connect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[st,"Arn"]},MemorySize:Ie,Timeout:Ne,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:nt},CHANNELS_TABLE:{Ref:Pt},ENVIRONMENT:S}},Code:{ZipFile:this.generateConnectHandlerCode()}},DependsOn:[st,nt]}),this.builder.addResource(pr,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${l}-${S}-realtime-disconnect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[st,"Arn"]},MemorySize:Ie,Timeout:Ne,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:nt},CHANNELS_TABLE:{Ref:Pt},ENVIRONMENT:S}},Code:{ZipFile:this.generateDisconnectHandlerCode()}},DependsOn:[st,nt,Pt]}),this.builder.addResource(gr,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${l}-${S}-realtime-message`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[st,"Arn"]},MemorySize:Ie,Timeout:Ne,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:nt},CHANNELS_TABLE:{Ref:Pt},ENVIRONMENT:S}},Code:{ZipFile:this.generateMessageHandlerCode()}},DependsOn:[st,nt,Pt]});let Dt=`${l}${S}RealtimeApi`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Dt,{Type:"AWS::ApiGatewayV2::Api",Properties:{Name:v,ProtocolType:"WEBSOCKET",RouteSelectionExpression:"$request.body.action",Tags:{Name:v,Environment:S}}});let St=`${ur}Permission`,Se=`${pr}Permission`,Bt=`${gr}Permission`;this.builder.addResource(St,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:ur},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${Dt}}/*/$connect`}}}),this.builder.addResource(Se,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:pr},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${Dt}}/*/$disconnect`}}}),this.builder.addResource(Bt,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:gr},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${Dt}}/*/$default`}}});let ie=`${Dt}ConnectInteg`,Rt=`${Dt}DisconnectInteg`,Nt=`${Dt}MessageInteg`;this.builder.addResource(ie,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:Dt},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${ur}.Arn}/invocations`}}}),this.builder.addResource(Rt,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:Dt},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${pr}.Arn}/invocations`}}}),this.builder.addResource(Nt,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:Dt},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${gr}.Arn}/invocations`}}}),this.builder.addResource(`${Dt}ConnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:Dt},RouteKey:"$connect",AuthorizationType:"NONE",Target:{"Fn::Sub":`integrations/\${${ie}}`}}}),this.builder.addResource(`${Dt}DisconnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:Dt},RouteKey:"$disconnect",Target:{"Fn::Sub":`integrations/\${${Rt}}`}}}),this.builder.addResource(`${Dt}DefaultRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:Dt},RouteKey:"$default",Target:{"Fn::Sub":`integrations/\${${Nt}}`}}});let er=`${Dt}Stage`;if(this.builder.addResource(er,{Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:{Ref:Dt},StageName:S,AutoDeploy:!0,DefaultRouteSettings:{ThrottlingBurstLimit:E.messagesPerSecond||1000,ThrottlingRateLimit:E.messagesPerSecond||1000}}}),P.monitoring?.enabled){let lr=P.monitoring,fr=lr.notificationTopicArn;if(!fr&&lr.notificationEmails?.length){let Cr=`${Dt}AlarmTopic`;this.builder.addResource(Cr,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${l}-${S}-realtime-alarms`,DisplayName:"Realtime WebSocket Alarms"}}),lr.notificationEmails.forEach((vr,an)=>{this.builder.addResource(`${Cr}Sub${an}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:Cr},Protocol:"email",Endpoint:vr}})}),fr={Ref:Cr}}if(lr.connectionThreshold)this.builder.addResource(`${Dt}ConnectionAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-realtime-connections`,AlarmDescription:`WebSocket connections exceed ${lr.connectionThreshold}`,MetricName:"ConnectCount",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:300,EvaluationPeriods:2,Threshold:lr.connectionThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:Dt}}],...fr&&{AlarmActions:[fr]}}});if(lr.errorThreshold)this.builder.addResource(`${Dt}ErrorAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-realtime-errors`,AlarmDescription:`WebSocket errors exceed ${lr.errorThreshold}/min`,MetricName:"ExecutionError",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:60,EvaluationPeriods:3,Threshold:lr.errorThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:Dt}}],...fr&&{AlarmActions:[fr]}}})}this.builder.addOutput(`${Dt}Endpoint`,{Description:"WebSocket API endpoint URL",Value:{"Fn::Sub":`wss://\${${Dt}}.execute-api.\${AWS::Region}.amazonaws.com/${S}`},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-endpoint"}}}),this.builder.addOutput(`${Dt}Id`,{Description:"WebSocket API ID",Value:{Ref:Dt},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-api-id"}}})}generateConnectHandlerCode(){return`
13
+ `:pr,at=T.map(([,Bt])=>Bt.port).filter((Bt)=>typeof Bt==="number"&&![80,443].includes(Bt)),se=this.resolveApiOriginPort(),kt=`${l}${f}DeployBucket`.replace(/[^a-zA-Z0-9]/g,""),N=`${l}-${f}-deploy`;this.builder.addResource(kt,{Type:"AWS::S3::Bucket",Properties:{BucketName:N,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},LifecycleConfiguration:{Rules:[{Id:"expire-old-releases",Status:"Enabled",ExpirationInDays:7,Prefix:"releases/"}]},Tags:[{Key:"Project",Value:l},{Key:"Environment",Value:f},{Key:"ManagedBy",Value:"ts-cloud"}]}});let ct=a.createServerModeStack({slug:`${l}-app`,environment:f,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},instanceType:ot,keyName:C.allowSsh?`${l}-${f}`:void 0,domain:Ce,userData:Et,volumeSize:C.disk?.size||20,imageId:C.image,allowedPorts:[...C.allowSsh?[22]:[],80,443,se,...at]}),Nt=ct.resources[ct.outputs.instanceLogicalId];if(Nt?.Properties){let Bt=Nt.Properties.Tags||[];Nt.Properties.Tags=[...Bt,{Key:"Project",Value:l},{Key:"Environment",Value:f},{Key:"Role",Value:"app"},{Key:"ManagedBy",Value:"ts-cloud"}]}let xt=ct.resources[ct.outputs.roleLogicalId];if(xt?.Properties)xt.Properties.Policies=xt.Properties.Policies||[],xt.Properties.Policies.push({PolicyName:"DeployBucketRead",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:GetObject","s3:ListBucket"],Resource:[`arn:aws:s3:::${N}`,`arn:aws:s3:::${N}/*`]}]}});for(let[Bt,mr]of Object.entries(ct.resources))this.builder.addResource(Bt,mr);this.builder.addOutput("deployBucketName",{Value:{Ref:kt},Description:"S3 bucket where release tarballs are uploaded"}),this.builder.addOutput("appInstanceId",{Value:{Ref:ct.outputs.instanceLogicalId},Description:"EC2 instance ID for the app server"}),this.builder.addOutput("appPublicIp",{Value:{Ref:ct.outputs.eipLogicalId},Description:"Public IP for the app server"}),this.serverEipLogicalIds.set("app",ct.outputs.eipLogicalId),this.serverEipLogicalIds.set("appInstance",ct.outputs.instanceLogicalId)}generateJumpBox(l,f){let C=this.mergedConfig.infrastructure?.jumpBox;if(!C)return;let b=C===!0?{}:C;if(b.enabled===!1)return;this.generateNetworkInfrastructure(l,f);let T=b.size||"micro",Ce=a.InstanceSize.specs[T]?.instanceType||T||"t3.micro",Se;if(b.mountEfs)Se={fileSystemId:typeof b.mountEfs==="string"?b.mountEfs:{Ref:"FileSystem"},mountPath:b.mountPath||"/mnt/efs"};let ke;if(b.databaseTools)ke=a.JumpBox.withDatabaseTools({slug:l,environment:f,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:b.keyName||`${l}-${f}`,allowedCidrs:b.allowedCidrs});else if(Se)ke=a.JumpBox.withEfsMount({slug:l,environment:f,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:b.keyName||`${l}-${f}`,fileSystemId:Se.fileSystemId,mountPath:Se.mountPath,allowedCidrs:b.allowedCidrs});else ke=a.createJumpBox({slug:l,environment:f,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:b.keyName||`${l}-${f}`,instanceType:Ce,allowedCidrs:b.allowedCidrs,mountEfs:Se});for(let[Pt,ot]of Object.entries(ke.resources))this.builder.addResource(Pt,ot);this.builder.addOutput("JumpBoxInstanceId",{Value:{Ref:ke.instanceLogicalId},Description:"The ID of the JumpBox EC2 instance (use with SSM Session Manager or SSH)"})}generateSharedInfrastructure(l,f){let C=this.mergedConfig.infrastructure?.ssl,b=this.mergedConfig.infrastructure?.dns,T=b?.domain,it=b?.hostedZoneId,Ce=[],Se,ke;if(C?.certificateArn)ke=C.certificateArn;else if(C?.enabled&&T&&it){let at=C.domains||[T],se=at[0],kt=at.slice(1).map((Nt)=>{if(Nt.includes(".")&&Nt.endsWith(se))return Nt.replace(`.${se}`,"");return Nt}),{certificate:N,logicalId:ct}=S.createCertificate({domain:se,subdomains:kt,slug:l,environment:f,validationMethod:"DNS",hostedZoneId:it});Se=ct,this.builder.addResource(ct,N)}if(this.mergedConfig.infrastructure?.storage){let at=Object.entries(this.mergedConfig.infrastructure.storage).some(([,N])=>N.website),se;if(at&&(Se||ke))se=`${l}${f}CloudFrontOAC`.replace(/[^a-zA-Z0-9]/g,""),this.builder.addResource(se,{Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${l}-${f}-s3-oac`,Description:`OAC for ${l} ${f} S3 website buckets`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}});let kt=Object.entries(this.mergedConfig.infrastructure.storage).map(([N,ct])=>({name:N,config:ct,mountPath:this.normalizeMountPath(ct),rewriteStyle:ct.pathRewriteStyle||"directory",logicalId:this.storageBucketLogicalId(l,f,N)})).filter((N)=>N.name!=="public"&&N.config.website&&N.mountPath);for(let[N,ct]of Object.entries(this.mergedConfig.infrastructure.storage)){let Nt=!!(ct.website&&se),xt=this.storageBucketName(l,f,N),{bucket:Bt,logicalId:mr}=Te.createBucket({slug:l,name:N,environment:f,bucketName:xt,versioning:ct.versioning,encryption:ct.encryption,public:Nt?!1:ct.public}),hr=this.normalizeMountPath(ct),br;if(ct.failover){let yr=`infrastructure.storage.${N}`;if(!Nt||!T||hr&&N!=="public")throw Error(`${yr}.failover needs this bucket to be served by its own CloudFront distribution: a website bucket (website: true), not mounted under the path of another site, with infrastructure.dns.domain set and SSL configured (infrastructure.ssl.certificateArn, or ssl.enabled with dns.hostedZoneId).`);if(br=fg({failover:ct.failover,primaryBucket:xt,primaryRegion:this.mergedConfig.project.region||"us-east-1",where:yr}),br.replicate&&Bt.Properties){let Tr=`${mr}FailoverReplicationRole`;this.builder.addResource(Tr,yg({primaryBucket:xt,replicaBucket:br.replicaBucket}));let dn=Bt.Properties;dn.VersioningConfiguration={Status:"Enabled"},dn.ReplicationConfiguration=Ig({replicaBucket:br.replicaBucket,roleArn:{"Fn::GetAtt":[Tr,"Arn"]}})}}if(Nt&&Bt.Properties)Bt.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1};if(this.builder.addResource(mr,Bt),ct.website){let yr=typeof ct.website==="object"?ct.website:{},Tr=Te.enableWebsiteHosting(Bt,yr.indexDocument||"index.html",yr.errorDocument);this.builder.addResource(mr,Tr)}let Wi=this.normalizeMountPath(ct);if(Nt&&se&&T&&!(Wi&&N!=="public")){let yr=`${l}${f}${N}CDN`.replace(/[^a-zA-Z0-9]/g,""),Tr=[];if(ct.aliases&&ct.aliases.length>0)Tr.push(...ct.aliases);else if(N==="public"){if(Tr.push(T),C?.domains?.includes(`www.${T}`))Tr.push(`www.${T}`)}else if(N==="docs")Tr.push(`docs.${T}`);else if(N==="blog")Tr.push(`blog.${T}`);let dn=typeof ct.website==="object"?ct.website:{},Ln=ct.spa===!0,mn=dn.errorDocument||(Ln?"index.html":"404.html"),Xi=[];if(Ln)Xi.push({ErrorCode:403,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:300});else Xi.push({ErrorCode:403,ResponseCode:404,ResponsePagePath:`/${mn}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${mn}`,ErrorCachingMinTTL:300});let Fn=ke&&Tr.length>0?{AcmCertificateArn:ke,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:Se&&Tr.length>0?{AcmCertificateArn:{Ref:Se},SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},_n=`S3-${l}-${f}-${N}`,ss=this.mergedConfig.project.region||"us-east-1",Gn;if(!Ln)Gn=`${l}${f}${N}UrlRewrite`.replace(/[^a-zA-Z0-9]/g,""),this.builder.addResource(Gn,{Type:"AWS::CloudFront::Function",Properties:{Name:`${l}-${f}-${N}-url-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`URL rewrite for ${l} ${f} ${N} - appends .html to extensionless paths`,Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) { var request = event.request; var uri = request.uri; if (uri.endsWith('/')) { request.uri += 'index.html'; }
14
+ else if (!uri.includes('.')) { request.uri += '.html'; } return request; }`}});let qn=[{Id:_n,DomainName:{"Fn::Sub":`\${${mr}}.s3.${ss}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:se}}],Ia=[],ls=[];if(this.shouldRouteStorageBucketToCompute(N,ct)){this.appendComputeAppOrigin(qn,Ia,ls,l,f,this.resolveComputeCachePathPatterns(ct.computeRoutes));for(let wr of kt){let qa=`S3-${l}-${f}-${wr.name}`,Ts=`${l}${f}${wr.name}PathMountRewrite`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Ts,{Type:"AWS::CloudFront::Function",Properties:{Name:`${l}-${f}-${wr.name}-path-mount-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`Path mount rewrite for ${l} ${f} ${wr.name} at ${wr.mountPath}`,Runtime:"cloudfront-js-2.0"},FunctionCode:this.pathMountRewriteFunctionCode(wr.mountPath,wr.rewriteStyle)}}),qn.push({Id:qa,DomainName:{"Fn::Sub":`\${${wr.logicalId}}.s3.${ss}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:se}}),ls.push(wr.logicalId,Ts);for(let Ec of[wr.mountPath,`${wr.mountPath}/*`])Ia.push({PathPattern:Ec,TargetOriginId:qa,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[Ts,"FunctionARN"]}}]})}}let ja,ac=_n;if(br){let wr=`${_n}-failover`;Object.assign(qn[0],br.primaryConnection),qn.push({Id:wr,DomainName:Ag(br.replicaBucket,br.replicaRegion),OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:se}}),ja=Qr({primaryOriginId:_n,secondaryOriginId:wr,statusCodes:br.statusCodes}),ac=ja.Items[0].Id}let Ps={Type:"AWS::CloudFront::Distribution",DependsOn:[mr,se,...Gn?[Gn]:[],...ls],Properties:{DistributionConfig:{Enabled:!0,Comment:`${l} ${f} ${N} site`,DefaultRootObject:"index.html",Origins:qn,...ja?{OriginGroups:ja}:{},DefaultCacheBehavior:{TargetOriginId:ac,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",...Gn?{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[Gn,"FunctionARN"]}}]}:{}},...Ia.length>0?{CacheBehaviors:Ia}:{},...Tr.length>0?{Aliases:Tr}:{},ViewerCertificate:Fn,PriceClass:"PriceClass_100",HttpVersion:"http2and3",IPV6Enabled:!0,CustomErrorResponses:Xi}}};if(Se)Ps.DependsOn.push(Se);if(br)qt(Ps.Properties.DistributionConfig,`infrastructure.storage.${N}`),this.storageFailoverReplicas.push({name:N,primaryBucket:xt,primaryRegion:ss,replicaBucket:br.replicaBucket,replicaRegion:br.replicaRegion,replicate:br.replicate,distributionArnOutput:`${N}CloudFrontDistributionArn`}),this.builder.addOutput(`${N}CloudFrontDistributionArn`,{Value:{"Fn::Sub":`arn:\${AWS::Partition}:cloudfront::\${AWS::AccountId}:distribution/\${${yr}}`},Description:`CloudFront distribution ARN for ${N} (scopes the bucket policy of the failover replica)`}),this.builder.addOutput(`${N}FailoverBucketName`,{Value:br.replicaBucket,Description:`Failover replica bucket for ${N} (${br.replicaRegion}), outside this stack`});this.builder.addResource(yr,Ps);let Ic=`${mr}CloudFrontPolicy`;if(this.builder.addResource(Ic,{Type:"AWS::S3::BucketPolicy",DependsOn:[mr,yr],Properties:{Bucket:{Ref:mr},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":`arn:aws:s3:::\${${mr}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${yr}}`}}}}]}}}),this.shouldRouteStorageBucketToCompute(N,ct))for(let wr of kt){let qa=`${wr.logicalId}CloudFrontPolicy`;this.builder.addResource(qa,{Type:"AWS::S3::BucketPolicy",DependsOn:[wr.logicalId,yr],Properties:{Bucket:{Ref:wr.logicalId},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":`arn:aws:s3:::\${${wr.logicalId}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${yr}}`}}}}]}}})}if(Tr.length>0)Ce.push({name:N,bucketLogicalId:mr,distLogicalId:yr,oacLogicalId:se,aliases:Tr});this.builder.addOutput(`${N}CloudFrontDomain`,{Value:{"Fn::GetAtt":[yr,"DomainName"]},Description:`CloudFront domain for ${N}`}),this.builder.addOutput(`${N}CloudFrontDistributionId`,{Value:{Ref:yr},Description:`CloudFront distribution ID for ${N}`})}if(this.builder.addOutput(`${N}BucketName`,{Value:{Ref:mr},Description:`S3 bucket name for ${N}`}),N==="public")this.builder.addOutput("FrontendBucketName",{Value:{Ref:mr},Description:"Frontend S3 bucket name"});if(N==="docs")this.builder.addOutput("DocsBucketName",{Value:{Ref:mr},Description:"Documentation S3 bucket name"});if(N==="blog")this.builder.addOutput("BlogBucketName",{Value:{Ref:mr},Description:"Blog S3 bucket name"})}}if(this.mergedConfig.infrastructure?.sftp){let at=this.mergedConfig.infrastructure.sftp,se=kd.create({...at,storage:this.resolveSftpStorage(at,l,f)??at.storage,slug:l,environment:f});for(let[kt,N]of Object.entries(se.resources))this.builder.addResource(kt,N);this.builder.addOutput("SftpServerId",{Value:{Ref:se.serverLogicalId},Description:"AWS Transfer Family SFTP server ID"}),this.builder.addOutput("SftpEndpoint",{Value:{"Fn::Sub":`\${${se.serverLogicalId}}.server.transfer.\${AWS::Region}.amazonaws.com`},Description:"AWS Transfer Family SFTP endpoint"}),this.builder.addOutput("SftpStorageDomain",{Value:se.domain,Description:"Storage backing the SFTP server (EFS or S3)"})}if(it&&Ce.length>0)for(let{name:at,distLogicalId:se,aliases:kt}of Ce)for(let N of kt){let ct=N.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${ct}ARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[se],Properties:{HostedZoneId:it,Name:N,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":[se,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}}),this.builder.addResource(`${ct}AAAARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[se],Properties:{HostedZoneId:it,Name:N,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":[se,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}})}if(this.mergedConfig.infrastructure?.databases){for(let[at,se]of Object.entries(this.mergedConfig.infrastructure.databases))if(se.engine==="dynamodb"){let{table:kt,logicalId:N}=Vt.createTable({slug:l,environment:f,tableName:`${l}-${f}-${at}`,partitionKey:se.partitionKey||{name:"id",type:"S"},sortKey:se.sortKey});this.builder.addResource(N,kt)}else if(se.engine==="postgres"){let{dbInstance:kt,logicalId:N}=Vt.createPostgres({slug:l,environment:f,dbInstanceIdentifier:`${l}-${f}-${at}`,masterUsername:se.username||"admin",masterUserPassword:se.password||"changeme123",allocatedStorage:se.storage||20,dbInstanceClass:se.instanceClass||"db.t3.micro"});this.builder.addResource(N,kt)}else if(se.engine==="mysql"){let{dbInstance:kt,logicalId:N}=Vt.createMysql({slug:l,environment:f,dbInstanceIdentifier:`${l}-${f}-${at}`,masterUsername:se.username||"admin",masterUserPassword:se.password||"changeme123",allocatedStorage:se.storage||20,dbInstanceClass:se.instanceClass||"db.t3.micro"});this.builder.addResource(N,kt)}}if(this.mergedConfig.infrastructure?.cdn)for(let[at,se]of Object.entries(this.mergedConfig.infrastructure.cdn)){if(!se.origin)continue;let kt=typeof se.customDomain==="string"?se.customDomain:se.customDomain?.domain||se.domain,N=typeof se.customDomain==="object"?se.customDomain?.certificateArn:se.certificateArn,ct=N||ke,Nt=`${l}${f}${at}CDN`.replace(/[^a-zA-Z0-9]/g,""),xt=`S3-${l}-${f}-${at}-cdn`,Bt=[{Id:xt,DomainName:se.origin,OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginShield:se.originShield?{Enabled:!0,OriginShieldRegion:se.originShieldRegion||this.mergedConfig.environments[f]?.region||this.mergedConfig.project.region||"us-east-1"}:{Enabled:!1},...we(se,`infrastructure.cdn.${at}`)}],mr=[],hr=[],br=["GET","HEAD","OPTIONS"],Wi=xt,yr;if(se.failoverOrigin){Gt(br,`the default cache behavior of infrastructure.cdn.${at}`);let mn=`${xt}-failover`,Xi=typeof se.failoverOrigin==="string"?{domain:se.failoverOrigin}:se.failoverOrigin;if(!Xi.domain)throw Error(`infrastructure.cdn.${at}.failoverOrigin.domain is required`);if(Xi.domain===se.origin)throw Error(`infrastructure.cdn.${at}: failoverOrigin must differ from origin (both are ${se.origin})`);Bt.push({Id:mn,DomainName:Xi.domain,OriginPath:Xi.originPath||"",...Dd(Xi.domain)?{S3OriginConfig:{OriginAccessIdentity:""}}:{CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"}},OriginShield:{Enabled:!1},...we(Xi,`infrastructure.cdn.${at}.failoverOrigin`)}),yr=Qr({primaryOriginId:xt,secondaryOriginId:mn,statusCodes:se.failoverStatusCodes}),Wi=yr.Items[0].Id}else if(se.failoverStatusCodes)throw Error(`infrastructure.cdn.${at}: failoverStatusCodes needs failoverOrigin to fail over to`);if(se.routeCompute)this.appendComputeAppOrigin(Bt,mr,hr,l,f,this.resolveComputeCachePathPatterns(se.computeRoutes));let Tr=ct&&kt?{AcmCertificateArn:Se&&!N?{Ref:Se}:ct,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},dn=[...hr];if(Se&&!N&&kt)dn.push(Se);let Ln={Type:"AWS::CloudFront::Distribution",...dn.length>0?{DependsOn:dn}:{},Properties:{DistributionConfig:{Enabled:!0,Comment:`${l} ${f} ${at} CDN`,DefaultRootObject:"index.html",Origins:Bt,...yr?{OriginGroups:yr}:{},DefaultCacheBehavior:{TargetOriginId:Wi,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:br,CachedMethods:["GET","HEAD","OPTIONS"],Compress:se.compress!==!1,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},...mr.length>0?{CacheBehaviors:mr}:{},...kt&&ct?{Aliases:[kt]}:{},ViewerCertificate:Tr,PriceClass:"PriceClass_100",HttpVersion:se.http3?"http2and3":"http2"}}};if(qt(Ln.Properties.DistributionConfig,`infrastructure.cdn.${at}`),this.builder.addResource(Nt,Ln),it&&kt&&ct){let mn=kt.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${mn}CdnARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[Nt,...Se&&!N?[Se]:[]],Properties:{HostedZoneId:it,Name:kt,Type:"A",AliasTarget:{HostedZoneId:"Z2FDTNDATAQYW2",DNSName:{"Fn::GetAtt":[Nt,"DomainName"]}}}})}}if(this.mergedConfig.infrastructure?.queues)for(let[at,se]of Object.entries(this.mergedConfig.infrastructure.queues)){if(!this.shouldDeploy(se))continue;let{queue:kt,logicalId:N}=F.createQueue({slug:l,environment:f,name:`${l}-${f}-${at}`,fifo:se.fifo,visibilityTimeout:se.visibilityTimeout,messageRetentionPeriod:se.messageRetentionPeriod,delaySeconds:se.delaySeconds,maxMessageSize:se.maxMessageSize,receiveMessageWaitTime:se.receiveMessageWaitTime,contentBasedDeduplication:se.contentBasedDeduplication,encrypted:se.encrypted,kmsKeyId:se.kmsKeyId});this.builder.addResource(N,kt);let ct;if(se.deadLetterQueue){let{deadLetterQueue:Nt,updatedSourceQueue:xt,deadLetterLogicalId:Bt}=F.createDeadLetterQueue(N,{slug:l,environment:f,maxReceiveCount:se.maxReceiveCount});ct=Bt,this.builder.addResource(Bt,Nt);let hr=this.builder.getResources()[N];if(hr?.Properties)hr.Properties.RedrivePolicy=xt.Properties?.RedrivePolicy}if(se.trigger){let Nt=se.trigger,xt=`${l}${f}${Nt.functionName}`.replace(/[^a-zA-Z0-9]/g,""),Bt={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:{"Fn::GetAtt":[N,"Arn"]},FunctionName:{Ref:xt},BatchSize:Nt.batchSize||10,MaximumBatchingWindowInSeconds:Nt.batchWindow||0,Enabled:!0,...Nt.reportBatchItemFailures!==!1&&{FunctionResponseTypes:["ReportBatchItemFailures"]},...Nt.maxConcurrency&&{ScalingConfig:{MaximumConcurrency:Nt.maxConcurrency}},...Nt.filterPattern&&{FilterCriteria:{Filters:[{Pattern:JSON.stringify(Nt.filterPattern)}]}}},DependsOn:[N,xt]};this.builder.addResource(`${N}Trigger`,Bt)}if(se.alarms?.enabled){let Nt=se.alarms,xt=Nt.notificationTopicArn;if(!xt&&Nt.notificationEmails?.length){let hr=`${N}AlarmTopic`;this.builder.addResource(hr,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${l}-${f}-${at}-alarms`,DisplayName:`${at} Queue Alarms`}}),Nt.notificationEmails.forEach((br,Wi)=>{this.builder.addResource(`${hr}Sub${Wi}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:hr},Protocol:"email",Endpoint:br}})}),xt={Ref:hr}}let Bt=Nt.queueDepthThreshold||1000;this.builder.addResource(`${N}DepthAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${f}-${at}-queue-depth`,AlarmDescription:`Queue ${at} depth exceeds ${Bt} messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:Bt,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[N,"QueueName"]}}],...xt&&{AlarmActions:[xt],OKActions:[xt]}}});let mr=Nt.messageAgeThreshold||3600;if(this.builder.addResource(`${N}AgeAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${f}-${at}-message-age`,AlarmDescription:`Queue ${at} oldest message exceeds ${mr} seconds`,MetricName:"ApproximateAgeOfOldestMessage",Namespace:"AWS/SQS",Statistic:"Maximum",Period:300,EvaluationPeriods:2,Threshold:mr,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[N,"QueueName"]}}],...xt&&{AlarmActions:[xt],OKActions:[xt]}}}),ct&&Nt.dlqAlarm!==!1)this.builder.addResource(`${ct}Alarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${f}-${at}-dlq-messages`,AlarmDescription:`Dead letter queue for ${at} has messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Sum",Period:300,EvaluationPeriods:1,Threshold:0,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[ct,"QueueName"]}}],...xt&&{AlarmActions:[xt]}}})}if(se.subscribe){let Nt=se.subscribe,xt=Nt.topicArn;if(!xt&&Nt.topicName)xt={Ref:Nt.topicName};if(xt){this.builder.addResource(`${N}SnsPolicy`,{Type:"AWS::SQS::QueuePolicy",Properties:{Queues:[{Ref:N}],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"sns.amazonaws.com"},Action:"sqs:SendMessage",Resource:{"Fn::GetAtt":[N,"Arn"]},Condition:{ArnEquals:{"aws:SourceArn":xt}}}]}}});let Bt={TopicArn:xt,Protocol:"sqs",Endpoint:{"Fn::GetAtt":[N,"Arn"]},RawMessageDelivery:Nt.rawMessageDelivery||!1};if(Nt.filterPolicy)Bt.FilterPolicy=Nt.filterPolicy,Bt.FilterPolicyScope=Nt.filterPolicyScope||"MessageAttributes";this.builder.addResource(`${N}SnsSub`,{Type:"AWS::SNS::Subscription",Properties:Bt,DependsOn:`${N}SnsPolicy`})}}}if(this.mergedConfig.infrastructure?.realtime?.enabled)if((this.mergedConfig.infrastructure.realtime.mode||"serverless")==="server")this.generateRealtimeServerResources(l,f);else this.generateRealtimeResources(l,f);let Pt=this.mergedConfig.infrastructure?.redirects;if(Pt){let at=Pt.target||this.mergedConfig.infrastructure?.dns?.domain||"",se=Pt.protocol||"https";if(Pt.domains?.length&&at)for(let kt of Pt.domains){let{bucket:N,bucketPolicy:ct,logicalId:Nt,policyLogicalId:xt}=ht.createDomainRedirectBucket({slug:l,environment:f,sourceDomain:kt,targetDomain:at,protocol:se});this.builder.addResource(Nt,N),this.builder.addResource(xt,ct)}if(Pt.paths&&Object.keys(Pt.paths).length>0){let kt=ht.fromMapping(Pt.paths,{statusCode:Pt.statusCode||301}),{function:N,logicalId:ct}=ht.createPathRedirectFunction({slug:l,environment:f,rules:kt});this.builder.addResource(ct,N)}}if(this.mergedConfig.infrastructure?.monitoring?.alarms)for(let[at,se]of Object.entries(this.mergedConfig.infrastructure.monitoring.alarms)){let{alarm:kt,logicalId:N}=uo.createAlarm({slug:l,environment:f,alarmName:`${l}-${f}-${at}`,metricName:se.metricName||"Errors",namespace:se.namespace||"AWS/Lambda",threshold:se.threshold||1,comparisonOperator:se.comparisonOperator||"GreaterThanThreshold"});this.builder.addResource(N,kt)}let ot=this.mergedConfig.infrastructure?.cache;if(ot){let at=ot.type||"redis";if(at==="redis"){this.generateNetworkInfrastructure(l,f);let se=ot.redis||{},{replicationGroup:kt,subnetGroup:N,logicalId:ct,subnetGroupId:Nt}=lo.createRedis({slug:l,environment:f,nodeType:se.nodeType||ot.nodeType||"cache.t3.micro",engineVersion:se.engineVersion||"7.1",port:se.port||6379,numCacheClusters:se.numCacheNodes||2,automaticFailover:se.automaticFailoverEnabled!==!1,atRestEncryption:!0,transitEncryption:!0,snapshotRetentionDays:se.snapshotRetentionLimit||7,snapshotWindow:se.snapshotWindow,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(ct,kt),N&&Nt)this.builder.addResource(Nt,N);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[ct,"PrimaryEndPoint.Address"]},Description:"Redis primary endpoint address"}),this.builder.addOutput("CachePort",{Value:{"Fn::GetAtt":[ct,"PrimaryEndPoint.Port"]},Description:"Redis primary endpoint port"})}else if(at==="memcached"){this.generateNetworkInfrastructure(l,f);let se=ot.elasticache||{},{cluster:kt,subnetGroup:N,logicalId:ct,subnetGroupId:Nt}=lo.createMemcached({slug:l,environment:f,nodeType:se.nodeType||ot.nodeType||"cache.t3.micro",engineVersion:se.engineVersion||"1.6.22",numCacheNodes:se.numCacheNodes||2,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(ct,kt),N&&Nt)this.builder.addResource(Nt,N);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[ct,"ConfigurationEndpoint.Address"]},Description:"Memcached configuration endpoint address"})}}let rr=this.mergedConfig.infrastructure?.email;if(rr){let at=rr.domain||this.mergedConfig.infrastructure?.dns?.domain;if(at){let{emailIdentity:se,logicalId:kt}=m.verifyDomain({domain:at,slug:l,environment:f,enableDkim:rr.enableDkim!==!1,dkimKeyLength:rr.dkimKeyLength||"RSA_2048_BIT"});if(this.builder.addResource(kt,se),rr.configurationSet!==!1){let{configurationSet:Nt,logicalId:xt}=m.createConfigurationSet({slug:l,environment:f});this.builder.addResource(xt,Nt)}let N=rr.hostedZoneId||this.mergedConfig.infrastructure?.dns?.hostedZoneId;if(N){if(rr.enableDkim!==!1)for(let hr=1;hr<=3;hr++){let br=`DkimRecord${hr}${at.replace(/\./g,"")}`;this.builder.addResource(br,{Type:"AWS::Route53::RecordSet",DependsOn:[kt],Properties:{HostedZoneId:N,Name:{"Fn::GetAtt":[kt,`DkimDNSTokenName${hr}`]},Type:"CNAME",TTL:1800,ResourceRecords:[{"Fn::GetAtt":[kt,`DkimDNSTokenValue${hr}`]}]}})}let{record:Nt,logicalId:xt}=m.createSpfRecord(at,N);this.builder.addResource(xt,Nt);let{record:Bt,logicalId:mr}=m.createDmarcRecord(at,N,{policy:"none",reportingEmail:rr.dmarcReportingEmail||`dmarc-reports@${at}`});this.builder.addResource(mr,Bt)}this.builder.addOutput("EmailDomain",{Value:at,Description:"SES verified email domain"});let ct=rr.server;if(ct?.enabled&&N){let Nt=this.mergedConfig.environments[f]?.region||this.mergedConfig.project.region||"us-east-1",xt=`${l}-${f}-email`,{role:Bt,policy:mr,roleLogicalId:hr,policyLogicalId:br}=m.createEmailLambdaRole({slug:l,environment:f,s3BucketArn:`arn:aws:s3:::${xt}`,sesIdentityArn:`arn:aws:ses:${Nt}:*:identity/${at}`});this.builder.addResource(hr,Bt),this.builder.addResource(br,mr);let{function:Wi,permission:yr,logicalId:Tr,permissionLogicalId:dn}=m.createInboundEmailLambda({slug:l,environment:f,roleArn:{"Fn::GetAtt":[hr,"Arn"]},s3BucketName:xt,organizedPrefix:"mailboxes/"});this.builder.addResource(Tr,Wi),this.builder.addResource(dn,yr);let Ln=m.createInboundEmailSetup({slug:l,environment:f,domain:at,s3BucketName:xt,s3KeyPrefix:"inbox/",region:Nt,hostedZoneId:N,lambdaFunctionArn:{"Fn::GetAtt":[Tr,"Arn"]}});for(let[Xi,Fn]of Object.entries(Ln.resources)){if(Fn.Type==="AWS::SES::ReceiptRule")Fn.DependsOn=[dn,Tr];this.builder.addResource(Xi,Fn)}this.builder.addOutput("InboundEmailLambda",{Value:{Ref:Tr},Description:"Inbound email processing Lambda function"}),this.builder.addOutput("EmailBucket",{Value:xt,Description:"S3 bucket for email storage"});let mn=this.serverEipLogicalIds.get("app");if(mn&&N){let Fn=`${ct?.subdomain||"mail"}.${at}`,_n=Fn.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${_n}ARecord`,{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:N,Name:Fn,Type:"A",TTL:"300",ResourceRecords:[{Ref:mn}]}})}this.builder.addOutput("MailHost",{Value:`mail.${at}`,Description:"Mail server hostname for SMTP/IMAP clients"})}}}let pr=this.mergedConfig.infrastructure?.search;if(pr){let at=pr.vpc?{subnetIds:[{Ref:"PublicSubnet1"}],securityGroupIds:[]}:void 0;if(at)this.generateNetworkInfrastructure(l,f);let{domain:se,logicalId:kt}=jt.createDomain({slug:l,environment:f,engineVersion:pr.engineVersion||"OpenSearch_2.11",instanceType:pr.instanceType||"t3.small.search",instanceCount:pr.instanceCount||1,volumeSize:pr.volumeSize||10,volumeType:pr.volumeType||"gp3",dedicatedMaster:pr.dedicatedMaster||!1,dedicatedMasterType:pr.dedicatedMasterType,dedicatedMasterCount:pr.dedicatedMasterCount||3,multiAz:pr.multiAz||!1,encryption:pr.encryption||{atRest:!0,nodeToNode:!0},advancedSecurity:pr.advancedSecurity,autoTune:pr.autoTune!==!1,vpc:at});this.builder.addResource(kt,se),this.builder.addOutput("SearchDomainEndpoint",{Value:{"Fn::GetAtt":[kt,"DomainEndpoint"]},Description:"OpenSearch domain endpoint"}),this.builder.addOutput("SearchDomainArn",{Value:{"Fn::GetAtt":[kt,"Arn"]},Description:"OpenSearch domain ARN"})}let gr=this.mergedConfig.infrastructure?.fileSystem;if(gr&&Object.keys(gr).length>0){this.generateNetworkInfrastructure(l,f);for(let[at,se]of Object.entries(gr)){let{fileSystem:kt,logicalId:N}=Ve.createFileSystem({slug:`${l}-${at}`,environment:f,encrypted:se.encrypted!==!1,performanceMode:se.performanceMode||"generalPurpose",throughputMode:se.throughputMode||"bursting",enableBackup:!0});this.builder.addResource(N,kt);let{securityGroup:ct,logicalId:Nt}=Ve.createEfsSecurityGroup({slug:`${l}-${at}`,environment:f,vpcId:{Ref:"VPC"},sourceCidrBlocks:["10.0.0.0/16"]});this.builder.addResource(Nt,ct);let{mountTargets:xt,logicalIds:Bt}=Ve.createMultiAzMountTargets(N,{slug:`${l}-${at}`,environment:f,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],securityGroupId:{Ref:Nt}});for(let mr=0;mr<xt.length;mr++)this.builder.addResource(Bt[mr],xt[mr]);this.builder.addOutput(`${at}FileSystemId`,{Value:{Ref:N},Description:`EFS file system ID for ${at}`})}}let Et=this.mergedConfig.infrastructure?.ai;if(Et){let at=Et.service||"ecs",se=Et.models||["*"],kt=Et.allowStreaming!==!1,N;if(at==="ecs")N=Re.enableBedrockForEcs({slug:l,environment:f,models:se,allowStreaming:kt});else if(at==="ec2")N=Re.enableBedrockForEc2({slug:l,environment:f,models:se,allowStreaming:kt});else if(at==="lambda")N=Re.enableBedrockForLambda({slug:l,environment:f,models:se,allowStreaming:kt});else N=Re.createBedrockRole(at,{slug:l,environment:f,models:se,allowStreaming:kt});if(this.builder.addResource(N.logicalId,N.role),Et.allowAsync){let{policy:ct,logicalId:Nt}=Re.createBedrockPolicy({slug:l,environment:f,models:se,allowStreaming:kt,allowAsync:!0});this.builder.addResource(Nt,ct)}this.builder.addOutput("BedrockRoleArn",{Value:{"Fn::GetAtt":[N.logicalId,"Arn"]},Description:"IAM role ARN with Bedrock permissions"})}}generateRealtimeResources(l,f){let C=this.mergedConfig.infrastructure?.realtime;if(!C)return;let b=C.name||`${l}-${f}-realtime`,T=C.scaling||{},it=C.storage||{type:"dynamodb"},Ce=T.handlerMemory||256,Se=T.handlerTimeout||30,ke=`${l}${f}RealtimeConnections`.replace(/[^a-zA-Z0-9]/g,""),Pt=`${l}${f}RealtimeChannels`.replace(/[^a-zA-Z0-9]/g,"");if(it.type==="dynamodb"){let Bt=it.dynamodb||{},mr=Bt.billingMode||"PAY_PER_REQUEST";this.builder.addResource(ke,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${l}-${f}-realtime-connections`,BillingMode:mr,AttributeDefinitions:[{AttributeName:"connectionId",AttributeType:"S"},{AttributeName:"userId",AttributeType:"S"}],KeySchema:[{AttributeName:"connectionId",KeyType:"HASH"}],GlobalSecondaryIndexes:[{IndexName:"userId-index",KeySchema:[{AttributeName:"userId",KeyType:"HASH"}],Projection:{ProjectionType:"ALL"},...mr==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Bt.readCapacity||5,WriteCapacityUnits:Bt.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...mr==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Bt.readCapacity||5,WriteCapacityUnits:Bt.writeCapacity||5}},...Bt.pointInTimeRecovery&&{PointInTimeRecoverySpecification:{PointInTimeRecoveryEnabled:!0}},Tags:[{Key:"Name",Value:`${l}-${f}-realtime-connections`},{Key:"Environment",Value:f}]}}),this.builder.addResource(Pt,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${l}-${f}-realtime-channels`,BillingMode:mr,AttributeDefinitions:[{AttributeName:"channel",AttributeType:"S"},{AttributeName:"connectionId",AttributeType:"S"}],KeySchema:[{AttributeName:"channel",KeyType:"HASH"},{AttributeName:"connectionId",KeyType:"RANGE"}],GlobalSecondaryIndexes:[{IndexName:"connectionId-index",KeySchema:[{AttributeName:"connectionId",KeyType:"HASH"}],Projection:{ProjectionType:"ALL"},...mr==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Bt.readCapacity||5,WriteCapacityUnits:Bt.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...mr==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Bt.readCapacity||5,WriteCapacityUnits:Bt.writeCapacity||5}},Tags:[{Key:"Name",Value:`${l}-${f}-realtime-channels`},{Key:"Environment",Value:f}]}})}let ot=`${l}${f}RealtimeRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(ot,{Type:"AWS::IAM::Role",Properties:{RoleName:`${l}-${f}-realtime-handler-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:"RealtimeHandlerPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan","dynamodb:UpdateItem"],Resource:[{"Fn::GetAtt":[ke,"Arn"]},{"Fn::Sub":`\${${ke}.Arn}/index/*`},{"Fn::GetAtt":[Pt,"Arn"]},{"Fn::Sub":`\${${Pt}.Arn}/index/*`}]},{Effect:"Allow",Action:"execute-api:ManageConnections",Resource:{"Fn::Sub":"arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:*/*"}}]}}]}});let rr=`${l}${f}RealtimeConnect`.replace(/[^a-zA-Z0-9]/g,""),pr=`${l}${f}RealtimeDisconnect`.replace(/[^a-zA-Z0-9]/g,""),gr=`${l}${f}RealtimeMessage`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(rr,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${l}-${f}-realtime-connect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[ot,"Arn"]},MemorySize:Ce,Timeout:Se,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:ke},CHANNELS_TABLE:{Ref:Pt},ENVIRONMENT:f}},Code:{ZipFile:this.generateConnectHandlerCode()}},DependsOn:[ot,ke]}),this.builder.addResource(pr,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${l}-${f}-realtime-disconnect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[ot,"Arn"]},MemorySize:Ce,Timeout:Se,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:ke},CHANNELS_TABLE:{Ref:Pt},ENVIRONMENT:f}},Code:{ZipFile:this.generateDisconnectHandlerCode()}},DependsOn:[ot,ke,Pt]}),this.builder.addResource(gr,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${l}-${f}-realtime-message`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[ot,"Arn"]},MemorySize:Ce,Timeout:Se,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:ke},CHANNELS_TABLE:{Ref:Pt},ENVIRONMENT:f}},Code:{ZipFile:this.generateMessageHandlerCode()}},DependsOn:[ot,ke,Pt]});let Et=`${l}${f}RealtimeApi`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Et,{Type:"AWS::ApiGatewayV2::Api",Properties:{Name:b,ProtocolType:"WEBSOCKET",RouteSelectionExpression:"$request.body.action",Tags:{Name:b,Environment:f}}});let at=`${rr}Permission`,se=`${pr}Permission`,kt=`${gr}Permission`;this.builder.addResource(at,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:rr},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${Et}}/*/$connect`}}}),this.builder.addResource(se,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:pr},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${Et}}/*/$disconnect`}}}),this.builder.addResource(kt,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:gr},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${Et}}/*/$default`}}});let N=`${Et}ConnectInteg`,ct=`${Et}DisconnectInteg`,Nt=`${Et}MessageInteg`;this.builder.addResource(N,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:Et},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${rr}.Arn}/invocations`}}}),this.builder.addResource(ct,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:Et},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${pr}.Arn}/invocations`}}}),this.builder.addResource(Nt,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:Et},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${gr}.Arn}/invocations`}}}),this.builder.addResource(`${Et}ConnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:Et},RouteKey:"$connect",AuthorizationType:"NONE",Target:{"Fn::Sub":`integrations/\${${N}}`}}}),this.builder.addResource(`${Et}DisconnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:Et},RouteKey:"$disconnect",Target:{"Fn::Sub":`integrations/\${${ct}}`}}}),this.builder.addResource(`${Et}DefaultRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:Et},RouteKey:"$default",Target:{"Fn::Sub":`integrations/\${${Nt}}`}}});let xt=`${Et}Stage`;if(this.builder.addResource(xt,{Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:{Ref:Et},StageName:f,AutoDeploy:!0,DefaultRouteSettings:{ThrottlingBurstLimit:T.messagesPerSecond||1000,ThrottlingRateLimit:T.messagesPerSecond||1000}}}),C.monitoring?.enabled){let Bt=C.monitoring,mr=Bt.notificationTopicArn;if(!mr&&Bt.notificationEmails?.length){let hr=`${Et}AlarmTopic`;this.builder.addResource(hr,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${l}-${f}-realtime-alarms`,DisplayName:"Realtime WebSocket Alarms"}}),Bt.notificationEmails.forEach((br,Wi)=>{this.builder.addResource(`${hr}Sub${Wi}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:hr},Protocol:"email",Endpoint:br}})}),mr={Ref:hr}}if(Bt.connectionThreshold)this.builder.addResource(`${Et}ConnectionAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${f}-realtime-connections`,AlarmDescription:`WebSocket connections exceed ${Bt.connectionThreshold}`,MetricName:"ConnectCount",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:300,EvaluationPeriods:2,Threshold:Bt.connectionThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:Et}}],...mr&&{AlarmActions:[mr]}}});if(Bt.errorThreshold)this.builder.addResource(`${Et}ErrorAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${f}-realtime-errors`,AlarmDescription:`WebSocket errors exceed ${Bt.errorThreshold}/min`,MetricName:"ExecutionError",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:60,EvaluationPeriods:3,Threshold:Bt.errorThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:Et}}],...mr&&{AlarmActions:[mr]}}})}this.builder.addOutput(`${Et}Endpoint`,{Description:"WebSocket API endpoint URL",Value:{"Fn::Sub":`wss://\${${Et}}.execute-api.\${AWS::Region}.amazonaws.com/${f}`},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-endpoint"}}}),this.builder.addOutput(`${Et}Id`,{Description:"WebSocket API ID",Value:{Ref:Et},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-api-id"}}})}generateConnectHandlerCode(){return`
15
15
  const { DynamoDBClient } = require('@aws-sdk/client-dynamodb');
16
16
  const { DynamoDBDocumentClient, PutCommand } = require('@aws-sdk/lib-dynamodb');
17
17
 
@@ -170,56 +170,56 @@ catch (error) {
170
170
  return { statusCode: 500, body: JSON.stringify({ error: 'Internal error' }) };
171
171
  }
172
172
  };
173
- `.trim()}generateRealtimeServerResources(l,S){let P=this.mergedConfig.infrastructure?.realtime;if(!P)return;let v=P.server||{},E=v.port||6001,ot=v.instances||1,Ie=`${l}${S}RealtimeSG`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Ie,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`Security group for ${l} realtime WebSocket server`,GroupName:`${l}-${S}-realtime-sg`,VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:E,ToPort:E,CidrIp:"0.0.0.0/0",Description:"WebSocket connections"},{IpProtocol:"tcp",FromPort:443,ToPort:443,CidrIp:"0.0.0.0/0",Description:"HTTPS/WSS connections"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0",Description:"Allow all outbound"}],Tags:[{Key:"Name",Value:`${l}-${S}-realtime-sg`},{Key:"Environment",Value:S}]}});let Ne=`${l}${S}RealtimeTaskDef`.replace(/[^a-zA-Z0-9]/g,""),nt=`${l}${S}RealtimeTaskRole`.replace(/[^a-zA-Z0-9]/g,""),Pt=`${l}${S}RealtimeExecRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Pt,{Type:"AWS::IAM::Role",Properties:{RoleName:`${l}-${S}-realtime-exec-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"]}}),this.builder.addResource(nt,{Type:"AWS::IAM::Role",Properties:{RoleName:`${l}-${S}-realtime-task-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"RealtimeTaskPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogStream","logs:PutLogEvents"],Resource:"*"},...v.redis?.enabled?[{Effect:"Allow",Action:["elasticache:DescribeCacheClusters","elasticache:DescribeReplicationGroups"],Resource:"*"}]:[]]}}]}});let st=[{Name:"BROADCAST_HOST",Value:v.host||"0.0.0.0"},{Name:"BROADCAST_PORT",Value:String(E)},{Name:"NODE_ENV",Value:S==="production"?"production":"development"}];if(v.redis?.enabled){if(v.redis.useElastiCache)st.push({Name:"REDIS_HOST",Value:{"Fn::GetAtt":["CacheCluster","RedisEndpoint.Address"]}}),st.push({Name:"REDIS_PORT",Value:{"Fn::GetAtt":["CacheCluster","RedisEndpoint.Port"]}});else st.push({Name:"REDIS_HOST",Value:v.redis.host||"localhost"}),st.push({Name:"REDIS_PORT",Value:String(v.redis.port||6379)});if(v.redis.keyPrefix)st.push({Name:"REDIS_KEY_PREFIX",Value:v.redis.keyPrefix})}this.builder.addResource(Ne,{Type:"AWS::ECS::TaskDefinition",Properties:{Family:`${l}-${S}-realtime`,NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:"512",Memory:"1024",ExecutionRoleArn:{"Fn::GetAtt":[Pt,"Arn"]},TaskRoleArn:{"Fn::GetAtt":[nt,"Arn"]},ContainerDefinitions:[{Name:"realtime",Image:{"Fn::Sub":`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${l}-realtime:latest`},Essential:!0,PortMappings:[{ContainerPort:E,Protocol:"tcp"}],Environment:st,LogConfiguration:{LogDriver:"awslogs",Options:{"awslogs-group":`/ecs/${l}-${S}-realtime`,"awslogs-region":{Ref:"AWS::Region"},"awslogs-stream-prefix":"realtime"}},HealthCheck:{Command:["CMD-SHELL",`curl -f http://localhost:${E}${v.healthCheckPath||"/health"} || exit 1`],Interval:30,Timeout:5,Retries:3,StartPeriod:60}}],Tags:[{Key:"Name",Value:`${l}-${S}-realtime`},{Key:"Environment",Value:S}]},DependsOn:[Pt,nt]});let ur=`${l}${S}RealtimeLogs`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(ur,{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/ecs/${l}-${S}-realtime`,RetentionInDays:30}});let pr=`${l}${S}RealtimeService`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(pr,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${l}-${S}-realtime`,Cluster:{Ref:"ECSCluster"},TaskDefinition:{Ref:Ne},DesiredCount:ot,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:Ie}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},HealthCheckGracePeriodSeconds:60,Tags:[{Key:"Name",Value:`${l}-${S}-realtime`},{Key:"Environment",Value:S}]},DependsOn:[Ne,Ie,ur]}),v.autoScaling){let gr=v.autoScaling,Dt=`${l}${S}RealtimeScalableTarget`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(Dt,{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{MaxCapacity:gr.max||10,MinCapacity:gr.min||1,ResourceId:{"Fn::Sub":`service/\${ECSCluster}/${l}-${S}-realtime`},RoleARN:{"Fn::Sub":"arn:aws:iam::${AWS::AccountId}:role/aws-service-role/ecs.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_ECSService"},ScalableDimension:"ecs:service:DesiredCount",ServiceNamespace:"ecs"},DependsOn:pr}),gr.targetCPU)this.builder.addResource(`${l}${S}RealtimeCPUPolicy`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${l}-${S}-realtime-cpu-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:Dt},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},TargetValue:gr.targetCPU,ScaleInCooldown:300,ScaleOutCooldown:60}}})}if(P.monitoring?.enabled){let gr=P.monitoring,Dt=gr.notificationTopicArn;if(!Dt&&gr.notificationEmails?.length){let St=`${l}${S}RealtimeAlarmTopic`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(St,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${l}-${S}-realtime-alarms`,DisplayName:"Realtime Server Alarms"}}),gr.notificationEmails.forEach((Se,Bt)=>{this.builder.addResource(`${St}Sub${Bt}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:St},Protocol:"email",Endpoint:Se}})}),Dt={Ref:St}}this.builder.addResource(`${l}${S}RealtimeCPUAlarm`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-realtime-high-cpu`,AlarmDescription:"Realtime server CPU utilization is high",MetricName:"CPUUtilization",Namespace:"AWS/ECS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:80,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ClusterName",Value:{Ref:"ECSCluster"}},{Name:"ServiceName",Value:`${l}-${S}-realtime`}],...Dt&&{AlarmActions:[Dt]}},DependsOn:pr}),this.builder.addResource(`${l}${S}RealtimeMemoryAlarm`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-realtime-high-memory`,AlarmDescription:"Realtime server memory utilization is high",MetricName:"MemoryUtilization",Namespace:"AWS/ECS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:80,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ClusterName",Value:{Ref:"ECSCluster"}},{Name:"ServiceName",Value:`${l}-${S}-realtime`}],...Dt&&{AlarmActions:[Dt]}},DependsOn:pr})}this.builder.addOutput(`${l}${S}RealtimeEndpoint`.replace(/[^a-zA-Z0-9]/g,""),{Description:"Realtime WebSocket server endpoint",Value:{"Fn::Sub":`wss://${l}-${S}-realtime.\${AWS::Region}.elb.amazonaws.com:${E}`},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-endpoint"}}})}generateBroadcastConfig(){let l=this.mergedConfig.infrastructure?.realtime;if(!l||l.mode!=="server")return"";let S=l.server||{};return`import type { BroadcastConfig } from 'ts-broadcasting'
173
+ `.trim()}generateRealtimeServerResources(l,f){let C=this.mergedConfig.infrastructure?.realtime;if(!C)return;let b=C.server||{},T=b.port||6001,it=b.instances||1,Ce=`${l}${f}RealtimeSG`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Ce,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`Security group for ${l} realtime WebSocket server`,GroupName:`${l}-${f}-realtime-sg`,VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:T,ToPort:T,CidrIp:"0.0.0.0/0",Description:"WebSocket connections"},{IpProtocol:"tcp",FromPort:443,ToPort:443,CidrIp:"0.0.0.0/0",Description:"HTTPS/WSS connections"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0",Description:"Allow all outbound"}],Tags:[{Key:"Name",Value:`${l}-${f}-realtime-sg`},{Key:"Environment",Value:f}]}});let Se=`${l}${f}RealtimeTaskDef`.replace(/[^a-zA-Z0-9]/g,""),ke=`${l}${f}RealtimeTaskRole`.replace(/[^a-zA-Z0-9]/g,""),Pt=`${l}${f}RealtimeExecRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Pt,{Type:"AWS::IAM::Role",Properties:{RoleName:`${l}-${f}-realtime-exec-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"]}}),this.builder.addResource(ke,{Type:"AWS::IAM::Role",Properties:{RoleName:`${l}-${f}-realtime-task-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"RealtimeTaskPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogStream","logs:PutLogEvents"],Resource:"*"},...b.redis?.enabled?[{Effect:"Allow",Action:["elasticache:DescribeCacheClusters","elasticache:DescribeReplicationGroups"],Resource:"*"}]:[]]}}]}});let ot=[{Name:"BROADCAST_HOST",Value:b.host||"0.0.0.0"},{Name:"BROADCAST_PORT",Value:String(T)},{Name:"NODE_ENV",Value:f==="production"?"production":"development"}];if(b.redis?.enabled){if(b.redis.useElastiCache)ot.push({Name:"REDIS_HOST",Value:{"Fn::GetAtt":["CacheCluster","RedisEndpoint.Address"]}}),ot.push({Name:"REDIS_PORT",Value:{"Fn::GetAtt":["CacheCluster","RedisEndpoint.Port"]}});else ot.push({Name:"REDIS_HOST",Value:b.redis.host||"localhost"}),ot.push({Name:"REDIS_PORT",Value:String(b.redis.port||6379)});if(b.redis.keyPrefix)ot.push({Name:"REDIS_KEY_PREFIX",Value:b.redis.keyPrefix})}this.builder.addResource(Se,{Type:"AWS::ECS::TaskDefinition",Properties:{Family:`${l}-${f}-realtime`,NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:"512",Memory:"1024",ExecutionRoleArn:{"Fn::GetAtt":[Pt,"Arn"]},TaskRoleArn:{"Fn::GetAtt":[ke,"Arn"]},ContainerDefinitions:[{Name:"realtime",Image:{"Fn::Sub":`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${l}-realtime:latest`},Essential:!0,PortMappings:[{ContainerPort:T,Protocol:"tcp"}],Environment:ot,LogConfiguration:{LogDriver:"awslogs",Options:{"awslogs-group":`/ecs/${l}-${f}-realtime`,"awslogs-region":{Ref:"AWS::Region"},"awslogs-stream-prefix":"realtime"}},HealthCheck:{Command:["CMD-SHELL",`curl -f http://localhost:${T}${b.healthCheckPath||"/health"} || exit 1`],Interval:30,Timeout:5,Retries:3,StartPeriod:60}}],Tags:[{Key:"Name",Value:`${l}-${f}-realtime`},{Key:"Environment",Value:f}]},DependsOn:[Pt,ke]});let rr=`${l}${f}RealtimeLogs`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(rr,{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/ecs/${l}-${f}-realtime`,RetentionInDays:30}});let pr=`${l}${f}RealtimeService`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(pr,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${l}-${f}-realtime`,Cluster:{Ref:"ECSCluster"},TaskDefinition:{Ref:Se},DesiredCount:it,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:Ce}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},HealthCheckGracePeriodSeconds:60,Tags:[{Key:"Name",Value:`${l}-${f}-realtime`},{Key:"Environment",Value:f}]},DependsOn:[Se,Ce,rr]}),b.autoScaling){let gr=b.autoScaling,Et=`${l}${f}RealtimeScalableTarget`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(Et,{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{MaxCapacity:gr.max||10,MinCapacity:gr.min||1,ResourceId:{"Fn::Sub":`service/\${ECSCluster}/${l}-${f}-realtime`},RoleARN:{"Fn::Sub":"arn:aws:iam::${AWS::AccountId}:role/aws-service-role/ecs.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_ECSService"},ScalableDimension:"ecs:service:DesiredCount",ServiceNamespace:"ecs"},DependsOn:pr}),gr.targetCPU)this.builder.addResource(`${l}${f}RealtimeCPUPolicy`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${l}-${f}-realtime-cpu-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:Et},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},TargetValue:gr.targetCPU,ScaleInCooldown:300,ScaleOutCooldown:60}}})}if(C.monitoring?.enabled){let gr=C.monitoring,Et=gr.notificationTopicArn;if(!Et&&gr.notificationEmails?.length){let at=`${l}${f}RealtimeAlarmTopic`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(at,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${l}-${f}-realtime-alarms`,DisplayName:"Realtime Server Alarms"}}),gr.notificationEmails.forEach((se,kt)=>{this.builder.addResource(`${at}Sub${kt}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:at},Protocol:"email",Endpoint:se}})}),Et={Ref:at}}this.builder.addResource(`${l}${f}RealtimeCPUAlarm`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${f}-realtime-high-cpu`,AlarmDescription:"Realtime server CPU utilization is high",MetricName:"CPUUtilization",Namespace:"AWS/ECS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:80,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ClusterName",Value:{Ref:"ECSCluster"}},{Name:"ServiceName",Value:`${l}-${f}-realtime`}],...Et&&{AlarmActions:[Et]}},DependsOn:pr}),this.builder.addResource(`${l}${f}RealtimeMemoryAlarm`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${f}-realtime-high-memory`,AlarmDescription:"Realtime server memory utilization is high",MetricName:"MemoryUtilization",Namespace:"AWS/ECS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:80,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ClusterName",Value:{Ref:"ECSCluster"}},{Name:"ServiceName",Value:`${l}-${f}-realtime`}],...Et&&{AlarmActions:[Et]}},DependsOn:pr})}this.builder.addOutput(`${l}${f}RealtimeEndpoint`.replace(/[^a-zA-Z0-9]/g,""),{Description:"Realtime WebSocket server endpoint",Value:{"Fn::Sub":`wss://${l}-${f}-realtime.\${AWS::Region}.elb.amazonaws.com:${T}`},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-endpoint"}}})}generateBroadcastConfig(){let l=this.mergedConfig.infrastructure?.realtime;if(!l||l.mode!=="server")return"";let f=l.server||{};return`import type { BroadcastConfig } from 'ts-broadcasting'
174
174
 
175
175
  export default {
176
176
  verbose: ${this.environment!=="production"},
177
- driver: '${S.driver||"bun"}',
177
+ driver: '${f.driver||"bun"}',
178
178
  default: 'bun',
179
179
 
180
180
  connections: {
181
181
  bun: {
182
182
  driver: 'bun',
183
- host: process.env.BROADCAST_HOST || '${S.host||"0.0.0.0"}',
184
- port: Number(process.env.BROADCAST_PORT) || ${S.port||6001},
185
- scheme: '${S.scheme||"wss"}',
183
+ host: process.env.BROADCAST_HOST || '${f.host||"0.0.0.0"}',
184
+ port: Number(process.env.BROADCAST_PORT) || ${f.port||6001},
185
+ scheme: '${f.scheme||"wss"}',
186
186
  options: {
187
- idleTimeout: ${S.idleTimeout||120},
188
- maxPayloadLength: ${S.maxPayloadLength||16777216},
189
- backpressureLimit: ${S.backpressureLimit||1048576},
190
- closeOnBackpressureLimit: ${S.closeOnBackpressureLimit||!1},
191
- sendPings: ${S.sendPings!==!1},
192
- perMessageDeflate: ${S.perMessageDeflate!==!1},
187
+ idleTimeout: ${f.idleTimeout||120},
188
+ maxPayloadLength: ${f.maxPayloadLength||16777216},
189
+ backpressureLimit: ${f.backpressureLimit||1048576},
190
+ closeOnBackpressureLimit: ${f.closeOnBackpressureLimit||!1},
191
+ sendPings: ${f.sendPings!==!1},
192
+ perMessageDeflate: ${f.perMessageDeflate!==!1},
193
193
  },
194
194
  },
195
195
  },
196
- ${S.redis?.enabled?`
196
+ ${f.redis?.enabled?`
197
197
  redis: {
198
- host: process.env.REDIS_HOST || '${S.redis.host||"localhost"}',
199
- port: Number(process.env.REDIS_PORT) || ${S.redis.port||6379},
200
- ${S.redis.password?`password: process.env.REDIS_PASSWORD || '${S.redis.password}',`:""}
201
- database: ${S.redis.database||0},
202
- keyPrefix: '${S.redis.keyPrefix||"broadcasting:"}',
198
+ host: process.env.REDIS_HOST || '${f.redis.host||"localhost"}',
199
+ port: Number(process.env.REDIS_PORT) || ${f.redis.port||6379},
200
+ ${f.redis.password?`password: process.env.REDIS_PASSWORD || '${f.redis.password}',`:""}
201
+ database: ${f.redis.database||0},
202
+ keyPrefix: '${f.redis.keyPrefix||"broadcasting:"}',
203
203
  },
204
204
  `:""}
205
- ${S.rateLimit?.enabled?`
205
+ ${f.rateLimit?.enabled?`
206
206
  rateLimit: {
207
- max: ${S.rateLimit.max||100},
208
- window: ${S.rateLimit.window||60000},
209
- perChannel: ${S.rateLimit.perChannel!==!1},
210
- perUser: ${S.rateLimit.perUser!==!1},
207
+ max: ${f.rateLimit.max||100},
208
+ window: ${f.rateLimit.window||60000},
209
+ perChannel: ${f.rateLimit.perChannel!==!1},
210
+ perUser: ${f.rateLimit.perUser!==!1},
211
211
  },
212
212
  `:""}
213
- ${S.loadManagement?.enabled?`
213
+ ${f.loadManagement?.enabled?`
214
214
  loadManagement: {
215
215
  enabled: true,
216
- maxConnections: ${S.loadManagement.maxConnections||1e4},
217
- maxSubscriptionsPerConnection: ${S.loadManagement.maxSubscriptionsPerConnection||100},
218
- shedLoadThreshold: ${S.loadManagement.shedLoadThreshold||0.8},
216
+ maxConnections: ${f.loadManagement.maxConnections||1e4},
217
+ maxSubscriptionsPerConnection: ${f.loadManagement.maxSubscriptionsPerConnection||100},
218
+ shedLoadThreshold: ${f.loadManagement.shedLoadThreshold||0.8},
219
219
  },
220
220
  `:""}
221
221
  } satisfies BroadcastConfig
222
- `}toYAML(){return this.builder.toYAML()}toJSON(){return this.builder.toJSON()}getBuilder(){return this.builder}}function Kd(l){let S=[],P=[];if(!l.AWSTemplateFormatVersion)S.push({path:"AWSTemplateFormatVersion",message:"AWSTemplateFormatVersion is required",severity:"error"});else if(l.AWSTemplateFormatVersion!=="2010-09-09")P.push({path:"AWSTemplateFormatVersion",message:'AWSTemplateFormatVersion should be "2010-09-09"',severity:"warning"});if(!l.Resources||Object.keys(l.Resources).length===0)S.push({path:"Resources",message:"At least one resource is required",severity:"error"});else for(let[v,E]of Object.entries(l.Resources))eu(v,E,S,P);if(l.Resources){let v=fu(l.Resources);if(v.length>0)S.push({path:"Resources",message:`Circular dependencies detected: ${v.join(" -> ")}`,severity:"error"})}if(l.Parameters)for(let[v,E]of Object.entries(l.Parameters))ou(v,E,S,P);if(l.Outputs)for(let[v,E]of Object.entries(l.Outputs))au(v,E,S,P);return{valid:S.length===0,errors:S,warnings:P}}function eu(l,S,P,v){if(!S.Type)P.push({path:`Resources.${l}.Type`,message:"Resource Type is required",severity:"error"});if(!/^[a-zA-Z0-9]+$/.test(l))v.push({path:`Resources.${l}`,message:"Logical ID should only contain alphanumeric characters",severity:"warning"});if(S.Type&&!S.Type.startsWith("AWS::")&&!S.Type.startsWith("Custom::"))P.push({path:`Resources.${l}.Type`,message:'Resource Type must start with "AWS::" or "Custom::"',severity:"error"});if(S.Properties){for(let[E,ot]of Object.entries(S.Properties))if(ot===void 0||ot===null)v.push({path:`Resources.${l}.Properties.${E}`,message:"Property has undefined or null value",severity:"warning"})}if(S.DependsOn){if(typeof S.DependsOn==="string"){if(S.DependsOn===l)P.push({path:`Resources.${l}.DependsOn`,message:"Resource cannot depend on itself",severity:"error"})}else if(Array.isArray(S.DependsOn)){if(S.DependsOn.includes(l))P.push({path:`Resources.${l}.DependsOn`,message:"Resource cannot depend on itself",severity:"error"})}}}function ou(l,S,P,v){if(!S.Type)P.push({path:`Parameters.${l}.Type`,message:"Parameter Type is required",severity:"error"});let E=["String","Number","List<Number>","CommaDelimitedList","AWS::SSM::Parameter::Value<String>"];if(S.Type&&!E.includes(S.Type)&&!S.Type.startsWith("AWS::"))v.push({path:`Parameters.${l}.Type`,message:`Uncommon parameter type: ${S.Type}`,severity:"warning"});if(S.NoEcho&&S.Default)v.push({path:`Parameters.${l}`,message:"NoEcho parameters should not have default values",severity:"warning"})}function au(l,S,P,v){if(!S.Value)P.push({path:`Outputs.${l}.Value`,message:"Output Value is required",severity:"error"})}function fu(l){let S={};for(let[Ie,Ne]of Object.entries(l)){if(S[Ie]=[],Ne.DependsOn){if(typeof Ne.DependsOn==="string")S[Ie].push(Ne.DependsOn);else if(Array.isArray(Ne.DependsOn))S[Ie].push(...Ne.DependsOn)}let nt=tc(Ne);S[Ie].push(...nt)}let P=new Set,v=new Set,E=[];function ot(Ie,Ne){P.add(Ie),v.add(Ie),Ne.push(Ie);let nt=S[Ie]||[];for(let Pt of nt)if(!P.has(Pt)){if(ot(Pt,Ne))return!0}else if(v.has(Pt)){let st=Ne.indexOf(Pt);return E.push(...Ne.slice(st),Pt),!0}return Ne.pop(),v.delete(Ie),!1}for(let Ie of Object.keys(S))if(!P.has(Ie)){if(ot(Ie,[]))return E}return[]}function tc(l,S=[]){if(typeof l!=="object"||l===null)return S;if(Array.isArray(l)){for(let P of l)tc(P,S);return S}if(l.Ref&&typeof l.Ref==="string"&&!l.Ref.startsWith("AWS::"))S.push(l.Ref);if(l["Fn::GetAtt"]){let P=l["Fn::GetAtt"];if(Array.isArray(P)&&P.length>0)S.push(P[0])}for(let P of Object.values(l))tc(P,S);return S}function hu(l){let S=[],P=[],v=new TextEncoder().encode(l).length,E=51200,ot=460800;if(v>51200)if(v>460800)S.push({path:"template",message:`Template size (${v} bytes) exceeds maximum allowed size of 460800 bytes`,severity:"error"});else P.push({path:"template",message:`Template size (${v} bytes) exceeds direct upload limit (51200 bytes). You must upload to S3 first.`,severity:"warning"});return{valid:S.length===0,errors:S,warnings:P}}function yu(l){let S=[],P=[],v=l.Resources?Object.keys(l.Resources).length:0,E=l.Parameters?Object.keys(l.Parameters).length:0,ot=l.Outputs?Object.keys(l.Outputs).length:0;if(v>500)S.push({path:"Resources",message:`Template has ${v} resources, exceeding the limit of 500`,severity:"error"});else if(v>200)P.push({path:"Resources",message:`Template has ${v} resources. Consider using nested stacks for better organization.`,severity:"warning"});if(E>200)S.push({path:"Parameters",message:`Template has ${E} parameters, exceeding the limit of 200`,severity:"error"});if(ot>200)S.push({path:"Outputs",message:`Template has ${ot} outputs, exceeding the limit of 200`,severity:"error"});return{valid:S.length===0,errors:S,warnings:P}}function lh(l){let{domains:S,email:P,staging:v=!1,challengeType:E="http-01",certPath:ot="/etc/letsencrypt/live",autoRenew:Ie=!0}=l,Ne=S[0],nt=S.map((st)=>`-d ${st}`).join(" "),Pt=v?"--staging":"";if(E==="http-01")return Su({domains:S,email:P,staging:v,certPath:ot,autoRenew:Ie,domainFlags:nt,stagingFlag:Pt,primaryDomain:Ne});else{let st=l.dnsProvider?.provider||(l.hostedZoneId?"route53":void 0);return Pu({domains:S,email:P,staging:v,certPath:ot,autoRenew:Ie,domainFlags:nt,stagingFlag:Pt,primaryDomain:Ne,hostedZoneId:l.hostedZoneId,dnsProvider:l.dnsProvider,dnsProviderType:st})}}function Su(l){let{email:S,certPath:P,autoRenew:v,domainFlags:E,stagingFlag:ot,primaryDomain:Ie}=l;return`
222
+ `}toYAML(){return this.builder.toYAML()}toJSON(){return this.builder.toJSON()}getBuilder(){return this.builder}}function Xl(l){let f=[],C=[];if(!l.AWSTemplateFormatVersion)f.push({path:"AWSTemplateFormatVersion",message:"AWSTemplateFormatVersion is required",severity:"error"});else if(l.AWSTemplateFormatVersion!=="2010-09-09")C.push({path:"AWSTemplateFormatVersion",message:'AWSTemplateFormatVersion should be "2010-09-09"',severity:"warning"});if(!l.Resources||Object.keys(l.Resources).length===0)f.push({path:"Resources",message:"At least one resource is required",severity:"error"});else for(let[b,T]of Object.entries(l.Resources))Xd(b,T,f,C);if(l.Resources){let b=nu(l.Resources);if(b.length>0)f.push({path:"Resources",message:`Circular dependencies detected: ${b.join(" -> ")}`,severity:"error"})}if(l.Parameters)for(let[b,T]of Object.entries(l.Parameters))tu(b,T,f,C);if(l.Outputs)for(let[b,T]of Object.entries(l.Outputs))ru(b,T,f,C);return{valid:f.length===0,errors:f,warnings:C}}function Xd(l,f,C,b){if(!f.Type)C.push({path:`Resources.${l}.Type`,message:"Resource Type is required",severity:"error"});if(!/^[a-zA-Z0-9]+$/.test(l))b.push({path:`Resources.${l}`,message:"Logical ID should only contain alphanumeric characters",severity:"warning"});if(f.Type&&!f.Type.startsWith("AWS::")&&!f.Type.startsWith("Custom::"))C.push({path:`Resources.${l}.Type`,message:'Resource Type must start with "AWS::" or "Custom::"',severity:"error"});if(f.Properties){for(let[T,it]of Object.entries(f.Properties))if(it===void 0||it===null)b.push({path:`Resources.${l}.Properties.${T}`,message:"Property has undefined or null value",severity:"warning"})}if(f.DependsOn){if(typeof f.DependsOn==="string"){if(f.DependsOn===l)C.push({path:`Resources.${l}.DependsOn`,message:"Resource cannot depend on itself",severity:"error"})}else if(Array.isArray(f.DependsOn)){if(f.DependsOn.includes(l))C.push({path:`Resources.${l}.DependsOn`,message:"Resource cannot depend on itself",severity:"error"})}}}function tu(l,f,C,b){if(!f.Type)C.push({path:`Parameters.${l}.Type`,message:"Parameter Type is required",severity:"error"});let T=["String","Number","List<Number>","CommaDelimitedList","AWS::SSM::Parameter::Value<String>"];if(f.Type&&!T.includes(f.Type)&&!f.Type.startsWith("AWS::"))b.push({path:`Parameters.${l}.Type`,message:`Uncommon parameter type: ${f.Type}`,severity:"warning"});if(f.NoEcho&&f.Default)b.push({path:`Parameters.${l}`,message:"NoEcho parameters should not have default values",severity:"warning"})}function ru(l,f,C,b){if(!f.Value)C.push({path:`Outputs.${l}.Value`,message:"Output Value is required",severity:"error"})}function nu(l){let f={};for(let[Ce,Se]of Object.entries(l)){if(f[Ce]=[],Se.DependsOn){if(typeof Se.DependsOn==="string")f[Ce].push(Se.DependsOn);else if(Array.isArray(Se.DependsOn))f[Ce].push(...Se.DependsOn)}let ke=Ds(Se);f[Ce].push(...ke)}let C=new Set,b=new Set,T=[];function it(Ce,Se){C.add(Ce),b.add(Ce),Se.push(Ce);let ke=f[Ce]||[];for(let Pt of ke)if(!C.has(Pt)){if(it(Pt,Se))return!0}else if(b.has(Pt)){let ot=Se.indexOf(Pt);return T.push(...Se.slice(ot),Pt),!0}return Se.pop(),b.delete(Ce),!1}for(let Ce of Object.keys(f))if(!C.has(Ce)){if(it(Ce,[]))return T}return[]}function Ds(l,f=[]){if(typeof l!=="object"||l===null)return f;if(Array.isArray(l)){for(let C of l)Ds(C,f);return f}if(l.Ref&&typeof l.Ref==="string"&&!l.Ref.startsWith("AWS::"))f.push(l.Ref);if(l["Fn::GetAtt"]){let C=l["Fn::GetAtt"];if(Array.isArray(C)&&C.length>0)f.push(C[0])}for(let C of Object.values(l))Ds(C,f);return f}function lu(l){let f=[],C=[],b=new TextEncoder().encode(l).length,T=51200,it=460800;if(b>51200)if(b>460800)f.push({path:"template",message:`Template size (${b} bytes) exceeds maximum allowed size of 460800 bytes`,severity:"error"});else C.push({path:"template",message:`Template size (${b} bytes) exceeds direct upload limit (51200 bytes). You must upload to S3 first.`,severity:"warning"});return{valid:f.length===0,errors:f,warnings:C}}function du(l){let f=[],C=[],b=l.Resources?Object.keys(l.Resources).length:0,T=l.Parameters?Object.keys(l.Parameters).length:0,it=l.Outputs?Object.keys(l.Outputs).length:0;if(b>500)f.push({path:"Resources",message:`Template has ${b} resources, exceeding the limit of 500`,severity:"error"});else if(b>200)C.push({path:"Resources",message:`Template has ${b} resources. Consider using nested stacks for better organization.`,severity:"warning"});if(T>200)f.push({path:"Parameters",message:`Template has ${T} parameters, exceeding the limit of 200`,severity:"error"});if(it>200)f.push({path:"Outputs",message:`Template has ${it} outputs, exceeding the limit of 200`,severity:"error"});return{valid:f.length===0,errors:f,warnings:C}}function Tf(l){let{domains:f,email:C,staging:b=!1,challengeType:T="http-01",certPath:it="/etc/letsencrypt/live",autoRenew:Ce=!0}=l,Se=f[0],ke=f.map((ot)=>`-d ${ot}`).join(" "),Pt=b?"--staging":"";if(T==="http-01")return yu({domains:f,email:C,staging:b,certPath:it,autoRenew:Ce,domainFlags:ke,stagingFlag:Pt,primaryDomain:Se});else{let ot=l.dnsProvider?.provider||(l.hostedZoneId?"route53":void 0);return Cu({domains:f,email:C,staging:b,certPath:it,autoRenew:Ce,domainFlags:ke,stagingFlag:Pt,primaryDomain:Se,hostedZoneId:l.hostedZoneId,dnsProvider:l.dnsProvider,dnsProviderType:ot})}}function yu(l){let{email:f,certPath:C,autoRenew:b,domainFlags:T,stagingFlag:it,primaryDomain:Ce}=l;return`
223
223
  # ==========================================
224
224
  # Let's Encrypt Certificate Setup (HTTP-01)
225
225
  # ==========================================
@@ -235,29 +235,29 @@ certbot certonly \\
235
235
  --standalone \\
236
236
  --non-interactive \\
237
237
  --agree-tos \\
238
- --email ${S} \\
239
- ${ot} \\
240
- ${E}
238
+ --email ${f} \\
239
+ ${it} \\
240
+ ${T}
241
241
 
242
242
  # Check if certificate was obtained
243
- if [ -f "${P}/${Ie}/fullchain.pem" ]; then
243
+ if [ -f "${C}/${Ce}/fullchain.pem" ]; then
244
244
  echo "Certificate obtained successfully!"
245
245
 
246
246
  # Create symlinks for easier access
247
247
  mkdir -p /etc/ssl/stacks
248
- ln -sf ${P}/${Ie}/fullchain.pem /etc/ssl/stacks/fullchain.pem
249
- ln -sf ${P}/${Ie}/privkey.pem /etc/ssl/stacks/privkey.pem
250
- ln -sf ${P}/${Ie}/cert.pem /etc/ssl/stacks/cert.pem
251
- ln -sf ${P}/${Ie}/chain.pem /etc/ssl/stacks/chain.pem
248
+ ln -sf ${C}/${Ce}/fullchain.pem /etc/ssl/stacks/fullchain.pem
249
+ ln -sf ${C}/${Ce}/privkey.pem /etc/ssl/stacks/privkey.pem
250
+ ln -sf ${C}/${Ce}/cert.pem /etc/ssl/stacks/cert.pem
251
+ ln -sf ${C}/${Ce}/chain.pem /etc/ssl/stacks/chain.pem
252
252
  else
253
253
  echo "Failed to obtain certificate!"
254
254
  fi
255
255
 
256
- ${v?ic(Ie):"# Auto-renewal disabled"}
256
+ ${b?rc(Ce):"# Auto-renewal disabled"}
257
257
 
258
258
  # Restart the application
259
259
  systemctl start stacks
260
- `}function Pu(l){let{email:S,certPath:P,autoRenew:v,domainFlags:E,stagingFlag:ot,primaryDomain:Ie,hostedZoneId:Ne,dnsProvider:nt,dnsProviderType:Pt}=l;if(Pt==="route53"||Ne){if(!Ne)throw Error("hostedZoneId is required for DNS-01 challenge with Route53");return`
260
+ `}function Cu(l){let{email:f,certPath:C,autoRenew:b,domainFlags:T,stagingFlag:it,primaryDomain:Ce,hostedZoneId:Se,dnsProvider:ke,dnsProviderType:Pt}=l;if(Pt==="route53"||Se){if(!Se)throw Error("hostedZoneId is required for DNS-01 challenge with Route53");return`
261
261
  # ==========================================
262
262
  # Let's Encrypt Certificate Setup (DNS-01 via Route53)
263
263
  # ==========================================
@@ -270,49 +270,49 @@ certbot certonly \\
270
270
  --dns-route53 \\
271
271
  --non-interactive \\
272
272
  --agree-tos \\
273
- --email ${S} \\
274
- ${ot} \\
275
- ${E}
273
+ --email ${f} \\
274
+ ${it} \\
275
+ ${T}
276
276
 
277
277
  # Check if certificate was obtained
278
- if [ -f "${P}/${Ie}/fullchain.pem" ]; then
278
+ if [ -f "${C}/${Ce}/fullchain.pem" ]; then
279
279
  echo "Certificate obtained successfully!"
280
280
 
281
281
  # Create symlinks for easier access
282
282
  mkdir -p /etc/ssl/stacks
283
- ln -sf ${P}/${Ie}/fullchain.pem /etc/ssl/stacks/fullchain.pem
284
- ln -sf ${P}/${Ie}/privkey.pem /etc/ssl/stacks/privkey.pem
285
- ln -sf ${P}/${Ie}/cert.pem /etc/ssl/stacks/cert.pem
286
- ln -sf ${P}/${Ie}/chain.pem /etc/ssl/stacks/chain.pem
283
+ ln -sf ${C}/${Ce}/fullchain.pem /etc/ssl/stacks/fullchain.pem
284
+ ln -sf ${C}/${Ce}/privkey.pem /etc/ssl/stacks/privkey.pem
285
+ ln -sf ${C}/${Ce}/cert.pem /etc/ssl/stacks/cert.pem
286
+ ln -sf ${C}/${Ce}/chain.pem /etc/ssl/stacks/chain.pem
287
287
  else
288
288
  echo "Failed to obtain certificate!"
289
289
  fi
290
290
 
291
- ${v?ic(Ie):"# Auto-renewal disabled"}
292
- `}if(!nt)throw Error("dnsProvider configuration is required for DNS-01 challenge with external DNS providers");let st=nt.provider.toUpperCase(),ur=$u(nt);return`
291
+ ${b?rc(Ce):"# Auto-renewal disabled"}
292
+ `}if(!ke)throw Error("dnsProvider configuration is required for DNS-01 challenge with external DNS providers");let ot=ke.provider.toUpperCase(),rr=bu(ke);return`
293
293
  # ==========================================
294
- # Let's Encrypt Certificate Setup (DNS-01 via ${st})
294
+ # Let's Encrypt Certificate Setup (DNS-01 via ${ot})
295
295
  # ==========================================
296
296
 
297
297
  # Install certbot
298
298
  dnf install -y certbot jq curl
299
299
 
300
- ${ur}
300
+ ${rr}
301
301
 
302
302
  # Create DNS challenge hook scripts directory
303
303
  mkdir -p /etc/letsencrypt/hooks
304
304
 
305
- # Create authenticator hook for ${st}
305
+ # Create authenticator hook for ${ot}
306
306
  cat > /etc/letsencrypt/hooks/auth-hook.sh << 'AUTHHOOK'
307
307
  #!/bin/bash
308
- # DNS-01 authenticator hook for ${st}
308
+ # DNS-01 authenticator hook for ${ot}
309
309
  # This creates the TXT record for ACME challenge
310
310
 
311
311
  DOMAIN="$CERTBOT_DOMAIN"
312
312
  VALIDATION="$CERTBOT_VALIDATION"
313
313
  RECORD_NAME="_acme-challenge.$DOMAIN"
314
314
 
315
- ${Iu(nt)}
315
+ ${$u(ke)}
316
316
 
317
317
  # Wait for DNS propagation
318
318
  echo "Waiting 60 seconds for DNS propagation..."
@@ -321,17 +321,17 @@ AUTHHOOK
321
321
 
322
322
  chmod +x /etc/letsencrypt/hooks/auth-hook.sh
323
323
 
324
- # Create cleanup hook for ${st}
324
+ # Create cleanup hook for ${ot}
325
325
  cat > /etc/letsencrypt/hooks/cleanup-hook.sh << 'CLEANUPHOOK'
326
326
  #!/bin/bash
327
- # DNS-01 cleanup hook for ${st}
327
+ # DNS-01 cleanup hook for ${ot}
328
328
  # This removes the TXT record after validation
329
329
 
330
330
  DOMAIN="$CERTBOT_DOMAIN"
331
331
  VALIDATION="$CERTBOT_VALIDATION"
332
332
  RECORD_NAME="_acme-challenge.$DOMAIN"
333
333
 
334
- ${Du(nt)}
334
+ ${Iu(ke)}
335
335
  CLEANUPHOOK
336
336
 
337
337
  chmod +x /etc/letsencrypt/hooks/cleanup-hook.sh
@@ -344,26 +344,26 @@ certbot certonly \\
344
344
  --manual-cleanup-hook /etc/letsencrypt/hooks/cleanup-hook.sh \\
345
345
  --non-interactive \\
346
346
  --agree-tos \\
347
- --email ${S} \\
348
- ${ot} \\
349
- ${E}
347
+ --email ${f} \\
348
+ ${it} \\
349
+ ${T}
350
350
 
351
351
  # Check if certificate was obtained
352
- if [ -f "${P}/${Ie}/fullchain.pem" ]; then
352
+ if [ -f "${C}/${Ce}/fullchain.pem" ]; then
353
353
  echo "Certificate obtained successfully!"
354
354
 
355
355
  # Create symlinks for easier access
356
356
  mkdir -p /etc/ssl/stacks
357
- ln -sf ${P}/${Ie}/fullchain.pem /etc/ssl/stacks/fullchain.pem
358
- ln -sf ${P}/${Ie}/privkey.pem /etc/ssl/stacks/privkey.pem
359
- ln -sf ${P}/${Ie}/cert.pem /etc/ssl/stacks/cert.pem
360
- ln -sf ${P}/${Ie}/chain.pem /etc/ssl/stacks/chain.pem
357
+ ln -sf ${C}/${Ce}/fullchain.pem /etc/ssl/stacks/fullchain.pem
358
+ ln -sf ${C}/${Ce}/privkey.pem /etc/ssl/stacks/privkey.pem
359
+ ln -sf ${C}/${Ce}/cert.pem /etc/ssl/stacks/cert.pem
360
+ ln -sf ${C}/${Ce}/chain.pem /etc/ssl/stacks/chain.pem
361
361
  else
362
362
  echo "Failed to obtain certificate!"
363
363
  fi
364
364
 
365
- ${v?ic(Ie):"# Auto-renewal disabled"}
366
- `}function $u(l){switch(l.provider){case"porkbun":return`
365
+ ${b?rc(Ce):"# Auto-renewal disabled"}
366
+ `}function bu(l){switch(l.provider){case"porkbun":return`
367
367
  # Porkbun API credentials
368
368
  export PORKBUN_API_KEY="${l.apiKey}"
369
369
  export PORKBUN_SECRET_KEY="${l.secretKey}"
@@ -374,7 +374,7 @@ export GODADDY_API_SECRET="${l.apiSecret}"
374
374
  export GODADDY_ENV="${l.environment||"production"}"
375
375
  `;case"route53":return`
376
376
  # Route53 uses IAM role credentials
377
- `;default:return""}}function Iu(l){switch(l.provider){case"porkbun":return`
377
+ `;default:return""}}function $u(l){switch(l.provider){case"porkbun":return`
378
378
  # Extract root domain (last two parts)
379
379
  ROOT_DOMAIN=$(echo "$DOMAIN" | awk -F. '{print $(NF-1)"."$NF}')
380
380
  SUBDOMAIN="_acme-challenge"
@@ -418,7 +418,7 @@ curl -s -X PATCH "$API_URL/v1/domains/$ROOT_DOMAIN/records" \\
418
418
  "data": "'"$VALIDATION"'",
419
419
  "ttl": 600
420
420
  }]'
421
- `;default:return'echo "Unsupported DNS provider"'}}function Du(l){switch(l.provider){case"porkbun":return`
421
+ `;default:return'echo "Unsupported DNS provider"'}}function Iu(l){switch(l.provider){case"porkbun":return`
422
422
  # Extract root domain, and the challenge's subdomain the way the auth hook did
423
423
  ROOT_DOMAIN=$(echo "$DOMAIN" | awk -F. '{print $(NF-1)"."$NF}')
424
424
  SUBDOMAIN="_acme-challenge"
@@ -470,7 +470,7 @@ fi
470
470
 
471
471
  curl -s -X DELETE "$API_URL/v1/domains/$ROOT_DOMAIN/records/TXT/$RECORD_NAME" \\
472
472
  -H "Authorization: sso-key $GODADDY_API_KEY:$GODADDY_API_SECRET"
473
- `;default:return'echo "Unsupported DNS provider"'}}function ic(l){return`
473
+ `;default:return'echo "Unsupported DNS provider"'}}function rc(l){return`
474
474
  # ==========================================
475
475
  # Certificate Auto-Renewal Setup
476
476
  # ==========================================
@@ -515,13 +515,13 @@ systemctl enable certbot-renewal.timer
515
515
  systemctl start certbot-renewal.timer
516
516
 
517
517
  echo "Certificate auto-renewal configured"
518
- `}function dh(l){let{httpPort:S=80,httpsPort:P=443,certPath:v="/etc/ssl/stacks",redirectHttp:E=!0}=l;return`
518
+ `}function vf(l){let{httpPort:f=80,httpsPort:C=443,certPath:b="/etc/ssl/stacks",redirectHttp:T=!0}=l;return`
519
519
  // HTTPS Server with Let's Encrypt certificates
520
520
  import { readFileSync, existsSync } from 'node:fs'
521
521
 
522
- const CERT_PATH = '${v}'
523
- const HTTP_PORT = ${S}
524
- const HTTPS_PORT = ${P}
522
+ const CERT_PATH = '${b}'
523
+ const HTTP_PORT = ${f}
524
+ const HTTPS_PORT = ${C}
525
525
 
526
526
  // Check if certificates exist
527
527
  const hasCerts = existsSync(\`\${CERT_PATH}/fullchain.pem\`) && existsSync(\`\${CERT_PATH}/privkey.pem\`)
@@ -541,7 +541,7 @@ if (hasCerts) {
541
541
  })
542
542
  console.log(\`HTTPS server running on port \${HTTPS_PORT}\`)
543
543
 
544
- ${E?`
544
+ ${T?`
545
545
  // Start HTTP server for redirect
546
546
  const httpServer = Bun.serve({
547
547
  port: HTTP_PORT,
@@ -601,5 +601,5 @@ async function handleRequest(request: Request): Promise<Response> {
601
601
  // Implement your request handling here
602
602
  return new Response('Hello from Stacks!')
603
603
  }
604
- `}async function Ou(l,S,P){let v=`_acme-challenge.${S}`;if(await ku(l,S,v,P))return;let E=await l.createRecord(S,{name:v,type:"TXT",content:P,ttl:60});if(!E.success)throw Error(`Failed to create DNS challenge record: ${E.message}`)}async function Nu(l,S,P){let v=await l.deleteRecord(S,{name:`_acme-challenge.${S}`,type:"TXT",content:P});if(!v.success)console.warn(`Failed to delete DNS challenge record: ${v.message}`)}async function ku(l,S,P,v){try{let E=await l.listRecords(S,"TXT"),ot=P.replace(/\.$/,"").toLowerCase();return(E.records??[]).some((Ie)=>Ie.name.replace(/\.$/,"").toLowerCase()===ot&&Ie.content.replace(/^"|"$/g,"")===v)}catch{return!1}}function fc(l){let{hostedZoneId:S,dnsProvider:P,region:v="us-east-1"}=l;if(P)return T(P);if(S)return new z(v,S);throw Error("Either dnsProvider or hostedZoneId must be provided")}async function uh(l){await Ou(fc(l),l.domain,l.challengeValue)}async function ph(l){await Nu(fc(l),l.domain,l.challengeValue)}function mh(l){try{let{execSync:S}=Fe("node:child_process"),P=S(`openssl x509 -checkend 2592000 -noout -in ${l}/cert.pem`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return!1}catch{return!0}}import{createHash as gc,createSign as xu,generateKeyPairSync as yc}from"node:crypto";var Cc={production:"https://acme-v02.api.letsencrypt.org/directory",staging:"https://acme-staging-v02.api.letsencrypt.org/directory"};class Lu{directoryUrl;email;accountKey;accountUrl=null;directory=null;nonce=null;constructor(l){this.directoryUrl=l.staging?Cc.staging:Cc.production,this.email=l.email,this.accountKey=l.accountKey||this.generateAccountKey()}generateAccountKey(){let{privateKey:l}=yc("ec",{namedCurve:"P-256"});return l.export({type:"pkcs8",format:"pem"})}async getDirectory(){if(this.directory)return this.directory;let l=await fetch(this.directoryUrl);if(!l.ok)throw Error(`Failed to fetch ACME directory: ${l.status}`);return this.directory=await l.json(),this.directory}async getNonce(){if(this.nonce){let v=this.nonce;return this.nonce=null,v}let l=await this.getDirectory(),P=(await fetch(l.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!P)throw Error("Failed to get nonce from ACME server");return P}getJwk(){let l=this.accountKey.split(`
605
- `).filter((ot)=>!ot.startsWith("-----")).join(""),S=Buffer.from(l,"base64"),P=S.length-65,v=S.subarray(P+1,P+33),E=S.subarray(P+33,P+65);return{kty:"EC",crv:"P-256",x:this.base64UrlEncode(v),y:this.base64UrlEncode(E)}}getJwkThumbprint(){let l=this.getJwk(),S=JSON.stringify({crv:l.crv,kty:l.kty,x:l.x,y:l.y}),P=gc("sha256").update(S).digest();return this.base64UrlEncode(P)}base64UrlEncode(l){return(typeof l==="string"?Buffer.from(l):l).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async signPayload(l,S){let P=await this.getNonce(),v=this.getJwk(),E={alg:"ES256",nonce:P,url:l};if(this.accountUrl)E.kid=this.accountUrl;else E.jwk=v;let ot=this.base64UrlEncode(JSON.stringify(E)),Ie=S===""?"":this.base64UrlEncode(JSON.stringify(S)),Ne=`${ot}.${Ie}`,nt=xu("SHA256");nt.update(Ne);let Pt=nt.sign(this.accountKey),st=Pt.subarray(4,4+Pt[3]),ur=4+Pt[3]+2,pr=Pt.subarray(ur,ur+Pt[ur-1]),gr=Buffer.alloc(32),Dt=Buffer.alloc(32);st.copy(gr,32-st.length),pr.copy(Dt,32-pr.length);let St=Buffer.concat([gr,Dt]);return JSON.stringify({protected:ot,payload:Ie,signature:this.base64UrlEncode(St)})}async acmeRequest(l,S){let P=await this.signPayload(l,S),v=await fetch(l,{method:"POST",headers:{"Content-Type":"application/jose+json"},body:P}),E=v.headers.get("replay-nonce");if(E)this.nonce=E;let ot,Ie=v.headers.get("content-type");if(Ie?.includes("application/json")||Ie?.includes("application/problem+json"))ot=await v.json();else ot=await v.text();if(!v.ok)throw Error(`ACME request failed: ${JSON.stringify(ot)}`);return{body:ot,headers:v.headers}}async registerAccount(){let l=await this.getDirectory(),{body:S,headers:P}=await this.acmeRequest(l.newAccount,{termsOfServiceAgreed:!0,contact:[`mailto:${this.email}`]}),v=P.get("location");if(!v)throw Error("No account URL returned");return this.accountUrl=v,v}async createOrder(l){if(!this.accountUrl)await this.registerAccount();let S=await this.getDirectory(),{body:P,headers:v}=await this.acmeRequest(S.newOrder,{identifiers:l.map((ot)=>({type:"dns",value:ot}))}),E=v.get("location");if(!E)throw Error("No order URL returned");return{orderUrl:E,authorizations:P.authorizations,finalize:P.finalize}}async getAuthorization(l){let{body:S}=await this.acmeRequest(l,""),P=S.identifier.value,v=this.getJwkThumbprint(),E=S.challenges.filter((ot)=>ot.type==="http-01"||ot.type==="dns-01").map((ot)=>{let Ie=`${ot.token}.${v}`;if(ot.type==="http-01")return{type:"http-01",token:ot.token,keyAuthorization:Ie,identifier:`/.well-known/acme-challenge/${ot.token}`};else{let Ne=this.base64UrlEncode(gc("sha256").update(Ie).digest());return{type:"dns-01",token:ot.token,keyAuthorization:Ie,identifier:`_acme-challenge.${P}`,dnsValue:Ne}}});return{domain:P,challenges:E}}async respondToChallenge(l){await this.acmeRequest(l,{})}async waitForAuthorization(l,S=30){for(let P=0;P<S;P++){let{body:v}=await this.acmeRequest(l,"");if(v.status==="valid")return;if(v.status==="invalid")throw Error(`Authorization failed: ${JSON.stringify(v)}`);await new Promise((E)=>setTimeout(E,2000))}throw Error("Authorization timed out")}generateCsr(l){let{privateKey:S}=yc("rsa",{modulusLength:2048}),P=S.export({type:"pkcs8",format:"pem"});return{csr:this.createSimpleCsr(l,S),privateKey:P}}createSimpleCsr(l,S){throw Error("CSR generation requires additional implementation. Consider using the shell-based certbot approach instead.")}async finalizeOrder(l,S){let{csr:P,privateKey:v}=this.generateCsr(S),{body:E}=await this.acmeRequest(l,{csr:this.base64UrlEncode(Buffer.from(P,"base64"))}),ot=E.certificate;if(!ot)throw Error("Certificate not immediately available - polling not implemented");let Ne=await(await fetch(ot)).text(),nt=Ne.split(/(?=-----BEGIN CERTIFICATE-----)/g),Pt=nt[0],st=nt.slice(1).join("");return{certificate:Pt,privateKey:v,chain:st,fullchain:Ne,expiresAt:new Date(Date.now()+7776000000)}}getAccountKey(){return this.accountKey}}var kn=(l)=>l===void 0?void 0:l?"on":"off";function oc(l){let S={ssl:l.ssl,always_use_https:kn(l.alwaysUseHttps),automatic_https_rewrites:kn(l.automaticHttpsRewrites),min_tls_version:l.minTlsVersion,tls_1_3:kn(l.tls13),brotli:kn(l.brotli),http3:kn(l.http3),"0rtt":kn(l.zeroRtt),early_hints:kn(l.earlyHints),browser_cache_ttl:l.browserCacheTtl,always_online:kn(l.alwaysOnline),websockets:kn(l.websockets),email_obfuscation:kn(l.emailObfuscation)};if(l.hsts)S.security_header={strict_transport_security:{enabled:l.hsts.enabled,max_age:l.hsts.maxAge??31536000,include_subdomains:l.hsts.includeSubdomains??!1,preload:l.hsts.preload??!1,nosniff:l.hsts.noSniff??!0}};for(let P of Object.keys(S))if(S[P]===void 0)delete S[P];return{...S,...l.raw??{}}}var Ha={ssl:"strict",alwaysUseHttps:!0,automaticHttpsRewrites:!0,minTlsVersion:"1.2",tls13:!0,brotli:!0,http3:!0,earlyHints:!0,alwaysOnline:!0,emailObfuscation:!1,browserCacheTtl:0};import{connect as Fu}from"node:tls";async function ac(l){let{address:S,serverName:P,port:v=443,timeoutMs:E=5000}=l;return new Promise((ot)=>{let Ie=!1,Ne=(Pt)=>{if(Ie)return;Ie=!0;try{nt.destroy()}catch{}ot(Pt)},nt=Fu({host:S,port:v,servername:P,rejectUnauthorized:!1,timeout:E});nt.once("secureConnect",()=>{if(nt.authorized){Ne({reachable:!0,trusted:!0});return}Ne({reachable:!0,trusted:!1,reason:nt.authorizationError?String(nt.authorizationError):"origin certificate is not trusted for this hostname"})}),nt.once("timeout",()=>{Ne({reachable:!1,trusted:!1,reason:`no TLS handshake within ${E}ms`})}),nt.once("error",(Pt)=>{Ne({reachable:!1,trusted:!1,reason:Pt.message})})})}function Mu(l,S){let P=S.replace(/\.$/,"").toLowerCase();return l.some((v)=>{let E=v.replace(/\.$/,"").toLowerCase();if(E===P)return!0;if(!E.startsWith("*."))return!1;let ot=E.slice(2);if(!P.endsWith(`.${ot}`))return!1;return!P.slice(0,P.length-ot.length-1).includes(".")})}async function Bu(l){let{provider:S,zone:P,hosts:v,ipv4:E,ipv6:ot,proxied:Ie=!0,settings:Ne=Ha,cache:nt,originGuard:Pt,purge:st=!0,ttl:ur=300,skipOriginProbe:pr=!1,skipEdgeCertificateCheck:gr=!1}=l,Dt={records:[],settingsChanged:[],cacheRules:0,originGuard:!1,purged:!1,deferredProxy:[],warnings:[]};if(v.length===0)return Dt;let St=[],Se=Ie&&!gr?await S.listEdgeCertificateHosts(P):null;for(let ie of v){let Rt=Ie;if(Rt&&Se&&!Mu(Se,ie)){Rt=!1;let er=Se.length===0?"the zone has no active edge certificate yet":`no active edge certificate covers it (${Se.join(", ")})`;Dt.deferredProxy.push({host:ie,reason:er}),Dt.warnings.push(`${ie}: publishing DNS-only — ${er}. Proxying it would make Cloudflare terminate TLS with no certificate for the name, which fails the handshake outright rather than degrading. Universal SSL covers the apex and ONE level of subdomain, so a deeper name needs its own certificate; otherwise re-run the deploy once the certificate is active.`)}if(Rt&&!pr){let er=await ac({address:E,serverName:ie});if(!er.trusted){Rt=!1;let lr=er.reason||"origin is not serving a trusted certificate";Dt.deferredProxy.push({host:ie,reason:lr}),Dt.warnings.push(`${ie}: publishing DNS-only for now — the origin does not yet serve a certificate this proxy can verify (${lr}). The origin issues certificates over HTTP-01, which needs the name to reach it directly; re-run the deploy once it has one and the record will be proxied.`)}}if(Rt)St.push(ie);let Nt=[{type:"A",content:E}];if(ot&&Tn(ie))Nt.push({type:"AAAA",content:ot});for(let{type:er,content:lr}of Nt){let fr=await S.upsertRecord(P,{name:ie,type:er,content:lr,ttl:ur,proxied:Rt});if(fr.success)Dt.records.push({host:ie,type:er,content:lr,proxied:Rt});else Dt.warnings.push(`${ie} ${er} → ${lr} failed: ${fr.message||"unknown provider error"}`)}}if(St.length===0){if(Ie)Dt.warnings.push("No host is proxied yet, so zone settings, cache rules and purge were skipped — they only take effect through the proxy.");return Dt}try{let ie=oc(Ne),Rt=await S.applyZoneSettings(P,ie);Dt.settingsChanged=Rt.changed;for(let Nt of Rt.failed)Dt.warnings.push(`zone setting '${Nt.id}' could not be applied: ${Nt.error}`)}catch(ie){Dt.warnings.push(`zone settings could not be read: ${ie instanceof Error?ie.message:String(ie)}`)}let Bt=za(St,nt);if(Bt.length>0){let ie=await S.putManagedPhaseRules(P,"http_request_cache_settings",Bt);if(ie.success)Dt.cacheRules=Bt.length;else Dt.warnings.push(`cache rules could not be written: ${ie.message}`)}if(Pt){let ie=Ka(St,Pt.header,Pt.value);if(ie.length>0){let Rt=await S.putManagedPhaseRules(P,"http_request_late_transform",ie);if(Rt.success)Dt.originGuard=!0;else Dt.warnings.push(`origin guard header could not be written: ${Rt.message}. `+"The gateway will reject requests that lack it — disable the guard or grant the token Transform Rules: Edit.")}}if(st){if(Dt.purged=await S.purgeCache(P,{hosts:St}),!Dt.purged)Dt.warnings.push("edge cache purge failed — new content may take until TTL expiry to appear.")}return Dt}var _u=(l)=>process.env[l];function Sc(l,S){let P=l.replace(/\.$/,"").toLowerCase();if(S){let v=S.replace(/\.$/,"").toLowerCase();if(P===v||P.endsWith(`.${v}`))return v}return P.split(".").slice(-2).join(".")}function Vu(l,S={}){let P=S.env??_u,v=l.infrastructure?.compute?.proxy?.cdn,E=[];if(!v||v.provider!=="cloudflare")return{plan:null,errors:E};if(v.originDomain)E.push(`compute.proxy.cdn.originDomain (${v.originDomain}) is ignored for Cloudflare: the proxy forwards to the address in the record it fronts, `+"so no separate origin hostname is needed — and publishing one gives clients a documented way around the edge.");let ot=P("CLOUDFLARE_API_TOKEN");if(!ot)return E.push("CLOUDFLARE_API_TOKEN is not set — the Cloudflare CDN cannot be reconciled."),{plan:null,errors:E};let Ie=l.sites??{},Ne=v.frontedHosts?.length?[...new Set(v.frontedHosts.map((pr)=>pr.toLowerCase()))]:Nn(Ie,{autoWww:l.infrastructure?.compute?.proxy?.autoWww!==!1});if(Ne.length===0)return E.push("No hostnames to front — set compute.proxy.cdn.frontedHosts, or give a site a domain."),{plan:null,errors:E};let nt=l.infrastructure?.dns?.domain,Pt=new Set(Ne.map((pr)=>Sc(pr,nt)));if(Pt.size>1)return E.push(`Fronted hosts span more than one zone (${[...Pt].join(", ")}). A Cloudflare zone is configured as a unit, so run one CDN config per zone.`),{plan:null,errors:E};let st=v.cloudflare??{},ur=v.secret?{header:v.secretHeader??"X-Origin-Verify",value:v.secret}:void 0;return{plan:{zone:[...Pt][0],hosts:Ne,apiToken:ot,zoneId:st.zoneId??P("CLOUDFLARE_ZONE_ID"),accountId:st.accountId??P("CLOUDFLARE_ACCOUNT_ID"),proxied:st.proxied!==!1,settings:st.settings??Ha,cache:st.cache,originGuard:ur,purge:st.purgeOnDeploy!==!1,skipOriginProbe:st.skipOriginProbe===!0},errors:E}}var Wu=26214400;var Hu=new Set(["/_headers","/_redirects","/_routes.json","/_worker.js"]);class Ac{name="cloudflare-pages";apiToken;accountId;constructor(l){if(!l.apiToken)throw Error("Cloudflare Pages needs an API token");if(!l.accountId)throw Error("Cloudflare Pages needs an account id");this.apiToken=l.apiToken,this.accountId=l.accountId}async request(l,S,P){return cs(l,`/accounts/${this.accountId}${S}`,`Bearer ${this.apiToken}`,P)}async getProject(l){try{return await this.request("GET",`/pages/projects/${l}`)}catch(S){if(S instanceof Error&&/\b8000007\b|not found/i.test(S.message))return null;throw S}}async ensureProject(l,S="main"){let P=await this.getProject(l);if(P)return P;return this.request("POST","/pages/projects",{name:l,production_branch:S})}async uploadToken(l){return(await this.request("GET",`/pages/projects/${l}/upload-token`)).jwt}async missingHashes(l,S){let P=await cs("POST","/pages/assets/check-missing",`Bearer ${l}`,{hashes:S});return new Set(P)}async upsertHashes(l,S){await cs("POST","/pages/assets/upsert-hashes",`Bearer ${l}`,{hashes:S})}async uploadBatch(l,S){let P=S.map((v)=>({key:v.hash,value:v.base64,metadata:{contentType:zu(v.extension)},base64:!0}));await cs("POST","/pages/assets/upload",`Bearer ${l}`,P)}async createDeployment(l,S,P){let v={};for(let ot of S)v[ot.path]=ot.hash;let E=new FormData;if(E.append("manifest",JSON.stringify(v)),P)E.append("branch",P);return this.request("POST",`/pages/projects/${l}/deployments`,E)}async deployDirectory(l){let S=await Wl(l.directory);if(S.length===0)throw Error(`No files to deploy in ${l.directory}`);let P=await this.uploadToken(l.project),v=await this.missingHashes(P,S.map((nt)=>nt.hash)),E=S.filter((nt)=>v.has(nt.hash)),ot=[];for(let nt=0;nt<E.length;nt+=100)ot.push(E.slice(nt,nt+100));let Ie=0;for(let nt=0;nt<ot.length;nt+=4){let Pt=ot.slice(nt,nt+4);await Promise.all(Pt.map((st)=>this.uploadBatch(P,st))),Ie+=Pt.reduce((st,ur)=>st+ur.length,0),l.onProgress?.(Ie,E.length)}return await this.upsertHashes(P,S.map((nt)=>nt.hash)),{deployment:await this.createDeployment(l.project,S,l.branch),total:S.length,uploaded:E.length,uploadedBytes:E.reduce((nt,Pt)=>nt+Pt.size,0)}}async listCustomDomains(l){return(await this.request("GET",`/pages/projects/${l}/domains`)).map((P)=>P.name)}async attachCustomDomain(l,S){if((await this.listCustomDomains(l)).includes(S))return!1;return await this.request("POST",`/pages/projects/${l}/domains`,{name:S}),!0}}function Gu(l,S){return{type:"CNAME",name:l,value:S.endsWith(".pages.dev")?S:`${S}.pages.dev`,ttl:1,proxied:!0}}async function Ic(l,S){let{blake3:P}=await import("./chunk-vs0qrm09.js").then((m)=>zh(m.default,1));return(await P(l+S)).slice(0,32)}async function Wl(l){let{readdir:S}=await import("node:fs/promises"),{join:P,relative:v,sep:E}=await import("node:path"),ot=[];async function Ie(Ne){let nt=await S(Ne,{withFileTypes:!0});for(let Pt of nt){let st=P(Ne,Pt.name);if(Pt.isDirectory()){await Ie(st);continue}if(!Pt.isFile())continue;let ur=`/${v(l,st).split(E).join("/")}`;if(Hu.has(ur))continue;let pr=await Bun.file(st).bytes();if(pr.byteLength>26214400)throw Error(`${ur} is ${pr.byteLength} bytes, over the Cloudflare Pages limit of 26214400`);let gr=Buffer.from(pr).toString("base64"),Dt=Pt.name.lastIndexOf("."),St=Dt>0?Pt.name.slice(Dt+1):"";ot.push({path:ur,hash:await Ic(gr,St),base64:gr,extension:St,size:pr.byteLength})}}return await Ie(l),ot.sort((Ne,nt)=>Ne.path.localeCompare(nt.path)),ot}function zu(l){return{html:"text/html; charset=utf-8",css:"text/css; charset=utf-8",js:"application/javascript; charset=utf-8",mjs:"application/javascript; charset=utf-8",json:"application/json; charset=utf-8",map:"application/json; charset=utf-8",xml:"application/xml; charset=utf-8",txt:"text/plain; charset=utf-8",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",pdf:"application/pdf",webmanifest:"application/manifest+json"}[l.toLowerCase()]||"application/octet-stream"}async function cs(l,S,P,v){let E={Authorization:P},ot;if(v instanceof FormData)ot=v;else if(v!==void 0)E["Content-Type"]="application/json",ot=JSON.stringify(v);let Ie=await fetch(`https://api.cloudflare.com/client/v4${S}`,{method:l,headers:E,body:ot}),Ne=await Ie.text(),nt;try{nt=JSON.parse(Ne)}catch{throw Error(`Cloudflare Pages API returned ${Ie.status} with a non-JSON body: ${Ne.slice(0,200)}`)}if(!nt.success){let Pt=(nt.errors??[]).map((st)=>`${st.code}: ${st.message}`).join(", ");throw Error(`Cloudflare Pages API error (${Ie.status}): ${Pt||Ne.slice(0,200)}`)}return nt.result}export{zg as ABTestManager,ae as ACMClient,dr as ACMDnsValidator,Cc as ACME_DIRECTORIES,we as AI,ol as API_IDEMPOTENCY_TTL_MS,il as API_TOKEN_DEFAULT_TTL_MS,sl as API_TOKEN_MAX_TTL_MS,Fi as API_VERSION,de as AUTHORIZATION_CAPABILITIES,el as AUTH_ACTION_TOKEN_TTL_MS,tl as AUTH_MFA_CHALLENGE_TTL_MS,rl as AUTH_OIDC_TRANSACTION_TTL_MS,ze as AUTH_SESSION_ABSOLUTE_TTL_MS,Zd as AUTH_SESSION_IDLE_TTL_MS,CA as AWSAPIError,n as AWSClient,h as AWSCloudFormationClient,A as AWSCloudFrontClient,Gg as AWSConfigManager,kI as AWS_PSEUDO_PARAMETERS,Re as AWS_REGIONS,Lu as AcmeClient,xr as AlertEvaluator,fi as AlertStore,Ks as AnomalyConfigStore,Pd as ApiGateway,i as ApiServiceError,Ga as ApplicationAutoScalingClient,lo as Arn,D as AssetHasher,U as Auth,Oi as AuthenticationStore,Ci as AutomationApiService,xi as AutomationIdentityStore,Xo as AwsAuroraDataAdapter,ra as AwsAuroraTransport,Sa as AwsDatabaseBackupSource,mr as AwsDriver,Yo as AwsElastiCacheDataAdapter,na as AwsElastiCacheTransport,Vm as AwsIamCapabilityScanner,Ta as AwsInfrastructureBackupSource,Jo as AwsRdsDataAdapter,ta as AwsRdsTransport,ih as AwsRegionalDriver,Ra as AwsSecretsManagerConfigurationBackend,Zp as AwsSpendTransport,Da as AwsSsmConfigurationBackend,Ji as BackupCoordinator,Qg as BackupManager,ya as BackupStore,Tm as BatchProcessingManager,fn as BedrockClient,hn as BedrockRuntimeClient,gl as BitbucketSourceAdapter,jg as BlueGreenManager,Im as BounceComplaintHandler,am as BuildOptimizationManager,xl as BunDockerRuntime,uu as BunDockerVolumeRuntime,lu as BunFilesystemArchiveRuntime,ue as CDN,Ao as CHAIN_HEADER,ds as CLOUDFLARE_MANAGED_RULE_PREFIX,bd as CLOUDFRONT_FAILOVER_STATUS_CODES,TC as COMMON_CROSS_ACCOUNT_ROLES,Ue as CONTROL_PLANE_SCHEMA_VERSION,ao as Cache,go as CanaryManager,im as CertificateManager,Nf as CloudBlockVolumeDriver,Ds as CloudDriverFactory,je as CloudError,Ag as CloudFormationBuilder,h as CloudFormationClient,A as CloudFrontClient,qg as CloudTrailManager,he as CloudWatchLogsClient,Ac as CloudflarePagesProvider,Ae as CloudflareProvider,xA as CommandHistory,H as Communication,Nr as ComposeApplicationService,Lt as ComposeApplicationStore,Et as ComprehendClient,a as Compute,eg as ComputeSpendTransport,po as ConfigurationError,Na as ConfigurationService,wa as ConfigurationStore,gn as ConnectClient,ea as ContainerDataAdapter,cm as ContainerRegistryManager,va as ControlPlaneBackupSource,ma as ControlPlaneCleanupDriver,di as ControlPlaneStore,Vs as CounterTracker,jt as CredentialError,xg as CrossRegionReferenceManager,oA as DASHBOARD_ENTRY,aA as DASHBOARD_PORT_BASE,cA as DASHBOARD_PORT_SPAN,sA as DASHBOARD_STATE_DIR,vo as DEFAULT_ATTACK_MODE_HOURS,ud as DEFAULT_DDOS_THRESHOLDS,ag as DEFAULT_FAILOVER_STATUS_CODES,jc as DEFAULT_METER_MAPPINGS,qc as DEFAULT_PRICE_BOOK,Di as DEFAULT_RECURSION_LIMITS,Dn as DEFAULT_RPX_CERTS_DIR,q as DEFAULT_SERVICE_LIMITS,ig as DEFAULT_STATE_DIR,bu as DEFAULT_STATIC_ASSET_EXTENSIONS,tA as DEFAULT_STORAGE_FAILOVER_STATUS_CODES,Gf as DEFAULT_TELEMETRY_POLICY,$p as DEFAULT_THRESHOLDS,Tf as DEPLOYMENT_QUEUE_KINDS,fo as DEPTH_HEADER,_r as DETECTABLE_SIGNALS,Nl as DIAGNOSTIC_PRESETS,vm as DLQMonitoringManager,L as DNS,Am as DNSSECManager,Gi as DataServiceLifecycle,Wo as DataServiceStore,Gt as Database,tm as DatabaseUserManager,ee as DebugLogger,eA as DependencyGraph,Q as Deployment,SA as DeploymentError,Hg as DisasterRecoveryManager,vn as DnsProviderFactory,Jt as DockerDataTransport,Go as DockerDiscoveryAdapter,Pr as DockerNamedVolumeDriver,ba as DockerVolumeBackupSource,c as DurableOperationQueue,Ms as DurableQueueWorker,Be as DynamoDBClient,Er as EC2Client,_e as ECRClient,Ye as ECSClient,sr as EFSClient,Fa as ELBv2Client,Bf as ENFORCEMENT_ACTIONS,mi as ENFORCEMENT_DESCRIPTIONS,R as ENFORCEMENT_SEVERITY,up as ENVIRONMENT_LABEL,Dl as EcsRuntimeAdapter,bo as EdgeRateLimiter,et as ElastiCacheClient,m as Email,MA as EmailAdvanced,Sm as EmailAnalyticsManager,Sn as EmailClient,FA as EmailHandlers,Em as EmailTemplateManager,ia as EncryptedDataSecretStore,EA as ErrorCodes,nr as EventBridgeClient,th as EventBridgeJobAdapter,Pa as ExternalConfigurationBackend,oo as FAILOVER_REPLICA_POLICY_SID,bm as FIFOQueueManager,Vp as FOCUS_VERSION,bg as FileCache,qe as FileSystem,Ca as FilesystemBackupSource,oa as FleetService,sa as FleetStore,e as Fn,ml as GiteaSourceAdapter,ul as GithubSourceAdapter,pl as GitlabSourceAdapter,Lg as GlobalResourceManager,Oe as GoDaddyProvider,Vg as GuardDutyManager,at as HOST_SITES_DIR,TA as HashCache,_m as HealthCheckManager,He as HealthCheckRunner,yr as HetznerClient,Ce as HetznerDriver,fe as IAMClient,Ya as IPV6_EXCLUDED_HOST_LABELS,om as ImageScanningManager,Yl as InfrastructureGenerator,_c as InvalidOperationTransitionError,pt as JobLoader,rh as JobProviderReconciler,Ko as JobService,jo as JobStore,rr as KendraClient,iy as LARAVEL_SERVERLESS_BUILD_STEPS,C as LambdaClient,pm as LambdaConcurrencyManager,hm as LambdaDLQManager,gm as LambdaDestinationsManager,lm as LambdaLayersManager,Pl as LambdaRuntimeAdapter,mm as LambdaVPCManager,um as LambdaVersionsManager,cn as LocalEncryptedConfigurationBackend,Ea as LogicalDatabaseBackupSource,Xg as LogsManager,qA as MANAGED_NODE_VERSIONS,Ec as MANAGEMENT_DASHBOARD_SITE,yg as MANAGEMENT_DASHBOARD_SITE_PREFIX,Bi as MAX_CONTROL_HOURS,Oc as MAX_CONTROL_PLANE_ERROR_BYTES,Bp as MAX_CONTROL_PLANE_JSON_BYTES,Hs as METERS,kf as METER_KEYS,_f as MICRO_CENTS,Mp as MIN_PROJECTION_CONFIDENCE,Ru as MTA_STS_PORT,ga as MaintenanceService,pa as MaintenanceStore,Z as Messaging,Jg as MetricsManager,Yg as MigrationManager,Dg as MockCloudFormation,Ng as MockDynamoDB,Pg as MockS3,co as Monitoring,Fg as MultiAccountManager,Og as MultiRegionManager,PA as MultiStepProgress,f as Network,Om as NetworkSecurityManager,Ai as NotificationRouter,lg as ORIGIN_CONNECTION_ATTEMPTS,ug as ORIGIN_CONNECTION_TIMEOUT,cg as ORIGIN_GROUP_ALLOWED_METHODS,DI as ORIGIN_GROUP_ID_SUFFIX,dg as ORIGIN_GROUP_SELECTION_CRITERIA,Ua as OpenSearchClient,ct as OptimisticConcurrencyError,Ug as OrganizationManager,Wu as PAGES_MAX_FILE_BYTES,sy as PHP_DEFAULT_EXCLUDES,VA as PHP_LAYER_EXTENSIONS,lp as PROJECT_LABEL,rt as PROXIABLE_RECORD_TYPES,b as ParameterStore,em as PerformanceManager,Y as Permissions,Qa as PersonalizeClient,Ve as Phone,UA as PhoneAdvanced,rA as PhoneHandlers,ca as PlacementService,aa as PlacementStore,An as PollyClient,se as PorkbunProvider,Jr as PreDeployScanner,kg as PreviewEnvironmentManager,Dr as PreviewEnvironmentService,Qe as PreviewEnvironmentStore,Bg as PreviewNotificationService,DA as ProgressBar,Kg as ProgressiveDeploymentManager,To as ProtectionControlStore,yI as Pseudo,M as Queue,li as QueueCancellationError,wm as QueueManagementManager,hI as QueuePresets,$s as QueueTimeoutError,Vd as RATE_LIMIT_KEY_SEPARATOR,j as RDSClient,$A as RECOMMENDED_ACCOUNT_STRUCTURES,vC as RECOMMENDED_SCPS,Qm as RELEASE_QUEUE_KINDS,BA as REPL,OA as REPLCommandBuilder,_A as REPLContext,pp as ROLE_LABEL,wA as RateLimiter,fI as RealtimePresets,jp as RecordingSpendTransport,Io as RecursionGuard,gt as Redirects,$g as RegionPairManager,la as RegionService,da as RegionStore,Ge as Registry,bt as RekognitionClient,mt as ReleaseService,Oo as ReleaseStore,nh as RemoteBuildService,Zg as ReplicaManager,xm as ResourceManagementManager,X as RetryableOperationError,y as Route53Client,Ma as Route53DomainsClient,z as Route53Provider,ym as Route53ResolverManager,fm as Route53RoutingManager,ge as RuntimeOperationService,Vo as RuntimeStreamRegistry,Ia as S3BackupDestinationAdapter,o as S3Client,G as S3Error,Al as SECRET_PATTERNS,Gp as SENSITIVITY_THRESHOLDS,tt as SESClient,F as SMS,Ze as SNSClient,Yp as SPEND_CYCLE_SECONDS,sd as SPEND_GATE_SETTING,zf as SPEND_LEASE_SETTING,ne as SQSClient,Ee as SSH_BOOTSTRAP_VERSION,Vn as SSH_PREFLIGHT_SCRIPT,be as SSMClient,sg as STATE_DIR_ENV_VAR,Ha as STATIC_SITE_ZONE_SETTINGS,wd as STORAGE_FAILOVER_METADATA_KEY,me as STSClient,yn as SchedulerClient,qt as Search,Xr as SecretFindingScanner,vi as Secrets,nm as SecretsManager,V as SecretsManagerClient,rm as SecretsRotationManager,I as Security,Hr as SecurityHubManager,Wr as SecurityPostureStore,ht as SecurityScannerRunner,sm as SecurityScanningManager,Cm as SenderReputationManager,eh as ServerCronJobAdapter,Zo as ServerDataAdapter,Qs as ServerPathVolumeDriver,dm as ServiceMeshManager,Dd as Sftp,Js as SignalSource,QA as SmsAdvanced,Tt as SmsClient,nA as SmsHandlers,ja as SmsVoiceClient,xo as SourceConnectionStore,Kt as SourceProviderError,od as SpendCapError,Or as SpendGate,Jp as SpendLoopLease,to as SpendNotificationRouter,Xp as SpendRunner,Mt as SpendService,pi as SpendStore,NA as Spinner,Sr as SshDriver,en as SshFleetDriver,Mg as StackDependencyManager,NI as StacksIntegration,km as StaticSiteManager,ve as Storage,Bm as StorageAdvancedManager,In as SupportClient,Gr as SyntheticsManager,Ll as SystemFleetSshTransport,Ir as SystemSshTransport,qo as SystemdDiscoveryAdapter,yo as TRACE_HEADER,kA as TaskList,ut as TelemetryStore,Cd as TemplateBuilder,vg as TemplateCache,vt as TextractClient,mn as TranscribeClient,tr as TranslateClient,ah as TransportDisasterRecoveryDriver,oh as TransportPlatformMaintenanceDriver,qi as TransportRemoteBuildDriver,Qo as TrivyImageScanner,_o as TsCloudApiError,al as TsCloudClient,jf as URGENT_SPEND_EVENTS,Fp as USER_VISIBLE_ACTIONS,ua as UnavailableRegionalDriver,oe as UnifiedDnsValidator,Os as UnsupportedSchemaVersionError,Cg as ValidationError,ir as VoiceClient,Us as VolumeService,xt as VolumeStore,iA as Workflow,Wg as XRayManager,ZC as abTestManager,cl as activateImmutableRelease,Ou as addDns01ChallengeRecord,rn as addSiteToCloudConfig,At as ageSeconds,Kc as aggregateDeltas,Pp as allocateSitePorts,wI as analyzeStackDiff,hi as anomalyOptionsForSignal,wo as applyControlsToDdos,Jd as applyControlsToRateLimits,ms as applyDeclaredZoneSettings,Mr as applyMitigationFactor,of as applyPlan,ys as applyZoneMigration,Od as artifactKey,Qt as assertOriginGroupMethods,Li as assertReleaseStrategy,Hf as assertSpendAllows,uf as attachConflicts,pf as attachIsViable,lf as attachPreconditions,El as attachProvenanceToRelease,Ho as attachSbomToRelease,Sl as attachVulnerabilitySummary,Fm as authEncryptionKeyFile,w as authorizeOrganization,Ym as authorizeRuntimePath,eC as autocomplete,zC as awsConfigManager,cu as backupCredentialStatus,VC as backupManager,IS as batch,BE as batchProcessingManager,ko as beginOidcAuthorization,XC as blueGreenManager,wE as bounceComplaintHandler,dt as budgetWindow,xa as buildAndPushServerlessImage,xE as buildBunRuntimeLayerZip,yf as buildCertificatePackScript,hf as buildCertificateStateScript,If as buildCertificateUnpackScript,Nd as buildCloudFormationTemplate,hc as buildCloudInitFirstBoot,Mc as buildComposeLogsCommand,iI as buildComposeRuntimeCommand,sI as buildComposeScaleCommand,Fc as buildComposeShellCommand,wp as buildDrainSourceScript,Jh as buildDrainedSiteScanScript,Rd as buildFailoverReplicaPolicyStatement,Yt as buildFunctionEnv,Tp as buildHealthGateScript,Ln as buildHostCleanupDeployScript,Ts as buildHostCleanupInstallScript,xn as buildHostCleanupScript,ai as buildHostSitePortsScript,Sd as buildMailEnv,Ns as buildManagementDashboardArtifact,Xu as buildMediaCdnPlan,wu as buildMtaStsPolicy,Ph as buildMtaStsServer,OE as buildNodeRuntimeLayerZip,mE as buildOptimizationManager,pg as buildOriginGroup,Fr as buildOriginGroups,Ka as buildOriginGuardRule,yp as buildPauseWorkersScript,FE as buildPhpRuntimeLayerZip,fg as buildReplicationConfiguration,hg as buildReplicationRole,Ep as buildRestoreScript,K as buildRpxConfig,xe as buildRpxFragmentRefreshScript,cf as buildSetHostnameScript,Mn as buildSiteDeployScript,Cp as buildSnapshotScript,Rp as buildSourceStateScript,Bn as buildSshArgs,Gn as buildSshBootstrapScript,za as buildStaticSiteCacheRules,Un as buildStaticSiteDeployScript,bp as buildTargetStateScript,Ip as buildWorkersStateScript,vl as bytes,YC as canaryManager,tn as canonicalJson,ft as capabilities,Xt as capacity,DS as categorizeChanges,uE as certificateManager,Af as certificatesMatch,cS as checkIAMPermissions,XA as checkInvocation,lS as checkServiceQuotas,RA as chunk,ph as cleanupDns01Challenge,uI as clearSigningKeyCache,$o as cloneSourceBinding,kS as cloudConfigSchema,Yu as cloudDrivers,KC as cloudTrailManager,Wl as collectAssets,Co as collectPhpAppEntries,vu as collectServerDnsDomains,_p as completeComposeVolumeDeletion,Bo as completeOidcAuthorization,WI as composePresets,Ls as composeProjectName,Ld as composeServerlessAppTemplate,Wf as compositeSpendTransport,Ct as compressBackup,ay as config,_l as connectionGuidance,hE as containerRegistryManager,bf as controlPlaneDatabaseFile,kc as controlPlaneMigrations,$I as createApiBackendPreset,Uo as createApiV1Handler,fy as createAsgBuildDriver,du as createBackupQueueHandlers,ry as createCliHandler,k as createCloudDriver,mc as createCloudFrontPolicy,nS as createCredentialProvider,zI as createDashboardSite,HI as createDataPipelinePreset,Ol as createDataServiceQueueHandlers,Uc as createDeploymentQueueHandlers,T as createDnsProvider,hy as createEcsBuildDriver,ad as createEnforcementHandlers,Eg as createError,kd as createExistingStaticFullStackPreset,$l as createFleetQueueHandlers,LI as createFullStackAppPreset,Cs as createGoDaddyValidator,ME as createHandlers,ey as createHttpHandler,FI as createJamstackPreset,Bl as createJobQueueHandlers,VI as createLaravelPreset,GI as createMLApiPreset,ql as createMaintenanceQueueHandlers,Zu as createMediaAccessToken,UI as createMicroservicesPreset,$S as createMockAWS,_I as createNodeJsServerPreset,OI as createNodeJsServerlessPreset,as as createObjectStorageClient,Ss as createPorkbunValidator,JI as createPreset,Xf as createPresignedUrl,oI as createPresignedUrlAsync,ty as createQueueHandler,QI as createRealtimeAppPreset,Fl as createRegionQueueHandlers,Cl as createReleaseProvenance,ll as createReleaseQueueHandlers,gy as createRemoteBuildQueueHandlers,Es as createRoute53Validator,Xm as createRuntimeAdapters,iS as createS3Client,my as createServerBuildDriver,jI as createServerlessLaravelPreset,xI as createServerlessNodePreset,Eu as createSmsInfrastructure,We as createSourceAdapter,BI as createStaticSitePreset,qI as createTraditionalWebAppPreset,Qc as createVolumeQueueHandlers,MI as createWordPressPreset,Ri as createZip,cC as crossRegionReferenceManager,dn as dashboardActions,Ps as dashboardCredentialsFile,Zr as dataServiceCapabilities,cE as databaseUserManager,Yd as decodeBase32,ke as decompressBackup,Ah as decryptBackup,Ro as defaultConfig,Rg as defaultLocalConfig,zd as defaultRateLimitRules,cr as delegateZone,ps as delegateZoneFromConfig,iu as deleteFailoverReplicaBuckets,_a as deleteStaticSite,vc as deployAllComputeSites,fa as deployServerlessApp,su as deploySite,ks as deploySiteRelease,es as deployStaticSite,Oa as deployStaticSiteFull,ln as deployStaticSiteWithExternalDns,un as deployStaticSiteWithExternalDnsFull,yd as deploymentCoexistenceError,dA as deriveManagementDashboardPort,gs as describeDelegation,Wd as describePosture,hs as describeZoneSettings,Zm as desiredJobProviderState,Hp as detectAnomalies,og as detectDeploymentTargets,Wa as detectDnsProvider,rd as detectLatestAnomaly,oS as detectMisconfigurations,rg as detectServiceRegion,Lc as diffCompose,TS as diffTemplates,Lo as discoverGitRefs,No as discoverOidcProvider,Tl as discoverRuntimeInventory,kE as dlqMonitoringManager,Ja as dnsProviders,vE as dnssecManager,Km as dockerWorkloads,Vi as documentDigest,jC as drManager,$e as driverStatePath,wl as ecsWorkloads,Ot as effectiveCapabilities,RE as emailAnalyticsManager,PE as emailTemplateManager,_i as encodeBase32,fh as encryptBackup,bl as ensureDefaultSecurityPolicies,tu as ensureFailoverReplicaBuckets,Yn as ensureFirewall,ti as ensureManagementDashboard,Zn as ensureServer,Xn as ensureSshKey,J as escapeSecLang,Jc as evaluateBudget,zn as evaluatePreflight,eo as evaluateTelemetryAlertRules,kl as eventBridgeScheduleInput,ZA as eventToRequest,Ff as ewma,xc as exportCompose,fs as exportRoute53Zone,Sg as extendPreset,NE as fifoQueueManager,yS as findChangedFiles,xp as findMapping,Op as findPriceEntry,PC as formatAccountStructure,gf as formatAttachPlan,jS as formatBytes,Lr as formatCents,RI as formatDiff,Yh as formatDrainedSiteRefusal,zS as formatDuration,rC as formatFlagSuggestions,sC as formatHistory,oC as formatHistoryStats,rf as formatInventory,WS as formatKeyValue,KS as formatList,sf as formatPlan,Wn as formatPreflightFindings,VS as formatProgressBar,LA as formatRegion,SC as formatRegionList,qm as formatScanResults,JS as formatSuggestion,GS as formatTable,Br as formatTimeToExhaustion,qS as formatTree,mA as fromEC2Metadata,hA as fromECSMetadata,pA as fromEnvironment,gA as fromSharedCredentials,fA as fromWebIdentity,Md as functionFingerprint,Nn as gatewayHostnames,$d as generateAppImageDockerfile,GC as generateApprovalConfig,HA as generateBootstrap,US as generateCleanupWorkflow,QS as generateCostReportWorkflow,RC as generateCrossAccountRoleCF,yl as generateCycloneDxSbom,UC as generateDeploymentConfig,xC as generateDeploymentPipeline,NC as generateDeploymentWorkflow,Ba as generateExternalDnsStaticSiteTemplate,dh as generateHttpsServerCode,Il as generateImageSbom,lh as generateLetsEncryptUserData,t as generateLogicalId,FC as generateManualPipeline,OC as generateMatrixWorkflow,QC as generateMultiEnvConfig,LC as generateMultiEnvPipeline,kC as generateMultiEnvWorkflow,BC as generatePRPreviewWorkflow,qC as generateParallelConfig,ny as generatePhpFpmConfig,zA as generatePhpLayerDockerfile,$C as generatePreviewPipeline,FS as generatePreviewWorkflow,r as generateResourceName,HC as generateScheduledConfig,MC as generateScheduledPipeline,_C as generateScheduledWorkflow,Zi as generateStaticSiteTemplate,N as generateUbuntuAppCloudInit,IA as getAccountId,pC as getAllRegions,AC as getClosestRegion,nC as getCommandUsage,vf as getComposeTemplate,Lm as getConfig,YS as getContextualHelp,uo as getCredentials,PS as getDeploymentStrategy,NS as getDiffStats,wS as getDiffSummary,bA as getErrorDetails,_d as getLocalConfig,xS as getLocalCredentials,OS as getLocalEndpoint,LS as getLocalEnvVars,uS as getQuotaUsageSummary,wC as getRecommendedStructure,wi as getRegion,CC as getRegionStats,mC as getRegionsByCompliance,gC as getRegionsByLocation,hC as getRegionsByPricingTier,vA as getRequiredPermissions,pI as getSigningKeyCacheSize,Cu as getSmsInfrastructureStatus,II as getTimestamp,Eo as globMatches,Bs as globToRegex,dC as globalResourceManager,gi as governingLimitCents,ru as grantFailoverReplicaAccess,WC as guardDutyManager,ro as handleSpendRequest,Pn as hasAutoWwwVariant,Vt as hasManagementDashboardSite,Nc as hasProxyUpstream,mS as hashBuffer,hS as hashDirectory,Tg as hashFile,fS as hashManifest,wg as hashString,HE as healthCheckManager,Tn as hostAcceptsIpv6,Cn as hostCondition,Do as hotp,kr as hourBucket,Mf as hourBucketsBetween,gE as imageScanningManager,Ki as infraEnvFromOutputs,Ud as inspectInvocation,WA as installRecursionFetch,rs as invalidateCache,Pm as invocationContext,XS as isLikelyTypo,Rn as isLocalDatabase,_S as isLocalDevelopment,Ur as isManagementDashboardSiteName,or as isNameserverRegistrar,gI as isNodeCryptoAvailable,td as isOperationAllowed,Zs as isQuietHours,Td as isS3RestEndpoint,ni as isSafePattern,fd as isStateDirConfigured,Ad as isStatePath,$r as isValidCidr,fC as isValidRegion,ui as isValidTimeZone,mI as isWebCryptoAvailable,ar as isZoneHost,Yr as jobProviderCapability,os as keyMatchesFilters,IE as lambdaConcurrencyManager,EE as lambdaDLQManager,SE as lambdaDestinationsManager,AE as lambdaLayersManager,CE as lambdaVPCManager,yE as lambdaVersionsManager,Rl as lambdaWorkloads,Gd as laravelServerlessEnvDefaults,Rr as listComposeTemplates,Mi as listSourceReferences,Xd as loadCloudConfig,Ft as loadTelemetryPolicy,nE as logsManager,nd as lookbackHoursForSignal,Zf as mailEnabled,Id as mailFirewallPorts,sh as maintenanceWindowOpen,Yf as makeAWSRequest,cI as makeAWSRequestAsync,aI as makeAWSRequestOnce,Ig as managementDashboardSiteName,Ul as manifestDigest,Vr as matchTotpCounter,Ju as mediaObjectHeaders,zs as median,Up as medianAbsoluteDeviation,Xc as mergeDecisions,Qr as mergeInfrastructure,Lf as mergePriceBooks,zc as meterTelemetry,rE as metricsManager,Au as migrateObjectStorage,sE as migrationManager,EC as multiAccountManager,aC as multiRegionManager,mh as needsRenewal,GE as networkSecurityManager,yt as nextScheduleRuns,ye as normalizePublicIpv6,De as normalizeRuntimeStatus,Je as normalizeScheduleExpression,Hm as normalizeSourceEvent,Le as normalizeSshPublicKey,zp as normalizeTelemetryPolicy,oi as occupiedHostPorts,Fo as openApiDocument,Xs as optionsForSignal,bC as organizationManager,qd as packagePhpApp,qr as packageServerlessApp,Ic as pagesAssetHash,Gu as pagesDnsRecord,Bd as parallel,SS as parallelMap,CS as parallelWithRetry,ff as parseCertificateState,Fd as parseChain,wr as parseCompose,rI as parseComposeCatalog,zm as parseDockerInspect,pu as parseDotenv,Xh as parseDrainedSites,ci as parseHostSiteFragments,lI as parseJSONResponse,jn as parsePreflightFacts,Dp as parseSourceDrained,Wm as parseSystemdRecords,vp as parseTargetReady,Pc as parseUpstreamPort,Sp as parseWorkersPaused,dI as parseXMLResponse,Ii as pathTemplate,Rc as pendingSteps,js as percentOfLimit,aE as performanceManager,Rm as phpLayerBuildStage,jA as phpLayerPackages,Pi as phpRuntimeLayerAssets,nI as planComposeTemplateUpgrade,Yc as planEnforcement,fp as planIsDestructive,tg as planMitigation,af as planServerRename,Sf as planSiteMove,As as planZoneMigration,wt as policyTag,Kn as preflightFailed,MS as previewManager,HS as previewNotifications,It as previewSchedule,$f as previousBudgetWindow,Gs as priceUsage,Of as priceUsageLines,ef as probeHostRoutes,ac as probeOriginTls,vS as processInChunks,hl as processSourceWebhook,Qi as productionChangeReview,eE as progressiveDeploymentManager,Wc as projectSpend,Qd as propagationHeaders,La as providerEndpoint,Ql as publicKeyFingerprint,En as qualifyName,_E as queueManagementManager,AS as quickHash,jd as rateLimitHeaders,ki as rateLimitKey,Me as readDriverState,tf as reconcile,Tu as reconcileAddressRecords,Bu as reconcileCloudflareCdn,us as reconcileDeclaredRecords,py as reconcileJobObservation,Kr as reconcileSourceWebhook,Ui as recordDashboardHostPosture,dy as recordPreDeploySecretScan,ly as recordSkippedSecretScan,Hd as recursionBlockedResponse,Pe as redactRuntimeConfig,ld as redactTelemetryText,yi as redactTelemetryValue,sn as redeployServerlessApp,lC as regionPairManager,zr as releaseStrategyCapabilities,Um as releaseTrafficPlan,ri as reloadRpxGateway,ss as remapKey,Nu as removeDns01ChallengeRecord,nn as removeSiteFromCloudConfig,fl as removeSourceWebhook,Xa as removeStaleServerAddressRecords,$c as renderComposeTemplate,Ei as renderDdosInstallScript,md as renderNftablesRuleset,Hi as renderServerCron,gd as renderSysctlFile,wc as renderWafConfig,ii as renderWafInstallScript,Tc as renewRpxCertificates,oE as replicaManager,Jf as requestHash,RS as requiresReplacement,LE as resetRecursionRuntime,$E as resolveApp,p as resolveAppDatabase,df as resolveAttachTarget,Ke as resolveAuthEncryptionKey,le as resolveCloudProvider,Vu as resolveCloudflareCdnPlan,AA as resolveCredentials,Yi as resolveDashboardAction,bc as resolveDashboardAuth,lA as resolveDashboardDomain,uA as resolveDashboardDomains,ls as resolveDeclaredRecords,TI as resolveDeployBucketName,x as resolveDeploymentMode,$n as resolveExecStart,vd as resolveFailoverStatusCodes,cc as resolveHetznerApiToken,Ar as resolveHostCleanupConfig,bi as resolveMailService,KI as resolveManagementDashboardSite,Ti as resolveManagementDashboardSites,$a as resolveObjectStorage,Te as resolveOriginConnection,nf as resolvePlan,g as resolveProjectStackName,Tr as resolveProxyUpstreams,xd as resolveQueueNames,wf as resolveQueuedDeploymentCommand,zt as resolveQueues,KA as resolveRecursionConfig,yA as resolveRegion,re as resolveRuntimeInventory,Ut as resolveServerlessAppStackName,Ed as resolveServerlessArtifactBucketName,so as resolveServerlessAssetBucketName,ho as resolveServerlessRuntime,bI as resolveSiteBucketName,_s as resolveSiteDeployTarget,u as resolveSiteKind,EI as resolveSiteResourceName,CI as resolveSiteStackName,qn as resolveSshSettings,d as resolveStatePath,vI as resolveStorageBucketName,gg as resolveStorageFailover,kt as resolveUiSource,Sc as resolveZoneApex,qE as resourceManagementManager,Nm as responseToResult,Qp as robustZScore,_t as roleCapabilities,dl as rollbackImmutableRelease,on as rollbackServerlessApp,xf as roundCents,TE as route53ResolverManager,bE as route53RoutingManager,qp as routeMatches,gp as routesFromFragments,Ni as ruleMatches,GA as runBuildHooks,Zc as runEnforcement,So as runPhpBuildHooks,Xe as runRemoteCommand,pe as runtimeId,mg as s3RegionalDomain,bn as sameNameservers,Xi as sanitizeCloudConfig,s as sanitizeControlPlaneValue,SI as sanitizeName,nl as sanitizeOidcReturnPath,cd as saveTelemetryPolicy,Gm as scanForSecrets,Bc as scopeContains,lt as scopeKey,rc as scpUpload,ZS as searchCommands,xs as searchControlPlane,lE as secretsManager,dE as secretsRotationManager,uy as secureContainerRelease,JC as securityHubManager,pE as securityScanningManager,te as securityScope,nu as seedFailoverReplicas,jr as sendAuthenticationEmail,DE as senderReputationManager,ES as sequence,gu as serializeDotenv,ei as serverPublicIpv4,fE as serviceMeshManager,Xl as setAttachToInCloudConfig,Zt as setMaintenance,ji as setSitePropertyInCloudConfig,hd as setStateDir,uh as setupDns01Challenge,Va as setupSmsInfrastructure,mo as sha256,JA as sharedRecursionGuard,Dm as sharedRuntimeLoop,kp as shipsARelease,ju as signCloudFrontCookies,Ku as signCloudFrontUrl,_ as signRequest,ng as signRequestAsync,Ws as signalDefinition,B as siteInstallBase,si as siteMoveArchivePath,mf as siteMoveCertArchivePath,Dc as siteUnitGlob,Wp as spendNotificationText,no as spendOpenApiPaths,hr as sshExec,ce as sshExecOrThrow,uC as stackDependencyManager,ka as startLocalDashboardServer,Kf as startSpendLoop,io as stateDir,O as statePath,UE as staticSiteManager,QE as storageAdvancedManager,PI as storageFailoverReplicasFromTemplate,Uf as streamFocusJsonl,ed as strongestActiveAction,_g as suggestCommand,tC as suggestFlags,dS as suggestIAMPolicy,pS as suggestQuotaIncrease,IC as suggestRegionPairs,yC as suggestRegions,$i as syncSourceRepositories,Hc as synchronizeComposeVolumes,mu as synchronizeConfiguredConfiguration,zo as synchronizeConfiguredJobs,iE as syntheticsManager,pd as sysctlHardening,Jm as systemdWorkloads,Vf as telemetryBucketLabel,Si as telemetryCursor,dd as telemetryEstimatedMonthlyCost,qf as telemetryPercentile,Kp as telemetryPolicyKey,gS as templateCache,mp as tenantsOf,Mo as testSourceConnection,Gc as tieredMicroCents,oc as toCloudflareZoneSettings,Ys as toFocusJsonl,id as toFocusRecords,Zh as toInventoryServer,$m as totp,Po as totpUri,hp as unaccountedSites,jm as unsupportedCapabilities,Rf as unsupportedVolumeCapabilities,Gl as updateCompatibility,Vl as updateSiteInCloudConfig,ts as uploadStaticFiles,Lp as usageDeltaKey,$t as utcInstantOfLocal,DC as validateAccountStructure,BS as validateAgainstSchema,Pf as validateAttachment,hh as validateBackupDestination,iC as validateCommand,sS as validateConfiguration,aS as validateCredentials,Np as validateDeploymentConfig,Df as validateMountPath,Ht as validateOriginGroups,yu as validateResourceLimits,Ap as validateServerName,Kd as validateTemplate,hu as validateTemplateSize,Za as verifyAddressRecord,cy as verifyArtifactSignature,qu as verifyMediaAccessToken,Mm as verifyTotp,Hl as verifyUpdateSignature,Is as verifyZoneParity,Fs as volumeCapabilities,dp as wafEventTelemetry,nc as waitForCloudInit,_n as waitForSsh,Wt as webhookEndpoint,tS as withCDN,eS as withCache,ZI as withDatabase,YA as withInvocation,XI as withMonitoring,rS as withQueue,YI as withSecurity,bS as withTimeout,W as wrapCloudInitUserData,it as writeDriverState,tE as xrayManager,Ml as zeroCapacity,Qf as zeroFill,Vc as zoneOffsetMs,qs as zonedParts};
604
+ `}async function Ou(l,f,C){let b=`_acme-challenge.${f}`;if(await ku(l,f,b,C))return;let T=await l.createRecord(f,{name:b,type:"TXT",content:C,ttl:60});if(!T.success)throw Error(`Failed to create DNS challenge record: ${T.message}`)}async function Eu(l,f,C){let b=await l.deleteRecord(f,{name:`_acme-challenge.${f}`,type:"TXT",content:C});if(!b.success)console.warn(`Failed to delete DNS challenge record: ${b.message}`)}async function ku(l,f,C,b){try{let T=await l.listRecords(f,"TXT"),it=C.replace(/\.$/,"").toLowerCase();return(T.records??[]).some((Ce)=>Ce.name.replace(/\.$/,"").toLowerCase()===it&&Ce.content.replace(/^"|"$/g,"")===b)}catch{return!1}}function fc(l){let{hostedZoneId:f,dnsProvider:C,region:b="us-east-1"}=l;if(C)return w(C);if(f)return new K(b,f);throw Error("Either dnsProvider or hostedZoneId must be provided")}async function uh(l){await Ou(fc(l),l.domain,l.challengeValue)}async function ph(l){await Eu(fc(l),l.domain,l.challengeValue)}function mh(l){try{let{execSync:f}=Ue("node:child_process"),C=f(`openssl x509 -checkend 2592000 -noout -in ${l}/cert.pem`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return!1}catch{return!0}}import{createHash as gc,createSign as xu,generateKeyPairSync as hc}from"node:crypto";var yc={production:"https://acme-v02.api.letsencrypt.org/directory",staging:"https://acme-staging-v02.api.letsencrypt.org/directory"};class Lu{directoryUrl;email;accountKey;accountUrl=null;directory=null;nonce=null;constructor(l){this.directoryUrl=l.staging?yc.staging:yc.production,this.email=l.email,this.accountKey=l.accountKey||this.generateAccountKey()}generateAccountKey(){let{privateKey:l}=hc("ec",{namedCurve:"P-256"});return l.export({type:"pkcs8",format:"pem"})}async getDirectory(){if(this.directory)return this.directory;let l=await fetch(this.directoryUrl);if(!l.ok)throw Error(`Failed to fetch ACME directory: ${l.status}`);return this.directory=await l.json(),this.directory}async getNonce(){if(this.nonce){let b=this.nonce;return this.nonce=null,b}let l=await this.getDirectory(),C=(await fetch(l.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!C)throw Error("Failed to get nonce from ACME server");return C}getJwk(){let l=this.accountKey.split(`
605
+ `).filter((it)=>!it.startsWith("-----")).join(""),f=Buffer.from(l,"base64"),C=f.length-65,b=f.subarray(C+1,C+33),T=f.subarray(C+33,C+65);return{kty:"EC",crv:"P-256",x:this.base64UrlEncode(b),y:this.base64UrlEncode(T)}}getJwkThumbprint(){let l=this.getJwk(),f=JSON.stringify({crv:l.crv,kty:l.kty,x:l.x,y:l.y}),C=gc("sha256").update(f).digest();return this.base64UrlEncode(C)}base64UrlEncode(l){return(typeof l==="string"?Buffer.from(l):l).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async signPayload(l,f){let C=await this.getNonce(),b=this.getJwk(),T={alg:"ES256",nonce:C,url:l};if(this.accountUrl)T.kid=this.accountUrl;else T.jwk=b;let it=this.base64UrlEncode(JSON.stringify(T)),Ce=f===""?"":this.base64UrlEncode(JSON.stringify(f)),Se=`${it}.${Ce}`,ke=xu("SHA256");ke.update(Se);let Pt=ke.sign(this.accountKey),ot=Pt.subarray(4,4+Pt[3]),rr=4+Pt[3]+2,pr=Pt.subarray(rr,rr+Pt[rr-1]),gr=Buffer.alloc(32),Et=Buffer.alloc(32);ot.copy(gr,32-ot.length),pr.copy(Et,32-pr.length);let at=Buffer.concat([gr,Et]);return JSON.stringify({protected:it,payload:Ce,signature:this.base64UrlEncode(at)})}async acmeRequest(l,f){let C=await this.signPayload(l,f),b=await fetch(l,{method:"POST",headers:{"Content-Type":"application/jose+json"},body:C}),T=b.headers.get("replay-nonce");if(T)this.nonce=T;let it,Ce=b.headers.get("content-type");if(Ce?.includes("application/json")||Ce?.includes("application/problem+json"))it=await b.json();else it=await b.text();if(!b.ok)throw Error(`ACME request failed: ${JSON.stringify(it)}`);return{body:it,headers:b.headers}}async registerAccount(){let l=await this.getDirectory(),{body:f,headers:C}=await this.acmeRequest(l.newAccount,{termsOfServiceAgreed:!0,contact:[`mailto:${this.email}`]}),b=C.get("location");if(!b)throw Error("No account URL returned");return this.accountUrl=b,b}async createOrder(l){if(!this.accountUrl)await this.registerAccount();let f=await this.getDirectory(),{body:C,headers:b}=await this.acmeRequest(f.newOrder,{identifiers:l.map((it)=>({type:"dns",value:it}))}),T=b.get("location");if(!T)throw Error("No order URL returned");return{orderUrl:T,authorizations:C.authorizations,finalize:C.finalize}}async getAuthorization(l){let{body:f}=await this.acmeRequest(l,""),C=f.identifier.value,b=this.getJwkThumbprint(),T=f.challenges.filter((it)=>it.type==="http-01"||it.type==="dns-01").map((it)=>{let Ce=`${it.token}.${b}`;if(it.type==="http-01")return{type:"http-01",token:it.token,keyAuthorization:Ce,identifier:`/.well-known/acme-challenge/${it.token}`};else{let Se=this.base64UrlEncode(gc("sha256").update(Ce).digest());return{type:"dns-01",token:it.token,keyAuthorization:Ce,identifier:`_acme-challenge.${C}`,dnsValue:Se}}});return{domain:C,challenges:T}}async respondToChallenge(l){await this.acmeRequest(l,{})}async waitForAuthorization(l,f=30){for(let C=0;C<f;C++){let{body:b}=await this.acmeRequest(l,"");if(b.status==="valid")return;if(b.status==="invalid")throw Error(`Authorization failed: ${JSON.stringify(b)}`);await new Promise((T)=>setTimeout(T,2000))}throw Error("Authorization timed out")}generateCsr(l){let{privateKey:f}=hc("rsa",{modulusLength:2048}),C=f.export({type:"pkcs8",format:"pem"});return{csr:this.createSimpleCsr(l,f),privateKey:C}}createSimpleCsr(l,f){throw Error("CSR generation requires additional implementation. Consider using the shell-based certbot approach instead.")}async finalizeOrder(l,f){let{csr:C,privateKey:b}=this.generateCsr(f),{body:T}=await this.acmeRequest(l,{csr:this.base64UrlEncode(Buffer.from(C,"base64"))}),it=T.certificate;if(!it)throw Error("Certificate not immediately available - polling not implemented");let Se=await(await fetch(it)).text(),ke=Se.split(/(?=-----BEGIN CERTIFICATE-----)/g),Pt=ke[0],ot=ke.slice(1).join("");return{certificate:Pt,privateKey:b,chain:ot,fullchain:Se,expiresAt:new Date(Date.now()+7776000000)}}getAccountKey(){return this.accountKey}}var Dn=(l)=>l===void 0?void 0:l?"on":"off";function nc(l){let f={ssl:l.ssl,always_use_https:Dn(l.alwaysUseHttps),automatic_https_rewrites:Dn(l.automaticHttpsRewrites),min_tls_version:l.minTlsVersion,tls_1_3:Dn(l.tls13),brotli:Dn(l.brotli),http3:Dn(l.http3),"0rtt":Dn(l.zeroRtt),early_hints:Dn(l.earlyHints),browser_cache_ttl:l.browserCacheTtl,always_online:Dn(l.alwaysOnline),websockets:Dn(l.websockets),email_obfuscation:Dn(l.emailObfuscation)};if(l.hsts)f.security_header={strict_transport_security:{enabled:l.hsts.enabled,max_age:l.hsts.maxAge??31536000,include_subdomains:l.hsts.includeSubdomains??!1,preload:l.hsts.preload??!1,nosniff:l.hsts.noSniff??!0}};for(let C of Object.keys(f))if(f[C]===void 0)delete f[C];return{...f,...l.raw??{}}}var Aa={ssl:"strict",alwaysUseHttps:!0,automaticHttpsRewrites:!0,minTlsVersion:"1.2",tls13:!0,brotli:!0,http3:!0,earlyHints:!0,alwaysOnline:!0,emailObfuscation:!1,browserCacheTtl:0};import{connect as Fu}from"node:tls";async function oc(l){let{address:f,serverName:C,port:b=443,timeoutMs:T=5000}=l;return new Promise((it)=>{let Ce=!1,Se=(Pt)=>{if(Ce)return;Ce=!0;try{ke.destroy()}catch{}it(Pt)},ke=Fu({host:f,port:b,servername:C,rejectUnauthorized:!1,timeout:T});ke.once("secureConnect",()=>{if(ke.authorized){Se({reachable:!0,trusted:!0});return}Se({reachable:!0,trusted:!1,reason:ke.authorizationError?String(ke.authorizationError):"origin certificate is not trusted for this hostname"})}),ke.once("timeout",()=>{Se({reachable:!1,trusted:!1,reason:`no TLS handshake within ${T}ms`})}),ke.once("error",(Pt)=>{Se({reachable:!1,trusted:!1,reason:Pt.message})})})}function Mu(l,f){let C=f.replace(/\.$/,"").toLowerCase();return l.some((b)=>{let T=b.replace(/\.$/,"").toLowerCase();if(T===C)return!0;if(!T.startsWith("*."))return!1;let it=T.slice(2);if(!C.endsWith(`.${it}`))return!1;return!C.slice(0,C.length-it.length-1).includes(".")})}async function Bu(l){let{provider:f,zone:C,hosts:b,ipv4:T,ipv6:it,proxied:Ce=!0,settings:Se=Aa,cache:ke,originGuard:Pt,purge:ot=!0,ttl:rr=300,skipOriginProbe:pr=!1,skipEdgeCertificateCheck:gr=!1}=l,Et={records:[],settingsChanged:[],cacheRules:0,originGuard:!1,purged:!1,deferredProxy:[],warnings:[]};if(b.length===0)return Et;let at=[],se=Ce&&!gr?await f.listEdgeCertificateHosts(C):null;for(let N of b){let ct=Ce;if(ct&&se&&!Mu(se,N)){ct=!1;let xt=se.length===0?"the zone has no active edge certificate yet":`no active edge certificate covers it (${se.join(", ")})`;Et.deferredProxy.push({host:N,reason:xt}),Et.warnings.push(`${N}: publishing DNS-only — ${xt}. Proxying it would make Cloudflare terminate TLS with no certificate for the name, which fails the handshake outright rather than degrading. Universal SSL covers the apex and ONE level of subdomain, so a deeper name needs its own certificate; otherwise re-run the deploy once the certificate is active.`)}if(ct&&!pr){let xt=await oc({address:T,serverName:N});if(!xt.trusted){ct=!1;let Bt=xt.reason||"origin is not serving a trusted certificate";Et.deferredProxy.push({host:N,reason:Bt}),Et.warnings.push(`${N}: publishing DNS-only for now — the origin does not yet serve a certificate this proxy can verify (${Bt}). The origin issues certificates over HTTP-01, which needs the name to reach it directly; re-run the deploy once it has one and the record will be proxied.`)}}if(ct)at.push(N);let Nt=[{type:"A",content:T}];if(it&&Rn(N))Nt.push({type:"AAAA",content:it});for(let{type:xt,content:Bt}of Nt){let mr=await f.upsertRecord(C,{name:N,type:xt,content:Bt,ttl:rr,proxied:ct});if(mr.success)Et.records.push({host:N,type:xt,content:Bt,proxied:ct});else Et.warnings.push(`${N} ${xt} → ${Bt} failed: ${mr.message||"unknown provider error"}`)}}if(at.length===0){if(Ce)Et.warnings.push("No host is proxied yet, so zone settings, cache rules and purge were skipped — they only take effect through the proxy.");return Et}try{let N=nc(Se),ct=await f.applyZoneSettings(C,N);Et.settingsChanged=ct.changed;for(let Nt of ct.failed)Et.warnings.push(`zone setting '${Nt.id}' could not be applied: ${Nt.error}`)}catch(N){Et.warnings.push(`zone settings could not be read: ${N instanceof Error?N.message:String(N)}`)}let kt=Wa(at,ke);if(kt.length>0){let N=await f.putManagedPhaseRules(C,"http_request_cache_settings",kt);if(N.success)Et.cacheRules=kt.length;else Et.warnings.push(`cache rules could not be written: ${N.message}`)}if(Pt){let N=Ja(at,Pt.header,Pt.value);if(N.length>0){let ct=await f.putManagedPhaseRules(C,"http_request_late_transform",N);if(ct.success)Et.originGuard=!0;else Et.warnings.push(`origin guard header could not be written: ${ct.message}. `+"The gateway will reject requests that lack it — disable the guard or grant the token Transform Rules: Edit.")}}if(ot){if(Et.purged=await f.purgeCache(C,{hosts:at}),!Et.purged)Et.warnings.push("edge cache purge failed — new content may take until TTL expiry to appear.")}return Et}var _u=(l)=>process.env[l];function Cc(l,f){let C=l.replace(/\.$/,"").toLowerCase();if(f){let b=f.replace(/\.$/,"").toLowerCase();if(C===b||C.endsWith(`.${b}`))return b}return C.split(".").slice(-2).join(".")}function Vu(l,f={}){let C=f.env??_u,b=l.infrastructure?.compute?.proxy?.cdn,T=[];if(!b||b.provider!=="cloudflare")return{plan:null,errors:T};if(b.originDomain)T.push(`compute.proxy.cdn.originDomain (${b.originDomain}) is ignored for Cloudflare: the proxy forwards to the address in the record it fronts, `+"so no separate origin hostname is needed — and publishing one gives clients a documented way around the edge.");let it=C("CLOUDFLARE_API_TOKEN");if(!it)return T.push("CLOUDFLARE_API_TOKEN is not set — the Cloudflare CDN cannot be reconciled."),{plan:null,errors:T};let Ce=l.sites??{},Se=b.frontedHosts?.length?[...new Set(b.frontedHosts.map((pr)=>pr.toLowerCase()))]:Bn(Ce,{autoWww:l.infrastructure?.compute?.proxy?.autoWww!==!1});if(Se.length===0)return T.push("No hostnames to front — set compute.proxy.cdn.frontedHosts, or give a site a domain."),{plan:null,errors:T};let ke=l.infrastructure?.dns?.domain,Pt=new Set(Se.map((pr)=>Cc(pr,ke)));if(Pt.size>1)return T.push(`Fronted hosts span more than one zone (${[...Pt].join(", ")}). A Cloudflare zone is configured as a unit, so run one CDN config per zone.`),{plan:null,errors:T};let ot=b.cloudflare??{},rr=b.secret?{header:b.secretHeader??"X-Origin-Verify",value:b.secret}:void 0;return{plan:{zone:[...Pt][0],hosts:Se,apiToken:it,zoneId:ot.zoneId??C("CLOUDFLARE_ZONE_ID"),accountId:ot.accountId??C("CLOUDFLARE_ACCOUNT_ID"),proxied:ot.proxied!==!1,settings:ot.settings??Aa,cache:ot.cache,originGuard:rr,purge:ot.purgeOnDeploy!==!1,skipOriginProbe:ot.skipOriginProbe===!0},errors:T}}var Wu=26214400;var Hu=new Set(["/_headers","/_redirects","/_routes.json","/_worker.js"]);class Sc{name="cloudflare-pages";apiToken;accountId;constructor(l){if(!l.apiToken)throw Error("Cloudflare Pages needs an API token");if(!l.accountId)throw Error("Cloudflare Pages needs an account id");this.apiToken=l.apiToken,this.accountId=l.accountId}async request(l,f,C){return os(l,`/accounts/${this.accountId}${f}`,`Bearer ${this.apiToken}`,C)}async getProject(l){try{return await this.request("GET",`/pages/projects/${l}`)}catch(f){if(f instanceof Error&&/\b8000007\b|not found/i.test(f.message))return null;throw f}}async ensureProject(l,f="main"){let C=await this.getProject(l);if(C)return C;return this.request("POST","/pages/projects",{name:l,production_branch:f})}async uploadToken(l){return(await this.request("GET",`/pages/projects/${l}/upload-token`)).jwt}async missingHashes(l,f){let C=await os("POST","/pages/assets/check-missing",`Bearer ${l}`,{hashes:f});return new Set(C)}async upsertHashes(l,f){await os("POST","/pages/assets/upsert-hashes",`Bearer ${l}`,{hashes:f})}async uploadBatch(l,f){let C=f.map((b)=>({key:b.hash,value:b.base64,metadata:{contentType:zu(b.extension)},base64:!0}));await os("POST","/pages/assets/upload",`Bearer ${l}`,C)}async createDeployment(l,f,C){let b={};for(let it of f)b[it.path]=it.hash;let T=new FormData;if(T.append("manifest",JSON.stringify(b)),C)T.append("branch",C);return this.request("POST",`/pages/projects/${l}/deployments`,T)}async deployDirectory(l){let f=await Pc(l.directory);if(f.length===0)throw Error(`No files to deploy in ${l.directory}`);let C=await this.uploadToken(l.project),b=await this.missingHashes(C,f.map((ke)=>ke.hash)),T=f.filter((ke)=>b.has(ke.hash)),it=[];for(let ke=0;ke<T.length;ke+=100)it.push(T.slice(ke,ke+100));let Ce=0;for(let ke=0;ke<it.length;ke+=4){let Pt=it.slice(ke,ke+4);await Promise.all(Pt.map((ot)=>this.uploadBatch(C,ot))),Ce+=Pt.reduce((ot,rr)=>ot+rr.length,0),l.onProgress?.(Ce,T.length)}return await this.upsertHashes(C,f.map((ke)=>ke.hash)),{deployment:await this.createDeployment(l.project,f,l.branch),total:f.length,uploaded:T.length,uploadedBytes:T.reduce((ke,Pt)=>ke+Pt.size,0)}}async listCustomDomains(l){return(await this.request("GET",`/pages/projects/${l}/domains`)).map((C)=>C.name)}async attachCustomDomain(l,f){if((await this.listCustomDomains(l)).includes(f))return!1;return await this.request("POST",`/pages/projects/${l}/domains`,{name:f}),!0}}function Gu(l,f){return{type:"CNAME",name:l,value:f.endsWith(".pages.dev")?f:`${f}.pages.dev`,ttl:1,proxied:!0}}async function bc(l,f){let{blake3:C}=await import("./chunk-pwywwdq2.js").then((m)=>Jh(m.default,1));return(await C(l+f)).slice(0,32)}async function Pc(l){let{readdir:f}=await import("node:fs/promises"),{join:C,relative:b,sep:T}=await import("node:path"),it=[];async function Ce(Se){let ke=await f(Se,{withFileTypes:!0});for(let Pt of ke){let ot=C(Se,Pt.name);if(Pt.isDirectory()){await Ce(ot);continue}if(!Pt.isFile())continue;let rr=`/${b(l,ot).split(T).join("/")}`;if(Hu.has(rr))continue;let pr=await Bun.file(ot).bytes();if(pr.byteLength>26214400)throw Error(`${rr} is ${pr.byteLength} bytes, over the Cloudflare Pages limit of 26214400`);let gr=Buffer.from(pr).toString("base64"),Et=Pt.name.lastIndexOf("."),at=Et>0?Pt.name.slice(Et+1):"";it.push({path:rr,hash:await bc(gr,at),base64:gr,extension:at,size:pr.byteLength})}}return await Ce(l),it.sort((Se,ke)=>Se.path.localeCompare(ke.path)),it}function zu(l){return{html:"text/html; charset=utf-8",css:"text/css; charset=utf-8",js:"application/javascript; charset=utf-8",mjs:"application/javascript; charset=utf-8",json:"application/json; charset=utf-8",map:"application/json; charset=utf-8",xml:"application/xml; charset=utf-8",txt:"text/plain; charset=utf-8",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",pdf:"application/pdf",webmanifest:"application/manifest+json"}[l.toLowerCase()]||"application/octet-stream"}async function os(l,f,C,b){let T={Authorization:C},it;if(b instanceof FormData)it=b;else if(b!==void 0)T["Content-Type"]="application/json",it=JSON.stringify(b);let Ce=await fetch(`https://api.cloudflare.com/client/v4${f}`,{method:l,headers:T,body:it}),Se=await Ce.text(),ke;try{ke=JSON.parse(Se)}catch{throw Error(`Cloudflare Pages API returned ${Ce.status} with a non-JSON body: ${Se.slice(0,200)}`)}if(!ke.success){let Pt=(ke.errors??[]).map((ot)=>`${ot.code}: ${ot.message}`).join(", ");throw Error(`Cloudflare Pages API error (${Ce.status}): ${Pt||Se.slice(0,200)}`)}return ke.result}export{Jg as ABTestManager,ce as ACMClient,ur as ACMDnsValidator,yc as ACME_DIRECTORIES,Re as AI,dl as API_IDEMPOTENCY_TTL_MS,al as API_TOKEN_DEFAULT_TTL_MS,cl as API_TOKEN_MAX_TTL_MS,Qi as API_VERSION,le as AUTHORIZATION_CAPABILITIES,nl as AUTH_ACTION_TOKEN_TTL_MS,il as AUTH_MFA_CHALLENGE_TTL_MS,sl as AUTH_OIDC_TRANSACTION_TTL_MS,Ke as AUTH_SESSION_ABSOLUTE_TTL_MS,rl as AUTH_SESSION_IDLE_TTL_MS,vA as AWSAPIError,n as AWSClient,h as AWSCloudFormationClient,y as AWSCloudFrontClient,jg as AWSConfigManager,xI as AWS_PSEUDO_PARAMETERS,De as AWS_REGIONS,Lu as AcmeClient,$r as AlertEvaluator,yi as AlertStore,Js as AnomalyConfigStore,Bd as ApiGateway,i as ApiServiceError,Va as ApplicationAutoScalingClient,po as Arn,P as AssetHasher,Q as Auth,Li as AuthenticationStore,bi as AutomationApiService,$i as AutomationIdentityStore,Zo as AwsAuroraDataAdapter,ia as AwsAuroraTransport,Ea as AwsDatabaseBackupSource,fr as AwsDriver,ea as AwsElastiCacheDataAdapter,sa as AwsElastiCacheTransport,Km as AwsIamCapabilityScanner,Ra as AwsInfrastructureBackupSource,Yo as AwsRdsDataAdapter,na as AwsRdsTransport,ah as AwsRegionalDriver,Pa as AwsSecretsManagerConfigurationBackend,rg as AwsSpendTransport,Na as AwsSsmConfigurationBackend,Yi as BackupCoordinator,qg as BackupManager,Sa as BackupStore,Dm as BatchProcessingManager,yn as BedrockClient,An as BedrockRuntimeClient,fl as BitbucketSourceAdapter,Wg as BlueGreenManager,Em as BounceComplaintHandler,lm as BuildOptimizationManager,Ml as BunDockerRuntime,mu as BunDockerVolumeRuntime,gu as BunFilesystemArchiveRuntime,pe as CDN,Io as CHAIN_HEADER,us as CLOUDFLARE_MANAGED_RULE_PREFIX,wd as CLOUDFRONT_FAILOVER_STATUS_CODES,DC as COMMON_CROSS_ACCOUNT_ROLES,Qe as CONTROL_PLANE_SCHEMA_VERSION,lo as Cache,ho as CanaryManager,am as CertificateManager,_f as CloudBlockVolumeDriver,Ns as CloudDriverFactory,ze as CloudError,Sg as CloudFormationBuilder,h as CloudFormationClient,y as CloudFrontClient,zg as CloudTrailManager,fe as CloudWatchLogsClient,Sc as CloudflarePagesProvider,ye as CloudflareProvider,MA as CommandHistory,G as Communication,Br as ComposeApplicationService,Mt as ComposeApplicationStore,vt as ComprehendClient,a as Compute,ng as ComputeSpendTransport,mo as ConfigurationError,Ba as ConfigurationService,Da as ConfigurationStore,hn as ConnectClient,ra as ContainerDataAdapter,um as ContainerRegistryManager,wa as ControlPlaneBackupSource,fa as ControlPlaneCleanupDriver,ui as ControlPlaneStore,zs as CounterTracker,Kt as CredentialError,Mg as CrossRegionReferenceManager,dA as DASHBOARD_ENTRY,lA as DASHBOARD_PORT_BASE,uA as DASHBOARD_PORT_SPAN,cA as DASHBOARD_STATE_DIR,wo as DEFAULT_ATTACK_MODE_HOURS,md as DEFAULT_DDOS_THRESHOLDS,lg as DEFAULT_FAILOVER_STATUS_CODES,Wc as DEFAULT_METER_MAPPINGS,zc as DEFAULT_PRICE_BOOK,Ni as DEFAULT_RECURSION_LIMITS,Nn as DEFAULT_RPX_CERTS_DIR,V as DEFAULT_SERVICE_LIMITS,ag as DEFAULT_STATE_DIR,wu as DEFAULT_STATIC_ASSET_EXTENSIONS,iA as DEFAULT_STORAGE_FAILOVER_STATUS_CODES,jf as DEFAULT_TELEMETRY_POLICY,Up as DEFAULT_THRESHOLDS,Df as DEPLOYMENT_QUEUE_KINDS,yo as DEPTH_HEADER,Or as DETECTABLE_SIGNALS,_l as DIAGNOSTIC_PRESETS,Rm as DLQMonitoringManager,M as DNS,Sm as DNSSECManager,Vi as DataServiceLifecycle,Xo as DataServiceStore,Vt as Database,im as DatabaseUserManager,te as DebugLogger,nA as DependencyGraph,H as Deployment,bA as DeploymentError,Vg as DisasterRecoveryManager,wn as DnsProviderFactory,Yt as DockerDataTransport,Vo as DockerDiscoveryAdapter,kr as DockerNamedVolumeDriver,Ta as DockerVolumeBackupSource,c as DurableOperationQueue,Us as DurableQueueWorker,_e as DynamoDBClient,vr as EC2Client,xe as ECRClient,Ze as ECSClient,ar as EFSClient,Qa as ELBv2Client,Of as ENFORCEMENT_ACTIONS,fi as ENFORCEMENT_DESCRIPTIONS,D as ENFORCEMENT_SEVERITY,mp as ENVIRONMENT_LABEL,kl as EcsRuntimeAdapter,To as EdgeRateLimiter,tt as ElastiCacheClient,m as Email,QA as EmailAdvanced,bm as EmailAnalyticsManager,En as EmailClient,HA as EmailHandlers,Tm as EmailTemplateManager,oa as EncryptedDataSecretStore,TA as ErrorCodes,sr as EventBridgeClient,ih as EventBridgeJobAdapter,ka as ExternalConfigurationBackend,co as FAILOVER_REPLICA_POLICY_SID,wm as FIFOQueueManager,Kp as FOCUS_VERSION,wg as FileCache,Ve as FileSystem,ba as FilesystemBackupSource,ca as FleetService,aa as FleetStore,e as Fn,Al as GiteaSourceAdapter,ml as GithubSourceAdapter,hl as GitlabSourceAdapter,Fg as GlobalResourceManager,Oe as GoDaddyProvider,Kg as GuardDutyManager,dt as HOST_SITES_DIR,DA as HashCache,Lm as HealthCheckManager,Ge as HealthCheckRunner,Sr as HetznerClient,Ee as HetznerDriver,Ae as IAMClient,ec as IPV6_EXCLUDED_HOST_LABELS,dm as ImageScanningManager,Yl as InfrastructureGenerator,Lc as InvalidOperationTransitionError,mt as JobLoader,sh as JobProviderReconciler,Jo as JobService,Ko as JobStore,ir as KendraClient,ay as LARAVEL_SERVERLESS_BUILD_STEPS,E as LambdaClient,hm as LambdaConcurrencyManager,ym as LambdaDLQManager,fm as LambdaDestinationsManager,gm as LambdaLayersManager,Bl as LambdaRuntimeAdapter,Am as LambdaVPCManager,mm as LambdaVersionsManager,ln as LocalEncryptedConfigurationBackend,va as LogicalDatabaseBackupSource,em as LogsManager,zA as MANAGED_NODE_VERSIONS,vc as MANAGEMENT_DASHBOARD_SITE,Cg as MANAGEMENT_DASHBOARD_SITE_PREFIX,xi as MAX_CONTROL_HOURS,$c as MAX_CONTROL_PLANE_ERROR_BYTES,Op as MAX_CONTROL_PLANE_JSON_BYTES,qs as METERS,xf as METER_KEYS,Lf as MICRO_CENTS,Qp as MIN_PROJECTION_CONFIDENCE,Nu as MTA_STS_PORT,ha as MaintenanceService,ma as MaintenanceStore,ee as Messaging,Zg as MetricsManager,tm as MigrationManager,kg as MockCloudFormation,_g as MockDynamoDB,Bg as MockS3,uo as Monitoring,Hg as MultiAccountManager,$g as MultiRegionManager,BA as MultiStepProgress,A as Network,$m as NetworkSecurityManager,Ii as NotificationRouter,gg as ORIGIN_CONNECTION_ATTEMPTS,mg as ORIGIN_CONNECTION_TIMEOUT,ug as ORIGIN_GROUP_ALLOWED_METHODS,kI as ORIGIN_GROUP_ID_SUFFIX,pg as ORIGIN_GROUP_SELECTION_CRITERIA,Ha as OpenSearchClient,lt as OptimisticConcurrencyError,Gg as OrganizationManager,Wu as PAGES_MAX_FILE_BYTES,cy as PHP_DEFAULT_EXCLUDES,KA as PHP_LAYER_EXTENSIONS,gp as PROJECT_LABEL,nt as PROXIABLE_RECORD_TYPES,v as ParameterStore,nm as PerformanceManager,Z as Permissions,Ga as PersonalizeClient,je as Phone,GA as PhoneAdvanced,sA as PhoneHandlers,la as PlacementService,da as PlacementStore,In as PollyClient,oe as PorkbunProvider,Yr as PreDeployScanner,xg as PreviewEnvironmentManager,Nr as PreviewEnvironmentService,He as PreviewEnvironmentStore,Og as PreviewNotificationService,kA as ProgressBar,Xg as ProgressiveDeploymentManager,Ro as ProtectionControlStore,CI as Pseudo,F as Queue,pi as QueueCancellationError,Pm as QueueManagementManager,II as QueuePresets,Fs as QueueTimeoutError,Kd as RATE_LIMIT_KEY_SEPARATOR,z as RDSClient,UA as RECOMMENDED_ACCOUNT_STRUCTURES,RC as RECOMMENDED_SCPS,qm as RELEASE_QUEUE_KINDS,OA as REPL,$A as REPLCommandBuilder,LA as REPLContext,hp as ROLE_LABEL,PA as RateLimiter,SI as RealtimePresets,Wp as RecordingSpendTransport,Co as RecursionGuard,ht as Redirects,Ug as RegionPairManager,pa as RegionService,ua as RegionStore,qe as Registry,Tt as RekognitionClient,ft as ReleaseService,Lo as ReleaseStore,oh as RemoteBuildService,rm as ReplicaManager,Mm as ResourceManagementManager,Y as RetryableOperationError,I as Route53Client,Ua as Route53DomainsClient,K as Route53Provider,Cm as Route53ResolverManager,Im as Route53RoutingManager,me as RuntimeOperationService,zo as RuntimeStreamRegistry,Ca as S3BackupDestinationAdapter,o as S3Client,q as S3Error,Sl as SECRET_PATTERNS,jp as SENSITIVITY_THRESHOLDS,rt as SESClient,U as SMS,et as SNSClient,tg as SPEND_CYCLE_SECONDS,cd as SPEND_GATE_SETTING,Jf as SPEND_LEASE_SETTING,ie as SQSClient,be as SSH_BOOTSTRAP_VERSION,zn as SSH_PREFLIGHT_SCRIPT,ve as SSMClient,cg as STATE_DIR_ENV_VAR,Aa as STATIC_SITE_ZONE_SETTINGS,Pd as STORAGE_FAILOVER_METADATA_KEY,he as STSClient,Sn as SchedulerClient,jt as Search,Zr as SecretFindingScanner,wi as Secrets,om as SecretsManager,j as SecretsManagerClient,sm as SecretsRotationManager,S as Security,qr as SecurityHubManager,Xr as SecurityPostureStore,At as SecurityScannerRunner,cm as SecurityScanningManager,vm as SenderReputationManager,nh as ServerCronJobAdapter,ta as ServerDataAdapter,Gs as ServerPathVolumeDriver,pm as ServiceMeshManager,kd as Sftp,Ys as SignalSource,qA as SmsAdvanced,Rt as SmsClient,oA as SmsHandlers,Ka as SmsVoiceClient,$o as SourceConnectionStore,Jt as SourceProviderError,dd as SpendCapError,Lr as SpendGate,Zp as SpendLoopLease,no as SpendNotificationRouter,eg as SpendRunner,Ut as SpendService,mi as SpendStore,_A as Spinner,Er as SshDriver,rn as SshFleetDriver,Qg as StackDependencyManager,_I as StacksIntegration,xm as StaticSiteManager,Te as Storage,Om as StorageAdvancedManager,Cn as SupportClient,Vr as SyntheticsManager,Fl as SystemFleetSshTransport,Cr as SystemSshTransport,jo as SystemdDiscoveryAdapter,So as TRACE_HEADER,xA as TaskList,gt as TelemetryStore,vd as TemplateBuilder,Rg as TemplateCache,wt as TextractClient,fn as TranscribeClient,nr as TranslateClient,lh as TransportDisasterRecoveryDriver,dh as TransportPlatformMaintenanceDriver,ji as TransportRemoteBuildDriver,Go as TrivyImageScanner,Oo as TsCloudApiError,ll as TsCloudClient,Wf as URGENT_SPEND_EVENTS,Hp as USER_VISIBLE_ACTIONS,ga as UnavailableRegionalDriver,ae as UnifiedDnsValidator,Ls as UnsupportedSchemaVersionError,vg as ValidationError,or as VoiceClient,Hs as VolumeService,$t as VolumeStore,aA as Workflow,Yg as XRayManager,rE as abTestManager,ul as activateImmutableRelease,Ou as addDns01ChallengeRecord,sn as addSiteToCloudConfig,It as ageSeconds,Xc as aggregateDeltas,Bp as allocateSitePorts,PI as analyzeStackDiff,Ai as anomalyOptionsForSignal,Do as applyControlsToDdos,Zd as applyControlsToRateLimits,fs as applyDeclaredZoneSettings,Ur as applyMitigationFactor,df as applyPlan,Ss as applyZoneMigration,$d as artifactKey,Gt as assertOriginGroupMethods,Mi as assertReleaseStrategy,Vf as assertSpendAllows,mf as attachConflicts,hf as attachIsViable,gf as attachPreconditions,Tl as attachProvenanceToRelease,qo as attachSbomToRelease,bl as attachVulnerabilitySummary,Hm as authEncryptionKeyFile,R as authorizeOrganization,th as authorizeRuntimePath,nC as autocomplete,JC as awsConfigManager,uu as backupCredentialStatus,KC as backupManager,ES as batch,OE as batchProcessingManager,_o as beginOidcAuthorization,eE as blueGreenManager,PE as bounceComplaintHandler,ut as budgetWindow,$a as buildAndPushServerlessImage,ME as buildBunRuntimeLayerZip,Cf as buildCertificatePackScript,yf as buildCertificateStateScript,Ef as buildCertificateUnpackScript,_d as buildCloudFormationTemplate,Ac as buildCloudInitFirstBoot,Qc as buildComposeLogsCommand,aI as buildComposeRuntimeCommand,cI as buildComposeScaleCommand,Hc as buildComposeShellCommand,Pp as buildDrainSourceScript,Zh as buildDrainedSiteScanScript,Nd as buildFailoverReplicaPolicyStatement,er as buildFunctionEnv,Dp as buildHealthGateScript,Mn as buildHostCleanupDeployScript,Rs as buildHostCleanupInstallScript,$n as buildHostCleanupScript,di as buildHostSitePortsScript,bd as buildMailEnv,Bs as buildManagementDashboardArtifact,Yu as buildMediaCdnPlan,Pu as buildMtaStsPolicy,Bh as buildMtaStsServer,$E as buildNodeRuntimeLayerZip,AE as buildOptimizationManager,hg as buildOriginGroup,Qr as buildOriginGroups,Ja as buildOriginGuardRule,Cp as buildPauseWorkersScript,HE as buildPhpRuntimeLayerZip,Ig as buildReplicationConfiguration,yg as buildReplicationRole,Tp as buildRestoreScript,W as buildRpxConfig,Le as buildRpxFragmentRefreshScript,uf as buildSetHostnameScript,Qn as buildSiteDeployScript,vp as buildSnapshotScript,Np as buildSourceStateScript,xn as buildSshArgs,Vn as buildSshBootstrapScript,Wa as buildStaticSiteCacheRules,Hn as buildStaticSiteDeployScript,wp as buildTargetStateScript,Ep as buildWorkersStateScript,Rl as bytes,tE as canaryManager,nn as canonicalJson,yt as capabilities,Zt as capacity,kS as categorizeChanges,mE as certificateManager,Sf as certificatesMatch,uS as checkIAMPermissions,ey as checkInvocation,gS as checkServiceQuotas,NA as chunk,ph as cleanupDns01Challenge,mI as clearSigningKeyCache,Fo as cloneSourceBinding,xS as cloudConfigSchema,tp as cloudDrivers,XC as cloudTrailManager,Pc as collectAssets,bo as collectPhpAppEntries,Ru as collectServerDnsDomains,Lp as completeComposeVolumeDeletion,xo as completeOidcAuthorization,YI as composePresets,Ms as composeProjectName,Fd as composeServerlessAppTemplate,Yf as compositeSpendTransport,bt as compressBackup,ly as config,Ll as connectionGuidance,yE as containerRegistryManager,wf as controlPlaneDatabaseFile,xc as controlPlaneMigrations,UI as createApiBackendPreset,Ho as createApiV1Handler,Iy as createAsgBuildDriver,pu as createBackupQueueHandlers,sy as createCliHandler,B as createCloudDriver,mc as createCloudFrontPolicy,oS as createCredentialProvider,JI as createDashboardSite,VI as createDataPipelinePreset,$l as createDataServiceQueueHandlers,Gc as createDeploymentQueueHandlers,w as createDnsProvider,yy as createEcsBuildDriver,ld as createEnforcementHandlers,Tg as createError,xd as createExistingStaticFullStackPreset,Ul as createFleetQueueHandlers,FI as createFullStackAppPreset,bs as createGoDaddyValidator,QE as createHandlers,ny as createHttpHandler,HI as createJamstackPreset,Ol as createJobQueueHandlers,KI as createLaravelPreset,jI as createMLApiPreset,zl as createMaintenanceQueueHandlers,Zu as createMediaAccessToken,GI as createMicroservicesPreset,US as createMockAWS,LI as createNodeJsServerPreset,$I as createNodeJsServerlessPreset,ds as createObjectStorageClient,Es as createPorkbunValidator,ZI as createPreset,eA as createPresignedUrl,dI as createPresignedUrlAsync,iy as createQueueHandler,qI as createRealtimeAppPreset,Hl as createRegionQueueHandlers,vl as createReleaseProvenance,gl as createReleaseQueueHandlers,fy as createRemoteBuildQueueHandlers,vs as createRoute53Validator,eh as createRuntimeAdapters,aS as createS3Client,Ay as createServerBuildDriver,WI as createServerlessLaravelPreset,MI as createServerlessNodePreset,Tu as createSmsInfrastructure,Je as createSourceAdapter,OI as createStaticSitePreset,zI as createTraditionalWebAppPreset,qc as createVolumeQueueHandlers,QI as createWordPressPreset,Pi as createZip,uC as crossRegionReferenceManager,un as dashboardActions,ks as dashboardCredentialsFile,tn as dataServiceCapabilities,uE as databaseUserManager,tl as decodeBase32,Be as decompressBackup,Sh as decryptBackup,Po as defaultConfig,Ng as defaultLocalConfig,Jd as defaultRateLimitRules,lr as delegateZone,ms as delegateZoneFromConfig,au as deleteFailoverReplicaBuckets,Oa as deleteStaticSite,wc as deployAllComputeSites,ya as deployServerlessApp,cu as deploySite,_s as deploySiteRelease,rs as deployStaticSite,La as deployStaticSiteFull,pn as deployStaticSiteWithExternalDns,gn as deployStaticSiteWithExternalDnsFull,Cd as deploymentCoexistenceError,pA as deriveManagementDashboardPort,hs as describeDelegation,Yd as describePosture,As as describeZoneSettings,rh as desiredJobProviderState,Vp as detectAnomalies,dg as detectDeploymentTargets,Xa as detectDnsProvider,sd as detectLatestAnomaly,dS as detectMisconfigurations,sg as detectServiceRegion,Fc as diffCompose,DS as diffTemplates,Mo as discoverGitRefs,Bo as discoverOidcProvider,Dl as discoverRuntimeInventory,xE as dlqMonitoringManager,Ya as dnsProviders,RE as dnssecManager,Xm as dockerWorkloads,zi as documentDigest,WC as drManager,Me as driverStatePath,Pl as ecsWorkloads,Lt as effectiveCapabilities,NE as emailAnalyticsManager,BE as emailTemplateManager,Oi as encodeBase32,Ih as encryptBackup,wl as ensureDefaultSecurityPolicies,iu as ensureFailoverReplicaBuckets,ei as ensureFirewall,ni as ensureManagementDashboard,ti as ensureServer,Zn as ensureSshKey,X as escapeSecLang,Zc as evaluateBudget,Wn as evaluatePreflight,ro as evaluateTelemetryAlertRules,xl as eventBridgeScheduleInput,ry as eventToRequest,Hf as ewma,Mc as exportCompose,ys as exportRoute53Zone,bg as extendPreset,_E as fifoQueueManager,CS as findChangedFiles,Mp as findMapping,$p as findPriceEntry,BC as formatAccountStructure,ff as formatAttachPlan,WS as formatBytes,Mr as formatCents,NI as formatDiff,tf as formatDrainedSiteRefusal,JS as formatDuration,sC as formatFlagSuggestions,cC as formatHistory,dC as formatHistoryStats,of as formatInventory,YS as formatKeyValue,XS as formatList,cf as formatPlan,Xn as formatPreflightFindings,KS as formatProgressBar,FA as formatRegion,bC as formatRegionList,zm as formatScanResults,ZS as formatSuggestion,jS as formatTable,xr as formatTimeToExhaustion,zS as formatTree,AA as fromEC2Metadata,yA as fromECSMetadata,hA as fromEnvironment,fA as fromSharedCredentials,IA as fromWebIdentity,Qd as functionFingerprint,Bn as gatewayHostnames,Ud as generateAppImageDockerfile,jC as generateApprovalConfig,VA as generateBootstrap,GS as generateCleanupWorkflow,qS as generateCostReportWorkflow,NC as generateCrossAccountRoleCF,Cl as generateCycloneDxSbom,GC as generateDeploymentConfig,MC as generateDeploymentPipeline,_C as generateDeploymentWorkflow,xa as generateExternalDnsStaticSiteTemplate,vf as generateHttpsServerCode,El as generateImageSbom,Tf as generateLetsEncryptUserData,t as generateLogicalId,HC as generateManualPipeline,$C as generateMatrixWorkflow,qC as generateMultiEnvConfig,FC as generateMultiEnvPipeline,xC as generateMultiEnvWorkflow,OC as generatePRPreviewWorkflow,zC as generateParallelConfig,oy as generatePhpFpmConfig,JA as generatePhpLayerDockerfile,UC as generatePreviewPipeline,HS as generatePreviewWorkflow,r as generateResourceName,VC as generateScheduledConfig,QC as generateScheduledPipeline,LC as generateScheduledWorkflow,ts as generateStaticSiteTemplate,k as generateUbuntuAppCloudInit,EA as getAccountId,hC as getAllRegions,SC as getClosestRegion,oC as getCommandUsage,Rf as getComposeTemplate,Fm as getConfig,tC as getContextualHelp,go as getCredentials,BS as getDeploymentStrategy,_S as getDiffStats,PS as getDiffSummary,wA as getErrorDetails,Ld as getLocalConfig,MS as getLocalCredentials,$S as getLocalEndpoint,FS as getLocalEnvVars,mS as getQuotaUsageSummary,PC as getRecommendedStructure,Di as getRegion,vC as getRegionStats,AC as getRegionsByCompliance,fC as getRegionsByLocation,yC as getRegionsByPricingTier,RA as getRequiredPermissions,hI as getSigningKeyCacheSize,vu as getSmsInfrastructureStatus,EI as getTimestamp,vo as globMatches,xs as globToRegex,pC as globalResourceManager,hi as governingLimitCents,su as grantFailoverReplicaAccess,YC as guardDutyManager,io as handleSpendRequest,kn as hasAutoWwwVariant,zt as hasManagementDashboardSite,_c as hasProxyUpstream,AS as hashBuffer,yS as hashDirectory,Dg as hashFile,IS as hashManifest,Pg as hashString,VE as healthCheckManager,Rn as hostAcceptsIpv6,bn as hostCondition,No as hotp,_r as hourBucket,Qf as hourBucketsBetween,fE as imageScanningManager,Ji as infraEnvFromOutputs,Gd as inspectInvocation,YA as installRecursionFetch,is as invalidateCache,Bm as invocationContext,eC as isLikelyTypo,Pn as isLocalDatabase,LS as isLocalDevelopment,Hr as isManagementDashboardSiteName,cr as isNameserverRegistrar,fI as isNodeCryptoAvailable,id as isOperationAllowed,to as isQuietHours,Dd as isS3RestEndpoint,si as isSafePattern,Id as isStateDirConfigured,Sd as isStatePath,Fr as isValidCidr,IC as isValidRegion,gi as isValidTimeZone,yI as isWebCryptoAvailable,dr as isZoneHost,en as jobProviderCapability,cs as keyMatchesFilters,EE as lambdaConcurrencyManager,TE as lambdaDLQManager,bE as lambdaDestinationsManager,SE as lambdaLayersManager,vE as lambdaVPCManager,CE as lambdaVersionsManager,Nl as lambdaWorkloads,jd as laravelServerlessEnvDefaults,Pr as listComposeTemplates,Ui as listSourceReferences,el as loadCloudConfig,Qt as loadTelemetryPolicy,oE as logsManager,od as lookbackHoursForSignal,rA as mailEnabled,Ed as mailFirewallPorts,ch as maintenanceWindowOpen,tA as makeAWSRequest,uI as makeAWSRequestAsync,lI as makeAWSRequestOnce,Eg as managementDashboardSiteName,Gl as manifestDigest,zr as matchTotpCounter,Ju as mediaObjectHeaders,Ws as median,Gp as medianAbsoluteDeviation,ed as mergeDecisions,Gr as mergeInfrastructure,Ff as mergePriceBooks,Jc as meterTelemetry,sE as metricsManager,Su as migrateObjectStorage,cE as migrationManager,TC as multiAccountManager,lC as multiRegionManager,mh as needsRenewal,jE as networkSecurityManager,St as nextScheduleRuns,Ie as normalizePublicIpv6,Pe as normalizeRuntimeStatus,Xe as normalizeScheduleExpression,Vm as normalizeSourceEvent,$e as normalizeSshPublicKey,Jp as normalizeTelemetryPolicy,ci as occupiedHostPorts,Qo as openApiDocument,Zs as optionsForSignal,wC as organizationManager,zd as packagePhpApp,jr as packageServerlessApp,bc as pagesAssetHash,Gu as pagesDnsRecord,Od as parallel,bS as parallelMap,vS as parallelWithRetry,If as parseCertificateState,Hd as parseChain,Dr as parseCompose,sI as parseComposeCatalog,Jm as parseDockerInspect,hu as parseDotenv,ef as parseDrainedSites,li as parseHostSiteFragments,gI as parseJSONResponse,Kn as parsePreflightFacts,kp as parseSourceDrained,Ym as parseSystemdRecords,Rp as parseTargetReady,Bc as parseUpstreamPort,bp as parseWorkersPaused,pI as parseXMLResponse,Ci as pathTemplate,Nc as pendingSteps,Ks as percentOfLimit,lE as performanceManager,Nm as phpLayerBuildStage,WA as phpLayerPackages,ki as phpRuntimeLayerAssets,oI as planComposeTemplateUpgrade,td as planEnforcement,Ip as planIsDestructive,ig as planMitigation,lf as planServerRename,bf as planSiteMove,Is as planZoneMigration,Dt as policyTag,Jn as preflightFailed,QS as previewManager,VS as previewNotifications,Ct as previewSchedule,Uf as previousBudgetWindow,Vs as priceUsage,$f as priceUsageLines,nf as probeHostRoutes,oc as probeOriginTls,RS as processInChunks,yl as processSourceWebhook,Gi as productionChangeReview,nE as progressiveDeploymentManager,Yc as projectSpend,qd as propagationHeaders,Ma as providerEndpoint,ql as publicKeyFingerprint,vn as qualifyName,LE as queueManagementManager,SS as quickHash,Wd as rateLimitHeaders,_i as rateLimitKey,Fe as readDriverState,sf as reconcile,Du as reconcileAddressRecords,Bu as reconcileCloudflareCdn,gs as reconcileDeclaredRecords,hy as reconcileJobObservation,Jr as reconcileSourceWebhook,Hi as recordDashboardHostPosture,py as recordPreDeploySecretScan,gy as recordSkippedSecretScan,Vd as recursionBlockedResponse,Ne as redactRuntimeConfig,gd as redactTelemetryText,Si as redactTelemetryValue,an as redeployServerlessApp,gC as regionPairManager,Wr as releaseStrategyCapabilities,Gm as releaseTrafficPlan,ii as reloadRpxGateway,as as remapKey,Eu as removeDns01ChallengeRecord,on as removeSiteFromCloudConfig,Il as removeSourceWebhook,Za as removeStaleServerAddressRecords,Uc as renderComposeTemplate,vi as renderDdosInstallScript,Ad as renderNftablesRuleset,qi as renderServerCron,fd as renderSysctlFile,Dc as renderWafConfig,oi as renderWafInstallScript,Rc as renewRpxCertificates,dE as replicaManager,Zf as requestHash,NS as requiresReplacement,FE as resetRecursionRuntime,UE as resolveApp,p as resolveAppDatabase,pf as resolveAttachTarget,We as resolveAuthEncryptionKey,ue as resolveCloudProvider,Vu as resolveCloudflareCdnPlan,SA as resolveCredentials,es as resolveDashboardAction,Tc as resolveDashboardAuth,gA as resolveDashboardDomain,mA as resolveDashboardDomains,ps as resolveDeclaredRecords,DI as resolveDeployBucketName,L as resolveDeploymentMode,Un as resolveExecStart,Rd as resolveFailoverStatusCodes,lc as resolveHetznerApiToken,Ir as resolveHostCleanupConfig,Ti as resolveMailService,XI as resolveManagementDashboardSite,Ri as resolveManagementDashboardSites,Fa as resolveObjectStorage,we as resolveOriginConnection,af as resolvePlan,g as resolveProjectStackName,Rr as resolveProxyUpstreams,Md as resolveQueueNames,Pf as resolveQueuedDeploymentCommand,Wt as resolveQueues,XA as resolveRecursionConfig,CA as resolveRegion,ne as resolveRuntimeInventory,Ht as resolveServerlessAppStackName,Td as resolveServerlessArtifactBucketName,ao as resolveServerlessAssetBucketName,Ao as resolveServerlessRuntime,wI as resolveSiteBucketName,Os as resolveSiteDeployTarget,u as resolveSiteKind,TI as resolveSiteResourceName,vI as resolveSiteStackName,jn as resolveSshSettings,d as resolveStatePath,RI as resolveStorageBucketName,fg as resolveStorageFailover,_t as resolveUiSource,Cc as resolveZoneApex,zE as resourceManagementManager,_m as responseToResult,qp as robustZScore,Ot as roleCapabilities,pl as rollbackImmutableRelease,cn as rollbackServerlessApp,Mf as roundCents,DE as route53ResolverManager,wE as route53RoutingManager,zp as routeMatches,fp as routesFromFragments,Bi as ruleMatches,jA as runBuildHooks,rd as runEnforcement,Eo as runPhpBuildHooks,Ye as runRemoteCommand,ge as runtimeId,Ag as s3RegionalDomain,Tn as sameNameservers,Zi as sanitizeCloudConfig,s as sanitizeControlPlaneValue,bI as sanitizeName,ol as sanitizeOidcReturnPath,ud as saveTelemetryPolicy,jm as scanForSecrets,Oc as scopeContains,pt as scopeKey,ic as scpUpload,rC as searchCommands,$s as searchControlPlane,gE as secretsManager,pE as secretsRotationManager,my as secureContainerRelease,ZC as securityHubManager,hE as securityScanningManager,re as securityScope,ou as seedFailoverReplicas,Kr as sendAuthenticationEmail,kE as senderReputationManager,TS as sequence,fu as serializeDotenv,ri as serverPublicIpv4,IE as serviceMeshManager,eu as setAttachToInCloudConfig,tr as setMaintenance,Ki as setSitePropertyInCloudConfig,yd as setStateDir,uh as setupDns01Challenge,za as setupSmsInfrastructure,fo as sha256,ZA as sharedRecursionGuard,km as sharedRuntimeLoop,xp as shipsARelease,ju as signCloudFrontCookies,Ku as signCloudFrontUrl,x as signRequest,og as signRequestAsync,Xs as signalDefinition,_ as siteInstallBase,ai as siteMoveArchivePath,Af as siteMoveCertArchivePath,kc as siteUnitGlob,Yp as spendNotificationText,so as spendOpenApiPaths,Ar as sshExec,de as sshExecOrThrow,mC as stackDependencyManager,_a as startLocalDashboardServer,Xf as startSpendLoop,oo as stateDir,O as statePath,GE as staticSiteManager,qE as storageAdvancedManager,BI as storageFailoverReplicasFromTemplate,Gf as streamFocusJsonl,nd as strongestActiveAction,Lg as suggestCommand,iC as suggestFlags,pS as suggestIAMPolicy,hS as suggestQuotaIncrease,EC as suggestRegionPairs,CC as suggestRegions,Fi as syncSourceRepositories,Vc as synchronizeComposeVolumes,Au as synchronizeConfiguredConfiguration,Wo as synchronizeConfiguredJobs,aE as syntheticsManager,hd as sysctlHardening,Zm as systemdWorkloads,Kf as telemetryBucketLabel,Ei as telemetryCursor,pd as telemetryEstimatedMonthlyCost,zf as telemetryPercentile,Xp as telemetryPolicyKey,fS as templateCache,Ap as tenantsOf,Uo as testSourceConnection,jc as tieredMicroCents,nc as toCloudflareZoneSettings,eo as toFocusJsonl,ad as toFocusRecords,rf as toInventoryServer,Um as totp,ko as totpUri,yp as unaccountedSites,Wm as unsupportedCapabilities,Nf as unsupportedVolumeCapabilities,jl as updateCompatibility,Kl as updateSiteInCloudConfig,ns as uploadStaticFiles,Fp as usageDeltaKey,Ft as utcInstantOfLocal,kC as validateAccountStructure,OS as validateAgainstSchema,Bf as validateAttachment,yh as validateBackupDestination,aC as validateCommand,cS as validateConfiguration,lS as validateCredentials,_p as validateDeploymentConfig,kf as validateMountPath,qt as validateOriginGroups,du as validateResourceLimits,Sp as validateServerName,Xl as validateTemplate,lu as validateTemplateSize,tc as verifyAddressRecord,uy as verifyArtifactSignature,qu as verifyMediaAccessToken,Qm as verifyTotp,Vl as verifyUpdateSignature,Cs as verifyZoneParity,Qs as volumeCapabilities,pp as wafEventTelemetry,sc as waitForCloudInit,On as waitForSsh,Xt as webhookEndpoint,iS as withCDN,nS as withCache,rS as withDatabase,ty as withInvocation,eS as withMonitoring,sS as withQueue,tS as withSecurity,wS as withTimeout,J as wrapCloudInitUserData,st as writeDriverState,iE as xrayManager,Ql as zeroCapacity,qf as zeroFill,Kc as zoneOffsetMs,js as zonedParts};