@stacksjs/ts-cloud 0.12.11 → 0.12.13

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 (237) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/chunk-0vsxpmfj.js +3 -0
  3. package/dist/bin/chunk-12e9v1dw.js +3 -0
  4. package/dist/bin/chunk-13dhcjjb.js +60 -0
  5. package/dist/bin/chunk-1fj5gk6r.js +725 -0
  6. package/dist/bin/chunk-1j2sja1j.js +1 -0
  7. package/dist/bin/chunk-1s4dny8d.js +1 -0
  8. package/dist/bin/chunk-2hpnd4g4.js +1 -0
  9. package/dist/bin/chunk-49sthm4q.js +2 -0
  10. package/dist/bin/chunk-4yntpqbe.js +1 -0
  11. package/dist/bin/chunk-4zbnwt9b.js +2 -0
  12. package/dist/bin/chunk-55kmbzr5.js +1 -0
  13. package/dist/{chunk-2ybcnrte.js → bin/chunk-57w9nsjk.js} +3 -3
  14. package/dist/bin/chunk-5gehfky4.js +2 -0
  15. package/dist/bin/chunk-6xw0r4gn.js +7364 -0
  16. package/dist/bin/chunk-6zk2n3wk.js +511 -0
  17. package/dist/bin/{chunk-2pevjm25.js → chunk-7a7n6p2m.js} +2 -2
  18. package/dist/bin/chunk-7h6h8yxm.js +6 -0
  19. package/dist/bin/chunk-7x0hrna6.js +1 -0
  20. package/dist/bin/{chunk-bj4ft4qc.js → chunk-80zkjpfz.js} +29 -29
  21. package/dist/bin/chunk-84tvv3x1.js +1 -0
  22. package/dist/bin/chunk-94cfdvrn.js +2 -0
  23. package/dist/bin/chunk-96xtj5j6.js +1 -0
  24. package/dist/bin/chunk-9jfjzycs.js +111 -0
  25. package/dist/bin/{chunk-mhrtx0p1.js → chunk-bckm6fre.js} +6 -6
  26. package/dist/bin/chunk-bnv8yd9w.js +6 -0
  27. package/dist/bin/chunk-c51xp8f7.js +1 -0
  28. package/dist/bin/chunk-d5qhwtkg.js +9 -0
  29. package/dist/bin/chunk-d7r6mhyv.js +34 -0
  30. package/dist/bin/chunk-de88yqwy.js +1 -0
  31. package/dist/bin/chunk-dh2qmxw9.js +1 -0
  32. package/dist/bin/chunk-dhxwmkhz.js +2 -0
  33. package/dist/bin/chunk-f35pte64.js +44 -0
  34. package/dist/bin/{chunk-3g80gjw6.js → chunk-gj5jkhfr.js} +13 -13
  35. package/dist/bin/chunk-jcyrm5q0.js +2 -0
  36. package/dist/bin/chunk-jh1593zx.js +1 -0
  37. package/dist/bin/chunk-nnkhrm4n.js +8 -0
  38. package/dist/bin/chunk-p36ns96s.js +1 -0
  39. package/dist/bin/{chunk-dep2n31v.js → chunk-p9hd27k4.js} +8 -8
  40. package/dist/bin/chunk-qz3za76g.js +1 -0
  41. package/dist/bin/chunk-r6cvc2pr.js +1 -0
  42. package/dist/bin/chunk-rh2sqtew.js +1 -0
  43. package/dist/bin/chunk-rxwecjgc.js +1 -0
  44. package/dist/bin/chunk-tkzpbb7n.js +1 -0
  45. package/dist/bin/chunk-vx649y7t.js +1 -0
  46. package/dist/bin/chunk-vymg9ywg.js +2 -0
  47. package/dist/bin/chunk-w7k5rvmw.js +1 -0
  48. package/dist/bin/chunk-wge61ccr.js +2 -0
  49. package/dist/bin/chunk-wvhqjr80.js +2 -0
  50. package/dist/bin/chunk-x5x9dzk7.js +3 -0
  51. package/dist/bin/chunk-xaafj6kf.js +1 -0
  52. package/dist/bin/chunk-xgepx8yx.js +1 -0
  53. package/dist/bin/{chunk-48eb4z0c.js → chunk-yhxpmk29.js} +32 -32
  54. package/dist/bin/chunk-ymbwekjm.js +1 -0
  55. package/dist/bin/chunk-yn34zgr2.js +1 -0
  56. package/dist/bin/chunk-ynr22ma8.js +2 -0
  57. package/dist/bin/chunk-yt8rgkqt.js +2 -0
  58. package/dist/bin/chunk-z2ez8wn9.js +37 -0
  59. package/dist/bin/cli.js +428 -428
  60. package/dist/bin/dashboard-server.js +1 -1
  61. package/dist/chunk-13d54txj.js +44 -0
  62. package/dist/chunk-1kp3y2s7.js +1 -0
  63. package/dist/chunk-1n3ckctd.js +7355 -0
  64. package/dist/chunk-30h9rgfn.js +6 -0
  65. package/dist/chunk-3kapcdpn.js +92 -0
  66. package/dist/chunk-3qp10j0j.js +5 -0
  67. package/dist/chunk-6g81m01r.js +141 -0
  68. package/dist/{chunk-6cxb8d6y.js → chunk-6nvn041c.js} +3 -3
  69. package/dist/chunk-7by4rm7y.js +1 -0
  70. package/dist/chunk-7ww65b66.js +709 -0
  71. package/dist/chunk-9c29rnk3.js +22 -0
  72. package/dist/chunk-9w32efae.js +1 -0
  73. package/dist/chunk-e0919h5g.js +2 -0
  74. package/dist/{chunk-dndxwssj.js → chunk-e7ds04wb.js} +2 -2
  75. package/dist/chunk-edqhhcg9.js +4 -0
  76. package/dist/chunk-ej4sm2tw.js +60 -0
  77. package/dist/chunk-emg3shmb.js +2 -0
  78. package/dist/chunk-fdexq9e1.js +1 -0
  79. package/dist/chunk-g8fpsdyq.js +37 -0
  80. package/dist/chunk-jb8em9ba.js +2 -0
  81. package/dist/chunk-n688m5fp.js +1 -0
  82. package/dist/chunk-r5emv4x8.js +2 -0
  83. package/dist/{chunk-q9a1z53k.js → chunk-sct6mdgc.js} +51 -51
  84. package/dist/chunk-thpce63q.js +34 -0
  85. package/dist/chunk-tnjae324.js +585 -0
  86. package/dist/{bin/chunk-hv3w2qy1.js → chunk-wjgnfg6q.js} +6 -6
  87. package/dist/chunk-wpqj98h8.js +2 -0
  88. package/dist/chunk-wrnhbb13.js +1 -0
  89. package/dist/chunk-zftpjxkr.js +2 -0
  90. package/dist/chunk-zmyv76f0.js +114 -0
  91. package/dist/deploy/index.js +1 -1
  92. package/dist/dns/index.js +1 -1
  93. package/dist/drivers/index.d.ts +1 -0
  94. package/dist/drivers/index.js +1 -1
  95. package/dist/drivers/shared/compute-deploy.d.ts +0 -12
  96. package/dist/drivers/shared/rpx-gateway.d.ts +124 -4
  97. package/dist/drivers/ssh/bootstrap.d.ts +13 -3
  98. package/dist/drivers/ssh/config.d.ts +11 -3
  99. package/dist/index.d.ts +1 -1
  100. package/dist/index.js +91 -91
  101. package/dist/operations/index.js +1 -1
  102. package/dist/protection/index.js +1 -1
  103. package/dist/push/index.js +1 -1
  104. package/dist/spend/index.js +1 -1
  105. package/dist/ui/404.html +1 -1
  106. package/dist/ui/accept-invitation.html +1 -1
  107. package/dist/ui/access-denied.html +2 -2
  108. package/dist/ui/account/automation.html +5 -5
  109. package/dist/ui/account/security.html +2 -2
  110. package/dist/ui/applications/compose.html +6 -6
  111. package/dist/ui/applications/new.html +2 -2
  112. package/dist/ui/data/backups.html +6 -6
  113. package/dist/ui/data/services.html +6 -6
  114. package/dist/ui/data/volumes.html +6 -6
  115. package/dist/ui/index.html +5 -5
  116. package/dist/ui/infrastructure/topology.html +9 -9
  117. package/dist/ui/integrations.html +2 -2
  118. package/dist/ui/operations/alerts.html +6 -6
  119. package/dist/ui/operations/configuration.html +6 -6
  120. package/dist/ui/operations/jobs.html +6 -6
  121. package/dist/ui/operations/maintenance.html +5 -5
  122. package/dist/ui/operations/observability.html +5 -5
  123. package/dist/ui/operations/previews.html +6 -6
  124. package/dist/ui/operations/queue.html +6 -6
  125. package/dist/ui/operations/regions.html +5 -5
  126. package/dist/ui/operations/releases.html +6 -6
  127. package/dist/ui/operations/spend.html +6 -6
  128. package/dist/ui/operations/workloads.html +10 -10
  129. package/dist/ui/security.html +2 -2
  130. package/dist/ui/server/actions.html +6 -6
  131. package/dist/ui/server/activity.html +2 -2
  132. package/dist/ui/server/capacity.html +5 -5
  133. package/dist/ui/server/database.html +5 -5
  134. package/dist/ui/server/deployments.html +5 -5
  135. package/dist/ui/server/diagnostics.html +2 -2
  136. package/dist/ui/server/firewall.html +6 -6
  137. package/dist/ui/server/fleet.html +5 -5
  138. package/dist/ui/server/logs.html +6 -6
  139. package/dist/ui/server/metrics.html +5 -5
  140. package/dist/ui/server/security.html +1 -1
  141. package/dist/ui/server/services.html +2 -2
  142. package/dist/ui/server/sites.html +16 -16
  143. package/dist/ui/server/ssh-keys.html +6 -6
  144. package/dist/ui/server/team.html +6 -6
  145. package/dist/ui/server/terminal.html +2 -2
  146. package/dist/ui/serverless/alarms.html +5 -5
  147. package/dist/ui/serverless/assets.html +2 -2
  148. package/dist/ui/serverless/cost.html +2 -2
  149. package/dist/ui/serverless/data.html +6 -6
  150. package/dist/ui/serverless/deployments.html +2 -2
  151. package/dist/ui/serverless/firewall.html +2 -2
  152. package/dist/ui/serverless/functions.html +5 -5
  153. package/dist/ui/serverless/logs.html +6 -6
  154. package/dist/ui/serverless/metrics.html +2 -2
  155. package/dist/ui/serverless/queues.html +6 -6
  156. package/dist/ui/serverless/secrets.html +6 -6
  157. package/dist/ui/serverless/traces.html +6 -6
  158. package/dist/ui/serverless.html +6 -6
  159. package/dist/ui-src/src/charts.ts +1141 -1294
  160. package/dist/ui-src/src/topology.ts +3 -3
  161. package/package.json +3 -3
  162. package/dist/bin/chunk-0x8szp53.js +0 -111
  163. package/dist/bin/chunk-1hggd7yz.js +0 -1
  164. package/dist/bin/chunk-2tsg6e8j.js +0 -1
  165. package/dist/bin/chunk-3f27aa5r.js +0 -2
  166. package/dist/bin/chunk-40j9hgzc.js +0 -1
  167. package/dist/bin/chunk-4gqfdr7t.js +0 -1
  168. package/dist/bin/chunk-5gx38418.js +0 -44
  169. package/dist/bin/chunk-5jv4cpky.js +0 -1
  170. package/dist/bin/chunk-5kxm5mx7.js +0 -1
  171. package/dist/bin/chunk-5rhvcgzt.js +0 -34
  172. package/dist/bin/chunk-8223r1xn.js +0 -2
  173. package/dist/bin/chunk-84703zpq.js +0 -7364
  174. package/dist/bin/chunk-9edyzdm0.js +0 -2
  175. package/dist/bin/chunk-9xbsmz1f.js +0 -2
  176. package/dist/bin/chunk-a8t3c4qe.js +0 -2
  177. package/dist/bin/chunk-aghy01we.js +0 -1
  178. package/dist/bin/chunk-akwfvn5k.js +0 -1
  179. package/dist/bin/chunk-asvz121j.js +0 -1
  180. package/dist/bin/chunk-b0xtsv8k.js +0 -6
  181. package/dist/bin/chunk-bcpdj01b.js +0 -1
  182. package/dist/bin/chunk-da49my09.js +0 -1
  183. package/dist/bin/chunk-ewxf62t8.js +0 -60
  184. package/dist/bin/chunk-f42gqn6c.js +0 -3
  185. package/dist/bin/chunk-fc6r1ack.js +0 -2
  186. package/dist/bin/chunk-ftcjjf76.js +0 -9
  187. package/dist/bin/chunk-g76sry03.js +0 -1
  188. package/dist/bin/chunk-hwdfky19.js +0 -2
  189. package/dist/bin/chunk-j02d6qmn.js +0 -1
  190. package/dist/bin/chunk-j2cb8we4.js +0 -37
  191. package/dist/bin/chunk-kmz8vb77.js +0 -1
  192. package/dist/bin/chunk-kyr5rasx.js +0 -511
  193. package/dist/bin/chunk-nc9pp87y.js +0 -8
  194. package/dist/bin/chunk-ncrnbcsa.js +0 -6
  195. package/dist/bin/chunk-py1hyeb2.js +0 -1
  196. package/dist/bin/chunk-qa06sft7.js +0 -1
  197. package/dist/bin/chunk-qr0xck72.js +0 -3
  198. package/dist/bin/chunk-r85ahkwq.js +0 -1
  199. package/dist/bin/chunk-re15e6p4.js +0 -2
  200. package/dist/bin/chunk-sj5csg49.js +0 -2
  201. package/dist/bin/chunk-t6y3pkm8.js +0 -1
  202. package/dist/bin/chunk-tfmx17he.js +0 -2
  203. package/dist/bin/chunk-vfcchrby.js +0 -1
  204. package/dist/bin/chunk-vmdh41kp.js +0 -1
  205. package/dist/bin/chunk-vrc7eemq.js +0 -1
  206. package/dist/bin/chunk-vsd7670h.js +0 -2
  207. package/dist/bin/chunk-vwqn3yx6.js +0 -3
  208. package/dist/bin/chunk-vxbnjz78.js +0 -1
  209. package/dist/bin/chunk-w8s8vgdj.js +0 -1
  210. package/dist/bin/chunk-yq9vetf8.js +0 -698
  211. package/dist/bin/chunk-zrgd65r8.js +0 -1
  212. package/dist/chunk-0a4tqwm9.js +0 -709
  213. package/dist/chunk-4884der5.js +0 -1
  214. package/dist/chunk-4wdxsnn2.js +0 -44
  215. package/dist/chunk-5hhyyhjt.js +0 -1
  216. package/dist/chunk-5zkacdw1.js +0 -1
  217. package/dist/chunk-6f68caq0.js +0 -1
  218. package/dist/chunk-7z50g5xz.js +0 -4
  219. package/dist/chunk-8fh4m5ge.js +0 -1
  220. package/dist/chunk-97pb7wb1.js +0 -1
  221. package/dist/chunk-ac87ds1k.js +0 -6
  222. package/dist/chunk-ess6vxfj.js +0 -2
  223. package/dist/chunk-fvpkxznh.js +0 -558
  224. package/dist/chunk-j06r5rwv.js +0 -2
  225. package/dist/chunk-j1g67djb.js +0 -92
  226. package/dist/chunk-k8x8mrkr.js +0 -2
  227. package/dist/chunk-mnmz8t7q.js +0 -34
  228. package/dist/chunk-n1fyryha.js +0 -141
  229. package/dist/chunk-n1hg0jxs.js +0 -2
  230. package/dist/chunk-n5xmh0ma.js +0 -37
  231. package/dist/chunk-q22qfwsc.js +0 -22
  232. package/dist/chunk-r8t25tbm.js +0 -7355
  233. package/dist/chunk-whyttetx.js +0 -5
  234. package/dist/chunk-yf8stygs.js +0 -114
  235. package/dist/chunk-ze5x2bpm.js +0 -2
  236. package/dist/chunk-zh0apedk.js +0 -60
  237. package/dist/chunk-zjyz926j.js +0 -2
