@stacksjs/ts-cloud 0.12.13 → 0.12.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aws/index.js +1 -1
- package/dist/bin/chunk-4w80w3sm.js +1 -0
- package/dist/bin/{chunk-wvhqjr80.js → chunk-5tsxt28g.js} +2 -2
- package/dist/bin/{chunk-7h6h8yxm.js → chunk-77qpn2m8.js} +3 -3
- package/dist/bin/{chunk-13dhcjjb.js → chunk-7xvm2ygt.js} +2 -2
- package/dist/bin/{chunk-6xw0r4gn.js → chunk-8tbj9h2a.js} +35 -35
- package/dist/bin/chunk-971tfc6m.js +1 -0
- package/dist/bin/{chunk-6zk2n3wk.js → chunk-9e22a51n.js} +42 -42
- package/dist/bin/{chunk-z2ez8wn9.js → chunk-9k60q9qz.js} +3 -3
- package/dist/bin/{chunk-5gehfky4.js → chunk-a929za72.js} +2 -2
- package/dist/bin/{chunk-w7k5rvmw.js → chunk-dpw8x3sr.js} +1 -1
- package/dist/bin/{chunk-84tvv3x1.js → chunk-ejqhbj1h.js} +1 -1
- package/dist/bin/{chunk-gj5jkhfr.js → chunk-gd4w6bht.js} +3 -3
- package/dist/bin/chunk-h785hw6a.js +1 -0
- package/dist/bin/chunk-jyggrdh2.js +1 -0
- package/dist/bin/{chunk-1fj5gk6r.js → chunk-kc2e193t.js} +59 -59
- package/dist/bin/{chunk-bnv8yd9w.js → chunk-n7eq4t9a.js} +3 -3
- package/dist/bin/{chunk-d5qhwtkg.js → chunk-n8cwx54p.js} +5 -5
- package/dist/bin/{chunk-d7r6mhyv.js → chunk-ng0949x3.js} +2 -2
- package/dist/bin/{chunk-p9hd27k4.js → chunk-pcyywgx7.js} +1 -1
- package/dist/bin/{chunk-55kmbzr5.js → chunk-pt2bz3kr.js} +1 -1
- package/dist/bin/{chunk-96xtj5j6.js → chunk-q524s7cx.js} +1 -1
- package/dist/bin/{chunk-dh2qmxw9.js → chunk-q9gpw6wv.js} +1 -1
- package/dist/bin/{chunk-x5x9dzk7.js → chunk-r1vtnn8w.js} +2 -2
- package/dist/bin/{chunk-jh1593zx.js → chunk-r1w08y38.js} +1 -1
- package/dist/bin/{chunk-nnkhrm4n.js → chunk-raj6j2j5.js} +2 -2
- package/dist/bin/{chunk-2hpnd4g4.js → chunk-s1j941z1.js} +1 -1
- package/dist/bin/{chunk-ymbwekjm.js → chunk-sdwr2tnp.js} +1 -1
- package/dist/bin/{chunk-9jfjzycs.js → chunk-swete552.js} +10 -10
- package/dist/bin/{chunk-yn34zgr2.js → chunk-v78r5tx0.js} +1 -1
- package/dist/bin/chunk-v7f4c62s.js +1 -0
- package/dist/bin/{chunk-jcyrm5q0.js → chunk-vesvsvdy.js} +1 -1
- package/dist/bin/{chunk-yt8rgkqt.js → chunk-w5hzt11d.js} +2 -2
- package/dist/bin/{chunk-12e9v1dw.js → chunk-x42gb7pq.js} +1 -1
- package/dist/bin/{chunk-0vsxpmfj.js → chunk-yx1qgp1q.js} +2 -2
- package/dist/bin/{chunk-xgepx8yx.js → chunk-zzsdhhmb.js} +1 -1
- package/dist/bin/cli.js +152 -152
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-7ww65b66.js → chunk-2knc1zyy.js} +100 -100
- package/dist/{chunk-tnjae324.js → chunk-678rwkz8.js} +75 -75
- package/dist/{chunk-emg3shmb.js → chunk-6t9tjvpy.js} +2 -2
- package/dist/{chunk-g8fpsdyq.js → chunk-6znnde1s.js} +4 -4
- package/dist/{chunk-edqhhcg9.js → chunk-83p688yv.js} +3 -3
- package/dist/{chunk-zmyv76f0.js → chunk-88nxsyry.js} +6 -6
- package/dist/{chunk-sct6mdgc.js → chunk-a6k322xc.js} +25 -25
- package/dist/chunk-atny1wp9.js +1 -0
- package/dist/{chunk-thpce63q.js → chunk-cy6qh4ea.js} +2 -2
- package/dist/{chunk-wpqj98h8.js → chunk-g9mnmddy.js} +2 -2
- package/dist/{chunk-9c29rnk3.js → chunk-gd9g0v9w.js} +8 -8
- package/dist/chunk-hn2v0b0d.js +1 -0
- package/dist/{chunk-e0919h5g.js → chunk-hnkw6pde.js} +2 -2
- package/dist/{chunk-1kp3y2s7.js → chunk-hw3p6pth.js} +1 -1
- package/dist/{chunk-1n3ckctd.js → chunk-jvqcw0b4.js} +48 -48
- package/dist/{chunk-13d54txj.js → chunk-qzwack6w.js} +2 -2
- package/dist/{chunk-e7ds04wb.js → chunk-rbem58rx.js} +1 -1
- package/dist/chunk-v46b25w9.js +1 -0
- package/dist/{chunk-3qp10j0j.js → chunk-w495x89g.js} +3 -3
- package/dist/{chunk-ej4sm2tw.js → chunk-x07tpsv0.js} +5 -5
- package/dist/{chunk-3kapcdpn.js → chunk-yq3pdbz7.js} +1 -1
- package/dist/deploy/index.js +1 -1
- package/dist/dns/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +47 -47
- package/dist/operations/index.js +1 -1
- package/dist/protection/index.js +1 -1
- package/dist/spend/index.js +1 -1
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +6 -6
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +6 -6
- package/dist/ui/data/services.html +5 -5
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +6 -6
- package/dist/ui/infrastructure/topology.html +6 -6
- package/dist/ui/integrations.html +1 -1
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +6 -6
- package/dist/ui/operations/jobs.html +6 -6
- package/dist/ui/operations/maintenance.html +5 -5
- package/dist/ui/operations/observability.html +5 -5
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +5 -5
- package/dist/ui/operations/releases.html +6 -6
- package/dist/ui/operations/spend.html +6 -6
- package/dist/ui/operations/workloads.html +6 -6
- package/dist/ui/security.html +1 -1
- package/dist/ui/server/actions.html +5 -5
- package/dist/ui/server/activity.html +2 -2
- package/dist/ui/server/capacity.html +5 -5
- package/dist/ui/server/database.html +6 -6
- package/dist/ui/server/deployments.html +6 -6
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +6 -6
- package/dist/ui/server/fleet.html +6 -6
- package/dist/ui/server/logs.html +5 -5
- package/dist/ui/server/metrics.html +6 -6
- package/dist/ui/server/security.html +1 -1
- package/dist/ui/server/services.html +1 -1
- package/dist/ui/server/sites.html +6 -6
- package/dist/ui/server/ssh-keys.html +6 -6
- package/dist/ui/server/team.html +6 -6
- package/dist/ui/server/terminal.html +2 -2
- package/dist/ui/serverless/alarms.html +6 -6
- package/dist/ui/serverless/assets.html +2 -2
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +5 -5
- package/dist/ui/serverless/deployments.html +1 -1
- package/dist/ui/serverless/firewall.html +2 -2
- package/dist/ui/serverless/functions.html +5 -5
- package/dist/ui/serverless/logs.html +6 -6
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +6 -6
- package/dist/ui/serverless/secrets.html +6 -6
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +5 -5
- package/package.json +3 -3
- package/dist/bin/chunk-de88yqwy.js +0 -1
- package/dist/bin/chunk-p36ns96s.js +0 -1
- package/dist/bin/chunk-qz3za76g.js +0 -1
- package/dist/bin/chunk-rxwecjgc.js +0 -1
- package/dist/bin/chunk-xaafj6kf.js +0 -1
- package/dist/chunk-7by4rm7y.js +0 -1
- package/dist/chunk-n688m5fp.js +0 -1
- package/dist/chunk-wrnhbb13.js +0 -1
package/dist/index.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
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
|
-
${
|
|
1
|
+
import{Sp,x,Cp,rf,uy,nf,py,gy,my,hy,fy,Ay,yy,Iy,Sy,Cy,bp,Ep,Wc,Jc,Qs,_,d,Xc,vp,O,Yc,p,sf,ui,Zc,ed,ce,td,by,r,t,Ey,vy,g,Ty,wy,Ry,Dy,Py,Mt,rd,Hs,of,Ny,ky,Se,Fe,Ce,L,I,o,A,Ue,m,af,Qe,M,ct,By,cf,F,nd,be,Ft,Gs,X,id,Y,df,qs,U,Q,D,pi,E,Ut,dt,H,e,Vs,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,gi,Jy,Dp,Xy,Yy,kr,Zy,eI,tI,rI,nI,iI,Af,yf,If,Sf,Cf,js,sI,bf,Ef,vf,G,oI,He,zs,Ht,Tf,Pp,wf,Rf,Df,Np,Z,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,mi,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,Ks,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,hi,zf,Kf,Ws,dd,_r,Wf,Js,Gt,ld,ud,Jf,Xf,Og,Yf,pd,Lg,$C,MC,Xs,Ys,Zs,gd,fi,md,hd,eo,fd,Ad,$g,Zf,eA,tA,FC,rA,nA,UC,iA,Mg,sA,oA,aA,QC,cA,Ai,yd,dA,HC,lA,to,ro,Id,Fg,GC,Ug,qC,Qg,VC,Hg,jC,Gg,zC}from"./chunk-jvqcw0b4.js";import{co,qg,wd,pA,Ci,Rd,lo,Vg,jg,Or,uo,Dd,Ge,Pd,Nd,kd,bi,Lr,zg,qe,Bd,po,go,mo,xd,_d,Od,Ei,ho,Ld,$r,vi,fo,lt,Kg,$d,Md,Wg,Fd,Ao,qt,Ud,Qd,Hd,Gd,Ve,Jg,qd,Vt,yo,Io,So,Ti,wi,Mr,Vd,Ri,Co,bo,Fr,jd,Ur,Xg,Yg,ut,Qr,Eo,Zg,zd,Kd,vo,Wd,Jd,Xd,gA,ee,Yd,mA,hA,Di,Pi,fA,de,em,pt,ve,Te,gt,Zd,el,tl,rl,tm,rm,To,nm,im,wo,nl,il,sm,te,om,sl,le,Ro,je,mt,ht,Hr,Ni,ol,AA,Do,am,cm,dm,lm,Po,No,al,Gr,ko,cl,ki,dl,Bo,xo,_o,Oo,Lo,$o,Mo,Fo,ll,jt,Uo,ul,qr,pl,Qo,Ho,gl,zt,Go,qo,um,yA,Bi,IA,SA,CA,Vo,jo,ml,pm,zo,Vr,hl,xi,fl,Al,yl,Ko,gm,Wo,Il,mm,Jo,hm,jr,zr,Sl,_i,wl,Nl,Li,Kt,Yo,Kr,Wr,Wt,ze,Em,ea,vm,Tm,xl,ta,Mi,_l,ra,At,Re,Ol,na,ia,Ll,sa,oa,aa,ca,$l,Ml,Xr,da,la,ua,pa,Fl,Fi,Yr,Ui,ga}from"./chunk-2knc1zyy.js";import{B,fr,lc,fs,u,Ku,Wu}from"./chunk-g9mnmddy.js";import{nt,dc,Kn,Wn,Jn,zu}from"./chunk-83p688yv.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,zn,cc,Lu,$u,Mu,Fu,Uu,Qu,Hu,Gu,qu,Vu,ju,Ih,Sh,Ch,bh,Eh,vh,Th}from"./chunk-gd9g0v9w.js";import{Le,uc,ae,kt,pc,w,Bt,it,gc,As,Dh,Ju,mc,s,Xn,ys,Ar,hc,fc,yr,Ph,Ac,ay,cy,Is,dy,ly,yc,Ic,Yn,Ss,J,c,Cs,$e,Ir,Nh,kh,Sc,xt,Bh,bs,xh,_h,Es,Cc,Sr,vs,Oh,bc,Xu,_t,Cr,Lh,Ts,$h,R,Mh,Ec,Yu,ws,Fh,Uh,Qh,vc,Zn,Rs,Tc,Ot,st,Hh,br,Gh,wc,Zu,ep,Ds,Rc,Dc,ot,tp,ei,Pc,Ps,Er,rp,ti,Nc,kc,ri,np,Bc,xc,_c,Oc,Ns,ip,sp,qh,op,Lc,ni,ap,cp,ks,vr,Bs,xs,_s,$c,dp,Mc,Os,Vh,Lt,jh,Fc,Tr,Uc,zh,Qc,lp,ii,wr,Ls,si,Me,Kh,up,pp,$t,Hc,Gc,qc,oi,ai,ci,Wh,Jh,at,$s,Xh,Rr,gp,Ms,Yh,mp,hp,fp,Zh,Ap,yp,ef,i,tf,di,Fs,Us}from"./chunk-a6k322xc.js";import{n}from"./chunk-30h9rgfn.js";import{a}from"./chunk-yq3pdbz7.js";import{ue,zi,Ki,Hl,ya,Ia,Wi,Sa,Ke,V,We,re,C,pe,rn,Ca,De,ba,nn,sn,on,yt,It,St,an,Xt,Ea,Yt,Zt,Je,cn,Ta,Ct,er,dn,Ra,jl,zl,Da,tr}from"./chunk-88nxsyry.js";import{un,Ne,bt,Xi,Et,vt,pn,Yi,Zi,me,es,ts,rs,ns,ie,is,ss,os,T,Pa,gn,Na,se,rr}from"./chunk-6t9tjvpy.js";import{ge,Xe,ln}from"./chunk-cy6qh4ea.js";import{j}from"./chunk-zftpjxkr.js";import{Kl,ka,he,Ba,mn,Wl,xa,Jl,Xl,$m,fn,cs,An,yn,In,z,ke,N,ar,Cn,cr,oe,La,bn,$a,dr,Ua,Be,K,xe,_e,et,Ae,lr,ye,Tn,wn,Rn,Dn,Pn,Nn,kn,ur,k,us,yu,za,xn,_n,On,Ln,$n,Mn,Un,Hn,rc,ps,nc,Pt,Gn,gs,ms,ic,qn,sc}from"./chunk-678rwkz8.js";import{Sd,no,yi,Ii,io,Cd,bd,Si,so,oo,vd,Td,ao}from"./chunk-hw3p6pth.js";import{ma,Zr,en,Qi,Hi,Gi,qi,ha,fa}from"./chunk-x07tpsv0.js";import{Aa}from"./chunk-w495x89g.js";import{y}from"./chunk-6g81m01r.js";import{Pe}from"./chunk-r5emv4x8.js";import{h}from"./chunk-wjgnfg6q.js";import{W,Vn,hs,oc,jn,Ru}from"./chunk-6znnde1s.js";import{gr,Ie}from"./chunk-6nvn041c.js";import{f}from"./chunk-jb8em9ba.js";import{Zm,Oe}from"./chunk-hnkw6pde.js";import{Vc,Dr,jc,zc,Kc,li,Ip,Pr}from"./chunk-qzwack6w.js";import{createHmac as qa,createSign as Dl,timingSafeEqual as El}from"node:crypto";function Oi(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 Za(l){return Buffer.from(l).toString("base64").replaceAll("+","-").replaceAll("=","_").replaceAll("/","~")}function vl(l){return Buffer.from(l).toString("base64url")}function Ja(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 Ya(l,S){let b=Dl("RSA-SHA1");return b.update(l),b.end(),Za(b.sign(S))}function Xa(l){Ja(l.resource,!0);let b={DateLessThan:{"AWS:EpochTime":Oi(l.expiresAt)}};if(l.activeAt!==void 0)b.DateGreaterThan={"AWS:EpochTime":Oi(l.activeAt)};if(l.ipAddress)b.IpAddress={"AWS:SourceIp":l.ipAddress};return JSON.stringify({Statement:[{Resource:l.resource,Condition:b}]})}function Cu(l,S,b){Ja(l);let P=Oi(S),v=l.includes("?")?"&":"?",tt=Xa({resource:l,expiresAt:S}),we=Ya(tt,b.privateKey);return`${l}${v}Expires=${P}&Signature=${encodeURIComponent(we)}&Key-Pair-Id=${encodeURIComponent(b.keyPairId)}`}function Su(l,S){let b=Xa(l);return{"CloudFront-Key-Pair-Id":S.keyPairId,"CloudFront-Policy":Za(Buffer.from(b)),"CloudFront-Signature":Ya(b,S.privateKey)}}function Au(l){if(!l.resource||/[\r\n]/.test(l.resource))throw TypeError("Media resource is invalid");let S=vl(Buffer.from(JSON.stringify({resource:l.resource,expiresAt:Oi(l.expiresAt),...l.keyId?{keyId:l.keyId}:{},...l.audience?{audience:l.audience}:{}}))),b=qa("sha256",l.secret).update(S).digest("base64url");return`${S}.${b}`}function bu(l,S){let[b,P,v]=l.split(".");if(!b||!P||v)return null;let tt=qa("sha256",S.secret).update(b).digest(),we;try{we=Buffer.from(P,"base64url")}catch{return null}if(tt.length!==we.length||!El(tt,we))return null;try{let fe=JSON.parse(Buffer.from(b,"base64url").toString("utf8")),Ye=Oi(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 Tu(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 Iu(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 kl{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,tt){let we=this.serverEipLogicalIds.get("app"),fe=this.serverEipLogicalIds.get("appInstance");if(!we)return;let Ye=`EC2-${P}-${v}-api`,ft=this.mergedConfig.infrastructure?.servers?.app?.region||this.mergedConfig.project?.region||"us-east-1",rt=ft==="us-east-1"?".compute-1.amazonaws.com":`.${ft}.compute.amazonaws.com`,or={"Fn::Join":["",["ec2-",{"Fn::Join":["-",{"Fn::Split":[".",{Ref:we}]}]},rt]]},Jt=this.resolveApiOriginPort();if(l.push({Id:Ye,DomainName:or,CustomOriginConfig:{HTTPPort:Jt,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}),b.push(we),fe)b.push(fe);for(let pr of tt)S.push(this.createComputeCacheBehavior(pr,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 tt=b.get(v.domain)??[];tt.push({port:v.port,path:v.path}),b.set(v.domain,tt)}let P=[];for(let[v,tt]of b){let fe=[...tt].sort((Ye,ft)=>{let rt=!Ye.path||Ye.path==="/",or=!ft.path||ft.path==="/";if(rt&&!or)return 1;if(!rt&&or)return-1;return(ft.path?.length??0)-(Ye.path?.length??0)}).map((Ye)=>{let ft=!Ye.path||Ye.path==="/",rt=`reverse_proxy localhost:${Ye.port}`;return ft?` handle {
|
|
2
|
+
${rt}
|
|
3
3
|
}`:` handle ${Ye.path} {
|
|
4
|
-
${
|
|
4
|
+
${rt}
|
|
5
5
|
}`});P.push(`${v} {
|
|
6
6
|
${fe.join(`
|
|
7
7
|
`)}
|
|
8
8
|
}`)}return P.join(`
|
|
9
9
|
|
|
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
|
-
${
|
|
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:tt}=A.createVpc({slug:l,environment:S,cidr:P,enableDnsHostnames:!0,enableDnsSupport:!0});this.builder.addResource("VPC",v);let we=`${l}${S}IGW`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(we,{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:we}}});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:we}},DependsOn:fe});let ft=this.mergedConfig.environments[S]?.region||this.mergedConfig.project.region||"us-east-1",rt=["a","b"];for(let or=0;or<2;or++){let Jt=`PublicSubnet${or+1}`;this.builder.addResource(Jt,{Type:"AWS::EC2::Subnet",Properties:{VpcId:{Ref:"VPC"},CidrBlock:`10.0.${or}.0/24`,AvailabilityZone:`${ft}${rt[or]}`,MapPublicIpOnLaunch:!0,Tags:[{Key:"Name",Value:`${l}-${S}-public-${rt[or]}`},{Key:"Environment",Value:S}]}}),this.builder.addResource(`${Jt}RTAssoc`,{Type:"AWS::EC2::SubnetRouteTableAssociation",Properties:{SubnetId:{Ref:Jt},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,tt=this.mergedConfig.infrastructure?.dns,we;if(v?.enabled&&v.domains?.length)if(v.certificateArn);else{let rt=v.domains[0],or=v.domains.slice(1).map((Dt)=>{if(Dt.includes(".")&&Dt.endsWith(rt))return Dt.replace(`.${rt}`,"");return Dt}),{certificate:Jt,logicalId:pr}=I.createCertificate({domain:rt,subdomains:or,slug:l,environment:S,validationMethod:"DNS",hostedZoneId:tt?.hostedZoneId});we=pr,this.builder.addResource(pr,Jt)}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 ft=`${l}${S}ECSSecurityGroup`.replace(/[^a-zA-Z0-9]/g,"");for(let[rt,or]of Object.entries(b)){let Jt=or.port||3000;this.builder.addResource(ft,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`ECS tasks security group for ${l}-${S}`,VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:Jt,ToPort:Jt,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 pr=`${l}${S}TaskExecRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(pr,{Type:"AWS::IAM::Role",Properties:{RoleName:`${l}-${S}-ecs-exec-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"],Policies:[{PolicyName:"ECRPullPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["ecr:GetAuthorizationToken","ecr:BatchCheckLayerAvailability","ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","logs:CreateLogStream","logs:PutLogEvents"],Resource:"*"}]}}]}});let Dt=`${l}${S}TaskRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Dt,{Type:"AWS::IAM::Role",Properties:{RoleName:`${l}-${S}-ecs-task-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"TaskPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogStream","logs:PutLogEvents"],Resource:"*"},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:ListBucket"],Resource:"*"}]}}]}});let Rt=`${l}${S}${rt}LogGroup`.replace(/[^a-zA-Z0-9]/g,""),Ze=`/ecs/${l}-${S}-${rt}`;this.builder.addResource(Rt,{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:Ze,RetentionInDays:30}});let Nt=`${l}${S}${rt}TaskDef`.replace(/[^a-zA-Z0-9]/g,""),ne=String(or.cpu||512),Tt=String(or.memory||1024);this.builder.addResource(Nt,{Type:"AWS::ECS::TaskDefinition",Properties:{Family:`${l}-${S}-${rt}`,NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:ne,Memory:Tt,ExecutionRoleArn:{"Fn::GetAtt":[pr,"Arn"]},TaskRoleArn:{"Fn::GetAtt":[Dt,"Arn"]},ContainerDefinitions:[{Name:rt,Image:{"Fn::Sub":`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${l}:latest`},Essential:!0,PortMappings:[{ContainerPort:Jt,Protocol:"tcp"}],LogConfiguration:{LogDriver:"awslogs",Options:{"awslogs-group":Ze,"awslogs-region":{Ref:"AWS::Region"},"awslogs-stream-prefix":rt}},HealthCheck:{Command:["CMD-SHELL",`curl -f http://localhost:${Jt}${or.healthCheck||"/health"} || exit 1`],Interval:30,Timeout:5,Retries:3,StartPeriod:60}}],Tags:[{Key:"Name",Value:`${l}-${S}-${rt}`},{Key:"Environment",Value:S}]},DependsOn:[pr,Dt,Rt]});let wt=`${l}${S}ALB`.replace(/[^a-zA-Z0-9]/g,"");if(P?.enabled!==!1){this.builder.addResource(wt,{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 nr=`${l}${S}TargetGroup`.replace(/[^a-zA-Z0-9]/g,""),ir=P?.healthCheck?.path||or.healthCheck||"/health";this.builder.addResource(nr,{Type:"AWS::ElasticLoadBalancingV2::TargetGroup",Properties:{Name:`${l}-${S}-tg`,Port:Jt,Protocol:"HTTP",VpcId:{Ref:"VPC"},TargetType:"ip",HealthCheckPath:ir,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 sr=`${l}${S}HTTPListener`.replace(/[^a-zA-Z0-9]/g,"");if(v?.enabled&&v?.redirectHttp)this.builder.addResource(sr,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:wt},Port:80,Protocol:"HTTP",DefaultActions:[{Type:"redirect",RedirectConfig:{Protocol:"HTTPS",Port:"443",StatusCode:"HTTP_301"}}]}});else this.builder.addResource(sr,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:wt},Port:80,Protocol:"HTTP",DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:nr}}]}});if(v?.enabled){let hn=v.certificateArn||(we?{Ref:we}:void 0);if(hn){let Sn=`${l}${S}HTTPSListener`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Sn,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:wt},Port:443,Protocol:"HTTPS",Certificates:[{CertificateArn:hn}],DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:nr}}],SslPolicy:"ELBSecurityPolicy-TLS13-1-2-2021-06"}})}}let hr=`${l}${S}${rt}Service`.replace(/[^a-zA-Z0-9]/g,""),Jr=or.desiredCount||1;this.builder.addResource(hr,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${l}-${S}-${rt}`,Cluster:{Ref:fe},TaskDefinition:{Ref:Nt},DesiredCount:Jr,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:ft}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},LoadBalancers:[{ContainerName:rt,ContainerPort:Jt,TargetGroupArn:{Ref:nr}}],HealthCheckGracePeriodSeconds:120,Tags:[{Key:"Name",Value:`${l}-${S}-${rt}`},{Key:"Environment",Value:S}]},DependsOn:[Nt,sr,nr]});let mr=or.autoScaling;if(mr){let hn=`${l}${S}${rt}ScalableTarget`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(hn,{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{MaxCapacity:mr.max||10,MinCapacity:mr.min||1,ResourceId:{"Fn::Sub":`service/\${${fe}}/${l}-${S}-${rt}`},ScalableDimension:"ecs:service:DesiredCount",ServiceNamespace:"ecs",RoleARN:{"Fn::Sub":"arn:aws:iam::${AWS::AccountId}:role/aws-service-role/ecs.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_ECSService"}},DependsOn:hr}),mr.targetCpuUtilization)this.builder.addResource(`${l}${S}${rt}CPUScaling`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${l}-${S}-${rt}-cpu-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:hn},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},TargetValue:mr.targetCpuUtilization,ScaleInCooldown:300,ScaleOutCooldown:60}}});if(mr.targetMemoryUtilization)this.builder.addResource(`${l}${S}${rt}MemoryScaling`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${l}-${S}-${rt}-memory-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:hn},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageMemoryUtilization"},TargetValue:mr.targetMemoryUtilization,ScaleInCooldown:300,ScaleOutCooldown:60}}})}if(tt?.domain&&tt?.hostedZoneId)this.builder.addResource(`${l}${S}ApiDnsRecord`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:tt.hostedZoneId,Name:`api.${tt.domain}`,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":[wt,"DNSName"]},HostedZoneId:{"Fn::GetAtt":[wt,"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}-${rt}`,Export:{Name:{"Fn::Sub":"${AWS::StackName}-ecs-service-name"}}}),this.builder.addOutput("LoadBalancerDNS",{Description:"Application Load Balancer DNS Name",Value:{"Fn::GetAtt":[wt,"DNSName"]},Export:{Name:{"Fn::Sub":"${AWS::StackName}-alb-dns"}}})}else{let nr=`${l}${S}${rt}Service`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(nr,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${l}-${S}-${rt}`,Cluster:{Ref:fe},TaskDefinition:{Ref:Nt},DesiredCount:or.desiredCount||1,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:ft}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},Tags:[{Key:"Name",Value:`${l}-${S}-${rt}`},{Key:"Environment",Value:S}]},DependsOn:[Nt]})}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:tt}=X.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(tt,v);let{lambdaFunction:we,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:tt,timeout:P.timeout,memorySize:P.memorySize});this.builder.addResource(fe,we)}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((we)=>!we.privateNetwork||we.privateNetwork==="create"))this.generateNetworkInfrastructure(l,S);for(let[we,fe]of Object.entries(b)){let Ye=fe.instanceType||fe.size||P?.size,rt=(Ye?o.InstanceSize.specs[Ye]:void 0)?.instanceType||Ye||"t3.micro",or=fe.type||"app",Jt=fe.userData||fe.startupScript;if(!Jt)Jt=o.UserData.generateAppServerScript({runtime:"bun",runtimeVersion:fe.bunVersion||"latest",webServer:"none",domain:fe.domain,enableSsl:!!v?.enabled,sslEmail:v?.letsEncrypt?.email,installRedis:or==="cache",installDatabaseClients:!!fe.database});let pr=fe.privateNetwork&&fe.privateNetwork!=="create"?fe.privateNetwork:{Ref:"VPC"},Dt=fe.subnet||{Ref:"PublicSubnet1"},Ze=!!this.mergedConfig.infrastructure?.email?.server?.enabled,Nt=[22,80,443,this.resolveApiOriginPort()];if(Ze)Nt.push(25,465,587,143,993);let ne=o.createServerModeStack({slug:`${l}-${we}`,environment:S,vpcId:pr,subnetId:Dt,instanceType:rt,keyName:fe.keyName||`${l}-${S}`,domain:fe.domain,userData:Jt,volumeSize:fe.diskSize||20,imageId:fe.image,allowedPorts:Nt});for(let[Tt,wt]of Object.entries(ne.resources))this.builder.addResource(Tt,wt);this.serverEipLogicalIds.set(we,ne.outputs.eipLogicalId),this.serverEipLogicalIds.set(`${we}Instance`,ne.outputs.instanceLogicalId),this.builder.addOutput(`${we}InstanceId`,{Value:{Ref:ne.outputs.instanceLogicalId},Description:`Instance ID for ${we} server`}),this.builder.addOutput(`${we}PublicIp`,{Value:{Ref:ne.outputs.eipLogicalId},Description:`Public IP for ${we} server`})}}generateComputeApp(l,S){let b=this.mergedConfig.infrastructure?.compute;if(!b)return;let P=this.mergedConfig.sites||{},v=Object.entries(P),we=this.mergedConfig.infrastructure?.dns?.domain,fe=this.mergedConfig.infrastructure?.database,Ye=b.size,rt=(Ye?o.InstanceSize.specs[Ye]:void 0)?.instanceType||Ye||"t3.micro";if(!this.builder.hasResource("VPC"))this.generateNetworkInfrastructure(l,S);let or=this.buildCaddyfile(v),Jt=o.UserData.generateBunAppScript({runtime:b.runtime||"bun",runtimeVersion:b.runtimeVersion||"latest",systemPackages:b.systemPackages,database:fe,caddyfile:or}),pr=cs(b.appUpdates),Dt=pr.length>0?`${Jt}
|
|
11
|
+
${pr.join(`
|
|
12
12
|
`)}
|
|
13
|
-
`:
|
|
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`
|
|
13
|
+
`:Jt,Rt=v.map(([,ir])=>ir.port).filter((ir)=>typeof ir==="number"&&![80,443].includes(ir)),Ze=this.resolveApiOriginPort(),Nt=`${l}${S}DeployBucket`.replace(/[^a-zA-Z0-9]/g,""),ne=`${l}-${S}-deploy`;this.builder.addResource(Nt,{Type:"AWS::S3::Bucket",Properties:{BucketName:ne,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 Tt=o.createServerModeStack({slug:`${l}-app`,environment:S,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},instanceType:rt,keyName:b.allowSsh?`${l}-${S}`:void 0,domain:we,userData:Dt,volumeSize:b.disk?.size||20,imageId:b.image,allowedPorts:[...b.allowSsh?[22]:[],80,443,Ze,...Rt]}),wt=Tt.resources[Tt.outputs.instanceLogicalId];if(wt?.Properties){let ir=wt.Properties.Tags||[];wt.Properties.Tags=[...ir,{Key:"Project",Value:l},{Key:"Environment",Value:S},{Key:"Role",Value:"app"},{Key:"ManagedBy",Value:"ts-cloud"}]}let nr=Tt.resources[Tt.outputs.roleLogicalId];if(nr?.Properties)nr.Properties.Policies=nr.Properties.Policies||[],nr.Properties.Policies.push({PolicyName:"DeployBucketRead",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:GetObject","s3:ListBucket"],Resource:[`arn:aws:s3:::${ne}`,`arn:aws:s3:::${ne}/*`]}]}});for(let[ir,sr]of Object.entries(Tt.resources))this.builder.addResource(ir,sr);this.builder.addOutput("deployBucketName",{Value:{Ref:Nt},Description:"S3 bucket where release tarballs are uploaded"}),this.builder.addOutput("appInstanceId",{Value:{Ref:Tt.outputs.instanceLogicalId},Description:"EC2 instance ID for the app server"}),this.builder.addOutput("appPublicIp",{Value:{Ref:Tt.outputs.eipLogicalId},Description:"Public IP for the app server"}),this.serverEipLogicalIds.set("app",Tt.outputs.eipLogicalId),this.serverEipLogicalIds.set("appInstance",Tt.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",we=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:we,allowedCidrs:P.allowedCidrs,mountEfs:fe});for(let[ft,rt]of Object.entries(Ye.resources))this.builder.addResource(ft,rt);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,tt=P?.hostedZoneId,we=[],fe,Ye;if(b?.certificateArn)Ye=b.certificateArn;else if(b?.enabled&&v&&tt){let Rt=b.domains||[v],Ze=Rt[0],Nt=Rt.slice(1).map((wt)=>{if(wt.includes(".")&&wt.endsWith(Ze))return wt.replace(`.${Ze}`,"");return wt}),{certificate:ne,logicalId:Tt}=I.createCertificate({domain:Ze,subdomains:Nt,slug:l,environment:S,validationMethod:"DNS",hostedZoneId:tt});fe=Tt,this.builder.addResource(Tt,ne)}if(this.mergedConfig.infrastructure?.storage){let Rt=Object.entries(this.mergedConfig.infrastructure.storage).some(([,ne])=>ne.website),Ze;if(Rt&&(fe||Ye))Ze=`${l}${S}CloudFrontOAC`.replace(/[^a-zA-Z0-9]/g,""),this.builder.addResource(Ze,{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 Nt=Object.entries(this.mergedConfig.infrastructure.storage).map(([ne,Tt])=>({name:ne,config:Tt,mountPath:this.normalizeMountPath(Tt),rewriteStyle:Tt.pathRewriteStyle||"directory",logicalId:this.storageBucketLogicalId(l,S,ne)})).filter((ne)=>ne.name!=="public"&&ne.config.website&&ne.mountPath);for(let[ne,Tt]of Object.entries(this.mergedConfig.infrastructure.storage)){let wt=!!(Tt.website&&Ze),nr=this.storageBucketName(l,S,ne),{bucket:ir,logicalId:sr}=Se.createBucket({slug:l,name:ne,environment:S,bucketName:nr,versioning:Tt.versioning,encryption:Tt.encryption,public:wt?!1:Tt.public});if(wt&&ir.Properties)ir.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1};if(this.builder.addResource(sr,ir),Tt.website){let Jr=typeof Tt.website==="object"?Tt.website:{},mr=Se.enableWebsiteHosting(ir,Jr.indexDocument||"index.html",Jr.errorDocument);this.builder.addResource(sr,mr)}let hr=this.normalizeMountPath(Tt);if(wt&&Ze&&v&&!(hr&&ne!=="public")){let Jr=`${l}${S}${ne}CDN`.replace(/[^a-zA-Z0-9]/g,""),mr=[];if(Tt.aliases&&Tt.aliases.length>0)mr.push(...Tt.aliases);else if(ne==="public"){if(mr.push(v),b?.domains?.includes(`www.${v}`))mr.push(`www.${v}`)}else if(ne==="docs")mr.push(`docs.${v}`);else if(ne==="blog")mr.push(`blog.${v}`);let hn=typeof Tt.website==="object"?Tt.website:{},Sn=Tt.spa===!0,Bn=hn.errorDocument||(Sn?"index.html":"404.html"),Qn=[];if(Sn)Qn.push({ErrorCode:403,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:300});else Qn.push({ErrorCode:403,ResponseCode:404,ResponsePagePath:`/${Bn}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${Bn}`,ErrorCachingMinTTL:300});let Ji=Ye&&mr.length>0?{AcmCertificateArn:Ye,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:fe&&mr.length>0?{AcmCertificateArn:{Ref:fe},SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},$i=`S3-${l}-${S}-${ne}`,vn=this.mergedConfig.project.region||"us-east-1",Fn;if(!Sn)Fn=`${l}${S}${ne}UrlRewrite`.replace(/[^a-zA-Z0-9]/g,""),this.builder.addResource(Fn,{Type:"AWS::CloudFront::Function",Properties:{Name:`${l}-${S}-${ne}-url-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`URL rewrite for ${l} ${S} ${ne} - 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 va=[{Id:$i,DomainName:{"Fn::Sub":`\${${sr}}.s3.${vn}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:Ze}}],Zo=[],Oa=[];if(this.shouldRouteStorageBucketToCompute(ne,Tt)){this.appendComputeAppOrigin(va,Zo,Oa,l,S,this.resolveComputeCachePathPatterns(Tt.computeRoutes));for(let tn of Nt){let Xo=`S3-${l}-${S}-${tn.name}`,Fa=`${l}${S}${tn.name}PathMountRewrite`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Fa,{Type:"AWS::CloudFront::Function",Properties:{Name:`${l}-${S}-${tn.name}-path-mount-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`Path mount rewrite for ${l} ${S} ${tn.name} at ${tn.mountPath}`,Runtime:"cloudfront-js-2.0"},FunctionCode:this.pathMountRewriteFunctionCode(tn.mountPath,tn.rewriteStyle)}}),va.push({Id:Xo,DomainName:{"Fn::Sub":`\${${tn.logicalId}}.s3.${vn}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:Ze}}),Oa.push(tn.logicalId,Fa);for(let Tl of[tn.mountPath,`${tn.mountPath}/*`])Zo.push({PathPattern:Tl,TargetOriginId:Xo,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":[Fa,"FunctionARN"]}}]})}}let Ka={Type:"AWS::CloudFront::Distribution",DependsOn:[sr,Ze,...Fn?[Fn]:[],...Oa],Properties:{DistributionConfig:{Enabled:!0,Comment:`${l} ${S} ${ne} site`,DefaultRootObject:"index.html",Origins:va,DefaultCacheBehavior:{TargetOriginId:$i,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",...Fn?{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[Fn,"FunctionARN"]}}]}:{}},...Zo.length>0?{CacheBehaviors:Zo}:{},...mr.length>0?{Aliases:mr}:{},ViewerCertificate:Ji,PriceClass:"PriceClass_100",HttpVersion:"http2and3",IPV6Enabled:!0,CustomErrorResponses:Qn}}};if(fe)Ka.DependsOn.push(fe);this.builder.addResource(Jr,Ka);let Pl=`${sr}CloudFrontPolicy`;if(this.builder.addResource(Pl,{Type:"AWS::S3::BucketPolicy",DependsOn:[sr,Jr],Properties:{Bucket:{Ref:sr},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":`arn:aws:s3:::\${${sr}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${Jr}}`}}}}]}}}),this.shouldRouteStorageBucketToCompute(ne,Tt))for(let tn of Nt){let Xo=`${tn.logicalId}CloudFrontPolicy`;this.builder.addResource(Xo,{Type:"AWS::S3::BucketPolicy",DependsOn:[tn.logicalId,Jr],Properties:{Bucket:{Ref:tn.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:::\${${tn.logicalId}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${Jr}}`}}}}]}}})}if(mr.length>0)we.push({name:ne,bucketLogicalId:sr,distLogicalId:Jr,oacLogicalId:Ze,aliases:mr});this.builder.addOutput(`${ne}CloudFrontDomain`,{Value:{"Fn::GetAtt":[Jr,"DomainName"]},Description:`CloudFront domain for ${ne}`}),this.builder.addOutput(`${ne}CloudFrontDistributionId`,{Value:{Ref:Jr},Description:`CloudFront distribution ID for ${ne}`})}if(this.builder.addOutput(`${ne}BucketName`,{Value:{Ref:sr},Description:`S3 bucket name for ${ne}`}),ne==="public")this.builder.addOutput("FrontendBucketName",{Value:{Ref:sr},Description:"Frontend S3 bucket name"});if(ne==="docs")this.builder.addOutput("DocsBucketName",{Value:{Ref:sr},Description:"Documentation S3 bucket name"});if(ne==="blog")this.builder.addOutput("BlogBucketName",{Value:{Ref:sr},Description:"Blog S3 bucket name"})}}if(this.mergedConfig.infrastructure?.sftp){let Rt=this.mergedConfig.infrastructure.sftp,Ze=nd.create({...Rt,storage:this.resolveSftpStorage(Rt,l,S)??Rt.storage,slug:l,environment:S});for(let[Nt,ne]of Object.entries(Ze.resources))this.builder.addResource(Nt,ne);this.builder.addOutput("SftpServerId",{Value:{Ref:Ze.serverLogicalId},Description:"AWS Transfer Family SFTP server ID"}),this.builder.addOutput("SftpEndpoint",{Value:{"Fn::Sub":`\${${Ze.serverLogicalId}}.server.transfer.\${AWS::Region}.amazonaws.com`},Description:"AWS Transfer Family SFTP endpoint"}),this.builder.addOutput("SftpStorageDomain",{Value:Ze.domain,Description:"Storage backing the SFTP server (EFS or S3)"})}if(tt&&we.length>0)for(let{name:Rt,distLogicalId:Ze,aliases:Nt}of we)for(let ne of Nt){let Tt=ne.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${Tt}ARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[Ze],Properties:{HostedZoneId:tt,Name:ne,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":[Ze,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}}),this.builder.addResource(`${Tt}AAAARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[Ze],Properties:{HostedZoneId:tt,Name:ne,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":[Ze,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}})}if(this.mergedConfig.infrastructure?.databases){for(let[Rt,Ze]of Object.entries(this.mergedConfig.infrastructure.databases))if(Ze.engine==="dynamodb"){let{table:Nt,logicalId:ne}=Ft.createTable({slug:l,environment:S,tableName:`${l}-${S}-${Rt}`,partitionKey:Ze.partitionKey||{name:"id",type:"S"},sortKey:Ze.sortKey});this.builder.addResource(ne,Nt)}else if(Ze.engine==="postgres"){let{dbInstance:Nt,logicalId:ne}=Ft.createPostgres({slug:l,environment:S,dbInstanceIdentifier:`${l}-${S}-${Rt}`,masterUsername:Ze.username||"admin",masterUserPassword:Ze.password||"changeme123",allocatedStorage:Ze.storage||20,dbInstanceClass:Ze.instanceClass||"db.t3.micro"});this.builder.addResource(ne,Nt)}else if(Ze.engine==="mysql"){let{dbInstance:Nt,logicalId:ne}=Ft.createMysql({slug:l,environment:S,dbInstanceIdentifier:`${l}-${S}-${Rt}`,masterUsername:Ze.username||"admin",masterUserPassword:Ze.password||"changeme123",allocatedStorage:Ze.storage||20,dbInstanceClass:Ze.instanceClass||"db.t3.micro"});this.builder.addResource(ne,Nt)}}if(this.mergedConfig.infrastructure?.cdn)for(let[Rt,Ze]of Object.entries(this.mergedConfig.infrastructure.cdn)){if(!Ze.origin)continue;let Nt=typeof Ze.customDomain==="string"?Ze.customDomain:Ze.customDomain?.domain||Ze.domain,ne=typeof Ze.customDomain==="object"?Ze.customDomain?.certificateArn:Ze.certificateArn,Tt=ne||Ye,wt=`${l}${S}${Rt}CDN`.replace(/[^a-zA-Z0-9]/g,""),nr=`S3-${l}-${S}-${Rt}-cdn`,ir=[{Id:nr,DomainName:Ze.origin,OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginShield:Ze.originShield?{Enabled:!0,OriginShieldRegion:Ze.originShieldRegion||this.mergedConfig.environments[S]?.region||this.mergedConfig.project.region||"us-east-1"}:{Enabled:!1}}],sr=[],hr=[];if(Ze.routeCompute)this.appendComputeAppOrigin(ir,sr,hr,l,S,this.resolveComputeCachePathPatterns(Ze.computeRoutes));let Jr=Tt&&Nt?{AcmCertificateArn:fe&&!ne?{Ref:fe}:Tt,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},mr=[...hr];if(fe&&!ne&&Nt)mr.push(fe);let hn={Type:"AWS::CloudFront::Distribution",...mr.length>0?{DependsOn:mr}:{},Properties:{DistributionConfig:{Enabled:!0,Comment:`${l} ${S} ${Rt} CDN`,DefaultRootObject:"index.html",Origins:ir,DefaultCacheBehavior:{TargetOriginId:nr,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:Ze.compress!==!1,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},...sr.length>0?{CacheBehaviors:sr}:{},...Nt&&Tt?{Aliases:[Nt]}:{},ViewerCertificate:Jr,PriceClass:"PriceClass_100",HttpVersion:Ze.http3?"http2and3":"http2"}}};if(this.builder.addResource(wt,hn),tt&&Nt&&Tt){let Sn=Nt.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${Sn}CdnARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[wt,...fe&&!ne?[fe]:[]],Properties:{HostedZoneId:tt,Name:Nt,Type:"A",AliasTarget:{HostedZoneId:"Z2FDTNDATAQYW2",DNSName:{"Fn::GetAtt":[wt,"DomainName"]}}}})}}if(this.mergedConfig.infrastructure?.queues)for(let[Rt,Ze]of Object.entries(this.mergedConfig.infrastructure.queues)){if(!this.shouldDeploy(Ze))continue;let{queue:Nt,logicalId:ne}=M.createQueue({slug:l,environment:S,name:`${l}-${S}-${Rt}`,fifo:Ze.fifo,visibilityTimeout:Ze.visibilityTimeout,messageRetentionPeriod:Ze.messageRetentionPeriod,delaySeconds:Ze.delaySeconds,maxMessageSize:Ze.maxMessageSize,receiveMessageWaitTime:Ze.receiveMessageWaitTime,contentBasedDeduplication:Ze.contentBasedDeduplication,encrypted:Ze.encrypted,kmsKeyId:Ze.kmsKeyId});this.builder.addResource(ne,Nt);let Tt;if(Ze.deadLetterQueue){let{deadLetterQueue:wt,updatedSourceQueue:nr,deadLetterLogicalId:ir}=M.createDeadLetterQueue(ne,{slug:l,environment:S,maxReceiveCount:Ze.maxReceiveCount});Tt=ir,this.builder.addResource(ir,wt);let hr=this.builder.getResources()[ne];if(hr?.Properties)hr.Properties.RedrivePolicy=nr.Properties?.RedrivePolicy}if(Ze.trigger){let wt=Ze.trigger,nr=`${l}${S}${wt.functionName}`.replace(/[^a-zA-Z0-9]/g,""),ir={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:{"Fn::GetAtt":[ne,"Arn"]},FunctionName:{Ref:nr},BatchSize:wt.batchSize||10,MaximumBatchingWindowInSeconds:wt.batchWindow||0,Enabled:!0,...wt.reportBatchItemFailures!==!1&&{FunctionResponseTypes:["ReportBatchItemFailures"]},...wt.maxConcurrency&&{ScalingConfig:{MaximumConcurrency:wt.maxConcurrency}},...wt.filterPattern&&{FilterCriteria:{Filters:[{Pattern:JSON.stringify(wt.filterPattern)}]}}},DependsOn:[ne,nr]};this.builder.addResource(`${ne}Trigger`,ir)}if(Ze.alarms?.enabled){let wt=Ze.alarms,nr=wt.notificationTopicArn;if(!nr&&wt.notificationEmails?.length){let hr=`${ne}AlarmTopic`;this.builder.addResource(hr,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${l}-${S}-${Rt}-alarms`,DisplayName:`${Rt} Queue Alarms`}}),wt.notificationEmails.forEach((Jr,mr)=>{this.builder.addResource(`${hr}Sub${mr}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:hr},Protocol:"email",Endpoint:Jr}})}),nr={Ref:hr}}let ir=wt.queueDepthThreshold||1000;this.builder.addResource(`${ne}DepthAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-${Rt}-queue-depth`,AlarmDescription:`Queue ${Rt} depth exceeds ${ir} messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:ir,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[ne,"QueueName"]}}],...nr&&{AlarmActions:[nr],OKActions:[nr]}}});let sr=wt.messageAgeThreshold||3600;if(this.builder.addResource(`${ne}AgeAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-${Rt}-message-age`,AlarmDescription:`Queue ${Rt} oldest message exceeds ${sr} seconds`,MetricName:"ApproximateAgeOfOldestMessage",Namespace:"AWS/SQS",Statistic:"Maximum",Period:300,EvaluationPeriods:2,Threshold:sr,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[ne,"QueueName"]}}],...nr&&{AlarmActions:[nr],OKActions:[nr]}}}),Tt&&wt.dlqAlarm!==!1)this.builder.addResource(`${Tt}Alarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-${Rt}-dlq-messages`,AlarmDescription:`Dead letter queue for ${Rt} has messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Sum",Period:300,EvaluationPeriods:1,Threshold:0,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[Tt,"QueueName"]}}],...nr&&{AlarmActions:[nr]}}})}if(Ze.subscribe){let wt=Ze.subscribe,nr=wt.topicArn;if(!nr&&wt.topicName)nr={Ref:wt.topicName};if(nr){this.builder.addResource(`${ne}SnsPolicy`,{Type:"AWS::SQS::QueuePolicy",Properties:{Queues:[{Ref:ne}],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"sns.amazonaws.com"},Action:"sqs:SendMessage",Resource:{"Fn::GetAtt":[ne,"Arn"]},Condition:{ArnEquals:{"aws:SourceArn":nr}}}]}}});let ir={TopicArn:nr,Protocol:"sqs",Endpoint:{"Fn::GetAtt":[ne,"Arn"]},RawMessageDelivery:wt.rawMessageDelivery||!1};if(wt.filterPolicy)ir.FilterPolicy=wt.filterPolicy,ir.FilterPolicyScope=wt.filterPolicyScope||"MessageAttributes";this.builder.addResource(`${ne}SnsSub`,{Type:"AWS::SNS::Subscription",Properties:ir,DependsOn:`${ne}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 ft=this.mergedConfig.infrastructure?.redirects;if(ft){let Rt=ft.target||this.mergedConfig.infrastructure?.dns?.domain||"",Ze=ft.protocol||"https";if(ft.domains?.length&&Rt)for(let Nt of ft.domains){let{bucket:ne,bucketPolicy:Tt,logicalId:wt,policyLogicalId:nr}=dt.createDomainRedirectBucket({slug:l,environment:S,sourceDomain:Nt,targetDomain:Rt,protocol:Ze});this.builder.addResource(wt,ne),this.builder.addResource(nr,Tt)}if(ft.paths&&Object.keys(ft.paths).length>0){let Nt=dt.fromMapping(ft.paths,{statusCode:ft.statusCode||301}),{function:ne,logicalId:Tt}=dt.createPathRedirectFunction({slug:l,environment:S,rules:Nt});this.builder.addResource(Tt,ne)}}if(this.mergedConfig.infrastructure?.monitoring?.alarms)for(let[Rt,Ze]of Object.entries(this.mergedConfig.infrastructure.monitoring.alarms)){let{alarm:Nt,logicalId:ne}=qs.createAlarm({slug:l,environment:S,alarmName:`${l}-${S}-${Rt}`,metricName:Ze.metricName||"Errors",namespace:Ze.namespace||"AWS/Lambda",threshold:Ze.threshold||1,comparisonOperator:Ze.comparisonOperator||"GreaterThanThreshold"});this.builder.addResource(ne,Nt)}let rt=this.mergedConfig.infrastructure?.cache;if(rt){let Rt=rt.type||"redis";if(Rt==="redis"){this.generateNetworkInfrastructure(l,S);let Ze=rt.redis||{},{replicationGroup:Nt,subnetGroup:ne,logicalId:Tt,subnetGroupId:wt}=Gs.createRedis({slug:l,environment:S,nodeType:Ze.nodeType||rt.nodeType||"cache.t3.micro",engineVersion:Ze.engineVersion||"7.1",port:Ze.port||6379,numCacheClusters:Ze.numCacheNodes||2,automaticFailover:Ze.automaticFailoverEnabled!==!1,atRestEncryption:!0,transitEncryption:!0,snapshotRetentionDays:Ze.snapshotRetentionLimit||7,snapshotWindow:Ze.snapshotWindow,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(Tt,Nt),ne&&wt)this.builder.addResource(wt,ne);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[Tt,"PrimaryEndPoint.Address"]},Description:"Redis primary endpoint address"}),this.builder.addOutput("CachePort",{Value:{"Fn::GetAtt":[Tt,"PrimaryEndPoint.Port"]},Description:"Redis primary endpoint port"})}else if(Rt==="memcached"){this.generateNetworkInfrastructure(l,S);let Ze=rt.elasticache||{},{cluster:Nt,subnetGroup:ne,logicalId:Tt,subnetGroupId:wt}=Gs.createMemcached({slug:l,environment:S,nodeType:Ze.nodeType||rt.nodeType||"cache.t3.micro",engineVersion:Ze.engineVersion||"1.6.22",numCacheNodes:Ze.numCacheNodes||2,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(Tt,Nt),ne&&wt)this.builder.addResource(wt,ne);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[Tt,"ConfigurationEndpoint.Address"]},Description:"Memcached configuration endpoint address"})}}let or=this.mergedConfig.infrastructure?.email;if(or){let Rt=or.domain||this.mergedConfig.infrastructure?.dns?.domain;if(Rt){let{emailIdentity:Ze,logicalId:Nt}=m.verifyDomain({domain:Rt,slug:l,environment:S,enableDkim:or.enableDkim!==!1,dkimKeyLength:or.dkimKeyLength||"RSA_2048_BIT"});if(this.builder.addResource(Nt,Ze),or.configurationSet!==!1){let{configurationSet:wt,logicalId:nr}=m.createConfigurationSet({slug:l,environment:S});this.builder.addResource(nr,wt)}let ne=or.hostedZoneId||this.mergedConfig.infrastructure?.dns?.hostedZoneId;if(ne){if(or.enableDkim!==!1)for(let hr=1;hr<=3;hr++){let Jr=`DkimRecord${hr}${Rt.replace(/\./g,"")}`;this.builder.addResource(Jr,{Type:"AWS::Route53::RecordSet",DependsOn:[Nt],Properties:{HostedZoneId:ne,Name:{"Fn::GetAtt":[Nt,`DkimDNSTokenName${hr}`]},Type:"CNAME",TTL:1800,ResourceRecords:[{"Fn::GetAtt":[Nt,`DkimDNSTokenValue${hr}`]}]}})}let{record:wt,logicalId:nr}=m.createSpfRecord(Rt,ne);this.builder.addResource(nr,wt);let{record:ir,logicalId:sr}=m.createDmarcRecord(Rt,ne,{policy:"none",reportingEmail:or.dmarcReportingEmail||`dmarc-reports@${Rt}`});this.builder.addResource(sr,ir)}this.builder.addOutput("EmailDomain",{Value:Rt,Description:"SES verified email domain"});let Tt=or.server;if(Tt?.enabled&&ne){let wt=this.mergedConfig.environments[S]?.region||this.mergedConfig.project.region||"us-east-1",nr=`${l}-${S}-email`,{role:ir,policy:sr,roleLogicalId:hr,policyLogicalId:Jr}=m.createEmailLambdaRole({slug:l,environment:S,s3BucketArn:`arn:aws:s3:::${nr}`,sesIdentityArn:`arn:aws:ses:${wt}:*:identity/${Rt}`});this.builder.addResource(hr,ir),this.builder.addResource(Jr,sr);let{function:mr,permission:hn,logicalId:Sn,permissionLogicalId:Bn}=m.createInboundEmailLambda({slug:l,environment:S,roleArn:{"Fn::GetAtt":[hr,"Arn"]},s3BucketName:nr,organizedPrefix:"mailboxes/"});this.builder.addResource(Sn,mr),this.builder.addResource(Bn,hn);let Qn=m.createInboundEmailSetup({slug:l,environment:S,domain:Rt,s3BucketName:nr,s3KeyPrefix:"inbox/",region:wt,hostedZoneId:ne,lambdaFunctionArn:{"Fn::GetAtt":[Sn,"Arn"]}});for(let[$i,vn]of Object.entries(Qn.resources)){if(vn.Type==="AWS::SES::ReceiptRule")vn.DependsOn=[Bn,Sn];this.builder.addResource($i,vn)}this.builder.addOutput("InboundEmailLambda",{Value:{Ref:Sn},Description:"Inbound email processing Lambda function"}),this.builder.addOutput("EmailBucket",{Value:nr,Description:"S3 bucket for email storage"});let Ji=this.serverEipLogicalIds.get("app");if(Ji&&ne){let vn=`${Tt?.subdomain||"mail"}.${Rt}`,Fn=vn.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${Fn}ARecord`,{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:ne,Name:vn,Type:"A",TTL:"300",ResourceRecords:[{Ref:Ji}]}})}this.builder.addOutput("MailHost",{Value:`mail.${Rt}`,Description:"Mail server hostname for SMTP/IMAP clients"})}}}let Jt=this.mergedConfig.infrastructure?.search;if(Jt){let Rt=Jt.vpc?{subnetIds:[{Ref:"PublicSubnet1"}],securityGroupIds:[]}:void 0;if(Rt)this.generateNetworkInfrastructure(l,S);let{domain:Ze,logicalId:Nt}=Ut.createDomain({slug:l,environment:S,engineVersion:Jt.engineVersion||"OpenSearch_2.11",instanceType:Jt.instanceType||"t3.small.search",instanceCount:Jt.instanceCount||1,volumeSize:Jt.volumeSize||10,volumeType:Jt.volumeType||"gp3",dedicatedMaster:Jt.dedicatedMaster||!1,dedicatedMasterType:Jt.dedicatedMasterType,dedicatedMasterCount:Jt.dedicatedMasterCount||3,multiAz:Jt.multiAz||!1,encryption:Jt.encryption||{atRest:!0,nodeToNode:!0},advancedSecurity:Jt.advancedSecurity,autoTune:Jt.autoTune!==!1,vpc:Rt});this.builder.addResource(Nt,Ze),this.builder.addOutput("SearchDomainEndpoint",{Value:{"Fn::GetAtt":[Nt,"DomainEndpoint"]},Description:"OpenSearch domain endpoint"}),this.builder.addOutput("SearchDomainArn",{Value:{"Fn::GetAtt":[Nt,"Arn"]},Description:"OpenSearch domain ARN"})}let pr=this.mergedConfig.infrastructure?.fileSystem;if(pr&&Object.keys(pr).length>0){this.generateNetworkInfrastructure(l,S);for(let[Rt,Ze]of Object.entries(pr)){let{fileSystem:Nt,logicalId:ne}=Ue.createFileSystem({slug:`${l}-${Rt}`,environment:S,encrypted:Ze.encrypted!==!1,performanceMode:Ze.performanceMode||"generalPurpose",throughputMode:Ze.throughputMode||"bursting",enableBackup:!0});this.builder.addResource(ne,Nt);let{securityGroup:Tt,logicalId:wt}=Ue.createEfsSecurityGroup({slug:`${l}-${Rt}`,environment:S,vpcId:{Ref:"VPC"},sourceCidrBlocks:["10.0.0.0/16"]});this.builder.addResource(wt,Tt);let{mountTargets:nr,logicalIds:ir}=Ue.createMultiAzMountTargets(ne,{slug:`${l}-${Rt}`,environment:S,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],securityGroupId:{Ref:wt}});for(let sr=0;sr<nr.length;sr++)this.builder.addResource(ir[sr],nr[sr]);this.builder.addOutput(`${Rt}FileSystemId`,{Value:{Ref:ne},Description:`EFS file system ID for ${Rt}`})}}let Dt=this.mergedConfig.infrastructure?.ai;if(Dt){let Rt=Dt.service||"ecs",Ze=Dt.models||["*"],Nt=Dt.allowStreaming!==!1,ne;if(Rt==="ecs")ne=be.enableBedrockForEcs({slug:l,environment:S,models:Ze,allowStreaming:Nt});else if(Rt==="ec2")ne=be.enableBedrockForEc2({slug:l,environment:S,models:Ze,allowStreaming:Nt});else if(Rt==="lambda")ne=be.enableBedrockForLambda({slug:l,environment:S,models:Ze,allowStreaming:Nt});else ne=be.createBedrockRole(Rt,{slug:l,environment:S,models:Ze,allowStreaming:Nt});if(this.builder.addResource(ne.logicalId,ne.role),Dt.allowAsync){let{policy:Tt,logicalId:wt}=be.createBedrockPolicy({slug:l,environment:S,models:Ze,allowStreaming:Nt,allowAsync:!0});this.builder.addResource(wt,Tt)}this.builder.addOutput("BedrockRoleArn",{Value:{"Fn::GetAtt":[ne.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||{},tt=b.storage||{type:"dynamodb"},we=v.handlerMemory||256,fe=v.handlerTimeout||30,Ye=`${l}${S}RealtimeConnections`.replace(/[^a-zA-Z0-9]/g,""),ft=`${l}${S}RealtimeChannels`.replace(/[^a-zA-Z0-9]/g,"");if(tt.type==="dynamodb"){let ir=tt.dynamodb||{},sr=ir.billingMode||"PAY_PER_REQUEST";this.builder.addResource(Ye,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${l}-${S}-realtime-connections`,BillingMode:sr,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"},...sr==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:ir.readCapacity||5,WriteCapacityUnits:ir.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...sr==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:ir.readCapacity||5,WriteCapacityUnits:ir.writeCapacity||5}},...ir.pointInTimeRecovery&&{PointInTimeRecoverySpecification:{PointInTimeRecoveryEnabled:!0}},Tags:[{Key:"Name",Value:`${l}-${S}-realtime-connections`},{Key:"Environment",Value:S}]}}),this.builder.addResource(ft,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${l}-${S}-realtime-channels`,BillingMode:sr,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"},...sr==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:ir.readCapacity||5,WriteCapacityUnits:ir.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...sr==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:ir.readCapacity||5,WriteCapacityUnits:ir.writeCapacity||5}},Tags:[{Key:"Name",Value:`${l}-${S}-realtime-channels`},{Key:"Environment",Value:S}]}})}let rt=`${l}${S}RealtimeRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(rt,{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":[ft,"Arn"]},{"Fn::Sub":`\${${ft}.Arn}/index/*`}]},{Effect:"Allow",Action:"execute-api:ManageConnections",Resource:{"Fn::Sub":"arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:*/*"}}]}}]}});let or=`${l}${S}RealtimeConnect`.replace(/[^a-zA-Z0-9]/g,""),Jt=`${l}${S}RealtimeDisconnect`.replace(/[^a-zA-Z0-9]/g,""),pr=`${l}${S}RealtimeMessage`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(or,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${l}-${S}-realtime-connect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[rt,"Arn"]},MemorySize:we,Timeout:fe,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:Ye},CHANNELS_TABLE:{Ref:ft},ENVIRONMENT:S}},Code:{ZipFile:this.generateConnectHandlerCode()}},DependsOn:[rt,Ye]}),this.builder.addResource(Jt,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${l}-${S}-realtime-disconnect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[rt,"Arn"]},MemorySize:we,Timeout:fe,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:Ye},CHANNELS_TABLE:{Ref:ft},ENVIRONMENT:S}},Code:{ZipFile:this.generateDisconnectHandlerCode()}},DependsOn:[rt,Ye,ft]}),this.builder.addResource(pr,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${l}-${S}-realtime-message`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[rt,"Arn"]},MemorySize:we,Timeout:fe,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:Ye},CHANNELS_TABLE:{Ref:ft},ENVIRONMENT:S}},Code:{ZipFile:this.generateMessageHandlerCode()}},DependsOn:[rt,Ye,ft]});let Dt=`${l}${S}RealtimeApi`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Dt,{Type:"AWS::ApiGatewayV2::Api",Properties:{Name:P,ProtocolType:"WEBSOCKET",RouteSelectionExpression:"$request.body.action",Tags:{Name:P,Environment:S}}});let Rt=`${or}Permission`,Ze=`${Jt}Permission`,Nt=`${pr}Permission`;this.builder.addResource(Rt,{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}:\${${Dt}}/*/$connect`}}}),this.builder.addResource(Ze,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:Jt},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${Dt}}/*/$disconnect`}}}),this.builder.addResource(Nt,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:pr},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${Dt}}/*/$default`}}});let ne=`${Dt}ConnectInteg`,Tt=`${Dt}DisconnectInteg`,wt=`${Dt}MessageInteg`;this.builder.addResource(ne,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:Dt},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${or}.Arn}/invocations`}}}),this.builder.addResource(Tt,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:Dt},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${Jt}.Arn}/invocations`}}}),this.builder.addResource(wt,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:Dt},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${pr}.Arn}/invocations`}}}),this.builder.addResource(`${Dt}ConnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:Dt},RouteKey:"$connect",AuthorizationType:"NONE",Target:{"Fn::Sub":`integrations/\${${ne}}`}}}),this.builder.addResource(`${Dt}DisconnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:Dt},RouteKey:"$disconnect",Target:{"Fn::Sub":`integrations/\${${Tt}}`}}}),this.builder.addResource(`${Dt}DefaultRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:Dt},RouteKey:"$default",Target:{"Fn::Sub":`integrations/\${${wt}}`}}});let nr=`${Dt}Stage`;if(this.builder.addResource(nr,{Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:{Ref:Dt},StageName:S,AutoDeploy:!0,DefaultRouteSettings:{ThrottlingBurstLimit:v.messagesPerSecond||1000,ThrottlingRateLimit:v.messagesPerSecond||1000}}}),b.monitoring?.enabled){let ir=b.monitoring,sr=ir.notificationTopicArn;if(!sr&&ir.notificationEmails?.length){let hr=`${Dt}AlarmTopic`;this.builder.addResource(hr,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${l}-${S}-realtime-alarms`,DisplayName:"Realtime WebSocket Alarms"}}),ir.notificationEmails.forEach((Jr,mr)=>{this.builder.addResource(`${hr}Sub${mr}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:hr},Protocol:"email",Endpoint:Jr}})}),sr={Ref:hr}}if(ir.connectionThreshold)this.builder.addResource(`${Dt}ConnectionAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-realtime-connections`,AlarmDescription:`WebSocket connections exceed ${ir.connectionThreshold}`,MetricName:"ConnectCount",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:300,EvaluationPeriods:2,Threshold:ir.connectionThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:Dt}}],...sr&&{AlarmActions:[sr]}}});if(ir.errorThreshold)this.builder.addResource(`${Dt}ErrorAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-realtime-errors`,AlarmDescription:`WebSocket errors exceed ${ir.errorThreshold}/min`,MetricName:"ExecutionError",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:60,EvaluationPeriods:3,Threshold:ir.errorThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:Dt}}],...sr&&{AlarmActions:[sr]}}})}this.builder.addOutput(`${Dt}Endpoint`,{Description:"WebSocket API endpoint URL",Value:{"Fn::Sub":`wss://\${${Dt}}.execute-api.\${AWS::Region}.amazonaws.com/${S}`},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-endpoint"}}}),this.builder.addOutput(`${Dt}Id`,{Description:"WebSocket API ID",Value:{Ref:Dt},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-api-id"}}})}generateConnectHandlerCode(){return`
|
|
15
15
|
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb');
|
|
16
16
|
const { DynamoDBDocumentClient, PutCommand } = require('@aws-sdk/lib-dynamodb');
|
|
17
17
|
|
|
@@ -170,7 +170,7 @@ catch (error) {
|
|
|
170
170
|
return { statusCode: 500, body: JSON.stringify({ error: 'Internal error' }) };
|
|
171
171
|
}
|
|
172
172
|
};
|
|
173
|
-
`.trim()}generateRealtimeServerResources(l,S){let b=this.mergedConfig.infrastructure?.realtime;if(!b)return;let P=b.server||{},v=P.port||6001,
|
|
173
|
+
`.trim()}generateRealtimeServerResources(l,S){let b=this.mergedConfig.infrastructure?.realtime;if(!b)return;let P=b.server||{},v=P.port||6001,tt=P.instances||1,we=`${l}${S}RealtimeSG`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(we,{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,""),ft=`${l}${S}RealtimeExecRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(ft,{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 rt=[{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)rt.push({Name:"REDIS_HOST",Value:{"Fn::GetAtt":["CacheCluster","RedisEndpoint.Address"]}}),rt.push({Name:"REDIS_PORT",Value:{"Fn::GetAtt":["CacheCluster","RedisEndpoint.Port"]}});else rt.push({Name:"REDIS_HOST",Value:P.redis.host||"localhost"}),rt.push({Name:"REDIS_PORT",Value:String(P.redis.port||6379)});if(P.redis.keyPrefix)rt.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":[ft,"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:rt,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:[ft,Ye]});let or=`${l}${S}RealtimeLogs`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(or,{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/ecs/${l}-${S}-realtime`,RetentionInDays:30}});let Jt=`${l}${S}RealtimeService`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(Jt,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${l}-${S}-realtime`,Cluster:{Ref:"ECSCluster"},TaskDefinition:{Ref:fe},DesiredCount:tt,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:we}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},HealthCheckGracePeriodSeconds:60,Tags:[{Key:"Name",Value:`${l}-${S}-realtime`},{Key:"Environment",Value:S}]},DependsOn:[fe,we,or]}),P.autoScaling){let pr=P.autoScaling,Dt=`${l}${S}RealtimeScalableTarget`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(Dt,{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{MaxCapacity:pr.max||10,MinCapacity:pr.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:Jt}),pr.targetCPU)this.builder.addResource(`${l}${S}RealtimeCPUPolicy`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${l}-${S}-realtime-cpu-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:Dt},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},TargetValue:pr.targetCPU,ScaleInCooldown:300,ScaleOutCooldown:60}}})}if(b.monitoring?.enabled){let pr=b.monitoring,Dt=pr.notificationTopicArn;if(!Dt&&pr.notificationEmails?.length){let Rt=`${l}${S}RealtimeAlarmTopic`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Rt,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${l}-${S}-realtime-alarms`,DisplayName:"Realtime Server Alarms"}}),pr.notificationEmails.forEach((Ze,Nt)=>{this.builder.addResource(`${Rt}Sub${Nt}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:Rt},Protocol:"email",Endpoint:Ze}})}),Dt={Ref:Rt}}this.builder.addResource(`${l}${S}RealtimeCPUAlarm`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-realtime-high-cpu`,AlarmDescription:"Realtime server CPU utilization is high",MetricName:"CPUUtilization",Namespace:"AWS/ECS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:80,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ClusterName",Value:{Ref:"ECSCluster"}},{Name:"ServiceName",Value:`${l}-${S}-realtime`}],...Dt&&{AlarmActions:[Dt]}},DependsOn:Jt}),this.builder.addResource(`${l}${S}RealtimeMemoryAlarm`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${l}-${S}-realtime-high-memory`,AlarmDescription:"Realtime server memory utilization is high",MetricName:"MemoryUtilization",Namespace:"AWS/ECS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:80,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ClusterName",Value:{Ref:"ECSCluster"}},{Name:"ServiceName",Value:`${l}-${S}-realtime`}],...Dt&&{AlarmActions:[Dt]}},DependsOn:Jt})}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"},
|
|
@@ -219,7 +219,7 @@ ${S.loadManagement?.enabled?`
|
|
|
219
219
|
},
|
|
220
220
|
`:""}
|
|
221
221
|
} satisfies BroadcastConfig
|
|
222
|
-
`}toYAML(){return this.builder.toYAML()}toJSON(){return this.builder.toJSON()}getBuilder(){return this.builder}}function
|
|
222
|
+
`}toYAML(){return this.builder.toYAML()}toJSON(){return this.builder.toJSON()}getBuilder(){return this.builder}}function Bl(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=ql(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))Gl(P,v,S,b);if(l.Outputs)for(let[P,v]of Object.entries(l.Outputs))Ul(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,tt]of Object.entries(S.Properties))if(tt===void 0||tt===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 Gl(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 Ul(l,S,b,P){if(!S.Value)b.push({path:`Outputs.${l}.Value`,message:"Output Value is required",severity:"error"})}function ql(l){let S={};for(let[we,fe]of Object.entries(l)){if(S[we]=[],fe.DependsOn){if(typeof fe.DependsOn==="string")S[we].push(fe.DependsOn);else if(Array.isArray(fe.DependsOn))S[we].push(...fe.DependsOn)}let Ye=_a(fe);S[we].push(...Ye)}let b=new Set,P=new Set,v=[];function tt(we,fe){b.add(we),P.add(we),fe.push(we);let Ye=S[we]||[];for(let ft of Ye)if(!b.has(ft)){if(tt(ft,fe))return!0}else if(P.has(ft)){let rt=fe.indexOf(ft);return v.push(...fe.slice(rt),ft),!0}return fe.pop(),P.delete(we),!1}for(let we of Object.keys(S))if(!b.has(we)){if(tt(we,[]))return v}return[]}function _a(l,S=[]){if(typeof l!=="object"||l===null)return S;if(Array.isArray(l)){for(let b of l)_a(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))_a(b,S);return S}function Zl(l){let S=[],b=[],P=new TextEncoder().encode(l).length,v=51200,tt=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 Yl(l){let S=[],b=[],P=l.Resources?Object.keys(l.Resources).length:0,v=l.Parameters?Object.keys(l.Parameters).length:0,tt=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(tt>200)S.push({path:"Outputs",message:`Template has ${tt} outputs, exceeding the limit of 200`,severity:"error"});return{valid:S.length===0,errors:S,warnings:b}}function wm(l){let{domains:S,email:b,staging:P=!1,challengeType:v="http-01",certPath:tt="/etc/letsencrypt/live",autoRenew:we=!0}=l,fe=S[0],Ye=S.map((rt)=>`-d ${rt}`).join(" "),ft=P?"--staging":"";if(v==="http-01")return Ql({domains:S,email:b,staging:P,certPath:tt,autoRenew:we,domainFlags:Ye,stagingFlag:ft,primaryDomain:fe});else{let rt=l.dnsProvider?.provider||(l.hostedZoneId?"route53":void 0);return Ed({domains:S,email:b,staging:P,certPath:tt,autoRenew:we,domainFlags:Ye,stagingFlag:ft,primaryDomain:fe,hostedZoneId:l.hostedZoneId,dnsProvider:l.dnsProvider,dnsProviderType:rt})}}function Ql(l){let{email:S,certPath:b,autoRenew:P,domainFlags:v,stagingFlag:tt,primaryDomain:we}=l;return`
|
|
223
223
|
# ==========================================
|
|
224
224
|
# Let's Encrypt Certificate Setup (HTTP-01)
|
|
225
225
|
# ==========================================
|
|
@@ -236,28 +236,28 @@ certbot certonly \\
|
|
|
236
236
|
--non-interactive \\
|
|
237
237
|
--agree-tos \\
|
|
238
238
|
--email ${S} \\
|
|
239
|
-
${
|
|
239
|
+
${tt} \\
|
|
240
240
|
${v}
|
|
241
241
|
|
|
242
242
|
# Check if certificate was obtained
|
|
243
|
-
if [ -f "${b}/${
|
|
243
|
+
if [ -f "${b}/${we}/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 ${b}/${
|
|
249
|
-
ln -sf ${b}/${
|
|
250
|
-
ln -sf ${b}/${
|
|
251
|
-
ln -sf ${b}/${
|
|
248
|
+
ln -sf ${b}/${we}/fullchain.pem /etc/ssl/stacks/fullchain.pem
|
|
249
|
+
ln -sf ${b}/${we}/privkey.pem /etc/ssl/stacks/privkey.pem
|
|
250
|
+
ln -sf ${b}/${we}/cert.pem /etc/ssl/stacks/cert.pem
|
|
251
|
+
ln -sf ${b}/${we}/chain.pem /etc/ssl/stacks/chain.pem
|
|
252
252
|
else
|
|
253
253
|
echo "Failed to obtain certificate!"
|
|
254
254
|
fi
|
|
255
255
|
|
|
256
|
-
${P?
|
|
256
|
+
${P?Ma(we):"# Auto-renewal disabled"}
|
|
257
257
|
|
|
258
258
|
# Restart the application
|
|
259
259
|
systemctl start stacks
|
|
260
|
-
`}function
|
|
260
|
+
`}function Ed(l){let{email:S,certPath:b,autoRenew:P,domainFlags:v,stagingFlag:tt,primaryDomain:we,hostedZoneId:fe,dnsProvider:Ye,dnsProviderType:ft}=l;if(ft==="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
|
# ==========================================
|
|
@@ -271,48 +271,48 @@ certbot certonly \\
|
|
|
271
271
|
--non-interactive \\
|
|
272
272
|
--agree-tos \\
|
|
273
273
|
--email ${S} \\
|
|
274
|
-
${
|
|
274
|
+
${tt} \\
|
|
275
275
|
${v}
|
|
276
276
|
|
|
277
277
|
# Check if certificate was obtained
|
|
278
|
-
if [ -f "${b}/${
|
|
278
|
+
if [ -f "${b}/${we}/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 ${b}/${
|
|
284
|
-
ln -sf ${b}/${
|
|
285
|
-
ln -sf ${b}/${
|
|
286
|
-
ln -sf ${b}/${
|
|
283
|
+
ln -sf ${b}/${we}/fullchain.pem /etc/ssl/stacks/fullchain.pem
|
|
284
|
+
ln -sf ${b}/${we}/privkey.pem /etc/ssl/stacks/privkey.pem
|
|
285
|
+
ln -sf ${b}/${we}/cert.pem /etc/ssl/stacks/cert.pem
|
|
286
|
+
ln -sf ${b}/${we}/chain.pem /etc/ssl/stacks/chain.pem
|
|
287
287
|
else
|
|
288
288
|
echo "Failed to obtain certificate!"
|
|
289
289
|
fi
|
|
290
290
|
|
|
291
|
-
${P?
|
|
292
|
-
`}if(!Ye)throw Error("dnsProvider configuration is required for DNS-01 challenge with external DNS providers");let
|
|
291
|
+
${P?Ma(we):"# Auto-renewal disabled"}
|
|
292
|
+
`}if(!Ye)throw Error("dnsProvider configuration is required for DNS-01 challenge with external DNS providers");let rt=Ye.provider.toUpperCase(),or=eu(Ye);return`
|
|
293
293
|
# ==========================================
|
|
294
|
-
# Let's Encrypt Certificate Setup (DNS-01 via ${
|
|
294
|
+
# Let's Encrypt Certificate Setup (DNS-01 via ${rt})
|
|
295
295
|
# ==========================================
|
|
296
296
|
|
|
297
297
|
# Install certbot
|
|
298
298
|
dnf install -y certbot jq curl
|
|
299
299
|
|
|
300
|
-
${
|
|
300
|
+
${or}
|
|
301
301
|
|
|
302
302
|
# Create DNS challenge hook scripts directory
|
|
303
303
|
mkdir -p /etc/letsencrypt/hooks
|
|
304
304
|
|
|
305
|
-
# Create authenticator hook for ${
|
|
305
|
+
# Create authenticator hook for ${rt}
|
|
306
306
|
cat > /etc/letsencrypt/hooks/auth-hook.sh << 'AUTHHOOK'
|
|
307
307
|
#!/bin/bash
|
|
308
|
-
# DNS-01 authenticator hook for ${
|
|
308
|
+
# DNS-01 authenticator hook for ${rt}
|
|
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
|
-
${
|
|
315
|
+
${tu(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 ${
|
|
324
|
+
# Create cleanup hook for ${rt}
|
|
325
325
|
cat > /etc/letsencrypt/hooks/cleanup-hook.sh << 'CLEANUPHOOK'
|
|
326
326
|
#!/bin/bash
|
|
327
|
-
# DNS-01 cleanup hook for ${
|
|
327
|
+
# DNS-01 cleanup hook for ${rt}
|
|
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
|
-
${
|
|
334
|
+
${ru(Ye)}
|
|
335
335
|
CLEANUPHOOK
|
|
336
336
|
|
|
337
337
|
chmod +x /etc/letsencrypt/hooks/cleanup-hook.sh
|
|
@@ -345,25 +345,25 @@ certbot certonly \\
|
|
|
345
345
|
--non-interactive \\
|
|
346
346
|
--agree-tos \\
|
|
347
347
|
--email ${S} \\
|
|
348
|
-
${
|
|
348
|
+
${tt} \\
|
|
349
349
|
${v}
|
|
350
350
|
|
|
351
351
|
# Check if certificate was obtained
|
|
352
|
-
if [ -f "${b}/${
|
|
352
|
+
if [ -f "${b}/${we}/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 ${b}/${
|
|
358
|
-
ln -sf ${b}/${
|
|
359
|
-
ln -sf ${b}/${
|
|
360
|
-
ln -sf ${b}/${
|
|
357
|
+
ln -sf ${b}/${we}/fullchain.pem /etc/ssl/stacks/fullchain.pem
|
|
358
|
+
ln -sf ${b}/${we}/privkey.pem /etc/ssl/stacks/privkey.pem
|
|
359
|
+
ln -sf ${b}/${we}/cert.pem /etc/ssl/stacks/cert.pem
|
|
360
|
+
ln -sf ${b}/${we}/chain.pem /etc/ssl/stacks/chain.pem
|
|
361
361
|
else
|
|
362
362
|
echo "Failed to obtain certificate!"
|
|
363
363
|
fi
|
|
364
364
|
|
|
365
|
-
${P?
|
|
366
|
-
`}function
|
|
365
|
+
${P?Ma(we):"# Auto-renewal disabled"}
|
|
366
|
+
`}function eu(l){switch(l.provider){case"porkbun":return`
|
|
367
367
|
# Porkbun API credentials
|
|
368
368
|
export PORKBUN_API_KEY="${l.apiKey}"
|
|
369
369
|
export PORKBUN_SECRET_KEY="${l.secretKey}"
|
|
@@ -374,7 +374,7 @@ export GODADDY_API_SECRET="${l.apiSecret}"
|
|
|
374
374
|
export GODADDY_ENV="${l.environment||"production"}"
|
|
375
375
|
`;case"route53":return`
|
|
376
376
|
# Route53 uses IAM role credentials
|
|
377
|
-
`;default:return""}}function
|
|
377
|
+
`;default:return""}}function tu(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
|
|
421
|
+
`;default:return'echo "Unsupported DNS provider"'}}function ru(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
|
|
464
|
+
`;default:return'echo "Unsupported DNS provider"'}}function Ma(l){return`
|
|
465
465
|
# ==========================================
|
|
466
466
|
# Certificate Auto-Renewal Setup
|
|
467
467
|
# ==========================================
|
|
@@ -506,7 +506,7 @@ systemctl enable certbot-renewal.timer
|
|
|
506
506
|
systemctl start certbot-renewal.timer
|
|
507
507
|
|
|
508
508
|
echo "Certificate auto-renewal configured"
|
|
509
|
-
`}function
|
|
509
|
+
`}function Om(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
|
|
|
@@ -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
|
|
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};
|
|
595
|
+
`}async function Nm(l){let{domain:S,challengeValue:b,hostedZoneId:P,dnsProvider:v,region:tt="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(tt).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 km(l){let{domain:S,challengeValue:b,hostedZoneId:P,dnsProvider:v,region:tt="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(tt).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 xm(l){try{let{execSync:S}=Oe("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 Qa,createSign as nu,generateKeyPairSync as as}from"node:crypto";var ls={production:"https://acme-v02.api.letsencrypt.org/directory",staging:"https://acme-staging-v02.api.letsencrypt.org/directory"};class iu{directoryUrl;email;accountKey;accountUrl=null;directory=null;nonce=null;constructor(l){this.directoryUrl=l.staging?ls.staging:ls.production,this.email=l.email,this.accountKey=l.accountKey||this.generateAccountKey()}generateAccountKey(){let{privateKey:l}=as("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((tt)=>!tt.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=Qa("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 tt=this.base64UrlEncode(JSON.stringify(v)),we=S===""?"":this.base64UrlEncode(JSON.stringify(S)),fe=`${tt}.${we}`,Ye=nu("SHA256");Ye.update(fe);let ft=Ye.sign(this.accountKey),rt=ft.subarray(4,4+ft[3]),or=4+ft[3]+2,Jt=ft.subarray(or,or+ft[or-1]),pr=Buffer.alloc(32),Dt=Buffer.alloc(32);rt.copy(pr,32-rt.length),Jt.copy(Dt,32-Jt.length);let Rt=Buffer.concat([pr,Dt]);return JSON.stringify({protected:tt,payload:we,signature:this.base64UrlEncode(Rt)})}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 tt,we=P.headers.get("content-type");if(we?.includes("application/json")||we?.includes("application/problem+json"))tt=await P.json();else tt=await P.text();if(!P.ok)throw Error(`ACME request failed: ${JSON.stringify(tt)}`);return{body:tt,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((tt)=>({type:"dns",value:tt}))}),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((tt)=>tt.type==="http-01"||tt.type==="dns-01").map((tt)=>{let we=`${tt.token}.${P}`;if(tt.type==="http-01")return{type:"http-01",token:tt.token,keyAuthorization:we,identifier:`/.well-known/acme-challenge/${tt.token}`};else{let fe=this.base64UrlEncode(Qa("sha256").update(we).digest());return{type:"dns-01",token:tt.token,keyAuthorization:we,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}=as("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"))}),tt=v.certificate;if(!tt)throw Error("Certificate not immediately available - polling not implemented");let fe=await(await fetch(tt)).text(),Ye=fe.split(/(?=-----BEGIN CERTIFICATE-----)/g),ft=Ye[0],rt=Ye.slice(1).join("");return{certificate:ft,privateKey:P,chain:rt,fullchain:fe,expiresAt:new Date(Date.now()+7776000000)}}getAccountKey(){return this.accountKey}}var ds=["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"],ou=[{name:"x-stx-router",value:"true"}];function Vi(l){return`"${l.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function ec(l){return`{${l.map(Vi).join(" ")}}`}function au(l){let S=`http.request.headers[${Vi(l.name.toLowerCase())}]`;return l.value===void 0?`len(${S}) > 0`:`any(${S}[*] == ${Vi(l.value)})`}function Va(l){if(l.length===1)return`http.host eq ${Vi(l[0])}`;return`http.host in ${ec(l)}`}function Wa(l,S={}){if(S.enabled===!1||l.length===0)return[];let b=Va(l),P=[],tt=(S.bypassPaths??[]).map((pr)=>`starts_with(http.request.uri.path, ${Vi(pr)})`),fe=(S.negotiatedRequestHeaders??ou).map(au),Ye=[...tt,...fe],ft=Ye.length>0?`(${Ye.join(" or ")})`:void 0;if(ft)P.push({action:"set_cache_settings",description:"bypass cache",expression:`(${b} and ${ft})`,enabled:!0,action_parameters:{cache:!1}});let rt=ft?`${b} and not ${ft}`:b,or=S.assetExtensions??ds,Jt=or.length>0?`lower(http.request.uri.path.extension) in ${ec([...or])}`:void 0;if(Jt)P.push({action:"set_cache_settings",description:"cache fingerprinted assets",expression:`(${rt} and ${Jt})`,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:Jt?`(${rt} and not ${Jt})`:`(${rt})`,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 Ha(l,S,b){if(l.length===0||!S||!b)return[];return[{action:"rewrite",description:"origin guard header",expression:`(${Va(l)})`,enabled:!0,action_parameters:{headers:{[S]:{operation:"set",value:b}}}}]}var En=(l)=>l===void 0?void 0:l?"on":"off";function Ga(l){let S={ssl:l.ssl,always_use_https:En(l.alwaysUseHttps),automatic_https_rewrites:En(l.automaticHttpsRewrites),min_tls_version:l.minTlsVersion,tls_1_3:En(l.tls13),brotli:En(l.brotli),http3:En(l.http3),"0rtt":En(l.zeroRtt),early_hints:En(l.earlyHints),browser_cache_ttl:l.browserCacheTtl,always_online:En(l.alwaysOnline),websockets:En(l.websockets),email_obfuscation:En(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 ji={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 su}from"node:tls";async function ja(l){let{address:S,serverName:b,port:P=443,timeoutMs:v=5000}=l;return new Promise((tt)=>{let we=!1,fe=(ft)=>{if(we)return;we=!0;try{Ye.destroy()}catch{}tt(ft)},Ye=su({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",(ft)=>{fe({reachable:!1,trusted:!1,reason:ft.message})})})}function cu(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 tt=v.slice(2);if(!b.endsWith(`.${tt}`))return!1;return!b.slice(0,b.length-tt.length-1).includes(".")})}async function lu(l){let{provider:S,zone:b,hosts:P,ipv4:v,ipv6:tt,proxied:we=!0,settings:fe=ji,cache:Ye,originGuard:ft,purge:rt=!0,ttl:or=300,skipOriginProbe:Jt=!1,skipEdgeCertificateCheck:pr=!1}=l,Dt={records:[],settingsChanged:[],cacheRules:0,originGuard:!1,purged:!1,deferredProxy:[],warnings:[]};if(P.length===0)return Dt;let Rt=[],Ze=we&&!pr?await S.listEdgeCertificateHosts(b):null;for(let ne of P){let Tt=we;if(Tt&&Ze&&!cu(Ze,ne)){Tt=!1;let nr=Ze.length===0?"the zone has no active edge certificate yet":`no active edge certificate covers it (${Ze.join(", ")})`;Dt.deferredProxy.push({host:ne,reason:nr}),Dt.warnings.push(`${ne}: publishing DNS-only — ${nr}. 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(Tt&&!Jt){let nr=await ja({address:v,serverName:ne});if(!nr.trusted){Tt=!1;let ir=nr.reason||"origin is not serving a trusted certificate";Dt.deferredProxy.push({host:ne,reason:ir}),Dt.warnings.push(`${ne}: publishing DNS-only for now — the origin does not yet serve a certificate this proxy can verify (${ir}). 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(Tt)Rt.push(ne);let wt=[{type:"A",content:v}];if(tt&&mn(ne))wt.push({type:"AAAA",content:tt});for(let{type:nr,content:ir}of wt){let sr=await S.upsertRecord(b,{name:ne,type:nr,content:ir,ttl:or,proxied:Tt});if(sr.success)Dt.records.push({host:ne,type:nr,content:ir,proxied:Tt});else Dt.warnings.push(`${ne} ${nr} → ${ir} failed: ${sr.message||"unknown provider error"}`)}}if(Rt.length===0){if(we)Dt.warnings.push("No host is proxied yet, so zone settings, cache rules and purge were skipped — they only take effect through the proxy.");return Dt}try{let ne=Ga(fe),Tt=await S.applyZoneSettings(b,ne);Dt.settingsChanged=Tt.changed;for(let wt of Tt.failed)Dt.warnings.push(`zone setting '${wt.id}' could not be applied: ${wt.error}`)}catch(ne){Dt.warnings.push(`zone settings could not be read: ${ne instanceof Error?ne.message:String(ne)}`)}let Nt=Wa(Rt,Ye);if(Nt.length>0){let ne=await S.putManagedPhaseRules(b,"http_request_cache_settings",Nt);if(ne.success)Dt.cacheRules=Nt.length;else Dt.warnings.push(`cache rules could not be written: ${ne.message}`)}if(ft){let ne=Ha(Rt,ft.header,ft.value);if(ne.length>0){let Tt=await S.putManagedPhaseRules(b,"http_request_late_transform",ne);if(Tt.success)Dt.originGuard=!0;else Dt.warnings.push(`origin guard header could not be written: ${Tt.message}. `+"The gateway will reject requests that lack it — disable the guard or grant the token Transform Rules: Edit.")}}if(rt){if(Dt.purged=await S.purgeCache(b,{hosts:Rt}),!Dt.purged)Dt.warnings.push("edge cache purge failed — new content may take until TTL expiry to appear.")}return Dt}var du=(l)=>process.env[l];function tc(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 uu(l,S={}){let b=S.env??du,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 tt=b("CLOUDFLARE_API_TOKEN");if(!tt)return v.push("CLOUDFLARE_API_TOKEN is not set — the Cloudflare CDN cannot be reconciled."),{plan:null,errors:v};let we=l.sites??{},fe=P.frontedHosts?.length?[...new Set(P.frontedHosts.map((Jt)=>Jt.toLowerCase()))]:In(we,{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,ft=new Set(fe.map((Jt)=>tc(Jt,Ye)));if(ft.size>1)return v.push(`Fronted hosts span more than one zone (${[...ft].join(", ")}). A Cloudflare zone is configured as a unit, so run one CDN config per zone.`),{plan:null,errors:v};let rt=P.cloudflare??{},or=P.secret?{header:P.secretHeader??"X-Origin-Verify",value:P.secret}:void 0;return{plan:{zone:[...ft][0],hosts:fe,apiToken:tt,zoneId:rt.zoneId??b("CLOUDFLARE_ZONE_ID"),accountId:rt.accountId??b("CLOUDFLARE_ACCOUNT_ID"),proxied:rt.proxied!==!1,settings:rt.settings??ji,cache:rt.cache,originGuard:or,purge:rt.purgeOnDeploy!==!1,skipOriginProbe:rt.skipOriginProbe===!0},errors:v}}var pu=26214400;var mu=new Set(["/_headers","/_redirects","/_routes.json","/_worker.js"]);class Cl{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 wa(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 wa("POST","/pages/assets/check-missing",`Bearer ${l}`,{hashes:S});return new Set(b)}async upsertHashes(l,S){await wa("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:gu(P.extension)},base64:!0}));await wa("POST","/pages/assets/upload",`Bearer ${l}`,b)}async createDeployment(l,S,b){let P={};for(let tt of S)P[tt.path]=tt.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 Rl(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)),tt=[];for(let Ye=0;Ye<v.length;Ye+=100)tt.push(v.slice(Ye,Ye+100));let we=0;for(let Ye=0;Ye<tt.length;Ye+=4){let ft=tt.slice(Ye,Ye+4);await Promise.all(ft.map((rt)=>this.uploadBatch(b,rt))),we+=ft.reduce((rt,or)=>rt+or.length,0),l.onProgress?.(we,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,ft)=>Ye+ft.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 fu(l,S){return{type:"CNAME",name:l,value:S.endsWith(".pages.dev")?S:`${S}.pages.dev`,ttl:1,proxied:!0}}async function bl(l,S){let{blake3:b}=await import("./chunk-rbem58rx.js").then((m)=>Zm(m.default,1));return(await b(l+S)).slice(0,32)}async function Rl(l){let{readdir:S}=await import("node:fs/promises"),{join:b,relative:P,sep:v}=await import("node:path"),tt=[];async function we(fe){let Ye=await S(fe,{withFileTypes:!0});for(let ft of Ye){let rt=b(fe,ft.name);if(ft.isDirectory()){await we(rt);continue}if(!ft.isFile())continue;let or=`/${P(l,rt).split(v).join("/")}`;if(mu.has(or))continue;let Jt=await Bun.file(rt).bytes();if(Jt.byteLength>26214400)throw Error(`${or} is ${Jt.byteLength} bytes, over the Cloudflare Pages limit of 26214400`);let pr=Buffer.from(Jt).toString("base64"),Dt=ft.name.lastIndexOf("."),Rt=Dt>0?ft.name.slice(Dt+1):"";tt.push({path:or,hash:await bl(pr,Rt),base64:pr,extension:Rt,size:Jt.byteLength})}}return await we(l),tt.sort((fe,Ye)=>fe.path.localeCompare(Ye.path)),tt}function gu(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 wa(l,S,b,P){let v={Authorization:b},tt;if(P instanceof FormData)tt=P;else if(P!==void 0)v["Content-Type"]="application/json",tt=JSON.stringify(P);let we=await fetch(`https://api.cloudflare.com/client/v4${S}`,{method:l,headers:v,body:tt}),fe=await we.text(),Ye;try{Ye=JSON.parse(fe)}catch{throw Error(`Cloudflare Pages API returned ${we.status} with a non-JSON body: ${fe.slice(0,200)}`)}if(!Ye.success){let ft=(Ye.errors??[]).map((rt)=>`${rt.code}: ${rt.message}`).join(", ");throw Error(`Cloudflare Pages API error (${we.status}): ${ft||fe.slice(0,200)}`)}return Ye.result}export{tg as ABTestManager,se as ACMClient,rr as ACMDnsValidator,ls 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,Ri as API_VERSION,ae as AUTHORIZATION_CAPABILITIES,Pd as AUTH_ACTION_TOKEN_TTL_MS,Nd as AUTH_MFA_CHALLENGE_TTL_MS,kd as AUTH_OIDC_TRANSACTION_TTL_MS,Ge 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,iu as AcmeClient,wr as AlertEvaluator,ii as AlertStore,ks as AnomalyConfigStore,id as ApiGateway,i as ApiServiceError,Ta as ApplicationAutoScalingClient,Vs as Arn,D as AssetHasher,U as Auth,bi as AuthenticationStore,di as AutomationApiService,Ei as AutomationIdentityStore,xo as AwsAuroraDataAdapter,Mo as AwsAuroraTransport,ra as AwsDatabaseBackupSource,ar as AwsDriver,_o as AwsElastiCacheDataAdapter,Fo as AwsElastiCacheTransport,Zg as AwsIamCapabilityScanner,aa as AwsInfrastructureBackupSource,Bo as AwsRdsDataAdapter,$o as AwsRdsTransport,pm as AwsRegionalDriver,da as AwsSecretsManagerConfigurationBackend,Ap as AwsSpendTransport,la as AwsSsmConfigurationBackend,Mi as BackupCoordinator,Wp as BackupManager,ea 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,Ys as CHAIN_HEADER,Xi as CLOUDFLARE_MANAGED_RULE_PREFIX,DS as COMMON_CROSS_ACCOUNT_ROLES,Le as CONTROL_PLANE_SCHEMA_VERSION,Gs as Cache,Ks as CanaryManager,pg as CertificateManager,Oh as CloudBlockVolumeDriver,us as CloudDriverFactory,He as CloudError,Tp as CloudFormationBuilder,f as CloudFormationClient,y as CloudFrontClient,Yp as CloudTrailManager,pe as CloudWatchLogsClient,Cl as CloudflarePagesProvider,Et as CloudflareProvider,Uf as CommandHistory,H as Communication,Cr as ComposeApplicationService,_t as ComposeApplicationStore,yt as ComprehendClient,o as Compute,yp as ComputeSpendTransport,zs as ConfigurationError,pa as ConfigurationService,ca as ConfigurationStore,rn as ConnectClient,Lo as ContainerDataAdapter,fg as ContainerRegistryManager,oa as ControlPlaneBackupSource,Jo as ControlPlaneCleanupDriver,Xn as ControlPlaneStore,Ds 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,so as DEFAULT_ATTACK_MODE_HOURS,Vc as DEFAULT_DDOS_THRESHOLDS,wc as DEFAULT_METER_MAPPINGS,vc as DEFAULT_PRICE_BOOK,fi as DEFAULT_RECURSION_LIMITS,An as DEFAULT_RPX_CERTS_DIR,q as DEFAULT_SERVICE_LIMITS,bp as DEFAULT_STATE_DIR,ds as DEFAULT_STATIC_ASSET_EXTENSIONS,Kh as DEFAULT_TELEMETRY_POLICY,tp as DEFAULT_THRESHOLDS,Nh as DEPLOYMENT_QUEUE_KINDS,Xs as DEPTH_HEADER,vr as DETECTABLE_SIGNALS,sl as DIAGNOSTIC_PRESETS,Bg as DLQMonitoringManager,L as DNS,Tg as DNSSECManager,ki as DataServiceLifecycle,ko as DataServiceStore,Ft as Database,dg as DatabaseUserManager,Z as DebugLogger,of as DependencyGraph,Q as Deployment,Tf as DeploymentError,Jp as DisasterRecoveryManager,gn as DnsProviderFactory,jt as DockerDataTransport,To as DockerDiscoveryAdapter,Sr as DockerNamedVolumeDriver,sa as DockerVolumeBackupSource,c as DurableOperationQueue,Cs as DurableQueueWorker,De as DynamoDBClient,gr as EC2Client,Pe as ECRClient,Ke as ECSClient,tr as EFSClient,Ca as ELBv2Client,$h as ENFORCEMENT_ACTIONS,ri as ENFORCEMENT_DESCRIPTIONS,R as ENFORCEMENT_SEVERITY,Pu as ENVIRONMENT_LABEL,nl as EcsRuntimeAdapter,io as EdgeRateLimiter,Je as ElastiCacheClient,m as Email,Gf as EmailAdvanced,Dg as EmailAnalyticsManager,ln as EmailClient,qf as EmailHandlers,Ng as EmailTemplateManager,Uo as EncryptedDataSecretStore,Rf as ErrorCodes,Zt as EventBridgeClient,dm as EventBridgeJobAdapter,ua as ExternalConfigurationBackend,kg as FIFOQueueManager,dp as FOCUS_VERSION,kp as FileCache,Ue as FileSystem,na as FilesystemBackupSource,Ho as FleetService,Qo as FleetStore,e as Fn,Gd as GiteaSourceAdapter,Ud as GithubSourceAdapter,Qd as GitlabSourceAdapter,qp as GlobalResourceManager,bt as GoDaddyProvider,Zp as GuardDutyManager,nt as HOST_SITES_DIR,Nf as HashCache,Qg as HealthCheckManager,Me as HealthCheckRunner,dr as HetznerClient,Ae as HetznerDriver,ge as IAMClient,Ba as IPV6_EXCLUDED_HOST_LABELS,mg as ImageScanningManager,kl as InfrastructureGenerator,gc as InvalidOperationTransitionError,ct as JobLoader,lm as JobProviderReconciler,No as JobService,Do 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,ia as LogicalDatabaseBackupSource,sg as LogsManager,Wf as MANAGED_NODE_VERSIONS,rc as MANAGEMENT_DASHBOARD_SITE,wp as MANAGEMENT_DASHBOARD_SITE_PREFIX,Si as MAX_CONTROL_HOURS,mc as MAX_CONTROL_PLANE_ERROR_BYTES,Ju as MAX_CONTROL_PLANE_JSON_BYTES,Ts as METERS,Lh as METER_KEYS,Mh as MICRO_CENTS,rp as MIN_PROJECTION_CONFIDENCE,Xl as MTA_STS_PORT,Wo as MaintenanceService,Ko as MaintenanceStore,Y as Messaging,ig as MetricsManager,og as MigrationManager,Lp as MockCloudFormation,Mp as MockDynamoDB,$p as MockS3,qs as Monitoring,zp as MultiAccountManager,Hp as MultiRegionManager,_f as MultiStepProgress,A as Network,Hg as NetworkSecurityManager,si as NotificationRouter,ba as OpenSearchClient,it as OptimisticConcurrencyError,Kp as OrganizationManager,pu 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,X as Permissions,Ea as PersonalizeClient,Qe as Phone,Vf as PhoneAdvanced,af as PhoneHandlers,qo as PlacementService,Go as PlacementStore,an as PollyClient,Ne as PorkbunProvider,Ur as PreDeployScanner,Fp as PreviewEnvironmentManager,Ir as PreviewEnvironmentService,$e as PreviewEnvironmentStore,Up as PreviewNotificationService,xf as ProgressBar,rg as ProgressiveDeploymentManager,oo as ProtectionControlStore,by as Pseudo,M as Queue,Yn as QueueCancellationError,_g as QueueManagementManager,Sy as QueuePresets,Ss 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,eo as RecursionGuard,dt as Redirects,Vp as RegionPairManager,jo as RegionService,Vo as RegionStore,Fe as Registry,It as RekognitionClient,lt as ReleaseService,fo as ReleaseStore,um as RemoteBuildService,ag as ReplicaManager,Gg as ResourceManagementManager,J as RetryableOperationError,h as Route53Client,Sa as Route53DomainsClient,me as Route53Provider,wg as Route53ResolverManager,vg as Route53RoutingManager,le as RuntimeOperationService,Ro as RuntimeStreamRegistry,ta as S3BackupDestinationAdapter,a as S3Client,G as S3Error,jd as SECRET_PATTERNS,ap as SENSITIVITY_THRESHOLDS,Xe as SESClient,F as SMS,We as SNSClient,fp as SPEND_CYCLE_SECONDS,Fc as SPEND_GATE_SETTING,Yh as SPEND_LEASE_SETTING,re as SQSClient,ye as SSH_BOOTSTRAP_VERSION,Rn as SSH_PREFLIGHT_SCRIPT,Ie as SSMClient,Ep as STATE_DIR_ENV_VAR,ji as STATIC_SITE_ZONE_SETTINGS,ue as STSClient,cn as SchedulerClient,Ut as Search,Qr as SecretFindingScanner,pi as Secrets,ug as SecretsManager,V as SecretsManagerClient,lg as SecretsRotationManager,I as Security,Br as SecurityHubManager,Fr as SecurityPostureStore,ut as SecurityScannerRunner,gg as SecurityScanningManager,Pg as SenderReputationManager,cm as ServerCronJobAdapter,Oo as ServerDataAdapter,vs as ServerPathVolumeDriver,Ag as ServiceMeshManager,nd as Sftp,xs as SignalSource,jf as SmsAdvanced,Ct as SmsClient,cf as SmsHandlers,Da as SmsVoiceClient,Ao as SourceConnectionStore,qt as SourceProviderError,Uc as SpendCapError,Tr as SpendGate,mp as SpendLoopLease,Ms as SpendNotificationRouter,hp as SpendRunner,Lt as SpendService,ei 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,wo as SystemdDiscoveryAdapter,Zs as TRACE_HEADER,Lf as TaskList,at as TelemetryStore,td as TemplateBuilder,Bp as TemplateCache,St as TextractClient,nn as TranscribeClient,Xt as TranslateClient,hm as TransportDisasterRecoveryDriver,mm as TransportPlatformMaintenanceDriver,Bi as TransportRemoteBuildDriver,Eo as TrivyImageScanner,ho as TsCloudApiError,Ld as TsCloudClient,Xh as URGENT_SPEND_EVENTS,np as USER_VISIBLE_ACTIONS,zo as UnavailableRegionalDriver,ie as UnifiedDnsValidator,As as UnsupportedSchemaVersionError,Pp as ValidationError,er as VoiceClient,Es as VolumeService,xt as VolumeStore,df as Workflow,ng as XRayManager,rC as abTestManager,$d as activateImmutableRelease,jr as addSiteToCloudConfig,gt as ageSeconds,Dc as aggregateDeltas,zu as allocateSitePorts,Ny as analyzeStackDiff,ni as anomalyOptionsForSignal,ao as applyControlsToDdos,Td as applyControlsToRateLimits,Pr as applyMitigationFactor,uh as applyPlan,rs as applyZoneMigration,dd as artifactKey,vi as assertReleaseStrategy,zh as assertSpendAllows,fh as attachConflicts,Ah as attachIsViable,hh as attachPreconditions,Xd as attachProvenanceToRelease,vo 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,go as beginOidcAuthorization,eC as blueGreenManager,PC as bounceComplaintHandler,st as budgetWindow,Aa 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,Hn as buildHostCleanupScript,Wn as buildHostSitePortsScript,ed as buildMailEnv,gs as buildManagementDashboardArtifact,Iu as buildMediaCdnPlan,Jl as buildMtaStsPolicy,$m as buildMtaStsServer,$C as buildNodeRuntimeLayerZip,AC as buildOptimizationManager,Ha as buildOriginGuardRule,Lu as buildPauseWorkersScript,HC as buildPhpRuntimeLayerZip,Uu as buildRestoreScript,z as buildRpxConfig,ke as buildRpxFragmentRefreshScript,gh as buildSetHostnameScript,Mn as buildSiteDeployScript,Fu as buildSnapshotScript,Vu as buildSourceStateScript,Cn as buildSshArgs,Tn as buildSshBootstrapScript,Wa as buildStaticSiteCacheRules,Un as buildStaticSiteDeployScript,Qu as buildTargetStateScript,$u as buildWorkersStateScript,Zd as bytes,tC as canaryManager,Vr as canonicalJson,pt 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,km as cleanupDns01Challenge,fy as clearSigningKeyCache,Io as cloneSourceBinding,_I as cloudConfigSchema,yu as cloudDrivers,XS as cloudTrailManager,Rl as collectAssets,ro as collectPhpAppEntries,Kl as collectServerDnsDomains,Xu as completeComposeVolumeDeletion,mo as completeOidcAuthorization,Xy as composePresets,Is as composeProjectName,ud as composeServerlessAppTemplate,ef as compositeSpendTransport,At as compressBackup,pA as config,cl as connectionGuidance,yC as containerRegistryManager,Dh as controlPlaneDatabaseFile,uc as controlPlaneMigrations,Fy as createApiBackendPreset,bo as createApiV1Handler,CA as createAsgBuildDriver,_l as createBackupQueueHandlers,aA as createCliHandler,k as createCloudDriver,Xa 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,ss as createGoDaddyValidator,QC as createHandlers,sA as createHttpHandler,Qy as createJamstackPreset,al as createJobQueueHandlers,zy as createLaravelPreset,Vy as createMLApiPreset,Il as createMaintenanceQueueHandlers,Au as createMediaAccessToken,Hy as createMicroservicesPreset,UI as createMockAWS,Oy as createNodeJsServerPreset,Ly as createNodeJsServerlessPreset,Wi as createObjectStorageClient,is 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,os as createRoute53Validator,sm as createRuntimeAdapters,oI as createS3Client,IA as createServerBuildDriver,Ky as createServerlessLaravelPreset,$y as createServerlessNodePreset,zl as createSmsInfrastructure,Ve as createSourceAdapter,_y as createStaticSitePreset,jy as createTraditionalWebAppPreset,Cc as createVolumeQueueHandlers,Uy as createWordPressPreset,hi as createZip,uS as crossRegionReferenceManager,Yr as dashboardActions,ps as dashboardCredentialsFile,Gr as dataServiceCapabilities,uC as databaseUserManager,Rd as decodeBase32,Re as decompressBackup,Tm as decryptBackup,co as defaultConfig,Op as defaultLocalConfig,bd as defaultRateLimitRules,ha as deleteStaticSite,ic as deployAllComputeSites,Yo as deployServerlessApp,Nl as deploySite,ms as deploySiteRelease,Hi as deployStaticSite,fa 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,Pa as detectDnsProvider,Lc as detectLatestAnomaly,cI as detectMisconfigurations,Sp as detectServiceRegion,fc as diffCompose,DI as diffTemplates,yo as discoverGitRefs,po as discoverOidcProvider,el as discoverRuntimeInventory,_C as dlqMonitoringManager,Na as dnsProviders,RC as dnssecManager,rm as dockerWorkloads,xi as documentDigest,WS as drManager,xe as driverStatePath,tl as ecsWorkloads,Bt as effectiveCapabilities,NC as emailAnalyticsManager,BC as emailTemplateManager,Ci as encodeBase32,vm as encryptBackup,Yd as ensureDefaultSecurityPolicies,_n as ensureFirewall,Gn as ensureManagementDashboard,On as ensureServer,xn as ensureSshKey,W as escapeSecLang,Nc as evaluateBudget,Pn as evaluatePreflight,$s as evaluateTelemetryAlertRules,ol as eventBridgeScheduleInput,iA as eventToRequest,qh as ewma,hc as exportCompose,es 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,kn 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,In 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,ma as generateExternalDnsStaticSiteTemplate,Om as generateHttpsServerCode,Kd as generateImageSbom,wm 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,Qi 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,js 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,mi 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,no as globMatches,hs as globToRegex,pS as globalResourceManager,ti as governingLimitCents,YS as guardDutyManager,Fs as handleSpendRequest,yn 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,Va as hostCondition,lo as hotp,br as hourBucket,Gh as hourBucketsBetween,fC as imageScanningManager,Li as infraEnvFromOutputs,hd as inspectInvocation,eA as installRecursionFetch,qi as invalidateCache,$g as invocationContext,eS as isLikelyTypo,fn as isLocalDatabase,LI as isLocalDevelopment,Nr as isManagementDashboardSiteName,yy as isNodeCryptoAvailable,Oc as isOperationAllowed,Ls as isQuietHours,Vn as isSafePattern,Jc as isStateDirConfigured,Xc as isStatePath,Dr as isValidCidr,IS as isValidRegion,Zn as isValidTimeZone,Iy as isWebCryptoAvailable,Hr as jobProviderCapability,Ki 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,wi 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,Tu as mediaObjectHeaders,Ns 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,xm as needsRenewal,jC as networkSecurityManager,mt as nextScheduleRuns,he as normalizePublicIpv6,ve as normalizeRuntimeStatus,je as normalizeScheduleExpression,Jg as normalizeSourceEvent,Be as normalizeSshPublicKey,up as normalizeTelemetryPolicy,Kn as occupiedHostPorts,Co as openApiDocument,_s as optionsForSignal,wS as organizationManager,Id as packagePhpApp,_r as packageServerlessApp,bl as pagesAssetHash,fu 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,Jn as parseHostSiteFragments,hy as parseJSONResponse,Dn as parsePreflightFacts,ju as parseSourceDrained,nm as parseSystemdRecords,Hu as parseTargetReady,dc as parseUpstreamPort,Mu as parseWorkersPaused,my as parseXMLResponse,ai as pathTemplate,ac as pendingSteps,Ps as percentOfLimit,lC as performanceManager,Og as phpLayerBuildStage,Xf as phpLayerPackages,Ai as phpRuntimeLayerAssets,cy as planComposeTemplateUpgrade,Bc as planEnforcement,_u as planIsDestructive,Ip as planMitigation,ph as planServerRename,Th as planSiteMove,ts as planZoneMigration,vt as policyTag,Nn as preflightFailed,QI as previewManager,VI as previewNotifications,ht as previewSchedule,Hh as previousBudgetWindow,ws as priceUsage,Fh as priceUsageLines,oh as probeHostRoutes,ja as probeOriginTls,RI as processInChunks,qd as processSourceWebhook,Pi as productionChangeReview,nC as progressiveDeploymentManager,Pc as projectSpend,fd as propagationHeaders,ya as providerEndpoint,fl as publicKeyFingerprint,pn as qualifyName,LC as queueManagementManager,SI as quickHash,Cd as rateLimitHeaders,Ii as rateLimitKey,_e as readDriverState,ah as reconcile,Wl as reconcileAddressRecords,lu as reconcileCloudflareCdn,Zi as reconcileDeclaredRecords,AA as reconcileJobObservation,Mr as reconcileSourceWebhook,Di as recordDashboardHostPosture,mA as recordPreDeploySecretScan,hA as recordSkippedSecretScan,Ad as recursionBlockedResponse,Te as redactRuntimeConfig,qc as redactTelemetryText,oi as redactTelemetryValue,Kr as redeployServerlessApp,gS as regionPairManager,$r as releaseStrategyCapabilities,Kg as releaseTrafficPlan,qn as reloadRpxGateway,zi as remapKey,zr as removeSiteFromCloudConfig,Vd as removeSourceWebhook,ka as removeStaleServerAddressRecords,Ac as renderComposeTemplate,li as renderDdosInstallScript,Kc as renderNftablesRuleset,Ni as renderServerCron,zc as renderSysctlFile,oc as renderWafConfig,jn 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,qe as resolveAuthEncryptionKey,ce as resolveCloudProvider,uu as resolveCloudflareCdnPlan,bf as resolveCredentials,Ui as resolveDashboardAction,nc as resolveDashboardAuth,hf as resolveDashboardDomain,ff as resolveDashboardDomains,Yi as resolveDeclaredRecords,Py as resolveDeployBucketName,O as resolveDeploymentMode,$n as resolveExecStart,Ua as resolveHetznerApiToken,ui as resolveMailService,Jy as resolveManagementDashboardSite,gi as resolveManagementDashboardSites,Ia 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,te as resolveRuntimeInventory,Mt as resolveServerlessAppStackName,rd as resolveServerlessArtifactBucketName,Hs as resolveServerlessAssetBucketName,Js as resolveServerlessRuntime,Ry as resolveSiteBucketName,fs as resolveSiteDeployTarget,u as resolveSiteKind,wy as resolveSiteResourceName,Ty as resolveSiteStackName,wn as resolveSshSettings,d as resolveStatePath,Dy as resolveStorageBucketName,Pt as resolveUiSource,tc 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,yi as ruleMatches,Kf as runBuildHooks,xc as runEnforcement,to as runPhpBuildHooks,ze as runRemoteCommand,de as runtimeId,Fi as sanitizeCloudConfig,s as sanitizeControlPlaneValue,vy as sanitizeName,Bd as sanitizeOidcReturnPath,Hc as saveTelemetryPolicy,Xg as scanForSecrets,pc as scopeContains,ot as scopeKey,La as scpUpload,rS as searchCommands,ys as searchControlPlane,gC as secretsManager,pC as secretsRotationManager,fA as secureContainerRelease,ZS as securityHubManager,hC as securityScanningManager,ee as securityScope,Lr as sendAuthenticationEmail,kC as senderReputationManager,TI as sequence,Ml as serializeDotenv,Ln as serverPublicIpv4,IC as serviceMeshManager,wl as setAttachToInCloudConfig,Wt as setMaintenance,_i as setSitePropertyInCloudConfig,Wc as setStateDir,Nm as setupDns01Challenge,Ra as setupSmsInfrastructure,Ws as sha256,tA as sharedRecursionGuard,Lg as sharedRuntimeLoop,Wu as shipsARelease,Su as signCloudFrontCookies,Cu as signCloudFrontUrl,x as signRequest,Cp as signRequestAsync,Bs as signalDefinition,B as siteInstallBase,zn as siteMoveArchivePath,Ih as siteMoveCertArchivePath,cc as siteUnitGlob,gp as spendNotificationText,Us as spendOpenApiPaths,cr as sshExec,oe as sshExecOrThrow,mS as stackDependencyManager,ga as startLocalDashboardServer,Zh as startSpendLoop,Qs 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,Ti as syncSourceRepositories,bc as synchronizeComposeVolumes,Fl as synchronizeConfiguredConfiguration,Po as synchronizeConfiguredJobs,aC as syntheticsManager,jc as sysctlHardening,im as systemdWorkloads,Jh as telemetryBucketLabel,ci as telemetryCursor,Gc as telemetryEstimatedMonthlyCost,Wh as telemetryPercentile,pp as telemetryPolicyKey,hI as templateCache,Bu as tenantsOf,So as testSourceConnection,Ec as tieredMicroCents,Ga as toCloudflareZoneSettings,Os as toFocusJsonl,Mc as toFocusRecords,sh as toInventoryServer,Vg as totp,uo as totpUri,xu as unaccountedSites,em as unsupportedCapabilities,Bh as unsupportedVolumeCapabilities,yl as updateCompatibility,Sl as updateSiteInCloudConfig,Gi 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,Yl as validateResourceLimits,Ou as validateServerName,Bl as validateTemplate,Zl as validateTemplateSize,xa as verifyAddressRecord,gA as verifyArtifactSignature,bu as verifyMediaAccessToken,jg as verifyTotp,Al as verifyUpdateSignature,ns as verifyZoneParity,bs as volumeCapabilities,Ru as wafEventTelemetry,$a as waitForCloudInit,bn 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,K as wrapCloudInitUserData,et as writeDriverState,iC as xrayManager,gl as zeroCapacity,jh as zeroFill,Tc as zoneOffsetMs,Rs as zonedParts};
|