package/dist/index.js CHANGED
@@ -1,17 +1,17 @@
1
- import{a as Ni,b as ki,c as xi,d as Li,e as Fi,f as _i,g as Mi,i as Bi,j as Vi,k as Wi,l as Hi,m as zi,n as Gi}from"./chunk-5hhyyhjt.js";import{$ as py,$a as nA,$b as nb,A as Vg,Aa as vS,Ab as vA,Ac as qi,Ad as Bb,B as Wg,Ba as OS,Bb as OA,Bd as Vb,C as Hg,Ca as NS,Cb as NA,Cd as Wb,D as zg,Da as kS,Db as kA,Dd as Hb,E as Gg,Ea as xS,Eb as xA,Ed as zb,F as Ug,Fa as LS,Fb as LA,Fd as Gb,G as jg,Ga as FS,Gb as FA,Gd as Ub,H as Kg,Ha as _S,Hb as _A,Hd as jb,I as qg,Ia as MS,Ib as MA,Ic as Zi,Id as Kb,J as Zg,Ja as BS,Jb as BA,Jd as qb,K as Jg,Ka as VS,Kb as VA,Kd as Zb,L as Yg,La as WS,Lb as WA,Ld as Jb,M as Xg,Ma as HS,Mb as HA,Md as Yb,N as gh,Na as zS,Nb as zA,Nd as Xb,O as hh,Oa as GS,Ob as GA,Od as Qb,P as yh,Pa as US,Pb as UA,Pd as go,Q as Ch,Qa as jS,Qb as jA,Qc as oo,Qd as ho,R as Sh,Ra as KS,Rb as KA,Rd as yo,S as Ah,Sa as qS,Sb as qA,Sd as Co,T as iy,Ta as ZS,Tb as ZA,U as oy,Ua as JS,Ub as JA,V as ay,Va as YS,Vb as YA,W as sy,Wa as XS,Wb as XA,X as cy,Xa as QS,Xb as QA,Y as ly,Ya as eA,Yb as eb,Z as dy,Za as tA,Zb as tb,_ as uy,_a as rA,_b as rb,aa as my,ab as iA,ac as ib,ad as so,ba as fy,bb as oA,bc as ob,bd as co,ca as gy,cb as aA,cc as ab,cd as lo,da as hy,db as sA,dc as sb,dd as uo,ea as yy,eb as cA,ec as cb,ed as po,fa as Cy,fb as lA,fc as lb,fd as mo,ga as Sy,gb as dA,gc as db,gd as fo,ha as Ay,hb as uA,hc as ub,ia as by,ib as pA,ic as pb,ja as Ry,jb as mA,jc as mb,ka as Py,kb as fA,kc as fb,la as Ty,lb as gA,lc as gb,ma as $y,mb as hA,mc as hb,na as Iy,nb as yA,nc as yb,oa as Dy,ob as CA,oc as Cb,od as Db,p as _f,pa as wy,pb as SA,pc as Sb,pd as wb,q as Mf,qa as Ey,qb as AA,qc as Ab,qd as Eb,r as Bf,ra as bS,rb as bA,rc as bb,rd as vb,s as Vf,sa as RS,sb as RA,sc as Rb,sd as Ob,t as kg,ta as PS,tb as PA,tc as Pb,td as Nb,u as xg,ua as TS,ub as TA,uc as Tb,ud as kb,v as Lg,va as $S,vb as $A,vc as $b,vd as xb,w as Fg,wa as IS,wb as IA,wc as Ib,wd as Lb,x as _g,xa as DS,xb as DA,xc as Ui,xd as Fb,y as Mg,ya as wS,yb as wA,yc as ji,yd as _b,z as Bg,za as ES,zb as EA,zc as Ki,zd as Mb}from"./chunk-0a4tqwm9.js";import{$d as io,Td as Ji,Ud as Yi,Vd as Xi,Wd as Qi,Xd as eo,Yd as to,Zd as ro,_d as no}from"./chunk-zh0apedk.js";import{he as ao}from"./chunk-whyttetx.js";import{Ae as Yr,Be as Xr,Ce as Qr,De as en,Ee as tn,Ff as gn,Jf as hn,Le as rn,Lf as yn,Mf as Cn,Nf as Sn,Of as An,Pf as bn,Qe as nn,Ue as on,Ye as an,af as sn,ef as cn,ie as cr,ke as lr,kf as ln,le as dr,me as ur,ne as pr,nf as dn,oe as mr,of as un,pe as fr,pf as pn,qf as mn,re as hr,se as Wr,te as zr,ue as Gr,ve as Ur,vf as fn,we as jr,xe as Kr,ye as qr,ze as Zr}from"./chunk-yf8stygs.js";import{Qf as Gt,Rf as jt,Sf as Kt}from"./chunk-mnmz8t7q.js";import{Uf as We}from"./chunk-n1fyryha.js";import{Vf as Vr}from"./chunk-ze5x2bpm.js";import{Wf as Jr}from"./chunk-k8x8mrkr.js";import{$f as br,Xf as yr,Yf as Cr,Zf as Sr,_f as Ar,ag as Rr,bg as Pr,cg as Tr,dg as $r,eg as Ir,fg as Dr,gg as wr,hg as Er,ig as vr,jg as Or,kg as Nr,lg as kr,mg as xr,ng as Y,og as Lr,pg as Fr,qg as _r,rg as Mr,sg as Br}from"./chunk-j06r5rwv.js";import{tg as J}from"./chunk-2ybcnrte.js";import{$h as ai,$i as wi,Ag as Dn,Ci as fi,Di as gi,Ei as hi,Fg as wn,Fi as yi,Gg as En,Hg as vn,Hh as ei,Ih as ti,Nh as ri,Ni as Ci,Og as ve,Oi as Si,Pi as Ai,Qg as On,Rg as fe,Ti as bi,Ui as Ri,Vi as Pi,Wi as Ti,Xi as $i,Yh as ni,Yi as Ii,Zh as ii,Zi as Di,_h as oi,ah as Mn,ai as si,aj as Ei,bh as Bn,bi as ci,bj as vi,ch as Vn,cj as Oi,dh as Wn,eh as Hn,fh as zn,fi as li,gh as Gn,gi as di,hh as Un,hi as ui,ii as pi,lh as jn,li as mi,mh as Kn,nh as qn,oh as Zn,rh as Jn,sh as Yn,th as Xn,ug as Rn,uh as Qn,vg as Pn,wg as Tn,xg as $n,yg as me,zg as In}from"./chunk-fvpkxznh.js";import{hj as Nn,ij as kn,jj as xn,kj as Ln,lj as Fn,mj as _n}from"./chunk-n5xmh0ma.js";import{nj as gr,oj as Hr}from"./chunk-6cxb8d6y.js";import{pj as Ve}from"./chunk-ess6vxfj.js";import{rj as Ut}from"./chunk-j1g67djb.js";import{tj as zt}from"./chunk-ac87ds1k.js";import{$j as Cg,Aj as Uf,Bj as jf,Cj as Kf,Dj as qf,Ej as Zf,Fj as Jf,Gj as Yf,Hj as Xf,Ij as Qf,Jj as eg,Kj as tg,Lj as rg,Mj as ng,Nj as ig,Oj as og,Pj as ag,Qj as sg,Rj as cg,Sj as lg,Tj as dg,Uj as ug,Vj as pg,Wj as mg,Xj as fg,Yj as gg,Zj as hg,_j as yg,ak as Sg,bk as Ag,ck as bg,dk as Rg,ek as Pg,fk as Tg,gk as $g,hk as Ig,ik as Dg,jk as wg,kk as Eg,lk as vg,mk as Og,nk as Ng,wj as Wf,xj as Hf,yj as zf,zj as Gf}from"./chunk-q22qfwsc.js";import{ok as _t,qk as Mt,rk as Bt,sk as Vt,tk as Wt,uk as Ht}from"./chunk-7z50g5xz.js";import{Ak as xt,Ck as Lt,Dk as Ft,vk as vt,xk as Ot,yk as Nt,zk as kt}from"./chunk-n1hg0jxs.js";import{$k as Ih,$l as Xy,$m as KC,Al as Qh,Am as $C,An as SS,Bl as ey,Bm as IC,Bn as AS,Cl as ty,Cm as DC,Dl as ry,Dm as wC,El as ny,Em as EC,Fl as vy,Fm as vC,Gk as Qg,Gl as Oy,Gm as OC,Hk as eh,Hl as Ny,Hm as NC,Ik as th,Il as ky,Im as kC,Jk as rh,Jl as xy,Jm as xC,Kk as nh,Kl as Ly,Km as LC,Lk as ih,Ll as Fy,Lm as FC,Mk as oh,Ml as _y,Mm as _C,Nk as ah,Nl as My,Nm as MC,Ok as sh,Ol as By,Om as BC,Pk as ch,Pl as Vy,Pm as VC,Qk as lh,Ql as Wy,Qm as WC,Rk as dh,Rl as Hy,Rm as HC,Sk as uh,Sl as zy,Sm as zC,Tk as ph,Tl as Gy,Tm as GC,Uk as mh,Ul as Uy,Um as qt,Vk as fh,Vl as jy,Vm as Zt,Wk as bh,Wl as Ky,Wm as Jt,Xk as Rh,Xl as qy,Xm as Yt,Yk as Ph,Yl as Zy,Ym as Xt,Zk as Th,Zl as Jy,Zm as UC,_k as $h,_l as Yy,_m as jC,al as Dh,am as Qy,an as qC,bl as wh,bm as eC,bn as ZC,cl as Eh,cm as tC,cn as JC,dl as vh,dm as rC,dn as YC,el as Oh,em as nC,en as XC,fl as Nh,fm as iC,fn as QC,gl as kh,gm as oC,gn as eS,hl as xh,hm as aC,hn as tS,il as Lh,im as sC,in as rS,jl as Fh,jm as cC,jn as nS,kl as _h,km as lC,kn as Qt,ll as Mh,lm as dC,ln as iS,ml as Bh,mm as uC,mn as oS,nl as Vh,nm as pC,nn as aS,ol as Wh,om as mC,on as sS,pl as Hh,pm as fC,pn as cS,ql as zh,qm as gC,qn as lS,rl as Gh,rm as hC,rn as dS,sl as Uh,sm as yC,sn as uS,tl as jh,tm as CC,tn as pS,ul as Kh,um as SC,un as mS,vl as qh,vm as AC,vn as fS,wl as Zh,wm as bC,wn as gS,xl as Jh,xm as RC,xn as hS,yl as Yh,ym as PC,yn as yS,zl as Xh,zm as TC,zn as CS}from"./chunk-q9a1z53k.js";import{Cn as er,Dn as tr,En as rr,Fn as nr,Gn as ir,Hn as or,In as ar,Jn as sr}from"./chunk-4wdxsnn2.js";import{$n as Is,$o as Ie,$p as sl,$q as sd,$r as su,$s as sp,$t as sm,$u as Tt,Ao as Js,Ap as xc,Aq as xl,Ar as xd,As as xu,At as xp,Au as xm,Av as $f,Bo as Ys,Bp as Lc,Bq as Ll,Br as Ld,Bs as Lu,Bt as Lp,Bu as Lm,Bv as If,Co as Xs,Cp as Fc,Cq as Fl,Cr as Fd,Cs as Fu,Ct as Fp,Cu as Fm,Cv as Df,Do as Qs,Dp as _c,Dq as _l,Dr as _d,Ds as _u,Dt as _p,Du as _m,Dv as wf,Eo as ec,Ep as Mc,Eq as Ml,Er as Md,Es as Mu,Et as Mp,Eu as Mm,Ev as Ef,Fo as tc,Fp as Bc,Fq as Bl,Fr as Bd,Fs as Bu,Ft as Bp,Fu as Bm,Fv as vf,Go as rc,Gp as Vc,Gq as Vl,Gr as Vd,Gs as Vu,Gt as Vp,Gu as Vm,Gv as Of,Ho as re,Hp as Wc,Hq as Wl,Hr as Wd,Hs as Wu,Ht as Wp,Hu as Wm,Hv as Nf,Io as nc,Ip as Hc,Iq as Hl,Ir as Hd,Is as Hu,It as Hp,Iu as Hm,Iv as kf,Jo as ic,Jp as zc,Jq as zl,Jr as zd,Js as zu,Jt as zp,Ju as zm,Jv as xf,Kn as ls,Ko as oc,Kp as Gc,Kq as Gl,Kr as Gd,Ks as Gu,Kt as Gp,Ku as Gm,Kv as Lf,Ln as ds,Lo as ne,Lp as Uc,Lq as Ul,Lr as Ud,Ls as Uu,Lt as Up,Lu as Um,Lv as Ff,Mn as us,Mo as E,Mp as jc,Mq as jl,Mr as jd,Ms as ju,Mt as jp,Mu as jm,Nn as ps,No as Te,Np as Kc,Nq as Kl,Nr as Kd,Ns as Ku,Nt as Kp,Nu as Km,On as ms,Oo as j,Op as qc,Oq as ql,Or as qd,Os as qu,Ot as qp,Ou as qm,Pn as fs,Po as L,Pp as Zc,Pq as Zl,Pr as Zd,Ps as Zu,Pt as Zp,Pu as Zm,Qn as gs,Qo as ac,Qp as Jc,Qq as Jl,Qr as Jd,Qs as Ju,Qt as Jp,Qu as Jm,Rn as hs,Ro as sc,Rp as Yc,Rq as Yl,Rr as Yd,Rs as Yu,Rt as Yp,Ru as Ym,Sn as ys,So as ie,Sp as Xc,Sq as Xl,Sr as Xd,Ss as Xu,St as Xp,Su as Xm,Tn as Cs,To as cc,Tp as Qc,Tq as Ql,Tr as Qd,Ts as Qu,Tt as Qp,Tu as Qm,Un as Ss,Uo as lc,Up as el,Uq as ed,Ur as eu,Us as ep,Ut as em,Uu as ef,Vn as As,Vo as dc,Vp as tl,Vq as td,Vr as tu,Vs as tp,Vt as tm,Vu as tf,Wn as bs,Wo as uc,Wp as rl,Wq as rd,Wr as ru,Ws as rp,Wt as rm,Wu as rf,Xn as Rs,Xo as $e,Xp as nl,Xq as nd,Xr as nu,Xs as np,Xt as nm,Xu as At,Yn as Ps,Yo as F,Yp as il,Yq as id,Yr as iu,Ys as ip,Yt as im,Yu as bt,Zn as Ts,Zo as K,Zp as ol,Zq as od,Zr as ou,Zs as op,Zt as om,Zu as Rt,_n as $s,_o as oe,_p as al,_q as ad,_r as au,_s as ap,_t as am,_u as Pt,ao as Ds,ap as De,aq as cl,ar as cd,as as cu,at as cp,au as cm,av as $t,bo as ws,bp as pc,bq as ll,br as ld,bs as lu,bt as lp,bu as lm,bv as It,co as Es,cp as mc,cq as dl,cr as dd,cs as du,ct as dp,cu as dm,cv as Dt,do as vs,dp as we,dq as ul,dr as ud,ds as uu,dt as up,du as um,dv as wt,eo as Os,ep as fc,eq as pl,er as pd,es as pu,et as pp,eu as pm,ev as Et,fo as Ns,fp as gc,fq as ml,fr as md,fs as mu,ft as mp,fu as mm,fv as nf,go as ks,gp as hc,gq as fl,gr as fd,gs as fu,gt as fp,gu as fm,gv as of,ho as xs,hp as yc,hq as gl,hr as gd,hs as gu,ht as gp,hu as gm,hv as af,io as Ls,ip as Cc,iq as hl,ir as hd,is as hu,it as hp,iu as hm,iv as sf,jo as Fs,jp as Ee,jq as yl,jr as yd,js as yu,jt as yp,ju as ym,jv as cf,ko as _s,kp as q,kq as Cl,kr as Cd,ks as Cu,kt as Cp,ku as Cm,kv as lf,lo as Ms,lp as Sc,lq as Sl,lr as Sd,ls as Su,lt as Sp,lu as Sm,lv as df,mo as Bs,mp as Ac,mq as Al,mr as Ad,ms as Au,mt as Ap,mu as Am,mv as uf,no as Vs,np as bc,nq as bl,nr as bd,ns as bu,nt as bp,nu as bm,nv as pf,oo as Ws,op as Rc,oq as Rl,or as Rd,os as Ru,ot as Rp,ou as Rm,ov as mf,po as be,pp as Pc,pq as Pl,pr as Pd,ps as Pu,pt as Pp,pu as Pm,pv as ff,qo as Hs,qp as Tc,qq as Tl,qr as Td,qs as Tu,qt as Tp,qu as Tm,qv as gf,ro as Re,rp as $c,rq as $l,rr as $d,rs as $u,rt as $p,ru as $m,rv as hf,so as Pe,sp as Ic,sq as Il,sr as Id,ss as Iu,st as Ip,su as Im,sv as yf,to as zs,tp as Dc,tq as Dl,tr as Dd,ts as Du,tt as Dp,tu as Dm,tv as Cf,uo as Gs,up as wc,uq as wl,ur as wd,us as wu,ut as wp,uu as wm,uv as Sf,vo as Us,vp as Ec,vq as El,vr as Ed,vs as Eu,vt as Ep,vu as Em,vv as Af,wo as js,wp as vc,wq as vl,wr as vd,ws as vu,wt as vp,wu as vm,wv as bf,xo as Ks,xp as Oc,xq as Ol,xr as Od,xs as Ou,xt as Op,xu as Om,xv as Rf,yo as qs,yp as Nc,yq as Nl,yr as Nd,ys as Nu,yt as Np,yu as Nm,yv as Pf,zo as Zs,zp as kc,zq as kl,zr as kd,zs as ku,zt as kp,zu as km,zv as Tf}from"./chunk-r8t25tbm.js";import{Mv as gt,Ov as Z}from"./chunk-zjyz926j.js";import{createHmac as he,createSign as Ge,timingSafeEqual as Ue}from"node:crypto";function V(e){let t=e instanceof Date?e.getTime():e;if(!Number.isFinite(t))throw TypeError("Media access timestamp must be finite");return Math.floor(t/1000)}function ye(e){return Buffer.from(e).toString("base64").replaceAll("+","-").replaceAll("=","_").replaceAll("/","~")}function je(e){return Buffer.from(e).toString("base64url")}function Ce(e,t=!1){if(!e||/[\r\n]/.test(e))throw TypeError("Media resource is invalid");let r=t?e.replaceAll("*","wildcard"):e,n=new URL(r);if(!["http:","https:"].includes(n.protocol))throw TypeError("Media resource must use HTTP or HTTPS");if(!t&&e.includes("*"))throw TypeError("Canned policies cannot contain wildcards")}function Se(e,t){let r=Ge("RSA-SHA1");return r.update(e),r.end(),ye(r.sign(t))}function Ae(e){Ce(e.resource,!0);let r={DateLessThan:{"AWS:EpochTime":V(e.expiresAt)}};if(e.activeAt!==void 0)r.DateGreaterThan={"AWS:EpochTime":V(e.activeAt)};if(e.ipAddress)r.IpAddress={"AWS:SourceIp":e.ipAddress};return JSON.stringify({Statement:[{Resource:e.resource,Condition:r}]})}function Ao(e,t,r){Ce(e);let n=V(t),i=e.includes("?")?"&":"?",d=Ae({resource:e,expiresAt:t}),s=Se(d,r.privateKey);return`${e}${i}Expires=${n}&Signature=${encodeURIComponent(s)}&Key-Pair-Id=${encodeURIComponent(r.keyPairId)}`}function bo(e,t){let r=Ae(e);return{"CloudFront-Key-Pair-Id":t.keyPairId,"CloudFront-Policy":ye(Buffer.from(r)),"CloudFront-Signature":Se(r,t.privateKey)}}function Ro(e){if(!e.resource||/[\r\n]/.test(e.resource))throw TypeError("Media resource is invalid");let t=je(Buffer.from(JSON.stringify({resource:e.resource,expiresAt:V(e.expiresAt),...e.keyId?{keyId:e.keyId}:{},...e.audience?{audience:e.audience}:{}}))),r=he("sha256",e.secret).update(t).digest("base64url");return`${t}.${r}`}function Po(e,t){let[r,n,i]=e.split(".");if(!r||!n||i)return null;let d=he("sha256",t.secret).update(r).digest(),s;try{s=Buffer.from(n,"base64url")}catch{return null}if(d.length!==s.length||!Ue(d,s))return null;try{let a=JSON.parse(Buffer.from(r,"base64url").toString("utf8")),l=V(t.now??Date.now());if(!a.resource||!Number.isSafeInteger(a.expiresAt)||a.expiresAt<=l)return null;if(t.resource&&a.resource!==t.resource)return null;if(t.audience&&a.audience!==t.audience)return null;return a}catch{return null}}function To(e,t=!1){let r=new URL(e,"https://media.invalid").pathname.toLowerCase(),n=/\.(?:m3u8|mpd|vtt|json)$/.test(r),i=/\.(?:key|license)$/.test(r)||r.includes("/keys/")||r.includes("/licenses/");return{"Accept-Ranges":"bytes","Cache-Control":t&&(n||i)?"private, no-store":n?"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 $o(e){if(!/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(e.bucket))throw TypeError("Media bucket is invalid");if(!/^[a-z0-9-]+$/.test(e.region))throw TypeError("Media bucket region is invalid");let t=e.prefix?`/${e.prefix.replace(/^\/+|\/+$/g,"")}`:"",r=e.protected??!1,n="public, max-age=31536000, immutable",i=r?"private, no-store":"public, max-age=5, s-maxage=30, stale-while-revalidate=30";return{originDomain:`${e.bucket}.s3.${e.region}.amazonaws.com`,originPath:t,domain:e.domain,trustedKeyGroupIds:[...new Set(e.trustedKeyGroupIds??[])],behaviors:[{pathPattern:"*.m3u8",cacheControl:i,compress:!0,signed:r},{pathPattern:"*.mpd",cacheControl:i,compress:!0,signed:r},{pathPattern:"*.vtt",cacheControl:i,compress:!0,signed:r},{pathPattern:"*",cacheControl:n,compress:!1,signed:r}],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 Ke{builder;config;environment;mergedConfig;serverEipLogicalIds=new Map;constructor(e){this.config=e.config,this.environment=e.environment,this.builder=new be(`${this.config.project.name} - ${this.environment}`),this.mergedConfig=this.mergeEnvironmentConfig()}mergeEnvironmentConfig(){let t=this.config.environments[this.environment]?.infrastructure;if(!t)return this.config;return{...this.config,infrastructure:{...this.config.infrastructure,...t,compute:{...this.config.infrastructure?.compute,...t.compute},storage:{...this.config.infrastructure?.storage,...t.storage},functions:{...this.config.infrastructure?.functions,...t.functions},servers:{...this.config.infrastructure?.servers,...t.servers},databases:{...this.config.infrastructure?.databases,...t.databases},cdn:{...this.config.infrastructure?.cdn,...t.cdn},sftp:t.sftp??this.config.infrastructure?.sftp,queues:{...this.config.infrastructure?.queues,...t.queues},redirects:{...this.config.infrastructure?.redirects,...t.redirects},realtime:{...this.config.infrastructure?.realtime,...t.realtime},cache:{...this.config.infrastructure?.cache,...t.cache},fileSystem:{...this.config.infrastructure?.fileSystem,...t.fileSystem},email:{...this.config.infrastructure?.email,...t.email},search:{...this.config.infrastructure?.search,...t.search},ai:{...this.config.infrastructure?.ai,...t.ai}}}}shouldDeploy(e){if(e.environments&&!e.environments.includes(this.environment))return!1;if(e.requiresFeatures){let t=this.config.features||{};if(!e.requiresFeatures.every((n)=>t[n]===!0))return!1}if(e.regions){let t=this.config.environments[this.environment]?.region||this.config.project.region;if(!e.regions.includes(t))return!1}if(e.condition&&typeof e.condition==="function")return e.condition(this.config,this.environment);return!0}resolveApiOriginPort(){let e=this.mergedConfig.infrastructure?.api?.port??this.mergedConfig.ports?.api,t=Number(e||3008);return Number.isFinite(t)&&t>0?t: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(e,t){return e==="public"||t.routeCompute===!0}storageBucketName(e,t,r){return this.mergedConfig.infrastructure?.storage?.[r]?.bucket??`${e}-${t}-${r}`}fileSystemLogicalId(e,t,r){return Pe(Re({slug:`${e}-${r}`,environment:t,resourceType:"efs"}))}resolveSftpStorage(e,t,r){let n=e.storage;if(n?.type==="efs"&&n.fileSystem){if(!this.mergedConfig.infrastructure?.fileSystem?.[n.fileSystem])throw Error(`sftp: storage.fileSystem "${n.fileSystem}" is not defined in infrastructure.fileSystem`);return{type:"efs",fileSystemId:{Ref:this.fileSystemLogicalId(t,r,n.fileSystem)},posixProfile:n.posixProfile}}if(n?.type==="s3"&&n.storageBucket){if(!this.mergedConfig.infrastructure?.storage?.[n.storageBucket])throw Error(`sftp: storage.storageBucket "${n.storageBucket}" is not defined in infrastructure.storage`);return{type:"s3",bucket:this.storageBucketName(t,r,n.storageBucket)}}return}resolveComputeCachePathPatterns(e){if(e&&e.length>0)return e;return this.defaultComputeCachePathPatterns()}createComputeCacheBehavior(e,t){return{PathPattern:e,TargetOriginId:t,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(e,t,r,n,i,d){let s=this.serverEipLogicalIds.get("app"),a=this.serverEipLogicalIds.get("appInstance");if(!s)return;let l=`EC2-${n}-${i}-api`,p=this.mergedConfig.infrastructure?.servers?.app?.region||this.mergedConfig.project?.region||"us-east-1",u=p==="us-east-1"?".compute-1.amazonaws.com":`.${p}.compute.amazonaws.com`,b={"Fn::Join":["",["ec2-",{"Fn::Join":["-",{"Fn::Split":[".",{Ref:s}]}]},u]]},C=this.resolveApiOriginPort();if(e.push({Id:l,DomainName:b,CustomOriginConfig:{HTTPPort:C,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}),r.push(s),a)r.push(a);for(let P of d)t.push(this.createComputeCacheBehavior(P,l))}buildCaddyfile(e){let t=e.filter(([,i])=>typeof i.domain==="string"&&i.domain&&typeof i.port==="number");if(t.length===0)return;let r=new Map;for(let[,i]of t){let d=r.get(i.domain)??[];d.push({port:i.port,path:i.path}),r.set(i.domain,d)}let n=[];for(let[i,d]of r){let a=[...d].sort((l,p)=>{let u=!l.path||l.path==="/",b=!p.path||p.path==="/";if(u&&!b)return 1;if(!u&&b)return-1;return(p.path?.length??0)-(l.path?.length??0)}).map((l)=>{let p=!l.path||l.path==="/",u=`reverse_proxy localhost:${l.port}`;return p?` handle {
2
- ${u}
3
- }`:` handle ${l.path} {
4
- ${u}
5
- }`});n.push(`${i} {
6
- ${a.join(`
1
+ import{Sp,x,Cp,rf,uy,nf,py,gy,my,hy,fy,Ay,yy,Iy,Sy,Cy,bp,Ep,Wc,Jc,Us,_,d,Xc,vp,O,Yc,p,sf,li,Zc,ed,ae,td,by,r,t,Ey,vy,g,Ty,wy,Ry,Dy,Py,Mt,rd,Qs,of,Ny,ky,Se,Me,Ce,L,I,o,A,Fe,m,af,Ue,M,at,By,cf,F,nd,be,Ft,Hs,J,id,X,df,Gs,U,Q,D,ui,E,Ut,ct,H,e,qs,xy,Tp,sd,_y,Oy,Ly,$y,od,My,Fy,Uy,Qy,Hy,Gy,qy,Vy,jy,zy,Ky,Wy,lf,uf,pf,gf,mf,hf,ff,Qt,wp,Rp,Nr,pi,Jy,Dp,Xy,Yy,kr,Zy,eI,tI,rI,nI,iI,Af,yf,If,Sf,Cf,Vs,sI,bf,Ef,vf,G,oI,Qe,js,Ht,Tf,Pp,wf,Rf,Df,Np,Y,aI,cI,dI,lI,Pf,uI,q,pI,gI,mI,kp,Bp,hI,xp,_p,fI,yI,II,SI,CI,Nf,ad,bI,EI,vI,TI,wI,kf,Bf,RI,DI,PI,NI,kI,BI,xI,_I,OI,Op,cd,LI,$I,MI,FI,Lp,$p,Mp,UI,Fp,QI,HI,GI,qI,Up,VI,jI,zI,KI,WI,JI,XI,YI,xf,_f,Of,Lf,Qp,ZI,eS,tS,rS,nS,iS,sS,oS,aS,$f,Mf,Ff,Uf,cS,dS,Hp,lS,Gp,qp,Vp,jp,uS,pS,gS,mS,Ee,gi,hS,fS,AS,yS,IS,SS,CS,bS,Qf,ES,vS,zp,Kp,TS,wS,Hf,RS,DS,PS,NS,kS,BS,xS,_S,OS,LS,$S,MS,FS,US,QS,HS,GS,qS,VS,jS,zS,Wp,KS,Jp,WS,Xp,JS,Yp,XS,Zp,YS,Br,ZS,eg,eC,zs,tC,tg,rC,rg,nC,ng,iC,ig,sC,sg,oC,xr,aC,og,cC,ag,dC,cg,lC,dg,uC,lg,pC,ug,gC,pg,mC,gg,hC,mg,fC,hg,AC,fg,yC,Ag,IC,yg,SC,Ig,CC,Sg,bC,Cg,EC,bg,vC,Eg,TC,vg,wC,Tg,RC,wg,DC,Rg,PC,Dg,NC,Pg,kC,Ng,BC,Gf,qf,Vf,jf,kg,xC,Bg,_C,xg,OC,_g,LC,mi,zf,Kf,Ks,dd,_r,Wf,Ws,Gt,ld,ud,Jf,Xf,Og,Yf,pd,Lg,$C,MC,Js,Xs,Ys,gd,hi,md,hd,Zs,fd,Ad,$g,Zf,eA,tA,FC,rA,nA,UC,iA,Mg,sA,oA,aA,QC,cA,fi,yd,dA,HC,lA,eo,to,Id,Fg,GC,Ug,qC,Qg,VC,Hg,jC,Gg,zC}from"./chunk-1n3ckctd.js";import{ao,qg,wd,pA,Si,Rd,co,Vg,jg,Or,lo,Dd,He,Pd,Nd,kd,Ci,Lr,zg,Ge,Bd,uo,po,go,xd,_d,Od,bi,mo,Ld,$r,Ei,ho,dt,Kg,$d,Md,Wg,Fd,fo,qt,Ud,Qd,Hd,Gd,qe,Jg,qd,Vt,Ao,yo,Io,vi,Ti,Mr,Vd,wi,So,Co,Fr,jd,Ur,Xg,Yg,lt,Qr,bo,Zg,zd,Kd,Eo,Wd,Jd,Xd,gA,Z,Yd,mA,hA,Ri,Di,fA,ce,em,ut,ve,Te,pt,Zd,el,tl,rl,tm,rm,vo,nm,im,To,nl,il,sm,ee,om,sl,de,wo,Ve,gt,mt,Hr,Pi,ol,AA,Ro,am,cm,dm,lm,Do,Po,al,Gr,No,cl,Ni,dl,ko,Bo,xo,_o,Oo,Lo,$o,Mo,ll,jt,Fo,ul,qr,pl,Uo,Qo,gl,zt,Ho,Go,um,yA,ki,IA,SA,CA,qo,Vo,ml,pm,jo,Vr,hl,Bi,fl,Al,yl,zo,gm,Ko,Il,mm,Wo,hm,jr,zr,Sl,xi,wl,Nl,Oi,Kt,Xo,Kr,Wr,Wt,je,Em,Zo,vm,Tm,xl,ea,$i,_l,ta,ft,Re,Ol,ra,na,Ll,ia,sa,oa,aa,$l,Ml,Xr,ca,da,la,ua,Fl,Mi,Yr,Fi,pa}from"./chunk-7ww65b66.js";import{B,fr,lc,hs,u,Ku,Wu}from"./chunk-wpqj98h8.js";import{rt,dc,zn,Kn,Wn,zu}from"./chunk-edqhhcg9.js";import{rh,nh,ih,Du,Pu,Nu,sh,ku,Bu,oh,ah,xu,ch,dh,ac,_u,lh,uh,Ou,ph,gh,mh,hh,fh,Ah,yh,jn,cc,Lu,$u,Mu,Fu,Uu,Qu,Hu,Gu,qu,Vu,ju,Ih,Sh,Ch,bh,Eh,vh,Th}from"./chunk-9c29rnk3.js";import{Oe,uc,oe,kt,pc,w,Bt,nt,gc,fs,Dh,Ju,mc,s,Jn,As,Ar,hc,fc,yr,Ph,Ac,ay,cy,ys,dy,ly,yc,Ic,Xn,Is,W,c,Ss,Le,Ir,Nh,kh,Sc,xt,Bh,Cs,xh,_h,bs,Cc,Sr,Es,Oh,bc,Xu,_t,Cr,Lh,vs,$h,R,Mh,Ec,Yu,Ts,Fh,Uh,Qh,vc,Yn,ws,Tc,Ot,it,Hh,br,Gh,wc,Zu,ep,Rs,Rc,Dc,st,tp,Zn,Pc,Ds,Er,rp,ei,Nc,kc,ti,np,Bc,xc,_c,Oc,Ps,ip,sp,qh,op,Lc,ri,ap,cp,Ns,vr,ks,Bs,xs,$c,dp,Mc,_s,Vh,Lt,jh,Fc,Tr,Uc,zh,Qc,lp,ni,wr,Os,ii,$e,Kh,up,pp,$t,Hc,Gc,qc,si,oi,ai,Wh,Jh,ot,Ls,Xh,Rr,gp,$s,Yh,mp,hp,fp,Zh,Ap,yp,ef,i,tf,ci,Ms,Fs}from"./chunk-sct6mdgc.js";import{n}from"./chunk-30h9rgfn.js";import{a}from"./chunk-3kapcdpn.js";import{le,ji,zi,Hl,Aa,ya,Ki,Ia,ze,V,Ke,te,C,ue,rn,Sa,De,Ca,nn,sn,on,At,yt,It,an,Xt,ba,Yt,Zt,We,cn,va,St,er,dn,wa,jl,zl,Ra,tr}from"./chunk-zmyv76f0.js";import{un,Ne,Ct,Ji,bt,Et,pn,Xi,Yi,ge,Zi,es,ts,rs,ne,ns,is,ss,T,Da,gn,Pa,ie,rr}from"./chunk-emg3shmb.js";import{pe,Je,ln}from"./chunk-thpce63q.js";import{j}from"./chunk-zftpjxkr.js";import{Kl,Na,me,ka,mn,Wl,Ba,Jl,Xl,$m,fn,as,An,yn,N,ar,Sn,cr,se,La,Cn,$a,dr,Ua,ke,z,Be,xe,Ze,Ae,lr,ye,vn,Tn,wn,Rn,Dn,Pn,Nn,ur,k,ls,yu,za,Bn,xn,_n,On,Ln,$n,Mn,Qn,rc,us,nc,Pt,Hn,ps,gs,ic,Gn,sc}from"./chunk-tnjae324.js";import{Sd,ro,Ai,yi,no,Cd,bd,Ii,io,so,vd,Td,oo}from"./chunk-1kp3y2s7.js";import{ga,Zr,en,Ui,Qi,Hi,Gi,ma,ha}from"./chunk-ej4sm2tw.js";import{fa}from"./chunk-3qp10j0j.js";import{y}from"./chunk-6g81m01r.js";import{Pe}from"./chunk-r5emv4x8.js";import{h}from"./chunk-wjgnfg6q.js";import{K,qn,ms,oc,Vn,Ru}from"./chunk-g8fpsdyq.js";import{gr,Ie}from"./chunk-6nvn041c.js";import{f}from"./chunk-jb8em9ba.js";import{Zm,_e}from"./chunk-e0919h5g.js";import{Vc,Dr,jc,zc,Kc,di,Ip,Pr}from"./chunk-13d54txj.js";import{createHmac as Ga,createSign as Rl,timingSafeEqual as Pl}from"node:crypto";function Un(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 ja(l){return Buffer.from(l).toString("base64").replaceAll("+","-").replaceAll("=","_").replaceAll("/","~")}function Tl(l){return Buffer.from(l).toString("base64url")}function Ka(l,S=!1){if(!l||/[\r\n]/.test(l))throw TypeError("Media resource is invalid");let b=S?l.replaceAll("*","wildcard"):l,P=new URL(b);if(!["http:","https:"].includes(P.protocol))throw TypeError("Media resource must use HTTP or HTTPS");if(!S&&l.includes("*"))throw TypeError("Canned policies cannot contain wildcards")}function qa(l,S){let b=Rl("RSA-SHA1");return b.update(l),b.end(),ja(b.sign(S))}function Za(l){Ka(l.resource,!0);let b={DateLessThan:{"AWS:EpochTime":Un(l.expiresAt)}};if(l.activeAt!==void 0)b.DateGreaterThan={"AWS:EpochTime":Un(l.activeAt)};if(l.ipAddress)b.IpAddress={"AWS:SourceIp":l.ipAddress};return JSON.stringify({Statement:[{Resource:l.resource,Condition:b}]})}function fu(l,S,b){Ka(l);let P=Un(S),v=l.includes("?")?"&":"?",Xe=Za({resource:l,expiresAt:S}),he=qa(Xe,b.privateKey);return`${l}${v}Expires=${P}&Signature=${encodeURIComponent(he)}&Key-Pair-Id=${encodeURIComponent(b.keyPairId)}`}function gu(l,S){let b=Za(l);return{"CloudFront-Key-Pair-Id":S.keyPairId,"CloudFront-Policy":ja(Buffer.from(b)),"CloudFront-Signature":qa(b,S.privateKey)}}function hu(l){if(!l.resource||/[\r\n]/.test(l.resource))throw TypeError("Media resource is invalid");let S=Tl(Buffer.from(JSON.stringify({resource:l.resource,expiresAt:Un(l.expiresAt),...l.keyId?{keyId:l.keyId}:{},...l.audience?{audience:l.audience}:{}}))),b=Ga("sha256",l.secret).update(S).digest("base64url");return`${S}.${b}`}function Cu(l,S){let[b,P,v]=l.split(".");if(!b||!P||v)return null;let Xe=Ga("sha256",S.secret).update(b).digest(),he;try{he=Buffer.from(P,"base64url")}catch{return null}if(Xe.length!==he.length||!Pl(Xe,he))return null;try{let fe=JSON.parse(Buffer.from(b,"base64url").toString("utf8")),Ye=Un(S.now??Date.now());if(!fe.resource||!Number.isSafeInteger(fe.expiresAt)||fe.expiresAt<=Ye)return null;if(S.resource&&fe.resource!==S.resource)return null;if(S.audience&&fe.audience!==S.audience)return null;return fe}catch{return null}}function Su(l,S=!1){let b=new URL(l,"https://media.invalid").pathname.toLowerCase(),P=/\.(?:m3u8|mpd|vtt|json)$/.test(b),v=/\.(?:key|license)$/.test(b)||b.includes("/keys/")||b.includes("/licenses/");return{"Accept-Ranges":"bytes","Cache-Control":S&&(P||v)?"private, no-store":P?"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 Au(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,"")}`:"",b=l.protected??!1,P="public, max-age=31536000, immutable",v=b?"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:v,compress:!0,signed:b},{pathPattern:"*.mpd",cacheControl:v,compress:!0,signed:b},{pathPattern:"*.vtt",cacheControl:v,compress:!0,signed:b},{pathPattern:"*",cacheControl:P,compress:!1,signed:b}],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 Dl{builder;config;environment;mergedConfig;serverEipLogicalIds=new Map;constructor(l){this.config=l.config,this.environment=l.environment,this.builder=new td(`${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((P)=>S[P]===!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,b){return this.mergedConfig.infrastructure?.storage?.[b]?.bucket??`${l}-${S}-${b}`}fileSystemLogicalId(l,S,b){return t(r({slug:`${l}-${b}`,environment:S,resourceType:"efs"}))}resolveSftpStorage(l,S,b){let P=l.storage;if(P?.type==="efs"&&P.fileSystem){if(!this.mergedConfig.infrastructure?.fileSystem?.[P.fileSystem])throw Error(`sftp: storage.fileSystem "${P.fileSystem}" is not defined in infrastructure.fileSystem`);return{type:"efs",fileSystemId:{Ref:this.fileSystemLogicalId(S,b,P.fileSystem)},posixProfile:P.posixProfile}}if(P?.type==="s3"&&P.storageBucket){if(!this.mergedConfig.infrastructure?.storage?.[P.storageBucket])throw Error(`sftp: storage.storageBucket "${P.storageBucket}" is not defined in infrastructure.storage`);return{type:"s3",bucket:this.storageBucketName(S,b,P.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,b,P,v,Xe){let he=this.serverEipLogicalIds.get("app"),fe=this.serverEipLogicalIds.get("appInstance");if(!he)return;let Ye=`EC2-${P}-${v}-api`,tt=this.mergedConfig.infrastructure?.servers?.app?.region||this.mergedConfig.project?.region||"us-east-1",et=tt==="us-east-1"?".compute-1.amazonaws.com":`.${tt}.compute.amazonaws.com`,nr={"Fn::Join":["",["ec2-",{"Fn::Join":["-",{"Fn::Split":[".",{Ref:he}]}]},et]]},vt=this.resolveApiOriginPort();if(l.push({Id:Ye,DomainName:nr,CustomOriginConfig:{HTTPPort:vt,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}),b.push(he),fe)b.push(fe);for(let or of Xe)S.push(this.createComputeCacheBehavior(or,Ye))}buildCaddyfile(l){let S=l.filter(([,v])=>typeof v.domain==="string"&&v.domain&&typeof v.port==="number");if(S.length===0)return;let b=new Map;for(let[,v]of S){let Xe=b.get(v.domain)??[];Xe.push({port:v.port,path:v.path}),b.set(v.domain,Xe)}let P=[];for(let[v,Xe]of b){let fe=[...Xe].sort((Ye,tt)=>{let et=!Ye.path||Ye.path==="/",nr=!tt.path||tt.path==="/";if(et&&!nr)return 1;if(!et&&nr)return-1;return(tt.path?.length??0)-(Ye.path?.length??0)}).map((Ye)=>{let tt=!Ye.path||Ye.path==="/",et=`reverse_proxy localhost:${Ye.port}`;return tt?` handle {
2
+ ${et}
3
+ }`:` handle ${Ye.path} {
4
+ ${et}
5
+ }`});P.push(`${v} {
6
+ ${fe.join(`
7
7
  `)}
8
- }`)}return n.join(`
8
+ }`)}return P.join(`
9
9
 
10
- `)}normalizeMountPath(e){let t=e?.mountPath||e?.path;if(!t||t==="/")return;let r=`/${t}`.replace(/\/+/g,"/").replace(/\/$/,"");return r==="/"?void 0:r}storageBucketLogicalId(e,t,r){return`${e}-${t}-s3-${r}`.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((n)=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}pathMountRewriteFunctionCode(e,t="directory"){return`function handler(event) { var request = event.request; var prefix = ${JSON.stringify(e)}; var rewriteStyle = ${JSON.stringify(t)}; 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 e=this.mergedConfig.project.slug,t=this.environment,r=!!(this.mergedConfig.infrastructure?.functions&&Object.keys(this.mergedConfig.infrastructure.functions).length>0||this.mergedConfig.infrastructure?.api),n=!!(this.mergedConfig.infrastructure?.servers&&Object.keys(this.mergedConfig.infrastructure.servers).length>0),i=!!this.mergedConfig.infrastructure?.compute;if(!!((this.mergedConfig.mode||"server")==="serverless"&&this.mergedConfig.infrastructure?.containers&&Object.keys(this.mergedConfig.infrastructure.containers).length>0))this.generateNetworkInfrastructure(e,t),this.generateContainerInfrastructure(e,t);if(r)this.generateServerless(e,t);if(n)this.generateServer(e,t);if(i)this.generateComputeApp(e,t);if(this.mergedConfig.infrastructure?.jumpBox)this.generateJumpBox(e,t);if(this.generateSharedInfrastructure(e,t),this.config.tags)this.applyGlobalTags(this.config.tags);return this}applyGlobalTags(e){}generateNetworkInfrastructure(e,t){if(this.builder.hasResource("VPC"))return;let n=this.mergedConfig.infrastructure?.network?.cidr||"10.0.0.0/16",{vpc:i,logicalId:d}=Te.createVpc({slug:e,environment:t,cidr:n,enableDnsHostnames:!0,enableDnsSupport:!0});this.builder.addResource("VPC",i);let s=`${e}${t}IGW`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(s,{Type:"AWS::EC2::InternetGateway",Properties:{Tags:[{Key:"Name",Value:`${e}-${t}-igw`},{Key:"Environment",Value:t}]}});let a=`${e}${t}IGWAttach`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(a,{Type:"AWS::EC2::VPCGatewayAttachment",Properties:{VpcId:{Ref:"VPC"},InternetGatewayId:{Ref:s}}});let l=`${e}${t}PublicRT`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(l,{Type:"AWS::EC2::RouteTable",Properties:{VpcId:{Ref:"VPC"},Tags:[{Key:"Name",Value:`${e}-${t}-public-rt`},{Key:"Environment",Value:t}]}}),this.builder.addResource(`${e}${t}PublicRoute`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::EC2::Route",Properties:{RouteTableId:{Ref:l},DestinationCidrBlock:"0.0.0.0/0",GatewayId:{Ref:s}},DependsOn:a});let p=this.mergedConfig.environments[t]?.region||this.mergedConfig.project.region||"us-east-1",u=["a","b"];for(let b=0;b<2;b++){let C=`PublicSubnet${b+1}`;this.builder.addResource(C,{Type:"AWS::EC2::Subnet",Properties:{VpcId:{Ref:"VPC"},CidrBlock:`10.0.${b}.0/24`,AvailabilityZone:`${p}${u[b]}`,MapPublicIpOnLaunch:!0,Tags:[{Key:"Name",Value:`${e}-${t}-public-${u[b]}`},{Key:"Environment",Value:t}]}}),this.builder.addResource(`${C}RTAssoc`,{Type:"AWS::EC2::SubnetRouteTableAssociation",Properties:{SubnetId:{Ref:C},RouteTableId:{Ref:l}}})}}generateContainerInfrastructure(e,t){let r=this.mergedConfig.infrastructure?.containers;if(!r)return;let n=this.mergedConfig.infrastructure?.loadBalancer,i=this.mergedConfig.infrastructure?.ssl,d=this.mergedConfig.infrastructure?.dns,s;if(i?.enabled&&i.domains?.length)if(i.certificateArn);else{let u=i.domains[0],b=i.domains.slice(1).map((g)=>{if(g.includes(".")&&g.endsWith(u))return g.replace(`.${u}`,"");return g}),{certificate:C,logicalId:P}=ne.createCertificate({domain:u,subdomains:b,slug:e,environment:t,validationMethod:"DNS",hostedZoneId:d?.hostedZoneId});s=P,this.builder.addResource(P,C)}let a="ECSCluster";this.builder.addResource(a,{Type:"AWS::ECS::Cluster",Properties:{ClusterName:`${e}-${t}`,ClusterSettings:[{Name:"containerInsights",Value:"enabled"}],Tags:[{Key:"Name",Value:`${e}-${t}`},{Key:"Environment",Value:t}]}});let l=`${e}${t}ALBSecurityGroup`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(l,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`ALB security group for ${e}-${t}`,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:`${e}-${t}-alb-sg`},{Key:"Environment",Value:t}]}});let p=`${e}${t}ECSSecurityGroup`.replace(/[^a-zA-Z0-9]/g,"");for(let[u,b]of Object.entries(r)){let C=b.port||3000;this.builder.addResource(p,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`ECS tasks security group for ${e}-${t}`,VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:C,ToPort:C,SourceSecurityGroupId:{Ref:l},Description:"Allow traffic from ALB"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0",Description:"Allow all outbound"}],Tags:[{Key:"Name",Value:`${e}-${t}-ecs-sg`},{Key:"Environment",Value:t}]}});let P=`${e}${t}TaskExecRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(P,{Type:"AWS::IAM::Role",Properties:{RoleName:`${e}-${t}-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 g=`${e}${t}TaskRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(g,{Type:"AWS::IAM::Role",Properties:{RoleName:`${e}-${t}-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 m=`${e}${t}${u}LogGroup`.replace(/[^a-zA-Z0-9]/g,""),c=`/ecs/${e}-${t}-${u}`;this.builder.addResource(m,{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:c,RetentionInDays:30}});let y=`${e}${t}${u}TaskDef`.replace(/[^a-zA-Z0-9]/g,""),o=String(b.cpu||512),f=String(b.memory||1024);this.builder.addResource(y,{Type:"AWS::ECS::TaskDefinition",Properties:{Family:`${e}-${t}-${u}`,NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:o,Memory:f,ExecutionRoleArn:{"Fn::GetAtt":[P,"Arn"]},TaskRoleArn:{"Fn::GetAtt":[g,"Arn"]},ContainerDefinitions:[{Name:u,Image:{"Fn::Sub":`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${e}:latest`},Essential:!0,PortMappings:[{ContainerPort:C,Protocol:"tcp"}],LogConfiguration:{LogDriver:"awslogs",Options:{"awslogs-group":c,"awslogs-region":{Ref:"AWS::Region"},"awslogs-stream-prefix":u}},HealthCheck:{Command:["CMD-SHELL",`curl -f http://localhost:${C}${b.healthCheck||"/health"} || exit 1`],Interval:30,Timeout:5,Retries:3,StartPeriod:60}}],Tags:[{Key:"Name",Value:`${e}-${t}-${u}`},{Key:"Environment",Value:t}]},DependsOn:[P,g,m]});let h=`${e}${t}ALB`.replace(/[^a-zA-Z0-9]/g,"");if(n?.enabled!==!1){this.builder.addResource(h,{Type:"AWS::ElasticLoadBalancingV2::LoadBalancer",Properties:{Name:`${e}-${t}-alb`,Scheme:"internet-facing",Type:"application",Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],SecurityGroups:[{Ref:l}],Tags:[{Key:"Name",Value:`${e}-${t}-alb`},{Key:"Environment",Value:t}]}});let S=`${e}${t}TargetGroup`.replace(/[^a-zA-Z0-9]/g,""),A=n?.healthCheck?.path||b.healthCheck||"/health";this.builder.addResource(S,{Type:"AWS::ElasticLoadBalancingV2::TargetGroup",Properties:{Name:`${e}-${t}-tg`,Port:C,Protocol:"HTTP",VpcId:{Ref:"VPC"},TargetType:"ip",HealthCheckPath:A,HealthCheckIntervalSeconds:n?.healthCheck?.interval||30,HealthyThresholdCount:n?.healthCheck?.healthyThreshold||2,UnhealthyThresholdCount:n?.healthCheck?.unhealthyThreshold||5,HealthCheckTimeoutSeconds:10,Tags:[{Key:"Name",Value:`${e}-${t}-tg`},{Key:"Environment",Value:t}]}});let R=`${e}${t}HTTPListener`.replace(/[^a-zA-Z0-9]/g,"");if(i?.enabled&&i?.redirectHttp)this.builder.addResource(R,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:h},Port:80,Protocol:"HTTP",DefaultActions:[{Type:"redirect",RedirectConfig:{Protocol:"HTTPS",Port:"443",StatusCode:"HTTP_301"}}]}});else this.builder.addResource(R,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:h},Port:80,Protocol:"HTTP",DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:S}}]}});if(i?.enabled){let v=i.certificateArn||(s?{Ref:s}:void 0);if(v){let O=`${e}${t}HTTPSListener`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(O,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:h},Port:443,Protocol:"HTTPS",Certificates:[{CertificateArn:v}],DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:S}}],SslPolicy:"ELBSecurityPolicy-TLS13-1-2-2021-06"}})}}let I=`${e}${t}${u}Service`.replace(/[^a-zA-Z0-9]/g,""),D=b.desiredCount||1;this.builder.addResource(I,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${e}-${t}-${u}`,Cluster:{Ref:a},TaskDefinition:{Ref:y},DesiredCount:D,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:p}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},LoadBalancers:[{ContainerName:u,ContainerPort:C,TargetGroupArn:{Ref:S}}],HealthCheckGracePeriodSeconds:120,Tags:[{Key:"Name",Value:`${e}-${t}-${u}`},{Key:"Environment",Value:t}]},DependsOn:[y,R,S]});let T=b.autoScaling;if(T){let v=`${e}${t}${u}ScalableTarget`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(v,{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{MaxCapacity:T.max||10,MinCapacity:T.min||1,ResourceId:{"Fn::Sub":`service/\${${a}}/${e}-${t}-${u}`},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:I}),T.targetCpuUtilization)this.builder.addResource(`${e}${t}${u}CPUScaling`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${e}-${t}-${u}-cpu-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:v},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},TargetValue:T.targetCpuUtilization,ScaleInCooldown:300,ScaleOutCooldown:60}}});if(T.targetMemoryUtilization)this.builder.addResource(`${e}${t}${u}MemoryScaling`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${e}-${t}-${u}-memory-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:v},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageMemoryUtilization"},TargetValue:T.targetMemoryUtilization,ScaleInCooldown:300,ScaleOutCooldown:60}}})}if(d?.domain&&d?.hostedZoneId)this.builder.addResource(`${e}${t}ApiDnsRecord`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:d.hostedZoneId,Name:`api.${d.domain}`,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":[h,"DNSName"]},HostedZoneId:{"Fn::GetAtt":[h,"CanonicalHostedZoneID"]}}}});this.builder.addOutput("ECSClusterArn",{Description:"ECS Cluster ARN",Value:{"Fn::GetAtt":[a,"Arn"]},Export:{Name:{"Fn::Sub":"${AWS::StackName}-ecs-cluster-arn"}}}),this.builder.addOutput("ECSServiceName",{Description:"ECS Service Name",Value:`${e}-${t}-${u}`,Export:{Name:{"Fn::Sub":"${AWS::StackName}-ecs-service-name"}}}),this.builder.addOutput("LoadBalancerDNS",{Description:"Application Load Balancer DNS Name",Value:{"Fn::GetAtt":[h,"DNSName"]},Export:{Name:{"Fn::Sub":"${AWS::StackName}-alb-dns"}}})}else{let S=`${e}${t}${u}Service`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(S,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${e}-${t}-${u}`,Cluster:{Ref:a},TaskDefinition:{Ref:y},DesiredCount:b.desiredCount||1,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:p}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},Tags:[{Key:"Name",Value:`${e}-${t}-${u}`},{Key:"Environment",Value:t}]},DependsOn:[y]})}break}}generateServerless(e,t){if(this.mergedConfig.infrastructure?.functions)for(let[r,n]of Object.entries(this.mergedConfig.infrastructure.functions)){if(!this.shouldDeploy(n))continue;let{role:i,logicalId:d}=Ie.createRole({slug:e,environment:t,roleName:`${e}-${t}-${r}-role`,servicePrincipal:"lambda.amazonaws.com",managedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]});this.builder.addResource(d,i);let{lambdaFunction:s,logicalId:a}=E.createLambdaFunction({slug:e,environment:t,functionName:`${e}-${t}-${r}`,handler:n.handler||"index.handler",runtime:n.runtime||"nodejs20.x",code:{zipFile:n.code||"export const handler = async () => ({ statusCode: 200 });"},role:d,timeout:n.timeout,memorySize:n.memorySize});this.builder.addResource(a,s)}if(this.mergedConfig.infrastructure?.api){let{restApi:r,logicalId:n}=De.createRestApi({slug:e,environment:t,apiName:`${e}-${t}-api`});this.builder.addResource(n,r)}}generateServer(e,t){if(!this.mergedConfig.infrastructure?.servers)return;let r=this.mergedConfig.infrastructure.servers,n=this.mergedConfig.infrastructure?.compute,i=this.mergedConfig.infrastructure?.ssl;if(Object.values(r).some((s)=>!s.privateNetwork||s.privateNetwork==="create"))this.generateNetworkInfrastructure(e,t);for(let[s,a]of Object.entries(r)){let l=a.instanceType||a.size||n?.size,u=(l?E.InstanceSize.specs[l]:void 0)?.instanceType||l||"t3.micro",b=a.type||"app",C=a.userData||a.startupScript;if(!C)C=E.UserData.generateAppServerScript({runtime:"bun",runtimeVersion:a.bunVersion||"latest",webServer:"none",domain:a.domain,enableSsl:!!i?.enabled,sslEmail:i?.letsEncrypt?.email,installRedis:b==="cache",installDatabaseClients:!!a.database});let P=a.privateNetwork&&a.privateNetwork!=="create"?a.privateNetwork:{Ref:"VPC"},g=a.subnet||{Ref:"PublicSubnet1"},c=!!this.mergedConfig.infrastructure?.email?.server?.enabled,y=[22,80,443,this.resolveApiOriginPort()];if(c)y.push(25,465,587,143,993);let o=E.createServerModeStack({slug:`${e}-${s}`,environment:t,vpcId:P,subnetId:g,instanceType:u,keyName:a.keyName||`${e}-${t}`,domain:a.domain,userData:C,volumeSize:a.diskSize||20,imageId:a.image,allowedPorts:y});for(let[f,h]of Object.entries(o.resources))this.builder.addResource(f,h);this.serverEipLogicalIds.set(s,o.outputs.eipLogicalId),this.serverEipLogicalIds.set(`${s}Instance`,o.outputs.instanceLogicalId),this.builder.addOutput(`${s}InstanceId`,{Value:{Ref:o.outputs.instanceLogicalId},Description:`Instance ID for ${s} server`}),this.builder.addOutput(`${s}PublicIp`,{Value:{Ref:o.outputs.eipLogicalId},Description:`Public IP for ${s} server`})}}generateComputeApp(e,t){let r=this.mergedConfig.infrastructure?.compute;if(!r)return;let n=this.mergedConfig.sites||{},i=Object.entries(n),s=this.mergedConfig.infrastructure?.dns?.domain,a=this.mergedConfig.infrastructure?.database,l=r.size,u=(l?E.InstanceSize.specs[l]:void 0)?.instanceType||l||"t3.micro";if(!this.builder.hasResource("VPC"))this.generateNetworkInfrastructure(e,t);let b=this.buildCaddyfile(i),C=E.UserData.generateBunAppScript({runtime:r.runtime||"bun",runtimeVersion:r.runtimeVersion||"latest",systemPackages:r.systemPackages,database:a,caddyfile:b}),P=ve(r.appUpdates),g=P.length>0?`${C}
11
- ${P.join(`
10
+ `)}normalizeMountPath(l){let S=l?.mountPath||l?.path;if(!S||S==="/")return;let b=`/${S}`.replace(/\/+/g,"/").replace(/\/$/,"");return b==="/"?void 0:b}storageBucketLogicalId(l,S,b){return`${l}-${S}-s3-${b}`.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((P)=>P.charAt(0).toUpperCase()+P.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,b=!!(this.mergedConfig.infrastructure?.functions&&Object.keys(this.mergedConfig.infrastructure.functions).length>0||this.mergedConfig.infrastructure?.api),P=!!(this.mergedConfig.infrastructure?.servers&&Object.keys(this.mergedConfig.infrastructure.servers).length>0),v=!!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(b)this.generateServerless(l,S);if(P)this.generateServer(l,S);if(v)this.generateComputeApp(l,S);if(this.mergedConfig.infrastructure?.jumpBox)this.generateJumpBox(l,S);if(this.generateSharedInfrastructure(l,S),this.config.tags)this.applyGlobalTags(this.config.tags);return this}applyGlobalTags(l){}generateNetworkInfrastructure(l,S){if(this.builder.hasResource("VPC"))return;let P=this.mergedConfig.infrastructure?.network?.cidr||"10.0.0.0/16",{vpc:v,logicalId:Xe}=A.createVpc({slug:l,environment:S,cidr:P,enableDnsHostnames:!0,enableDnsSupport:!0});this.builder.addResource("VPC",v);let he=`${l}${S}IGW`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(he,{Type:"AWS::EC2::InternetGateway",Properties:{Tags:[{Key:"Name",Value:`${l}-${S}-igw`},{Key:"Environment",Value:S}]}});let fe=`${l}${S}IGWAttach`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(fe,{Type:"AWS::EC2::VPCGatewayAttachment",Properties:{VpcId:{Ref:"VPC"},InternetGatewayId:{Ref:he}}});let Ye=`${l}${S}PublicRT`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Ye,{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:Ye},DestinationCidrBlock:"0.0.0.0/0",GatewayId:{Ref:he}},DependsOn:fe});let tt=this.mergedConfig.environments[S]?.region||this.mergedConfig.project.region||"us-east-1",et=["a","b"];for(let nr=0;nr<2;nr++){let vt=`PublicSubnet${nr+1}`;this.builder.addResource(vt,{Type:"AWS::EC2::Subnet",Properties:{VpcId:{Ref:"VPC"},CidrBlock:`10.0.${nr}.0/24`,AvailabilityZone:`${tt}${et[nr]}`,MapPublicIpOnLaunch:!0,Tags:[{Key:"Name",Value:`${l}-${S}-public-${et[nr]}`},{Key:"Environment",Value:S}]}}),this.builder.addResource(`${vt}RTAssoc`,{Type:"AWS::EC2::SubnetRouteTableAssociation",Properties:{SubnetId:{Ref:vt},RouteTableId:{Ref:Ye}}})}}generateContainerInfrastructure(l,S){let b=this.mergedConfig.infrastructure?.containers;if(!b)return;let P=this.mergedConfig.infrastructure?.loadBalancer,v=this.mergedConfig.infrastructure?.ssl,Xe=this.mergedConfig.infrastructure?.dns,he;if(v?.enabled&&v.domains?.length)if(v.certificateArn);else{let et=v.domains[0],nr=v.domains.slice(1).map((Tt)=>{if(Tt.includes(".")&&Tt.endsWith(et))return Tt.replace(`.${et}`,"");return Tt}),{certificate:vt,logicalId:or}=I.createCertificate({domain:et,subdomains:nr,slug:l,environment:S,validationMethod:"DNS",hostedZoneId:Xe?.hostedZoneId});he=or,this.builder.addResource(or,vt)}let fe="ECSCluster";this.builder.addResource(fe,{Type:"AWS::ECS::Cluster",Properties:{ClusterName:`${l}-${S}`,ClusterSettings:[{Name:"containerInsights",Value:"enabled"}],Tags:[{Key:"Name",Value:`${l}-${S}`},{Key:"Environment",Value:S}]}});let Ye=`${l}${S}ALBSecurityGroup`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Ye,{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 tt=`${l}${S}ECSSecurityGroup`.replace(/[^a-zA-Z0-9]/g,"");for(let[et,nr]of Object.entries(b)){let vt=nr.port||3000;this.builder.addResource(tt,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`ECS tasks security group for ${l}-${S}`,VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:vt,ToPort:vt,SourceSecurityGroupId:{Ref:Ye},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 or=`${l}${S}TaskExecRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(or,{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 Tt=`${l}${S}TaskRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Tt,{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 ht=`${l}${S}${et}LogGroup`.replace(/[^a-zA-Z0-9]/g,""),we=`/ecs/${l}-${S}-${et}`;this.builder.addResource(ht,{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:we,RetentionInDays:30}});let wt=`${l}${S}${et}TaskDef`.replace(/[^a-zA-Z0-9]/g,""),re=String(nr.cpu||512),Rt=String(nr.memory||1024);this.builder.addResource(wt,{Type:"AWS::ECS::TaskDefinition",Properties:{Family:`${l}-${S}-${et}`,NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:re,Memory:Rt,ExecutionRoleArn:{"Fn::GetAtt":[or,"Arn"]},TaskRoleArn:{"Fn::GetAtt":[Tt,"Arn"]},ContainerDefinitions:[{Name:et,Image:{"Fn::Sub":`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${l}:latest`},Essential:!0,PortMappings:[{ContainerPort:vt,Protocol:"tcp"}],LogConfiguration:{LogDriver:"awslogs",Options:{"awslogs-group":we,"awslogs-region":{Ref:"AWS::Region"},"awslogs-stream-prefix":et}},HealthCheck:{Command:["CMD-SHELL",`curl -f http://localhost:${vt}${nr.healthCheck||"/health"} || exit 1`],Interval:30,Timeout:5,Retries:3,StartPeriod:60}}],Tags:[{Key:"Name",Value:`${l}-${S}-${et}`},{Key:"Environment",Value:S}]},DependsOn:[or,Tt,ht]});let Dt=`${l}${S}ALB`.replace(/[^a-zA-Z0-9]/g,"");if(P?.enabled!==!1){this.builder.addResource(Dt,{Type:"AWS::ElasticLoadBalancingV2::LoadBalancer",Properties:{Name:`${l}-${S}-alb`,Scheme:"internet-facing",Type:"application",Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],SecurityGroups:[{Ref:Ye}],Tags:[{Key:"Name",Value:`${l}-${S}-alb`},{Key:"Environment",Value:S}]}});let Nt=`${l}${S}TargetGroup`.replace(/[^a-zA-Z0-9]/g,""),Jt=P?.healthCheck?.path||nr.healthCheck||"/health";this.builder.addResource(Nt,{Type:"AWS::ElasticLoadBalancingV2::TargetGroup",Properties:{Name:`${l}-${S}-tg`,Port:vt,Protocol:"HTTP",VpcId:{Ref:"VPC"},TargetType:"ip",HealthCheckPath:Jt,HealthCheckIntervalSeconds:P?.healthCheck?.interval||30,HealthyThresholdCount:P?.healthCheck?.healthyThreshold||2,UnhealthyThresholdCount:P?.healthCheck?.unhealthyThreshold||5,HealthCheckTimeoutSeconds:10,Tags:[{Key:"Name",Value:`${l}-${S}-tg`},{Key:"Environment",Value:S}]}});let ir=`${l}${S}HTTPListener`.replace(/[^a-zA-Z0-9]/g,"");if(v?.enabled&&v?.redirectHttp)this.builder.addResource(ir,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:Dt},Port:80,Protocol:"HTTP",DefaultActions:[{Type:"redirect",RedirectConfig:{Protocol:"HTTPS",Port:"443",StatusCode:"HTTP_301"}}]}});else this.builder.addResource(ir,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:Dt},Port:80,Protocol:"HTTP",DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:Nt}}]}});if(v?.enabled){let Jr=v.certificateArn||(he?{Ref:he}:void 0);if(Jr){let tn=`${l}${S}HTTPSListener`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(tn,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:Dt},Port:443,Protocol:"HTTPS",Certificates:[{CertificateArn:Jr}],DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:Nt}}],SslPolicy:"ELBSecurityPolicy-TLS13-1-2-2021-06"}})}}let pr=`${l}${S}${et}Service`.replace(/[^a-zA-Z0-9]/g,""),mr=nr.desiredCount||1;this.builder.addResource(pr,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${l}-${S}-${et}`,Cluster:{Ref:fe},TaskDefinition:{Ref:wt},DesiredCount:mr,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:tt}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},LoadBalancers:[{ContainerName:et,ContainerPort:vt,TargetGroupArn:{Ref:Nt}}],HealthCheckGracePeriodSeconds:120,Tags:[{Key:"Name",Value:`${l}-${S}-${et}`},{Key:"Environment",Value:S}]},DependsOn:[wt,ir,Nt]});let sr=nr.autoScaling;if(sr){let Jr=`${l}${S}${et}ScalableTarget`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(Jr,{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{MaxCapacity:sr.max||10,MinCapacity:sr.min||1,ResourceId:{"Fn::Sub":`service/\${${fe}}/${l}-${S}-${et}`},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:pr}),sr.targetCpuUtilization)this.builder.addResource(`${l}${S}${et}CPUScaling`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${l}-${S}-${et}-cpu-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:Jr},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},TargetValue:sr.targetCpuUtilization,ScaleInCooldown:300,ScaleOutCooldown:60}}});if(sr.targetMemoryUtilization)this.builder.addResource(`${l}${S}${et}MemoryScaling`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${l}-${S}-${et}-memory-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:Jr},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageMemoryUtilization"},TargetValue:sr.targetMemoryUtilization,ScaleInCooldown:300,ScaleOutCooldown:60}}})}if(Xe?.domain&&Xe?.hostedZoneId)this.builder.addResource(`${l}${S}ApiDnsRecord`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:Xe.hostedZoneId,Name:`api.${Xe.domain}`,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":[Dt,"DNSName"]},HostedZoneId:{"Fn::GetAtt":[Dt,"CanonicalHostedZoneID"]}}}});this.builder.addOutput("ECSClusterArn",{Description:"ECS Cluster ARN",Value:{"Fn::GetAtt":[fe,"Arn"]},Export:{Name:{"Fn::Sub":"${AWS::StackName}-ecs-cluster-arn"}}}),this.builder.addOutput("ECSServiceName",{Description:"ECS Service Name",Value:`${l}-${S}-${et}`,Export:{Name:{"Fn::Sub":"${AWS::StackName}-ecs-service-name"}}}),this.builder.addOutput("LoadBalancerDNS",{Description:"Application Load Balancer DNS Name",Value:{"Fn::GetAtt":[Dt,"DNSName"]},Export:{Name:{"Fn::Sub":"${AWS::StackName}-alb-dns"}}})}else{let Nt=`${l}${S}${et}Service`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Nt,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${l}-${S}-${et}`,Cluster:{Ref:fe},TaskDefinition:{Ref:wt},DesiredCount:nr.desiredCount||1,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:tt}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},Tags:[{Key:"Name",Value:`${l}-${S}-${et}`},{Key:"Environment",Value:S}]},DependsOn:[wt]})}break}}generateServerless(l,S){if(this.mergedConfig.infrastructure?.functions)for(let[b,P]of Object.entries(this.mergedConfig.infrastructure.functions)){if(!this.shouldDeploy(P))continue;let{role:v,logicalId:Xe}=J.createRole({slug:l,environment:S,roleName:`${l}-${S}-${b}-role`,servicePrincipal:"lambda.amazonaws.com",managedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]});this.builder.addResource(Xe,v);let{lambdaFunction:he,logicalId:fe}=o.createLambdaFunction({slug:l,environment:S,functionName:`${l}-${S}-${b}`,handler:P.handler||"index.handler",runtime:P.runtime||"nodejs20.x",code:{zipFile:P.code||"export const handler = async () => ({ statusCode: 200 });"},role:Xe,timeout:P.timeout,memorySize:P.memorySize});this.builder.addResource(fe,he)}if(this.mergedConfig.infrastructure?.api){let{restApi:b,logicalId:P}=id.createRestApi({slug:l,environment:S,apiName:`${l}-${S}-api`});this.builder.addResource(P,b)}}generateServer(l,S){if(!this.mergedConfig.infrastructure?.servers)return;let b=this.mergedConfig.infrastructure.servers,P=this.mergedConfig.infrastructure?.compute,v=this.mergedConfig.infrastructure?.ssl;if(Object.values(b).some((he)=>!he.privateNetwork||he.privateNetwork==="create"))this.generateNetworkInfrastructure(l,S);for(let[he,fe]of Object.entries(b)){let Ye=fe.instanceType||fe.size||P?.size,et=(Ye?o.InstanceSize.specs[Ye]:void 0)?.instanceType||Ye||"t3.micro",nr=fe.type||"app",vt=fe.userData||fe.startupScript;if(!vt)vt=o.UserData.generateAppServerScript({runtime:"bun",runtimeVersion:fe.bunVersion||"latest",webServer:"none",domain:fe.domain,enableSsl:!!v?.enabled,sslEmail:v?.letsEncrypt?.email,installRedis:nr==="cache",installDatabaseClients:!!fe.database});let or=fe.privateNetwork&&fe.privateNetwork!=="create"?fe.privateNetwork:{Ref:"VPC"},Tt=fe.subnet||{Ref:"PublicSubnet1"},we=!!this.mergedConfig.infrastructure?.email?.server?.enabled,wt=[22,80,443,this.resolveApiOriginPort()];if(we)wt.push(25,465,587,143,993);let re=o.createServerModeStack({slug:`${l}-${he}`,environment:S,vpcId:or,subnetId:Tt,instanceType:et,keyName:fe.keyName||`${l}-${S}`,domain:fe.domain,userData:vt,volumeSize:fe.diskSize||20,imageId:fe.image,allowedPorts:wt});for(let[Rt,Dt]of Object.entries(re.resources))this.builder.addResource(Rt,Dt);this.serverEipLogicalIds.set(he,re.outputs.eipLogicalId),this.serverEipLogicalIds.set(`${he}Instance`,re.outputs.instanceLogicalId),this.builder.addOutput(`${he}InstanceId`,{Value:{Ref:re.outputs.instanceLogicalId},Description:`Instance ID for ${he} server`}),this.builder.addOutput(`${he}PublicIp`,{Value:{Ref:re.outputs.eipLogicalId},Description:`Public IP for ${he} server`})}}generateComputeApp(l,S){let b=this.mergedConfig.infrastructure?.compute;if(!b)return;let P=this.mergedConfig.sites||{},v=Object.entries(P),he=this.mergedConfig.infrastructure?.dns?.domain,fe=this.mergedConfig.infrastructure?.database,Ye=b.size,et=(Ye?o.InstanceSize.specs[Ye]:void 0)?.instanceType||Ye||"t3.micro";if(!this.builder.hasResource("VPC"))this.generateNetworkInfrastructure(l,S);let nr=this.buildCaddyfile(v),vt=o.UserData.generateBunAppScript({runtime:b.runtime||"bun",runtimeVersion:b.runtimeVersion||"latest",systemPackages:b.systemPackages,database:fe,caddyfile:nr}),or=as(b.appUpdates),Tt=or.length>0?`${vt}
11
+ ${or.join(`
12
12
  `)}
13
- `:C,m=i.map(([,A])=>A.port).filter((A)=>typeof A==="number"&&![80,443].includes(A)),c=this.resolveApiOriginPort(),y=`${e}${t}DeployBucket`.replace(/[^a-zA-Z0-9]/g,""),o=`${e}-${t}-deploy`;this.builder.addResource(y,{Type:"AWS::S3::Bucket",Properties:{BucketName:o,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:e},{Key:"Environment",Value:t},{Key:"ManagedBy",Value:"ts-cloud"}]}});let f=E.createServerModeStack({slug:`${e}-app`,environment:t,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},instanceType:u,keyName:r.allowSsh?`${e}-${t}`:void 0,domain:s,userData:g,volumeSize:r.disk?.size||20,imageId:r.image,allowedPorts:[...r.allowSsh?[22]:[],80,443,c,...m]}),h=f.resources[f.outputs.instanceLogicalId];if(h?.Properties){let A=h.Properties.Tags||[];h.Properties.Tags=[...A,{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:"app"},{Key:"ManagedBy",Value:"ts-cloud"}]}let S=f.resources[f.outputs.roleLogicalId];if(S?.Properties)S.Properties.Policies=S.Properties.Policies||[],S.Properties.Policies.push({PolicyName:"DeployBucketRead",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:GetObject","s3:ListBucket"],Resource:[`arn:aws:s3:::${o}`,`arn:aws:s3:::${o}/*`]}]}});for(let[A,R]of Object.entries(f.resources))this.builder.addResource(A,R);this.builder.addOutput("deployBucketName",{Value:{Ref:y},Description:"S3 bucket where release tarballs are uploaded"}),this.builder.addOutput("appInstanceId",{Value:{Ref:f.outputs.instanceLogicalId},Description:"EC2 instance ID for the app server"}),this.builder.addOutput("appPublicIp",{Value:{Ref:f.outputs.eipLogicalId},Description:"Public IP for the app server"}),this.serverEipLogicalIds.set("app",f.outputs.eipLogicalId),this.serverEipLogicalIds.set("appInstance",f.outputs.instanceLogicalId)}generateJumpBox(e,t){let r=this.mergedConfig.infrastructure?.jumpBox;if(!r)return;let n=r===!0?{}:r;if(n.enabled===!1)return;this.generateNetworkInfrastructure(e,t);let i=n.size||"micro",s=E.InstanceSize.specs[i]?.instanceType||i||"t3.micro",a;if(n.mountEfs)a={fileSystemId:typeof n.mountEfs==="string"?n.mountEfs:{Ref:"FileSystem"},mountPath:n.mountPath||"/mnt/efs"};let l;if(n.databaseTools)l=E.JumpBox.withDatabaseTools({slug:e,environment:t,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:n.keyName||`${e}-${t}`,allowedCidrs:n.allowedCidrs});else if(a)l=E.JumpBox.withEfsMount({slug:e,environment:t,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:n.keyName||`${e}-${t}`,fileSystemId:a.fileSystemId,mountPath:a.mountPath,allowedCidrs:n.allowedCidrs});else l=E.createJumpBox({slug:e,environment:t,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:n.keyName||`${e}-${t}`,instanceType:s,allowedCidrs:n.allowedCidrs,mountEfs:a});for(let[p,u]of Object.entries(l.resources))this.builder.addResource(p,u);this.builder.addOutput("JumpBoxInstanceId",{Value:{Ref:l.instanceLogicalId},Description:"The ID of the JumpBox EC2 instance (use with SSM Session Manager or SSH)"})}generateSharedInfrastructure(e,t){let r=this.mergedConfig.infrastructure?.ssl,n=this.mergedConfig.infrastructure?.dns,i=n?.domain,d=n?.hostedZoneId,s=[],a,l;if(r?.certificateArn)l=r.certificateArn;else if(r?.enabled&&i&&d){let m=r.domains||[i],c=m[0],y=m.slice(1).map((h)=>{if(h.includes(".")&&h.endsWith(c))return h.replace(`.${c}`,"");return h}),{certificate:o,logicalId:f}=ne.createCertificate({domain:c,subdomains:y,slug:e,environment:t,validationMethod:"DNS",hostedZoneId:d});a=f,this.builder.addResource(f,o)}if(this.mergedConfig.infrastructure?.storage){let m=Object.entries(this.mergedConfig.infrastructure.storage).some(([,o])=>o.website),c;if(m&&(a||l))c=`${e}${t}CloudFrontOAC`.replace(/[^a-zA-Z0-9]/g,""),this.builder.addResource(c,{Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${e}-${t}-s3-oac`,Description:`OAC for ${e} ${t} S3 website buckets`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}});let y=Object.entries(this.mergedConfig.infrastructure.storage).map(([o,f])=>({name:o,config:f,mountPath:this.normalizeMountPath(f),rewriteStyle:f.pathRewriteStyle||"directory",logicalId:this.storageBucketLogicalId(e,t,o)})).filter((o)=>o.name!=="public"&&o.config.website&&o.mountPath);for(let[o,f]of Object.entries(this.mergedConfig.infrastructure.storage)){let h=!!(f.website&&c),S=this.storageBucketName(e,t,o),{bucket:A,logicalId:R}=re.createBucket({slug:e,name:o,environment:t,bucketName:S,versioning:f.versioning,encryption:f.encryption,public:h?!1:f.public});if(h&&A.Properties)A.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1};if(this.builder.addResource(R,A),f.website){let D=typeof f.website==="object"?f.website:{},T=re.enableWebsiteHosting(A,D.indexDocument||"index.html",D.errorDocument);this.builder.addResource(R,T)}let I=this.normalizeMountPath(f);if(h&&c&&i&&!(I&&o!=="public")){let D=`${e}${t}${o}CDN`.replace(/[^a-zA-Z0-9]/g,""),T=[];if(f.aliases&&f.aliases.length>0)T.push(...f.aliases);else if(o==="public"){if(T.push(i),r?.domains?.includes(`www.${i}`))T.push(`www.${i}`)}else if(o==="docs")T.push(`docs.${i}`);else if(o==="blog")T.push(`blog.${i}`);let v=typeof f.website==="object"?f.website:{},O=f.spa===!0,_=v.errorDocument||(O?"index.html":"404.html"),M=[];if(O)M.push({ErrorCode:403,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:300});else M.push({ErrorCode:403,ResponseCode:404,ResponsePagePath:`/${_}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${_}`,ErrorCachingMinTTL:300});let z=l&&T.length>0?{AcmCertificateArn:l,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:a&&T.length>0?{AcmCertificateArn:{Ref:a},SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},B=`S3-${e}-${t}-${o}`,k=this.mergedConfig.project.region||"us-east-1",x;if(!O)x=`${e}${t}${o}UrlRewrite`.replace(/[^a-zA-Z0-9]/g,""),this.builder.addResource(x,{Type:"AWS::CloudFront::Function",Properties:{Name:`${e}-${t}-${o}-url-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`URL rewrite for ${e} ${t} ${o} - 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 Q=[{Id:B,DomainName:{"Fn::Sub":`\${${R}}.s3.${k}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:c}}],G=[],ee=[];if(this.shouldRouteStorageBucketToCompute(o,f)){this.appendComputeAppOrigin(Q,G,ee,e,t,this.resolveComputeCachePathPatterns(f.computeRoutes));for(let w of y){let U=`S3-${e}-${t}-${w.name}`,te=`${e}${t}${w.name}PathMountRewrite`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(te,{Type:"AWS::CloudFront::Function",Properties:{Name:`${e}-${t}-${w.name}-path-mount-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`Path mount rewrite for ${e} ${t} ${w.name} at ${w.mountPath}`,Runtime:"cloudfront-js-2.0"},FunctionCode:this.pathMountRewriteFunctionCode(w.mountPath,w.rewriteStyle)}}),Q.push({Id:U,DomainName:{"Fn::Sub":`\${${w.logicalId}}.s3.${k}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:c}}),ee.push(w.logicalId,te);for(let ze of[w.mountPath,`${w.mountPath}/*`])G.push({PathPattern:ze,TargetOriginId:U,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":[te,"FunctionARN"]}}]})}}let ge={Type:"AWS::CloudFront::Distribution",DependsOn:[R,c,...x?[x]:[],...ee],Properties:{DistributionConfig:{Enabled:!0,Comment:`${e} ${t} ${o} site`,DefaultRootObject:"index.html",Origins:Q,DefaultCacheBehavior:{TargetOriginId:B,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",...x?{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[x,"FunctionARN"]}}]}:{}},...G.length>0?{CacheBehaviors:G}:{},...T.length>0?{Aliases:T}:{},ViewerCertificate:z,PriceClass:"PriceClass_100",HttpVersion:"http2and3",IPV6Enabled:!0,CustomErrorResponses:M}}};if(a)ge.DependsOn.push(a);this.builder.addResource(D,ge);let He=`${R}CloudFrontPolicy`;if(this.builder.addResource(He,{Type:"AWS::S3::BucketPolicy",DependsOn:[R,D],Properties:{Bucket:{Ref:R},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":`arn:aws:s3:::\${${R}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${D}}`}}}}]}}}),this.shouldRouteStorageBucketToCompute(o,f))for(let w of y){let U=`${w.logicalId}CloudFrontPolicy`;this.builder.addResource(U,{Type:"AWS::S3::BucketPolicy",DependsOn:[w.logicalId,D],Properties:{Bucket:{Ref:w.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:::\${${w.logicalId}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${D}}`}}}}]}}})}if(T.length>0)s.push({name:o,bucketLogicalId:R,distLogicalId:D,oacLogicalId:c,aliases:T});this.builder.addOutput(`${o}CloudFrontDomain`,{Value:{"Fn::GetAtt":[D,"DomainName"]},Description:`CloudFront domain for ${o}`}),this.builder.addOutput(`${o}CloudFrontDistributionId`,{Value:{Ref:D},Description:`CloudFront distribution ID for ${o}`})}if(this.builder.addOutput(`${o}BucketName`,{Value:{Ref:R},Description:`S3 bucket name for ${o}`}),o==="public")this.builder.addOutput("FrontendBucketName",{Value:{Ref:R},Description:"Frontend S3 bucket name"});if(o==="docs")this.builder.addOutput("DocsBucketName",{Value:{Ref:R},Description:"Documentation S3 bucket name"});if(o==="blog")this.builder.addOutput("BlogBucketName",{Value:{Ref:R},Description:"Blog S3 bucket name"})}}if(this.mergedConfig.infrastructure?.sftp){let m=this.mergedConfig.infrastructure.sftp,c=$e.create({...m,storage:this.resolveSftpStorage(m,e,t)??m.storage,slug:e,environment:t});for(let[y,o]of Object.entries(c.resources))this.builder.addResource(y,o);this.builder.addOutput("SftpServerId",{Value:{Ref:c.serverLogicalId},Description:"AWS Transfer Family SFTP server ID"}),this.builder.addOutput("SftpEndpoint",{Value:{"Fn::Sub":`\${${c.serverLogicalId}}.server.transfer.\${AWS::Region}.amazonaws.com`},Description:"AWS Transfer Family SFTP endpoint"}),this.builder.addOutput("SftpStorageDomain",{Value:c.domain,Description:"Storage backing the SFTP server (EFS or S3)"})}if(d&&s.length>0)for(let{name:m,distLogicalId:c,aliases:y}of s)for(let o of y){let f=o.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${f}ARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[c],Properties:{HostedZoneId:d,Name:o,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":[c,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}}),this.builder.addResource(`${f}AAAARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[c],Properties:{HostedZoneId:d,Name:o,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":[c,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}})}if(this.mergedConfig.infrastructure?.databases){for(let[m,c]of Object.entries(this.mergedConfig.infrastructure.databases))if(c.engine==="dynamodb"){let{table:y,logicalId:o}=K.createTable({slug:e,environment:t,tableName:`${e}-${t}-${m}`,partitionKey:c.partitionKey||{name:"id",type:"S"},sortKey:c.sortKey});this.builder.addResource(o,y)}else if(c.engine==="postgres"){let{dbInstance:y,logicalId:o}=K.createPostgres({slug:e,environment:t,dbInstanceIdentifier:`${e}-${t}-${m}`,masterUsername:c.username||"admin",masterUserPassword:c.password||"changeme123",allocatedStorage:c.storage||20,dbInstanceClass:c.instanceClass||"db.t3.micro"});this.builder.addResource(o,y)}else if(c.engine==="mysql"){let{dbInstance:y,logicalId:o}=K.createMysql({slug:e,environment:t,dbInstanceIdentifier:`${e}-${t}-${m}`,masterUsername:c.username||"admin",masterUserPassword:c.password||"changeme123",allocatedStorage:c.storage||20,dbInstanceClass:c.instanceClass||"db.t3.micro"});this.builder.addResource(o,y)}}if(this.mergedConfig.infrastructure?.cdn)for(let[m,c]of Object.entries(this.mergedConfig.infrastructure.cdn)){if(!c.origin)continue;let y=typeof c.customDomain==="string"?c.customDomain:c.customDomain?.domain||c.domain,o=typeof c.customDomain==="object"?c.customDomain?.certificateArn:c.certificateArn,f=o||l,h=`${e}${t}${m}CDN`.replace(/[^a-zA-Z0-9]/g,""),S=`S3-${e}-${t}-${m}-cdn`,A=[{Id:S,DomainName:c.origin,OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginShield:c.originShield?{Enabled:!0,OriginShieldRegion:c.originShieldRegion||this.mergedConfig.environments[t]?.region||this.mergedConfig.project.region||"us-east-1"}:{Enabled:!1}}],R=[],I=[];if(c.routeCompute)this.appendComputeAppOrigin(A,R,I,e,t,this.resolveComputeCachePathPatterns(c.computeRoutes));let D=f&&y?{AcmCertificateArn:a&&!o?{Ref:a}:f,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},T=[...I];if(a&&!o&&y)T.push(a);let v={Type:"AWS::CloudFront::Distribution",...T.length>0?{DependsOn:T}:{},Properties:{DistributionConfig:{Enabled:!0,Comment:`${e} ${t} ${m} CDN`,DefaultRootObject:"index.html",Origins:A,DefaultCacheBehavior:{TargetOriginId:S,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:c.compress!==!1,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},...R.length>0?{CacheBehaviors:R}:{},...y&&f?{Aliases:[y]}:{},ViewerCertificate:D,PriceClass:"PriceClass_100",HttpVersion:c.http3?"http2and3":"http2"}}};if(this.builder.addResource(h,v),d&&y&&f){let O=y.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${O}CdnARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[h,...a&&!o?[a]:[]],Properties:{HostedZoneId:d,Name:y,Type:"A",AliasTarget:{HostedZoneId:"Z2FDTNDATAQYW2",DNSName:{"Fn::GetAtt":[h,"DomainName"]}}}})}}if(this.mergedConfig.infrastructure?.queues)for(let[m,c]of Object.entries(this.mergedConfig.infrastructure.queues)){if(!this.shouldDeploy(c))continue;let{queue:y,logicalId:o}=ie.createQueue({slug:e,environment:t,name:`${e}-${t}-${m}`,fifo:c.fifo,visibilityTimeout:c.visibilityTimeout,messageRetentionPeriod:c.messageRetentionPeriod,delaySeconds:c.delaySeconds,maxMessageSize:c.maxMessageSize,receiveMessageWaitTime:c.receiveMessageWaitTime,contentBasedDeduplication:c.contentBasedDeduplication,encrypted:c.encrypted,kmsKeyId:c.kmsKeyId});this.builder.addResource(o,y);let f;if(c.deadLetterQueue){let{deadLetterQueue:h,updatedSourceQueue:S,deadLetterLogicalId:A}=ie.createDeadLetterQueue(o,{slug:e,environment:t,maxReceiveCount:c.maxReceiveCount});f=A,this.builder.addResource(A,h);let I=this.builder.getResources()[o];if(I?.Properties)I.Properties.RedrivePolicy=S.Properties?.RedrivePolicy}if(c.trigger){let h=c.trigger,S=`${e}${t}${h.functionName}`.replace(/[^a-zA-Z0-9]/g,""),A={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:{"Fn::GetAtt":[o,"Arn"]},FunctionName:{Ref:S},BatchSize:h.batchSize||10,MaximumBatchingWindowInSeconds:h.batchWindow||0,Enabled:!0,...h.reportBatchItemFailures!==!1&&{FunctionResponseTypes:["ReportBatchItemFailures"]},...h.maxConcurrency&&{ScalingConfig:{MaximumConcurrency:h.maxConcurrency}},...h.filterPattern&&{FilterCriteria:{Filters:[{Pattern:JSON.stringify(h.filterPattern)}]}}},DependsOn:[o,S]};this.builder.addResource(`${o}Trigger`,A)}if(c.alarms?.enabled){let h=c.alarms,S=h.notificationTopicArn;if(!S&&h.notificationEmails?.length){let I=`${o}AlarmTopic`;this.builder.addResource(I,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${e}-${t}-${m}-alarms`,DisplayName:`${m} Queue Alarms`}}),h.notificationEmails.forEach((D,T)=>{this.builder.addResource(`${I}Sub${T}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:I},Protocol:"email",Endpoint:D}})}),S={Ref:I}}let A=h.queueDepthThreshold||1000;this.builder.addResource(`${o}DepthAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${e}-${t}-${m}-queue-depth`,AlarmDescription:`Queue ${m} depth exceeds ${A} messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:A,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[o,"QueueName"]}}],...S&&{AlarmActions:[S],OKActions:[S]}}});let R=h.messageAgeThreshold||3600;if(this.builder.addResource(`${o}AgeAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${e}-${t}-${m}-message-age`,AlarmDescription:`Queue ${m} oldest message exceeds ${R} seconds`,MetricName:"ApproximateAgeOfOldestMessage",Namespace:"AWS/SQS",Statistic:"Maximum",Period:300,EvaluationPeriods:2,Threshold:R,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[o,"QueueName"]}}],...S&&{AlarmActions:[S],OKActions:[S]}}}),f&&h.dlqAlarm!==!1)this.builder.addResource(`${f}Alarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${e}-${t}-${m}-dlq-messages`,AlarmDescription:`Dead letter queue for ${m} has messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Sum",Period:300,EvaluationPeriods:1,Threshold:0,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[f,"QueueName"]}}],...S&&{AlarmActions:[S]}}})}if(c.subscribe){let h=c.subscribe,S=h.topicArn;if(!S&&h.topicName)S={Ref:h.topicName};if(S){this.builder.addResource(`${o}SnsPolicy`,{Type:"AWS::SQS::QueuePolicy",Properties:{Queues:[{Ref:o}],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"sns.amazonaws.com"},Action:"sqs:SendMessage",Resource:{"Fn::GetAtt":[o,"Arn"]},Condition:{ArnEquals:{"aws:SourceArn":S}}}]}}});let A={TopicArn:S,Protocol:"sqs",Endpoint:{"Fn::GetAtt":[o,"Arn"]},RawMessageDelivery:h.rawMessageDelivery||!1};if(h.filterPolicy)A.FilterPolicy=h.filterPolicy,A.FilterPolicyScope=h.filterPolicyScope||"MessageAttributes";this.builder.addResource(`${o}SnsSub`,{Type:"AWS::SNS::Subscription",Properties:A,DependsOn:`${o}SnsPolicy`})}}}if(this.mergedConfig.infrastructure?.realtime?.enabled)if((this.mergedConfig.infrastructure.realtime.mode||"serverless")==="server")this.generateRealtimeServerResources(e,t);else this.generateRealtimeResources(e,t);let p=this.mergedConfig.infrastructure?.redirects;if(p){let m=p.target||this.mergedConfig.infrastructure?.dns?.domain||"",c=p.protocol||"https";if(p.domains?.length&&m)for(let y of p.domains){let{bucket:o,bucketPolicy:f,logicalId:h,policyLogicalId:S}=q.createDomainRedirectBucket({slug:e,environment:t,sourceDomain:y,targetDomain:m,protocol:c});this.builder.addResource(h,o),this.builder.addResource(S,f)}if(p.paths&&Object.keys(p.paths).length>0){let y=q.fromMapping(p.paths,{statusCode:p.statusCode||301}),{function:o,logicalId:f}=q.createPathRedirectFunction({slug:e,environment:t,rules:y});this.builder.addResource(f,o)}}if(this.mergedConfig.infrastructure?.monitoring?.alarms)for(let[m,c]of Object.entries(this.mergedConfig.infrastructure.monitoring.alarms)){let{alarm:y,logicalId:o}=we.createAlarm({slug:e,environment:t,alarmName:`${e}-${t}-${m}`,metricName:c.metricName||"Errors",namespace:c.namespace||"AWS/Lambda",threshold:c.threshold||1,comparisonOperator:c.comparisonOperator||"GreaterThanThreshold"});this.builder.addResource(o,y)}let u=this.mergedConfig.infrastructure?.cache;if(u){let m=u.type||"redis";if(m==="redis"){this.generateNetworkInfrastructure(e,t);let c=u.redis||{},{replicationGroup:y,subnetGroup:o,logicalId:f,subnetGroupId:h}=oe.createRedis({slug:e,environment:t,nodeType:c.nodeType||u.nodeType||"cache.t3.micro",engineVersion:c.engineVersion||"7.1",port:c.port||6379,numCacheClusters:c.numCacheNodes||2,automaticFailover:c.automaticFailoverEnabled!==!1,atRestEncryption:!0,transitEncryption:!0,snapshotRetentionDays:c.snapshotRetentionLimit||7,snapshotWindow:c.snapshotWindow,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(f,y),o&&h)this.builder.addResource(h,o);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[f,"PrimaryEndPoint.Address"]},Description:"Redis primary endpoint address"}),this.builder.addOutput("CachePort",{Value:{"Fn::GetAtt":[f,"PrimaryEndPoint.Port"]},Description:"Redis primary endpoint port"})}else if(m==="memcached"){this.generateNetworkInfrastructure(e,t);let c=u.elasticache||{},{cluster:y,subnetGroup:o,logicalId:f,subnetGroupId:h}=oe.createMemcached({slug:e,environment:t,nodeType:c.nodeType||u.nodeType||"cache.t3.micro",engineVersion:c.engineVersion||"1.6.22",numCacheNodes:c.numCacheNodes||2,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(f,y),o&&h)this.builder.addResource(h,o);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[f,"ConfigurationEndpoint.Address"]},Description:"Memcached configuration endpoint address"})}}let b=this.mergedConfig.infrastructure?.email;if(b){let m=b.domain||this.mergedConfig.infrastructure?.dns?.domain;if(m){let{emailIdentity:c,logicalId:y}=L.verifyDomain({domain:m,slug:e,environment:t,enableDkim:b.enableDkim!==!1,dkimKeyLength:b.dkimKeyLength||"RSA_2048_BIT"});if(this.builder.addResource(y,c),b.configurationSet!==!1){let{configurationSet:h,logicalId:S}=L.createConfigurationSet({slug:e,environment:t});this.builder.addResource(S,h)}let o=b.hostedZoneId||this.mergedConfig.infrastructure?.dns?.hostedZoneId;if(o){if(b.enableDkim!==!1)for(let I=1;I<=3;I++){let D=`DkimRecord${I}${m.replace(/\./g,"")}`;this.builder.addResource(D,{Type:"AWS::Route53::RecordSet",DependsOn:[y],Properties:{HostedZoneId:o,Name:{"Fn::GetAtt":[y,`DkimDNSTokenName${I}`]},Type:"CNAME",TTL:1800,ResourceRecords:[{"Fn::GetAtt":[y,`DkimDNSTokenValue${I}`]}]}})}let{record:h,logicalId:S}=L.createSpfRecord(m,o);this.builder.addResource(S,h);let{record:A,logicalId:R}=L.createDmarcRecord(m,o,{policy:"none",reportingEmail:b.dmarcReportingEmail||`dmarc-reports@${m}`});this.builder.addResource(R,A)}this.builder.addOutput("EmailDomain",{Value:m,Description:"SES verified email domain"});let f=b.server;if(f?.enabled&&o){let h=this.mergedConfig.environments[t]?.region||this.mergedConfig.project.region||"us-east-1",S=`${e}-${t}-email`,{role:A,policy:R,roleLogicalId:I,policyLogicalId:D}=L.createEmailLambdaRole({slug:e,environment:t,s3BucketArn:`arn:aws:s3:::${S}`,sesIdentityArn:`arn:aws:ses:${h}:*:identity/${m}`});this.builder.addResource(I,A),this.builder.addResource(D,R);let{function:T,permission:v,logicalId:O,permissionLogicalId:_}=L.createInboundEmailLambda({slug:e,environment:t,roleArn:{"Fn::GetAtt":[I,"Arn"]},s3BucketName:S,organizedPrefix:"mailboxes/"});this.builder.addResource(O,T),this.builder.addResource(_,v);let M=L.createInboundEmailSetup({slug:e,environment:t,domain:m,s3BucketName:S,s3KeyPrefix:"inbox/",region:h,hostedZoneId:o,lambdaFunctionArn:{"Fn::GetAtt":[O,"Arn"]}});for(let[B,k]of Object.entries(M.resources)){if(k.Type==="AWS::SES::ReceiptRule")k.DependsOn=[_,O];this.builder.addResource(B,k)}this.builder.addOutput("InboundEmailLambda",{Value:{Ref:O},Description:"Inbound email processing Lambda function"}),this.builder.addOutput("EmailBucket",{Value:S,Description:"S3 bucket for email storage"});let z=this.serverEipLogicalIds.get("app");if(z&&o){let k=`${f?.subdomain||"mail"}.${m}`,x=k.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${x}ARecord`,{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:o,Name:k,Type:"A",TTL:"300",ResourceRecords:[{Ref:z}]}})}this.builder.addOutput("MailHost",{Value:`mail.${m}`,Description:"Mail server hostname for SMTP/IMAP clients"})}}}let C=this.mergedConfig.infrastructure?.search;if(C){let m=C.vpc?{subnetIds:[{Ref:"PublicSubnet1"}],securityGroupIds:[]}:void 0;if(m)this.generateNetworkInfrastructure(e,t);let{domain:c,logicalId:y}=Ee.createDomain({slug:e,environment:t,engineVersion:C.engineVersion||"OpenSearch_2.11",instanceType:C.instanceType||"t3.small.search",instanceCount:C.instanceCount||1,volumeSize:C.volumeSize||10,volumeType:C.volumeType||"gp3",dedicatedMaster:C.dedicatedMaster||!1,dedicatedMasterType:C.dedicatedMasterType,dedicatedMasterCount:C.dedicatedMasterCount||3,multiAz:C.multiAz||!1,encryption:C.encryption||{atRest:!0,nodeToNode:!0},advancedSecurity:C.advancedSecurity,autoTune:C.autoTune!==!1,vpc:m});this.builder.addResource(y,c),this.builder.addOutput("SearchDomainEndpoint",{Value:{"Fn::GetAtt":[y,"DomainEndpoint"]},Description:"OpenSearch domain endpoint"}),this.builder.addOutput("SearchDomainArn",{Value:{"Fn::GetAtt":[y,"Arn"]},Description:"OpenSearch domain ARN"})}let P=this.mergedConfig.infrastructure?.fileSystem;if(P&&Object.keys(P).length>0){this.generateNetworkInfrastructure(e,t);for(let[m,c]of Object.entries(P)){let{fileSystem:y,logicalId:o}=j.createFileSystem({slug:`${e}-${m}`,environment:t,encrypted:c.encrypted!==!1,performanceMode:c.performanceMode||"generalPurpose",throughputMode:c.throughputMode||"bursting",enableBackup:!0});this.builder.addResource(o,y);let{securityGroup:f,logicalId:h}=j.createEfsSecurityGroup({slug:`${e}-${m}`,environment:t,vpcId:{Ref:"VPC"},sourceCidrBlocks:["10.0.0.0/16"]});this.builder.addResource(h,f);let{mountTargets:S,logicalIds:A}=j.createMultiAzMountTargets(o,{slug:`${e}-${m}`,environment:t,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],securityGroupId:{Ref:h}});for(let R=0;R<S.length;R++)this.builder.addResource(A[R],S[R]);this.builder.addOutput(`${m}FileSystemId`,{Value:{Ref:o},Description:`EFS file system ID for ${m}`})}}let g=this.mergedConfig.infrastructure?.ai;if(g){let m=g.service||"ecs",c=g.models||["*"],y=g.allowStreaming!==!1,o;if(m==="ecs")o=F.enableBedrockForEcs({slug:e,environment:t,models:c,allowStreaming:y});else if(m==="ec2")o=F.enableBedrockForEc2({slug:e,environment:t,models:c,allowStreaming:y});else if(m==="lambda")o=F.enableBedrockForLambda({slug:e,environment:t,models:c,allowStreaming:y});else o=F.createBedrockRole(m,{slug:e,environment:t,models:c,allowStreaming:y});if(this.builder.addResource(o.logicalId,o.role),g.allowAsync){let{policy:f,logicalId:h}=F.createBedrockPolicy({slug:e,environment:t,models:c,allowStreaming:y,allowAsync:!0});this.builder.addResource(h,f)}this.builder.addOutput("BedrockRoleArn",{Value:{"Fn::GetAtt":[o.logicalId,"Arn"]},Description:"IAM role ARN with Bedrock permissions"})}}generateRealtimeResources(e,t){let r=this.mergedConfig.infrastructure?.realtime;if(!r)return;let n=r.name||`${e}-${t}-realtime`,i=r.scaling||{},d=r.storage||{type:"dynamodb"},s=i.handlerMemory||256,a=i.handlerTimeout||30,l=`${e}${t}RealtimeConnections`.replace(/[^a-zA-Z0-9]/g,""),p=`${e}${t}RealtimeChannels`.replace(/[^a-zA-Z0-9]/g,"");if(d.type==="dynamodb"){let A=d.dynamodb||{},R=A.billingMode||"PAY_PER_REQUEST";this.builder.addResource(l,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${e}-${t}-realtime-connections`,BillingMode:R,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"},...R==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:A.readCapacity||5,WriteCapacityUnits:A.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...R==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:A.readCapacity||5,WriteCapacityUnits:A.writeCapacity||5}},...A.pointInTimeRecovery&&{PointInTimeRecoverySpecification:{PointInTimeRecoveryEnabled:!0}},Tags:[{Key:"Name",Value:`${e}-${t}-realtime-connections`},{Key:"Environment",Value:t}]}}),this.builder.addResource(p,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${e}-${t}-realtime-channels`,BillingMode:R,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"},...R==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:A.readCapacity||5,WriteCapacityUnits:A.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...R==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:A.readCapacity||5,WriteCapacityUnits:A.writeCapacity||5}},Tags:[{Key:"Name",Value:`${e}-${t}-realtime-channels`},{Key:"Environment",Value:t}]}})}let u=`${e}${t}RealtimeRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(u,{Type:"AWS::IAM::Role",Properties:{RoleName:`${e}-${t}-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":[l,"Arn"]},{"Fn::Sub":`\${${l}.Arn}/index/*`},{"Fn::GetAtt":[p,"Arn"]},{"Fn::Sub":`\${${p}.Arn}/index/*`}]},{Effect:"Allow",Action:"execute-api:ManageConnections",Resource:{"Fn::Sub":"arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:*/*"}}]}}]}});let b=`${e}${t}RealtimeConnect`.replace(/[^a-zA-Z0-9]/g,""),C=`${e}${t}RealtimeDisconnect`.replace(/[^a-zA-Z0-9]/g,""),P=`${e}${t}RealtimeMessage`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(b,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e}-${t}-realtime-connect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[u,"Arn"]},MemorySize:s,Timeout:a,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:l},CHANNELS_TABLE:{Ref:p},ENVIRONMENT:t}},Code:{ZipFile:this.generateConnectHandlerCode()}},DependsOn:[u,l]}),this.builder.addResource(C,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e}-${t}-realtime-disconnect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[u,"Arn"]},MemorySize:s,Timeout:a,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:l},CHANNELS_TABLE:{Ref:p},ENVIRONMENT:t}},Code:{ZipFile:this.generateDisconnectHandlerCode()}},DependsOn:[u,l,p]}),this.builder.addResource(P,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${e}-${t}-realtime-message`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[u,"Arn"]},MemorySize:s,Timeout:a,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:l},CHANNELS_TABLE:{Ref:p},ENVIRONMENT:t}},Code:{ZipFile:this.generateMessageHandlerCode()}},DependsOn:[u,l,p]});let g=`${e}${t}RealtimeApi`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(g,{Type:"AWS::ApiGatewayV2::Api",Properties:{Name:n,ProtocolType:"WEBSOCKET",RouteSelectionExpression:"$request.body.action",Tags:{Name:n,Environment:t}}});let m=`${b}Permission`,c=`${C}Permission`,y=`${P}Permission`;this.builder.addResource(m,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:b},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${g}}/*/$connect`}}}),this.builder.addResource(c,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:C},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${g}}/*/$disconnect`}}}),this.builder.addResource(y,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:P},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${g}}/*/$default`}}});let o=`${g}ConnectInteg`,f=`${g}DisconnectInteg`,h=`${g}MessageInteg`;this.builder.addResource(o,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:g},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${b}.Arn}/invocations`}}}),this.builder.addResource(f,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:g},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${C}.Arn}/invocations`}}}),this.builder.addResource(h,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:g},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${P}.Arn}/invocations`}}}),this.builder.addResource(`${g}ConnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:g},RouteKey:"$connect",AuthorizationType:"NONE",Target:{"Fn::Sub":`integrations/\${${o}}`}}}),this.builder.addResource(`${g}DisconnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:g},RouteKey:"$disconnect",Target:{"Fn::Sub":`integrations/\${${f}}`}}}),this.builder.addResource(`${g}DefaultRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:g},RouteKey:"$default",Target:{"Fn::Sub":`integrations/\${${h}}`}}});let S=`${g}Stage`;if(this.builder.addResource(S,{Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:{Ref:g},StageName:t,AutoDeploy:!0,DefaultRouteSettings:{ThrottlingBurstLimit:i.messagesPerSecond||1000,ThrottlingRateLimit:i.messagesPerSecond||1000}}}),r.monitoring?.enabled){let A=r.monitoring,R=A.notificationTopicArn;if(!R&&A.notificationEmails?.length){let I=`${g}AlarmTopic`;this.builder.addResource(I,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${e}-${t}-realtime-alarms`,DisplayName:"Realtime WebSocket Alarms"}}),A.notificationEmails.forEach((D,T)=>{this.builder.addResource(`${I}Sub${T}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:I},Protocol:"email",Endpoint:D}})}),R={Ref:I}}if(A.connectionThreshold)this.builder.addResource(`${g}ConnectionAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${e}-${t}-realtime-connections`,AlarmDescription:`WebSocket connections exceed ${A.connectionThreshold}`,MetricName:"ConnectCount",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:300,EvaluationPeriods:2,Threshold:A.connectionThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:g}}],...R&&{AlarmActions:[R]}}});if(A.errorThreshold)this.builder.addResource(`${g}ErrorAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${e}-${t}-realtime-errors`,AlarmDescription:`WebSocket errors exceed ${A.errorThreshold}/min`,MetricName:"ExecutionError",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:60,EvaluationPeriods:3,Threshold:A.errorThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:g}}],...R&&{AlarmActions:[R]}}})}this.builder.addOutput(`${g}Endpoint`,{Description:"WebSocket API endpoint URL",Value:{"Fn::Sub":`wss://\${${g}}.execute-api.\${AWS::Region}.amazonaws.com/${t}`},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-endpoint"}}}),this.builder.addOutput(`${g}Id`,{Description:"WebSocket API ID",Value:{Ref:g},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-api-id"}}})}generateConnectHandlerCode(){return`
13
+ `:vt,ht=v.map(([,Jt])=>Jt.port).filter((Jt)=>typeof Jt==="number"&&![80,443].includes(Jt)),we=this.resolveApiOriginPort(),wt=`${l}${S}DeployBucket`.replace(/[^a-zA-Z0-9]/g,""),re=`${l}-${S}-deploy`;this.builder.addResource(wt,{Type:"AWS::S3::Bucket",Properties:{BucketName:re,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=o.createServerModeStack({slug:`${l}-app`,environment:S,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},instanceType:et,keyName:b.allowSsh?`${l}-${S}`:void 0,domain:he,userData:Tt,volumeSize:b.disk?.size||20,imageId:b.image,allowedPorts:[...b.allowSsh?[22]:[],80,443,we,...ht]}),Dt=Rt.resources[Rt.outputs.instanceLogicalId];if(Dt?.Properties){let Jt=Dt.Properties.Tags||[];Dt.Properties.Tags=[...Jt,{Key:"Project",Value:l},{Key:"Environment",Value:S},{Key:"Role",Value:"app"},{Key:"ManagedBy",Value:"ts-cloud"}]}let Nt=Rt.resources[Rt.outputs.roleLogicalId];if(Nt?.Properties)Nt.Properties.Policies=Nt.Properties.Policies||[],Nt.Properties.Policies.push({PolicyName:"DeployBucketRead",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:GetObject","s3:ListBucket"],Resource:[`arn:aws:s3:::${re}`,`arn:aws:s3:::${re}/*`]}]}});for(let[Jt,ir]of Object.entries(Rt.resources))this.builder.addResource(Jt,ir);this.builder.addOutput("deployBucketName",{Value:{Ref:wt},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 b=this.mergedConfig.infrastructure?.jumpBox;if(!b)return;let P=b===!0?{}:b;if(P.enabled===!1)return;this.generateNetworkInfrastructure(l,S);let v=P.size||"micro",he=o.InstanceSize.specs[v]?.instanceType||v||"t3.micro",fe;if(P.mountEfs)fe={fileSystemId:typeof P.mountEfs==="string"?P.mountEfs:{Ref:"FileSystem"},mountPath:P.mountPath||"/mnt/efs"};let Ye;if(P.databaseTools)Ye=o.JumpBox.withDatabaseTools({slug:l,environment:S,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:P.keyName||`${l}-${S}`,allowedCidrs:P.allowedCidrs});else if(fe)Ye=o.JumpBox.withEfsMount({slug:l,environment:S,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:P.keyName||`${l}-${S}`,fileSystemId:fe.fileSystemId,mountPath:fe.mountPath,allowedCidrs:P.allowedCidrs});else Ye=o.createJumpBox({slug:l,environment:S,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:P.keyName||`${l}-${S}`,instanceType:he,allowedCidrs:P.allowedCidrs,mountEfs:fe});for(let[tt,et]of Object.entries(Ye.resources))this.builder.addResource(tt,et);this.builder.addOutput("JumpBoxInstanceId",{Value:{Ref:Ye.instanceLogicalId},Description:"The ID of the JumpBox EC2 instance (use with SSM Session Manager or SSH)"})}generateSharedInfrastructure(l,S){let b=this.mergedConfig.infrastructure?.ssl,P=this.mergedConfig.infrastructure?.dns,v=P?.domain,Xe=P?.hostedZoneId,he=[],fe,Ye;if(b?.certificateArn)Ye=b.certificateArn;else if(b?.enabled&&v&&Xe){let ht=b.domains||[v],we=ht[0],wt=ht.slice(1).map((Dt)=>{if(Dt.includes(".")&&Dt.endsWith(we))return Dt.replace(`.${we}`,"");return Dt}),{certificate:re,logicalId:Rt}=I.createCertificate({domain:we,subdomains:wt,slug:l,environment:S,validationMethod:"DNS",hostedZoneId:Xe});fe=Rt,this.builder.addResource(Rt,re)}if(this.mergedConfig.infrastructure?.storage){let ht=Object.entries(this.mergedConfig.infrastructure.storage).some(([,re])=>re.website),we;if(ht&&(fe||Ye))we=`${l}${S}CloudFrontOAC`.replace(/[^a-zA-Z0-9]/g,""),this.builder.addResource(we,{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 wt=Object.entries(this.mergedConfig.infrastructure.storage).map(([re,Rt])=>({name:re,config:Rt,mountPath:this.normalizeMountPath(Rt),rewriteStyle:Rt.pathRewriteStyle||"directory",logicalId:this.storageBucketLogicalId(l,S,re)})).filter((re)=>re.name!=="public"&&re.config.website&&re.mountPath);for(let[re,Rt]of Object.entries(this.mergedConfig.infrastructure.storage)){let Dt=!!(Rt.website&&we),Nt=this.storageBucketName(l,S,re),{bucket:Jt,logicalId:ir}=Se.createBucket({slug:l,name:re,environment:S,bucketName:Nt,versioning:Rt.versioning,encryption:Rt.encryption,public:Dt?!1:Rt.public});if(Dt&&Jt.Properties)Jt.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1};if(this.builder.addResource(ir,Jt),Rt.website){let mr=typeof Rt.website==="object"?Rt.website:{},sr=Se.enableWebsiteHosting(Jt,mr.indexDocument||"index.html",mr.errorDocument);this.builder.addResource(ir,sr)}let pr=this.normalizeMountPath(Rt);if(Dt&&we&&v&&!(pr&&re!=="public")){let mr=`${l}${S}${re}CDN`.replace(/[^a-zA-Z0-9]/g,""),sr=[];if(Rt.aliases&&Rt.aliases.length>0)sr.push(...Rt.aliases);else if(re==="public"){if(sr.push(v),b?.domains?.includes(`www.${v}`))sr.push(`www.${v}`)}else if(re==="docs")sr.push(`docs.${v}`);else if(re==="blog")sr.push(`blog.${v}`);let Jr=typeof Rt.website==="object"?Rt.website:{},tn=Rt.spa===!0,En=Jr.errorDocument||(tn?"index.html":"404.html"),kn=[];if(tn)kn.push({ErrorCode:403,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:300});else kn.push({ErrorCode:403,ResponseCode:404,ResponsePagePath:`/${En}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${En}`,ErrorCachingMinTTL:300});let Vi=Ye&&sr.length>0?{AcmCertificateArn:Ye,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:fe&&sr.length>0?{AcmCertificateArn:{Ref:fe},SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},Fn=`S3-${l}-${S}-${re}`,bn=this.mergedConfig.project.region||"us-east-1",In;if(!tn)In=`${l}${S}${re}UrlRewrite`.replace(/[^a-zA-Z0-9]/g,""),this.builder.addResource(In,{Type:"AWS::CloudFront::Function",Properties:{Name:`${l}-${S}-${re}-url-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`URL rewrite for ${l} ${S} ${re} - 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 Yo=[{Id:Fn,DomainName:{"Fn::Sub":`\${${ir}}.s3.${bn}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:we}}],Wi=[],Ta=[];if(this.shouldRouteStorageBucketToCompute(re,Rt)){this.appendComputeAppOrigin(Yo,Wi,Ta,l,S,this.resolveComputeCachePathPatterns(Rt.computeRoutes));for(let hr of wt){let qi=`S3-${l}-${S}-${hr.name}`,Ea=`${l}${S}${hr.name}PathMountRewrite`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Ea,{Type:"AWS::CloudFront::Function",Properties:{Name:`${l}-${S}-${hr.name}-path-mount-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`Path mount rewrite for ${l} ${S} ${hr.name} at ${hr.mountPath}`,Runtime:"cloudfront-js-2.0"},FunctionCode:this.pathMountRewriteFunctionCode(hr.mountPath,hr.rewriteStyle)}}),Yo.push({Id:qi,DomainName:{"Fn::Sub":`\${${hr.logicalId}}.s3.${bn}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:we}}),Ta.push(hr.logicalId,Ea);for(let bl of[hr.mountPath,`${hr.mountPath}/*`])Wi.push({PathPattern:bl,TargetOriginId:qi,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":[Ea,"FunctionARN"]}}]})}}let Ha={Type:"AWS::CloudFront::Distribution",DependsOn:[ir,we,...In?[In]:[],...Ta],Properties:{DistributionConfig:{Enabled:!0,Comment:`${l} ${S} ${re} site`,DefaultRootObject:"index.html",Origins:Yo,DefaultCacheBehavior:{TargetOriginId:Fn,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",...In?{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[In,"FunctionARN"]}}]}:{}},...Wi.length>0?{CacheBehaviors:Wi}:{},...sr.length>0?{Aliases:sr}:{},ViewerCertificate:Vi,PriceClass:"PriceClass_100",HttpVersion:"http2and3",IPV6Enabled:!0,CustomErrorResponses:kn}}};if(fe)Ha.DependsOn.push(fe);this.builder.addResource(mr,Ha);let Cl=`${ir}CloudFrontPolicy`;if(this.builder.addResource(Cl,{Type:"AWS::S3::BucketPolicy",DependsOn:[ir,mr],Properties:{Bucket:{Ref:ir},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":`arn:aws:s3:::\${${ir}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${mr}}`}}}}]}}}),this.shouldRouteStorageBucketToCompute(re,Rt))for(let hr of wt){let qi=`${hr.logicalId}CloudFrontPolicy`;this.builder.addResource(qi,{Type:"AWS::S3::BucketPolicy",DependsOn:[hr.logicalId,mr],Properties:{Bucket:{Ref:hr.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:::\${${hr.logicalId}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${mr}}`}}}}]}}})}if(sr.length>0)he.push({name:re,bucketLogicalId:ir,distLogicalId:mr,oacLogicalId:we,aliases:sr});this.builder.addOutput(`${re}CloudFrontDomain`,{Value:{"Fn::GetAtt":[mr,"DomainName"]},Description:`CloudFront domain for ${re}`}),this.builder.addOutput(`${re}CloudFrontDistributionId`,{Value:{Ref:mr},Description:`CloudFront distribution ID for ${re}`})}if(this.builder.addOutput(`${re}BucketName`,{Value:{Ref:ir},Description:`S3 bucket name for ${re}`}),re==="public")this.builder.addOutput("FrontendBucketName",{Value:{Ref:ir},Description:"Frontend S3 bucket name"});if(re==="docs")this.builder.addOutput("DocsBucketName",{Value:{Ref:ir},Description:"Documentation S3 bucket name"});if(re==="blog")this.builder.addOutput("BlogBucketName",{Value:{Ref:ir},Description:"Blog S3 bucket name"})}}if(this.mergedConfig.infrastructure?.sftp){let ht=this.mergedConfig.infrastructure.sftp,we=nd.create({...ht,storage:this.resolveSftpStorage(ht,l,S)??ht.storage,slug:l,environment:S});for(let[wt,re]of Object.entries(we.resources))this.builder.addResource(wt,re);this.builder.addOutput("SftpServerId",{Value:{Ref:we.serverLogicalId},Description:"AWS Transfer Family SFTP server ID"}),this.builder.addOutput("SftpEndpoint",{Value:{"Fn::Sub":`\${${we.serverLogicalId}}.server.transfer.\${AWS::Region}.amazonaws.com`},Description:"AWS Transfer Family SFTP endpoint"}),this.builder.addOutput("SftpStorageDomain",{Value:we.domain,Description:"Storage backing the SFTP server (EFS or S3)"})}if(Xe&&he.length>0)for(let{name:ht,distLogicalId:we,aliases:wt}of he)for(let re of wt){let Rt=re.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${Rt}ARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[we],Properties:{HostedZoneId:Xe,Name:re,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":[we,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}}),this.builder.addResource(`${Rt}AAAARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[we],Properties:{HostedZoneId:Xe,Name:re,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":[we,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}})}if(this.mergedConfig.infrastructure?.databases){for(let[ht,we]of Object.entries(this.mergedConfig.infrastructure.databases))if(we.engine==="dynamodb"){let{table:wt,logicalId:re}=Ft.createTable({slug:l,environment:S,tableName:`${l}-${S}-${ht}`,partitionKey:we.partitionKey||{name:"id",type:"S"},sortKey:we.sortKey});this.builder.addResource(re,wt)}else if(we.engine==="postgres"){let{dbInstance:wt,logicalId:re}=Ft.createPostgres({slug:l,environment:S,dbInstanceIdentifier:`${l}-${S}-${ht}`,masterUsername:we.username||"admin",masterUserPassword:we.password||"changeme123",allocatedStorage:we.storage||20,dbInstanceClass:we.instanceClass||"db.t3.micro"});this.builder.addResource(re,wt)}else if(we.engine==="mysql"){let{dbInstance:wt,logicalId:re}=Ft.createMysql({slug:l,environment:S,dbInstanceIdentifier:`${l}-${S}-${ht}`,masterUsername:we.username||"admin",masterUserPassword:we.password||"changeme123",allocatedStorage:we.storage||20,dbInstanceClass:we.instanceClass||"db.t3.micro"});this.builder.addResource(re,wt)}}if(this.mergedConfig.infrastructure?.cdn)for(let[ht,we]of Object.entries(this.mergedConfig.infrastructure.cdn)){if(!we.origin)continue;let wt=typeof we.customDomain==="string"?we.customDomain:we.customDomain?.domain||we.domain,re=typeof we.customDomain==="object"?we.customDomain?.certificateArn:we.certificateArn,Rt=re||Ye,Dt=`${l}${S}${ht}CDN`.replace(/[^a-zA-Z0-9]/g,""),Nt=`S3-${l}-${S}-${ht}-cdn`,Jt=[{Id:Nt,DomainName:we.origin,OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginShield:we.originShield?{Enabled:!0,OriginShieldRegion:we.originShieldRegion||this.mergedConfig.environments[S]?.region||this.mergedConfig.project.region||"us-east-1"}:{Enabled:!1}}],ir=[],pr=[];if(we.routeCompute)this.appendComputeAppOrigin(Jt,ir,pr,l,S,this.resolveComputeCachePathPatterns(we.computeRoutes));let mr=Rt&&wt?{AcmCertificateArn:fe&&!re?{Ref:fe}:Rt,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},sr=[...pr];if(fe&&!re&&wt)sr.push(fe);let Jr={Type:"AWS::CloudFront::Distribution",...sr.length>0?{DependsOn:sr}:{},Properties:{DistributionConfig:{Enabled:!0,Comment:`${l} ${S} ${ht} CDN`,DefaultRootObject:"index.html",Origins:Jt,DefaultCacheBehavior:{TargetOriginId:Nt,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:we.compress!==!1,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},...ir.length>0?{CacheBehaviors:ir}:{},...wt&&Rt?{Aliases:[wt]}:{},ViewerCertificate:mr,PriceClass:"PriceClass_100",HttpVersion:we.http3?"http2and3":"http2"}}};if(this.builder.addResource(Dt,Jr),Xe&&wt&&Rt){let tn=wt.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${tn}CdnARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[Dt,...fe&&!re?[fe]:[]],Properties:{HostedZoneId:Xe,Name:wt,Type:"A",AliasTarget:{HostedZoneId:"Z2FDTNDATAQYW2",DNSName:{"Fn::GetAtt":[Dt,"DomainName"]}}}})}}if(this.mergedConfig.infrastructure?.queues)for(let[ht,we]of Object.entries(this.mergedConfig.infrastructure.queues)){if(!this.shouldDeploy(we))continue;let{queue:wt,logicalId:re}=M.createQueue({slug:l,environment:S,name:`${l}-${S}-${ht}`,fifo:we.fifo,visibilityTimeout:we.visibilityTimeout,messageRetentionPeriod:we.messageRetentionPeriod,delaySeconds:we.delaySeconds,maxMessageSize:we.maxMessageSize,receiveMessageWaitTime:we.receiveMessageWaitTime,contentBasedDeduplication:we.contentBasedDeduplication,encrypted:we.encrypted,kmsKeyId:we.kmsKeyId});this.builder.addResource(re,wt);let Rt;if(we.deadLetterQueue){let{deadLetterQueue:Dt,updatedSourceQueue:Nt,deadLetterLogicalId:Jt}=M.createDeadLetterQueue(re,{slug:l,environment:S,maxReceiveCount:we.maxReceiveCount});Rt=Jt,this.builder.addResource(Jt,Dt);let pr=this.builder.getResources()[re];if(pr?.Properties)pr.Properties.RedrivePolicy=Nt.Properties?.RedrivePolicy}if(we.trigger){let Dt=we.trigger,Nt=`${l}${S}${Dt.functionName}`.replace(/[^a-zA-Z0-9]/g,""),Jt={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:{"Fn::GetAtt":[re,"Arn"]},FunctionName:{Ref:Nt},BatchSize:Dt.batchSize||10,MaximumBatchingWindowInSeconds:Dt.batchWindow||0,Enabled:!0,...Dt.reportBatchItemFailures!==!1&&{FunctionResponseTypes:["ReportBatchItemFailures"]},...Dt.maxConcurrency&&{ScalingConfig:{MaximumConcurrency:Dt.maxConcurrency}},...Dt.filterPattern&&{FilterCriteria:{Filters:[{Pattern:JSON.stringify(Dt.filterPattern)}]}}},DependsOn:[re,Nt]};this.builder.addResource(`${re}Trigger`,Jt)}if(we.alarms?.enabled){let Dt=we.alarms,Nt=Dt.notificationTopicArn;if(!Nt&&Dt.notificationEmails?.length){let pr=`${re}AlarmTopic`;this.builder.addResource(pr,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${l}-${S}-${ht}-alarms`,DisplayName:`${ht} Queue Alarms`}}),Dt.notificationEmails.forEach((mr,sr)=>{this.builder.addResource(`${pr}Sub${sr}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:pr},Protocol:"email",Endpoint:mr}})}),Nt={Ref:pr}}let Jt=Dt.queueDepthThreshold||1000;this.builder.addResource(`${re}DepthAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-${ht}-queue-depth`,AlarmDescription:`Queue ${ht} depth exceeds ${Jt} messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:Jt,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[re,"QueueName"]}}],...Nt&&{AlarmActions:[Nt],OKActions:[Nt]}}});let ir=Dt.messageAgeThreshold||3600;if(this.builder.addResource(`${re}AgeAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-${ht}-message-age`,AlarmDescription:`Queue ${ht} oldest message exceeds ${ir} seconds`,MetricName:"ApproximateAgeOfOldestMessage",Namespace:"AWS/SQS",Statistic:"Maximum",Period:300,EvaluationPeriods:2,Threshold:ir,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[re,"QueueName"]}}],...Nt&&{AlarmActions:[Nt],OKActions:[Nt]}}}),Rt&&Dt.dlqAlarm!==!1)this.builder.addResource(`${Rt}Alarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-${ht}-dlq-messages`,AlarmDescription:`Dead letter queue for ${ht} 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"]}}],...Nt&&{AlarmActions:[Nt]}}})}if(we.subscribe){let Dt=we.subscribe,Nt=Dt.topicArn;if(!Nt&&Dt.topicName)Nt={Ref:Dt.topicName};if(Nt){this.builder.addResource(`${re}SnsPolicy`,{Type:"AWS::SQS::QueuePolicy",Properties:{Queues:[{Ref:re}],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"sns.amazonaws.com"},Action:"sqs:SendMessage",Resource:{"Fn::GetAtt":[re,"Arn"]},Condition:{ArnEquals:{"aws:SourceArn":Nt}}}]}}});let Jt={TopicArn:Nt,Protocol:"sqs",Endpoint:{"Fn::GetAtt":[re,"Arn"]},RawMessageDelivery:Dt.rawMessageDelivery||!1};if(Dt.filterPolicy)Jt.FilterPolicy=Dt.filterPolicy,Jt.FilterPolicyScope=Dt.filterPolicyScope||"MessageAttributes";this.builder.addResource(`${re}SnsSub`,{Type:"AWS::SNS::Subscription",Properties:Jt,DependsOn:`${re}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 tt=this.mergedConfig.infrastructure?.redirects;if(tt){let ht=tt.target||this.mergedConfig.infrastructure?.dns?.domain||"",we=tt.protocol||"https";if(tt.domains?.length&&ht)for(let wt of tt.domains){let{bucket:re,bucketPolicy:Rt,logicalId:Dt,policyLogicalId:Nt}=ct.createDomainRedirectBucket({slug:l,environment:S,sourceDomain:wt,targetDomain:ht,protocol:we});this.builder.addResource(Dt,re),this.builder.addResource(Nt,Rt)}if(tt.paths&&Object.keys(tt.paths).length>0){let wt=ct.fromMapping(tt.paths,{statusCode:tt.statusCode||301}),{function:re,logicalId:Rt}=ct.createPathRedirectFunction({slug:l,environment:S,rules:wt});this.builder.addResource(Rt,re)}}if(this.mergedConfig.infrastructure?.monitoring?.alarms)for(let[ht,we]of Object.entries(this.mergedConfig.infrastructure.monitoring.alarms)){let{alarm:wt,logicalId:re}=Gs.createAlarm({slug:l,environment:S,alarmName:`${l}-${S}-${ht}`,metricName:we.metricName||"Errors",namespace:we.namespace||"AWS/Lambda",threshold:we.threshold||1,comparisonOperator:we.comparisonOperator||"GreaterThanThreshold"});this.builder.addResource(re,wt)}let et=this.mergedConfig.infrastructure?.cache;if(et){let ht=et.type||"redis";if(ht==="redis"){this.generateNetworkInfrastructure(l,S);let we=et.redis||{},{replicationGroup:wt,subnetGroup:re,logicalId:Rt,subnetGroupId:Dt}=Hs.createRedis({slug:l,environment:S,nodeType:we.nodeType||et.nodeType||"cache.t3.micro",engineVersion:we.engineVersion||"7.1",port:we.port||6379,numCacheClusters:we.numCacheNodes||2,automaticFailover:we.automaticFailoverEnabled!==!1,atRestEncryption:!0,transitEncryption:!0,snapshotRetentionDays:we.snapshotRetentionLimit||7,snapshotWindow:we.snapshotWindow,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(Rt,wt),re&&Dt)this.builder.addResource(Dt,re);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(ht==="memcached"){this.generateNetworkInfrastructure(l,S);let we=et.elasticache||{},{cluster:wt,subnetGroup:re,logicalId:Rt,subnetGroupId:Dt}=Hs.createMemcached({slug:l,environment:S,nodeType:we.nodeType||et.nodeType||"cache.t3.micro",engineVersion:we.engineVersion||"1.6.22",numCacheNodes:we.numCacheNodes||2,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(Rt,wt),re&&Dt)this.builder.addResource(Dt,re);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[Rt,"ConfigurationEndpoint.Address"]},Description:"Memcached configuration endpoint address"})}}let nr=this.mergedConfig.infrastructure?.email;if(nr){let ht=nr.domain||this.mergedConfig.infrastructure?.dns?.domain;if(ht){let{emailIdentity:we,logicalId:wt}=m.verifyDomain({domain:ht,slug:l,environment:S,enableDkim:nr.enableDkim!==!1,dkimKeyLength:nr.dkimKeyLength||"RSA_2048_BIT"});if(this.builder.addResource(wt,we),nr.configurationSet!==!1){let{configurationSet:Dt,logicalId:Nt}=m.createConfigurationSet({slug:l,environment:S});this.builder.addResource(Nt,Dt)}let re=nr.hostedZoneId||this.mergedConfig.infrastructure?.dns?.hostedZoneId;if(re){if(nr.enableDkim!==!1)for(let pr=1;pr<=3;pr++){let mr=`DkimRecord${pr}${ht.replace(/\./g,"")}`;this.builder.addResource(mr,{Type:"AWS::Route53::RecordSet",DependsOn:[wt],Properties:{HostedZoneId:re,Name:{"Fn::GetAtt":[wt,`DkimDNSTokenName${pr}`]},Type:"CNAME",TTL:1800,ResourceRecords:[{"Fn::GetAtt":[wt,`DkimDNSTokenValue${pr}`]}]}})}let{record:Dt,logicalId:Nt}=m.createSpfRecord(ht,re);this.builder.addResource(Nt,Dt);let{record:Jt,logicalId:ir}=m.createDmarcRecord(ht,re,{policy:"none",reportingEmail:nr.dmarcReportingEmail||`dmarc-reports@${ht}`});this.builder.addResource(ir,Jt)}this.builder.addOutput("EmailDomain",{Value:ht,Description:"SES verified email domain"});let Rt=nr.server;if(Rt?.enabled&&re){let Dt=this.mergedConfig.environments[S]?.region||this.mergedConfig.project.region||"us-east-1",Nt=`${l}-${S}-email`,{role:Jt,policy:ir,roleLogicalId:pr,policyLogicalId:mr}=m.createEmailLambdaRole({slug:l,environment:S,s3BucketArn:`arn:aws:s3:::${Nt}`,sesIdentityArn:`arn:aws:ses:${Dt}:*:identity/${ht}`});this.builder.addResource(pr,Jt),this.builder.addResource(mr,ir);let{function:sr,permission:Jr,logicalId:tn,permissionLogicalId:En}=m.createInboundEmailLambda({slug:l,environment:S,roleArn:{"Fn::GetAtt":[pr,"Arn"]},s3BucketName:Nt,organizedPrefix:"mailboxes/"});this.builder.addResource(tn,sr),this.builder.addResource(En,Jr);let kn=m.createInboundEmailSetup({slug:l,environment:S,domain:ht,s3BucketName:Nt,s3KeyPrefix:"inbox/",region:Dt,hostedZoneId:re,lambdaFunctionArn:{"Fn::GetAtt":[tn,"Arn"]}});for(let[Fn,bn]of Object.entries(kn.resources)){if(bn.Type==="AWS::SES::ReceiptRule")bn.DependsOn=[En,tn];this.builder.addResource(Fn,bn)}this.builder.addOutput("InboundEmailLambda",{Value:{Ref:tn},Description:"Inbound email processing Lambda function"}),this.builder.addOutput("EmailBucket",{Value:Nt,Description:"S3 bucket for email storage"});let Vi=this.serverEipLogicalIds.get("app");if(Vi&&re){let bn=`${Rt?.subdomain||"mail"}.${ht}`,In=bn.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${In}ARecord`,{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:re,Name:bn,Type:"A",TTL:"300",ResourceRecords:[{Ref:Vi}]}})}this.builder.addOutput("MailHost",{Value:`mail.${ht}`,Description:"Mail server hostname for SMTP/IMAP clients"})}}}let vt=this.mergedConfig.infrastructure?.search;if(vt){let ht=vt.vpc?{subnetIds:[{Ref:"PublicSubnet1"}],securityGroupIds:[]}:void 0;if(ht)this.generateNetworkInfrastructure(l,S);let{domain:we,logicalId:wt}=Ut.createDomain({slug:l,environment:S,engineVersion:vt.engineVersion||"OpenSearch_2.11",instanceType:vt.instanceType||"t3.small.search",instanceCount:vt.instanceCount||1,volumeSize:vt.volumeSize||10,volumeType:vt.volumeType||"gp3",dedicatedMaster:vt.dedicatedMaster||!1,dedicatedMasterType:vt.dedicatedMasterType,dedicatedMasterCount:vt.dedicatedMasterCount||3,multiAz:vt.multiAz||!1,encryption:vt.encryption||{atRest:!0,nodeToNode:!0},advancedSecurity:vt.advancedSecurity,autoTune:vt.autoTune!==!1,vpc:ht});this.builder.addResource(wt,we),this.builder.addOutput("SearchDomainEndpoint",{Value:{"Fn::GetAtt":[wt,"DomainEndpoint"]},Description:"OpenSearch domain endpoint"}),this.builder.addOutput("SearchDomainArn",{Value:{"Fn::GetAtt":[wt,"Arn"]},Description:"OpenSearch domain ARN"})}let or=this.mergedConfig.infrastructure?.fileSystem;if(or&&Object.keys(or).length>0){this.generateNetworkInfrastructure(l,S);for(let[ht,we]of Object.entries(or)){let{fileSystem:wt,logicalId:re}=Fe.createFileSystem({slug:`${l}-${ht}`,environment:S,encrypted:we.encrypted!==!1,performanceMode:we.performanceMode||"generalPurpose",throughputMode:we.throughputMode||"bursting",enableBackup:!0});this.builder.addResource(re,wt);let{securityGroup:Rt,logicalId:Dt}=Fe.createEfsSecurityGroup({slug:`${l}-${ht}`,environment:S,vpcId:{Ref:"VPC"},sourceCidrBlocks:["10.0.0.0/16"]});this.builder.addResource(Dt,Rt);let{mountTargets:Nt,logicalIds:Jt}=Fe.createMultiAzMountTargets(re,{slug:`${l}-${ht}`,environment:S,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],securityGroupId:{Ref:Dt}});for(let ir=0;ir<Nt.length;ir++)this.builder.addResource(Jt[ir],Nt[ir]);this.builder.addOutput(`${ht}FileSystemId`,{Value:{Ref:re},Description:`EFS file system ID for ${ht}`})}}let Tt=this.mergedConfig.infrastructure?.ai;if(Tt){let ht=Tt.service||"ecs",we=Tt.models||["*"],wt=Tt.allowStreaming!==!1,re;if(ht==="ecs")re=be.enableBedrockForEcs({slug:l,environment:S,models:we,allowStreaming:wt});else if(ht==="ec2")re=be.enableBedrockForEc2({slug:l,environment:S,models:we,allowStreaming:wt});else if(ht==="lambda")re=be.enableBedrockForLambda({slug:l,environment:S,models:we,allowStreaming:wt});else re=be.createBedrockRole(ht,{slug:l,environment:S,models:we,allowStreaming:wt});if(this.builder.addResource(re.logicalId,re.role),Tt.allowAsync){let{policy:Rt,logicalId:Dt}=be.createBedrockPolicy({slug:l,environment:S,models:we,allowStreaming:wt,allowAsync:!0});this.builder.addResource(Dt,Rt)}this.builder.addOutput("BedrockRoleArn",{Value:{"Fn::GetAtt":[re.logicalId,"Arn"]},Description:"IAM role ARN with Bedrock permissions"})}}generateRealtimeResources(l,S){let b=this.mergedConfig.infrastructure?.realtime;if(!b)return;let P=b.name||`${l}-${S}-realtime`,v=b.scaling||{},Xe=b.storage||{type:"dynamodb"},he=v.handlerMemory||256,fe=v.handlerTimeout||30,Ye=`${l}${S}RealtimeConnections`.replace(/[^a-zA-Z0-9]/g,""),tt=`${l}${S}RealtimeChannels`.replace(/[^a-zA-Z0-9]/g,"");if(Xe.type==="dynamodb"){let Jt=Xe.dynamodb||{},ir=Jt.billingMode||"PAY_PER_REQUEST";this.builder.addResource(Ye,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${l}-${S}-realtime-connections`,BillingMode:ir,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"},...ir==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Jt.readCapacity||5,WriteCapacityUnits:Jt.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...ir==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Jt.readCapacity||5,WriteCapacityUnits:Jt.writeCapacity||5}},...Jt.pointInTimeRecovery&&{PointInTimeRecoverySpecification:{PointInTimeRecoveryEnabled:!0}},Tags:[{Key:"Name",Value:`${l}-${S}-realtime-connections`},{Key:"Environment",Value:S}]}}),this.builder.addResource(tt,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${l}-${S}-realtime-channels`,BillingMode:ir,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"},...ir==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Jt.readCapacity||5,WriteCapacityUnits:Jt.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...ir==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Jt.readCapacity||5,WriteCapacityUnits:Jt.writeCapacity||5}},Tags:[{Key:"Name",Value:`${l}-${S}-realtime-channels`},{Key:"Environment",Value:S}]}})}let et=`${l}${S}RealtimeRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(et,{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":[Ye,"Arn"]},{"Fn::Sub":`\${${Ye}.Arn}/index/*`},{"Fn::GetAtt":[tt,"Arn"]},{"Fn::Sub":`\${${tt}.Arn}/index/*`}]},{Effect:"Allow",Action:"execute-api:ManageConnections",Resource:{"Fn::Sub":"arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:*/*"}}]}}]}});let nr=`${l}${S}RealtimeConnect`.replace(/[^a-zA-Z0-9]/g,""),vt=`${l}${S}RealtimeDisconnect`.replace(/[^a-zA-Z0-9]/g,""),or=`${l}${S}RealtimeMessage`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(nr,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${l}-${S}-realtime-connect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[et,"Arn"]},MemorySize:he,Timeout:fe,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:Ye},CHANNELS_TABLE:{Ref:tt},ENVIRONMENT:S}},Code:{ZipFile:this.generateConnectHandlerCode()}},DependsOn:[et,Ye]}),this.builder.addResource(vt,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${l}-${S}-realtime-disconnect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[et,"Arn"]},MemorySize:he,Timeout:fe,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:Ye},CHANNELS_TABLE:{Ref:tt},ENVIRONMENT:S}},Code:{ZipFile:this.generateDisconnectHandlerCode()}},DependsOn:[et,Ye,tt]}),this.builder.addResource(or,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${l}-${S}-realtime-message`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[et,"Arn"]},MemorySize:he,Timeout:fe,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:Ye},CHANNELS_TABLE:{Ref:tt},ENVIRONMENT:S}},Code:{ZipFile:this.generateMessageHandlerCode()}},DependsOn:[et,Ye,tt]});let Tt=`${l}${S}RealtimeApi`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Tt,{Type:"AWS::ApiGatewayV2::Api",Properties:{Name:P,ProtocolType:"WEBSOCKET",RouteSelectionExpression:"$request.body.action",Tags:{Name:P,Environment:S}}});let ht=`${nr}Permission`,we=`${vt}Permission`,wt=`${or}Permission`;this.builder.addResource(ht,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:nr},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${Tt}}/*/$connect`}}}),this.builder.addResource(we,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:vt},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${Tt}}/*/$disconnect`}}}),this.builder.addResource(wt,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:or},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${Tt}}/*/$default`}}});let re=`${Tt}ConnectInteg`,Rt=`${Tt}DisconnectInteg`,Dt=`${Tt}MessageInteg`;this.builder.addResource(re,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:Tt},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${nr}.Arn}/invocations`}}}),this.builder.addResource(Rt,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:Tt},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${vt}.Arn}/invocations`}}}),this.builder.addResource(Dt,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:Tt},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${or}.Arn}/invocations`}}}),this.builder.addResource(`${Tt}ConnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:Tt},RouteKey:"$connect",AuthorizationType:"NONE",Target:{"Fn::Sub":`integrations/\${${re}}`}}}),this.builder.addResource(`${Tt}DisconnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:Tt},RouteKey:"$disconnect",Target:{"Fn::Sub":`integrations/\${${Rt}}`}}}),this.builder.addResource(`${Tt}DefaultRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:Tt},RouteKey:"$default",Target:{"Fn::Sub":`integrations/\${${Dt}}`}}});let Nt=`${Tt}Stage`;if(this.builder.addResource(Nt,{Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:{Ref:Tt},StageName:S,AutoDeploy:!0,DefaultRouteSettings:{ThrottlingBurstLimit:v.messagesPerSecond||1000,ThrottlingRateLimit:v.messagesPerSecond||1000}}}),b.monitoring?.enabled){let Jt=b.monitoring,ir=Jt.notificationTopicArn;if(!ir&&Jt.notificationEmails?.length){let pr=`${Tt}AlarmTopic`;this.builder.addResource(pr,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${l}-${S}-realtime-alarms`,DisplayName:"Realtime WebSocket Alarms"}}),Jt.notificationEmails.forEach((mr,sr)=>{this.builder.addResource(`${pr}Sub${sr}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:pr},Protocol:"email",Endpoint:mr}})}),ir={Ref:pr}}if(Jt.connectionThreshold)this.builder.addResource(`${Tt}ConnectionAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-realtime-connections`,AlarmDescription:`WebSocket connections exceed ${Jt.connectionThreshold}`,MetricName:"ConnectCount",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:300,EvaluationPeriods:2,Threshold:Jt.connectionThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:Tt}}],...ir&&{AlarmActions:[ir]}}});if(Jt.errorThreshold)this.builder.addResource(`${Tt}ErrorAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-realtime-errors`,AlarmDescription:`WebSocket errors exceed ${Jt.errorThreshold}/min`,MetricName:"ExecutionError",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:60,EvaluationPeriods:3,Threshold:Jt.errorThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:Tt}}],...ir&&{AlarmActions:[ir]}}})}this.builder.addOutput(`${Tt}Endpoint`,{Description:"WebSocket API endpoint URL",Value:{"Fn::Sub":`wss://\${${Tt}}.execute-api.\${AWS::Region}.amazonaws.com/${S}`},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-endpoint"}}}),this.builder.addOutput(`${Tt}Id`,{Description:"WebSocket API ID",Value:{Ref:Tt},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(e,t){let r=this.mergedConfig.infrastructure?.realtime;if(!r)return;let n=r.server||{},i=n.port||6001,d=n.instances||1,s=`${e}${t}RealtimeSG`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(s,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`Security group for ${e} realtime WebSocket server`,GroupName:`${e}-${t}-realtime-sg`,VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:i,ToPort:i,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:`${e}-${t}-realtime-sg`},{Key:"Environment",Value:t}]}});let a=`${e}${t}RealtimeTaskDef`.replace(/[^a-zA-Z0-9]/g,""),l=`${e}${t}RealtimeTaskRole`.replace(/[^a-zA-Z0-9]/g,""),p=`${e}${t}RealtimeExecRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(p,{Type:"AWS::IAM::Role",Properties:{RoleName:`${e}-${t}-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(l,{Type:"AWS::IAM::Role",Properties:{RoleName:`${e}-${t}-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:"*"},...n.redis?.enabled?[{Effect:"Allow",Action:["elasticache:DescribeCacheClusters","elasticache:DescribeReplicationGroups"],Resource:"*"}]:[]]}}]}});let u=[{Name:"BROADCAST_HOST",Value:n.host||"0.0.0.0"},{Name:"BROADCAST_PORT",Value:String(i)},{Name:"NODE_ENV",Value:t==="production"?"production":"development"}];if(n.redis?.enabled){if(n.redis.useElastiCache)u.push({Name:"REDIS_HOST",Value:{"Fn::GetAtt":["CacheCluster","RedisEndpoint.Address"]}}),u.push({Name:"REDIS_PORT",Value:{"Fn::GetAtt":["CacheCluster","RedisEndpoint.Port"]}});else u.push({Name:"REDIS_HOST",Value:n.redis.host||"localhost"}),u.push({Name:"REDIS_PORT",Value:String(n.redis.port||6379)});if(n.redis.keyPrefix)u.push({Name:"REDIS_KEY_PREFIX",Value:n.redis.keyPrefix})}this.builder.addResource(a,{Type:"AWS::ECS::TaskDefinition",Properties:{Family:`${e}-${t}-realtime`,NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:"512",Memory:"1024",ExecutionRoleArn:{"Fn::GetAtt":[p,"Arn"]},TaskRoleArn:{"Fn::GetAtt":[l,"Arn"]},ContainerDefinitions:[{Name:"realtime",Image:{"Fn::Sub":`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${e}-realtime:latest`},Essential:!0,PortMappings:[{ContainerPort:i,Protocol:"tcp"}],Environment:u,LogConfiguration:{LogDriver:"awslogs",Options:{"awslogs-group":`/ecs/${e}-${t}-realtime`,"awslogs-region":{Ref:"AWS::Region"},"awslogs-stream-prefix":"realtime"}},HealthCheck:{Command:["CMD-SHELL",`curl -f http://localhost:${i}${n.healthCheckPath||"/health"} || exit 1`],Interval:30,Timeout:5,Retries:3,StartPeriod:60}}],Tags:[{Key:"Name",Value:`${e}-${t}-realtime`},{Key:"Environment",Value:t}]},DependsOn:[p,l]});let b=`${e}${t}RealtimeLogs`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(b,{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/ecs/${e}-${t}-realtime`,RetentionInDays:30}});let C=`${e}${t}RealtimeService`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(C,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${e}-${t}-realtime`,Cluster:{Ref:"ECSCluster"},TaskDefinition:{Ref:a},DesiredCount:d,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:s}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},HealthCheckGracePeriodSeconds:60,Tags:[{Key:"Name",Value:`${e}-${t}-realtime`},{Key:"Environment",Value:t}]},DependsOn:[a,s,b]}),n.autoScaling){let P=n.autoScaling,g=`${e}${t}RealtimeScalableTarget`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(g,{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{MaxCapacity:P.max||10,MinCapacity:P.min||1,ResourceId:{"Fn::Sub":`service/\${ECSCluster}/${e}-${t}-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:C}),P.targetCPU)this.builder.addResource(`${e}${t}RealtimeCPUPolicy`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${e}-${t}-realtime-cpu-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:g},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},TargetValue:P.targetCPU,ScaleInCooldown:300,ScaleOutCooldown:60}}})}if(r.monitoring?.enabled){let P=r.monitoring,g=P.notificationTopicArn;if(!g&&P.notificationEmails?.length){let m=`${e}${t}RealtimeAlarmTopic`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(m,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${e}-${t}-realtime-alarms`,DisplayName:"Realtime Server Alarms"}}),P.notificationEmails.forEach((c,y)=>{this.builder.addResource(`${m}Sub${y}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:m},Protocol:"email",Endpoint:c}})}),g={Ref:m}}this.builder.addResource(`${e}${t}RealtimeCPUAlarm`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${e}-${t}-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:`${e}-${t}-realtime`}],...g&&{AlarmActions:[g]}},DependsOn:C}),this.builder.addResource(`${e}${t}RealtimeMemoryAlarm`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${e}-${t}-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:`${e}-${t}-realtime`}],...g&&{AlarmActions:[g]}},DependsOn:C})}this.builder.addOutput(`${e}${t}RealtimeEndpoint`.replace(/[^a-zA-Z0-9]/g,""),{Description:"Realtime WebSocket server endpoint",Value:{"Fn::Sub":`wss://${e}-${t}-realtime.\${AWS::Region}.elb.amazonaws.com:${i}`},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-endpoint"}}})}generateBroadcastConfig(){let e=this.mergedConfig.infrastructure?.realtime;if(!e||e.mode!=="server")return"";let t=e.server||{};return`import type { BroadcastConfig } from 'ts-broadcasting'
173
+ `.trim()}generateRealtimeServerResources(l,S){let b=this.mergedConfig.infrastructure?.realtime;if(!b)return;let P=b.server||{},v=P.port||6001,Xe=P.instances||1,he=`${l}${S}RealtimeSG`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(he,{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:v,ToPort:v,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 fe=`${l}${S}RealtimeTaskDef`.replace(/[^a-zA-Z0-9]/g,""),Ye=`${l}${S}RealtimeTaskRole`.replace(/[^a-zA-Z0-9]/g,""),tt=`${l}${S}RealtimeExecRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(tt,{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(Ye,{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:"*"},...P.redis?.enabled?[{Effect:"Allow",Action:["elasticache:DescribeCacheClusters","elasticache:DescribeReplicationGroups"],Resource:"*"}]:[]]}}]}});let et=[{Name:"BROADCAST_HOST",Value:P.host||"0.0.0.0"},{Name:"BROADCAST_PORT",Value:String(v)},{Name:"NODE_ENV",Value:S==="production"?"production":"development"}];if(P.redis?.enabled){if(P.redis.useElastiCache)et.push({Name:"REDIS_HOST",Value:{"Fn::GetAtt":["CacheCluster","RedisEndpoint.Address"]}}),et.push({Name:"REDIS_PORT",Value:{"Fn::GetAtt":["CacheCluster","RedisEndpoint.Port"]}});else et.push({Name:"REDIS_HOST",Value:P.redis.host||"localhost"}),et.push({Name:"REDIS_PORT",Value:String(P.redis.port||6379)});if(P.redis.keyPrefix)et.push({Name:"REDIS_KEY_PREFIX",Value:P.redis.keyPrefix})}this.builder.addResource(fe,{Type:"AWS::ECS::TaskDefinition",Properties:{Family:`${l}-${S}-realtime`,NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:"512",Memory:"1024",ExecutionRoleArn:{"Fn::GetAtt":[tt,"Arn"]},TaskRoleArn:{"Fn::GetAtt":[Ye,"Arn"]},ContainerDefinitions:[{Name:"realtime",Image:{"Fn::Sub":`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${l}-realtime:latest`},Essential:!0,PortMappings:[{ContainerPort:v,Protocol:"tcp"}],Environment:et,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:${v}${P.healthCheckPath||"/health"} || exit 1`],Interval:30,Timeout:5,Retries:3,StartPeriod:60}}],Tags:[{Key:"Name",Value:`${l}-${S}-realtime`},{Key:"Environment",Value:S}]},DependsOn:[tt,Ye]});let nr=`${l}${S}RealtimeLogs`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(nr,{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/ecs/${l}-${S}-realtime`,RetentionInDays:30}});let vt=`${l}${S}RealtimeService`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(vt,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${l}-${S}-realtime`,Cluster:{Ref:"ECSCluster"},TaskDefinition:{Ref:fe},DesiredCount:Xe,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:he}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},HealthCheckGracePeriodSeconds:60,Tags:[{Key:"Name",Value:`${l}-${S}-realtime`},{Key:"Environment",Value:S}]},DependsOn:[fe,he,nr]}),P.autoScaling){let or=P.autoScaling,Tt=`${l}${S}RealtimeScalableTarget`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(Tt,{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{MaxCapacity:or.max||10,MinCapacity:or.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:vt}),or.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:Tt},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},TargetValue:or.targetCPU,ScaleInCooldown:300,ScaleOutCooldown:60}}})}if(b.monitoring?.enabled){let or=b.monitoring,Tt=or.notificationTopicArn;if(!Tt&&or.notificationEmails?.length){let ht=`${l}${S}RealtimeAlarmTopic`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(ht,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${l}-${S}-realtime-alarms`,DisplayName:"Realtime Server Alarms"}}),or.notificationEmails.forEach((we,wt)=>{this.builder.addResource(`${ht}Sub${wt}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:ht},Protocol:"email",Endpoint:we}})}),Tt={Ref:ht}}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`}],...Tt&&{AlarmActions:[Tt]}},DependsOn:vt}),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`}],...Tt&&{AlarmActions:[Tt]}},DependsOn:vt})}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:${v}`},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'
174
174
 
175
175
  export default {
176
176
  verbose: ${this.environment!=="production"},
177
- driver: '${t.driver||"bun"}',
177
+ driver: '${S.driver||"bun"}',
178
178
  default: 'bun',
179
179
 
180
180
  connections: {
181
181
  bun: {
182
182
  driver: 'bun',
183
- host: process.env.BROADCAST_HOST || '${t.host||"0.0.0.0"}',
184
- port: Number(process.env.BROADCAST_PORT) || ${t.port||6001},
185
- scheme: '${t.scheme||"wss"}',
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"}',
186
186
  options: {
187
- idleTimeout: ${t.idleTimeout||120},
188
- maxPayloadLength: ${t.maxPayloadLength||16777216},
189
- backpressureLimit: ${t.backpressureLimit||1048576},
190
- closeOnBackpressureLimit: ${t.closeOnBackpressureLimit||!1},
191
- sendPings: ${t.sendPings!==!1},
192
- perMessageDeflate: ${t.perMessageDeflate!==!1},
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},
193
193
  },
194
194
  },
195
195
  },
196
- ${t.redis?.enabled?`
196
+ ${S.redis?.enabled?`
197
197
  redis: {
198
- host: process.env.REDIS_HOST || '${t.redis.host||"localhost"}',
199
- port: Number(process.env.REDIS_PORT) || ${t.redis.port||6379},
200
- ${t.redis.password?`password: process.env.REDIS_PASSWORD || '${t.redis.password}',`:""}
201
- database: ${t.redis.database||0},
202
- keyPrefix: '${t.redis.keyPrefix||"broadcasting:"}',
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:"}',
203
203
  },
204
204
  `:""}
205
- ${t.rateLimit?.enabled?`
205
+ ${S.rateLimit?.enabled?`
206
206
  rateLimit: {
207
- max: ${t.rateLimit.max||100},
208
- window: ${t.rateLimit.window||60000},
209
- perChannel: ${t.rateLimit.perChannel!==!1},
210
- perUser: ${t.rateLimit.perUser!==!1},
207
+ max: ${S.rateLimit.max||100},
208
+ window: ${S.rateLimit.window||60000},
209
+ perChannel: ${S.rateLimit.perChannel!==!1},
210
+ perUser: ${S.rateLimit.perUser!==!1},
211
211
  },
212
212
  `:""}
213
- ${t.loadManagement?.enabled?`
213
+ ${S.loadManagement?.enabled?`
214
214
  loadManagement: {
215
215
  enabled: true,
216
- maxConnections: ${t.loadManagement.maxConnections||1e4},
217
- maxSubscriptionsPerConnection: ${t.loadManagement.maxSubscriptionsPerConnection||100},
218
- shedLoadThreshold: ${t.loadManagement.shedLoadThreshold||0.8},
216
+ maxConnections: ${S.loadManagement.maxConnections||1e4},
217
+ maxSubscriptionsPerConnection: ${S.loadManagement.maxSubscriptionsPerConnection||100},
218
+ shedLoadThreshold: ${S.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 qe(e){let t=[],r=[];if(!e.AWSTemplateFormatVersion)t.push({path:"AWSTemplateFormatVersion",message:"AWSTemplateFormatVersion is required",severity:"error"});else if(e.AWSTemplateFormatVersion!=="2010-09-09")r.push({path:"AWSTemplateFormatVersion",message:'AWSTemplateFormatVersion should be "2010-09-09"',severity:"warning"});if(!e.Resources||Object.keys(e.Resources).length===0)t.push({path:"Resources",message:"At least one resource is required",severity:"error"});else for(let[n,i]of Object.entries(e.Resources))Ze(n,i,t,r);if(e.Resources){let n=Xe(e.Resources);if(n.length>0)t.push({path:"Resources",message:`Circular dependencies detected: ${n.join(" -> ")}`,severity:"error"})}if(e.Parameters)for(let[n,i]of Object.entries(e.Parameters))Je(n,i,t,r);if(e.Outputs)for(let[n,i]of Object.entries(e.Outputs))Ye(n,i,t,r);return{valid:t.length===0,errors:t,warnings:r}}function Ze(e,t,r,n){if(!t.Type)r.push({path:`Resources.${e}.Type`,message:"Resource Type is required",severity:"error"});if(!/^[a-zA-Z0-9]+$/.test(e))n.push({path:`Resources.${e}`,message:"Logical ID should only contain alphanumeric characters",severity:"warning"});if(t.Type&&!t.Type.startsWith("AWS::")&&!t.Type.startsWith("Custom::"))r.push({path:`Resources.${e}.Type`,message:'Resource Type must start with "AWS::" or "Custom::"',severity:"error"});if(t.Properties){for(let[i,d]of Object.entries(t.Properties))if(d===void 0||d===null)n.push({path:`Resources.${e}.Properties.${i}`,message:"Property has undefined or null value",severity:"warning"})}if(t.DependsOn){if(typeof t.DependsOn==="string"){if(t.DependsOn===e)r.push({path:`Resources.${e}.DependsOn`,message:"Resource cannot depend on itself",severity:"error"})}else if(Array.isArray(t.DependsOn)){if(t.DependsOn.includes(e))r.push({path:`Resources.${e}.DependsOn`,message:"Resource cannot depend on itself",severity:"error"})}}}function Je(e,t,r,n){if(!t.Type)r.push({path:`Parameters.${e}.Type`,message:"Parameter Type is required",severity:"error"});let i=["String","Number","List<Number>","CommaDelimitedList","AWS::SSM::Parameter::Value<String>"];if(t.Type&&!i.includes(t.Type)&&!t.Type.startsWith("AWS::"))n.push({path:`Parameters.${e}.Type`,message:`Uncommon parameter type: ${t.Type}`,severity:"warning"});if(t.NoEcho&&t.Default)n.push({path:`Parameters.${e}`,message:"NoEcho parameters should not have default values",severity:"warning"})}function Ye(e,t,r,n){if(!t.Value)r.push({path:`Outputs.${e}.Value`,message:"Output Value is required",severity:"error"})}function Xe(e){let t={};for(let[s,a]of Object.entries(e)){if(t[s]=[],a.DependsOn){if(typeof a.DependsOn==="string")t[s].push(a.DependsOn);else if(Array.isArray(a.DependsOn))t[s].push(...a.DependsOn)}let l=ae(a);t[s].push(...l)}let r=new Set,n=new Set,i=[];function d(s,a){r.add(s),n.add(s),a.push(s);let l=t[s]||[];for(let p of l)if(!r.has(p)){if(d(p,a))return!0}else if(n.has(p)){let u=a.indexOf(p);return i.push(...a.slice(u),p),!0}return a.pop(),n.delete(s),!1}for(let s of Object.keys(t))if(!r.has(s)){if(d(s,[]))return i}return[]}function ae(e,t=[]){if(typeof e!=="object"||e===null)return t;if(Array.isArray(e)){for(let r of e)ae(r,t);return t}if(e.Ref&&typeof e.Ref==="string"&&!e.Ref.startsWith("AWS::"))t.push(e.Ref);if(e["Fn::GetAtt"]){let r=e["Fn::GetAtt"];if(Array.isArray(r)&&r.length>0)t.push(r[0])}for(let r of Object.values(e))ae(r,t);return t}function Qe(e){let t=[],r=[],n=new TextEncoder().encode(e).length,i=51200,d=460800;if(n>51200)if(n>460800)t.push({path:"template",message:`Template size (${n} bytes) exceeds maximum allowed size of 460800 bytes`,severity:"error"});else r.push({path:"template",message:`Template size (${n} bytes) exceeds direct upload limit (51200 bytes). You must upload to S3 first.`,severity:"warning"});return{valid:t.length===0,errors:t,warnings:r}}function et(e){let t=[],r=[],n=e.Resources?Object.keys(e.Resources).length:0,i=e.Parameters?Object.keys(e.Parameters).length:0,d=e.Outputs?Object.keys(e.Outputs).length:0;if(n>500)t.push({path:"Resources",message:`Template has ${n} resources, exceeding the limit of 500`,severity:"error"});else if(n>200)r.push({path:"Resources",message:`Template has ${n} resources. Consider using nested stacks for better organization.`,severity:"warning"});if(i>200)t.push({path:"Parameters",message:`Template has ${i} parameters, exceeding the limit of 200`,severity:"error"});if(d>200)t.push({path:"Outputs",message:`Template has ${d} outputs, exceeding the limit of 200`,severity:"error"});return{valid:t.length===0,errors:t,warnings:r}}function Bo(e){let{domains:t,email:r,staging:n=!1,challengeType:i="http-01",certPath:d="/etc/letsencrypt/live",autoRenew:s=!0}=e,a=t[0],l=t.map((u)=>`-d ${u}`).join(" "),p=n?"--staging":"";if(i==="http-01")return tt({domains:t,email:r,staging:n,certPath:d,autoRenew:s,domainFlags:l,stagingFlag:p,primaryDomain:a});else{let u=e.dnsProvider?.provider||(e.hostedZoneId?"route53":void 0);return rt({domains:t,email:r,staging:n,certPath:d,autoRenew:s,domainFlags:l,stagingFlag:p,primaryDomain:a,hostedZoneId:e.hostedZoneId,dnsProvider:e.dnsProvider,dnsProviderType:u})}}function tt(e){let{email:t,certPath:r,autoRenew:n,domainFlags:i,stagingFlag:d,primaryDomain:s}=e;return`
222
+ `}toYAML(){return this.builder.toYAML()}toJSON(){return this.builder.toJSON()}getBuilder(){return this.builder}}function El(l){let S=[],b=[];if(!l.AWSTemplateFormatVersion)S.push({path:"AWSTemplateFormatVersion",message:"AWSTemplateFormatVersion is required",severity:"error"});else if(l.AWSTemplateFormatVersion!=="2010-09-09")b.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[P,v]of Object.entries(l.Resources))vl(P,v,S,b);if(l.Resources){let P=Vl(l.Resources);if(P.length>0)S.push({path:"Resources",message:`Circular dependencies detected: ${P.join(" -> ")}`,severity:"error"})}if(l.Parameters)for(let[P,v]of Object.entries(l.Parameters))kl(P,v,S,b);if(l.Outputs)for(let[P,v]of Object.entries(l.Outputs))Bl(P,v,S,b);return{valid:S.length===0,errors:S,warnings:b}}function vl(l,S,b,P){if(!S.Type)b.push({path:`Resources.${l}.Type`,message:"Resource Type is required",severity:"error"});if(!/^[a-zA-Z0-9]+$/.test(l))P.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::"))b.push({path:`Resources.${l}.Type`,message:'Resource Type must start with "AWS::" or "Custom::"',severity:"error"});if(S.Properties){for(let[v,Xe]of Object.entries(S.Properties))if(Xe===void 0||Xe===null)P.push({path:`Resources.${l}.Properties.${v}`,message:"Property has undefined or null value",severity:"warning"})}if(S.DependsOn){if(typeof S.DependsOn==="string"){if(S.DependsOn===l)b.push({path:`Resources.${l}.DependsOn`,message:"Resource cannot depend on itself",severity:"error"})}else if(Array.isArray(S.DependsOn)){if(S.DependsOn.includes(l))b.push({path:`Resources.${l}.DependsOn`,message:"Resource cannot depend on itself",severity:"error"})}}}function kl(l,S,b,P){if(!S.Type)b.push({path:`Parameters.${l}.Type`,message:"Parameter Type is required",severity:"error"});let v=["String","Number","List<Number>","CommaDelimitedList","AWS::SSM::Parameter::Value<String>"];if(S.Type&&!v.includes(S.Type)&&!S.Type.startsWith("AWS::"))P.push({path:`Parameters.${l}.Type`,message:`Uncommon parameter type: ${S.Type}`,severity:"warning"});if(S.NoEcho&&S.Default)P.push({path:`Parameters.${l}`,message:"NoEcho parameters should not have default values",severity:"warning"})}function Bl(l,S,b,P){if(!S.Value)b.push({path:`Outputs.${l}.Value`,message:"Output Value is required",severity:"error"})}function Vl(l){let S={};for(let[he,fe]of Object.entries(l)){if(S[he]=[],fe.DependsOn){if(typeof fe.DependsOn==="string")S[he].push(fe.DependsOn);else if(Array.isArray(fe.DependsOn))S[he].push(...fe.DependsOn)}let Ye=Oa(fe);S[he].push(...Ye)}let b=new Set,P=new Set,v=[];function Xe(he,fe){b.add(he),P.add(he),fe.push(he);let Ye=S[he]||[];for(let tt of Ye)if(!b.has(tt)){if(Xe(tt,fe))return!0}else if(P.has(tt)){let et=fe.indexOf(tt);return v.push(...fe.slice(et),tt),!0}return fe.pop(),P.delete(he),!1}for(let he of Object.keys(S))if(!b.has(he)){if(Xe(he,[]))return v}return[]}function Oa(l,S=[]){if(typeof l!=="object"||l===null)return S;if(Array.isArray(l)){for(let b of l)Oa(b,S);return S}if(l.Ref&&typeof l.Ref==="string"&&!l.Ref.startsWith("AWS::"))S.push(l.Ref);if(l["Fn::GetAtt"]){let b=l["Fn::GetAtt"];if(Array.isArray(b)&&b.length>0)S.push(b[0])}for(let b of Object.values(l))Oa(b,S);return S}function Gl(l){let S=[],b=[],P=new TextEncoder().encode(l).length,v=51200,Xe=460800;if(P>51200)if(P>460800)S.push({path:"template",message:`Template size (${P} bytes) exceeds maximum allowed size of 460800 bytes`,severity:"error"});else b.push({path:"template",message:`Template size (${P} bytes) exceeds direct upload limit (51200 bytes). You must upload to S3 first.`,severity:"warning"});return{valid:S.length===0,errors:S,warnings:b}}function Ul(l){let S=[],b=[],P=l.Resources?Object.keys(l.Resources).length:0,v=l.Parameters?Object.keys(l.Parameters).length:0,Xe=l.Outputs?Object.keys(l.Outputs).length:0;if(P>500)S.push({path:"Resources",message:`Template has ${P} resources, exceeding the limit of 500`,severity:"error"});else if(P>200)b.push({path:"Resources",message:`Template has ${P} resources. Consider using nested stacks for better organization.`,severity:"warning"});if(v>200)S.push({path:"Parameters",message:`Template has ${v} parameters, exceeding the limit of 200`,severity:"error"});if(Xe>200)S.push({path:"Outputs",message:`Template has ${Xe} outputs, exceeding the limit of 200`,severity:"error"});return{valid:S.length===0,errors:S,warnings:b}}function Pm(l){let{domains:S,email:b,staging:P=!1,challengeType:v="http-01",certPath:Xe="/etc/letsencrypt/live",autoRenew:he=!0}=l,fe=S[0],Ye=S.map((et)=>`-d ${et}`).join(" "),tt=P?"--staging":"";if(v==="http-01")return ql({domains:S,email:b,staging:P,certPath:Xe,autoRenew:he,domainFlags:Ye,stagingFlag:tt,primaryDomain:fe});else{let et=l.dnsProvider?.provider||(l.hostedZoneId?"route53":void 0);return Zl({domains:S,email:b,staging:P,certPath:Xe,autoRenew:he,domainFlags:Ye,stagingFlag:tt,primaryDomain:fe,hostedZoneId:l.hostedZoneId,dnsProvider:l.dnsProvider,dnsProviderType:et})}}function ql(l){let{email:S,certPath:b,autoRenew:P,domainFlags:v,stagingFlag:Xe,primaryDomain:he}=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 ${t} \\
239
- ${d} \\
240
- ${i}
238
+ --email ${S} \\
239
+ ${Xe} \\
240
+ ${v}
241
241
 
242
242
  # Check if certificate was obtained
243
- if [ -f "${r}/${s}/fullchain.pem" ]; then
243
+ if [ -f "${b}/${he}/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 ${r}/${s}/fullchain.pem /etc/ssl/stacks/fullchain.pem
249
- ln -sf ${r}/${s}/privkey.pem /etc/ssl/stacks/privkey.pem
250
- ln -sf ${r}/${s}/cert.pem /etc/ssl/stacks/cert.pem
251
- ln -sf ${r}/${s}/chain.pem /etc/ssl/stacks/chain.pem
248
+ ln -sf ${b}/${he}/fullchain.pem /etc/ssl/stacks/fullchain.pem
249
+ ln -sf ${b}/${he}/privkey.pem /etc/ssl/stacks/privkey.pem
250
+ ln -sf ${b}/${he}/cert.pem /etc/ssl/stacks/cert.pem
251
+ ln -sf ${b}/${he}/chain.pem /etc/ssl/stacks/chain.pem
252
252
  else
253
253
  echo "Failed to obtain certificate!"
254
254
  fi
255
255
 
256
- ${n?se(s):"# Auto-renewal disabled"}
256
+ ${P?xa(he):"# Auto-renewal disabled"}
257
257
 
258
258
  # Restart the application
259
259
  systemctl start stacks
260
- `}function rt(e){let{email:t,certPath:r,autoRenew:n,domainFlags:i,stagingFlag:d,primaryDomain:s,hostedZoneId:a,dnsProvider:l,dnsProviderType:p}=e;if(p==="route53"||a){if(!a)throw Error("hostedZoneId is required for DNS-01 challenge with Route53");return`
260
+ `}function Zl(l){let{email:S,certPath:b,autoRenew:P,domainFlags:v,stagingFlag:Xe,primaryDomain:he,hostedZoneId:fe,dnsProvider:Ye,dnsProviderType:tt}=l;if(tt==="route53"||fe){if(!fe)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 ${t} \\
274
- ${d} \\
275
- ${i}
273
+ --email ${S} \\
274
+ ${Xe} \\
275
+ ${v}
276
276
 
277
277
  # Check if certificate was obtained
278
- if [ -f "${r}/${s}/fullchain.pem" ]; then
278
+ if [ -f "${b}/${he}/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 ${r}/${s}/fullchain.pem /etc/ssl/stacks/fullchain.pem
284
- ln -sf ${r}/${s}/privkey.pem /etc/ssl/stacks/privkey.pem
285
- ln -sf ${r}/${s}/cert.pem /etc/ssl/stacks/cert.pem
286
- ln -sf ${r}/${s}/chain.pem /etc/ssl/stacks/chain.pem
283
+ ln -sf ${b}/${he}/fullchain.pem /etc/ssl/stacks/fullchain.pem
284
+ ln -sf ${b}/${he}/privkey.pem /etc/ssl/stacks/privkey.pem
285
+ ln -sf ${b}/${he}/cert.pem /etc/ssl/stacks/cert.pem
286
+ ln -sf ${b}/${he}/chain.pem /etc/ssl/stacks/chain.pem
287
287
  else
288
288
  echo "Failed to obtain certificate!"
289
289
  fi
290
290
 
291
- ${n?se(s):"# Auto-renewal disabled"}
292
- `}if(!l)throw Error("dnsProvider configuration is required for DNS-01 challenge with external DNS providers");let u=l.provider.toUpperCase(),b=nt(l);return`
291
+ ${P?xa(he):"# Auto-renewal disabled"}
292
+ `}if(!Ye)throw Error("dnsProvider configuration is required for DNS-01 challenge with external DNS providers");let et=Ye.provider.toUpperCase(),nr=Yl(Ye);return`
293
293
  # ==========================================
294
- # Let's Encrypt Certificate Setup (DNS-01 via ${u})
294
+ # Let's Encrypt Certificate Setup (DNS-01 via ${et})
295
295
  # ==========================================
296
296
 
297
297
  # Install certbot
298
298
  dnf install -y certbot jq curl
299
299
 
300
- ${b}
300
+ ${nr}
301
301
 
302
302
  # Create DNS challenge hook scripts directory
303
303
  mkdir -p /etc/letsencrypt/hooks
304
304
 
305
- # Create authenticator hook for ${u}
305
+ # Create authenticator hook for ${et}
306
306
  cat > /etc/letsencrypt/hooks/auth-hook.sh << 'AUTHHOOK'
307
307
  #!/bin/bash
308
- # DNS-01 authenticator hook for ${u}
308
+ # DNS-01 authenticator hook for ${et}
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
- ${it(l)}
315
+ ${Ql(Ye)}
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 ${u}
324
+ # Create cleanup hook for ${et}
325
325
  cat > /etc/letsencrypt/hooks/cleanup-hook.sh << 'CLEANUPHOOK'
326
326
  #!/bin/bash
327
- # DNS-01 cleanup hook for ${u}
327
+ # DNS-01 cleanup hook for ${et}
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
- ${ot(l)}
334
+ ${Ed(Ye)}
335
335
  CLEANUPHOOK
336
336
 
337
337
  chmod +x /etc/letsencrypt/hooks/cleanup-hook.sh
@@ -344,37 +344,37 @@ certbot certonly \\
344
344
  --manual-cleanup-hook /etc/letsencrypt/hooks/cleanup-hook.sh \\
345
345
  --non-interactive \\
346
346
  --agree-tos \\
347
- --email ${t} \\
348
- ${d} \\
349
- ${i}
347
+ --email ${S} \\
348
+ ${Xe} \\
349
+ ${v}
350
350
 
351
351
  # Check if certificate was obtained
352
- if [ -f "${r}/${s}/fullchain.pem" ]; then
352
+ if [ -f "${b}/${he}/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 ${r}/${s}/fullchain.pem /etc/ssl/stacks/fullchain.pem
358
- ln -sf ${r}/${s}/privkey.pem /etc/ssl/stacks/privkey.pem
359
- ln -sf ${r}/${s}/cert.pem /etc/ssl/stacks/cert.pem
360
- ln -sf ${r}/${s}/chain.pem /etc/ssl/stacks/chain.pem
357
+ ln -sf ${b}/${he}/fullchain.pem /etc/ssl/stacks/fullchain.pem
358
+ ln -sf ${b}/${he}/privkey.pem /etc/ssl/stacks/privkey.pem
359
+ ln -sf ${b}/${he}/cert.pem /etc/ssl/stacks/cert.pem
360
+ ln -sf ${b}/${he}/chain.pem /etc/ssl/stacks/chain.pem
361
361
  else
362
362
  echo "Failed to obtain certificate!"
363
363
  fi
364
364
 
365
- ${n?se(s):"# Auto-renewal disabled"}
366
- `}function nt(e){switch(e.provider){case"porkbun":return`
365
+ ${P?xa(he):"# Auto-renewal disabled"}
366
+ `}function Yl(l){switch(l.provider){case"porkbun":return`
367
367
  # Porkbun API credentials
368
- export PORKBUN_API_KEY="${e.apiKey}"
369
- export PORKBUN_SECRET_KEY="${e.secretKey}"
368
+ export PORKBUN_API_KEY="${l.apiKey}"
369
+ export PORKBUN_SECRET_KEY="${l.secretKey}"
370
370
  `;case"godaddy":return`
371
371
  # GoDaddy API credentials
372
- export GODADDY_API_KEY="${e.apiKey}"
373
- export GODADDY_API_SECRET="${e.apiSecret}"
374
- export GODADDY_ENV="${e.environment||"production"}"
372
+ export GODADDY_API_KEY="${l.apiKey}"
373
+ export GODADDY_API_SECRET="${l.apiSecret}"
374
+ export GODADDY_ENV="${l.environment||"production"}"
375
375
  `;case"route53":return`
376
376
  # Route53 uses IAM role credentials
377
- `;default:return""}}function it(e){switch(e.provider){case"porkbun":return`
377
+ `;default:return""}}function Ql(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 ot(e){switch(e.provider){case"porkbun":return`
421
+ `;default:return'echo "Unsupported DNS provider"'}}function Ed(l){switch(l.provider){case"porkbun":return`
422
422
  # Extract root domain
423
423
  ROOT_DOMAIN=$(echo "$DOMAIN" | awk -F. '{print $(NF-1)"."$NF}')
424
424
 
@@ -461,7 +461,7 @@ fi
461
461
 
462
462
  curl -s -X DELETE "$API_URL/v1/domains/$ROOT_DOMAIN/records/TXT/$RECORD_NAME" \\
463
463
  -H "Authorization: sso-key $GODADDY_API_KEY:$GODADDY_API_SECRET"
464
- `;default:return'echo "Unsupported DNS provider"'}}function se(e){return`
464
+ `;default:return'echo "Unsupported DNS provider"'}}function xa(l){return`
465
465
  # ==========================================
466
466
  # Certificate Auto-Renewal Setup
467
467
  # ==========================================
@@ -506,13 +506,13 @@ systemctl enable certbot-renewal.timer
506
506
  systemctl start certbot-renewal.timer
507
507
 
508
508
  echo "Certificate auto-renewal configured"
509
- `}function Vo(e){let{httpPort:t=80,httpsPort:r=443,certPath:n="/etc/ssl/stacks",redirectHttp:i=!0}=e;return`
509
+ `}function Im(l){let{httpPort:S=80,httpsPort:b=443,certPath:P="/etc/ssl/stacks",redirectHttp:v=!0}=l;return`
510
510
  // HTTPS Server with Let's Encrypt certificates
511
511
  import { readFileSync, existsSync } from 'node:fs'
512
512
 
513
- const CERT_PATH = '${n}'
514
- const HTTP_PORT = ${t}
515
- const HTTPS_PORT = ${r}
513
+ const CERT_PATH = '${P}'
514
+ const HTTP_PORT = ${S}
515
+ const HTTPS_PORT = ${b}
516
516
 
517
517
  // Check if certificates exist
518
518
  const hasCerts = existsSync(\`\${CERT_PATH}/fullchain.pem\`) && existsSync(\`\${CERT_PATH}/privkey.pem\`)
@@ -532,7 +532,7 @@ if (hasCerts) {
532
532
  })
533
533
  console.log(\`HTTPS server running on port \${HTTPS_PORT}\`)
534
534
 
535
- ${i?`
535
+ ${v?`
536
536
  // Start HTTP server for redirect
537
537
  const httpServer = Bun.serve({
538
538
  port: HTTP_PORT,
@@ -592,5 +592,5 @@ async function handleRequest(request: Request): Promise<Response> {
592
592
  // Implement your request handling here
593
593
  return new Response('Hello from Stacks!')
594
594
  }
595
- `}async function Wo(e){let{domain:t,challengeValue:r,hostedZoneId:n,dnsProvider:i,region:d="us-east-1"}=e;if(i){let a=await Y(i).upsertRecord(t,{name:`_acme-challenge.${t}`,type:"TXT",content:r,ttl:60});if(!a.success)throw Error(`Failed to create DNS challenge record: ${a.message}`);return}if(n){await new J(d).changeResourceRecordSets({HostedZoneId:n,ChangeBatch:{Comment:"ACME DNS-01 challenge",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:`_acme-challenge.${t}`,Type:"TXT",TTL:60,ResourceRecords:[{Value:`"${r}"`}]}}]}});return}throw Error("Either dnsProvider or hostedZoneId must be provided")}async function Ho(e){let{domain:t,challengeValue:r,hostedZoneId:n,dnsProvider:i,region:d="us-east-1"}=e;if(i){let a=await Y(i).deleteRecord(t,{name:`_acme-challenge.${t}`,type:"TXT",content:r});if(!a.success)console.warn(`Failed to delete DNS challenge record: ${a.message}`);return}if(n){await new J(d).changeResourceRecordSets({HostedZoneId:n,ChangeBatch:{Comment:"Remove ACME DNS-01 challenge",Changes:[{Action:"DELETE",ResourceRecordSet:{Name:`_acme-challenge.${t}`,Type:"TXT",TTL:60,ResourceRecords:[{Value:`"${r}"`}]}}]}});return}throw Error("Either dnsProvider or hostedZoneId must be provided")}function zo(e){try{let{execSync:t}=Z("node:child_process"),r=t(`openssl x509 -checkend 2592000 -noout -in ${e}/cert.pem`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return!1}catch{return!0}}import{createHash as Oe,createSign as at,generateKeyPairSync as Ne}from"node:crypto";var ke={production:"https://acme-v02.api.letsencrypt.org/directory",staging:"https://acme-staging-v02.api.letsencrypt.org/directory"};class st{directoryUrl;email;accountKey;accountUrl=null;directory=null;nonce=null;constructor(e){this.directoryUrl=e.staging?ke.staging:ke.production,this.email=e.email,this.accountKey=e.accountKey||this.generateAccountKey()}generateAccountKey(){let{privateKey:e}=Ne("ec",{namedCurve:"P-256"});return e.export({type:"pkcs8",format:"pem"})}async getDirectory(){if(this.directory)return this.directory;let e=await fetch(this.directoryUrl);if(!e.ok)throw Error(`Failed to fetch ACME directory: ${e.status}`);return this.directory=await e.json(),this.directory}async getNonce(){if(this.nonce){let n=this.nonce;return this.nonce=null,n}let e=await this.getDirectory(),r=(await fetch(e.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!r)throw Error("Failed to get nonce from ACME server");return r}getJwk(){let e=this.accountKey.split(`
596
- `).filter((d)=>!d.startsWith("-----")).join(""),t=Buffer.from(e,"base64"),r=t.length-65,n=t.subarray(r+1,r+33),i=t.subarray(r+33,r+65);return{kty:"EC",crv:"P-256",x:this.base64UrlEncode(n),y:this.base64UrlEncode(i)}}getJwkThumbprint(){let e=this.getJwk(),t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x,y:e.y}),r=Oe("sha256").update(t).digest();return this.base64UrlEncode(r)}base64UrlEncode(e){return(typeof e==="string"?Buffer.from(e):e).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async signPayload(e,t){let r=await this.getNonce(),n=this.getJwk(),i={alg:"ES256",nonce:r,url:e};if(this.accountUrl)i.kid=this.accountUrl;else i.jwk=n;let d=this.base64UrlEncode(JSON.stringify(i)),s=t===""?"":this.base64UrlEncode(JSON.stringify(t)),a=`${d}.${s}`,l=at("SHA256");l.update(a);let p=l.sign(this.accountKey),u=p.subarray(4,4+p[3]),b=4+p[3]+2,C=p.subarray(b,b+p[b-1]),P=Buffer.alloc(32),g=Buffer.alloc(32);u.copy(P,32-u.length),C.copy(g,32-C.length);let m=Buffer.concat([P,g]);return JSON.stringify({protected:d,payload:s,signature:this.base64UrlEncode(m)})}async acmeRequest(e,t){let r=await this.signPayload(e,t),n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/jose+json"},body:r}),i=n.headers.get("replay-nonce");if(i)this.nonce=i;let d,s=n.headers.get("content-type");if(s?.includes("application/json")||s?.includes("application/problem+json"))d=await n.json();else d=await n.text();if(!n.ok)throw Error(`ACME request failed: ${JSON.stringify(d)}`);return{body:d,headers:n.headers}}async registerAccount(){let e=await this.getDirectory(),{body:t,headers:r}=await this.acmeRequest(e.newAccount,{termsOfServiceAgreed:!0,contact:[`mailto:${this.email}`]}),n=r.get("location");if(!n)throw Error("No account URL returned");return this.accountUrl=n,n}async createOrder(e){if(!this.accountUrl)await this.registerAccount();let t=await this.getDirectory(),{body:r,headers:n}=await this.acmeRequest(t.newOrder,{identifiers:e.map((d)=>({type:"dns",value:d}))}),i=n.get("location");if(!i)throw Error("No order URL returned");return{orderUrl:i,authorizations:r.authorizations,finalize:r.finalize}}async getAuthorization(e){let{body:t}=await this.acmeRequest(e,""),r=t.identifier.value,n=this.getJwkThumbprint(),i=t.challenges.filter((d)=>d.type==="http-01"||d.type==="dns-01").map((d)=>{let s=`${d.token}.${n}`;if(d.type==="http-01")return{type:"http-01",token:d.token,keyAuthorization:s,identifier:`/.well-known/acme-challenge/${d.token}`};else{let a=this.base64UrlEncode(Oe("sha256").update(s).digest());return{type:"dns-01",token:d.token,keyAuthorization:s,identifier:`_acme-challenge.${r}`,dnsValue:a}}});return{domain:r,challenges:i}}async respondToChallenge(e){await this.acmeRequest(e,{})}async waitForAuthorization(e,t=30){for(let r=0;r<t;r++){let{body:n}=await this.acmeRequest(e,"");if(n.status==="valid")return;if(n.status==="invalid")throw Error(`Authorization failed: ${JSON.stringify(n)}`);await new Promise((i)=>setTimeout(i,2000))}throw Error("Authorization timed out")}generateCsr(e){let{privateKey:t}=Ne("rsa",{modulusLength:2048}),r=t.export({type:"pkcs8",format:"pem"});return{csr:this.createSimpleCsr(e,t),privateKey:r}}createSimpleCsr(e,t){throw Error("CSR generation requires additional implementation. Consider using the shell-based certbot approach instead.")}async finalizeOrder(e,t){let{csr:r,privateKey:n}=this.generateCsr(t),{body:i}=await this.acmeRequest(e,{csr:this.base64UrlEncode(Buffer.from(r,"base64"))}),d=i.certificate;if(!d)throw Error("Certificate not immediately available - polling not implemented");let a=await(await fetch(d)).text(),l=a.split(/(?=-----BEGIN CERTIFICATE-----)/g),p=l[0],u=l.slice(1).join("");return{certificate:p,privateKey:n,chain:u,fullchain:a,expiresAt:new Date(Date.now()+7776000000)}}getAccountKey(){return this.accountKey}}var xe=["js","mjs","cjs","css","map","woff","woff2","ttf","otf","eot","png","jpg","jpeg","gif","webp","avif","svg","ico","mp4","webm","ogg","mp3","wav","pdf","wasm"],ct=[{name:"x-stx-router",value:"true"}];function W(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function Le(e){return`{${e.map(W).join(" ")}}`}function lt(e){let t=`http.request.headers[${W(e.name.toLowerCase())}]`;return e.value===void 0?`len(${t}) > 0`:`any(${t}[*] == ${W(e.value)})`}function ce(e){if(e.length===1)return`http.host eq ${W(e[0])}`;return`http.host in ${Le(e)}`}function le(e,t={}){if(t.enabled===!1||e.length===0)return[];let r=ce(e),n=[],d=(t.bypassPaths??[]).map((P)=>`starts_with(http.request.uri.path, ${W(P)})`),a=(t.negotiatedRequestHeaders??ct).map(lt),l=[...d,...a],p=l.length>0?`(${l.join(" or ")})`:void 0;if(p)n.push({action:"set_cache_settings",description:"bypass cache",expression:`(${r} and ${p})`,enabled:!0,action_parameters:{cache:!1}});let u=p?`${r} and not ${p}`:r,b=t.assetExtensions??xe,C=b.length>0?`lower(http.request.uri.path.extension) in ${Le([...b])}`:void 0;if(C)n.push({action:"set_cache_settings",description:"cache fingerprinted assets",expression:`(${u} and ${C})`,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:t.assetEdgeTtl??2592000},browser_ttl:{mode:"override_origin",default:t.assetBrowserTtl??31536000}}});return n.push({action:"set_cache_settings",description:"cache documents",expression:C?`(${u} and not ${C})`:`(${u})`,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:t.documentEdgeTtl??3600},browser_ttl:{mode:"override_origin",default:t.documentBrowserTtl??0}}}),n}function de(e,t,r){if(e.length===0||!t||!r)return[];return[{action:"rewrite",description:"origin guard header",expression:`(${ce(e)})`,enabled:!0,action_parameters:{headers:{[t]:{operation:"set",value:r}}}}]}var N=(e)=>e===void 0?void 0:e?"on":"off";function ue(e){let t={ssl:e.ssl,always_use_https:N(e.alwaysUseHttps),automatic_https_rewrites:N(e.automaticHttpsRewrites),min_tls_version:e.minTlsVersion,tls_1_3:N(e.tls13),brotli:N(e.brotli),http3:N(e.http3),"0rtt":N(e.zeroRtt),early_hints:N(e.earlyHints),browser_cache_ttl:e.browserCacheTtl,always_online:N(e.alwaysOnline),websockets:N(e.websockets),email_obfuscation:N(e.emailObfuscation)};if(e.hsts)t.security_header={strict_transport_security:{enabled:e.hsts.enabled,max_age:e.hsts.maxAge??31536000,include_subdomains:e.hsts.includeSubdomains??!1,preload:e.hsts.preload??!1,nosniff:e.hsts.noSniff??!0}};for(let r of Object.keys(t))if(t[r]===void 0)delete t[r];return{...t,...e.raw??{}}}var H={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 dt}from"node:tls";async function pe(e){let{address:t,serverName:r,port:n=443,timeoutMs:i=5000}=e;return new Promise((d)=>{let s=!1,a=(p)=>{if(s)return;s=!0;try{l.destroy()}catch{}d(p)},l=dt({host:t,port:n,servername:r,rejectUnauthorized:!1,timeout:i});l.once("secureConnect",()=>{if(l.authorized){a({reachable:!0,trusted:!0});return}a({reachable:!0,trusted:!1,reason:l.authorizationError?String(l.authorizationError):"origin certificate is not trusted for this hostname"})}),l.once("timeout",()=>{a({reachable:!1,trusted:!1,reason:`no TLS handshake within ${i}ms`})}),l.once("error",(p)=>{a({reachable:!1,trusted:!1,reason:p.message})})})}function ut(e,t){let r=t.replace(/\.$/,"").toLowerCase();return e.some((n)=>{let i=n.replace(/\.$/,"").toLowerCase();if(i===r)return!0;if(!i.startsWith("*."))return!1;let d=i.slice(2);if(!r.endsWith(`.${d}`))return!1;return!r.slice(0,r.length-d.length-1).includes(".")})}async function pt(e){let{provider:t,zone:r,hosts:n,ipv4:i,ipv6:d,proxied:s=!0,settings:a=H,cache:l,originGuard:p,purge:u=!0,ttl:b=300,skipOriginProbe:C=!1,skipEdgeCertificateCheck:P=!1}=e,g={records:[],settingsChanged:[],cacheRules:0,originGuard:!1,purged:!1,deferredProxy:[],warnings:[]};if(n.length===0)return g;let m=[],c=s&&!P?await t.listEdgeCertificateHosts(r):null;for(let o of n){let f=s;if(f&&c&&!ut(c,o)){f=!1;let S=c.length===0?"the zone has no active edge certificate yet":`no active edge certificate covers it (${c.join(", ")})`;g.deferredProxy.push({host:o,reason:S}),g.warnings.push(`${o}: publishing DNS-only — ${S}. 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(f&&!C){let S=await pe({address:i,serverName:o});if(!S.trusted){f=!1;let A=S.reason||"origin is not serving a trusted certificate";g.deferredProxy.push({host:o,reason:A}),g.warnings.push(`${o}: publishing DNS-only for now — the origin does not yet serve a certificate this proxy can verify (${A}). 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(f)m.push(o);let h=[{type:"A",content:i}];if(d&&me(o))h.push({type:"AAAA",content:d});for(let{type:S,content:A}of h){let R=await t.upsertRecord(r,{name:o,type:S,content:A,ttl:b,proxied:f});if(R.success)g.records.push({host:o,type:S,content:A,proxied:f});else g.warnings.push(`${o} ${S} → ${A} failed: ${R.message||"unknown provider error"}`)}}if(m.length===0){if(s)g.warnings.push("No host is proxied yet, so zone settings, cache rules and purge were skipped — they only take effect through the proxy.");return g}try{let o=ue(a),f=await t.applyZoneSettings(r,o);g.settingsChanged=f.changed;for(let h of f.failed)g.warnings.push(`zone setting '${h.id}' could not be applied: ${h.error}`)}catch(o){g.warnings.push(`zone settings could not be read: ${o instanceof Error?o.message:String(o)}`)}let y=le(m,l);if(y.length>0){let o=await t.putManagedPhaseRules(r,"http_request_cache_settings",y);if(o.success)g.cacheRules=y.length;else g.warnings.push(`cache rules could not be written: ${o.message}`)}if(p){let o=de(m,p.header,p.value);if(o.length>0){let f=await t.putManagedPhaseRules(r,"http_request_late_transform",o);if(f.success)g.originGuard=!0;else g.warnings.push(`origin guard header could not be written: ${f.message}. `+"The gateway will reject requests that lack it — disable the guard or grant the token Transform Rules: Edit.")}}if(u){if(g.purged=await t.purgeCache(r,{hosts:m}),!g.purged)g.warnings.push("edge cache purge failed — new content may take until TTL expiry to appear.")}return g}var mt=(e)=>process.env[e];function Fe(e,t){let r=e.replace(/\.$/,"").toLowerCase();if(t){let n=t.replace(/\.$/,"").toLowerCase();if(r===n||r.endsWith(`.${n}`))return n}return r.split(".").slice(-2).join(".")}function ft(e,t={}){let r=t.env??mt,n=e.infrastructure?.compute?.proxy?.cdn,i=[];if(!n||n.provider!=="cloudflare")return{plan:null,errors:i};if(n.originDomain)i.push(`compute.proxy.cdn.originDomain (${n.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 d=r("CLOUDFLARE_API_TOKEN");if(!d)return i.push("CLOUDFLARE_API_TOKEN is not set — the Cloudflare CDN cannot be reconciled."),{plan:null,errors:i};let s=e.sites??{},a=n.frontedHosts?.length?[...new Set(n.frontedHosts.map((C)=>C.toLowerCase()))]:fe(s,{autoWww:e.infrastructure?.compute?.proxy?.autoWww!==!1});if(a.length===0)return i.push("No hostnames to front — set compute.proxy.cdn.frontedHosts, or give a site a domain."),{plan:null,errors:i};let l=e.infrastructure?.dns?.domain,p=new Set(a.map((C)=>Fe(C,l)));if(p.size>1)return i.push(`Fronted hosts span more than one zone (${[...p].join(", ")}). A Cloudflare zone is configured as a unit, so run one CDN config per zone.`),{plan:null,errors:i};let u=n.cloudflare??{},b=n.secret?{header:n.secretHeader??"X-Origin-Verify",value:n.secret}:void 0;return{plan:{zone:[...p][0],hosts:a,apiToken:d,zoneId:u.zoneId??r("CLOUDFLARE_ZONE_ID"),accountId:u.accountId??r("CLOUDFLARE_ACCOUNT_ID"),proxied:u.proxied!==!1,settings:u.settings??H,cache:u.cache,originGuard:b,purge:u.purgeOnDeploy!==!1,skipOriginProbe:u.skipOriginProbe===!0},errors:i}}var ht=26214400;var yt=new Set(["/_headers","/_redirects","/_routes.json","/_worker.js"]);class _e{name="cloudflare-pages";apiToken;accountId;constructor(e){if(!e.apiToken)throw Error("Cloudflare Pages needs an API token");if(!e.accountId)throw Error("Cloudflare Pages needs an account id");this.apiToken=e.apiToken,this.accountId=e.accountId}async request(e,t,r){return X(e,`/accounts/${this.accountId}${t}`,`Bearer ${this.apiToken}`,r)}async getProject(e){try{return await this.request("GET",`/pages/projects/${e}`)}catch(t){if(t instanceof Error&&/\b8000007\b|not found/i.test(t.message))return null;throw t}}async ensureProject(e,t="main"){let r=await this.getProject(e);if(r)return r;return this.request("POST","/pages/projects",{name:e,production_branch:t})}async uploadToken(e){return(await this.request("GET",`/pages/projects/${e}/upload-token`)).jwt}async missingHashes(e,t){let r=await X("POST","/pages/assets/check-missing",`Bearer ${e}`,{hashes:t});return new Set(r)}async upsertHashes(e,t){await X("POST","/pages/assets/upsert-hashes",`Bearer ${e}`,{hashes:t})}async uploadBatch(e,t){let r=t.map((n)=>({key:n.hash,value:n.base64,metadata:{contentType:St(n.extension)},base64:!0}));await X("POST","/pages/assets/upload",`Bearer ${e}`,r)}async createDeployment(e,t,r){let n={};for(let d of t)n[d.path]=d.hash;let i=new FormData;if(i.append("manifest",JSON.stringify(n)),r)i.append("branch",r);return this.request("POST",`/pages/projects/${e}/deployments`,i)}async deployDirectory(e){let t=await Be(e.directory);if(t.length===0)throw Error(`No files to deploy in ${e.directory}`);let r=await this.uploadToken(e.project),n=await this.missingHashes(r,t.map((l)=>l.hash)),i=t.filter((l)=>n.has(l.hash)),d=[];for(let l=0;l<i.length;l+=100)d.push(i.slice(l,l+100));let s=0;for(let l=0;l<d.length;l+=4){let p=d.slice(l,l+4);await Promise.all(p.map((u)=>this.uploadBatch(r,u))),s+=p.reduce((u,b)=>u+b.length,0),e.onProgress?.(s,i.length)}return await this.upsertHashes(r,t.map((l)=>l.hash)),{deployment:await this.createDeployment(e.project,t,e.branch),total:t.length,uploaded:i.length,uploadedBytes:i.reduce((l,p)=>l+p.size,0)}}async listCustomDomains(e){return(await this.request("GET",`/pages/projects/${e}/domains`)).map((r)=>r.name)}async attachCustomDomain(e,t){if((await this.listCustomDomains(e)).includes(t))return!1;return await this.request("POST",`/pages/projects/${e}/domains`,{name:t}),!0}}function Ct(e,t){return{type:"CNAME",name:e,value:t.endsWith(".pages.dev")?t:`${t}.pages.dev`,ttl:1,proxied:!0}}async function Me(e,t){let{blake3:r}=await import("./chunk-dndxwssj.js").then((m)=>gt(m.default,1));return(await r(e+t)).slice(0,32)}async function Be(e){let{readdir:t}=await import("node:fs/promises"),{join:r,relative:n,sep:i}=await import("node:path"),d=[];async function s(a){let l=await t(a,{withFileTypes:!0});for(let p of l){let u=r(a,p.name);if(p.isDirectory()){await s(u);continue}if(!p.isFile())continue;let b=`/${n(e,u).split(i).join("/")}`;if(yt.has(b))continue;let C=await Bun.file(u).bytes();if(C.byteLength>26214400)throw Error(`${b} is ${C.byteLength} bytes, over the Cloudflare Pages limit of 26214400`);let P=Buffer.from(C).toString("base64"),g=p.name.lastIndexOf("."),m=g>0?p.name.slice(g+1):"";d.push({path:b,hash:await Me(P,m),base64:P,extension:m,size:C.byteLength})}}return await s(e),d.sort((a,l)=>a.path.localeCompare(l.path)),d}function St(e){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"}[e.toLowerCase()]||"application/octet-stream"}async function X(e,t,r,n){let i={Authorization:r},d;if(n instanceof FormData)d=n;else if(n!==void 0)i["Content-Type"]="application/json",d=JSON.stringify(n);let s=await fetch(`https://api.cloudflare.com/client/v4${t}`,{method:e,headers:i,body:d}),a=await s.text(),l;try{l=JSON.parse(a)}catch{throw Error(`Cloudflare Pages API returned ${s.status} with a non-JSON body: ${a.slice(0,200)}`)}if(!l.success){let p=(l.errors??[]).map((u)=>`${u.code}: ${u.message}`).join(", ");throw Error(`Cloudflare Pages API error (${s.status}): ${p||a.slice(0,200)}`)}return l.result}export{Cp as ABTestManager,Mr as ACMClient,Br as ACMDnsValidator,ke as ACME_DIRECTORIES,F as AI,yh as API_IDEMPOTENCY_TTL_MS,gh as API_TOKEN_DEFAULT_TTL_MS,hh as API_TOKEN_MAX_TTL_MS,bS as API_VERSION,th as AUTHORIZATION_CAPABILITIES,Hg as AUTH_ACTION_TOKEN_TTL_MS,zg as AUTH_MFA_CHALLENGE_TTL_MS,Gg as AUTH_OIDC_TRANSACTION_TTL_MS,Wg as AUTH_SESSION_ABSOLUTE_TTL_MS,Vg as AUTH_SESSION_IDLE_TTL_MS,wl as AWSAPIError,zt as AWSClient,Ve as AWSCloudFormationClient,We as AWSCloudFrontClient,ap as AWSConfigManager,Rc as AWS_PSEUDO_PARAMETERS,yu as AWS_REGIONS,st as AcmeClient,Zt as AlertEvaluator,qt as AlertStore,DC as AnomalyConfigStore,De as ApiGateway,hS as ApiServiceError,mn as ApplicationAutoScalingClient,bc as Arn,hc as AssetHasher,fc as Auth,Ug as AuthenticationStore,CS as AutomationApiService,Ch as AutomationIdentityStore,MA as AwsAuroraDataAdapter,zA as AwsAuroraTransport,Lb as AwsDatabaseBackupSource,Bn as AwsDriver,BA as AwsElastiCacheDataAdapter,GA as AwsElastiCacheTransport,NS as AwsIamCapabilityScanner,Gb as AwsInfrastructureBackupSource,_A as AwsRdsDataAdapter,HA as AwsRdsTransport,pb as AwsRegionalDriver,Zb as AwsSecretsManagerConfigurationBackend,mS as AwsSpendTransport,Jb as AwsSsmConfigurationBackend,kb as BackupCoordinator,rp as BackupManager,wb as BackupStore,xm as BatchProcessingManager,tn as BedrockClient,en as BedrockRuntimeClient,yy as BitbucketSourceAdapter,fp as BlueGreenManager,Cm as BounceComplaintHandler,qp as BuildOptimizationManager,UA as BunDockerRuntime,Wb as BunDockerVolumeRuntime,Mb as BunFilesystemArchiveRuntime,ic as CDN,bt as CHAIN_HEADER,Ar as CLOUDFLARE_MANAGED_RULE_PREFIX,Fu as COMMON_CROSS_ACCOUNT_ROLES,Qg as CONTROL_PLANE_SCHEMA_VERSION,oe as Cache,hp as CanaryManager,Hp as CertificateManager,Qh as CloudBlockVolumeDriver,ui as CloudDriverFactory,Pl as CloudError,Pc as CloudFormationBuilder,Ve as CloudFormationClient,We as CloudFrontClient,cp as CloudTrailManager,Kr as CloudWatchLogsClient,_e as CloudflarePagesProvider,br as CloudflareProvider,iu as CommandHistory,Sc as Communication,ny as ComposeApplicationService,ry as ComposeApplicationStore,rn as ComprehendClient,E as Compute,fS as ComputeSpendTransport,Tl as ConfigurationError,Xb as ConfigurationService,Ub as ConfigurationStore,qr as ConnectClient,WA as ContainerDataAdapter,Jp as ContainerRegistryManager,zb as ControlPlaneBackupSource,$b as ControlPlaneCleanupDriver,mh as ControlPlaneStore,Qy as CounterTracker,$l as CredentialError,lu as CrossRegionReferenceManager,zc as DASHBOARD_ENTRY,Gc as DASHBOARD_PORT_BASE,Uc as DASHBOARD_PORT_SPAN,Hc as DASHBOARD_STATE_DIR,Vi as DEFAULT_ATTACK_MODE_HOURS,er as DEFAULT_DDOS_THRESHOLDS,Jy as DEFAULT_METER_MAPPINGS,Wy as DEFAULT_PRICE_BOOK,Tt as DEFAULT_RECURSION_LIMITS,Bl as DEFAULT_SERVICE_LIMITS,$s as DEFAULT_STATE_DIR,xe as DEFAULT_STATIC_ASSET_EXTENSIONS,UC as DEFAULT_TELEMETRY_POLICY,nC as DEFAULT_THRESHOLDS,Wh as DEPLOYMENT_QUEUE_KINDS,At as DEPTH_HEADER,wC as DETECTABLE_SIGNALS,fA as DIAGNOSTIC_PRESETS,Nm as DLQMonitoringManager,oc as DNS,fm as DNSSECManager,LA as DataServiceLifecycle,kA as DataServiceStore,K as Database,Fp as DatabaseUserManager,Nl as DebugLogger,ec as DependencyGraph,gc as Deployment,Il as DeploymentError,ip as DisasterRecoveryManager,Fr as DnsProviderFactory,jA as DockerDataTransport,oA as DockerDiscoveryAdapter,Yh as DockerNamedVolumeDriver,Hb as DockerVolumeBackupSource,_h as DurableOperationQueue,Mh as DurableQueueWorker,Yr as DynamoDBClient,gr as EC2Client,Vr as ECRClient,Wr as ECSClient,bn as EFSClient,Zr as ELBv2Client,Ny as ENFORCEMENT_ACTIONS,pC as ENFORCEMENT_DESCRIPTIONS,ky as ENFORCEMENT_SEVERITY,Uf as ENVIRONMENT_LABEL,lA as EcsRuntimeAdapter,Fi as EdgeRateLimiter,un as ElastiCacheClient,L as Email,Im as EmailAdvanced,Am as EmailAnalyticsManager,Kt as EmailClient,Dm as EmailHandlers,Tm as EmailTemplateManager,KA as EncryptedDataSecretStore,El as ErrorCodes,dn as EventBridgeClient,DA as EventBridgeJobAdapter,Yb as ExternalConfigurationBackend,vm as FIFOQueueManager,kC as FOCUS_VERSION,zl as FileCache,j as FileSystem,Bb as FilesystemBackupSource,XA as FleetService,YA as FleetStore,Ac as Fn,Cy as GiteaSourceAdapter,gy as GithubSourceAdapter,hy as GitlabSourceAdapter,du as GlobalResourceManager,Sr as GoDaddyProvider,dp as GuardDutyManager,_t as HOST_SITES_DIR,Ql as HashCache,Of as HealthCheckManager,Xt as HealthCheckRunner,jn as HetznerClient,Qn as HetznerDriver,Gt as IAMClient,$n as IPV6_EXCLUDED_HOST_LABELS,jp as ImageScanningManager,Ke as InfrastructureGenerator,sh as InvalidOperationTransitionError,cc as JobLoader,wA as JobProviderReconciler,vA as JobService,TA as JobStore,ln as KendraClient,bf as LARAVEL_SERVERLESS_BUILD_STEPS,jr as LambdaClient,im as LambdaConcurrencyManager,dm as LambdaDLQManager,am as LambdaDestinationsManager,em as LambdaLayersManager,dA as LambdaRuntimeAdapter,cm as LambdaVPCManager,rm as LambdaVersionsManager,qb as LocalEncryptedConfigurationBackend,Vb as LogicalDatabaseBackupSource,Ip as LogsManager,Gm as MANAGED_NODE_VERSIONS,Ri as MANAGEMENT_DASHBOARD_SITE,Jc as MANAGEMENT_DASHBOARD_SITE_PREFIX,Bi as MAX_CONTROL_HOURS,uh as MAX_CONTROL_PLANE_ERROR_BYTES,dh as MAX_CONTROL_PLANE_JSON_BYTES,Oy as METERS,vy as METER_KEYS,xy as MICRO_CENTS,cC as MIN_PROJECTION_CONFIDENCE,En as MTA_STS_PORT,Rb as MaintenanceService,Ab as MaintenanceStore,pc as Messaging,Tp as MetricsManager,vp as MigrationManager,Pd as MockCloudFormation,$d as MockDynamoDB,Td as MockS3,we as Monitoring,vu as MultiAccountManager,su as MultiRegionManager,Hd as MultiStepProgress,Te as Network,kf as NetworkSecurityManager,Yt as NotificationRouter,Xr as OpenSearchClient,ah as OptimisticConcurrencyError,Ou as OrganizationManager,ht as PAGES_MAX_FILE_BYTES,Pf as PHP_DEFAULT_EXCLUDES,Zm as PHP_LAYER_EXTENSIONS,Gf as PROJECT_LABEL,yr as PROXIABLE_RECORD_TYPES,Cc as ParameterStore,xp as PerformanceManager,Ie as Permissions,cn as PersonalizeClient,sc as Phone,wm as PhoneAdvanced,ac as PhoneHandlers,rb as PlacementService,tb as PlacementStore,an as PollyClient,Cr as PorkbunProvider,IS as PreDeployScanner,Dd as PreviewEnvironmentManager,Vh as PreviewEnvironmentService,Bh as PreviewEnvironmentStore,Nd as PreviewNotificationService,Wd as ProgressBar,Ap as ProgressiveDeploymentManager,Wi as ProtectionControlStore,Hs as Pseudo,ie as Queue,xh as QueueCancellationError,Fm as QueueManagementManager,Ps as QueuePresets,Lh as QueueTimeoutError,Ni as RATE_LIMIT_KEY_SEPARATOR,Jr as RDSClient,xu as RECOMMENDED_ACCOUNT_STRUCTURES,Lu as RECOMMENDED_SCPS,uy as RELEASE_QUEUE_KINDS,tu as REPL,nu as REPLCommandBuilder,ru as REPLContext,jf as ROLE_LABEL,ad as RateLimiter,Ts as RealtimePresets,GC as RecordingSpendTransport,Dt as RecursionGuard,q as Redirects,uu as RegionPairManager,db as RegionService,lb as RegionStore,nc as Registry,nn as RekognitionClient,sy as ReleaseService,ay as ReleaseStore,nb as RemoteBuildService,Np as ReplicaManager,Lf as ResourceManagementManager,Fh as RetryableOperationError,J as Route53Client,hr as Route53DomainsClient,Ir as Route53Provider,hm as Route53ResolverManager,pm as Route53RoutingManager,gA as RuntimeOperationService,hA as RuntimeStreamRegistry,Nb as S3BackupDestinationAdapter,Ut as S3Client,bl as S3Error,$S as SECRET_PATTERNS,$C as SENSITIVITY_THRESHOLDS,jt as SESClient,uc as SMS,Gr as SNSClient,uS as SPEND_CYCLE_SECONDS,BC as SPEND_GATE_SETTING,cS as SPEND_LEASE_SETTING,Ur as SQSClient,ti as SSH_BOOTSTRAP_VERSION,ii as SSH_PREFLIGHT_SCRIPT,Hr as SSMClient,Is as STATE_DIR_ENV_VAR,H as STATIC_SITE_ZONE_SETTINGS,cr as STSClient,pn as SchedulerClient,Ee as Search,vS as SecretFindingScanner,yc as Secrets,Vp as SecretsManager,zr as SecretsManagerClient,Mp as SecretsRotationManager,ne as Security,pp as SecurityHubManager,TS as SecurityPostureStore,ES as SecurityScannerRunner,Gp as SecurityScanningManager,Rm as SenderReputationManager,IA as ServerCronJobAdapter,VA as ServerDataAdapter,Xh as ServerPathVolumeDriver,Xp as ServiceMeshManager,$e as Sftp,vC as SignalSource,Em as SmsAdvanced,fn as SmsClient,dc as SmsHandlers,An as SmsVoiceClient,my as SourceConnectionStore,fy as SourceProviderError,WC as SpendCapError,VC as SpendGate,lS as SpendLoopLease,sS as SpendNotificationRouter,dS as SpendRunner,_C as SpendService,iC as SpendStore,zd as Spinner,li as SshDriver,ZA as SshFleetDriver,pu as StackDependencyManager,lc as StacksIntegration,Df as StaticSiteManager,re as Storage,Ef as StorageAdvancedManager,hn as SupportClient,wp as SyntheticsManager,qA as SystemFleetSshTransport,ei as SystemSshTransport,cA as SystemdDiscoveryAdapter,Rt as TRACE_HEADER,Gd as TaskList,nS as TelemetryStore,be as TemplateBuilder,Gl as TemplateCache,on as TextractClient,Qr as TranscribeClient,sn as TranslateClient,Ib as TransportDisasterRecoveryDriver,Tb as TransportPlatformMaintenanceDriver,ob as TransportRemoteBuildDriver,OS as TrivyImageScanner,Sh as TsCloudApiError,Ah as TsCloudClient,iS as URGENT_SPEND_EVENTS,mC as USER_VISIBLE_ACTIONS,mb as UnavailableRegionalDriver,Or as UnifiedDnsValidator,ch as UnsupportedSchemaVersionError,Dl as ValidationError,gn as VoiceClient,Zh as VolumeService,Gh as VolumeStore,mc as Workflow,Rp as XRayManager,Sp as abTestManager,ly as activateImmutableRelease,Ui as addSiteToCloudConfig,XS as ageSeconds,tC as aggregateDeltas,Ht as allocateSitePorts,tc as analyzeStackDiff,TC as anomalyOptionsForSignal,Gi as applyControlsToDdos,zi as applyControlsToRateLimits,sr as applyMitigationFactor,ig as applyPlan,Er as applyZoneMigration,Hm as artifactKey,oy as assertReleaseStrategy,HC as assertSpendAllows,dg as attachConflicts,ug as attachIsViable,lg as attachPreconditions,MS as attachProvenanceToRelease,LS as attachSbomToRelease,FS as attachVulnerabilitySummary,Kg as authEncryptionKeyFile,ih as authorizeOrganization,mA as authorizeRuntimePath,Jd as autocomplete,sp as awsConfigManager,Ob as backupCredentialStatus,np as backupManager,td as batch,Lm as batchProcessingManager,Yg as beginOidcAuthorization,gp as blueGreenManager,Sm as bounceComplaintHandler,jy as budgetWindow,ao as buildAndPushServerlessImage,rf as buildBunRuntimeLayerZip,vg as buildCertificatePackScript,Dg as buildCertificateStateScript,Og as buildCertificateUnpackScript,Tc as buildCloudFormationTemplate,mi as buildCloudInitFirstBoot,Nh as buildComposeLogsCommand,vh as buildComposeRuntimeCommand,Oh as buildComposeScaleCommand,kh as buildComposeShellCommand,Pg as buildDrainSourceScript,Wf as buildDrainedSiteScanScript,co as buildFunctionEnv,Rg as buildHealthGateScript,bi as buildHostCleanupScript,Vt as buildHostSitePortsScript,Vs as buildMailEnv,Di as buildManagementDashboardArtifact,$o as buildMediaCdnPlan,wn as buildMtaStsPolicy,vn as buildMtaStsServer,tf as buildNodeRuntimeLayerZip,Zp as buildOptimizationManager,de as buildOriginGuardRule,gg as buildPauseWorkersScript,Rf as buildPhpRuntimeLayerZip,Sg as buildRestoreScript,sg as buildSetHostnameScript,Si as buildSiteDeployScript,Cg as buildSnapshotScript,Tg as buildSourceStateScript,Vn as buildSshArgs,ri as buildSshBootstrapScript,le as buildStaticSiteCacheRules,Ai as buildStaticSiteDeployScript,Ag as buildTargetStateScript,hg as buildWorkersStateScript,QS as bytes,yp as canaryManager,fb as canonicalJson,ZS as capabilities,eb as capacity,pd as categorizeChanges,zp as certificateManager,Eg as certificatesMatch,Fl as checkIAMPermissions,lf as checkInvocation,Vl as checkServiceQuotas,sd as chunk,Ho as cleanupDns01Challenge,Ss as clearSigningKeyCache,Ty as cloneSourceBinding,gd as cloudConfigSchema,pi as cloudDrivers,lp as cloudTrailManager,Be as collectAssets,$f as collectPhpAppEntries,Rn as collectServerDnsDomains,ty as completeComposeVolumeDeletion,Xg as completeOidcAuthorization,rl as composePresets,Eh as composeProjectName,qm as composeServerlessAppTemplate,gS as compositeSpendTransport,Fb as compressBackup,Vf as config,xA as connectionGuidance,Yp as containerRegistryManager,lh as controlPlaneDatabaseFile,eh as controlPlaneMigrations,Oc as createApiBackendPreset,PS as createApiV1Handler,cb as createAsgBuildDriver,xb as createBackupQueueHandlers,hf as createCliHandler,di as createCloudDriver,Ae as createCloudFrontPolicy,yl as createCredentialProvider,Wc as createDashboardSite,Fc as createDataPipelinePreset,FA as createDataServiceQueueHandlers,zh as createDeploymentQueueHandlers,Y as createDnsProvider,sb as createEcsBuildDriver,zC as createEnforcementHandlers,Ol as createError,Ec as createExistingStaticFullStackPreset,JA as createFleetQueueHandlers,vc as createFullStackAppPreset,kr as createGoDaddyValidator,yf as createHandlers,ff as createHttpHandler,kc as createJamstackPreset,OA as createJobQueueHandlers,Bc as createLaravelPreset,_c as createMLApiPreset,Pb as createMaintenanceQueueHandlers,Ro as createMediaAccessToken,xc as createMicroservicesPreset,Id as createMockAWS,Ic as createNodeJsServerPreset,Dc as createNodeJsServerlessPreset,fr as createObjectStorageClient,Nr as createPorkbunValidator,nl as createPreset,ps as createPresignedUrl,ms as createPresignedUrlAsync,gf as createQueueHandler,Lc as createRealtimeAppPreset,ub as createRegionQueueHandlers,_S as createReleaseProvenance,py as createReleaseQueueHandlers,ib as createRemoteBuildQueueHandlers,xr as createRoute53Validator,uA as createRuntimeAdapters,Rl as createS3Client,ab as createServerBuildDriver,Vc as createServerlessLaravelPreset,wc as createServerlessNodePreset,Sn as createSmsInfrastructure,Sy as createSourceAdapter,$c as createStaticSitePreset,Mc as createTraditionalWebAppPreset,Jh as createVolumeQueueHandlers,Nc as createWordPressPreset,Mm as createZip,mu as crossRegionReferenceManager,ho as dashboardActions,Pi as dashboardCredentialsFile,NA as dataServiceCapabilities,_p as databaseUserManager,xg as decodeBase32,_b as decompressBackup,vb as decryptBackup,_f as defaultConfig,yd as defaultLocalConfig,Mi as defaultRateLimitRules,no as deleteStaticSite,Ei as deployAllComputeSites,lo as deployServerlessApp,oo as deploySite,wi as deploySiteRelease,eo as deployStaticSite,io as deployStaticSiteFull,Yi as deployStaticSiteWithExternalDns,Xi as deployStaticSiteWithExternalDnsFull,Ls as deploymentCoexistenceError,jc as deriveManagementDashboardPort,Hi as describePosture,$A as desiredJobProviderState,RC as detectAnomalies,ks as detectDeploymentTargets,Lr as detectDnsProvider,PC as detectLatestAnomaly,xl as detectMisconfigurations,ls as detectServiceRegion,Ph as diffCompose,ld as diffTemplates,Py as discoverGitRefs,Jg as discoverOidcProvider,eA as discoverRuntimeInventory,km as dlqMonitoringManager,_r as dnsProviders,gm as dnssecManager,iA as dockerWorkloads,hb as documentDigest,op as drManager,Jn as driverStatePath,tA as ecsWorkloads,oh as effectiveCapabilities,bm as emailAnalyticsManager,$m as emailTemplateManager,kg as encodeBase32,Eb as encryptBackup,WS as ensureDefaultSecurityPolicies,gi as ensureFirewall,Ii as ensureManagementDashboard,hi as ensureServer,fi as ensureSshKey,Nn as escapeSecLang,dC as evaluateBudget,ai as evaluatePreflight,Qt as evaluateTelemetryAlertRules,RA as eventBridgeScheduleInput,pf as eventToRequest,bC as ewma,Rh as exportCompose,Dr as exportRoute53Zone,tl as extendPreset,Om as fifoQueueManager,Xl as findChangedFiles,Yy as findMapping,Fy as findPriceEntry,Vu as formatAccountStructure,pg as formatAttachPlan,_d as formatBytes,oS as formatCents,rc as formatDiff,zf as formatDrainedSiteRefusal,Md as formatDuration,Xd as formatFlagSuggestions,ou as formatHistory,au as formatHistoryStats,Qf as formatInventory,Vd as formatKeyValue,Bd as formatList,ng as formatPlan,ci as formatPreflightFindings,Fd as formatProgressBar,Du as formatRegion,wu as formatRegionList,wS as formatScanResults,jd as formatSuggestion,xd as formatTable,sC as formatTimeToExhaustion,Ld as formatTree,ml as fromEC2Metadata,fl as fromECSMetadata,ul as fromEnvironment,pl as fromSharedCredentials,gl as fromWebIdentity,Pt as functionFingerprint,fe as gatewayHostnames,Qm as generateAppImageDockerfile,ep as generateApprovalConfig,Bm as generateBootstrap,vd as generateCleanupWorkflow,Od as generateCostReportWorkflow,Mu as generateCrossAccountRoleCF,kS as generateCycloneDxSbom,Yu as generateDeploymentConfig,ju as generateDeploymentPipeline,Wu as generateDeploymentWorkflow,Ji as generateExternalDnsStaticSiteTemplate,Vo as generateHttpsServerCode,xS as generateImageSbom,Bo as generateLetsEncryptUserData,Pe as generateLogicalId,Ju as generateManualPipeline,Uu as generateMatrixWorkflow,Xu as generateMultiEnvConfig,Ku as generateMultiEnvPipeline,Hu as generateMultiEnvWorkflow,zu as generatePRPreviewWorkflow,tp as generateParallelConfig,Cf as generatePhpFpmConfig,Xm as generatePhpLayerDockerfile,qu as generatePreviewPipeline,Ed as generatePreviewWorkflow,Re as generateResourceName,Qu as generateScheduledConfig,Zu as generateScheduledPipeline,Gu as generateScheduledWorkflow,Qi as generateStaticSiteTemplate,Mn as generateUbuntuAppCloudInit,Al as getAccountId,Su as getAllRegions,Tu as getClosestRegion,Qd as getCommandUsage,$h as getComposeTemplate,Mf as getConfig,qd as getContextualHelp,hl as getCredentials,md as getDeploymentStrategy,fd as getDiffStats,dd as getDiffSummary,vl as getErrorDetails,Cd as getLocalConfig,bd as getLocalCredentials,Ad as getLocalEndpoint,Rd as getLocalEnvVars,Wl as getQuotaUsageSummary,_u as getRecommendedStructure,Cu as getRegion,Eu as getRegionStats,bu as getRegionsByCompliance,Au as getRegionsByLocation,Ru as getRegionsByPricingTier,_l as getRequiredPermissions,As as getSigningKeyCacheSize,Cn as getSmsInfrastructureStatus,zs as getTimestamp,ki as globMatches,xn as globToRegex,fu as globalResourceManager,lC as governingLimitCents,up as guardDutyManager,SS as handleSpendRequest,On as hasAutoWwwVariant,Zc as hasManagementDashboardSite,Nt as hasProxyUpstream,ql as hashBuffer,Zl as hashDirectory,jl as hashFile,Jl as hashManifest,Kl as hashString,Nf as healthCheckManager,me as hostAcceptsIpv6,ce as hostCondition,Lg as hotp,qy as hourBucket,Zy as hourBucketsBetween,Kp as imageScanningManager,so as infraEnvFromOutputs,It as inspectInvocation,af as installRecursionFetch,ro as invalidateCache,nf as invocationContext,Kd as isLikelyTypo,Sd as isLocalDevelopment,Xc as isManagementDashboardSiteName,bs as isNodeCryptoAvailable,yC as isOperationAllowed,Jt as isQuietHours,kn as isSafePattern,ws as isStateDirConfigured,Ns as isStatePath,tr as isValidCidr,Pu as isValidRegion,Hy as isValidTimeZone,Rs as isWebCryptoAvailable,AA as jobProviderCapability,dr as keyMatchesFilters,om as lambdaConcurrencyManager,um as lambdaDLQManager,sm as lambdaDestinationsManager,tm as lambdaLayersManager,lm as lambdaVPCManager,nm as lambdaVersionsManager,rA as lambdaWorkloads,Af as laravelServerlessEnvDefaults,Th as listComposeTemplates,Dy as listSourceReferences,Bf as loadCloudConfig,qC as loadTelemetryPolicy,Dp as logsManager,NC as lookbackHoursForSignal,_s as mailEnabled,Bs as mailFirewallPorts,bb as maintenanceWindowOpen,fs as makeAWSRequest,hs as makeAWSRequestAsync,gs as makeAWSRequestOnce,Yc as managementDashboardSiteName,gb as manifestDigest,Mg as matchTotpCounter,To as mediaObjectHeaders,CC as median,SC as medianAbsoluteDeviation,uC as mergeDecisions,il as mergeInfrastructure,Vy as mergePriceBooks,eC as meterTelemetry,$p as metricsManager,ur as migrateObjectStorage,Op as migrationManager,Nu as multiAccountManager,cu as multiRegionManager,zo as needsRenewal,xf as networkSecurityManager,CA as nextScheduleRuns,Tn as normalizePublicIpv6,JS as normalizeRuntimeStatus,yA as normalizeScheduleExpression,Ay as normalizeSourceEvent,qn as normalizeSshPublicKey,jC as normalizeTelemetryPolicy,Bt as occupiedHostPorts,RS as openApiDocument,OC as optionsForSignal,ku as organizationManager,If as packagePhpApp,zm as packageServerlessApp,Me as pagesAssetHash,Ct as pagesDnsRecord,ed as parallel,rd as parallelMap,nd as parallelWithRetry,wg as parseCertificateState,$t as parseChain,bh as parseCompose,Dh as parseComposeCatalog,nA as parseDockerInspect,jb as parseDotenv,Hf as parseDrainedSites,Wt as parseHostSiteFragments,Cs as parseJSONResponse,oi as parsePreflightFacts,$g as parseSourceDrained,aA as parseSystemdRecords,bg as parseTargetReady,Mt as parseUpstreamPort,yg as parseWorkersPaused,ys as parseXMLResponse,QC as pathTemplate,tg as pendingSteps,aC as percentOfLimit,Lp as performanceManager,Ym as phpLayerBuildStage,Jm as phpLayerPackages,Sf as phpRuntimeLayerAssets,wh as planComposeTemplateUpgrade,fC as planEnforcement,rg as planIsDestructive,ar as planMitigation,ag as planServerRename,Ng as planSiteMove,wr as planZoneMigration,Rr as policyTag,si as preflightFailed,wd as previewManager,kd as previewNotifications,SA as previewSchedule,Ky as previousBudgetWindow,_y as priceUsage,My as priceUsageLines,Jf as probeHostRoutes,pe as probeOriginTls,cd as processInChunks,by as processSourceWebhook,US as productionChangeReview,bp as progressiveDeploymentManager,oC as projectSpend,wt as propagationHeaders,pr as providerEndpoint,yb as publicKeyFingerprint,Pr as qualifyName,_m as queueManagementManager,Yl as quickHash,_i as rateLimitHeaders,Li as rateLimitKey,Yn as readDriverState,Yf as reconcile,In as reconcileAddressRecords,pt as reconcileCloudflareCdn,$r as reconcileDeclaredRecords,PA as reconcileJobObservation,wy as reconcileSourceWebhook,GS as recordDashboardHostPosture,HS as recordPreDeploySecretScan,zS as recordSkippedSecretScan,Et as recursionBlockedResponse,YS as redactRuntimeConfig,YC as redactTelemetryText,XC as redactTelemetryValue,uo as redeployServerlessApp,gu as regionPairManager,iy as releaseStrategyCapabilities,cy as releaseTrafficPlan,vi as reloadRpxGateway,lr as remapKey,ji as removeSiteFromCloudConfig,Ey as removeSourceWebhook,Pn as removeStaleServerAddressRecords,Ih as renderComposeTemplate,or as renderDdosInstallScript,ir as renderNftablesRuleset,bA as renderServerCron,nr as renderSysctlFile,Ln as renderWafConfig,Fn as renderWafInstallScript,Oi as renewRpxCertificates,kp as replicaManager,yS as requestHash,ud as requiresReplacement,cf as resetRecursionRuntime,uf as resolveApp,Fs as resolveAppDatabase,cg as resolveAttachTarget,qg as resolveAuthEncryptionKey,Ws as resolveCloudProvider,ft as resolveCloudflareCdnPlan,Cl as resolveCredentials,yo as resolveDashboardAction,Ti as resolveDashboardAuth,Kc as resolveDashboardDomain,qc as resolveDashboardDomains,Tr as resolveDeclaredRecords,Js as resolveDeployBucketName,xs as resolveDeploymentMode,Ci as resolveExecStart,Kn as resolveHetznerApiToken,Ms as resolveMailService,el as resolveManagementDashboardSite,Qc as resolveManagementDashboardSites,mr as resolveObjectStorage,eg as resolvePlan,Us as resolveProjectStackName,Ot as resolveProxyUpstreams,Km as resolveQueueNames,Hh as resolveQueuedDeploymentCommand,jm as resolveQueues,of as resolveRecursionConfig,Sl as resolveRegion,pA as resolveRuntimeInventory,Ys as resolveServerlessAppStackName,Xs as resolveServerlessArtifactBucketName,Qs as resolveServerlessAssetBucketName,Um as resolveServerlessRuntime,qs as resolveSiteBucketName,kt as resolveSiteDeployTarget,xt as resolveSiteKind,Ks as resolveSiteResourceName,js as resolveSiteStackName,ni as resolveSshSettings,Os as resolveStatePath,Zs as resolveStorageBucketName,$i as resolveUiSource,Fe as resolveZoneApex,Ff as resourceManagementManager,mf as responseToResult,AC as robustZScore,rh as roleCapabilities,dy as rollbackImmutableRelease,po as rollbackServerlessApp,By as roundCents,ym as route53ResolverManager,mm as route53RoutingManager,IC as routeMatches,qf as routesFromFragments,xi as ruleMatches,Vm as runBuildHooks,gC as runEnforcement,Tf as runPhpBuildHooks,fo as runRemoteCommand,KS as runtimeId,go as sanitizeCloudConfig,ph as sanitizeControlPlaneValue,Gs as sanitizeName,Zg as sanitizeOidcReturnPath,ZC as saveTelemetryPolicy,DS as scanForSecrets,nh as scopeContains,rC as scopeKey,zn as scpUpload,Zd as searchCommands,fh as searchControlPlane,Wp as secretsManager,Bp as secretsRotationManager,jS as secureContainerRelease,mp as securityHubManager,Up as securityScanningManager,VS as securityScope,jg as sendAuthenticationEmail,Pm as senderReputationManager,id as sequence,Kb as serializeDotenv,yi as serverPublicIpv4,Qp as serviceMeshManager,Zi as setAttachToInCloudConfig,mo as setMaintenance,qi as setSitePropertyInCloudConfig,Ds as setStateDir,Wo as setupDns01Challenge,yn as setupSmsInfrastructure,Wm as sha256,sf as sharedRecursionGuard,ef as sharedRuntimeLoop,Ft as shipsARelease,bo as signCloudFrontCookies,Ao as signCloudFrontUrl,ds as signRequest,us as signRequestAsync,EC as signalDefinition,vt as siteInstallBase,mg as siteMoveArchivePath,Ig as siteMoveCertArchivePath,fg as siteUnitGlob,aS as spendNotificationText,AS as spendOpenApiPaths,Wn as sshExec,Hn as sshExecOrThrow,hu as stackDependencyManager,Co as startLocalDashboardServer,pS as startSpendLoop,Es as stateDir,vs as statePath,wf as staticSiteManager,vf as storageAdvancedManager,FC as streamFocusJsonl,hC as strongestActiveAction,Ud as suggestCommand,Yd as suggestFlags,Ml as suggestIAMPolicy,Hl as suggestQuotaIncrease,Iu as suggestRegionPairs,$u as suggestRegions,Iy as syncSourceRepositories,ey as synchronizeComposeVolumes,Qb as synchronizeConfiguredConfiguration,EA as synchronizeConfiguredJobs,Ep as syntheticsManager,rr as sysctlHardening,sA as systemdWorkloads,rS as telemetryBucketLabel,eS as telemetryCursor,JC as telemetryEstimatedMonthlyCost,tS as telemetryPercentile,KC as telemetryPolicyKey,Ul as templateCache,Zf as tenantsOf,$y as testSourceConnection,Ly as tieredMicroCents,ue as toCloudflareZoneSettings,LC as toFocusJsonl,xC as toFocusRecords,Kf as toInventoryServer,Fg as totp,Bg as totpUri,Xf as unaccountedSites,qS as unsupportedCapabilities,Uh as unsupportedVolumeCapabilities,Sb as updateCompatibility,Ki as updateSiteInCloudConfig,to as uploadStaticFiles,Xy as usageDeltaKey,Uy as utcInstantOfLocal,Bu as validateAccountStructure,hd as validateAgainstSchema,qh as validateAttachment,Db as validateBackupDestination,eu as validateCommand,kl as validateConfiguration,Ll as validateCredentials,Lt as validateDeploymentConfig,Kh as validateMountPath,et as validateResourceLimits,og as validateServerName,qe as validateTemplate,Qe as validateTemplateSize,Dn as verifyAddressRecord,BS as verifyArtifactSignature,Po as verifyMediaAccessToken,_g as verifyTotp,Cb as verifyUpdateSignature,vr as verifyZoneParity,jh as volumeCapabilities,_n as wafEventTelemetry,Un as waitForCloudInit,Gn as waitForSsh,Ry as webhookEndpoint,ll as withCDN,cl as withCache,sl as withDatabase,df as withInvocation,ol as withMonitoring,dl as withQueue,al as withSecurity,od as withTimeout,Zn as wrapCloudInitUserData,Xn as writeDriverState,Pp as xrayManager,QA as zeroCapacity,MC as zeroFill,Gy as zoneOffsetMs,zy as zonedParts};
595
+ `}async function Dm(l){let{domain:S,challengeValue:b,hostedZoneId:P,dnsProvider:v,region:Xe="us-east-1"}=l;if(v){let fe=await T(v).upsertRecord(S,{name:`_acme-challenge.${S}`,type:"TXT",content:b,ttl:60});if(!fe.success)throw Error(`Failed to create DNS challenge record: ${fe.message}`);return}if(P){await new h(Xe).changeResourceRecordSets({HostedZoneId:P,ChangeBatch:{Comment:"ACME DNS-01 challenge",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:`_acme-challenge.${S}`,Type:"TXT",TTL:60,ResourceRecords:[{Value:`"${b}"`}]}}]}});return}throw Error("Either dnsProvider or hostedZoneId must be provided")}async function wm(l){let{domain:S,challengeValue:b,hostedZoneId:P,dnsProvider:v,region:Xe="us-east-1"}=l;if(v){let fe=await T(v).deleteRecord(S,{name:`_acme-challenge.${S}`,type:"TXT",content:b});if(!fe.success)console.warn(`Failed to delete DNS challenge record: ${fe.message}`);return}if(P){await new h(Xe).changeResourceRecordSets({HostedZoneId:P,ChangeBatch:{Comment:"Remove ACME DNS-01 challenge",Changes:[{Action:"DELETE",ResourceRecordSet:{Name:`_acme-challenge.${S}`,Type:"TXT",TTL:60,ResourceRecords:[{Value:`"${b}"`}]}}]}});return}throw Error("Either dnsProvider or hostedZoneId must be provided")}function Om(l){try{let{execSync:S}=_e("node:child_process"),b=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 Ja,createSign as eu,generateKeyPairSync as Ya}from"node:crypto";var Xa={production:"https://acme-v02.api.letsencrypt.org/directory",staging:"https://acme-staging-v02.api.letsencrypt.org/directory"};class tu{directoryUrl;email;accountKey;accountUrl=null;directory=null;nonce=null;constructor(l){this.directoryUrl=l.staging?Xa.staging:Xa.production,this.email=l.email,this.accountKey=l.accountKey||this.generateAccountKey()}generateAccountKey(){let{privateKey:l}=Ya("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 P=this.nonce;return this.nonce=null,P}let l=await this.getDirectory(),b=(await fetch(l.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!b)throw Error("Failed to get nonce from ACME server");return b}getJwk(){let l=this.accountKey.split(`
596
+ `).filter((Xe)=>!Xe.startsWith("-----")).join(""),S=Buffer.from(l,"base64"),b=S.length-65,P=S.subarray(b+1,b+33),v=S.subarray(b+33,b+65);return{kty:"EC",crv:"P-256",x:this.base64UrlEncode(P),y:this.base64UrlEncode(v)}}getJwkThumbprint(){let l=this.getJwk(),S=JSON.stringify({crv:l.crv,kty:l.kty,x:l.x,y:l.y}),b=Ja("sha256").update(S).digest();return this.base64UrlEncode(b)}base64UrlEncode(l){return(typeof l==="string"?Buffer.from(l):l).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async signPayload(l,S){let b=await this.getNonce(),P=this.getJwk(),v={alg:"ES256",nonce:b,url:l};if(this.accountUrl)v.kid=this.accountUrl;else v.jwk=P;let Xe=this.base64UrlEncode(JSON.stringify(v)),he=S===""?"":this.base64UrlEncode(JSON.stringify(S)),fe=`${Xe}.${he}`,Ye=eu("SHA256");Ye.update(fe);let tt=Ye.sign(this.accountKey),et=tt.subarray(4,4+tt[3]),nr=4+tt[3]+2,vt=tt.subarray(nr,nr+tt[nr-1]),or=Buffer.alloc(32),Tt=Buffer.alloc(32);et.copy(or,32-et.length),vt.copy(Tt,32-vt.length);let ht=Buffer.concat([or,Tt]);return JSON.stringify({protected:Xe,payload:he,signature:this.base64UrlEncode(ht)})}async acmeRequest(l,S){let b=await this.signPayload(l,S),P=await fetch(l,{method:"POST",headers:{"Content-Type":"application/jose+json"},body:b}),v=P.headers.get("replay-nonce");if(v)this.nonce=v;let Xe,he=P.headers.get("content-type");if(he?.includes("application/json")||he?.includes("application/problem+json"))Xe=await P.json();else Xe=await P.text();if(!P.ok)throw Error(`ACME request failed: ${JSON.stringify(Xe)}`);return{body:Xe,headers:P.headers}}async registerAccount(){let l=await this.getDirectory(),{body:S,headers:b}=await this.acmeRequest(l.newAccount,{termsOfServiceAgreed:!0,contact:[`mailto:${this.email}`]}),P=b.get("location");if(!P)throw Error("No account URL returned");return this.accountUrl=P,P}async createOrder(l){if(!this.accountUrl)await this.registerAccount();let S=await this.getDirectory(),{body:b,headers:P}=await this.acmeRequest(S.newOrder,{identifiers:l.map((Xe)=>({type:"dns",value:Xe}))}),v=P.get("location");if(!v)throw Error("No order URL returned");return{orderUrl:v,authorizations:b.authorizations,finalize:b.finalize}}async getAuthorization(l){let{body:S}=await this.acmeRequest(l,""),b=S.identifier.value,P=this.getJwkThumbprint(),v=S.challenges.filter((Xe)=>Xe.type==="http-01"||Xe.type==="dns-01").map((Xe)=>{let he=`${Xe.token}.${P}`;if(Xe.type==="http-01")return{type:"http-01",token:Xe.token,keyAuthorization:he,identifier:`/.well-known/acme-challenge/${Xe.token}`};else{let fe=this.base64UrlEncode(Ja("sha256").update(he).digest());return{type:"dns-01",token:Xe.token,keyAuthorization:he,identifier:`_acme-challenge.${b}`,dnsValue:fe}}});return{domain:b,challenges:v}}async respondToChallenge(l){await this.acmeRequest(l,{})}async waitForAuthorization(l,S=30){for(let b=0;b<S;b++){let{body:P}=await this.acmeRequest(l,"");if(P.status==="valid")return;if(P.status==="invalid")throw Error(`Authorization failed: ${JSON.stringify(P)}`);await new Promise((v)=>setTimeout(v,2000))}throw Error("Authorization timed out")}generateCsr(l){let{privateKey:S}=Ya("rsa",{modulusLength:2048}),b=S.export({type:"pkcs8",format:"pem"});return{csr:this.createSimpleCsr(l,S),privateKey:b}}createSimpleCsr(l,S){throw Error("CSR generation requires additional implementation. Consider using the shell-based certbot approach instead.")}async finalizeOrder(l,S){let{csr:b,privateKey:P}=this.generateCsr(S),{body:v}=await this.acmeRequest(l,{csr:this.base64UrlEncode(Buffer.from(b,"base64"))}),Xe=v.certificate;if(!Xe)throw Error("Certificate not immediately available - polling not implemented");let fe=await(await fetch(Xe)).text(),Ye=fe.split(/(?=-----BEGIN CERTIFICATE-----)/g),tt=Ye[0],et=Ye.slice(1).join("");return{certificate:tt,privateKey:P,chain:et,fullchain:fe,expiresAt:new Date(Date.now()+7776000000)}}getAccountKey(){return this.accountKey}}var Qa=["js","mjs","cjs","css","map","woff","woff2","ttf","otf","eot","png","jpg","jpeg","gif","webp","avif","svg","ico","mp4","webm","ogg","mp3","wav","pdf","wasm"],ru=[{name:"x-stx-router",value:"true"}];function Li(l){return`"${l.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function os(l){return`{${l.map(Li).join(" ")}}`}function nu(l){let S=`http.request.headers[${Li(l.name.toLowerCase())}]`;return l.value===void 0?`len(${S}) > 0`:`any(${S}[*] == ${Li(l.value)})`}function Fa(l){if(l.length===1)return`http.host eq ${Li(l[0])}`;return`http.host in ${os(l)}`}function _a(l,S={}){if(S.enabled===!1||l.length===0)return[];let b=Fa(l),P=[],Xe=(S.bypassPaths??[]).map((or)=>`starts_with(http.request.uri.path, ${Li(or)})`),fe=(S.negotiatedRequestHeaders??ru).map(nu),Ye=[...Xe,...fe],tt=Ye.length>0?`(${Ye.join(" or ")})`:void 0;if(tt)P.push({action:"set_cache_settings",description:"bypass cache",expression:`(${b} and ${tt})`,enabled:!0,action_parameters:{cache:!1}});let et=tt?`${b} and not ${tt}`:b,nr=S.assetExtensions??Qa,vt=nr.length>0?`lower(http.request.uri.path.extension) in ${os([...nr])}`:void 0;if(vt)P.push({action:"set_cache_settings",description:"cache fingerprinted assets",expression:`(${et} and ${vt})`,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:S.assetEdgeTtl??2592000},browser_ttl:{mode:"override_origin",default:S.assetBrowserTtl??31536000}}});return P.push({action:"set_cache_settings",description:"cache documents",expression:vt?`(${et} and not ${vt})`:`(${et})`,enabled:!0,action_parameters:{cache:!0,edge_ttl:{mode:"override_origin",default:S.documentEdgeTtl??3600},browser_ttl:{mode:"override_origin",default:S.documentBrowserTtl??0}}}),P}function Ma(l,S,b){if(l.length===0||!S||!b)return[];return[{action:"rewrite",description:"origin guard header",expression:`(${Fa(l)})`,enabled:!0,action_parameters:{headers:{[S]:{operation:"set",value:b}}}}]}var hn=(l)=>l===void 0?void 0:l?"on":"off";function Va(l){let S={ssl:l.ssl,always_use_https:hn(l.alwaysUseHttps),automatic_https_rewrites:hn(l.automaticHttpsRewrites),min_tls_version:l.minTlsVersion,tls_1_3:hn(l.tls13),brotli:hn(l.brotli),http3:hn(l.http3),"0rtt":hn(l.zeroRtt),early_hints:hn(l.earlyHints),browser_cache_ttl:l.browserCacheTtl,always_online:hn(l.alwaysOnline),websockets:hn(l.websockets),email_obfuscation:hn(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 b of Object.keys(S))if(S[b]===void 0)delete S[b];return{...S,...l.raw??{}}}var _i={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 iu}from"node:tls";async function Wa(l){let{address:S,serverName:b,port:P=443,timeoutMs:v=5000}=l;return new Promise((Xe)=>{let he=!1,fe=(tt)=>{if(he)return;he=!0;try{Ye.destroy()}catch{}Xe(tt)},Ye=iu({host:S,port:P,servername:b,rejectUnauthorized:!1,timeout:v});Ye.once("secureConnect",()=>{if(Ye.authorized){fe({reachable:!0,trusted:!0});return}fe({reachable:!0,trusted:!1,reason:Ye.authorizationError?String(Ye.authorizationError):"origin certificate is not trusted for this hostname"})}),Ye.once("timeout",()=>{fe({reachable:!1,trusted:!1,reason:`no TLS handshake within ${v}ms`})}),Ye.once("error",(tt)=>{fe({reachable:!1,trusted:!1,reason:tt.message})})})}function ou(l,S){let b=S.replace(/\.$/,"").toLowerCase();return l.some((P)=>{let v=P.replace(/\.$/,"").toLowerCase();if(v===b)return!0;if(!v.startsWith("*."))return!1;let Xe=v.slice(2);if(!b.endsWith(`.${Xe}`))return!1;return!b.slice(0,b.length-Xe.length-1).includes(".")})}async function au(l){let{provider:S,zone:b,hosts:P,ipv4:v,ipv6:Xe,proxied:he=!0,settings:fe=_i,cache:Ye,originGuard:tt,purge:et=!0,ttl:nr=300,skipOriginProbe:vt=!1,skipEdgeCertificateCheck:or=!1}=l,Tt={records:[],settingsChanged:[],cacheRules:0,originGuard:!1,purged:!1,deferredProxy:[],warnings:[]};if(P.length===0)return Tt;let ht=[],we=he&&!or?await S.listEdgeCertificateHosts(b):null;for(let re of P){let Rt=he;if(Rt&&we&&!ou(we,re)){Rt=!1;let Nt=we.length===0?"the zone has no active edge certificate yet":`no active edge certificate covers it (${we.join(", ")})`;Tt.deferredProxy.push({host:re,reason:Nt}),Tt.warnings.push(`${re}: publishing DNS-only — ${Nt}. 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&&!vt){let Nt=await Wa({address:v,serverName:re});if(!Nt.trusted){Rt=!1;let Jt=Nt.reason||"origin is not serving a trusted certificate";Tt.deferredProxy.push({host:re,reason:Jt}),Tt.warnings.push(`${re}: publishing DNS-only for now — the origin does not yet serve a certificate this proxy can verify (${Jt}). 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)ht.push(re);let Dt=[{type:"A",content:v}];if(Xe&&mn(re))Dt.push({type:"AAAA",content:Xe});for(let{type:Nt,content:Jt}of Dt){let ir=await S.upsertRecord(b,{name:re,type:Nt,content:Jt,ttl:nr,proxied:Rt});if(ir.success)Tt.records.push({host:re,type:Nt,content:Jt,proxied:Rt});else Tt.warnings.push(`${re} ${Nt} → ${Jt} failed: ${ir.message||"unknown provider error"}`)}}if(ht.length===0){if(he)Tt.warnings.push("No host is proxied yet, so zone settings, cache rules and purge were skipped — they only take effect through the proxy.");return Tt}try{let re=Va(fe),Rt=await S.applyZoneSettings(b,re);Tt.settingsChanged=Rt.changed;for(let Dt of Rt.failed)Tt.warnings.push(`zone setting '${Dt.id}' could not be applied: ${Dt.error}`)}catch(re){Tt.warnings.push(`zone settings could not be read: ${re instanceof Error?re.message:String(re)}`)}let wt=_a(ht,Ye);if(wt.length>0){let re=await S.putManagedPhaseRules(b,"http_request_cache_settings",wt);if(re.success)Tt.cacheRules=wt.length;else Tt.warnings.push(`cache rules could not be written: ${re.message}`)}if(tt){let re=Ma(ht,tt.header,tt.value);if(re.length>0){let Rt=await S.putManagedPhaseRules(b,"http_request_late_transform",re);if(Rt.success)Tt.originGuard=!0;else Tt.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(et){if(Tt.purged=await S.purgeCache(b,{hosts:ht}),!Tt.purged)Tt.warnings.push("edge cache purge failed — new content may take until TTL expiry to appear.")}return Tt}var su=(l)=>process.env[l];function cs(l,S){let b=l.replace(/\.$/,"").toLowerCase();if(S){let P=S.replace(/\.$/,"").toLowerCase();if(b===P||b.endsWith(`.${P}`))return P}return b.split(".").slice(-2).join(".")}function cu(l,S={}){let b=S.env??su,P=l.infrastructure?.compute?.proxy?.cdn,v=[];if(!P||P.provider!=="cloudflare")return{plan:null,errors:v};if(P.originDomain)v.push(`compute.proxy.cdn.originDomain (${P.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 Xe=b("CLOUDFLARE_API_TOKEN");if(!Xe)return v.push("CLOUDFLARE_API_TOKEN is not set — the Cloudflare CDN cannot be reconciled."),{plan:null,errors:v};let he=l.sites??{},fe=P.frontedHosts?.length?[...new Set(P.frontedHosts.map((vt)=>vt.toLowerCase()))]:yn(he,{autoWww:l.infrastructure?.compute?.proxy?.autoWww!==!1});if(fe.length===0)return v.push("No hostnames to front — set compute.proxy.cdn.frontedHosts, or give a site a domain."),{plan:null,errors:v};let Ye=l.infrastructure?.dns?.domain,tt=new Set(fe.map((vt)=>cs(vt,Ye)));if(tt.size>1)return v.push(`Fronted hosts span more than one zone (${[...tt].join(", ")}). A Cloudflare zone is configured as a unit, so run one CDN config per zone.`),{plan:null,errors:v};let et=P.cloudflare??{},nr=P.secret?{header:P.secretHeader??"X-Origin-Verify",value:P.secret}:void 0;return{plan:{zone:[...tt][0],hosts:fe,apiToken:Xe,zoneId:et.zoneId??b("CLOUDFLARE_ZONE_ID"),accountId:et.accountId??b("CLOUDFLARE_ACCOUNT_ID"),proxied:et.proxied!==!1,settings:et.settings??_i,cache:et.cache,originGuard:nr,purge:et.purgeOnDeploy!==!1,skipOriginProbe:et.skipOriginProbe===!0},errors:v}}var lu=26214400;var du=new Set(["/_headers","/_redirects","/_routes.json","/_worker.js"]);class ds{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,b){return Jo(l,`/accounts/${this.accountId}${S}`,`Bearer ${this.apiToken}`,b)}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 b=await this.getProject(l);if(b)return b;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 b=await Jo("POST","/pages/assets/check-missing",`Bearer ${l}`,{hashes:S});return new Set(b)}async upsertHashes(l,S){await Jo("POST","/pages/assets/upsert-hashes",`Bearer ${l}`,{hashes:S})}async uploadBatch(l,S){let b=S.map((P)=>({key:P.hash,value:P.base64,metadata:{contentType:pu(P.extension)},base64:!0}));await Jo("POST","/pages/assets/upload",`Bearer ${l}`,b)}async createDeployment(l,S,b){let P={};for(let Xe of S)P[Xe.path]=Xe.hash;let v=new FormData;if(v.append("manifest",JSON.stringify(P)),b)v.append("branch",b);return this.request("POST",`/pages/projects/${l}/deployments`,v)}async deployDirectory(l){let S=await tc(l.directory);if(S.length===0)throw Error(`No files to deploy in ${l.directory}`);let b=await this.uploadToken(l.project),P=await this.missingHashes(b,S.map((Ye)=>Ye.hash)),v=S.filter((Ye)=>P.has(Ye.hash)),Xe=[];for(let Ye=0;Ye<v.length;Ye+=100)Xe.push(v.slice(Ye,Ye+100));let he=0;for(let Ye=0;Ye<Xe.length;Ye+=4){let tt=Xe.slice(Ye,Ye+4);await Promise.all(tt.map((et)=>this.uploadBatch(b,et))),he+=tt.reduce((et,nr)=>et+nr.length,0),l.onProgress?.(he,v.length)}return await this.upsertHashes(b,S.map((Ye)=>Ye.hash)),{deployment:await this.createDeployment(l.project,S,l.branch),total:S.length,uploaded:v.length,uploadedBytes:v.reduce((Ye,tt)=>Ye+tt.size,0)}}async listCustomDomains(l){return(await this.request("GET",`/pages/projects/${l}/domains`)).map((b)=>b.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 uu(l,S){return{type:"CNAME",name:l,value:S.endsWith(".pages.dev")?S:`${S}.pages.dev`,ttl:1,proxied:!0}}async function ec(l,S){let{blake3:b}=await import("./chunk-e7ds04wb.js").then((m)=>Zm(m.default,1));return(await b(l+S)).slice(0,32)}async function tc(l){let{readdir:S}=await import("node:fs/promises"),{join:b,relative:P,sep:v}=await import("node:path"),Xe=[];async function he(fe){let Ye=await S(fe,{withFileTypes:!0});for(let tt of Ye){let et=b(fe,tt.name);if(tt.isDirectory()){await he(et);continue}if(!tt.isFile())continue;let nr=`/${P(l,et).split(v).join("/")}`;if(du.has(nr))continue;let vt=await Bun.file(et).bytes();if(vt.byteLength>26214400)throw Error(`${nr} is ${vt.byteLength} bytes, over the Cloudflare Pages limit of 26214400`);let or=Buffer.from(vt).toString("base64"),Tt=tt.name.lastIndexOf("."),ht=Tt>0?tt.name.slice(Tt+1):"";Xe.push({path:nr,hash:await ec(or,ht),base64:or,extension:ht,size:vt.byteLength})}}return await he(l),Xe.sort((fe,Ye)=>fe.path.localeCompare(Ye.path)),Xe}function pu(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 Jo(l,S,b,P){let v={Authorization:b},Xe;if(P instanceof FormData)Xe=P;else if(P!==void 0)v["Content-Type"]="application/json",Xe=JSON.stringify(P);let he=await fetch(`https://api.cloudflare.com/client/v4${S}`,{method:l,headers:v,body:Xe}),fe=await he.text(),Ye;try{Ye=JSON.parse(fe)}catch{throw Error(`Cloudflare Pages API returned ${he.status} with a non-JSON body: ${fe.slice(0,200)}`)}if(!Ye.success){let tt=(Ye.errors??[]).map((et)=>`${et.code}: ${et.message}`).join(", ");throw Error(`Cloudflare Pages API error (${he.status}): ${tt||fe.slice(0,200)}`)}return Ye.result}export{tg as ABTestManager,ie as ACMClient,rr as ACMDnsValidator,Xa as ACME_DIRECTORIES,be as AI,Od as API_IDEMPOTENCY_TTL_MS,xd as API_TOKEN_DEFAULT_TTL_MS,_d as API_TOKEN_MAX_TTL_MS,wi as API_VERSION,oe as AUTHORIZATION_CAPABILITIES,Pd as AUTH_ACTION_TOKEN_TTL_MS,Nd as AUTH_MFA_CHALLENGE_TTL_MS,kd as AUTH_OIDC_TRANSACTION_TTL_MS,He as AUTH_SESSION_ABSOLUTE_TTL_MS,Dd as AUTH_SESSION_IDLE_TTL_MS,wf as AWSAPIError,n as AWSClient,f as AWSCloudFormationClient,y as AWSCloudFrontClient,Xp as AWSConfigManager,xy as AWS_PSEUDO_PARAMETERS,Ee as AWS_REGIONS,tu as AcmeClient,wr as AlertEvaluator,ni as AlertStore,Ns as AnomalyConfigStore,id as ApiGateway,i as ApiServiceError,va as ApplicationAutoScalingClient,qs as Arn,D as AssetHasher,U as Auth,Ci as AuthenticationStore,ci as AutomationApiService,bi as AutomationIdentityStore,Bo as AwsAuroraDataAdapter,$o as AwsAuroraTransport,ta as AwsDatabaseBackupSource,ar as AwsDriver,xo as AwsElastiCacheDataAdapter,Mo as AwsElastiCacheTransport,Zg as AwsIamCapabilityScanner,oa as AwsInfrastructureBackupSource,ko as AwsRdsDataAdapter,Lo as AwsRdsTransport,pm as AwsRegionalDriver,ca as AwsSecretsManagerConfigurationBackend,Ap as AwsSpendTransport,da as AwsSsmConfigurationBackend,$i as BackupCoordinator,Wp as BackupManager,Zo as BackupStore,xg as BatchProcessingManager,on as BedrockClient,sn as BedrockRuntimeClient,Hd as BitbucketSourceAdapter,eg as BlueGreenManager,Rg as BounceComplaintHandler,hg as BuildOptimizationManager,ll as BunDockerRuntime,Ll as BunDockerVolumeRuntime,Ol as BunFilesystemArchiveRuntime,Ce as CDN,Xs as CHAIN_HEADER,Ji as CLOUDFLARE_MANAGED_RULE_PREFIX,DS as COMMON_CROSS_ACCOUNT_ROLES,Oe as CONTROL_PLANE_SCHEMA_VERSION,Hs as Cache,zs as CanaryManager,pg as CertificateManager,Oh as CloudBlockVolumeDriver,ls as CloudDriverFactory,Qe as CloudError,Tp as CloudFormationBuilder,f as CloudFormationClient,y as CloudFrontClient,Yp as CloudTrailManager,ue as CloudWatchLogsClient,ds as CloudflarePagesProvider,bt as CloudflareProvider,Uf as CommandHistory,H as Communication,Cr as ComposeApplicationService,_t as ComposeApplicationStore,At as ComprehendClient,o as Compute,yp as ComputeSpendTransport,js as ConfigurationError,ua as ConfigurationService,aa as ConfigurationStore,rn as ConnectClient,Oo as ContainerDataAdapter,fg as ContainerRegistryManager,sa as ControlPlaneBackupSource,Wo as ControlPlaneCleanupDriver,Jn as ControlPlaneStore,Rs as CounterTracker,Ht as CredentialError,Gp as CrossRegionReferenceManager,uf as DASHBOARD_ENTRY,pf as DASHBOARD_PORT_BASE,gf as DASHBOARD_PORT_SPAN,lf as DASHBOARD_STATE_DIR,io as DEFAULT_ATTACK_MODE_HOURS,Vc as DEFAULT_DDOS_THRESHOLDS,wc as DEFAULT_METER_MAPPINGS,vc as DEFAULT_PRICE_BOOK,hi as DEFAULT_RECURSION_LIMITS,q as DEFAULT_SERVICE_LIMITS,bp as DEFAULT_STATE_DIR,Qa as DEFAULT_STATIC_ASSET_EXTENSIONS,Kh as DEFAULT_TELEMETRY_POLICY,tp as DEFAULT_THRESHOLDS,Nh as DEPLOYMENT_QUEUE_KINDS,Js as DEPTH_HEADER,vr as DETECTABLE_SIGNALS,sl as DIAGNOSTIC_PRESETS,Bg as DLQMonitoringManager,L as DNS,Tg as DNSSECManager,Ni as DataServiceLifecycle,No as DataServiceStore,Ft as Database,dg as DatabaseUserManager,Y as DebugLogger,of as DependencyGraph,Q as Deployment,Tf as DeploymentError,Jp as DisasterRecoveryManager,gn as DnsProviderFactory,jt as DockerDataTransport,vo as DockerDiscoveryAdapter,Sr as DockerNamedVolumeDriver,ia as DockerVolumeBackupSource,c as DurableOperationQueue,Ss as DurableQueueWorker,De as DynamoDBClient,gr as EC2Client,Pe as ECRClient,ze as ECSClient,tr as EFSClient,Sa as ELBv2Client,$h as ENFORCEMENT_ACTIONS,ti as ENFORCEMENT_DESCRIPTIONS,R as ENFORCEMENT_SEVERITY,Pu as ENVIRONMENT_LABEL,nl as EcsRuntimeAdapter,no as EdgeRateLimiter,We as ElastiCacheClient,m as Email,Gf as EmailAdvanced,Dg as EmailAnalyticsManager,ln as EmailClient,qf as EmailHandlers,Ng as EmailTemplateManager,Fo as EncryptedDataSecretStore,Rf as ErrorCodes,Zt as EventBridgeClient,dm as EventBridgeJobAdapter,la as ExternalConfigurationBackend,kg as FIFOQueueManager,dp as FOCUS_VERSION,kp as FileCache,Fe as FileSystem,ra as FilesystemBackupSource,Qo as FleetService,Uo as FleetStore,e as Fn,Gd as GiteaSourceAdapter,Ud as GithubSourceAdapter,Qd as GitlabSourceAdapter,qp as GlobalResourceManager,Ct as GoDaddyProvider,Zp as GuardDutyManager,rt as HOST_SITES_DIR,Nf as HashCache,Qg as HealthCheckManager,$e as HealthCheckRunner,dr as HetznerClient,Ae as HetznerDriver,pe as IAMClient,ka as IPV6_EXCLUDED_HOST_LABELS,mg as ImageScanningManager,Dl as InfrastructureGenerator,gc as InvalidOperationTransitionError,at as JobLoader,lm as JobProviderReconciler,Po as JobService,Ro as JobStore,Yt as KendraClient,dA as LARAVEL_SERVERLESS_BUILD_STEPS,C as LambdaClient,Sg as LambdaConcurrencyManager,Eg as LambdaDLQManager,Cg as LambdaDestinationsManager,yg as LambdaLayersManager,il as LambdaRuntimeAdapter,bg as LambdaVPCManager,Ig as LambdaVersionsManager,Xr as LocalEncryptedConfigurationBackend,na as LogicalDatabaseBackupSource,sg as LogsManager,Wf as MANAGED_NODE_VERSIONS,rc as MANAGEMENT_DASHBOARD_SITE,wp as MANAGEMENT_DASHBOARD_SITE_PREFIX,Ii as MAX_CONTROL_HOURS,mc as MAX_CONTROL_PLANE_ERROR_BYTES,Ju as MAX_CONTROL_PLANE_JSON_BYTES,vs as METERS,Lh as METER_KEYS,Mh as MICRO_CENTS,rp as MIN_PROJECTION_CONFIDENCE,Xl as MTA_STS_PORT,Ko as MaintenanceService,zo as MaintenanceStore,X as Messaging,ig as MetricsManager,og as MigrationManager,Lp as MockCloudFormation,Mp as MockDynamoDB,$p as MockS3,Gs as Monitoring,zp as MultiAccountManager,Hp as MultiRegionManager,_f as MultiStepProgress,A as Network,Hg as NetworkSecurityManager,ii as NotificationRouter,Ca as OpenSearchClient,nt as OptimisticConcurrencyError,Kp as OrganizationManager,lu as PAGES_MAX_FILE_BYTES,lA as PHP_DEFAULT_EXCLUDES,Jf as PHP_LAYER_EXTENSIONS,Du as PROJECT_LABEL,un as PROXIABLE_RECORD_TYPES,E as ParameterStore,cg as PerformanceManager,J as Permissions,ba as PersonalizeClient,Ue as Phone,Vf as PhoneAdvanced,af as PhoneHandlers,Go as PlacementService,Ho as PlacementStore,an as PollyClient,Ne as PorkbunProvider,Ur as PreDeployScanner,Fp as PreviewEnvironmentManager,Ir as PreviewEnvironmentService,Le as PreviewEnvironmentStore,Up as PreviewNotificationService,xf as ProgressBar,rg as ProgressiveDeploymentManager,so as ProtectionControlStore,by as Pseudo,M as Queue,Xn as QueueCancellationError,_g as QueueManagementManager,Sy as QueuePresets,Is as QueueTimeoutError,Sd as RATE_LIMIT_KEY_SEPARATOR,j as RDSClient,Hf as RECOMMENDED_ACCOUNT_STRUCTURES,RS as RECOMMENDED_SCPS,Wg as RELEASE_QUEUE_KINDS,$f as REPL,Ff as REPLCommandBuilder,Mf as REPLContext,Nu as ROLE_LABEL,kf as RateLimiter,Cy as RealtimePresets,lp as RecordingSpendTransport,Zs as RecursionGuard,ct as Redirects,Vp as RegionPairManager,Vo as RegionService,qo as RegionStore,Me as Registry,yt as RekognitionClient,dt as ReleaseService,ho as ReleaseStore,um as RemoteBuildService,ag as ReplicaManager,Gg as ResourceManagementManager,W as RetryableOperationError,h as Route53Client,Ia as Route53DomainsClient,ge as Route53Provider,wg as Route53ResolverManager,vg as Route53RoutingManager,de as RuntimeOperationService,wo as RuntimeStreamRegistry,ea as S3BackupDestinationAdapter,a as S3Client,G as S3Error,jd as SECRET_PATTERNS,ap as SENSITIVITY_THRESHOLDS,Je as SESClient,F as SMS,Ke as SNSClient,fp as SPEND_CYCLE_SECONDS,Fc as SPEND_GATE_SETTING,Yh as SPEND_LEASE_SETTING,te as SQSClient,ye as SSH_BOOTSTRAP_VERSION,wn as SSH_PREFLIGHT_SCRIPT,Ie as SSMClient,Ep as STATE_DIR_ENV_VAR,_i as STATIC_SITE_ZONE_SETTINGS,le as STSClient,cn as SchedulerClient,Ut as Search,Qr as SecretFindingScanner,ui as Secrets,ug as SecretsManager,V as SecretsManagerClient,lg as SecretsRotationManager,I as Security,Br as SecurityHubManager,Fr as SecurityPostureStore,lt as SecurityScannerRunner,gg as SecurityScanningManager,Pg as SenderReputationManager,cm as ServerCronJobAdapter,_o as ServerDataAdapter,Es as ServerPathVolumeDriver,Ag as ServiceMeshManager,nd as Sftp,Bs as SignalSource,jf as SmsAdvanced,St as SmsClient,cf as SmsHandlers,Ra as SmsVoiceClient,fo as SourceConnectionStore,qt as SourceProviderError,Uc as SpendCapError,Tr as SpendGate,mp as SpendLoopLease,$s as SpendNotificationRouter,hp as SpendRunner,Lt as SpendService,Zn as SpendStore,Of as Spinner,ur as SshDriver,qr as SshFleetDriver,jp as StackDependencyManager,By as StacksIntegration,Fg as StaticSiteManager,Se as Storage,Ug as StorageAdvancedManager,dn as SupportClient,xr as SyntheticsManager,ul as SystemFleetSshTransport,lr as SystemSshTransport,To as SystemdDiscoveryAdapter,Ys as TRACE_HEADER,Lf as TaskList,ot as TelemetryStore,td as TemplateBuilder,Bp as TemplateCache,It as TextractClient,nn as TranscribeClient,Xt as TranslateClient,hm as TransportDisasterRecoveryDriver,mm as TransportPlatformMaintenanceDriver,ki as TransportRemoteBuildDriver,bo as TrivyImageScanner,mo as TsCloudApiError,Ld as TsCloudClient,Xh as URGENT_SPEND_EVENTS,np as USER_VISIBLE_ACTIONS,jo as UnavailableRegionalDriver,ne as UnifiedDnsValidator,fs as UnsupportedSchemaVersionError,Pp as ValidationError,er as VoiceClient,bs as VolumeService,xt as VolumeStore,df as Workflow,ng as XRayManager,rC as abTestManager,$d as activateImmutableRelease,jr as addSiteToCloudConfig,pt as ageSeconds,Dc as aggregateDeltas,zu as allocateSitePorts,Ny as analyzeStackDiff,ri as anomalyOptionsForSignal,oo as applyControlsToDdos,Td as applyControlsToRateLimits,Pr as applyMitigationFactor,uh as applyPlan,ts as applyZoneMigration,dd as artifactKey,Ei as assertReleaseStrategy,zh as assertSpendAllows,fh as attachConflicts,Ah as attachIsViable,hh as attachPreconditions,Xd as attachProvenanceToRelease,Eo as attachSbomToRelease,Wd as attachVulnerabilitySummary,zg as authEncryptionKeyFile,w as authorizeOrganization,om as authorizeRuntimePath,nS as autocomplete,JS as awsConfigManager,xl as backupCredentialStatus,KS as backupManager,bI as batch,OC as batchProcessingManager,po as beginOidcAuthorization,eC as blueGreenManager,PC as bounceComplaintHandler,it as budgetWindow,fa as buildAndPushServerlessImage,MC as buildBunRuntimeLayerZip,Eh as buildCertificatePackScript,Sh as buildCertificateStateScript,vh as buildCertificateUnpackScript,sd as buildCloudFormationTemplate,za as buildCloudInitFirstBoot,yc as buildComposeLogsCommand,dy as buildComposeRuntimeCommand,ly as buildComposeScaleCommand,Ic as buildComposeShellCommand,qu as buildDrainSourceScript,rh as buildDrainedSiteScanScript,Kt as buildFunctionEnv,Gu as buildHealthGateScript,Qn as buildHostCleanupScript,Kn as buildHostSitePortsScript,ed as buildMailEnv,ps as buildManagementDashboardArtifact,Au as buildMediaCdnPlan,Jl as buildMtaStsPolicy,$m as buildMtaStsServer,$C as buildNodeRuntimeLayerZip,AC as buildOptimizationManager,Ma as buildOriginGuardRule,Lu as buildPauseWorkersScript,HC as buildPhpRuntimeLayerZip,Uu as buildRestoreScript,gh as buildSetHostnameScript,$n as buildSiteDeployScript,Fu as buildSnapshotScript,Vu as buildSourceStateScript,Sn as buildSshArgs,vn as buildSshBootstrapScript,_a as buildStaticSiteCacheRules,Mn as buildStaticSiteDeployScript,Qu as buildTargetStateScript,$u as buildWorkersStateScript,Zd as bytes,tC as canaryManager,Vr as canonicalJson,ut as capabilities,zt as capacity,kI as categorizeChanges,mC as certificateManager,bh as certificatesMatch,lI as checkIAMPermissions,rA as checkInvocation,pI as checkServiceQuotas,Bf as chunk,wm as cleanupDns01Challenge,fy as clearSigningKeyCache,yo as cloneSourceBinding,_I as cloudConfigSchema,yu as cloudDrivers,XS as cloudTrailManager,tc as collectAssets,to as collectPhpAppEntries,Kl as collectServerDnsDomains,Xu as completeComposeVolumeDeletion,go as completeOidcAuthorization,Xy as composePresets,ys as composeProjectName,ud as composeServerlessAppTemplate,ef as compositeSpendTransport,ft as compressBackup,pA as config,cl as connectionGuidance,yC as containerRegistryManager,Dh as controlPlaneDatabaseFile,uc as controlPlaneMigrations,Fy as createApiBackendPreset,Co as createApiV1Handler,CA as createAsgBuildDriver,_l as createBackupQueueHandlers,aA as createCliHandler,k as createCloudDriver,Za as createCloudFrontPolicy,sI as createCredentialProvider,Wy as createDashboardSite,qy as createDataPipelinePreset,dl as createDataServiceQueueHandlers,Sc as createDeploymentQueueHandlers,T as createDnsProvider,SA as createEcsBuildDriver,Qc as createEnforcementHandlers,Np as createError,od as createExistingStaticFullStackPreset,pl as createFleetQueueHandlers,My as createFullStackAppPreset,is as createGoDaddyValidator,QC as createHandlers,sA as createHttpHandler,Qy as createJamstackPreset,al as createJobQueueHandlers,zy as createLaravelPreset,Vy as createMLApiPreset,Il as createMaintenanceQueueHandlers,hu as createMediaAccessToken,Hy as createMicroservicesPreset,UI as createMockAWS,Oy as createNodeJsServerPreset,Ly as createNodeJsServerlessPreset,Ki as createObjectStorageClient,ns as createPorkbunValidator,Yy as createPreset,rf as createPresignedUrl,uy as createPresignedUrlAsync,oA as createQueueHandler,Gy as createRealtimeAppPreset,ml as createRegionQueueHandlers,Jd as createReleaseProvenance,Fd as createReleaseQueueHandlers,yA as createRemoteBuildQueueHandlers,ss as createRoute53Validator,sm as createRuntimeAdapters,oI as createS3Client,IA as createServerBuildDriver,Ky as createServerlessLaravelPreset,$y as createServerlessNodePreset,zl as createSmsInfrastructure,qe as createSourceAdapter,_y as createStaticSitePreset,jy as createTraditionalWebAppPreset,Cc as createVolumeQueueHandlers,Uy as createWordPressPreset,mi as createZip,uS as crossRegionReferenceManager,Yr as dashboardActions,us as dashboardCredentialsFile,Gr as dataServiceCapabilities,uC as databaseUserManager,Rd as decodeBase32,Re as decompressBackup,Tm as decryptBackup,ao as defaultConfig,Op as defaultLocalConfig,bd as defaultRateLimitRules,ma as deleteStaticSite,ic as deployAllComputeSites,Xo as deployServerlessApp,Nl as deploySite,gs as deploySiteRelease,Qi as deployStaticSite,ha as deployStaticSiteFull,Zr as deployStaticSiteWithExternalDns,en as deployStaticSiteWithExternalDnsFull,Yc as deploymentCoexistenceError,mf as deriveManagementDashboardPort,vd as describePosture,am as desiredJobProviderState,op as detectAnomalies,vp as detectDeploymentTargets,Da as detectDnsProvider,Lc as detectLatestAnomaly,cI as detectMisconfigurations,Sp as detectServiceRegion,fc as diffCompose,DI as diffTemplates,Ao as discoverGitRefs,uo as discoverOidcProvider,el as discoverRuntimeInventory,_C as dlqMonitoringManager,Pa as dnsProviders,RC as dnssecManager,rm as dockerWorkloads,Bi as documentDigest,WS as drManager,Be as driverStatePath,tl as ecsWorkloads,Bt as effectiveCapabilities,NC as emailAnalyticsManager,BC as emailTemplateManager,Si as encodeBase32,vm as encryptBackup,Yd as ensureDefaultSecurityPolicies,xn as ensureFirewall,Hn as ensureManagementDashboard,_n as ensureServer,Bn as ensureSshKey,K as escapeSecLang,Nc as evaluateBudget,Dn as evaluatePreflight,Ls as evaluateTelemetryAlertRules,ol as eventBridgeScheduleInput,iA as eventToRequest,qh as ewma,hc as exportCompose,Zi as exportRoute53Zone,Dp as extendPreset,xC as fifoQueueManager,CI as findChangedFiles,Zu as findMapping,Yu as findPriceEntry,BS as formatAccountStructure,yh as formatAttachPlan,WI as formatBytes,Rr as formatCents,ky as formatDiff,ih as formatDrainedSiteRefusal,JI as formatDuration,sS as formatFlagSuggestions,cS as formatHistory,dS as formatHistoryStats,ch as formatInventory,YI as formatKeyValue,XI as formatList,lh as formatPlan,Nn as formatPreflightFindings,KI as formatProgressBar,Qf as formatRegion,ES as formatRegionList,Yg as formatScanResults,ZI as formatSuggestion,jI as formatTable,Er as formatTimeToExhaustion,zI as formatTree,If as fromEC2Metadata,Sf as fromECSMetadata,Af as fromEnvironment,yf as fromSharedCredentials,Cf as fromWebIdentity,gd as functionFingerprint,yn as gatewayHostnames,pd as generateAppImageDockerfile,jS as generateApprovalConfig,zf as generateBootstrap,GI as generateCleanupWorkflow,qI as generateCostReportWorkflow,NS as generateCrossAccountRoleCF,zd as generateCycloneDxSbom,GS as generateDeploymentConfig,MS as generateDeploymentPipeline,xS as generateDeploymentWorkflow,ga as generateExternalDnsStaticSiteTemplate,Im as generateHttpsServerCode,Kd as generateImageSbom,Pm as generateLetsEncryptUserData,t as generateLogicalId,HS as generateManualPipeline,$S as generateMatrixWorkflow,qS as generateMultiEnvConfig,FS as generateMultiEnvPipeline,_S as generateMultiEnvWorkflow,OS as generatePRPreviewWorkflow,zS as generateParallelConfig,cA as generatePhpFpmConfig,Yf as generatePhpLayerDockerfile,US as generatePreviewPipeline,HI as generatePreviewWorkflow,r as generateResourceName,VS as generateScheduledConfig,QS as generateScheduledPipeline,LS as generateScheduledWorkflow,Ui as generateStaticSiteTemplate,N as generateUbuntuAppCloudInit,vf as getAccountId,hS as getAllRegions,SS as getClosestRegion,oS as getCommandUsage,Ph as getComposeTemplate,qg as getConfig,tS as getContextualHelp,Vs as getCredentials,BI as getDeploymentStrategy,xI as getDiffStats,PI as getDiffSummary,Df as getErrorDetails,cd as getLocalConfig,MI as getLocalCredentials,$I as getLocalEndpoint,FI as getLocalEnvVars,gI as getQuotaUsageSummary,PS as getRecommendedStructure,gi as getRegion,vS as getRegionStats,AS as getRegionsByCompliance,fS as getRegionsByLocation,yS as getRegionsByPricingTier,Pf as getRequiredPermissions,Ay as getSigningKeyCacheSize,jl as getSmsInfrastructureStatus,Ey as getTimestamp,ro as globMatches,ms as globToRegex,pS as globalResourceManager,ei as governingLimitCents,YS as guardDutyManager,Ms as handleSpendRequest,An as hasAutoWwwVariant,Qt as hasManagementDashboardSite,lc as hasProxyUpstream,fI as hashBuffer,yI as hashDirectory,xp as hashFile,II as hashManifest,_p as hashString,VC as healthCheckManager,mn as hostAcceptsIpv6,Fa as hostCondition,co as hotp,br as hourBucket,Gh as hourBucketsBetween,fC as imageScanningManager,Oi as infraEnvFromOutputs,hd as inspectInvocation,eA as installRecursionFetch,Gi as invalidateCache,$g as invocationContext,eS as isLikelyTypo,fn as isLocalDatabase,LI as isLocalDevelopment,Nr as isManagementDashboardSiteName,yy as isNodeCryptoAvailable,Oc as isOperationAllowed,Os as isQuietHours,qn as isSafePattern,Jc as isStateDirConfigured,Xc as isStatePath,Dr as isValidCidr,IS as isValidRegion,Yn as isValidTimeZone,Iy as isWebCryptoAvailable,Hr as jobProviderCapability,zi as keyMatchesFilters,bC as lambdaConcurrencyManager,TC as lambdaDLQManager,EC as lambdaDestinationsManager,SC as lambdaLayersManager,vC as lambdaVPCManager,CC as lambdaVersionsManager,rl as lambdaWorkloads,yd as laravelServerlessEnvDefaults,yr as listComposeTemplates,Ti as listSourceReferences,wd as loadCloudConfig,$t as loadTelemetryPolicy,oC as logsManager,$c as lookbackHoursForSignal,sf as mailEnabled,Zc as mailFirewallPorts,gm as maintenanceWindowOpen,nf as makeAWSRequest,gy as makeAWSRequestAsync,py as makeAWSRequestOnce,Rp as managementDashboardSiteName,hl as manifestDigest,Or as matchTotpCounter,Su as mediaObjectHeaders,Ps as median,ip as medianAbsoluteDeviation,kc as mergeDecisions,kr as mergeInfrastructure,Qh as mergePriceBooks,Rc as meterTelemetry,sC as metricsManager,Hl as migrateObjectStorage,cC as migrationManager,TS as multiAccountManager,lS as multiRegionManager,Om as needsRenewal,jC as networkSecurityManager,gt as nextScheduleRuns,me as normalizePublicIpv6,ve as normalizeRuntimeStatus,Ve as normalizeScheduleExpression,Jg as normalizeSourceEvent,ke as normalizeSshPublicKey,up as normalizeTelemetryPolicy,zn as occupiedHostPorts,So as openApiDocument,xs as optionsForSignal,wS as organizationManager,Id as packagePhpApp,_r as packageServerlessApp,ec as pagesAssetHash,uu as pagesDnsRecord,ad as parallel,EI as parallelMap,vI as parallelWithRetry,Ch as parseCertificateState,md as parseChain,Ar as parseCompose,ay as parseComposeCatalog,tm as parseDockerInspect,$l as parseDotenv,nh as parseDrainedSites,Wn as parseHostSiteFragments,hy as parseJSONResponse,Rn as parsePreflightFacts,ju as parseSourceDrained,nm as parseSystemdRecords,Hu as parseTargetReady,dc as parseUpstreamPort,Mu as parseWorkersPaused,my as parseXMLResponse,oi as pathTemplate,ac as pendingSteps,Ds as percentOfLimit,lC as performanceManager,Og as phpLayerBuildStage,Xf as phpLayerPackages,fi as phpRuntimeLayerAssets,cy as planComposeTemplateUpgrade,Bc as planEnforcement,_u as planIsDestructive,Ip as planMitigation,ph as planServerRename,Th as planSiteMove,es as planZoneMigration,Et as policyTag,Pn as preflightFailed,QI as previewManager,VI as previewNotifications,mt as previewSchedule,Hh as previousBudgetWindow,Ts as priceUsage,Fh as priceUsageLines,oh as probeHostRoutes,Wa as probeOriginTls,RI as processInChunks,qd as processSourceWebhook,Di as productionChangeReview,nC as progressiveDeploymentManager,Pc as projectSpend,fd as propagationHeaders,Aa as providerEndpoint,fl as publicKeyFingerprint,pn as qualifyName,LC as queueManagementManager,SI as quickHash,Cd as rateLimitHeaders,yi as rateLimitKey,xe as readDriverState,ah as reconcile,Wl as reconcileAddressRecords,au as reconcileCloudflareCdn,Yi as reconcileDeclaredRecords,AA as reconcileJobObservation,Mr as reconcileSourceWebhook,Ri as recordDashboardHostPosture,mA as recordPreDeploySecretScan,hA as recordSkippedSecretScan,Ad as recursionBlockedResponse,Te as redactRuntimeConfig,qc as redactTelemetryText,si as redactTelemetryValue,Kr as redeployServerlessApp,gS as regionPairManager,$r as releaseStrategyCapabilities,Kg as releaseTrafficPlan,Gn as reloadRpxGateway,ji as remapKey,zr as removeSiteFromCloudConfig,Vd as removeSourceWebhook,Na as removeStaleServerAddressRecords,Ac as renderComposeTemplate,di as renderDdosInstallScript,Kc as renderNftablesRuleset,Pi as renderServerCron,zc as renderSysctlFile,oc as renderWafConfig,Vn as renderWafInstallScript,sc as renewRpxCertificates,dC as replicaManager,tf as requestHash,NI as requiresReplacement,FC as resetRecursionRuntime,UC as resolveApp,p as resolveAppDatabase,mh as resolveAttachTarget,Ge as resolveAuthEncryptionKey,ae as resolveCloudProvider,cu as resolveCloudflareCdnPlan,bf as resolveCredentials,Fi as resolveDashboardAction,nc as resolveDashboardAuth,hf as resolveDashboardDomain,ff as resolveDashboardDomains,Xi as resolveDeclaredRecords,Py as resolveDeployBucketName,O as resolveDeploymentMode,Ln as resolveExecStart,Ua as resolveHetznerApiToken,li as resolveMailService,Jy as resolveManagementDashboardSite,pi as resolveManagementDashboardSites,ya as resolveObjectStorage,dh as resolvePlan,g as resolveProjectStackName,fr as resolveProxyUpstreams,ld as resolveQueueNames,kh as resolveQueuedDeploymentCommand,Gt as resolveQueues,Zf as resolveRecursionConfig,Ef as resolveRegion,ee as resolveRuntimeInventory,Mt as resolveServerlessAppStackName,rd as resolveServerlessArtifactBucketName,Qs as resolveServerlessAssetBucketName,Ws as resolveServerlessRuntime,Ry as resolveSiteBucketName,hs as resolveSiteDeployTarget,u as resolveSiteKind,wy as resolveSiteResourceName,Ty as resolveSiteStackName,Tn as resolveSshSettings,d as resolveStatePath,Dy as resolveStorageBucketName,Pt as resolveUiSource,cs as resolveZoneApex,zC as resourceManagementManager,Mg as responseToResult,sp as robustZScore,kt as roleCapabilities,Md as rollbackImmutableRelease,Wr as rollbackServerlessApp,Uh as roundCents,DC as route53ResolverManager,wC as route53RoutingManager,cp as routeMatches,ku as routesFromFragments,Ai as ruleMatches,Kf as runBuildHooks,xc as runEnforcement,eo as runPhpBuildHooks,je as runRemoteCommand,ce as runtimeId,Mi as sanitizeCloudConfig,s as sanitizeControlPlaneValue,vy as sanitizeName,Bd as sanitizeOidcReturnPath,Hc as saveTelemetryPolicy,Xg as scanForSecrets,pc as scopeContains,st as scopeKey,La as scpUpload,rS as searchCommands,As as searchControlPlane,gC as secretsManager,pC as secretsRotationManager,fA as secureContainerRelease,ZS as securityHubManager,hC as securityScanningManager,Z as securityScope,Lr as sendAuthenticationEmail,kC as senderReputationManager,TI as sequence,Ml as serializeDotenv,On as serverPublicIpv4,IC as serviceMeshManager,wl as setAttachToInCloudConfig,Wt as setMaintenance,xi as setSitePropertyInCloudConfig,Wc as setStateDir,Dm as setupDns01Challenge,wa as setupSmsInfrastructure,Ks as sha256,tA as sharedRecursionGuard,Lg as sharedRuntimeLoop,Wu as shipsARelease,gu as signCloudFrontCookies,fu as signCloudFrontUrl,x as signRequest,Cp as signRequestAsync,ks as signalDefinition,B as siteInstallBase,jn as siteMoveArchivePath,Ih as siteMoveCertArchivePath,cc as siteUnitGlob,gp as spendNotificationText,Fs as spendOpenApiPaths,cr as sshExec,se as sshExecOrThrow,mS as stackDependencyManager,pa as startLocalDashboardServer,Zh as startSpendLoop,Us as stateDir,_ as statePath,GC as staticSiteManager,qC as storageAdvancedManager,Vh as streamFocusJsonl,_c as strongestActiveAction,Qp as suggestCommand,iS as suggestFlags,uI as suggestIAMPolicy,mI as suggestQuotaIncrease,bS as suggestRegionPairs,CS as suggestRegions,vi as syncSourceRepositories,bc as synchronizeComposeVolumes,Fl as synchronizeConfiguredConfiguration,Do as synchronizeConfiguredJobs,aC as syntheticsManager,jc as sysctlHardening,im as systemdWorkloads,Jh as telemetryBucketLabel,ai as telemetryCursor,Gc as telemetryEstimatedMonthlyCost,Wh as telemetryPercentile,pp as telemetryPolicyKey,hI as templateCache,Bu as tenantsOf,Io as testSourceConnection,Ec as tieredMicroCents,Va as toCloudflareZoneSettings,_s as toFocusJsonl,Mc as toFocusRecords,sh as toInventoryServer,Vg as totp,lo as totpUri,xu as unaccountedSites,em as unsupportedCapabilities,Bh as unsupportedVolumeCapabilities,yl as updateCompatibility,Sl as updateSiteInCloudConfig,Hi as uploadStaticFiles,ep as usageDeltaKey,Ot as utcInstantOfLocal,kS as validateAccountStructure,OI as validateAgainstSchema,_h as validateAttachment,Em as validateBackupDestination,aS as validateCommand,aI as validateConfiguration,dI as validateCredentials,Ku as validateDeploymentConfig,xh as validateMountPath,Ul as validateResourceLimits,Ou as validateServerName,El as validateTemplate,Gl as validateTemplateSize,Ba as verifyAddressRecord,gA as verifyArtifactSignature,Cu as verifyMediaAccessToken,jg as verifyTotp,Al as verifyUpdateSignature,rs as verifyZoneParity,Cs as volumeCapabilities,Ru as wafEventTelemetry,$a as waitForCloudInit,Cn as waitForSsh,Vt as webhookEndpoint,nI as withCDN,rI as withCache,tI as withDatabase,nA as withInvocation,Zy as withMonitoring,iI as withQueue,eI as withSecurity,wI as withTimeout,z as wrapCloudInitUserData,Ze as writeDriverState,iC as xrayManager,gl as zeroCapacity,jh as zeroFill,Tc as zoneOffsetMs,ws as zonedParts};