@stacksjs/ts-cloud 0.16.84 → 0.16.86

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/{chunk-sbm0ft8c.js → chunk-0e56zmps.js} +1 -1
  3. package/dist/bin/{chunk-vr9jcw65.js → chunk-1vw6khps.js} +1 -1
  4. package/dist/bin/{chunk-j1dpdjec.js → chunk-2dbyh1g2.js} +5 -5
  5. package/dist/bin/{chunk-b61yq5rn.js → chunk-4k2x5x3k.js} +1 -1
  6. package/dist/bin/{chunk-c4krzg7x.js → chunk-4mep3m41.js} +1 -1
  7. package/dist/bin/{chunk-7477zgt9.js → chunk-6wvjr3ne.js} +1 -1
  8. package/dist/bin/{chunk-kvwm9z1r.js → chunk-71fa7yed.js} +1 -1
  9. package/dist/bin/{chunk-hkgbbph1.js → chunk-76ekkat8.js} +1 -1
  10. package/dist/bin/chunk-7aqzsbak.js +1 -0
  11. package/dist/bin/{chunk-7yhy2a7h.js → chunk-86w3vzx8.js} +1 -1
  12. package/dist/bin/chunk-8tfqpp9m.js +1 -0
  13. package/dist/bin/{chunk-5xvvxh1f.js → chunk-9bmaq8q7.js} +8 -8
  14. package/dist/bin/chunk-9tt7ahdf.js +1 -0
  15. package/dist/bin/{chunk-08sws53b.js → chunk-bxks81wn.js} +2 -2
  16. package/dist/bin/{chunk-9p6hkb64.js → chunk-bycbwddj.js} +1 -1
  17. package/dist/bin/{chunk-mhmvr5w3.js → chunk-em9swj0k.js} +1 -1
  18. package/dist/bin/{chunk-2bghtp9b.js → chunk-ff3x4pgw.js} +1 -1
  19. package/dist/bin/{chunk-r5zsebn5.js → chunk-g9820x34.js} +28 -28
  20. package/dist/bin/{chunk-8dzqjsz1.js → chunk-mwprtzxp.js} +1 -1
  21. package/dist/bin/chunk-ndjpa2tq.js +1 -0
  22. package/dist/bin/{chunk-yd2vnd4y.js → chunk-ndvma07s.js} +1 -1
  23. package/dist/bin/{chunk-ydbvafmk.js → chunk-nemj07g1.js} +1 -1
  24. package/dist/bin/{chunk-rpsnnr53.js → chunk-nfxxr6g7.js} +1 -1
  25. package/dist/bin/{chunk-f1jkvaxm.js → chunk-v1a0b9yq.js} +8 -8
  26. package/dist/bin/{chunk-8erhr0vh.js → chunk-v3trt4q1.js} +2 -2
  27. package/dist/bin/{chunk-cbb6wqqz.js → chunk-xkp5r2ye.js} +90 -90
  28. package/dist/bin/{chunk-eqw1dk00.js → chunk-xycxw00z.js} +7 -7
  29. package/dist/bin/cli.js +147 -147
  30. package/dist/bin/dashboard-server.js +1 -1
  31. package/dist/chunk-03gf4e58.js +1 -0
  32. package/dist/{chunk-pbkev5pe.js → chunk-2yqvgbmn.js} +39 -39
  33. package/dist/{chunk-q61qcpp4.js → chunk-3bvhthfb.js} +14 -14
  34. package/dist/{chunk-42vtybcm.js → chunk-4pztf7ws.js} +3 -3
  35. package/dist/{chunk-rq650jaz.js → chunk-5t92a838.js} +10 -10
  36. package/dist/{chunk-18dqxyz5.js → chunk-8kn7rszy.js} +1 -1
  37. package/dist/{chunk-8drf81qf.js → chunk-ax320pn8.js} +1 -1
  38. package/dist/{chunk-dvw5dy32.js → chunk-cq079p4a.js} +4 -4
  39. package/dist/{chunk-pk8ppz98.js → chunk-e75dvdqf.js} +2 -2
  40. package/dist/{chunk-0f23y8ba.js → chunk-fpad8xw9.js} +1 -1
  41. package/dist/{chunk-cz4dw2hk.js → chunk-gdw52mn4.js} +2 -2
  42. package/dist/{chunk-bhbv9qqn.js → chunk-gpgmp9dt.js} +1 -1
  43. package/dist/{chunk-kcb203be.js → chunk-m35z9vyn.js} +1 -1
  44. package/dist/{chunk-tb5hy7rm.js → chunk-ncet7ba7.js} +1 -1
  45. package/dist/{chunk-7ea0q5tg.js → chunk-py8dq1ey.js} +4 -4
  46. package/dist/{chunk-rec9q5vz.js → chunk-s56rah0t.js} +99 -99
  47. package/dist/{chunk-xyhh44eq.js → chunk-tr54e9c0.js} +1 -1
  48. package/dist/deploy/index.js +1 -1
  49. package/dist/dns/index.js +1 -1
  50. package/dist/drivers/hetzner/client.d.ts +6 -0
  51. package/dist/drivers/hetzner/driver.d.ts +1 -0
  52. package/dist/drivers/hetzner/reverse-dns.d.ts +6 -0
  53. package/dist/drivers/index.js +1 -1
  54. package/dist/index.js +16 -16
  55. package/dist/mail/index.js +1 -1
  56. package/dist/operations/index.js +1 -1
  57. package/dist/protection/index.js +1 -1
  58. package/dist/spend/index.js +1 -1
  59. package/dist/ui/404.html +1 -1
  60. package/dist/ui/accept-invitation.html +1 -1
  61. package/dist/ui/access-denied.html +1 -1
  62. package/dist/ui/account/automation.html +5 -5
  63. package/dist/ui/account/security.html +2 -2
  64. package/dist/ui/applications/compose.html +6 -6
  65. package/dist/ui/applications/new.html +2 -2
  66. package/dist/ui/data/backups.html +6 -6
  67. package/dist/ui/data/services.html +6 -6
  68. package/dist/ui/data/volumes.html +6 -6
  69. package/dist/ui/index.html +6 -6
  70. package/dist/ui/infrastructure/topology.html +5 -5
  71. package/dist/ui/integrations.html +1 -1
  72. package/dist/ui/operations/alerts.html +6 -6
  73. package/dist/ui/operations/configuration.html +6 -6
  74. package/dist/ui/operations/jobs.html +6 -6
  75. package/dist/ui/operations/maintenance.html +5 -5
  76. package/dist/ui/operations/observability.html +6 -6
  77. package/dist/ui/operations/previews.html +6 -6
  78. package/dist/ui/operations/queue.html +6 -6
  79. package/dist/ui/operations/regions.html +5 -5
  80. package/dist/ui/operations/releases.html +6 -6
  81. package/dist/ui/operations/spend.html +5 -5
  82. package/dist/ui/operations/workloads.html +6 -6
  83. package/dist/ui/security.html +1 -1
  84. package/dist/ui/server/actions.html +6 -6
  85. package/dist/ui/server/activity.html +2 -2
  86. package/dist/ui/server/capacity.html +5 -5
  87. package/dist/ui/server/database.html +5 -5
  88. package/dist/ui/server/deployments.html +6 -6
  89. package/dist/ui/server/diagnostics.html +2 -2
  90. package/dist/ui/server/firewall.html +6 -6
  91. package/dist/ui/server/fleet.html +6 -6
  92. package/dist/ui/server/logs.html +6 -6
  93. package/dist/ui/server/metrics.html +6 -6
  94. package/dist/ui/server/security.html +2 -2
  95. package/dist/ui/server/services.html +1 -1
  96. package/dist/ui/server/sites.html +6 -6
  97. package/dist/ui/server/ssh-keys.html +6 -6
  98. package/dist/ui/server/team.html +6 -6
  99. package/dist/ui/server/terminal.html +2 -2
  100. package/dist/ui/serverless/alarms.html +6 -6
  101. package/dist/ui/serverless/assets.html +2 -2
  102. package/dist/ui/serverless/cost.html +2 -2
  103. package/dist/ui/serverless/data.html +6 -6
  104. package/dist/ui/serverless/deployments.html +2 -2
  105. package/dist/ui/serverless/firewall.html +1 -1
  106. package/dist/ui/serverless/functions.html +6 -6
  107. package/dist/ui/serverless/logs.html +6 -6
  108. package/dist/ui/serverless/metrics.html +2 -2
  109. package/dist/ui/serverless/queues.html +6 -6
  110. package/dist/ui/serverless/secrets.html +6 -6
  111. package/dist/ui/serverless/traces.html +6 -6
  112. package/dist/ui/serverless.html +5 -5
  113. package/package.json +3 -3
  114. package/dist/bin/chunk-1nnt30xt.js +0 -1
  115. package/dist/bin/chunk-24g6snzv.js +0 -1
  116. package/dist/bin/chunk-4a9p7fd0.js +0 -1
  117. package/dist/bin/chunk-q82s4yzg.js +0 -1
  118. package/dist/chunk-2ntc2qz2.js +0 -1
package/dist/index.js CHANGED
@@ -1,17 +1,17 @@
1
- import{$I,MI,rl,Sm,nl,il,dn,Q,l,sl,Im,K,ol,p,ry,b,Ze,Ji,ln,w,ce,al,ny,r,t,FI,UI,m,QI,HI,GI,VI,qI,lr,cl,Xi,iy,jI,zI,xe,et,dl,bm,Cm,KI,Em,vm,Tm,Ho,ll,de,un,kt,Go,Nt,Ce,sy,ul,Vo,wm,Rm,Dm,Pm,gl,WI,W,E,oy,ay,km,a,S,tt,f,Nm,rt,J,Bt,JI,Bm,X,pl,Oe,ur,qo,le,ml,ue,cy,jo,Y,Z,_,Yi,D,gr,xt,ee,e,gn,XI,xm,fl,YI,ZI,eb,tb,hl,rb,nb,ib,sb,ob,ab,cb,db,lb,ub,gb,pb,dy,ly,uy,gy,py,my,fy,pr,Om,_m,mr,Zi,mb,Lm,fb,hb,pn,Ab,yb,Sb,Ib,bb,Cb,hy,Ay,yy,Sy,Iy,es,Eb,zo,by,$m,V,Cy,nt,Ko,Ot,Ey,Mm,vy,Ty,wy,Fm,q,vb,Tb,wb,Rb,Ry,Db,te,Pb,kb,Nb,Al,yl,Dy,Um,Qm,Bb,xb,Ob,_b,Lb,Py,Sl,$b,Mb,Fb,Ub,Qb,ky,Ny,Hb,Gb,Vb,qb,jb,zb,Kb,By,Wb,Hm,Il,Jb,Xb,Yb,Zb,Gm,Vm,qm,eC,bl,xy,Oy,_y,Ly,Cl,$y,tC,rC,nC,iC,sC,oC,aC,My,Fy,Uy,Qy,jm,cC,dC,lC,uC,gC,pC,mC,fC,hC,Hy,Gy,Vy,qy,AC,yC,zm,SC,Km,Wm,Jm,Xm,IC,bC,CC,EC,_e,ts,vC,TC,wC,RC,DC,PC,kC,NC,jy,BC,xC,Ym,Zm,OC,_C,zy,LC,$C,MC,FC,UC,QC,HC,GC,VC,qC,jC,zC,KC,WC,JC,XC,YC,ZC,eE,tE,rE,El,Ky,vl,Wy,Tl,Jy,wl,Xy,Rl,Yy,fr,Zy,Dl,eS,rs,tS,Pl,rS,kl,nS,ef,nE,tf,iE,Nl,iS,hr,sS,rf,sE,Bl,oS,nf,oE,sf,aE,of,cE,xl,aS,af,dE,cf,lE,df,uE,lf,gE,Ol,cS,_l,dS,uf,pE,gf,mE,pf,fE,mf,hE,ff,AE,hf,yE,Ll,lS,Af,SE,yf,IE,Sf,bE,If,CE,bf,EE,Cf,vE,Ef,vf,Tf,wf,Rf,TE,Df,wE,Pf,RE,kf,DE,it,Nf,uS,Wo,$l,mn,gS,ns,Ar,Ml,Fl,pS,mS,Ul,Bf,Ql,xf,PE,kE,Jo,Xo,Yo,Hl,fn,Gl,Vl,is,Zo,ea,Of,fS,hS,AS,NE,_f,Lf,BE,yS,$f,SS,IS,bS,xE,Mf,hn,ql,Ff,OE,CS,ta,ra,jl,Uf,_E,zl,ES,Qf,LE,Hf,$E,Gf,ME}from"./chunk-q61qcpp4.js";import{Kl,k,Wl,na,vS,Vf,TS,wS,RS,DS,PS,kS,NS,BS}from"./chunk-928z0h9b.js";import{da,qf,nu,LS,cs,iu,la,jf,zf,yn,ua,su,ot,ou,au,cu,ds,Sn,Kf,at,du,ga,pa,ma,lu,uu,gu,ls,fa,pu,In,us,ha,_t,Wf,mu,fu,Jf,hu,Aa,yr,Au,yu,Su,Iu,ct,Xf,bu,Sr,ya,Sa,Ia,gs,ps,bn,Cu,ms,ba,Ca,Cn,Eu,En,Yf,Zf,Lt,vn,Ea,eh,vu,Tu,va,wu,Ru,Du,$S,ge,Pu,MS,FS,fs,hs,US,Ee,th,$t,Le,$e,Mt,ku,Nu,Bu,xu,rh,nh,Ta,ih,sh,wa,Ou,_u,oh,pe,ah,Lu,ve,Ra,dt,Ft,Ut,Tn,As,$u,QS,ch,dh,lh,uh,Da,Pa,Mu,ka,wn,Na,Fu,ys,Uu,Ba,xa,Oa,_a,La,$a,Ma,Fa,Qu,Ir,Ua,Hu,Rn,Gu,Qa,Ha,Vu,br,Ga,Va,gh,HS,Ss,GS,VS,qS,qa,ja,qu,ph,za,Dn,ju,Is,zu,Ku,Wu,Ka,mh,Wa,Ju,fh,Ja,hh,Pn,kn,Xu,bs,ng,ag,cg,dg,lg,ug,Es,Cr,Ya,Nn,Bn,Er,lt,vh,ec,Th,wh,mg,tc,Ts,fg,rc,Ht,Fe,hg,nc,ic,Ag,sc,oc,ac,cc,yg,Sg,On,dc,lc,uc,gc,Ig,ws,_n,Rs,pc}from"./chunk-pbkev5pe.js";import{ru}from"./chunk-fjs0wgyw.js";import{U,Kr,Ad,Ao,d,zp,Kp}from"./chunk-xyhh44eq.js";import{Tt,hd,xi,Oi,_i,jp}from"./chunk-0f23y8ba.js";import{rA,nA,iA,Rp,Dp,Pp,sA,kp,Np,oA,aA,Bp,cA,dA,md,xp,lA,uA,Op,gA,pA,mA,fA,hA,AA,yA,Bi,fd,_p,Lp,$p,Mp,Fp,Up,Qp,Hp,Gp,Vp,qp,SA,IA,bA,CA,EA,vA,TA}from"./chunk-8drf81qf.js";import{Je,yd,be,nr,Sd,x,ir,wt,Id,yo,DA,Wp,bd,s,Li,So,Wr,Cd,Ed,Jr,PA,vd,xI,OI,Io,_I,LI,Td,wd,$i,bo,ae,c,Co,Xe,Xr,kA,NA,Rd,BA,Eo,xA,OA,vo,Dd,Yr,To,_A,sr,Pd,Jp,or,Zr,LA,wo,$A,O,MA,kd,Xp,Ro,FA,UA,QA,Nd,Mi,Do,Bd,ar,Rt,HA,en,GA,xd,Yp,Zp,Po,Od,_d,Dt,em,Fi,Ld,ko,tn,tm,Ui,$d,Md,Qi,rm,Fd,Ud,Qd,Hd,No,nm,im,VA,sm,Gd,Hi,om,am,Bo,rn,xo,Oo,_o,Vd,cm,qd,Lo,qA,cr,jA,jd,nn,zd,zA,Kd,dm,Gi,sn,$o,Vi,Ye,KA,lm,um,dr,Wd,Jd,Xd,qi,ji,zi,WA,JA,Pt,Mo,XA,on,gm,Fo,YA,pm,mm,fm,ZA,hm,Am,ey,i,ty,Ki,Uo,Qo}from"./chunk-rq650jaz.js";import{n}from"./chunk-m9szynnf.js";import{Re,mt,zn}from"./chunk-cz4dw2hk.js";import{o}from"./chunk-c8kf2268.js";import{Te,Os,_s,Eg,yc,Sc,Ls,Ic,ut,re,gt,me,T,we,Un,bc,Ue,Cc,Qn,Hn,Gn,Gt,Vt,qt,Vn,Tr,Ec,wr,Rr,pt,qn,Tc,jt,Dr,jn,Rc,Dg,Pg,Dc,Pr}from"./chunk-7ea0q5tg.js";import{ft,Ae,Ge,kg,zt,kc,Nc,Kt,H,Kn,Wt,Jt,Wn,Us,Qs,kr,Nr,Jn,Br,Hs,Gs,Vs,qs,ie,js,zs,Ks,Ws,ye,Js,Xs,Ys,N,Bc,Xn,xc,Se,xr}from"./chunk-pk8ppz98.js";import{ne}from"./chunk-nftqsker.js";import{Ng,Oc,Bg,De,_c,Yn,xg,Lc,Og,_g,Fh,_r,eo,M,$r,ei,ti,Mr,Ur,ri,to,ni,ii,si,oi,ci,Qr,Ie,Fc,At,Uc,Hr,Gc,qe,se,je,ze,St,ui,gi,Pe,bt,ke,mi,fi,hi,Ai,yi,Si,Ii,Gr,F,so,ap,Yc,Ci,Ei,vi,Ti,id,ao,sd,tr,Ri,co,lo,od,Di,ad}from"./chunk-rec9q5vz.js";import{go,mo,fo,B,Ne}from"./chunk-bhbv9qqn.js";import{Jl,ia,ss,os,sa,Xl,Yl,as,oa,aa,eu,tu,ca}from"./chunk-jx1zz1pw.js";import{mc,Ln,$n,Ds,Ps,ks,Ns,fc,hc}from"./chunk-dvw5dy32.js";import{Ac}from"./chunk-kcb203be.js";import{Pc,Qe,I}from"./chunk-z56sccfh.js";import{He}from"./chunk-fdf181e6.js";import{C}from"./chunk-c71hhcsb.js";import{oe,Pi,uo,cd,ki,bp}from"./chunk-42vtybcm.js";import{qr,Be}from"./chunk-vq8bejep.js";import{A}from"./chunk-tmp2ym80.js";import{Yd,an,Zd,el,tl,Wi,ym,cn}from"./chunk-84z2a1xn.js";import{xS,st}from"./chunk-9pwvnh3f.js";var jh="https://api.machines.dev/v1";class Cs extends Error{status;path;constructor(u,g,h){super(u);this.status=g;this.path=h;this.name="FlyApiError"}}function Qc(u){let g=u.ip.includes(":");if(g&&u.ip.startsWith("fdaa:"))return"private_v6";if(u.shared)return"shared_v4";return g?"v6":"v4"}class hp{token;fetch;constructor(u){if(!u.token)throw Error("Fly.io needs an API token: set FLY_API_TOKEN (`fly tokens create deploy` makes one scoped to an app).");this.token=u.token,this.fetch=u.fetch??fetch}async rest(u,g,h={}){let y=new URL(`https://api.machines.dev/v1${g}`);for(let[L,z]of Object.entries(h.query??{}))y.searchParams.set(L,z);let R=await this.fetch(y,{method:u,headers:{Authorization:`Bearer ${this.token}`,...h.body!==void 0?{"Content-Type":"application/json"}:{},...h.headers},body:h.body===void 0?void 0:JSON.stringify(h.body)});if(R.status===404&&h.notFound==="null")return null;let v=await R.text(),P=v?yp(v):void 0;if(!R.ok){let L=typeof P==="object"&&P&&"error"in P?String(P.error):v||R.statusText;throw new Cs(`Fly.io ${u} ${g} failed (${R.status}): ${L}`,R.status,g)}return P}getApp(u){return this.rest("GET",`/apps/${encodeURIComponent(u)}`,{notFound:"null"})}createApp(u,g){return this.rest("POST","/apps",{body:{app_name:u,org_slug:g}})}async listMachines(u){return await this.rest("GET",`/apps/${encodeURIComponent(u)}/machines`)??[]}createMachine(u,g){return this.rest("POST",`/apps/${encodeURIComponent(u)}/machines`,{body:g})}updateMachine(u,g,h,y){return this.rest("POST",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(g)}`,{body:h,headers:{"fly-machine-lease-nonce":y}})}async acquireLease(u,g,h=120){let R=(await this.rest("POST",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(g)}/lease`,{body:{ttl:h}})).data?.nonce;if(!R)throw new Cs(`Fly.io gave no lease nonce for Machine ${g}`,200,`/machines/${g}/lease`);return R}async releaseLease(u,g,h){await this.rest("DELETE",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(g)}/lease`,{headers:{"fly-machine-lease-nonce":h}})}async waitForState(u,g,h,y={}){await this.rest("GET",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(g)}/wait`,{query:{state:h,timeout:String(y.timeoutSeconds??60),...y.instanceId?{instance_id:y.instanceId}:{}}})}async listVolumes(u){return await this.rest("GET",`/apps/${encodeURIComponent(u)}/volumes`)??[]}createVolume(u,g){return this.rest("POST",`/apps/${encodeURIComponent(u)}/volumes`,{body:{...g,encrypted:!0}})}async setSecrets(u,g){return(await this.rest("POST",`/apps/${encodeURIComponent(u)}/secrets`,{body:{values:g}})).version}async listIpAssignments(u){return(await this.rest("GET",`/apps/${encodeURIComponent(u)}/ip_assignments`)).ips??[]}async assignIp(u,g){let h=await this.rest("POST",`/apps/${encodeURIComponent(u)}/ip_assignments`,{body:{type:g}});if(!h.ip)throw new Cs(`Fly.io assigned no ${g} address to ${u}`,200,`/apps/${u}/ip_assignments`);return{ip:h.ip,shared:h.shared??g==="shared_v4",region:h.region}}async requestCertificate(u,g){return this.rest("POST",`/apps/${encodeURIComponent(u)}/certificates/acme`,{body:{hostname:g}})}}function yp(u){try{return JSON.parse(u)}catch{return}}var vc="ts-cloud-role";function Zh(u,g){let h=u.fly??{},y=h.app??`${u.project.slug}-${g.environment}`;if(!/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(y))throw Error(`"${y}" is not a valid Fly app name: lowercase letters, digits and dashes, 3 to 63 characters.`);let R=h.internalPort??3000,v=h.count??1;if(!Number.isInteger(v)||v<1)throw Error(`fly.count must be a whole number of at least 1, got ${v}.`);return{app:y,org:h.org??"personal",image:g.image,regions:h.regions?.length?h.regions:["iad"],count:v,internalPort:R,healthPath:h.healthPath??"/",vm:{cpuKind:h.vm?.cpuKind??"shared",cpus:h.vm?.cpus??1,memoryMb:h.vm?.memoryMb??512},...h.volume?{volume:{name:h.volume.name??"data",sizeGb:h.volume.sizeGb,path:h.volume.path}}:{},autoStop:h.autoStop??!1,env:{...g.env,PORT:String(R)},secrets:g.secrets??{},hostnames:h.hostnames??[],release:g.release}}function Cp(u){return{image:u.image,env:u.env,guest:{cpu_kind:u.vm.cpuKind,cpus:u.vm.cpus,memory_mb:u.vm.memoryMb},services:[{protocol:"tcp",internal_port:u.internalPort,ports:[{port:80,handlers:["http"],force_https:!0},{port:443,handlers:["tls","http"]}],autostop:u.autoStop?"stop":"off",autostart:!0,...u.autoStop?{min_machines_running:0}:{},checks:[{type:"http",method:"GET",path:u.healthPath,interval:"15s",timeout:"5s",grace_period:"10s"}]}],restart:{policy:"on-failure",max_retries:10},metadata:{[vc]:"app","ts-cloud-release":u.release}}}async function Jh(u,g,h=()=>{}){let y=!1;if(!await u.getApp(g.app))h(`Creating Fly app ${g.app} in ${g.org}`),await u.createApp(g.app,g.org),y=!0;let R;if(Object.keys(g.secrets).length>0)R=await u.setSecrets(g.app,g.secrets),h(`Set ${Object.keys(g.secrets).length} secret(s) (version ${R})`);let v=await u.listIpAssignments(g.app),P=new Set(v.map(Qc));if(!P.has("v6"))v.push(await u.assignIp(g.app,"v6")),h("Assigned a dedicated IPv6");if(!P.has("v4")&&!P.has("shared_v4"))v.push(await u.assignIp(g.app,"shared_v4")),h("Assigned a shared IPv4");let L=Cp(g),z=(await u.listMachines(g.app)).filter((Me)=>{let We=Me.config?.metadata??{};if(We[vc])return We[vc]==="app";return!We.fly_process_group||We.fly_process_group==="app"}),he=g.volume?await u.listVolumes(g.app):[],fe=[],Ct=[],It=new Set;for(let Me of g.regions){let We=z.filter((j)=>j.region===Me).sort((j,ht)=>j.id.localeCompare(ht.id));for(let j=0;j<g.count;j++){let ht=We[j];if(ht){It.add(ht.id),await Sp(u,g.app,ht,L,R),Ct.push(ht.id),h(`Updated ${ht.id} (${Me}) to ${g.image}`);continue}let G=g.volume?[{volume:(await Ap(u,g,Me,he)).id,path:g.volume.path}]:void 0,Ke=await u.createMachine(g.app,{region:Me,name:`${g.app}-${Me}-${j+1}`,config:{...L,...G?{mounts:G}:{}},...R!==void 0?{min_secrets_version:R}:{}});await u.waitForState(g.app,Ke.id,"started",{instanceId:Ke.instance_id}),fe.push(Ke.id),h(`Created ${Ke.id} in ${Me}`)}}let Ve=[];for(let Me of g.hostnames)Ve.push(await u.requestCertificate(g.app,Me));return{app:g.app,url:`https://${g.app}.fly.dev`,createdApp:y,created:fe,updated:Ct,untouched:z.filter((Me)=>!It.has(Me.id)).map((Me)=>Me.id),ips:v,certificates:Ve}}async function Sp(u,g,h,y,R){let v=await u.acquireLease(g,h.id);try{let P=await u.updateMachine(g,h.id,{config:{...y,...h.config?.mounts?.length?{mounts:h.config.mounts}:{}},...R!==void 0?{min_secrets_version:R}:{}},v);await u.waitForState(g,h.id,"started",{instanceId:P.instance_id})}finally{await u.releaseLease(g,h.id,v)}}async function Ap(u,g,h,y){let R=y.find((P)=>P.region===h&&P.name===g.volume.name&&!P.attached_machine_id);if(R)return R.attached_machine_id="pending",R;let v=await u.createVolume(g.app,{name:g.volume.name,region:h,size_gb:g.volume.sizeGb});return y.push({...v,attached_machine_id:"pending"}),v}import{createHmac as Zl,createSign as Tp,timingSafeEqual as wp}from"node:crypto";function bi(u){let g=u instanceof Date?u.getTime():u;if(!Number.isFinite(g))throw TypeError("Media access timestamp must be finite");return Math.floor(g/1000)}function Zu(u){return Buffer.from(u).toString("base64").replaceAll("+","-").replaceAll("=","_").replaceAll("/","~")}function Ip(u){return Buffer.from(u).toString("base64url")}function Yu(u,g=!1){if(!u||/[\r\n]/.test(u))throw TypeError("Media resource is invalid");let h=g?u.replaceAll("*","wildcard"):u,y=new URL(h);if(!["http:","https:"].includes(y.protocol))throw TypeError("Media resource must use HTTP or HTTPS");if(!g&&u.includes("*"))throw TypeError("Canned policies cannot contain wildcards")}function ed(u,g){let h=Tp("RSA-SHA1");return h.update(u),h.end(),Zu(h.sign(g))}function td(u){Yu(u.resource,!0);let h={DateLessThan:{"AWS:EpochTime":bi(u.expiresAt)}};if(u.activeAt!==void 0)h.DateGreaterThan={"AWS:EpochTime":bi(u.activeAt)};if(u.ipAddress)h.IpAddress={"AWS:SourceIp":u.ipAddress};return JSON.stringify({Statement:[{Resource:u.resource,Condition:h}]})}function WS(u,g,h){Yu(u);let y=bi(g),R=u.includes("?")?"&":"?",v=td({resource:u,expiresAt:g}),P=ed(v,h.privateKey);return`${u}${R}Expires=${y}&Signature=${encodeURIComponent(P)}&Key-Pair-Id=${encodeURIComponent(h.keyPairId)}`}function zS(u,g){let h=td(u);return{"CloudFront-Key-Pair-Id":g.keyPairId,"CloudFront-Policy":Zu(Buffer.from(h)),"CloudFront-Signature":ed(h,g.privateKey)}}function jS(u){if(!u.resource||/[\r\n]/.test(u.resource))throw TypeError("Media resource is invalid");let g=Ip(Buffer.from(JSON.stringify({resource:u.resource,expiresAt:bi(u.expiresAt),...u.keyId?{keyId:u.keyId}:{},...u.audience?{audience:u.audience}:{}}))),h=Zl("sha256",u.secret).update(g).digest("base64url");return`${g}.${h}`}function KS(u,g){let[h,y,R]=u.split(".");if(!h||!y||R)return null;let v=Zl("sha256",g.secret).update(h).digest(),P;try{P=Buffer.from(y,"base64url")}catch{return null}if(v.length!==P.length||!wp(v,P))return null;try{let L=JSON.parse(Buffer.from(h,"base64url").toString("utf8")),z=bi(g.now??Date.now());if(!L.resource||!Number.isSafeInteger(L.expiresAt)||L.expiresAt<=z)return null;if(g.resource&&L.resource!==g.resource)return null;if(g.audience&&L.audience!==g.audience)return null;return L}catch{return null}}function ZS(u,g=!1){let h=new URL(u,"https://media.invalid").pathname.toLowerCase(),y=/\.(?:m3u8|mpd|vtt|json)$/.test(h),R=/\.(?:key|license)$/.test(h)||h.includes("/keys/")||h.includes("/licenses/");return{"Accept-Ranges":"bytes","Cache-Control":g&&(y||R)?"private, no-store":y?"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 JS(u){if(!/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(u.bucket))throw TypeError("Media bucket is invalid");if(!/^[a-z0-9-]+$/.test(u.region))throw TypeError("Media bucket region is invalid");let g=u.prefix?`/${u.prefix.replace(/^\/+|\/+$/g,"")}`:"",h=u.protected??!1,y="public, max-age=31536000, immutable",R=h?"private, no-store":"public, max-age=5, s-maxage=30, stale-while-revalidate=30";return{originDomain:`${u.bucket}.s3.${u.region}.amazonaws.com`,originPath:g,domain:u.domain,trustedKeyGroupIds:[...new Set(u.trustedKeyGroupIds??[])],behaviors:[{pathPattern:"*.m3u8",cacheControl:R,compress:!0,signed:h},{pathPattern:"*.mpd",cacheControl:R,compress:!0,signed:h},{pathPattern:"*.vtt",cacheControl:R,compress:!0,signed:h},{pathPattern:"*",cacheControl:y,compress:!1,signed:h}],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 vp{builder;config;environment;mergedConfig;serverEipLogicalIds=new Map;storageFailoverReplicas=[];constructor(u){this.config=u.config,this.environment=u.environment,this.builder=new al(`${this.config.project.name} - ${this.environment}`),this.mergedConfig=this.mergeEnvironmentConfig()}mergeEnvironmentConfig(){let g=this.config.environments[this.environment]?.infrastructure;if(!g)return this.config;return{...this.config,infrastructure:{...this.config.infrastructure,...g,compute:{...this.config.infrastructure?.compute,...g.compute},storage:{...this.config.infrastructure?.storage,...g.storage},functions:{...this.config.infrastructure?.functions,...g.functions},servers:{...this.config.infrastructure?.servers,...g.servers},databases:{...this.config.infrastructure?.databases,...g.databases},cdn:{...this.config.infrastructure?.cdn,...g.cdn},sftp:g.sftp??this.config.infrastructure?.sftp,queues:{...this.config.infrastructure?.queues,...g.queues},redirects:{...this.config.infrastructure?.redirects,...g.redirects},realtime:{...this.config.infrastructure?.realtime,...g.realtime},cache:{...this.config.infrastructure?.cache,...g.cache},fileSystem:{...this.config.infrastructure?.fileSystem,...g.fileSystem},email:{...this.config.infrastructure?.email,...g.email},search:{...this.config.infrastructure?.search,...g.search},ai:{...this.config.infrastructure?.ai,...g.ai}}}}shouldDeploy(u){if(u.environments&&!u.environments.includes(this.environment))return!1;if(u.requiresFeatures){let g=this.config.features||{};if(!u.requiresFeatures.every((y)=>g[y]===!0))return!1}if(u.regions){let g=this.config.environments[this.environment]?.region||this.config.project.region;if(!u.regions.includes(g))return!1}if(u.condition&&typeof u.condition==="function")return u.condition(this.config,this.environment);return!0}resolveApiOriginPort(){let u=this.mergedConfig.infrastructure?.api?.port??this.mergedConfig.ports?.api,g=Number(u||3008);return Number.isFinite(g)&&g>0?g: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(u,g){return u==="public"||g.routeCompute===!0}storageBucketName(u,g,h){return this.mergedConfig.infrastructure?.storage?.[h]?.bucket??`${u}-${g}-${h}`}fileSystemLogicalId(u,g,h){return t(r({slug:`${u}-${h}`,environment:g,resourceType:"efs"}))}resolveSftpStorage(u,g,h){let y=u.storage;if(y?.type==="efs"&&y.fileSystem){if(!this.mergedConfig.infrastructure?.fileSystem?.[y.fileSystem])throw Error(`sftp: storage.fileSystem "${y.fileSystem}" is not defined in infrastructure.fileSystem`);return{type:"efs",fileSystemId:{Ref:this.fileSystemLogicalId(g,h,y.fileSystem)},posixProfile:y.posixProfile}}if(y?.type==="s3"&&y.storageBucket){if(!this.mergedConfig.infrastructure?.storage?.[y.storageBucket])throw Error(`sftp: storage.storageBucket "${y.storageBucket}" is not defined in infrastructure.storage`);return{type:"s3",bucket:this.storageBucketName(g,h,y.storageBucket)}}return}resolveComputeCachePathPatterns(u){if(u&&u.length>0)return u;return this.defaultComputeCachePathPatterns()}createComputeCacheBehavior(u,g){return{PathPattern:u,TargetOriginId:g,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(u,g,h,y,R,v){let P=this.serverEipLogicalIds.get("app"),L=this.serverEipLogicalIds.get("appInstance");if(!P)return;let z=`EC2-${y}-${R}-api`,he=this.mergedConfig.infrastructure?.servers?.app?.region||this.mergedConfig.project?.region||"us-east-1",fe=he==="us-east-1"?".compute-1.amazonaws.com":`.${he}.compute.amazonaws.com`,Ct={"Fn::Join":["",["ec2-",{"Fn::Join":["-",{"Fn::Split":[".",{Ref:P}]}]},fe]]},It=this.resolveApiOriginPort();if(u.push({Id:z,DomainName:Ct,CustomOriginConfig:{HTTPPort:It,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}),h.push(P),L)h.push(L);for(let Ve of v)g.push(this.createComputeCacheBehavior(Ve,z))}buildCaddyfile(u){let g=u.filter(([,R])=>typeof R.domain==="string"&&R.domain&&typeof R.port==="number");if(g.length===0)return;let h=new Map;for(let[,R]of g){let v=h.get(R.domain)??[];v.push({port:R.port,path:R.path}),h.set(R.domain,v)}let y=[];for(let[R,v]of h){let L=[...v].sort((z,he)=>{let fe=!z.path||z.path==="/",Ct=!he.path||he.path==="/";if(fe&&!Ct)return 1;if(!fe&&Ct)return-1;return(he.path?.length??0)-(z.path?.length??0)}).map((z)=>{let he=!z.path||z.path==="/",fe=`reverse_proxy localhost:${z.port}`;return he?` handle {
2
- ${fe}
1
+ import{$I,MI,rl,Sm,nl,il,dn,Q,l,sl,Im,K,ol,p,ry,b,Ze,Ji,ln,w,de,al,ny,r,t,FI,UI,m,QI,HI,GI,VI,qI,lr,cl,Xi,iy,jI,zI,xe,et,dl,bm,Cm,KI,Em,vm,Tm,Ho,ll,le,un,kt,Go,Nt,Ee,sy,ul,Vo,wm,Rm,Dm,Pm,gl,WI,W,E,oy,ay,km,a,S,tt,f,Nm,rt,J,Bt,JI,Bm,X,pl,Oe,ur,qo,ue,ml,ge,cy,jo,Y,Z,_,Yi,D,gr,xt,ee,e,gn,XI,xm,fl,YI,ZI,eb,tb,hl,rb,nb,ib,sb,ob,ab,cb,db,lb,ub,gb,pb,dy,ly,uy,gy,py,my,fy,pr,Om,_m,mr,Zi,mb,Lm,fb,hb,pn,Ab,yb,Sb,Ib,bb,Cb,hy,Ay,yy,Sy,Iy,es,Eb,zo,by,$m,V,Cy,nt,Ko,Ot,Ey,Mm,vy,Ty,wy,Fm,q,vb,Tb,wb,Rb,Ry,Db,te,Pb,kb,Nb,Al,yl,Dy,Um,Qm,Bb,xb,Ob,_b,Lb,Py,Sl,$b,Mb,Fb,Ub,Qb,ky,Ny,Hb,Gb,Vb,qb,jb,zb,Kb,By,Wb,Hm,Il,Jb,Xb,Yb,Zb,Gm,Vm,qm,eC,bl,xy,Oy,_y,Ly,Cl,$y,tC,rC,nC,iC,sC,oC,aC,My,Fy,Uy,Qy,jm,cC,dC,lC,uC,gC,pC,mC,fC,hC,Hy,Gy,Vy,qy,AC,yC,zm,SC,Km,Wm,Jm,Xm,IC,bC,CC,EC,_e,ts,vC,TC,wC,RC,DC,PC,kC,NC,jy,BC,xC,Ym,Zm,OC,_C,zy,LC,$C,MC,FC,UC,QC,HC,GC,VC,qC,jC,zC,KC,WC,JC,XC,YC,ZC,eE,tE,rE,El,Ky,vl,Wy,Tl,Jy,wl,Xy,Rl,Yy,fr,Zy,Dl,eS,rs,tS,Pl,rS,kl,nS,ef,nE,tf,iE,Nl,iS,hr,sS,rf,sE,Bl,oS,nf,oE,sf,aE,of,cE,xl,aS,af,dE,cf,lE,df,uE,lf,gE,Ol,cS,_l,dS,uf,pE,gf,mE,pf,fE,mf,hE,ff,AE,hf,yE,Ll,lS,Af,SE,yf,IE,Sf,bE,If,CE,bf,EE,Cf,vE,Ef,vf,Tf,wf,Rf,TE,Df,wE,Pf,RE,kf,DE,it,Nf,uS,Wo,$l,mn,gS,ns,Ar,Ml,Fl,pS,mS,Ul,Bf,Ql,xf,PE,kE,Jo,Xo,Yo,Hl,fn,Gl,Vl,is,Zo,ea,Of,fS,hS,AS,NE,_f,Lf,BE,yS,$f,SS,IS,bS,xE,Mf,hn,ql,Ff,OE,CS,ta,ra,jl,Uf,_E,zl,ES,Qf,LE,Hf,$E,Gf,ME}from"./chunk-3bvhthfb.js";import{Kl,k,Wl,na,vS,Vf,TS,wS,RS,DS,PS,kS,NS,BS}from"./chunk-928z0h9b.js";import{da,qf,nu,LS,cs,iu,la,jf,zf,yn,ua,su,ot,ou,au,cu,ds,Sn,Kf,at,du,ga,pa,ma,lu,uu,gu,ls,fa,pu,In,us,ha,_t,Wf,mu,fu,Jf,hu,Aa,yr,Au,yu,Su,Iu,ct,Xf,bu,Sr,ya,Sa,Ia,gs,ps,bn,Cu,ms,ba,Ca,Cn,Eu,En,Yf,Zf,Lt,vn,Ea,eh,vu,Tu,va,wu,Ru,Du,$S,pe,Pu,MS,FS,fs,hs,US,ve,th,$t,Le,$e,Mt,ku,Nu,Bu,xu,rh,nh,Ta,ih,sh,wa,Ou,_u,oh,me,ah,Lu,Te,Ra,dt,Ft,Ut,Tn,As,$u,QS,ch,dh,lh,uh,Da,Pa,Mu,ka,wn,Na,Fu,ys,Uu,Ba,xa,Oa,_a,La,$a,Ma,Fa,Qu,Ir,Ua,Hu,Rn,Gu,Qa,Ha,Vu,br,Ga,Va,gh,HS,Ss,GS,VS,qS,qa,ja,qu,ph,za,Dn,ju,Is,zu,Ku,Wu,Ka,mh,Wa,Ju,fh,Ja,hh,Pn,kn,Xu,bs,ng,ag,cg,dg,lg,ug,Es,Cr,Ya,Nn,Bn,Er,lt,vh,ec,Th,wh,mg,tc,Ts,fg,rc,Ht,Fe,hg,nc,ic,Ag,sc,oc,ac,cc,yg,Sg,On,dc,lc,uc,gc,Ig,ws,_n,Rs,pc}from"./chunk-2yqvgbmn.js";import{ru}from"./chunk-fjs0wgyw.js";import{U,Kr,Ad,Ao,d,zp,Kp}from"./chunk-tr54e9c0.js";import{Tt,hd,xi,Oi,_i,jp}from"./chunk-fpad8xw9.js";import{rA,nA,iA,Rp,Dp,Pp,sA,kp,Np,oA,aA,Bp,cA,dA,md,xp,lA,uA,Op,gA,pA,mA,fA,hA,AA,yA,Bi,fd,_p,Lp,$p,Mp,Fp,Up,Qp,Hp,Gp,Vp,qp,SA,IA,bA,CA,EA,vA,TA}from"./chunk-ax320pn8.js";import{Je,yd,Ce,nr,Sd,x,ir,wt,Id,yo,DA,Wp,bd,s,Li,So,Wr,Cd,Ed,Jr,PA,vd,xI,OI,Io,_I,LI,Td,wd,$i,bo,ce,c,Co,Xe,Xr,kA,NA,Rd,BA,Eo,xA,OA,vo,Dd,Yr,To,_A,sr,Pd,Jp,or,Zr,LA,wo,$A,O,MA,kd,Xp,Ro,FA,UA,QA,Nd,Mi,Do,Bd,ar,Rt,HA,en,GA,xd,Yp,Zp,Po,Od,_d,Dt,em,Fi,Ld,ko,tn,tm,Ui,$d,Md,Qi,rm,Fd,Ud,Qd,Hd,No,nm,im,VA,sm,Gd,Hi,om,am,Bo,rn,xo,Oo,_o,Vd,cm,qd,Lo,qA,cr,jA,jd,nn,zd,zA,Kd,dm,Gi,sn,$o,Vi,Ye,KA,lm,um,dr,Wd,Jd,Xd,qi,ji,zi,WA,JA,Pt,Mo,XA,on,gm,Fo,YA,pm,mm,fm,ZA,hm,Am,ey,i,ty,Ki,Uo,Qo}from"./chunk-5t92a838.js";import{n}from"./chunk-m9szynnf.js";import{De,mt,zn}from"./chunk-gdw52mn4.js";import{o}from"./chunk-c8kf2268.js";import{we,Os,_s,Eg,yc,Sc,Ls,Ic,ut,re,gt,fe,T,Re,Un,bc,Ue,Cc,Qn,Hn,Gn,Gt,Vt,qt,Vn,Tr,Ec,wr,Rr,pt,qn,Tc,jt,Dr,jn,Rc,Dg,Pg,Dc,Pr}from"./chunk-py8dq1ey.js";import{ft,ye,Ge,kg,zt,kc,Nc,Kt,H,Kn,Wt,Jt,Wn,Us,Qs,kr,Nr,Jn,Br,Hs,Gs,Vs,qs,ie,js,zs,Ks,Ws,Se,Js,Xs,Ys,N,Bc,Xn,xc,Ie,xr}from"./chunk-e75dvdqf.js";import{ne}from"./chunk-nftqsker.js";import{Ng,Oc,Bg,se,_c,Yn,xg,Lc,Og,_g,Fh,_r,eo,M,$r,ei,ti,Mr,Ur,ri,to,ni,ii,si,oi,ci,Qr,be,Fc,At,Uc,Hr,Gc,qe,oe,je,ze,St,ui,gi,Pe,bt,ke,mi,fi,hi,Ai,yi,Si,Ii,Gr,F,so,ap,Yc,Ci,Ei,vi,Ti,id,ao,sd,tr,Ri,co,lo,od,Di,ad}from"./chunk-s56rah0t.js";import{go,mo,fo,B,Ne}from"./chunk-gpgmp9dt.js";import{Jl,ia,ss,os,sa,Xl,Yl,as,oa,aa,eu,tu,ca}from"./chunk-jx1zz1pw.js";import{mc,Ln,$n,Ds,Ps,ks,Ns,fc,hc}from"./chunk-cq079p4a.js";import{Ac}from"./chunk-m35z9vyn.js";import{Pc,Qe,I}from"./chunk-z56sccfh.js";import{He}from"./chunk-fdf181e6.js";import{C}from"./chunk-c71hhcsb.js";import{ae,Pi,uo,cd,ki,bp}from"./chunk-4pztf7ws.js";import{qr,Be}from"./chunk-vq8bejep.js";import{A}from"./chunk-tmp2ym80.js";import{Yd,an,Zd,el,tl,Wi,ym,cn}from"./chunk-84z2a1xn.js";import{xS,st}from"./chunk-9pwvnh3f.js";var jh="https://api.machines.dev/v1";class Cs extends Error{status;path;constructor(u,g,h){super(u);this.status=g;this.path=h;this.name="FlyApiError"}}function Qc(u){let g=u.ip.includes(":");if(g&&u.ip.startsWith("fdaa:"))return"private_v6";if(u.shared)return"shared_v4";return g?"v6":"v4"}class hp{token;fetch;constructor(u){if(!u.token)throw Error("Fly.io needs an API token: set FLY_API_TOKEN (`fly tokens create deploy` makes one scoped to an app).");this.token=u.token,this.fetch=u.fetch??fetch}async rest(u,g,h={}){let y=new URL(`https://api.machines.dev/v1${g}`);for(let[L,z]of Object.entries(h.query??{}))y.searchParams.set(L,z);let R=await this.fetch(y,{method:u,headers:{Authorization:`Bearer ${this.token}`,...h.body!==void 0?{"Content-Type":"application/json"}:{},...h.headers},body:h.body===void 0?void 0:JSON.stringify(h.body)});if(R.status===404&&h.notFound==="null")return null;let v=await R.text(),P=v?yp(v):void 0;if(!R.ok){let L=typeof P==="object"&&P&&"error"in P?String(P.error):v||R.statusText;throw new Cs(`Fly.io ${u} ${g} failed (${R.status}): ${L}`,R.status,g)}return P}getApp(u){return this.rest("GET",`/apps/${encodeURIComponent(u)}`,{notFound:"null"})}createApp(u,g){return this.rest("POST","/apps",{body:{app_name:u,org_slug:g}})}async listMachines(u){return await this.rest("GET",`/apps/${encodeURIComponent(u)}/machines`)??[]}createMachine(u,g){return this.rest("POST",`/apps/${encodeURIComponent(u)}/machines`,{body:g})}updateMachine(u,g,h,y){return this.rest("POST",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(g)}`,{body:h,headers:{"fly-machine-lease-nonce":y}})}async acquireLease(u,g,h=120){let R=(await this.rest("POST",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(g)}/lease`,{body:{ttl:h}})).data?.nonce;if(!R)throw new Cs(`Fly.io gave no lease nonce for Machine ${g}`,200,`/machines/${g}/lease`);return R}async releaseLease(u,g,h){await this.rest("DELETE",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(g)}/lease`,{headers:{"fly-machine-lease-nonce":h}})}async waitForState(u,g,h,y={}){await this.rest("GET",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(g)}/wait`,{query:{state:h,timeout:String(y.timeoutSeconds??60),...y.instanceId?{instance_id:y.instanceId}:{}}})}async listVolumes(u){return await this.rest("GET",`/apps/${encodeURIComponent(u)}/volumes`)??[]}createVolume(u,g){return this.rest("POST",`/apps/${encodeURIComponent(u)}/volumes`,{body:{...g,encrypted:!0}})}async setSecrets(u,g){return(await this.rest("POST",`/apps/${encodeURIComponent(u)}/secrets`,{body:{values:g}})).version}async listIpAssignments(u){return(await this.rest("GET",`/apps/${encodeURIComponent(u)}/ip_assignments`)).ips??[]}async assignIp(u,g){let h=await this.rest("POST",`/apps/${encodeURIComponent(u)}/ip_assignments`,{body:{type:g}});if(!h.ip)throw new Cs(`Fly.io assigned no ${g} address to ${u}`,200,`/apps/${u}/ip_assignments`);return{ip:h.ip,shared:h.shared??g==="shared_v4",region:h.region}}async requestCertificate(u,g){return this.rest("POST",`/apps/${encodeURIComponent(u)}/certificates/acme`,{body:{hostname:g}})}}function yp(u){try{return JSON.parse(u)}catch{return}}var vc="ts-cloud-role";function Zh(u,g){let h=u.fly??{},y=h.app??`${u.project.slug}-${g.environment}`;if(!/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(y))throw Error(`"${y}" is not a valid Fly app name: lowercase letters, digits and dashes, 3 to 63 characters.`);let R=h.internalPort??3000,v=h.count??1;if(!Number.isInteger(v)||v<1)throw Error(`fly.count must be a whole number of at least 1, got ${v}.`);return{app:y,org:h.org??"personal",image:g.image,regions:h.regions?.length?h.regions:["iad"],count:v,internalPort:R,healthPath:h.healthPath??"/",vm:{cpuKind:h.vm?.cpuKind??"shared",cpus:h.vm?.cpus??1,memoryMb:h.vm?.memoryMb??512},...h.volume?{volume:{name:h.volume.name??"data",sizeGb:h.volume.sizeGb,path:h.volume.path}}:{},autoStop:h.autoStop??!1,env:{...g.env,PORT:String(R)},secrets:g.secrets??{},hostnames:h.hostnames??[],release:g.release}}function Cp(u){return{image:u.image,env:u.env,guest:{cpu_kind:u.vm.cpuKind,cpus:u.vm.cpus,memory_mb:u.vm.memoryMb},services:[{protocol:"tcp",internal_port:u.internalPort,ports:[{port:80,handlers:["http"],force_https:!0},{port:443,handlers:["tls","http"]}],autostop:u.autoStop?"stop":"off",autostart:!0,...u.autoStop?{min_machines_running:0}:{},checks:[{type:"http",method:"GET",path:u.healthPath,interval:"15s",timeout:"5s",grace_period:"10s"}]}],restart:{policy:"on-failure",max_retries:10},metadata:{[vc]:"app","ts-cloud-release":u.release}}}async function Jh(u,g,h=()=>{}){let y=!1;if(!await u.getApp(g.app))h(`Creating Fly app ${g.app} in ${g.org}`),await u.createApp(g.app,g.org),y=!0;let R;if(Object.keys(g.secrets).length>0)R=await u.setSecrets(g.app,g.secrets),h(`Set ${Object.keys(g.secrets).length} secret(s) (version ${R})`);let v=await u.listIpAssignments(g.app),P=new Set(v.map(Qc));if(!P.has("v6"))v.push(await u.assignIp(g.app,"v6")),h("Assigned a dedicated IPv6");if(!P.has("v4")&&!P.has("shared_v4"))v.push(await u.assignIp(g.app,"shared_v4")),h("Assigned a shared IPv4");let L=Cp(g),z=(await u.listMachines(g.app)).filter((Me)=>{let We=Me.config?.metadata??{};if(We[vc])return We[vc]==="app";return!We.fly_process_group||We.fly_process_group==="app"}),Ae=g.volume?await u.listVolumes(g.app):[],he=[],Ct=[],It=new Set;for(let Me of g.regions){let We=z.filter((j)=>j.region===Me).sort((j,ht)=>j.id.localeCompare(ht.id));for(let j=0;j<g.count;j++){let ht=We[j];if(ht){It.add(ht.id),await Sp(u,g.app,ht,L,R),Ct.push(ht.id),h(`Updated ${ht.id} (${Me}) to ${g.image}`);continue}let G=g.volume?[{volume:(await Ap(u,g,Me,Ae)).id,path:g.volume.path}]:void 0,Ke=await u.createMachine(g.app,{region:Me,name:`${g.app}-${Me}-${j+1}`,config:{...L,...G?{mounts:G}:{}},...R!==void 0?{min_secrets_version:R}:{}});await u.waitForState(g.app,Ke.id,"started",{instanceId:Ke.instance_id}),he.push(Ke.id),h(`Created ${Ke.id} in ${Me}`)}}let Ve=[];for(let Me of g.hostnames)Ve.push(await u.requestCertificate(g.app,Me));return{app:g.app,url:`https://${g.app}.fly.dev`,createdApp:y,created:he,updated:Ct,untouched:z.filter((Me)=>!It.has(Me.id)).map((Me)=>Me.id),ips:v,certificates:Ve}}async function Sp(u,g,h,y,R){let v=await u.acquireLease(g,h.id);try{let P=await u.updateMachine(g,h.id,{config:{...y,...h.config?.mounts?.length?{mounts:h.config.mounts}:{}},...R!==void 0?{min_secrets_version:R}:{}},v);await u.waitForState(g,h.id,"started",{instanceId:P.instance_id})}finally{await u.releaseLease(g,h.id,v)}}async function Ap(u,g,h,y){let R=y.find((P)=>P.region===h&&P.name===g.volume.name&&!P.attached_machine_id);if(R)return R.attached_machine_id="pending",R;let v=await u.createVolume(g.app,{name:g.volume.name,region:h,size_gb:g.volume.sizeGb});return y.push({...v,attached_machine_id:"pending"}),v}import{createHmac as Zl,createSign as Tp,timingSafeEqual as wp}from"node:crypto";function bi(u){let g=u instanceof Date?u.getTime():u;if(!Number.isFinite(g))throw TypeError("Media access timestamp must be finite");return Math.floor(g/1000)}function Zu(u){return Buffer.from(u).toString("base64").replaceAll("+","-").replaceAll("=","_").replaceAll("/","~")}function Ip(u){return Buffer.from(u).toString("base64url")}function Yu(u,g=!1){if(!u||/[\r\n]/.test(u))throw TypeError("Media resource is invalid");let h=g?u.replaceAll("*","wildcard"):u,y=new URL(h);if(!["http:","https:"].includes(y.protocol))throw TypeError("Media resource must use HTTP or HTTPS");if(!g&&u.includes("*"))throw TypeError("Canned policies cannot contain wildcards")}function ed(u,g){let h=Tp("RSA-SHA1");return h.update(u),h.end(),Zu(h.sign(g))}function td(u){Yu(u.resource,!0);let h={DateLessThan:{"AWS:EpochTime":bi(u.expiresAt)}};if(u.activeAt!==void 0)h.DateGreaterThan={"AWS:EpochTime":bi(u.activeAt)};if(u.ipAddress)h.IpAddress={"AWS:SourceIp":u.ipAddress};return JSON.stringify({Statement:[{Resource:u.resource,Condition:h}]})}function WS(u,g,h){Yu(u);let y=bi(g),R=u.includes("?")?"&":"?",v=td({resource:u,expiresAt:g}),P=ed(v,h.privateKey);return`${u}${R}Expires=${y}&Signature=${encodeURIComponent(P)}&Key-Pair-Id=${encodeURIComponent(h.keyPairId)}`}function zS(u,g){let h=td(u);return{"CloudFront-Key-Pair-Id":g.keyPairId,"CloudFront-Policy":Zu(Buffer.from(h)),"CloudFront-Signature":ed(h,g.privateKey)}}function jS(u){if(!u.resource||/[\r\n]/.test(u.resource))throw TypeError("Media resource is invalid");let g=Ip(Buffer.from(JSON.stringify({resource:u.resource,expiresAt:bi(u.expiresAt),...u.keyId?{keyId:u.keyId}:{},...u.audience?{audience:u.audience}:{}}))),h=Zl("sha256",u.secret).update(g).digest("base64url");return`${g}.${h}`}function KS(u,g){let[h,y,R]=u.split(".");if(!h||!y||R)return null;let v=Zl("sha256",g.secret).update(h).digest(),P;try{P=Buffer.from(y,"base64url")}catch{return null}if(v.length!==P.length||!wp(v,P))return null;try{let L=JSON.parse(Buffer.from(h,"base64url").toString("utf8")),z=bi(g.now??Date.now());if(!L.resource||!Number.isSafeInteger(L.expiresAt)||L.expiresAt<=z)return null;if(g.resource&&L.resource!==g.resource)return null;if(g.audience&&L.audience!==g.audience)return null;return L}catch{return null}}function ZS(u,g=!1){let h=new URL(u,"https://media.invalid").pathname.toLowerCase(),y=/\.(?:m3u8|mpd|vtt|json)$/.test(h),R=/\.(?:key|license)$/.test(h)||h.includes("/keys/")||h.includes("/licenses/");return{"Accept-Ranges":"bytes","Cache-Control":g&&(y||R)?"private, no-store":y?"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 JS(u){if(!/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(u.bucket))throw TypeError("Media bucket is invalid");if(!/^[a-z0-9-]+$/.test(u.region))throw TypeError("Media bucket region is invalid");let g=u.prefix?`/${u.prefix.replace(/^\/+|\/+$/g,"")}`:"",h=u.protected??!1,y="public, max-age=31536000, immutable",R=h?"private, no-store":"public, max-age=5, s-maxage=30, stale-while-revalidate=30";return{originDomain:`${u.bucket}.s3.${u.region}.amazonaws.com`,originPath:g,domain:u.domain,trustedKeyGroupIds:[...new Set(u.trustedKeyGroupIds??[])],behaviors:[{pathPattern:"*.m3u8",cacheControl:R,compress:!0,signed:h},{pathPattern:"*.mpd",cacheControl:R,compress:!0,signed:h},{pathPattern:"*.vtt",cacheControl:R,compress:!0,signed:h},{pathPattern:"*",cacheControl:y,compress:!1,signed:h}],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 vp{builder;config;environment;mergedConfig;serverEipLogicalIds=new Map;storageFailoverReplicas=[];constructor(u){this.config=u.config,this.environment=u.environment,this.builder=new al(`${this.config.project.name} - ${this.environment}`),this.mergedConfig=this.mergeEnvironmentConfig()}mergeEnvironmentConfig(){let g=this.config.environments[this.environment]?.infrastructure;if(!g)return this.config;return{...this.config,infrastructure:{...this.config.infrastructure,...g,compute:{...this.config.infrastructure?.compute,...g.compute},storage:{...this.config.infrastructure?.storage,...g.storage},functions:{...this.config.infrastructure?.functions,...g.functions},servers:{...this.config.infrastructure?.servers,...g.servers},databases:{...this.config.infrastructure?.databases,...g.databases},cdn:{...this.config.infrastructure?.cdn,...g.cdn},sftp:g.sftp??this.config.infrastructure?.sftp,queues:{...this.config.infrastructure?.queues,...g.queues},redirects:{...this.config.infrastructure?.redirects,...g.redirects},realtime:{...this.config.infrastructure?.realtime,...g.realtime},cache:{...this.config.infrastructure?.cache,...g.cache},fileSystem:{...this.config.infrastructure?.fileSystem,...g.fileSystem},email:{...this.config.infrastructure?.email,...g.email},search:{...this.config.infrastructure?.search,...g.search},ai:{...this.config.infrastructure?.ai,...g.ai}}}}shouldDeploy(u){if(u.environments&&!u.environments.includes(this.environment))return!1;if(u.requiresFeatures){let g=this.config.features||{};if(!u.requiresFeatures.every((y)=>g[y]===!0))return!1}if(u.regions){let g=this.config.environments[this.environment]?.region||this.config.project.region;if(!u.regions.includes(g))return!1}if(u.condition&&typeof u.condition==="function")return u.condition(this.config,this.environment);return!0}resolveApiOriginPort(){let u=this.mergedConfig.infrastructure?.api?.port??this.mergedConfig.ports?.api,g=Number(u||3008);return Number.isFinite(g)&&g>0?g: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(u,g){return u==="public"||g.routeCompute===!0}storageBucketName(u,g,h){return this.mergedConfig.infrastructure?.storage?.[h]?.bucket??`${u}-${g}-${h}`}fileSystemLogicalId(u,g,h){return t(r({slug:`${u}-${h}`,environment:g,resourceType:"efs"}))}resolveSftpStorage(u,g,h){let y=u.storage;if(y?.type==="efs"&&y.fileSystem){if(!this.mergedConfig.infrastructure?.fileSystem?.[y.fileSystem])throw Error(`sftp: storage.fileSystem "${y.fileSystem}" is not defined in infrastructure.fileSystem`);return{type:"efs",fileSystemId:{Ref:this.fileSystemLogicalId(g,h,y.fileSystem)},posixProfile:y.posixProfile}}if(y?.type==="s3"&&y.storageBucket){if(!this.mergedConfig.infrastructure?.storage?.[y.storageBucket])throw Error(`sftp: storage.storageBucket "${y.storageBucket}" is not defined in infrastructure.storage`);return{type:"s3",bucket:this.storageBucketName(g,h,y.storageBucket)}}return}resolveComputeCachePathPatterns(u){if(u&&u.length>0)return u;return this.defaultComputeCachePathPatterns()}createComputeCacheBehavior(u,g){return{PathPattern:u,TargetOriginId:g,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(u,g,h,y,R,v){let P=this.serverEipLogicalIds.get("app"),L=this.serverEipLogicalIds.get("appInstance");if(!P)return;let z=`EC2-${y}-${R}-api`,Ae=this.mergedConfig.infrastructure?.servers?.app?.region||this.mergedConfig.project?.region||"us-east-1",he=Ae==="us-east-1"?".compute-1.amazonaws.com":`.${Ae}.compute.amazonaws.com`,Ct={"Fn::Join":["",["ec2-",{"Fn::Join":["-",{"Fn::Split":[".",{Ref:P}]}]},he]]},It=this.resolveApiOriginPort();if(u.push({Id:z,DomainName:Ct,CustomOriginConfig:{HTTPPort:It,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}),h.push(P),L)h.push(L);for(let Ve of v)g.push(this.createComputeCacheBehavior(Ve,z))}buildCaddyfile(u){let g=u.filter(([,R])=>typeof R.domain==="string"&&R.domain&&typeof R.port==="number");if(g.length===0)return;let h=new Map;for(let[,R]of g){let v=h.get(R.domain)??[];v.push({port:R.port,path:R.path}),h.set(R.domain,v)}let y=[];for(let[R,v]of h){let L=[...v].sort((z,Ae)=>{let he=!z.path||z.path==="/",Ct=!Ae.path||Ae.path==="/";if(he&&!Ct)return 1;if(!he&&Ct)return-1;return(Ae.path?.length??0)-(z.path?.length??0)}).map((z)=>{let Ae=!z.path||z.path==="/",he=`reverse_proxy localhost:${z.port}`;return Ae?` handle {
2
+ ${he}
3
3
  }`:` handle ${z.path} {
4
- ${fe}
4
+ ${he}
5
5
  }`});y.push(`${R} {
6
6
  ${L.join(`
7
7
  `)}
8
8
  }`)}return y.join(`
9
9
 
10
- `)}normalizeMountPath(u){let g=u?.mountPath||u?.path;if(!g||g==="/")return;let h=`/${g}`.replace(/\/+/g,"/").replace(/\/$/,"");return h==="/"?void 0:h}storageBucketLogicalId(u,g,h){return`${u}-${g}-s3-${h}`.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((y)=>y.charAt(0).toUpperCase()+y.slice(1)).join("")}pathMountRewriteFunctionCode(u,g="directory"){return`function handler(event) { var request = event.request; var prefix = ${JSON.stringify(u)}; var rewriteStyle = ${JSON.stringify(g)}; 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 u=this.mergedConfig.project.slug,g=this.environment,h=!!(this.mergedConfig.infrastructure?.functions&&Object.keys(this.mergedConfig.infrastructure.functions).length>0||this.mergedConfig.infrastructure?.api),y=!!(this.mergedConfig.infrastructure?.servers&&Object.keys(this.mergedConfig.infrastructure.servers).length>0),R=!!this.mergedConfig.infrastructure?.compute;if(!!((this.mergedConfig.mode||"server")==="serverless"&&this.mergedConfig.infrastructure?.containers&&Object.keys(this.mergedConfig.infrastructure.containers).length>0))this.generateNetworkInfrastructure(u,g),this.generateContainerInfrastructure(u,g);if(h)this.generateServerless(u,g);if(y)this.generateServer(u,g);if(R)this.generateComputeApp(u,g);if(this.mergedConfig.infrastructure?.jumpBox)this.generateJumpBox(u,g);if(this.storageFailoverReplicas=[],this.generateSharedInfrastructure(u,g),this.storageFailoverReplicas.length>0)this.builder.addMetadata(ul,this.storageFailoverReplicas);if(this.config.tags)this.applyGlobalTags(this.config.tags);return this}getStorageFailoverReplicas(){return[...this.storageFailoverReplicas]}applyGlobalTags(u){}generateNetworkInfrastructure(u,g){if(this.builder.hasResource("VPC"))return;let y=this.mergedConfig.infrastructure?.network?.cidr||"10.0.0.0/16",{vpc:R,logicalId:v}=S.createVpc({slug:u,environment:g,cidr:y,enableDnsHostnames:!0,enableDnsSupport:!0});this.builder.addResource("VPC",R);let P=`${u}${g}IGW`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(P,{Type:"AWS::EC2::InternetGateway",Properties:{Tags:[{Key:"Name",Value:`${u}-${g}-igw`},{Key:"Environment",Value:g}]}});let L=`${u}${g}IGWAttach`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(L,{Type:"AWS::EC2::VPCGatewayAttachment",Properties:{VpcId:{Ref:"VPC"},InternetGatewayId:{Ref:P}}});let z=`${u}${g}PublicRT`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(z,{Type:"AWS::EC2::RouteTable",Properties:{VpcId:{Ref:"VPC"},Tags:[{Key:"Name",Value:`${u}-${g}-public-rt`},{Key:"Environment",Value:g}]}}),this.builder.addResource(`${u}${g}PublicRoute`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::EC2::Route",Properties:{RouteTableId:{Ref:z},DestinationCidrBlock:"0.0.0.0/0",GatewayId:{Ref:P}},DependsOn:L});let he=this.mergedConfig.environments[g]?.region||this.mergedConfig.project.region||"us-east-1",fe=["a","b"];for(let Ct=0;Ct<2;Ct++){let It=`PublicSubnet${Ct+1}`;this.builder.addResource(It,{Type:"AWS::EC2::Subnet",Properties:{VpcId:{Ref:"VPC"},CidrBlock:`10.0.${Ct}.0/24`,AvailabilityZone:`${he}${fe[Ct]}`,MapPublicIpOnLaunch:!0,Tags:[{Key:"Name",Value:`${u}-${g}-public-${fe[Ct]}`},{Key:"Environment",Value:g}]}}),this.builder.addResource(`${It}RTAssoc`,{Type:"AWS::EC2::SubnetRouteTableAssociation",Properties:{SubnetId:{Ref:It},RouteTableId:{Ref:z}}})}}generateContainerInfrastructure(u,g){let h=this.mergedConfig.infrastructure?.containers;if(!h)return;let y=this.mergedConfig.infrastructure?.loadBalancer,R=this.mergedConfig.infrastructure?.ssl,v=this.mergedConfig.infrastructure?.dns,P;if(R?.enabled&&R.domains?.length)if(R.certificateArn);else{let fe=R.domains[0],Ct=R.domains.slice(1).map((Me)=>{if(Me.includes(".")&&Me.endsWith(fe))return Me.replace(`.${fe}`,"");return Me}),{certificate:It,logicalId:Ve}=E.createCertificate({domain:fe,subdomains:Ct,slug:u,environment:g,validationMethod:"DNS",hostedZoneId:v?.hostedZoneId});P=Ve,this.builder.addResource(Ve,It)}let L="ECSCluster";this.builder.addResource(L,{Type:"AWS::ECS::Cluster",Properties:{ClusterName:`${u}-${g}`,ClusterSettings:[{Name:"containerInsights",Value:"enabled"}],Tags:[{Key:"Name",Value:`${u}-${g}`},{Key:"Environment",Value:g}]}});let z=`${u}${g}ALBSecurityGroup`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(z,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`ALB security group for ${u}-${g}`,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:`${u}-${g}-alb-sg`},{Key:"Environment",Value:g}]}});let he=`${u}${g}ECSSecurityGroup`.replace(/[^a-zA-Z0-9]/g,"");for(let[fe,Ct]of Object.entries(h)){let It=Ct.port||3000;this.builder.addResource(he,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`ECS tasks security group for ${u}-${g}`,VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:It,ToPort:It,SourceSecurityGroupId:{Ref:z},Description:"Allow traffic from ALB"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0",Description:"Allow all outbound"}],Tags:[{Key:"Name",Value:`${u}-${g}-ecs-sg`},{Key:"Environment",Value:g}]}});let Ve=`${u}${g}TaskExecRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Ve,{Type:"AWS::IAM::Role",Properties:{RoleName:`${u}-${g}-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 Me=`${u}${g}TaskRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Me,{Type:"AWS::IAM::Role",Properties:{RoleName:`${u}-${g}-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 We=`${u}${g}${fe}LogGroup`.replace(/[^a-zA-Z0-9]/g,""),j=`/ecs/${u}-${g}-${fe}`;this.builder.addResource(We,{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:j,RetentionInDays:30}});let ht=`${u}${g}${fe}TaskDef`.replace(/[^a-zA-Z0-9]/g,""),G=String(Ct.cpu||512),Ke=String(Ct.memory||1024);this.builder.addResource(ht,{Type:"AWS::ECS::TaskDefinition",Properties:{Family:`${u}-${g}-${fe}`,NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:G,Memory:Ke,ExecutionRoleArn:{"Fn::GetAtt":[Ve,"Arn"]},TaskRoleArn:{"Fn::GetAtt":[Me,"Arn"]},ContainerDefinitions:[{Name:fe,Image:{"Fn::Sub":`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${u}:latest`},Essential:!0,PortMappings:[{ContainerPort:It,Protocol:"tcp"}],LogConfiguration:{LogDriver:"awslogs",Options:{"awslogs-group":j,"awslogs-region":{Ref:"AWS::Region"},"awslogs-stream-prefix":fe}},HealthCheck:{Command:["CMD-SHELL",`curl -f http://localhost:${It}${Ct.healthCheck||"/health"} || exit 1`],Interval:30,Timeout:5,Retries:3,StartPeriod:60}}],Tags:[{Key:"Name",Value:`${u}-${g}-${fe}`},{Key:"Environment",Value:g}]},DependsOn:[Ve,Me,We]});let yt=`${u}${g}ALB`.replace(/[^a-zA-Z0-9]/g,"");if(y?.enabled!==!1){this.builder.addResource(yt,{Type:"AWS::ElasticLoadBalancingV2::LoadBalancer",Properties:{Name:`${u}-${g}-alb`,Scheme:"internet-facing",Type:"application",Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],SecurityGroups:[{Ref:z}],Tags:[{Key:"Name",Value:`${u}-${g}-alb`},{Key:"Environment",Value:g}]}});let vt=`${u}${g}TargetGroup`.replace(/[^a-zA-Z0-9]/g,""),Et=y?.healthCheck?.path||Ct.healthCheck||"/health";this.builder.addResource(vt,{Type:"AWS::ElasticLoadBalancingV2::TargetGroup",Properties:{Name:`${u}-${g}-tg`,Port:It,Protocol:"HTTP",VpcId:{Ref:"VPC"},TargetType:"ip",HealthCheckPath:Et,HealthCheckIntervalSeconds:y?.healthCheck?.interval||30,HealthyThresholdCount:y?.healthCheck?.healthyThreshold||2,UnhealthyThresholdCount:y?.healthCheck?.unhealthyThreshold||5,HealthCheckTimeoutSeconds:10,Tags:[{Key:"Name",Value:`${u}-${g}-tg`},{Key:"Environment",Value:g}]}});let Zt=`${u}${g}HTTPListener`.replace(/[^a-zA-Z0-9]/g,"");if(R?.enabled&&R?.redirectHttp)this.builder.addResource(Zt,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:yt},Port:80,Protocol:"HTTP",DefaultActions:[{Type:"redirect",RedirectConfig:{Protocol:"HTTPS",Port:"443",StatusCode:"HTTP_301"}}]}});else this.builder.addResource(Zt,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:yt},Port:80,Protocol:"HTTP",DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:vt}}]}});if(R?.enabled){let Xt=R.certificateArn||(P?{Ref:P}:void 0);if(Xt){let er=`${u}${g}HTTPSListener`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(er,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:yt},Port:443,Protocol:"HTTPS",Certificates:[{CertificateArn:Xt}],DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:vt}}],SslPolicy:"ELBSecurityPolicy-TLS13-1-2-2021-06"}})}}let Yt=`${u}${g}${fe}Service`.replace(/[^a-zA-Z0-9]/g,""),Qt=Ct.desiredCount||1;this.builder.addResource(Yt,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${u}-${g}-${fe}`,Cluster:{Ref:L},TaskDefinition:{Ref:ht},DesiredCount:Qt,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:he}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},LoadBalancers:[{ContainerName:fe,ContainerPort:It,TargetGroupArn:{Ref:vt}}],HealthCheckGracePeriodSeconds:120,Tags:[{Key:"Name",Value:`${u}-${g}-${fe}`},{Key:"Environment",Value:g}]},DependsOn:[ht,Zt,vt]});let vr=Ct.autoScaling;if(vr){let Xt=`${u}${g}${fe}ScalableTarget`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(Xt,{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{MaxCapacity:vr.max||10,MinCapacity:vr.min||1,ResourceId:{"Fn::Sub":`service/\${${L}}/${u}-${g}-${fe}`},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:Yt}),vr.targetCpuUtilization)this.builder.addResource(`${u}${g}${fe}CPUScaling`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${u}-${g}-${fe}-cpu-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:Xt},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},TargetValue:vr.targetCpuUtilization,ScaleInCooldown:300,ScaleOutCooldown:60}}});if(vr.targetMemoryUtilization)this.builder.addResource(`${u}${g}${fe}MemoryScaling`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${u}-${g}-${fe}-memory-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:Xt},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageMemoryUtilization"},TargetValue:vr.targetMemoryUtilization,ScaleInCooldown:300,ScaleOutCooldown:60}}})}if(v?.domain&&v?.hostedZoneId)this.builder.addResource(`${u}${g}ApiDnsRecord`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:v.hostedZoneId,Name:`api.${v.domain}`,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":[yt,"DNSName"]},HostedZoneId:{"Fn::GetAtt":[yt,"CanonicalHostedZoneID"]}}}});this.builder.addOutput("ECSClusterArn",{Description:"ECS Cluster ARN",Value:{"Fn::GetAtt":[L,"Arn"]},Export:{Name:{"Fn::Sub":"${AWS::StackName}-ecs-cluster-arn"}}}),this.builder.addOutput("ECSServiceName",{Description:"ECS Service Name",Value:`${u}-${g}-${fe}`,Export:{Name:{"Fn::Sub":"${AWS::StackName}-ecs-service-name"}}}),this.builder.addOutput("LoadBalancerDNS",{Description:"Application Load Balancer DNS Name",Value:{"Fn::GetAtt":[yt,"DNSName"]},Export:{Name:{"Fn::Sub":"${AWS::StackName}-alb-dns"}}})}else{let vt=`${u}${g}${fe}Service`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(vt,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${u}-${g}-${fe}`,Cluster:{Ref:L},TaskDefinition:{Ref:ht},DesiredCount:Ct.desiredCount||1,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:he}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},Tags:[{Key:"Name",Value:`${u}-${g}-${fe}`},{Key:"Environment",Value:g}]},DependsOn:[ht]})}break}}generateServerless(u,g){if(this.mergedConfig.infrastructure?.functions)for(let[h,y]of Object.entries(this.mergedConfig.infrastructure.functions)){if(!this.shouldDeploy(y))continue;let{role:R,logicalId:v}=le.createRole({slug:u,environment:g,roleName:`${u}-${g}-${h}-role`,servicePrincipal:"lambda.amazonaws.com",managedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]});this.builder.addResource(v,R);let{lambdaFunction:P,logicalId:L}=a.createLambdaFunction({slug:u,environment:g,functionName:`${u}-${g}-${h}`,handler:y.handler||"index.handler",runtime:y.runtime||"nodejs20.x",code:{zipFile:y.code||"export const handler = async () => ({ statusCode: 200 });"},role:v,timeout:y.timeout,memorySize:y.memorySize});this.builder.addResource(L,P)}if(this.mergedConfig.infrastructure?.api){let{restApi:h,logicalId:y}=ml.createRestApi({slug:u,environment:g,apiName:`${u}-${g}-api`});this.builder.addResource(y,h)}}generateServer(u,g){if(!this.mergedConfig.infrastructure?.servers)return;let h=this.mergedConfig.infrastructure.servers,y=this.mergedConfig.infrastructure?.compute,R=this.mergedConfig.infrastructure?.ssl;if(Object.values(h).some((P)=>!P.privateNetwork||P.privateNetwork==="create"))this.generateNetworkInfrastructure(u,g);for(let[P,L]of Object.entries(h)){let z=L.instanceType||L.size||y?.size,fe=(z?a.InstanceSize.specs[z]:void 0)?.instanceType||z||"t3.micro",Ct=L.type||"app",It=L.userData||L.startupScript;if(!It)It=a.UserData.generateAppServerScript({runtime:"bun",runtimeVersion:L.bunVersion||"latest",webServer:"none",domain:L.domain,enableSsl:!!R?.enabled,sslEmail:R?.letsEncrypt?.email,installRedis:Ct==="cache",installDatabaseClients:!!L.database});let Ve=L.privateNetwork&&L.privateNetwork!=="create"?L.privateNetwork:{Ref:"VPC"},Me=L.subnet||{Ref:"PublicSubnet1"},j=!!this.mergedConfig.infrastructure?.email?.server?.enabled,ht=[22,80,443,this.resolveApiOriginPort()];if(j)ht.push(25,465,587,143,993);let G=a.createServerModeStack({slug:`${u}-${P}`,environment:g,vpcId:Ve,subnetId:Me,instanceType:fe,keyName:L.keyName||`${u}-${g}`,domain:L.domain,userData:It,volumeSize:L.diskSize||20,imageId:L.image,allowedPorts:ht});for(let[Ke,yt]of Object.entries(G.resources))this.builder.addResource(Ke,yt);this.serverEipLogicalIds.set(P,G.outputs.eipLogicalId),this.serverEipLogicalIds.set(`${P}Instance`,G.outputs.instanceLogicalId),this.builder.addOutput(`${P}InstanceId`,{Value:{Ref:G.outputs.instanceLogicalId},Description:`Instance ID for ${P} server`}),this.builder.addOutput(`${P}PublicIp`,{Value:{Ref:G.outputs.eipLogicalId},Description:`Public IP for ${P} server`})}}generateComputeApp(u,g){let h=this.mergedConfig.infrastructure?.compute;if(!h)return;let y=this.mergedConfig.sites||{},R=Object.entries(y),P=this.mergedConfig.infrastructure?.dns?.domain,L=this.mergedConfig.infrastructure?.database,z=h.size,fe=(z?a.InstanceSize.specs[z]:void 0)?.instanceType||z||"t3.micro";if(!this.builder.hasResource("VPC"))this.generateNetworkInfrastructure(u,g);let Ct=this.buildCaddyfile(R),It=a.UserData.generateBunAppScript({runtime:h.runtime||"bun",runtimeVersion:h.runtimeVersion||"latest",systemPackages:h.systemPackages,database:L,caddyfile:Ct}),Ve=eo(h.appUpdates),Me=Ve.length>0?`${It}
10
+ `)}normalizeMountPath(u){let g=u?.mountPath||u?.path;if(!g||g==="/")return;let h=`/${g}`.replace(/\/+/g,"/").replace(/\/$/,"");return h==="/"?void 0:h}storageBucketLogicalId(u,g,h){return`${u}-${g}-s3-${h}`.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((y)=>y.charAt(0).toUpperCase()+y.slice(1)).join("")}pathMountRewriteFunctionCode(u,g="directory"){return`function handler(event) { var request = event.request; var prefix = ${JSON.stringify(u)}; var rewriteStyle = ${JSON.stringify(g)}; 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 u=this.mergedConfig.project.slug,g=this.environment,h=!!(this.mergedConfig.infrastructure?.functions&&Object.keys(this.mergedConfig.infrastructure.functions).length>0||this.mergedConfig.infrastructure?.api),y=!!(this.mergedConfig.infrastructure?.servers&&Object.keys(this.mergedConfig.infrastructure.servers).length>0),R=!!this.mergedConfig.infrastructure?.compute;if(!!((this.mergedConfig.mode||"server")==="serverless"&&this.mergedConfig.infrastructure?.containers&&Object.keys(this.mergedConfig.infrastructure.containers).length>0))this.generateNetworkInfrastructure(u,g),this.generateContainerInfrastructure(u,g);if(h)this.generateServerless(u,g);if(y)this.generateServer(u,g);if(R)this.generateComputeApp(u,g);if(this.mergedConfig.infrastructure?.jumpBox)this.generateJumpBox(u,g);if(this.storageFailoverReplicas=[],this.generateSharedInfrastructure(u,g),this.storageFailoverReplicas.length>0)this.builder.addMetadata(ul,this.storageFailoverReplicas);if(this.config.tags)this.applyGlobalTags(this.config.tags);return this}getStorageFailoverReplicas(){return[...this.storageFailoverReplicas]}applyGlobalTags(u){}generateNetworkInfrastructure(u,g){if(this.builder.hasResource("VPC"))return;let y=this.mergedConfig.infrastructure?.network?.cidr||"10.0.0.0/16",{vpc:R,logicalId:v}=S.createVpc({slug:u,environment:g,cidr:y,enableDnsHostnames:!0,enableDnsSupport:!0});this.builder.addResource("VPC",R);let P=`${u}${g}IGW`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(P,{Type:"AWS::EC2::InternetGateway",Properties:{Tags:[{Key:"Name",Value:`${u}-${g}-igw`},{Key:"Environment",Value:g}]}});let L=`${u}${g}IGWAttach`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(L,{Type:"AWS::EC2::VPCGatewayAttachment",Properties:{VpcId:{Ref:"VPC"},InternetGatewayId:{Ref:P}}});let z=`${u}${g}PublicRT`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(z,{Type:"AWS::EC2::RouteTable",Properties:{VpcId:{Ref:"VPC"},Tags:[{Key:"Name",Value:`${u}-${g}-public-rt`},{Key:"Environment",Value:g}]}}),this.builder.addResource(`${u}${g}PublicRoute`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::EC2::Route",Properties:{RouteTableId:{Ref:z},DestinationCidrBlock:"0.0.0.0/0",GatewayId:{Ref:P}},DependsOn:L});let Ae=this.mergedConfig.environments[g]?.region||this.mergedConfig.project.region||"us-east-1",he=["a","b"];for(let Ct=0;Ct<2;Ct++){let It=`PublicSubnet${Ct+1}`;this.builder.addResource(It,{Type:"AWS::EC2::Subnet",Properties:{VpcId:{Ref:"VPC"},CidrBlock:`10.0.${Ct}.0/24`,AvailabilityZone:`${Ae}${he[Ct]}`,MapPublicIpOnLaunch:!0,Tags:[{Key:"Name",Value:`${u}-${g}-public-${he[Ct]}`},{Key:"Environment",Value:g}]}}),this.builder.addResource(`${It}RTAssoc`,{Type:"AWS::EC2::SubnetRouteTableAssociation",Properties:{SubnetId:{Ref:It},RouteTableId:{Ref:z}}})}}generateContainerInfrastructure(u,g){let h=this.mergedConfig.infrastructure?.containers;if(!h)return;let y=this.mergedConfig.infrastructure?.loadBalancer,R=this.mergedConfig.infrastructure?.ssl,v=this.mergedConfig.infrastructure?.dns,P;if(R?.enabled&&R.domains?.length)if(R.certificateArn);else{let he=R.domains[0],Ct=R.domains.slice(1).map((Me)=>{if(Me.includes(".")&&Me.endsWith(he))return Me.replace(`.${he}`,"");return Me}),{certificate:It,logicalId:Ve}=E.createCertificate({domain:he,subdomains:Ct,slug:u,environment:g,validationMethod:"DNS",hostedZoneId:v?.hostedZoneId});P=Ve,this.builder.addResource(Ve,It)}let L="ECSCluster";this.builder.addResource(L,{Type:"AWS::ECS::Cluster",Properties:{ClusterName:`${u}-${g}`,ClusterSettings:[{Name:"containerInsights",Value:"enabled"}],Tags:[{Key:"Name",Value:`${u}-${g}`},{Key:"Environment",Value:g}]}});let z=`${u}${g}ALBSecurityGroup`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(z,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`ALB security group for ${u}-${g}`,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:`${u}-${g}-alb-sg`},{Key:"Environment",Value:g}]}});let Ae=`${u}${g}ECSSecurityGroup`.replace(/[^a-zA-Z0-9]/g,"");for(let[he,Ct]of Object.entries(h)){let It=Ct.port||3000;this.builder.addResource(Ae,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`ECS tasks security group for ${u}-${g}`,VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:It,ToPort:It,SourceSecurityGroupId:{Ref:z},Description:"Allow traffic from ALB"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0",Description:"Allow all outbound"}],Tags:[{Key:"Name",Value:`${u}-${g}-ecs-sg`},{Key:"Environment",Value:g}]}});let Ve=`${u}${g}TaskExecRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Ve,{Type:"AWS::IAM::Role",Properties:{RoleName:`${u}-${g}-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 Me=`${u}${g}TaskRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Me,{Type:"AWS::IAM::Role",Properties:{RoleName:`${u}-${g}-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 We=`${u}${g}${he}LogGroup`.replace(/[^a-zA-Z0-9]/g,""),j=`/ecs/${u}-${g}-${he}`;this.builder.addResource(We,{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:j,RetentionInDays:30}});let ht=`${u}${g}${he}TaskDef`.replace(/[^a-zA-Z0-9]/g,""),G=String(Ct.cpu||512),Ke=String(Ct.memory||1024);this.builder.addResource(ht,{Type:"AWS::ECS::TaskDefinition",Properties:{Family:`${u}-${g}-${he}`,NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:G,Memory:Ke,ExecutionRoleArn:{"Fn::GetAtt":[Ve,"Arn"]},TaskRoleArn:{"Fn::GetAtt":[Me,"Arn"]},ContainerDefinitions:[{Name:he,Image:{"Fn::Sub":`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${u}:latest`},Essential:!0,PortMappings:[{ContainerPort:It,Protocol:"tcp"}],LogConfiguration:{LogDriver:"awslogs",Options:{"awslogs-group":j,"awslogs-region":{Ref:"AWS::Region"},"awslogs-stream-prefix":he}},HealthCheck:{Command:["CMD-SHELL",`curl -f http://localhost:${It}${Ct.healthCheck||"/health"} || exit 1`],Interval:30,Timeout:5,Retries:3,StartPeriod:60}}],Tags:[{Key:"Name",Value:`${u}-${g}-${he}`},{Key:"Environment",Value:g}]},DependsOn:[Ve,Me,We]});let yt=`${u}${g}ALB`.replace(/[^a-zA-Z0-9]/g,"");if(y?.enabled!==!1){this.builder.addResource(yt,{Type:"AWS::ElasticLoadBalancingV2::LoadBalancer",Properties:{Name:`${u}-${g}-alb`,Scheme:"internet-facing",Type:"application",Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],SecurityGroups:[{Ref:z}],Tags:[{Key:"Name",Value:`${u}-${g}-alb`},{Key:"Environment",Value:g}]}});let vt=`${u}${g}TargetGroup`.replace(/[^a-zA-Z0-9]/g,""),Et=y?.healthCheck?.path||Ct.healthCheck||"/health";this.builder.addResource(vt,{Type:"AWS::ElasticLoadBalancingV2::TargetGroup",Properties:{Name:`${u}-${g}-tg`,Port:It,Protocol:"HTTP",VpcId:{Ref:"VPC"},TargetType:"ip",HealthCheckPath:Et,HealthCheckIntervalSeconds:y?.healthCheck?.interval||30,HealthyThresholdCount:y?.healthCheck?.healthyThreshold||2,UnhealthyThresholdCount:y?.healthCheck?.unhealthyThreshold||5,HealthCheckTimeoutSeconds:10,Tags:[{Key:"Name",Value:`${u}-${g}-tg`},{Key:"Environment",Value:g}]}});let Zt=`${u}${g}HTTPListener`.replace(/[^a-zA-Z0-9]/g,"");if(R?.enabled&&R?.redirectHttp)this.builder.addResource(Zt,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:yt},Port:80,Protocol:"HTTP",DefaultActions:[{Type:"redirect",RedirectConfig:{Protocol:"HTTPS",Port:"443",StatusCode:"HTTP_301"}}]}});else this.builder.addResource(Zt,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:yt},Port:80,Protocol:"HTTP",DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:vt}}]}});if(R?.enabled){let Xt=R.certificateArn||(P?{Ref:P}:void 0);if(Xt){let er=`${u}${g}HTTPSListener`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(er,{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:yt},Port:443,Protocol:"HTTPS",Certificates:[{CertificateArn:Xt}],DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:vt}}],SslPolicy:"ELBSecurityPolicy-TLS13-1-2-2021-06"}})}}let Yt=`${u}${g}${he}Service`.replace(/[^a-zA-Z0-9]/g,""),Qt=Ct.desiredCount||1;this.builder.addResource(Yt,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${u}-${g}-${he}`,Cluster:{Ref:L},TaskDefinition:{Ref:ht},DesiredCount:Qt,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:Ae}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},LoadBalancers:[{ContainerName:he,ContainerPort:It,TargetGroupArn:{Ref:vt}}],HealthCheckGracePeriodSeconds:120,Tags:[{Key:"Name",Value:`${u}-${g}-${he}`},{Key:"Environment",Value:g}]},DependsOn:[ht,Zt,vt]});let vr=Ct.autoScaling;if(vr){let Xt=`${u}${g}${he}ScalableTarget`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(Xt,{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{MaxCapacity:vr.max||10,MinCapacity:vr.min||1,ResourceId:{"Fn::Sub":`service/\${${L}}/${u}-${g}-${he}`},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:Yt}),vr.targetCpuUtilization)this.builder.addResource(`${u}${g}${he}CPUScaling`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${u}-${g}-${he}-cpu-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:Xt},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},TargetValue:vr.targetCpuUtilization,ScaleInCooldown:300,ScaleOutCooldown:60}}});if(vr.targetMemoryUtilization)this.builder.addResource(`${u}${g}${he}MemoryScaling`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${u}-${g}-${he}-memory-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:Xt},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageMemoryUtilization"},TargetValue:vr.targetMemoryUtilization,ScaleInCooldown:300,ScaleOutCooldown:60}}})}if(v?.domain&&v?.hostedZoneId)this.builder.addResource(`${u}${g}ApiDnsRecord`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:v.hostedZoneId,Name:`api.${v.domain}`,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":[yt,"DNSName"]},HostedZoneId:{"Fn::GetAtt":[yt,"CanonicalHostedZoneID"]}}}});this.builder.addOutput("ECSClusterArn",{Description:"ECS Cluster ARN",Value:{"Fn::GetAtt":[L,"Arn"]},Export:{Name:{"Fn::Sub":"${AWS::StackName}-ecs-cluster-arn"}}}),this.builder.addOutput("ECSServiceName",{Description:"ECS Service Name",Value:`${u}-${g}-${he}`,Export:{Name:{"Fn::Sub":"${AWS::StackName}-ecs-service-name"}}}),this.builder.addOutput("LoadBalancerDNS",{Description:"Application Load Balancer DNS Name",Value:{"Fn::GetAtt":[yt,"DNSName"]},Export:{Name:{"Fn::Sub":"${AWS::StackName}-alb-dns"}}})}else{let vt=`${u}${g}${he}Service`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(vt,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${u}-${g}-${he}`,Cluster:{Ref:L},TaskDefinition:{Ref:ht},DesiredCount:Ct.desiredCount||1,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:Ae}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},Tags:[{Key:"Name",Value:`${u}-${g}-${he}`},{Key:"Environment",Value:g}]},DependsOn:[ht]})}break}}generateServerless(u,g){if(this.mergedConfig.infrastructure?.functions)for(let[h,y]of Object.entries(this.mergedConfig.infrastructure.functions)){if(!this.shouldDeploy(y))continue;let{role:R,logicalId:v}=ue.createRole({slug:u,environment:g,roleName:`${u}-${g}-${h}-role`,servicePrincipal:"lambda.amazonaws.com",managedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]});this.builder.addResource(v,R);let{lambdaFunction:P,logicalId:L}=a.createLambdaFunction({slug:u,environment:g,functionName:`${u}-${g}-${h}`,handler:y.handler||"index.handler",runtime:y.runtime||"nodejs20.x",code:{zipFile:y.code||"export const handler = async () => ({ statusCode: 200 });"},role:v,timeout:y.timeout,memorySize:y.memorySize});this.builder.addResource(L,P)}if(this.mergedConfig.infrastructure?.api){let{restApi:h,logicalId:y}=ml.createRestApi({slug:u,environment:g,apiName:`${u}-${g}-api`});this.builder.addResource(y,h)}}generateServer(u,g){if(!this.mergedConfig.infrastructure?.servers)return;let h=this.mergedConfig.infrastructure.servers,y=this.mergedConfig.infrastructure?.compute,R=this.mergedConfig.infrastructure?.ssl;if(Object.values(h).some((P)=>!P.privateNetwork||P.privateNetwork==="create"))this.generateNetworkInfrastructure(u,g);for(let[P,L]of Object.entries(h)){let z=L.instanceType||L.size||y?.size,he=(z?a.InstanceSize.specs[z]:void 0)?.instanceType||z||"t3.micro",Ct=L.type||"app",It=L.userData||L.startupScript;if(!It)It=a.UserData.generateAppServerScript({runtime:"bun",runtimeVersion:L.bunVersion||"latest",webServer:"none",domain:L.domain,enableSsl:!!R?.enabled,sslEmail:R?.letsEncrypt?.email,installRedis:Ct==="cache",installDatabaseClients:!!L.database});let Ve=L.privateNetwork&&L.privateNetwork!=="create"?L.privateNetwork:{Ref:"VPC"},Me=L.subnet||{Ref:"PublicSubnet1"},j=!!this.mergedConfig.infrastructure?.email?.server?.enabled,ht=[22,80,443,this.resolveApiOriginPort()];if(j)ht.push(25,465,587,143,993);let G=a.createServerModeStack({slug:`${u}-${P}`,environment:g,vpcId:Ve,subnetId:Me,instanceType:he,keyName:L.keyName||`${u}-${g}`,domain:L.domain,userData:It,volumeSize:L.diskSize||20,imageId:L.image,allowedPorts:ht});for(let[Ke,yt]of Object.entries(G.resources))this.builder.addResource(Ke,yt);this.serverEipLogicalIds.set(P,G.outputs.eipLogicalId),this.serverEipLogicalIds.set(`${P}Instance`,G.outputs.instanceLogicalId),this.builder.addOutput(`${P}InstanceId`,{Value:{Ref:G.outputs.instanceLogicalId},Description:`Instance ID for ${P} server`}),this.builder.addOutput(`${P}PublicIp`,{Value:{Ref:G.outputs.eipLogicalId},Description:`Public IP for ${P} server`})}}generateComputeApp(u,g){let h=this.mergedConfig.infrastructure?.compute;if(!h)return;let y=this.mergedConfig.sites||{},R=Object.entries(y),P=this.mergedConfig.infrastructure?.dns?.domain,L=this.mergedConfig.infrastructure?.database,z=h.size,he=(z?a.InstanceSize.specs[z]:void 0)?.instanceType||z||"t3.micro";if(!this.builder.hasResource("VPC"))this.generateNetworkInfrastructure(u,g);let Ct=this.buildCaddyfile(R),It=a.UserData.generateBunAppScript({runtime:h.runtime||"bun",runtimeVersion:h.runtimeVersion||"latest",systemPackages:h.systemPackages,database:L,caddyfile:Ct}),Ve=eo(h.appUpdates),Me=Ve.length>0?`${It}
11
11
  ${Ve.join(`
12
12
  `)}
13
- `:It,We=R.map(([,Et])=>Et.port).filter((Et)=>typeof Et==="number"&&![80,443].includes(Et)),j=this.resolveApiOriginPort(),ht=`${u}${g}DeployBucket`.replace(/[^a-zA-Z0-9]/g,""),G=`${u}-${g}-deploy`;this.builder.addResource(ht,{Type:"AWS::S3::Bucket",Properties:{BucketName:G,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:u},{Key:"Environment",Value:g},{Key:"ManagedBy",Value:"ts-cloud"}]}});let Ke=a.createServerModeStack({slug:`${u}-app`,environment:g,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},instanceType:fe,keyName:h.allowSsh?`${u}-${g}`:void 0,domain:P,userData:Me,volumeSize:h.disk?.size||20,imageId:h.image,allowedPorts:[...h.allowSsh?[22]:[],80,443,j,...We]}),yt=Ke.resources[Ke.outputs.instanceLogicalId];if(yt?.Properties){let Et=yt.Properties.Tags||[];yt.Properties.Tags=[...Et,{Key:"Project",Value:u},{Key:"Environment",Value:g},{Key:"Role",Value:"app"},{Key:"ManagedBy",Value:"ts-cloud"}]}let vt=Ke.resources[Ke.outputs.roleLogicalId];if(vt?.Properties)vt.Properties.Policies=vt.Properties.Policies||[],vt.Properties.Policies.push({PolicyName:"DeployBucketRead",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:GetObject","s3:ListBucket"],Resource:[`arn:aws:s3:::${G}`,`arn:aws:s3:::${G}/*`]}]}});for(let[Et,Zt]of Object.entries(Ke.resources))this.builder.addResource(Et,Zt);this.builder.addOutput("deployBucketName",{Value:{Ref:ht},Description:"S3 bucket where release tarballs are uploaded"}),this.builder.addOutput("appInstanceId",{Value:{Ref:Ke.outputs.instanceLogicalId},Description:"EC2 instance ID for the app server"}),this.builder.addOutput("appPublicIp",{Value:{Ref:Ke.outputs.eipLogicalId},Description:"Public IP for the app server"}),this.serverEipLogicalIds.set("app",Ke.outputs.eipLogicalId),this.serverEipLogicalIds.set("appInstance",Ke.outputs.instanceLogicalId)}jumpBoxFileSystemId(u,g,h){let y=Object.keys(this.mergedConfig.infrastructure?.fileSystem??{});if(typeof h==="string")return y.includes(h)?{Ref:this.fileSystemLogicalId(u,g,h)}:h;if(y.length===1)return{Ref:this.fileSystemLogicalId(u,g,y[0])};throw Error(y.length===0?"infrastructure.jumpBox.mountEfs is true, but infrastructure.fileSystem declares no file system. Declare one, or set mountEfs to an EFS id.":`infrastructure.jumpBox.mountEfs is true, but infrastructure.fileSystem declares ${y.length} (${y.join(", ")}). Set mountEfs to the name of the one to mount.`)}generateJumpBox(u,g){let h=this.mergedConfig.infrastructure?.jumpBox;if(!h)return;let y=h===!0?{}:h;if(y.enabled===!1)return;this.generateNetworkInfrastructure(u,g);let R=y.size||"micro",P=a.InstanceSize.specs[R]?.instanceType||R||"t3.micro",L=a.createJumpBox({slug:u,environment:g,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:y.keyName,instanceType:P,allowedCidrs:y.allowedCidrs,mountEfs:y.mountEfs?{fileSystemId:this.jumpBoxFileSystemId(u,g,y.mountEfs),mountPath:y.mountPath||"/mnt/efs"}:void 0,databaseTools:y.databaseTools});for(let[z,he]of Object.entries(L.resources))this.builder.addResource(z,he);this.builder.addOutput("JumpBoxInstanceId",{Value:{Ref:L.instanceLogicalId},Description:"The ID of the JumpBox EC2 instance (use with SSM Session Manager or SSH)"})}generateSharedInfrastructure(u,g){let h=this.mergedConfig.infrastructure?.ssl,y=this.mergedConfig.infrastructure?.dns,R=y?.domain,v=y?.hostedZoneId,P=[],L,z;if(h?.certificateArn)z=h.certificateArn;else if(h?.enabled&&R&&v){let We=h.domains||[R],j=We[0],ht=We.slice(1).map((yt)=>{if(yt.includes(".")&&yt.endsWith(j))return yt.replace(`.${j}`,"");return yt}),{certificate:G,logicalId:Ke}=E.createCertificate({domain:j,subdomains:ht,slug:u,environment:g,validationMethod:"DNS",hostedZoneId:v});L=Ke,this.builder.addResource(Ke,G)}if(this.mergedConfig.infrastructure?.storage){let We=Object.entries(this.mergedConfig.infrastructure.storage).some(([,G])=>G.website),j;if(We&&(L||z))j=`${u}${g}CloudFrontOAC`.replace(/[^a-zA-Z0-9]/g,""),this.builder.addResource(j,{Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${u}-${g}-s3-oac`,Description:`OAC for ${u} ${g} S3 website buckets`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}});let ht=Object.entries(this.mergedConfig.infrastructure.storage).map(([G,Ke])=>({name:G,config:Ke,mountPath:this.normalizeMountPath(Ke),rewriteStyle:Ke.pathRewriteStyle||"directory",logicalId:this.storageBucketLogicalId(u,g,G)})).filter((G)=>G.name!=="public"&&G.config.website&&G.mountPath);for(let[G,Ke]of Object.entries(this.mergedConfig.infrastructure.storage)){let yt=!!(Ke.website&&j),vt=this.storageBucketName(u,g,G),{bucket:Et,logicalId:Zt}=xe.createBucket({slug:u,name:G,environment:g,bucketName:vt,versioning:Ke.versioning,encryption:Ke.encryption,public:yt?!1:Ke.public}),Yt=this.normalizeMountPath(Ke),Qt;if(Ke.failover){let Xt=`infrastructure.storage.${G}`;if(!yt||!R||Yt&&G!=="public")throw Error(`${Xt}.failover needs this bucket to be served by its own CloudFront distribution: a website bucket (website: true), not mounted under the path of another site, with infrastructure.dns.domain set and SSL configured (infrastructure.ssl.certificateArn, or ssl.enabled with dns.hostedZoneId).`);if(Qt=wm({failover:Ke.failover,primaryBucket:vt,primaryRegion:this.mergedConfig.project.region||"us-east-1",where:Xt}),Qt.replicate&&Et.Properties){let er=`${Zt}FailoverReplicationRole`;this.builder.addResource(er,Dm({primaryBucket:vt,replicaBucket:Qt.replicaBucket}));let Lr=Et.Properties;Lr.VersioningConfiguration={Status:"Enabled"},Lr.ReplicationConfiguration=Pm({replicaBucket:Qt.replicaBucket,roleArn:{"Fn::GetAtt":[er,"Arn"]}})}}if(yt&&Et.Properties)Et.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1};if(this.builder.addResource(Zt,Et),Ke.website){let Xt=typeof Ke.website==="object"?Ke.website:{},er=xe.enableWebsiteHosting(Et,Xt.indexDocument||"index.html",Xt.errorDocument);this.builder.addResource(Zt,er)}let vr=this.normalizeMountPath(Ke);if(yt&&j&&R&&!(vr&&G!=="public")){let Xt=`${u}${g}${G}CDN`.replace(/[^a-zA-Z0-9]/g,""),er=[];if(Ke.aliases&&Ke.aliases.length>0)er.push(...Ke.aliases);else if(G==="public"){if(er.push(R),h?.domains?.includes(`www.${R}`))er.push(`www.${R}`)}else if(G==="docs")er.push(`docs.${R}`);else if(G==="blog")er.push(`blog.${R}`);let Lr=typeof Ke.website==="object"?Ke.website:{},zr=Ke.spa===!0,Fr=Lr.errorDocument||(zr?"index.html":"404.html"),Or=[];if(zr)Or.push({ErrorCode:403,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:300});else Or.push({ErrorCode:403,ResponseCode:404,ResponsePagePath:`/${Fr}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${Fr}`,ErrorCachingMinTTL:300});let jr=z&&er.length>0?{AcmCertificateArn:z,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:L&&er.length>0?{AcmCertificateArn:{Ref:L},SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},Mn=`S3-${u}-${g}-${G}`,Za=this.mergedConfig.project.region||"us-east-1",Zn;if(!zr)Zn=`${u}${g}${G}UrlRewrite`.replace(/[^a-zA-Z0-9]/g,""),this.builder.addResource(Zn,{Type:"AWS::CloudFront::Function",Properties:{Name:`${u}-${g}-${G}-url-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`URL rewrite for ${u} ${g} ${G} - 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 pi=[{Id:Mn,DomainName:{"Fn::Sub":`\${${Zt}}.s3.${Za}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:j}}],oo=[],Xa=[];if(this.shouldRouteStorageBucketToCompute(G,Ke)){this.appendComputeAppOrigin(pi,oo,Xa,u,g,this.resolveComputeCachePathPatterns(Ke.computeRoutes));for(let rr of ht){let ho=`S3-${u}-${g}-${rr.name}`,wc=`${u}${g}${rr.name}PathMountRewrite`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(wc,{Type:"AWS::CloudFront::Function",Properties:{Name:`${u}-${g}-${rr.name}-path-mount-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`Path mount rewrite for ${u} ${g} ${rr.name} at ${rr.mountPath}`,Runtime:"cloudfront-js-2.0"},FunctionCode:this.pathMountRewriteFunctionCode(rr.mountPath,rr.rewriteStyle)}}),pi.push({Id:ho,DomainName:{"Fn::Sub":`\${${rr.logicalId}}.s3.${Za}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:j}}),Xa.push(rr.logicalId,wc);for(let fp of[rr.mountPath,`${rr.mountPath}/*`])oo.push({PathPattern:fp,TargetOriginId:ho,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":[wc,"FunctionARN"]}}]})}}let po,Xc=Mn;if(Qt){let rr=`${Mn}-failover`;Object.assign(pi[0],Qt.primaryConnection),pi.push({Id:rr,DomainName:Rm(Qt.replicaBucket,Qt.replicaRegion),OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:j}}),po=un({primaryOriginId:Mn,secondaryOriginId:rr,statusCodes:Qt.statusCodes}),Xc=po.Items[0].Id}let $c={Type:"AWS::CloudFront::Distribution",DependsOn:[Zt,j,...Zn?[Zn]:[],...Xa],Properties:{DistributionConfig:{Enabled:!0,Comment:`${u} ${g} ${G} site`,DefaultRootObject:"index.html",Origins:pi,...po?{OriginGroups:po}:{},DefaultCacheBehavior:{TargetOriginId:Xc,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",...Zn?{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[Zn,"FunctionARN"]}}]}:{}},...oo.length>0?{CacheBehaviors:oo}:{},...er.length>0?{Aliases:er}:{},ViewerCertificate:jr,PriceClass:"PriceClass_100",HttpVersion:"http2and3",IPV6Enabled:!0,CustomErrorResponses:Or}}};if(L)$c.DependsOn.push(L);if(Qt)Nt($c.Properties.DistributionConfig,`infrastructure.storage.${G}`),this.storageFailoverReplicas.push({name:G,primaryBucket:vt,primaryRegion:Za,replicaBucket:Qt.replicaBucket,replicaRegion:Qt.replicaRegion,replicate:Qt.replicate,distributionArnOutput:`${G}CloudFrontDistributionArn`}),this.builder.addOutput(`${G}CloudFrontDistributionArn`,{Value:{"Fn::Sub":`arn:\${AWS::Partition}:cloudfront::\${AWS::AccountId}:distribution/\${${Xt}}`},Description:`CloudFront distribution ARN for ${G} (scopes the bucket policy of the failover replica)`}),this.builder.addOutput(`${G}FailoverBucketName`,{Value:Qt.replicaBucket,Description:`Failover replica bucket for ${G} (${Qt.replicaRegion}), outside this stack`});this.builder.addResource(Xt,$c);let gp=`${Zt}CloudFrontPolicy`;if(this.builder.addResource(gp,{Type:"AWS::S3::BucketPolicy",DependsOn:[Zt,Xt],Properties:{Bucket:{Ref:Zt},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":`arn:aws:s3:::\${${Zt}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${Xt}}`}}}}]}}}),this.shouldRouteStorageBucketToCompute(G,Ke))for(let rr of ht){let ho=`${rr.logicalId}CloudFrontPolicy`;this.builder.addResource(ho,{Type:"AWS::S3::BucketPolicy",DependsOn:[rr.logicalId,Xt],Properties:{Bucket:{Ref:rr.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:::\${${rr.logicalId}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${Xt}}`}}}}]}}})}if(er.length>0)P.push({name:G,bucketLogicalId:Zt,distLogicalId:Xt,oacLogicalId:j,aliases:er});this.builder.addOutput(`${G}CloudFrontDomain`,{Value:{"Fn::GetAtt":[Xt,"DomainName"]},Description:`CloudFront domain for ${G}`}),this.builder.addOutput(`${G}CloudFrontDistributionId`,{Value:{Ref:Xt},Description:`CloudFront distribution ID for ${G}`})}if(this.builder.addOutput(`${G}BucketName`,{Value:{Ref:Zt},Description:`S3 bucket name for ${G}`}),G==="public")this.builder.addOutput("FrontendBucketName",{Value:{Ref:Zt},Description:"Frontend S3 bucket name"});if(G==="docs")this.builder.addOutput("DocsBucketName",{Value:{Ref:Zt},Description:"Documentation S3 bucket name"});if(G==="blog")this.builder.addOutput("BlogBucketName",{Value:{Ref:Zt},Description:"Blog S3 bucket name"})}}if(this.mergedConfig.infrastructure?.sftp){let We=this.mergedConfig.infrastructure.sftp,j=pl.create({...We,storage:this.resolveSftpStorage(We,u,g)??We.storage,slug:u,environment:g});for(let[ht,G]of Object.entries(j.resources))this.builder.addResource(ht,G);this.builder.addOutput("SftpServerId",{Value:{Ref:j.serverLogicalId},Description:"AWS Transfer Family SFTP server ID"}),this.builder.addOutput("SftpEndpoint",{Value:{"Fn::Sub":`\${${j.serverLogicalId}}.server.transfer.\${AWS::Region}.amazonaws.com`},Description:"AWS Transfer Family SFTP endpoint"}),this.builder.addOutput("SftpStorageDomain",{Value:j.domain,Description:"Storage backing the SFTP server (EFS or S3)"})}if(v&&P.length>0)for(let{name:We,distLogicalId:j,aliases:ht}of P)for(let G of ht){let Ke=G.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${Ke}ARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[j],Properties:{HostedZoneId:v,Name:G,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":[j,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}}),this.builder.addResource(`${Ke}AAAARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[j],Properties:{HostedZoneId:v,Name:G,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":[j,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}})}if(this.mergedConfig.infrastructure?.databases){for(let[We,j]of Object.entries(this.mergedConfig.infrastructure.databases))if(j.engine==="dynamodb"){let{table:ht,logicalId:G}=ur.createTable({slug:u,environment:g,tableName:`${u}-${g}-${We}`,partitionKey:j.partitionKey||{name:"id",type:"S"},sortKey:j.sortKey});this.builder.addResource(G,ht)}else if(j.engine==="postgres"){let{dbInstance:ht,logicalId:G}=ur.createPostgres({slug:u,environment:g,dbInstanceIdentifier:`${u}-${g}-${We}`,masterUsername:j.username||"admin",masterUserPassword:j.password||"changeme123",allocatedStorage:j.storage||20,dbInstanceClass:j.instanceClass||"db.t3.micro"});this.builder.addResource(G,ht)}else if(j.engine==="mysql"){let{dbInstance:ht,logicalId:G}=ur.createMysql({slug:u,environment:g,dbInstanceIdentifier:`${u}-${g}-${We}`,masterUsername:j.username||"admin",masterUserPassword:j.password||"changeme123",allocatedStorage:j.storage||20,dbInstanceClass:j.instanceClass||"db.t3.micro"});this.builder.addResource(G,ht)}}if(this.mergedConfig.infrastructure?.cdn)for(let[We,j]of Object.entries(this.mergedConfig.infrastructure.cdn)){if(!j.origin)continue;let ht=typeof j.customDomain==="string"?j.customDomain:j.customDomain?.domain||j.domain,G=typeof j.customDomain==="object"?j.customDomain?.certificateArn:j.certificateArn,Ke=G||z,yt=`${u}${g}${We}CDN`.replace(/[^a-zA-Z0-9]/g,""),vt=`S3-${u}-${g}-${We}-cdn`,Et=[{Id:vt,DomainName:j.origin,OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginShield:j.originShield?{Enabled:!0,OriginShieldRegion:j.originShieldRegion||this.mergedConfig.environments[g]?.region||this.mergedConfig.project.region||"us-east-1"}:{Enabled:!1},...de(j,`infrastructure.cdn.${We}`)}],Zt=[],Yt=[],Qt=["GET","HEAD","OPTIONS"],vr=vt,Xt;if(j.failoverOrigin){kt(Qt,`the default cache behavior of infrastructure.cdn.${We}`);let Fr=`${vt}-failover`,Or=typeof j.failoverOrigin==="string"?{domain:j.failoverOrigin}:j.failoverOrigin;if(!Or.domain)throw Error(`infrastructure.cdn.${We}.failoverOrigin.domain is required`);if(Or.domain===j.origin)throw Error(`infrastructure.cdn.${We}: failoverOrigin must differ from origin (both are ${j.origin})`);Et.push({Id:Fr,DomainName:Or.domain,OriginPath:Or.originPath||"",...Go(Or.domain)?{S3OriginConfig:{OriginAccessIdentity:""}}:{CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"}},OriginShield:{Enabled:!1},...de(Or,`infrastructure.cdn.${We}.failoverOrigin`)}),Xt=un({primaryOriginId:vt,secondaryOriginId:Fr,statusCodes:j.failoverStatusCodes}),vr=Xt.Items[0].Id}else if(j.failoverStatusCodes)throw Error(`infrastructure.cdn.${We}: failoverStatusCodes needs failoverOrigin to fail over to`);if(j.routeCompute)this.appendComputeAppOrigin(Et,Zt,Yt,u,g,this.resolveComputeCachePathPatterns(j.computeRoutes));let er=Ke&&ht?{AcmCertificateArn:L&&!G?{Ref:L}:Ke,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},Lr=[...Yt];if(L&&!G&&ht)Lr.push(L);let zr={Type:"AWS::CloudFront::Distribution",...Lr.length>0?{DependsOn:Lr}:{},Properties:{DistributionConfig:{Enabled:!0,Comment:`${u} ${g} ${We} CDN`,DefaultRootObject:"index.html",Origins:Et,...Xt?{OriginGroups:Xt}:{},DefaultCacheBehavior:{TargetOriginId:vr,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:Qt,CachedMethods:["GET","HEAD","OPTIONS"],Compress:j.compress!==!1,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},...Zt.length>0?{CacheBehaviors:Zt}:{},...ht&&Ke?{Aliases:[ht]}:{},ViewerCertificate:er,PriceClass:"PriceClass_100",HttpVersion:j.http3?"http2and3":"http2"}}};if(Nt(zr.Properties.DistributionConfig,`infrastructure.cdn.${We}`),this.builder.addResource(yt,zr),v&&ht&&Ke){let Fr=ht.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${Fr}CdnARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[yt,...L&&!G?[L]:[]],Properties:{HostedZoneId:v,Name:ht,Type:"A",AliasTarget:{HostedZoneId:"Z2FDTNDATAQYW2",DNSName:{"Fn::GetAtt":[yt,"DomainName"]}}}})}}if(this.mergedConfig.infrastructure?.queues)for(let[We,j]of Object.entries(this.mergedConfig.infrastructure.queues)){if(!this.shouldDeploy(j))continue;let{queue:ht,logicalId:G}=J.createQueue({slug:u,environment:g,name:`${u}-${g}-${We}`,fifo:j.fifo,visibilityTimeout:j.visibilityTimeout,messageRetentionPeriod:j.messageRetentionPeriod,delaySeconds:j.delaySeconds,maxMessageSize:j.maxMessageSize,receiveMessageWaitTime:j.receiveMessageWaitTime,contentBasedDeduplication:j.contentBasedDeduplication,encrypted:j.encrypted,kmsKeyId:j.kmsKeyId});this.builder.addResource(G,ht);let Ke;if(j.deadLetterQueue){let{deadLetterQueue:yt,updatedSourceQueue:vt,deadLetterLogicalId:Et}=J.createDeadLetterQueue(G,{slug:u,environment:g,maxReceiveCount:j.maxReceiveCount});Ke=Et,this.builder.addResource(Et,yt);let Yt=this.builder.getResources()[G];if(Yt?.Properties)Yt.Properties.RedrivePolicy=vt.Properties?.RedrivePolicy}if(j.trigger){let yt=j.trigger,vt=`${u}${g}${yt.functionName}`.replace(/[^a-zA-Z0-9]/g,""),Et={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:{"Fn::GetAtt":[G,"Arn"]},FunctionName:{Ref:vt},BatchSize:yt.batchSize||10,MaximumBatchingWindowInSeconds:yt.batchWindow||0,Enabled:!0,...yt.reportBatchItemFailures!==!1&&{FunctionResponseTypes:["ReportBatchItemFailures"]},...yt.maxConcurrency&&{ScalingConfig:{MaximumConcurrency:yt.maxConcurrency}},...yt.filterPattern&&{FilterCriteria:{Filters:[{Pattern:JSON.stringify(yt.filterPattern)}]}}},DependsOn:[G,vt]};this.builder.addResource(`${G}Trigger`,Et)}if(j.alarms?.enabled){let yt=j.alarms,vt=yt.notificationTopicArn;if(!vt&&yt.notificationEmails?.length){let Yt=`${G}AlarmTopic`;this.builder.addResource(Yt,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${u}-${g}-${We}-alarms`,DisplayName:`${We} Queue Alarms`}}),yt.notificationEmails.forEach((Qt,vr)=>{this.builder.addResource(`${Yt}Sub${vr}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:Yt},Protocol:"email",Endpoint:Qt}})}),vt={Ref:Yt}}let Et=yt.queueDepthThreshold||1000;this.builder.addResource(`${G}DepthAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${u}-${g}-${We}-queue-depth`,AlarmDescription:`Queue ${We} depth exceeds ${Et} messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:Et,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[G,"QueueName"]}}],...vt&&{AlarmActions:[vt],OKActions:[vt]}}});let Zt=yt.messageAgeThreshold||3600;if(this.builder.addResource(`${G}AgeAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${u}-${g}-${We}-message-age`,AlarmDescription:`Queue ${We} oldest message exceeds ${Zt} seconds`,MetricName:"ApproximateAgeOfOldestMessage",Namespace:"AWS/SQS",Statistic:"Maximum",Period:300,EvaluationPeriods:2,Threshold:Zt,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[G,"QueueName"]}}],...vt&&{AlarmActions:[vt],OKActions:[vt]}}}),Ke&&yt.dlqAlarm!==!1)this.builder.addResource(`${Ke}Alarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${u}-${g}-${We}-dlq-messages`,AlarmDescription:`Dead letter queue for ${We} has messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Sum",Period:300,EvaluationPeriods:1,Threshold:0,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[Ke,"QueueName"]}}],...vt&&{AlarmActions:[vt]}}})}if(j.subscribe){let yt=j.subscribe,vt=yt.topicArn;if(!vt&&yt.topicName)vt={Ref:yt.topicName};if(vt){this.builder.addResource(`${G}SnsPolicy`,{Type:"AWS::SQS::QueuePolicy",Properties:{Queues:[{Ref:G}],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"sns.amazonaws.com"},Action:"sqs:SendMessage",Resource:{"Fn::GetAtt":[G,"Arn"]},Condition:{ArnEquals:{"aws:SourceArn":vt}}}]}}});let Et={TopicArn:vt,Protocol:"sqs",Endpoint:{"Fn::GetAtt":[G,"Arn"]},RawMessageDelivery:yt.rawMessageDelivery||!1};if(yt.filterPolicy)Et.FilterPolicy=yt.filterPolicy,Et.FilterPolicyScope=yt.filterPolicyScope||"MessageAttributes";this.builder.addResource(`${G}SnsSub`,{Type:"AWS::SNS::Subscription",Properties:Et,DependsOn:`${G}SnsPolicy`})}}}if(this.mergedConfig.infrastructure?.realtime?.enabled)if((this.mergedConfig.infrastructure.realtime.mode||"serverless")==="server")this.generateRealtimeServerResources(u,g);else this.generateRealtimeResources(u,g);let he=this.mergedConfig.infrastructure?.redirects;if(he){let We=he.target||this.mergedConfig.infrastructure?.dns?.domain||"",j=he.protocol||"https";if(he.domains?.length&&We)for(let ht of he.domains){let{bucket:G,bucketPolicy:Ke,logicalId:yt,policyLogicalId:vt}=xt.createDomainRedirectBucket({slug:u,environment:g,sourceDomain:ht,targetDomain:We,protocol:j});this.builder.addResource(yt,G),this.builder.addResource(vt,Ke)}if(he.paths&&Object.keys(he.paths).length>0){let ht=xt.fromMapping(he.paths,{statusCode:he.statusCode||301}),{function:G,logicalId:Ke}=xt.createPathRedirectFunction({slug:u,environment:g,rules:ht});this.builder.addResource(Ke,G)}}if(this.mergedConfig.infrastructure?.monitoring?.alarms)for(let[We,j]of Object.entries(this.mergedConfig.infrastructure.monitoring.alarms)){let{alarm:ht,logicalId:G}=jo.createAlarm({slug:u,environment:g,alarmName:`${u}-${g}-${We}`,metricName:j.metricName||"Errors",namespace:j.namespace||"AWS/Lambda",threshold:j.threshold||1,comparisonOperator:j.comparisonOperator||"GreaterThanThreshold"});this.builder.addResource(G,ht)}let fe=this.mergedConfig.infrastructure?.cache;if(fe){let We=fe.type||"redis";if(We==="redis"){this.generateNetworkInfrastructure(u,g);let j=fe.redis||{},{replicationGroup:ht,subnetGroup:G,logicalId:Ke,subnetGroupId:yt}=qo.createRedis({slug:u,environment:g,nodeType:j.nodeType||fe.nodeType||"cache.t3.micro",engineVersion:j.engineVersion||"7.1",port:j.port||6379,numCacheClusters:j.numCacheNodes||2,automaticFailover:j.automaticFailoverEnabled!==!1,atRestEncryption:!0,transitEncryption:!0,snapshotRetentionDays:j.snapshotRetentionLimit||7,snapshotWindow:j.snapshotWindow,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(Ke,ht),G&&yt)this.builder.addResource(yt,G);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[Ke,"PrimaryEndPoint.Address"]},Description:"Redis primary endpoint address"}),this.builder.addOutput("CachePort",{Value:{"Fn::GetAtt":[Ke,"PrimaryEndPoint.Port"]},Description:"Redis primary endpoint port"})}else if(We==="memcached"){this.generateNetworkInfrastructure(u,g);let j=fe.elasticache||{},{cluster:ht,subnetGroup:G,logicalId:Ke,subnetGroupId:yt}=qo.createMemcached({slug:u,environment:g,nodeType:j.nodeType||fe.nodeType||"cache.t3.micro",engineVersion:j.engineVersion||"1.6.22",numCacheNodes:j.numCacheNodes||2,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(Ke,ht),G&&yt)this.builder.addResource(yt,G);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[Ke,"ConfigurationEndpoint.Address"]},Description:"Memcached configuration endpoint address"})}}let Ct=this.mergedConfig.infrastructure?.email;if(Ct){let We=Ct.domain||this.mergedConfig.infrastructure?.dns?.domain;if(We){let{emailIdentity:j,logicalId:ht}=f.verifyDomain({domain:We,slug:u,environment:g,enableDkim:Ct.enableDkim!==!1,dkimKeyLength:Ct.dkimKeyLength||"RSA_2048_BIT"});if(this.builder.addResource(ht,j),Ct.configurationSet!==!1){let{configurationSet:yt,logicalId:vt}=f.createConfigurationSet({slug:u,environment:g});this.builder.addResource(vt,yt)}let G=Ct.hostedZoneId||this.mergedConfig.infrastructure?.dns?.hostedZoneId;if(G){if(Ct.enableDkim!==!1)for(let Yt=1;Yt<=3;Yt++){let Qt=`DkimRecord${Yt}${We.replace(/\./g,"")}`;this.builder.addResource(Qt,{Type:"AWS::Route53::RecordSet",DependsOn:[ht],Properties:{HostedZoneId:G,Name:{"Fn::GetAtt":[ht,`DkimDNSTokenName${Yt}`]},Type:"CNAME",TTL:1800,ResourceRecords:[{"Fn::GetAtt":[ht,`DkimDNSTokenValue${Yt}`]}]}})}let{record:yt,logicalId:vt}=f.createSpfRecord(We,G);this.builder.addResource(vt,yt);let{record:Et,logicalId:Zt}=f.createDmarcRecord(We,G,{policy:"none",reportingEmail:Ct.dmarcReportingEmail||`dmarc-reports@${We}`});this.builder.addResource(Zt,Et)}this.builder.addOutput("EmailDomain",{Value:We,Description:"SES verified email domain"});let Ke=Ct.server;if(Ke?.enabled&&G){let yt=this.mergedConfig.environments[g]?.region||this.mergedConfig.project.region||"us-east-1",vt=`${u}-${g}-email`,{role:Et,policy:Zt,roleLogicalId:Yt,policyLogicalId:Qt}=f.createEmailLambdaRole({slug:u,environment:g,s3BucketArn:`arn:aws:s3:::${vt}`,sesIdentityArn:`arn:aws:ses:${yt}:*:identity/${We}`});this.builder.addResource(Yt,Et),this.builder.addResource(Qt,Zt);let{function:vr,permission:Xt,logicalId:er,permissionLogicalId:Lr}=f.createInboundEmailLambda({slug:u,environment:g,roleArn:{"Fn::GetAtt":[Yt,"Arn"]},s3BucketName:vt,organizedPrefix:"mailboxes/"});this.builder.addResource(er,vr),this.builder.addResource(Lr,Xt);let zr=f.createInboundEmailSetup({slug:u,environment:g,domain:We,s3BucketName:vt,s3KeyPrefix:"inbox/",region:yt,hostedZoneId:G,lambdaFunctionArn:{"Fn::GetAtt":[er,"Arn"]}});for(let[Or,jr]of Object.entries(zr.resources)){if(jr.Type==="AWS::SES::ReceiptRule")jr.DependsOn=[Lr,er];this.builder.addResource(Or,jr)}this.builder.addOutput("InboundEmailLambda",{Value:{Ref:er},Description:"Inbound email processing Lambda function"}),this.builder.addOutput("EmailBucket",{Value:vt,Description:"S3 bucket for email storage"});let Fr=this.serverEipLogicalIds.get("app");if(Fr&&G){let jr=`${Ke?.subdomain||"mail"}.${We}`,Mn=jr.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${Mn}ARecord`,{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:G,Name:jr,Type:"A",TTL:"300",ResourceRecords:[{Ref:Fr}]}})}this.builder.addOutput("MailHost",{Value:`mail.${We}`,Description:"Mail server hostname for SMTP/IMAP clients"})}}}let It=this.mergedConfig.infrastructure?.search;if(It){let We=It.vpc?{subnetIds:[{Ref:"PublicSubnet1"}],securityGroupIds:[]}:void 0;if(We)this.generateNetworkInfrastructure(u,g);let{domain:j,logicalId:ht}=gr.createDomain({slug:u,environment:g,engineVersion:It.engineVersion||"OpenSearch_2.11",instanceType:It.instanceType||"t3.small.search",instanceCount:It.instanceCount||1,volumeSize:It.volumeSize||10,volumeType:It.volumeType||"gp3",dedicatedMaster:It.dedicatedMaster||!1,dedicatedMasterType:It.dedicatedMasterType,dedicatedMasterCount:It.dedicatedMasterCount||3,multiAz:It.multiAz||!1,encryption:It.encryption||{atRest:!0,nodeToNode:!0},advancedSecurity:It.advancedSecurity,autoTune:It.autoTune!==!1,vpc:We});this.builder.addResource(ht,j),this.builder.addOutput("SearchDomainEndpoint",{Value:{"Fn::GetAtt":[ht,"DomainEndpoint"]},Description:"OpenSearch domain endpoint"}),this.builder.addOutput("SearchDomainArn",{Value:{"Fn::GetAtt":[ht,"Arn"]},Description:"OpenSearch domain ARN"})}let Ve=this.mergedConfig.infrastructure?.fileSystem;if(Ve&&Object.keys(Ve).length>0){this.generateNetworkInfrastructure(u,g);for(let[We,j]of Object.entries(Ve)){let{fileSystem:ht,logicalId:G}=tt.createFileSystem({slug:`${u}-${We}`,environment:g,encrypted:j.encrypted!==!1,performanceMode:j.performanceMode||"generalPurpose",throughputMode:j.throughputMode||"bursting",enableBackup:!0});this.builder.addResource(G,ht);let{securityGroup:Ke,logicalId:yt}=tt.createEfsSecurityGroup({slug:`${u}-${We}`,environment:g,vpcId:{Ref:"VPC"},sourceCidrBlocks:["10.0.0.0/16"]});this.builder.addResource(yt,Ke);let{mountTargets:vt,logicalIds:Et}=tt.createMultiAzMountTargets(G,{slug:`${u}-${We}`,environment:g,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],securityGroupId:{Ref:yt}});for(let Zt=0;Zt<vt.length;Zt++)this.builder.addResource(Et[Zt],vt[Zt]);this.builder.addOutput(`${We}FileSystemId`,{Value:{Ref:G},Description:`EFS file system ID for ${We}`})}}let Me=this.mergedConfig.infrastructure?.ai;if(Me){let We=Me.service||"ecs",j=Me.models||["*"],ht=Me.allowStreaming!==!1,G;if(We==="ecs")G=Oe.enableBedrockForEcs({slug:u,environment:g,models:j,allowStreaming:ht});else if(We==="ec2")G=Oe.enableBedrockForEc2({slug:u,environment:g,models:j,allowStreaming:ht});else if(We==="lambda")G=Oe.enableBedrockForLambda({slug:u,environment:g,models:j,allowStreaming:ht});else G=Oe.createBedrockRole(We,{slug:u,environment:g,models:j,allowStreaming:ht});if(this.builder.addResource(G.logicalId,G.role),Me.allowAsync){let{policy:Ke,logicalId:yt}=Oe.createBedrockPolicy({slug:u,environment:g,models:j,allowStreaming:ht,allowAsync:!0});this.builder.addResource(yt,Ke)}this.builder.addOutput("BedrockRoleArn",{Value:{"Fn::GetAtt":[G.logicalId,"Arn"]},Description:"IAM role ARN with Bedrock permissions"})}}generateRealtimeResources(u,g){let h=this.mergedConfig.infrastructure?.realtime;if(!h)return;let y=h.name||`${u}-${g}-realtime`,R=h.scaling||{},v=h.storage||{type:"dynamodb"},P=R.handlerMemory||256,L=R.handlerTimeout||30,z=`${u}${g}RealtimeConnections`.replace(/[^a-zA-Z0-9]/g,""),he=`${u}${g}RealtimeChannels`.replace(/[^a-zA-Z0-9]/g,"");if(v.type==="dynamodb"){let Et=v.dynamodb||{},Zt=Et.billingMode||"PAY_PER_REQUEST";this.builder.addResource(z,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-${g}-realtime-connections`,BillingMode:Zt,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"},...Zt==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Et.readCapacity||5,WriteCapacityUnits:Et.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...Zt==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Et.readCapacity||5,WriteCapacityUnits:Et.writeCapacity||5}},...Et.pointInTimeRecovery&&{PointInTimeRecoverySpecification:{PointInTimeRecoveryEnabled:!0}},Tags:[{Key:"Name",Value:`${u}-${g}-realtime-connections`},{Key:"Environment",Value:g}]}}),this.builder.addResource(he,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-${g}-realtime-channels`,BillingMode:Zt,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"},...Zt==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Et.readCapacity||5,WriteCapacityUnits:Et.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...Zt==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Et.readCapacity||5,WriteCapacityUnits:Et.writeCapacity||5}},Tags:[{Key:"Name",Value:`${u}-${g}-realtime-channels`},{Key:"Environment",Value:g}]}})}let fe=`${u}${g}RealtimeRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(fe,{Type:"AWS::IAM::Role",Properties:{RoleName:`${u}-${g}-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":[z,"Arn"]},{"Fn::Sub":`\${${z}.Arn}/index/*`},{"Fn::GetAtt":[he,"Arn"]},{"Fn::Sub":`\${${he}.Arn}/index/*`}]},{Effect:"Allow",Action:"execute-api:ManageConnections",Resource:{"Fn::Sub":"arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:*/*"}}]}}]}});let Ct=`${u}${g}RealtimeConnect`.replace(/[^a-zA-Z0-9]/g,""),It=`${u}${g}RealtimeDisconnect`.replace(/[^a-zA-Z0-9]/g,""),Ve=`${u}${g}RealtimeMessage`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Ct,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-${g}-realtime-connect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[fe,"Arn"]},MemorySize:P,Timeout:L,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:z},CHANNELS_TABLE:{Ref:he},ENVIRONMENT:g}},Code:{ZipFile:this.generateConnectHandlerCode()}},DependsOn:[fe,z]}),this.builder.addResource(It,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-${g}-realtime-disconnect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[fe,"Arn"]},MemorySize:P,Timeout:L,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:z},CHANNELS_TABLE:{Ref:he},ENVIRONMENT:g}},Code:{ZipFile:this.generateDisconnectHandlerCode()}},DependsOn:[fe,z,he]}),this.builder.addResource(Ve,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-${g}-realtime-message`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[fe,"Arn"]},MemorySize:P,Timeout:L,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:z},CHANNELS_TABLE:{Ref:he},ENVIRONMENT:g}},Code:{ZipFile:this.generateMessageHandlerCode()}},DependsOn:[fe,z,he]});let Me=`${u}${g}RealtimeApi`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Me,{Type:"AWS::ApiGatewayV2::Api",Properties:{Name:y,ProtocolType:"WEBSOCKET",RouteSelectionExpression:"$request.body.action",Tags:{Name:y,Environment:g}}});let We=`${Ct}Permission`,j=`${It}Permission`,ht=`${Ve}Permission`;this.builder.addResource(We,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:Ct},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${Me}}/*/$connect`}}}),this.builder.addResource(j,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:It},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${Me}}/*/$disconnect`}}}),this.builder.addResource(ht,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:Ve},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${Me}}/*/$default`}}});let G=`${Me}ConnectInteg`,Ke=`${Me}DisconnectInteg`,yt=`${Me}MessageInteg`;this.builder.addResource(G,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:Me},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${Ct}.Arn}/invocations`}}}),this.builder.addResource(Ke,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:Me},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${It}.Arn}/invocations`}}}),this.builder.addResource(yt,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:Me},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${Ve}.Arn}/invocations`}}}),this.builder.addResource(`${Me}ConnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:Me},RouteKey:"$connect",AuthorizationType:"NONE",Target:{"Fn::Sub":`integrations/\${${G}}`}}}),this.builder.addResource(`${Me}DisconnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:Me},RouteKey:"$disconnect",Target:{"Fn::Sub":`integrations/\${${Ke}}`}}}),this.builder.addResource(`${Me}DefaultRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:Me},RouteKey:"$default",Target:{"Fn::Sub":`integrations/\${${yt}}`}}});let vt=`${Me}Stage`;if(this.builder.addResource(vt,{Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:{Ref:Me},StageName:g,AutoDeploy:!0,DefaultRouteSettings:{ThrottlingBurstLimit:R.messagesPerSecond||1000,ThrottlingRateLimit:R.messagesPerSecond||1000}}}),h.monitoring?.enabled){let Et=h.monitoring,Zt=Et.notificationTopicArn;if(!Zt&&Et.notificationEmails?.length){let Yt=`${Me}AlarmTopic`;this.builder.addResource(Yt,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${u}-${g}-realtime-alarms`,DisplayName:"Realtime WebSocket Alarms"}}),Et.notificationEmails.forEach((Qt,vr)=>{this.builder.addResource(`${Yt}Sub${vr}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:Yt},Protocol:"email",Endpoint:Qt}})}),Zt={Ref:Yt}}if(Et.connectionThreshold)this.builder.addResource(`${Me}ConnectionAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${u}-${g}-realtime-connections`,AlarmDescription:`WebSocket connections exceed ${Et.connectionThreshold}`,MetricName:"ConnectCount",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:300,EvaluationPeriods:2,Threshold:Et.connectionThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:Me}}],...Zt&&{AlarmActions:[Zt]}}});if(Et.errorThreshold)this.builder.addResource(`${Me}ErrorAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${u}-${g}-realtime-errors`,AlarmDescription:`WebSocket errors exceed ${Et.errorThreshold}/min`,MetricName:"ExecutionError",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:60,EvaluationPeriods:3,Threshold:Et.errorThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:Me}}],...Zt&&{AlarmActions:[Zt]}}})}this.builder.addOutput(`${Me}Endpoint`,{Description:"WebSocket API endpoint URL",Value:{"Fn::Sub":`wss://\${${Me}}.execute-api.\${AWS::Region}.amazonaws.com/${g}`},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-endpoint"}}}),this.builder.addOutput(`${Me}Id`,{Description:"WebSocket API ID",Value:{Ref:Me},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-api-id"}}})}generateConnectHandlerCode(){return`
13
+ `:It,We=R.map(([,Et])=>Et.port).filter((Et)=>typeof Et==="number"&&![80,443].includes(Et)),j=this.resolveApiOriginPort(),ht=`${u}${g}DeployBucket`.replace(/[^a-zA-Z0-9]/g,""),G=`${u}-${g}-deploy`;this.builder.addResource(ht,{Type:"AWS::S3::Bucket",Properties:{BucketName:G,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:u},{Key:"Environment",Value:g},{Key:"ManagedBy",Value:"ts-cloud"}]}});let Ke=a.createServerModeStack({slug:`${u}-app`,environment:g,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},instanceType:he,keyName:h.allowSsh?`${u}-${g}`:void 0,domain:P,userData:Me,volumeSize:h.disk?.size||20,imageId:h.image,allowedPorts:[...h.allowSsh?[22]:[],80,443,j,...We]}),yt=Ke.resources[Ke.outputs.instanceLogicalId];if(yt?.Properties){let Et=yt.Properties.Tags||[];yt.Properties.Tags=[...Et,{Key:"Project",Value:u},{Key:"Environment",Value:g},{Key:"Role",Value:"app"},{Key:"ManagedBy",Value:"ts-cloud"}]}let vt=Ke.resources[Ke.outputs.roleLogicalId];if(vt?.Properties)vt.Properties.Policies=vt.Properties.Policies||[],vt.Properties.Policies.push({PolicyName:"DeployBucketRead",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:GetObject","s3:ListBucket"],Resource:[`arn:aws:s3:::${G}`,`arn:aws:s3:::${G}/*`]}]}});for(let[Et,Zt]of Object.entries(Ke.resources))this.builder.addResource(Et,Zt);this.builder.addOutput("deployBucketName",{Value:{Ref:ht},Description:"S3 bucket where release tarballs are uploaded"}),this.builder.addOutput("appInstanceId",{Value:{Ref:Ke.outputs.instanceLogicalId},Description:"EC2 instance ID for the app server"}),this.builder.addOutput("appPublicIp",{Value:{Ref:Ke.outputs.eipLogicalId},Description:"Public IP for the app server"}),this.serverEipLogicalIds.set("app",Ke.outputs.eipLogicalId),this.serverEipLogicalIds.set("appInstance",Ke.outputs.instanceLogicalId)}jumpBoxFileSystemId(u,g,h){let y=Object.keys(this.mergedConfig.infrastructure?.fileSystem??{});if(typeof h==="string")return y.includes(h)?{Ref:this.fileSystemLogicalId(u,g,h)}:h;if(y.length===1)return{Ref:this.fileSystemLogicalId(u,g,y[0])};throw Error(y.length===0?"infrastructure.jumpBox.mountEfs is true, but infrastructure.fileSystem declares no file system. Declare one, or set mountEfs to an EFS id.":`infrastructure.jumpBox.mountEfs is true, but infrastructure.fileSystem declares ${y.length} (${y.join(", ")}). Set mountEfs to the name of the one to mount.`)}generateJumpBox(u,g){let h=this.mergedConfig.infrastructure?.jumpBox;if(!h)return;let y=h===!0?{}:h;if(y.enabled===!1)return;this.generateNetworkInfrastructure(u,g);let R=y.size||"micro",P=a.InstanceSize.specs[R]?.instanceType||R||"t3.micro",L=a.createJumpBox({slug:u,environment:g,vpcId:{Ref:"VPC"},subnetId:{Ref:"PublicSubnet1"},keyName:y.keyName,instanceType:P,allowedCidrs:y.allowedCidrs,mountEfs:y.mountEfs?{fileSystemId:this.jumpBoxFileSystemId(u,g,y.mountEfs),mountPath:y.mountPath||"/mnt/efs"}:void 0,databaseTools:y.databaseTools});for(let[z,Ae]of Object.entries(L.resources))this.builder.addResource(z,Ae);this.builder.addOutput("JumpBoxInstanceId",{Value:{Ref:L.instanceLogicalId},Description:"The ID of the JumpBox EC2 instance (use with SSM Session Manager or SSH)"})}generateSharedInfrastructure(u,g){let h=this.mergedConfig.infrastructure?.ssl,y=this.mergedConfig.infrastructure?.dns,R=y?.domain,v=y?.hostedZoneId,P=[],L,z;if(h?.certificateArn)z=h.certificateArn;else if(h?.enabled&&R&&v){let We=h.domains||[R],j=We[0],ht=We.slice(1).map((yt)=>{if(yt.includes(".")&&yt.endsWith(j))return yt.replace(`.${j}`,"");return yt}),{certificate:G,logicalId:Ke}=E.createCertificate({domain:j,subdomains:ht,slug:u,environment:g,validationMethod:"DNS",hostedZoneId:v});L=Ke,this.builder.addResource(Ke,G)}if(this.mergedConfig.infrastructure?.storage){let We=Object.entries(this.mergedConfig.infrastructure.storage).some(([,G])=>G.website),j;if(We&&(L||z))j=`${u}${g}CloudFrontOAC`.replace(/[^a-zA-Z0-9]/g,""),this.builder.addResource(j,{Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${u}-${g}-s3-oac`,Description:`OAC for ${u} ${g} S3 website buckets`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}});let ht=Object.entries(this.mergedConfig.infrastructure.storage).map(([G,Ke])=>({name:G,config:Ke,mountPath:this.normalizeMountPath(Ke),rewriteStyle:Ke.pathRewriteStyle||"directory",logicalId:this.storageBucketLogicalId(u,g,G)})).filter((G)=>G.name!=="public"&&G.config.website&&G.mountPath);for(let[G,Ke]of Object.entries(this.mergedConfig.infrastructure.storage)){let yt=!!(Ke.website&&j),vt=this.storageBucketName(u,g,G),{bucket:Et,logicalId:Zt}=xe.createBucket({slug:u,name:G,environment:g,bucketName:vt,versioning:Ke.versioning,encryption:Ke.encryption,public:yt?!1:Ke.public}),Yt=this.normalizeMountPath(Ke),Qt;if(Ke.failover){let Xt=`infrastructure.storage.${G}`;if(!yt||!R||Yt&&G!=="public")throw Error(`${Xt}.failover needs this bucket to be served by its own CloudFront distribution: a website bucket (website: true), not mounted under the path of another site, with infrastructure.dns.domain set and SSL configured (infrastructure.ssl.certificateArn, or ssl.enabled with dns.hostedZoneId).`);if(Qt=wm({failover:Ke.failover,primaryBucket:vt,primaryRegion:this.mergedConfig.project.region||"us-east-1",where:Xt}),Qt.replicate&&Et.Properties){let er=`${Zt}FailoverReplicationRole`;this.builder.addResource(er,Dm({primaryBucket:vt,replicaBucket:Qt.replicaBucket}));let Lr=Et.Properties;Lr.VersioningConfiguration={Status:"Enabled"},Lr.ReplicationConfiguration=Pm({replicaBucket:Qt.replicaBucket,roleArn:{"Fn::GetAtt":[er,"Arn"]}})}}if(yt&&Et.Properties)Et.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1};if(this.builder.addResource(Zt,Et),Ke.website){let Xt=typeof Ke.website==="object"?Ke.website:{},er=xe.enableWebsiteHosting(Et,Xt.indexDocument||"index.html",Xt.errorDocument);this.builder.addResource(Zt,er)}let vr=this.normalizeMountPath(Ke);if(yt&&j&&R&&!(vr&&G!=="public")){let Xt=`${u}${g}${G}CDN`.replace(/[^a-zA-Z0-9]/g,""),er=[];if(Ke.aliases&&Ke.aliases.length>0)er.push(...Ke.aliases);else if(G==="public"){if(er.push(R),h?.domains?.includes(`www.${R}`))er.push(`www.${R}`)}else if(G==="docs")er.push(`docs.${R}`);else if(G==="blog")er.push(`blog.${R}`);let Lr=typeof Ke.website==="object"?Ke.website:{},zr=Ke.spa===!0,Fr=Lr.errorDocument||(zr?"index.html":"404.html"),Or=[];if(zr)Or.push({ErrorCode:403,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:300});else Or.push({ErrorCode:403,ResponseCode:404,ResponsePagePath:`/${Fr}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${Fr}`,ErrorCachingMinTTL:300});let jr=z&&er.length>0?{AcmCertificateArn:z,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:L&&er.length>0?{AcmCertificateArn:{Ref:L},SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},Mn=`S3-${u}-${g}-${G}`,Za=this.mergedConfig.project.region||"us-east-1",Zn;if(!zr)Zn=`${u}${g}${G}UrlRewrite`.replace(/[^a-zA-Z0-9]/g,""),this.builder.addResource(Zn,{Type:"AWS::CloudFront::Function",Properties:{Name:`${u}-${g}-${G}-url-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`URL rewrite for ${u} ${g} ${G} - 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 pi=[{Id:Mn,DomainName:{"Fn::Sub":`\${${Zt}}.s3.${Za}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:j}}],oo=[],Xa=[];if(this.shouldRouteStorageBucketToCompute(G,Ke)){this.appendComputeAppOrigin(pi,oo,Xa,u,g,this.resolveComputeCachePathPatterns(Ke.computeRoutes));for(let rr of ht){let ho=`S3-${u}-${g}-${rr.name}`,wc=`${u}${g}${rr.name}PathMountRewrite`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(wc,{Type:"AWS::CloudFront::Function",Properties:{Name:`${u}-${g}-${rr.name}-path-mount-rewrite`,AutoPublish:!0,FunctionConfig:{Comment:`Path mount rewrite for ${u} ${g} ${rr.name} at ${rr.mountPath}`,Runtime:"cloudfront-js-2.0"},FunctionCode:this.pathMountRewriteFunctionCode(rr.mountPath,rr.rewriteStyle)}}),pi.push({Id:ho,DomainName:{"Fn::Sub":`\${${rr.logicalId}}.s3.${Za}.amazonaws.com`},OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:j}}),Xa.push(rr.logicalId,wc);for(let fp of[rr.mountPath,`${rr.mountPath}/*`])oo.push({PathPattern:fp,TargetOriginId:ho,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":[wc,"FunctionARN"]}}]})}}let po,Xc=Mn;if(Qt){let rr=`${Mn}-failover`;Object.assign(pi[0],Qt.primaryConnection),pi.push({Id:rr,DomainName:Rm(Qt.replicaBucket,Qt.replicaRegion),OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{Ref:j}}),po=un({primaryOriginId:Mn,secondaryOriginId:rr,statusCodes:Qt.statusCodes}),Xc=po.Items[0].Id}let $c={Type:"AWS::CloudFront::Distribution",DependsOn:[Zt,j,...Zn?[Zn]:[],...Xa],Properties:{DistributionConfig:{Enabled:!0,Comment:`${u} ${g} ${G} site`,DefaultRootObject:"index.html",Origins:pi,...po?{OriginGroups:po}:{},DefaultCacheBehavior:{TargetOriginId:Xc,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",...Zn?{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[Zn,"FunctionARN"]}}]}:{}},...oo.length>0?{CacheBehaviors:oo}:{},...er.length>0?{Aliases:er}:{},ViewerCertificate:jr,PriceClass:"PriceClass_100",HttpVersion:"http2and3",IPV6Enabled:!0,CustomErrorResponses:Or}}};if(L)$c.DependsOn.push(L);if(Qt)Nt($c.Properties.DistributionConfig,`infrastructure.storage.${G}`),this.storageFailoverReplicas.push({name:G,primaryBucket:vt,primaryRegion:Za,replicaBucket:Qt.replicaBucket,replicaRegion:Qt.replicaRegion,replicate:Qt.replicate,distributionArnOutput:`${G}CloudFrontDistributionArn`}),this.builder.addOutput(`${G}CloudFrontDistributionArn`,{Value:{"Fn::Sub":`arn:\${AWS::Partition}:cloudfront::\${AWS::AccountId}:distribution/\${${Xt}}`},Description:`CloudFront distribution ARN for ${G} (scopes the bucket policy of the failover replica)`}),this.builder.addOutput(`${G}FailoverBucketName`,{Value:Qt.replicaBucket,Description:`Failover replica bucket for ${G} (${Qt.replicaRegion}), outside this stack`});this.builder.addResource(Xt,$c);let gp=`${Zt}CloudFrontPolicy`;if(this.builder.addResource(gp,{Type:"AWS::S3::BucketPolicy",DependsOn:[Zt,Xt],Properties:{Bucket:{Ref:Zt},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":`arn:aws:s3:::\${${Zt}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${Xt}}`}}}}]}}}),this.shouldRouteStorageBucketToCompute(G,Ke))for(let rr of ht){let ho=`${rr.logicalId}CloudFrontPolicy`;this.builder.addResource(ho,{Type:"AWS::S3::BucketPolicy",DependsOn:[rr.logicalId,Xt],Properties:{Bucket:{Ref:rr.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:::\${${rr.logicalId}}/*`},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":`arn:aws:cloudfront::\${AWS::AccountId}:distribution/\${${Xt}}`}}}}]}}})}if(er.length>0)P.push({name:G,bucketLogicalId:Zt,distLogicalId:Xt,oacLogicalId:j,aliases:er});this.builder.addOutput(`${G}CloudFrontDomain`,{Value:{"Fn::GetAtt":[Xt,"DomainName"]},Description:`CloudFront domain for ${G}`}),this.builder.addOutput(`${G}CloudFrontDistributionId`,{Value:{Ref:Xt},Description:`CloudFront distribution ID for ${G}`})}if(this.builder.addOutput(`${G}BucketName`,{Value:{Ref:Zt},Description:`S3 bucket name for ${G}`}),G==="public")this.builder.addOutput("FrontendBucketName",{Value:{Ref:Zt},Description:"Frontend S3 bucket name"});if(G==="docs")this.builder.addOutput("DocsBucketName",{Value:{Ref:Zt},Description:"Documentation S3 bucket name"});if(G==="blog")this.builder.addOutput("BlogBucketName",{Value:{Ref:Zt},Description:"Blog S3 bucket name"})}}if(this.mergedConfig.infrastructure?.sftp){let We=this.mergedConfig.infrastructure.sftp,j=pl.create({...We,storage:this.resolveSftpStorage(We,u,g)??We.storage,slug:u,environment:g});for(let[ht,G]of Object.entries(j.resources))this.builder.addResource(ht,G);this.builder.addOutput("SftpServerId",{Value:{Ref:j.serverLogicalId},Description:"AWS Transfer Family SFTP server ID"}),this.builder.addOutput("SftpEndpoint",{Value:{"Fn::Sub":`\${${j.serverLogicalId}}.server.transfer.\${AWS::Region}.amazonaws.com`},Description:"AWS Transfer Family SFTP endpoint"}),this.builder.addOutput("SftpStorageDomain",{Value:j.domain,Description:"Storage backing the SFTP server (EFS or S3)"})}if(v&&P.length>0)for(let{name:We,distLogicalId:j,aliases:ht}of P)for(let G of ht){let Ke=G.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${Ke}ARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[j],Properties:{HostedZoneId:v,Name:G,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":[j,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}}),this.builder.addResource(`${Ke}AAAARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[j],Properties:{HostedZoneId:v,Name:G,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":[j,"DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}})}if(this.mergedConfig.infrastructure?.databases){for(let[We,j]of Object.entries(this.mergedConfig.infrastructure.databases))if(j.engine==="dynamodb"){let{table:ht,logicalId:G}=ur.createTable({slug:u,environment:g,tableName:`${u}-${g}-${We}`,partitionKey:j.partitionKey||{name:"id",type:"S"},sortKey:j.sortKey});this.builder.addResource(G,ht)}else if(j.engine==="postgres"){let{dbInstance:ht,logicalId:G}=ur.createPostgres({slug:u,environment:g,dbInstanceIdentifier:`${u}-${g}-${We}`,masterUsername:j.username||"admin",masterUserPassword:j.password||"changeme123",allocatedStorage:j.storage||20,dbInstanceClass:j.instanceClass||"db.t3.micro"});this.builder.addResource(G,ht)}else if(j.engine==="mysql"){let{dbInstance:ht,logicalId:G}=ur.createMysql({slug:u,environment:g,dbInstanceIdentifier:`${u}-${g}-${We}`,masterUsername:j.username||"admin",masterUserPassword:j.password||"changeme123",allocatedStorage:j.storage||20,dbInstanceClass:j.instanceClass||"db.t3.micro"});this.builder.addResource(G,ht)}}if(this.mergedConfig.infrastructure?.cdn)for(let[We,j]of Object.entries(this.mergedConfig.infrastructure.cdn)){if(!j.origin)continue;let ht=typeof j.customDomain==="string"?j.customDomain:j.customDomain?.domain||j.domain,G=typeof j.customDomain==="object"?j.customDomain?.certificateArn:j.certificateArn,Ke=G||z,yt=`${u}${g}${We}CDN`.replace(/[^a-zA-Z0-9]/g,""),vt=`S3-${u}-${g}-${We}-cdn`,Et=[{Id:vt,DomainName:j.origin,OriginPath:"",S3OriginConfig:{OriginAccessIdentity:""},OriginShield:j.originShield?{Enabled:!0,OriginShieldRegion:j.originShieldRegion||this.mergedConfig.environments[g]?.region||this.mergedConfig.project.region||"us-east-1"}:{Enabled:!1},...le(j,`infrastructure.cdn.${We}`)}],Zt=[],Yt=[],Qt=["GET","HEAD","OPTIONS"],vr=vt,Xt;if(j.failoverOrigin){kt(Qt,`the default cache behavior of infrastructure.cdn.${We}`);let Fr=`${vt}-failover`,Or=typeof j.failoverOrigin==="string"?{domain:j.failoverOrigin}:j.failoverOrigin;if(!Or.domain)throw Error(`infrastructure.cdn.${We}.failoverOrigin.domain is required`);if(Or.domain===j.origin)throw Error(`infrastructure.cdn.${We}: failoverOrigin must differ from origin (both are ${j.origin})`);Et.push({Id:Fr,DomainName:Or.domain,OriginPath:Or.originPath||"",...Go(Or.domain)?{S3OriginConfig:{OriginAccessIdentity:""}}:{CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only"}},OriginShield:{Enabled:!1},...le(Or,`infrastructure.cdn.${We}.failoverOrigin`)}),Xt=un({primaryOriginId:vt,secondaryOriginId:Fr,statusCodes:j.failoverStatusCodes}),vr=Xt.Items[0].Id}else if(j.failoverStatusCodes)throw Error(`infrastructure.cdn.${We}: failoverStatusCodes needs failoverOrigin to fail over to`);if(j.routeCompute)this.appendComputeAppOrigin(Et,Zt,Yt,u,g,this.resolveComputeCachePathPatterns(j.computeRoutes));let er=Ke&&ht?{AcmCertificateArn:L&&!G?{Ref:L}:Ke,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}:{CloudFrontDefaultCertificate:!0},Lr=[...Yt];if(L&&!G&&ht)Lr.push(L);let zr={Type:"AWS::CloudFront::Distribution",...Lr.length>0?{DependsOn:Lr}:{},Properties:{DistributionConfig:{Enabled:!0,Comment:`${u} ${g} ${We} CDN`,DefaultRootObject:"index.html",Origins:Et,...Xt?{OriginGroups:Xt}:{},DefaultCacheBehavior:{TargetOriginId:vr,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:Qt,CachedMethods:["GET","HEAD","OPTIONS"],Compress:j.compress!==!1,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},...Zt.length>0?{CacheBehaviors:Zt}:{},...ht&&Ke?{Aliases:[ht]}:{},ViewerCertificate:er,PriceClass:"PriceClass_100",HttpVersion:j.http3?"http2and3":"http2"}}};if(Nt(zr.Properties.DistributionConfig,`infrastructure.cdn.${We}`),this.builder.addResource(yt,zr),v&&ht&&Ke){let Fr=ht.replace(/\./g,"").replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${Fr}CdnARecord`,{Type:"AWS::Route53::RecordSet",DependsOn:[yt,...L&&!G?[L]:[]],Properties:{HostedZoneId:v,Name:ht,Type:"A",AliasTarget:{HostedZoneId:"Z2FDTNDATAQYW2",DNSName:{"Fn::GetAtt":[yt,"DomainName"]}}}})}}if(this.mergedConfig.infrastructure?.queues)for(let[We,j]of Object.entries(this.mergedConfig.infrastructure.queues)){if(!this.shouldDeploy(j))continue;let{queue:ht,logicalId:G}=J.createQueue({slug:u,environment:g,name:`${u}-${g}-${We}`,fifo:j.fifo,visibilityTimeout:j.visibilityTimeout,messageRetentionPeriod:j.messageRetentionPeriod,delaySeconds:j.delaySeconds,maxMessageSize:j.maxMessageSize,receiveMessageWaitTime:j.receiveMessageWaitTime,contentBasedDeduplication:j.contentBasedDeduplication,encrypted:j.encrypted,kmsKeyId:j.kmsKeyId});this.builder.addResource(G,ht);let Ke;if(j.deadLetterQueue){let{deadLetterQueue:yt,updatedSourceQueue:vt,deadLetterLogicalId:Et}=J.createDeadLetterQueue(G,{slug:u,environment:g,maxReceiveCount:j.maxReceiveCount});Ke=Et,this.builder.addResource(Et,yt);let Yt=this.builder.getResources()[G];if(Yt?.Properties)Yt.Properties.RedrivePolicy=vt.Properties?.RedrivePolicy}if(j.trigger){let yt=j.trigger,vt=`${u}${g}${yt.functionName}`.replace(/[^a-zA-Z0-9]/g,""),Et={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:{"Fn::GetAtt":[G,"Arn"]},FunctionName:{Ref:vt},BatchSize:yt.batchSize||10,MaximumBatchingWindowInSeconds:yt.batchWindow||0,Enabled:!0,...yt.reportBatchItemFailures!==!1&&{FunctionResponseTypes:["ReportBatchItemFailures"]},...yt.maxConcurrency&&{ScalingConfig:{MaximumConcurrency:yt.maxConcurrency}},...yt.filterPattern&&{FilterCriteria:{Filters:[{Pattern:JSON.stringify(yt.filterPattern)}]}}},DependsOn:[G,vt]};this.builder.addResource(`${G}Trigger`,Et)}if(j.alarms?.enabled){let yt=j.alarms,vt=yt.notificationTopicArn;if(!vt&&yt.notificationEmails?.length){let Yt=`${G}AlarmTopic`;this.builder.addResource(Yt,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${u}-${g}-${We}-alarms`,DisplayName:`${We} Queue Alarms`}}),yt.notificationEmails.forEach((Qt,vr)=>{this.builder.addResource(`${Yt}Sub${vr}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:Yt},Protocol:"email",Endpoint:Qt}})}),vt={Ref:Yt}}let Et=yt.queueDepthThreshold||1000;this.builder.addResource(`${G}DepthAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${u}-${g}-${We}-queue-depth`,AlarmDescription:`Queue ${We} depth exceeds ${Et} messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Average",Period:300,EvaluationPeriods:2,Threshold:Et,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[G,"QueueName"]}}],...vt&&{AlarmActions:[vt],OKActions:[vt]}}});let Zt=yt.messageAgeThreshold||3600;if(this.builder.addResource(`${G}AgeAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${u}-${g}-${We}-message-age`,AlarmDescription:`Queue ${We} oldest message exceeds ${Zt} seconds`,MetricName:"ApproximateAgeOfOldestMessage",Namespace:"AWS/SQS",Statistic:"Maximum",Period:300,EvaluationPeriods:2,Threshold:Zt,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[G,"QueueName"]}}],...vt&&{AlarmActions:[vt],OKActions:[vt]}}}),Ke&&yt.dlqAlarm!==!1)this.builder.addResource(`${Ke}Alarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${u}-${g}-${We}-dlq-messages`,AlarmDescription:`Dead letter queue for ${We} has messages`,MetricName:"ApproximateNumberOfMessagesVisible",Namespace:"AWS/SQS",Statistic:"Sum",Period:300,EvaluationPeriods:1,Threshold:0,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"QueueName",Value:{"Fn::GetAtt":[Ke,"QueueName"]}}],...vt&&{AlarmActions:[vt]}}})}if(j.subscribe){let yt=j.subscribe,vt=yt.topicArn;if(!vt&&yt.topicName)vt={Ref:yt.topicName};if(vt){this.builder.addResource(`${G}SnsPolicy`,{Type:"AWS::SQS::QueuePolicy",Properties:{Queues:[{Ref:G}],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"sns.amazonaws.com"},Action:"sqs:SendMessage",Resource:{"Fn::GetAtt":[G,"Arn"]},Condition:{ArnEquals:{"aws:SourceArn":vt}}}]}}});let Et={TopicArn:vt,Protocol:"sqs",Endpoint:{"Fn::GetAtt":[G,"Arn"]},RawMessageDelivery:yt.rawMessageDelivery||!1};if(yt.filterPolicy)Et.FilterPolicy=yt.filterPolicy,Et.FilterPolicyScope=yt.filterPolicyScope||"MessageAttributes";this.builder.addResource(`${G}SnsSub`,{Type:"AWS::SNS::Subscription",Properties:Et,DependsOn:`${G}SnsPolicy`})}}}if(this.mergedConfig.infrastructure?.realtime?.enabled)if((this.mergedConfig.infrastructure.realtime.mode||"serverless")==="server")this.generateRealtimeServerResources(u,g);else this.generateRealtimeResources(u,g);let Ae=this.mergedConfig.infrastructure?.redirects;if(Ae){let We=Ae.target||this.mergedConfig.infrastructure?.dns?.domain||"",j=Ae.protocol||"https";if(Ae.domains?.length&&We)for(let ht of Ae.domains){let{bucket:G,bucketPolicy:Ke,logicalId:yt,policyLogicalId:vt}=xt.createDomainRedirectBucket({slug:u,environment:g,sourceDomain:ht,targetDomain:We,protocol:j});this.builder.addResource(yt,G),this.builder.addResource(vt,Ke)}if(Ae.paths&&Object.keys(Ae.paths).length>0){let ht=xt.fromMapping(Ae.paths,{statusCode:Ae.statusCode||301}),{function:G,logicalId:Ke}=xt.createPathRedirectFunction({slug:u,environment:g,rules:ht});this.builder.addResource(Ke,G)}}if(this.mergedConfig.infrastructure?.monitoring?.alarms)for(let[We,j]of Object.entries(this.mergedConfig.infrastructure.monitoring.alarms)){let{alarm:ht,logicalId:G}=jo.createAlarm({slug:u,environment:g,alarmName:`${u}-${g}-${We}`,metricName:j.metricName||"Errors",namespace:j.namespace||"AWS/Lambda",threshold:j.threshold||1,comparisonOperator:j.comparisonOperator||"GreaterThanThreshold"});this.builder.addResource(G,ht)}let he=this.mergedConfig.infrastructure?.cache;if(he){let We=he.type||"redis";if(We==="redis"){this.generateNetworkInfrastructure(u,g);let j=he.redis||{},{replicationGroup:ht,subnetGroup:G,logicalId:Ke,subnetGroupId:yt}=qo.createRedis({slug:u,environment:g,nodeType:j.nodeType||he.nodeType||"cache.t3.micro",engineVersion:j.engineVersion||"7.1",port:j.port||6379,numCacheClusters:j.numCacheNodes||2,automaticFailover:j.automaticFailoverEnabled!==!1,atRestEncryption:!0,transitEncryption:!0,snapshotRetentionDays:j.snapshotRetentionLimit||7,snapshotWindow:j.snapshotWindow,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(Ke,ht),G&&yt)this.builder.addResource(yt,G);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[Ke,"PrimaryEndPoint.Address"]},Description:"Redis primary endpoint address"}),this.builder.addOutput("CachePort",{Value:{"Fn::GetAtt":[Ke,"PrimaryEndPoint.Port"]},Description:"Redis primary endpoint port"})}else if(We==="memcached"){this.generateNetworkInfrastructure(u,g);let j=he.elasticache||{},{cluster:ht,subnetGroup:G,logicalId:Ke,subnetGroupId:yt}=qo.createMemcached({slug:u,environment:g,nodeType:j.nodeType||he.nodeType||"cache.t3.micro",engineVersion:j.engineVersion||"1.6.22",numCacheNodes:j.numCacheNodes||2,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]});if(this.builder.addResource(Ke,ht),G&&yt)this.builder.addResource(yt,G);this.builder.addOutput("CacheEndpoint",{Value:{"Fn::GetAtt":[Ke,"ConfigurationEndpoint.Address"]},Description:"Memcached configuration endpoint address"})}}let Ct=this.mergedConfig.infrastructure?.email;if(Ct){let We=Ct.domain||this.mergedConfig.infrastructure?.dns?.domain;if(We){let{emailIdentity:j,logicalId:ht}=f.verifyDomain({domain:We,slug:u,environment:g,enableDkim:Ct.enableDkim!==!1,dkimKeyLength:Ct.dkimKeyLength||"RSA_2048_BIT"});if(this.builder.addResource(ht,j),Ct.configurationSet!==!1){let{configurationSet:yt,logicalId:vt}=f.createConfigurationSet({slug:u,environment:g});this.builder.addResource(vt,yt)}let G=Ct.hostedZoneId||this.mergedConfig.infrastructure?.dns?.hostedZoneId;if(G){if(Ct.enableDkim!==!1)for(let Yt=1;Yt<=3;Yt++){let Qt=`DkimRecord${Yt}${We.replace(/\./g,"")}`;this.builder.addResource(Qt,{Type:"AWS::Route53::RecordSet",DependsOn:[ht],Properties:{HostedZoneId:G,Name:{"Fn::GetAtt":[ht,`DkimDNSTokenName${Yt}`]},Type:"CNAME",TTL:1800,ResourceRecords:[{"Fn::GetAtt":[ht,`DkimDNSTokenValue${Yt}`]}]}})}let{record:yt,logicalId:vt}=f.createSpfRecord(We,G);this.builder.addResource(vt,yt);let{record:Et,logicalId:Zt}=f.createDmarcRecord(We,G,{policy:"none",reportingEmail:Ct.dmarcReportingEmail||`dmarc-reports@${We}`});this.builder.addResource(Zt,Et)}this.builder.addOutput("EmailDomain",{Value:We,Description:"SES verified email domain"});let Ke=Ct.server;if(Ke?.enabled&&G){let yt=this.mergedConfig.environments[g]?.region||this.mergedConfig.project.region||"us-east-1",vt=`${u}-${g}-email`,{role:Et,policy:Zt,roleLogicalId:Yt,policyLogicalId:Qt}=f.createEmailLambdaRole({slug:u,environment:g,s3BucketArn:`arn:aws:s3:::${vt}`,sesIdentityArn:`arn:aws:ses:${yt}:*:identity/${We}`});this.builder.addResource(Yt,Et),this.builder.addResource(Qt,Zt);let{function:vr,permission:Xt,logicalId:er,permissionLogicalId:Lr}=f.createInboundEmailLambda({slug:u,environment:g,roleArn:{"Fn::GetAtt":[Yt,"Arn"]},s3BucketName:vt,organizedPrefix:"mailboxes/"});this.builder.addResource(er,vr),this.builder.addResource(Lr,Xt);let zr=f.createInboundEmailSetup({slug:u,environment:g,domain:We,s3BucketName:vt,s3KeyPrefix:"inbox/",region:yt,hostedZoneId:G,lambdaFunctionArn:{"Fn::GetAtt":[er,"Arn"]}});for(let[Or,jr]of Object.entries(zr.resources)){if(jr.Type==="AWS::SES::ReceiptRule")jr.DependsOn=[Lr,er];this.builder.addResource(Or,jr)}this.builder.addOutput("InboundEmailLambda",{Value:{Ref:er},Description:"Inbound email processing Lambda function"}),this.builder.addOutput("EmailBucket",{Value:vt,Description:"S3 bucket for email storage"});let Fr=this.serverEipLogicalIds.get("app");if(Fr&&G){let jr=`${Ke?.subdomain||"mail"}.${We}`,Mn=jr.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(`${Mn}ARecord`,{Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:G,Name:jr,Type:"A",TTL:"300",ResourceRecords:[{Ref:Fr}]}})}this.builder.addOutput("MailHost",{Value:`mail.${We}`,Description:"Mail server hostname for SMTP/IMAP clients"})}}}let It=this.mergedConfig.infrastructure?.search;if(It){let We=It.vpc?{subnetIds:[{Ref:"PublicSubnet1"}],securityGroupIds:[]}:void 0;if(We)this.generateNetworkInfrastructure(u,g);let{domain:j,logicalId:ht}=gr.createDomain({slug:u,environment:g,engineVersion:It.engineVersion||"OpenSearch_2.11",instanceType:It.instanceType||"t3.small.search",instanceCount:It.instanceCount||1,volumeSize:It.volumeSize||10,volumeType:It.volumeType||"gp3",dedicatedMaster:It.dedicatedMaster||!1,dedicatedMasterType:It.dedicatedMasterType,dedicatedMasterCount:It.dedicatedMasterCount||3,multiAz:It.multiAz||!1,encryption:It.encryption||{atRest:!0,nodeToNode:!0},advancedSecurity:It.advancedSecurity,autoTune:It.autoTune!==!1,vpc:We});this.builder.addResource(ht,j),this.builder.addOutput("SearchDomainEndpoint",{Value:{"Fn::GetAtt":[ht,"DomainEndpoint"]},Description:"OpenSearch domain endpoint"}),this.builder.addOutput("SearchDomainArn",{Value:{"Fn::GetAtt":[ht,"Arn"]},Description:"OpenSearch domain ARN"})}let Ve=this.mergedConfig.infrastructure?.fileSystem;if(Ve&&Object.keys(Ve).length>0){this.generateNetworkInfrastructure(u,g);for(let[We,j]of Object.entries(Ve)){let{fileSystem:ht,logicalId:G}=tt.createFileSystem({slug:`${u}-${We}`,environment:g,encrypted:j.encrypted!==!1,performanceMode:j.performanceMode||"generalPurpose",throughputMode:j.throughputMode||"bursting",enableBackup:!0});this.builder.addResource(G,ht);let{securityGroup:Ke,logicalId:yt}=tt.createEfsSecurityGroup({slug:`${u}-${We}`,environment:g,vpcId:{Ref:"VPC"},sourceCidrBlocks:["10.0.0.0/16"]});this.builder.addResource(yt,Ke);let{mountTargets:vt,logicalIds:Et}=tt.createMultiAzMountTargets(G,{slug:`${u}-${We}`,environment:g,subnetIds:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],securityGroupId:{Ref:yt}});for(let Zt=0;Zt<vt.length;Zt++)this.builder.addResource(Et[Zt],vt[Zt]);this.builder.addOutput(`${We}FileSystemId`,{Value:{Ref:G},Description:`EFS file system ID for ${We}`})}}let Me=this.mergedConfig.infrastructure?.ai;if(Me){let We=Me.service||"ecs",j=Me.models||["*"],ht=Me.allowStreaming!==!1,G;if(We==="ecs")G=Oe.enableBedrockForEcs({slug:u,environment:g,models:j,allowStreaming:ht});else if(We==="ec2")G=Oe.enableBedrockForEc2({slug:u,environment:g,models:j,allowStreaming:ht});else if(We==="lambda")G=Oe.enableBedrockForLambda({slug:u,environment:g,models:j,allowStreaming:ht});else G=Oe.createBedrockRole(We,{slug:u,environment:g,models:j,allowStreaming:ht});if(this.builder.addResource(G.logicalId,G.role),Me.allowAsync){let{policy:Ke,logicalId:yt}=Oe.createBedrockPolicy({slug:u,environment:g,models:j,allowStreaming:ht,allowAsync:!0});this.builder.addResource(yt,Ke)}this.builder.addOutput("BedrockRoleArn",{Value:{"Fn::GetAtt":[G.logicalId,"Arn"]},Description:"IAM role ARN with Bedrock permissions"})}}generateRealtimeResources(u,g){let h=this.mergedConfig.infrastructure?.realtime;if(!h)return;let y=h.name||`${u}-${g}-realtime`,R=h.scaling||{},v=h.storage||{type:"dynamodb"},P=R.handlerMemory||256,L=R.handlerTimeout||30,z=`${u}${g}RealtimeConnections`.replace(/[^a-zA-Z0-9]/g,""),Ae=`${u}${g}RealtimeChannels`.replace(/[^a-zA-Z0-9]/g,"");if(v.type==="dynamodb"){let Et=v.dynamodb||{},Zt=Et.billingMode||"PAY_PER_REQUEST";this.builder.addResource(z,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-${g}-realtime-connections`,BillingMode:Zt,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"},...Zt==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Et.readCapacity||5,WriteCapacityUnits:Et.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...Zt==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Et.readCapacity||5,WriteCapacityUnits:Et.writeCapacity||5}},...Et.pointInTimeRecovery&&{PointInTimeRecoverySpecification:{PointInTimeRecoveryEnabled:!0}},Tags:[{Key:"Name",Value:`${u}-${g}-realtime-connections`},{Key:"Environment",Value:g}]}}),this.builder.addResource(Ae,{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${u}-${g}-realtime-channels`,BillingMode:Zt,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"},...Zt==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Et.readCapacity||5,WriteCapacityUnits:Et.writeCapacity||5}}}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0},...Zt==="PROVISIONED"&&{ProvisionedThroughput:{ReadCapacityUnits:Et.readCapacity||5,WriteCapacityUnits:Et.writeCapacity||5}},Tags:[{Key:"Name",Value:`${u}-${g}-realtime-channels`},{Key:"Environment",Value:g}]}})}let he=`${u}${g}RealtimeRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(he,{Type:"AWS::IAM::Role",Properties:{RoleName:`${u}-${g}-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":[z,"Arn"]},{"Fn::Sub":`\${${z}.Arn}/index/*`},{"Fn::GetAtt":[Ae,"Arn"]},{"Fn::Sub":`\${${Ae}.Arn}/index/*`}]},{Effect:"Allow",Action:"execute-api:ManageConnections",Resource:{"Fn::Sub":"arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:*/*"}}]}}]}});let Ct=`${u}${g}RealtimeConnect`.replace(/[^a-zA-Z0-9]/g,""),It=`${u}${g}RealtimeDisconnect`.replace(/[^a-zA-Z0-9]/g,""),Ve=`${u}${g}RealtimeMessage`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Ct,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-${g}-realtime-connect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[he,"Arn"]},MemorySize:P,Timeout:L,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:z},CHANNELS_TABLE:{Ref:Ae},ENVIRONMENT:g}},Code:{ZipFile:this.generateConnectHandlerCode()}},DependsOn:[he,z]}),this.builder.addResource(It,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-${g}-realtime-disconnect`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[he,"Arn"]},MemorySize:P,Timeout:L,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:z},CHANNELS_TABLE:{Ref:Ae},ENVIRONMENT:g}},Code:{ZipFile:this.generateDisconnectHandlerCode()}},DependsOn:[he,z,Ae]}),this.builder.addResource(Ve,{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${u}-${g}-realtime-message`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":[he,"Arn"]},MemorySize:P,Timeout:L,Environment:{Variables:{CONNECTIONS_TABLE:{Ref:z},CHANNELS_TABLE:{Ref:Ae},ENVIRONMENT:g}},Code:{ZipFile:this.generateMessageHandlerCode()}},DependsOn:[he,z,Ae]});let Me=`${u}${g}RealtimeApi`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Me,{Type:"AWS::ApiGatewayV2::Api",Properties:{Name:y,ProtocolType:"WEBSOCKET",RouteSelectionExpression:"$request.body.action",Tags:{Name:y,Environment:g}}});let We=`${Ct}Permission`,j=`${It}Permission`,ht=`${Ve}Permission`;this.builder.addResource(We,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:Ct},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${Me}}/*/$connect`}}}),this.builder.addResource(j,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:It},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${Me}}/*/$disconnect`}}}),this.builder.addResource(ht,{Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:Ve},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":`arn:aws:execute-api:\${AWS::Region}:\${AWS::AccountId}:\${${Me}}/*/$default`}}});let G=`${Me}ConnectInteg`,Ke=`${Me}DisconnectInteg`,yt=`${Me}MessageInteg`;this.builder.addResource(G,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:Me},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${Ct}.Arn}/invocations`}}}),this.builder.addResource(Ke,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:Me},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${It}.Arn}/invocations`}}}),this.builder.addResource(yt,{Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:Me},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::Sub":`arn:aws:apigateway:\${AWS::Region}:lambda:path/2015-03-31/functions/\${${Ve}.Arn}/invocations`}}}),this.builder.addResource(`${Me}ConnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:Me},RouteKey:"$connect",AuthorizationType:"NONE",Target:{"Fn::Sub":`integrations/\${${G}}`}}}),this.builder.addResource(`${Me}DisconnectRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:Me},RouteKey:"$disconnect",Target:{"Fn::Sub":`integrations/\${${Ke}}`}}}),this.builder.addResource(`${Me}DefaultRoute`,{Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:Me},RouteKey:"$default",Target:{"Fn::Sub":`integrations/\${${yt}}`}}});let vt=`${Me}Stage`;if(this.builder.addResource(vt,{Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:{Ref:Me},StageName:g,AutoDeploy:!0,DefaultRouteSettings:{ThrottlingBurstLimit:R.messagesPerSecond||1000,ThrottlingRateLimit:R.messagesPerSecond||1000}}}),h.monitoring?.enabled){let Et=h.monitoring,Zt=Et.notificationTopicArn;if(!Zt&&Et.notificationEmails?.length){let Yt=`${Me}AlarmTopic`;this.builder.addResource(Yt,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${u}-${g}-realtime-alarms`,DisplayName:"Realtime WebSocket Alarms"}}),Et.notificationEmails.forEach((Qt,vr)=>{this.builder.addResource(`${Yt}Sub${vr}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:Yt},Protocol:"email",Endpoint:Qt}})}),Zt={Ref:Yt}}if(Et.connectionThreshold)this.builder.addResource(`${Me}ConnectionAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${u}-${g}-realtime-connections`,AlarmDescription:`WebSocket connections exceed ${Et.connectionThreshold}`,MetricName:"ConnectCount",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:300,EvaluationPeriods:2,Threshold:Et.connectionThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:Me}}],...Zt&&{AlarmActions:[Zt]}}});if(Et.errorThreshold)this.builder.addResource(`${Me}ErrorAlarm`,{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${u}-${g}-realtime-errors`,AlarmDescription:`WebSocket errors exceed ${Et.errorThreshold}/min`,MetricName:"ExecutionError",Namespace:"AWS/ApiGateway",Statistic:"Sum",Period:60,EvaluationPeriods:3,Threshold:Et.errorThreshold,ComparisonOperator:"GreaterThanThreshold",Dimensions:[{Name:"ApiId",Value:{Ref:Me}}],...Zt&&{AlarmActions:[Zt]}}})}this.builder.addOutput(`${Me}Endpoint`,{Description:"WebSocket API endpoint URL",Value:{"Fn::Sub":`wss://\${${Me}}.execute-api.\${AWS::Region}.amazonaws.com/${g}`},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-endpoint"}}}),this.builder.addOutput(`${Me}Id`,{Description:"WebSocket API ID",Value:{Ref:Me},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(u,g){let h=this.mergedConfig.infrastructure?.realtime;if(!h)return;let y=h.server||{},R=y.port||6001,v=y.instances||1,P=`${u}${g}RealtimeSG`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(P,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`Security group for ${u} realtime WebSocket server`,GroupName:`${u}-${g}-realtime-sg`,VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:R,ToPort:R,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:`${u}-${g}-realtime-sg`},{Key:"Environment",Value:g}]}});let L=`${u}${g}RealtimeTaskDef`.replace(/[^a-zA-Z0-9]/g,""),z=`${u}${g}RealtimeTaskRole`.replace(/[^a-zA-Z0-9]/g,""),he=`${u}${g}RealtimeExecRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(he,{Type:"AWS::IAM::Role",Properties:{RoleName:`${u}-${g}-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(z,{Type:"AWS::IAM::Role",Properties:{RoleName:`${u}-${g}-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:"*"},...y.redis?.enabled?[{Effect:"Allow",Action:["elasticache:DescribeCacheClusters","elasticache:DescribeReplicationGroups"],Resource:"*"}]:[]]}}]}});let fe=[{Name:"BROADCAST_HOST",Value:y.host||"0.0.0.0"},{Name:"BROADCAST_PORT",Value:String(R)},{Name:"NODE_ENV",Value:g==="production"?"production":"development"}];if(y.redis?.enabled){if(y.redis.useElastiCache)fe.push({Name:"REDIS_HOST",Value:{"Fn::GetAtt":["CacheCluster","RedisEndpoint.Address"]}}),fe.push({Name:"REDIS_PORT",Value:{"Fn::GetAtt":["CacheCluster","RedisEndpoint.Port"]}});else fe.push({Name:"REDIS_HOST",Value:y.redis.host||"localhost"}),fe.push({Name:"REDIS_PORT",Value:String(y.redis.port||6379)});if(y.redis.keyPrefix)fe.push({Name:"REDIS_KEY_PREFIX",Value:y.redis.keyPrefix})}this.builder.addResource(L,{Type:"AWS::ECS::TaskDefinition",Properties:{Family:`${u}-${g}-realtime`,NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:"512",Memory:"1024",ExecutionRoleArn:{"Fn::GetAtt":[he,"Arn"]},TaskRoleArn:{"Fn::GetAtt":[z,"Arn"]},ContainerDefinitions:[{Name:"realtime",Image:{"Fn::Sub":`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${u}-realtime:latest`},Essential:!0,PortMappings:[{ContainerPort:R,Protocol:"tcp"}],Environment:fe,LogConfiguration:{LogDriver:"awslogs",Options:{"awslogs-group":`/ecs/${u}-${g}-realtime`,"awslogs-region":{Ref:"AWS::Region"},"awslogs-stream-prefix":"realtime"}},HealthCheck:{Command:["CMD-SHELL",`curl -f http://localhost:${R}${y.healthCheckPath||"/health"} || exit 1`],Interval:30,Timeout:5,Retries:3,StartPeriod:60}}],Tags:[{Key:"Name",Value:`${u}-${g}-realtime`},{Key:"Environment",Value:g}]},DependsOn:[he,z]});let Ct=`${u}${g}RealtimeLogs`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Ct,{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/ecs/${u}-${g}-realtime`,RetentionInDays:30}});let It=`${u}${g}RealtimeService`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(It,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${u}-${g}-realtime`,Cluster:{Ref:"ECSCluster"},TaskDefinition:{Ref:L},DesiredCount:v,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:P}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},HealthCheckGracePeriodSeconds:60,Tags:[{Key:"Name",Value:`${u}-${g}-realtime`},{Key:"Environment",Value:g}]},DependsOn:[L,P,Ct]}),y.autoScaling){let Ve=y.autoScaling,Me=`${u}${g}RealtimeScalableTarget`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(Me,{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{MaxCapacity:Ve.max||10,MinCapacity:Ve.min||1,ResourceId:{"Fn::Sub":`service/\${ECSCluster}/${u}-${g}-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:It}),Ve.targetCPU)this.builder.addResource(`${u}${g}RealtimeCPUPolicy`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${u}-${g}-realtime-cpu-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:Me},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},TargetValue:Ve.targetCPU,ScaleInCooldown:300,ScaleOutCooldown:60}}})}if(h.monitoring?.enabled){let Ve=h.monitoring,Me=Ve.notificationTopicArn;if(!Me&&Ve.notificationEmails?.length){let We=`${u}${g}RealtimeAlarmTopic`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(We,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${u}-${g}-realtime-alarms`,DisplayName:"Realtime Server Alarms"}}),Ve.notificationEmails.forEach((j,ht)=>{this.builder.addResource(`${We}Sub${ht}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:We},Protocol:"email",Endpoint:j}})}),Me={Ref:We}}this.builder.addResource(`${u}${g}RealtimeCPUAlarm`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${u}-${g}-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:`${u}-${g}-realtime`}],...Me&&{AlarmActions:[Me]}},DependsOn:It}),this.builder.addResource(`${u}${g}RealtimeMemoryAlarm`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${u}-${g}-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:`${u}-${g}-realtime`}],...Me&&{AlarmActions:[Me]}},DependsOn:It})}this.builder.addOutput(`${u}${g}RealtimeEndpoint`.replace(/[^a-zA-Z0-9]/g,""),{Description:"Realtime WebSocket server endpoint",Value:{"Fn::Sub":`wss://${u}-${g}-realtime.\${AWS::Region}.elb.amazonaws.com:${R}`},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-endpoint"}}})}generateBroadcastConfig(){let u=this.mergedConfig.infrastructure?.realtime;if(!u||u.mode!=="server")return"";let g=u.server||{};return`import type { BroadcastConfig } from 'ts-broadcasting'
173
+ `.trim()}generateRealtimeServerResources(u,g){let h=this.mergedConfig.infrastructure?.realtime;if(!h)return;let y=h.server||{},R=y.port||6001,v=y.instances||1,P=`${u}${g}RealtimeSG`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(P,{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`Security group for ${u} realtime WebSocket server`,GroupName:`${u}-${g}-realtime-sg`,VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:R,ToPort:R,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:`${u}-${g}-realtime-sg`},{Key:"Environment",Value:g}]}});let L=`${u}${g}RealtimeTaskDef`.replace(/[^a-zA-Z0-9]/g,""),z=`${u}${g}RealtimeTaskRole`.replace(/[^a-zA-Z0-9]/g,""),Ae=`${u}${g}RealtimeExecRole`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Ae,{Type:"AWS::IAM::Role",Properties:{RoleName:`${u}-${g}-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(z,{Type:"AWS::IAM::Role",Properties:{RoleName:`${u}-${g}-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:"*"},...y.redis?.enabled?[{Effect:"Allow",Action:["elasticache:DescribeCacheClusters","elasticache:DescribeReplicationGroups"],Resource:"*"}]:[]]}}]}});let he=[{Name:"BROADCAST_HOST",Value:y.host||"0.0.0.0"},{Name:"BROADCAST_PORT",Value:String(R)},{Name:"NODE_ENV",Value:g==="production"?"production":"development"}];if(y.redis?.enabled){if(y.redis.useElastiCache)he.push({Name:"REDIS_HOST",Value:{"Fn::GetAtt":["CacheCluster","RedisEndpoint.Address"]}}),he.push({Name:"REDIS_PORT",Value:{"Fn::GetAtt":["CacheCluster","RedisEndpoint.Port"]}});else he.push({Name:"REDIS_HOST",Value:y.redis.host||"localhost"}),he.push({Name:"REDIS_PORT",Value:String(y.redis.port||6379)});if(y.redis.keyPrefix)he.push({Name:"REDIS_KEY_PREFIX",Value:y.redis.keyPrefix})}this.builder.addResource(L,{Type:"AWS::ECS::TaskDefinition",Properties:{Family:`${u}-${g}-realtime`,NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:"512",Memory:"1024",ExecutionRoleArn:{"Fn::GetAtt":[Ae,"Arn"]},TaskRoleArn:{"Fn::GetAtt":[z,"Arn"]},ContainerDefinitions:[{Name:"realtime",Image:{"Fn::Sub":`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${u}-realtime:latest`},Essential:!0,PortMappings:[{ContainerPort:R,Protocol:"tcp"}],Environment:he,LogConfiguration:{LogDriver:"awslogs",Options:{"awslogs-group":`/ecs/${u}-${g}-realtime`,"awslogs-region":{Ref:"AWS::Region"},"awslogs-stream-prefix":"realtime"}},HealthCheck:{Command:["CMD-SHELL",`curl -f http://localhost:${R}${y.healthCheckPath||"/health"} || exit 1`],Interval:30,Timeout:5,Retries:3,StartPeriod:60}}],Tags:[{Key:"Name",Value:`${u}-${g}-realtime`},{Key:"Environment",Value:g}]},DependsOn:[Ae,z]});let Ct=`${u}${g}RealtimeLogs`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(Ct,{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/ecs/${u}-${g}-realtime`,RetentionInDays:30}});let It=`${u}${g}RealtimeService`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(It,{Type:"AWS::ECS::Service",Properties:{ServiceName:`${u}-${g}-realtime`,Cluster:{Ref:"ECSCluster"},TaskDefinition:{Ref:L},DesiredCount:v,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",SecurityGroups:[{Ref:P}],Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}]}},HealthCheckGracePeriodSeconds:60,Tags:[{Key:"Name",Value:`${u}-${g}-realtime`},{Key:"Environment",Value:g}]},DependsOn:[L,P,Ct]}),y.autoScaling){let Ve=y.autoScaling,Me=`${u}${g}RealtimeScalableTarget`.replace(/[^a-zA-Z0-9]/g,"");if(this.builder.addResource(Me,{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{MaxCapacity:Ve.max||10,MinCapacity:Ve.min||1,ResourceId:{"Fn::Sub":`service/\${ECSCluster}/${u}-${g}-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:It}),Ve.targetCPU)this.builder.addResource(`${u}${g}RealtimeCPUPolicy`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${u}-${g}-realtime-cpu-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:Me},TargetTrackingScalingPolicyConfiguration:{PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},TargetValue:Ve.targetCPU,ScaleInCooldown:300,ScaleOutCooldown:60}}})}if(h.monitoring?.enabled){let Ve=h.monitoring,Me=Ve.notificationTopicArn;if(!Me&&Ve.notificationEmails?.length){let We=`${u}${g}RealtimeAlarmTopic`.replace(/[^a-zA-Z0-9]/g,"");this.builder.addResource(We,{Type:"AWS::SNS::Topic",Properties:{TopicName:`${u}-${g}-realtime-alarms`,DisplayName:"Realtime Server Alarms"}}),Ve.notificationEmails.forEach((j,ht)=>{this.builder.addResource(`${We}Sub${ht}`,{Type:"AWS::SNS::Subscription",Properties:{TopicArn:{Ref:We},Protocol:"email",Endpoint:j}})}),Me={Ref:We}}this.builder.addResource(`${u}${g}RealtimeCPUAlarm`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${u}-${g}-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:`${u}-${g}-realtime`}],...Me&&{AlarmActions:[Me]}},DependsOn:It}),this.builder.addResource(`${u}${g}RealtimeMemoryAlarm`.replace(/[^a-zA-Z0-9]/g,""),{Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:`${u}-${g}-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:`${u}-${g}-realtime`}],...Me&&{AlarmActions:[Me]}},DependsOn:It})}this.builder.addOutput(`${u}${g}RealtimeEndpoint`.replace(/[^a-zA-Z0-9]/g,""),{Description:"Realtime WebSocket server endpoint",Value:{"Fn::Sub":`wss://${u}-${g}-realtime.\${AWS::Region}.elb.amazonaws.com:${R}`},Export:{Name:{"Fn::Sub":"${AWS::StackName}-realtime-endpoint"}}})}generateBroadcastConfig(){let u=this.mergedConfig.infrastructure?.realtime;if(!u||u.mode!=="server")return"";let g=u.server||{};return`import type { BroadcastConfig } from 'ts-broadcasting'
174
174
 
175
175
  export default {
176
176
  verbose: ${this.environment!=="production"},
@@ -219,7 +219,7 @@ ${g.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 Ep(u){let g=[],h=[];if(!u.AWSTemplateFormatVersion)g.push({path:"AWSTemplateFormatVersion",message:"AWSTemplateFormatVersion is required",severity:"error"});else if(u.AWSTemplateFormatVersion!=="2010-09-09")h.push({path:"AWSTemplateFormatVersion",message:'AWSTemplateFormatVersion should be "2010-09-09"',severity:"warning"});if(!u.Resources||Object.keys(u.Resources).length===0)g.push({path:"Resources",message:"At least one resource is required",severity:"error"});else for(let[y,R]of Object.entries(u.Resources))eg(y,R,g,h);if(u.Resources){let y=ig(u.Resources);if(y.length>0)g.push({path:"Resources",message:`Circular dependencies detected: ${y.join(" -> ")}`,severity:"error"})}if(u.Parameters)for(let[y,R]of Object.entries(u.Parameters))tg(y,R,g,h);if(u.Outputs)for(let[y,R]of Object.entries(u.Outputs))rg(y,R,g,h);return{valid:g.length===0,errors:g,warnings:h}}function eg(u,g,h,y){if(!g.Type)h.push({path:`Resources.${u}.Type`,message:"Resource Type is required",severity:"error"});if(!/^[a-zA-Z0-9]+$/.test(u))y.push({path:`Resources.${u}`,message:"Logical ID should only contain alphanumeric characters",severity:"warning"});if(g.Type&&!g.Type.startsWith("AWS::")&&!g.Type.startsWith("Custom::"))h.push({path:`Resources.${u}.Type`,message:'Resource Type must start with "AWS::" or "Custom::"',severity:"error"});if(g.Properties){for(let[R,v]of Object.entries(g.Properties))if(v===void 0||v===null)y.push({path:`Resources.${u}.Properties.${R}`,message:"Property has undefined or null value",severity:"warning"})}if(g.DependsOn){if(typeof g.DependsOn==="string"){if(g.DependsOn===u)h.push({path:`Resources.${u}.DependsOn`,message:"Resource cannot depend on itself",severity:"error"})}else if(Array.isArray(g.DependsOn)){if(g.DependsOn.includes(u))h.push({path:`Resources.${u}.DependsOn`,message:"Resource cannot depend on itself",severity:"error"})}}}function tg(u,g,h,y){if(!g.Type)h.push({path:`Parameters.${u}.Type`,message:"Parameter Type is required",severity:"error"});let R=["String","Number","List<Number>","CommaDelimitedList","AWS::SSM::Parameter::Value<String>"];if(g.Type&&!R.includes(g.Type)&&!g.Type.startsWith("AWS::"))y.push({path:`Parameters.${u}.Type`,message:`Uncommon parameter type: ${g.Type}`,severity:"warning"});if(g.NoEcho&&g.Default)y.push({path:`Parameters.${u}`,message:"NoEcho parameters should not have default values",severity:"warning"})}function rg(u,g,h,y){if(!g.Value)h.push({path:`Outputs.${u}.Value`,message:"Output Value is required",severity:"error"})}function ig(u){let g={};for(let[P,L]of Object.entries(u)){if(g[P]=[],L.DependsOn){if(typeof L.DependsOn==="string")g[P].push(L.DependsOn);else if(Array.isArray(L.DependsOn))g[P].push(...L.DependsOn)}let z=Mc(L);g[P].push(...z)}let h=new Set,y=new Set,R=[];function v(P,L){h.add(P),y.add(P),L.push(P);let z=g[P]||[];for(let he of z)if(!h.has(he)){if(v(he,L))return!0}else if(y.has(he)){let fe=L.indexOf(he);return R.push(...L.slice(fe),he),!0}return L.pop(),y.delete(P),!1}for(let P of Object.keys(g))if(!h.has(P)){if(v(P,[]))return R}return[]}function Mc(u,g=[]){if(typeof u!=="object"||u===null)return g;if(Array.isArray(u)){for(let h of u)Mc(h,g);return g}if(u.Ref&&typeof u.Ref==="string"&&!u.Ref.startsWith("AWS::"))g.push(u.Ref);if(u["Fn::GetAtt"]){let h=u["Fn::GetAtt"];if(Array.isArray(h)&&h.length>0)g.push(h[0])}for(let h of Object.values(u))Mc(h,g);return g}function og(u){let g=[],h=[],y=new TextEncoder().encode(u).length,R=51200,v=460800;if(y>51200)if(y>460800)g.push({path:"template",message:`Template size (${y} bytes) exceeds maximum allowed size of 460800 bytes`,severity:"error"});else h.push({path:"template",message:`Template size (${y} bytes) exceeds direct upload limit (51200 bytes). You must upload to S3 first.`,severity:"warning"});return{valid:g.length===0,errors:g,warnings:h}}function sg(u){let g=[],h=[],y=u.Resources?Object.keys(u.Resources).length:0,R=u.Parameters?Object.keys(u.Parameters).length:0,v=u.Outputs?Object.keys(u.Outputs).length:0;if(y>500)g.push({path:"Resources",message:`Template has ${y} resources, exceeding the limit of 500`,severity:"error"});else if(y>200)h.push({path:"Resources",message:`Template has ${y} resources. Consider using nested stacks for better organization.`,severity:"warning"});if(R>200)g.push({path:"Parameters",message:`Template has ${R} parameters, exceeding the limit of 200`,severity:"error"});if(v>200)g.push({path:"Outputs",message:`Template has ${v} outputs, exceeding the limit of 200`,severity:"error"});return{valid:g.length===0,errors:g,warnings:h}}function dR(u){let{domains:g,email:h,staging:y=!1,challengeType:R="http-01",certPath:v="/etc/letsencrypt/live",autoRenew:P=!0}=u,L=g[0],z=g.map((fe)=>`-d ${fe}`).join(" "),he=y?"--staging":"";if(R==="http-01")return pg({domains:g,email:h,staging:y,certPath:v,autoRenew:P,domainFlags:z,stagingFlag:he,primaryDomain:L});else{let fe=u.dnsProvider?.provider||(u.hostedZoneId?"route53":void 0);return gg({domains:g,email:h,staging:y,certPath:v,autoRenew:P,domainFlags:z,stagingFlag:he,primaryDomain:L,hostedZoneId:u.hostedZoneId,dnsProvider:u.dnsProvider,dnsProviderType:fe})}}function pg(u){let{email:g,certPath:h,autoRenew:y,domainFlags:R,stagingFlag:v,primaryDomain:P}=u;return`
222
+ `}toYAML(){return this.builder.toYAML()}toJSON(){return this.builder.toJSON()}getBuilder(){return this.builder}}function Ep(u){let g=[],h=[];if(!u.AWSTemplateFormatVersion)g.push({path:"AWSTemplateFormatVersion",message:"AWSTemplateFormatVersion is required",severity:"error"});else if(u.AWSTemplateFormatVersion!=="2010-09-09")h.push({path:"AWSTemplateFormatVersion",message:'AWSTemplateFormatVersion should be "2010-09-09"',severity:"warning"});if(!u.Resources||Object.keys(u.Resources).length===0)g.push({path:"Resources",message:"At least one resource is required",severity:"error"});else for(let[y,R]of Object.entries(u.Resources))eg(y,R,g,h);if(u.Resources){let y=ig(u.Resources);if(y.length>0)g.push({path:"Resources",message:`Circular dependencies detected: ${y.join(" -> ")}`,severity:"error"})}if(u.Parameters)for(let[y,R]of Object.entries(u.Parameters))tg(y,R,g,h);if(u.Outputs)for(let[y,R]of Object.entries(u.Outputs))rg(y,R,g,h);return{valid:g.length===0,errors:g,warnings:h}}function eg(u,g,h,y){if(!g.Type)h.push({path:`Resources.${u}.Type`,message:"Resource Type is required",severity:"error"});if(!/^[a-zA-Z0-9]+$/.test(u))y.push({path:`Resources.${u}`,message:"Logical ID should only contain alphanumeric characters",severity:"warning"});if(g.Type&&!g.Type.startsWith("AWS::")&&!g.Type.startsWith("Custom::"))h.push({path:`Resources.${u}.Type`,message:'Resource Type must start with "AWS::" or "Custom::"',severity:"error"});if(g.Properties){for(let[R,v]of Object.entries(g.Properties))if(v===void 0||v===null)y.push({path:`Resources.${u}.Properties.${R}`,message:"Property has undefined or null value",severity:"warning"})}if(g.DependsOn){if(typeof g.DependsOn==="string"){if(g.DependsOn===u)h.push({path:`Resources.${u}.DependsOn`,message:"Resource cannot depend on itself",severity:"error"})}else if(Array.isArray(g.DependsOn)){if(g.DependsOn.includes(u))h.push({path:`Resources.${u}.DependsOn`,message:"Resource cannot depend on itself",severity:"error"})}}}function tg(u,g,h,y){if(!g.Type)h.push({path:`Parameters.${u}.Type`,message:"Parameter Type is required",severity:"error"});let R=["String","Number","List<Number>","CommaDelimitedList","AWS::SSM::Parameter::Value<String>"];if(g.Type&&!R.includes(g.Type)&&!g.Type.startsWith("AWS::"))y.push({path:`Parameters.${u}.Type`,message:`Uncommon parameter type: ${g.Type}`,severity:"warning"});if(g.NoEcho&&g.Default)y.push({path:`Parameters.${u}`,message:"NoEcho parameters should not have default values",severity:"warning"})}function rg(u,g,h,y){if(!g.Value)h.push({path:`Outputs.${u}.Value`,message:"Output Value is required",severity:"error"})}function ig(u){let g={};for(let[P,L]of Object.entries(u)){if(g[P]=[],L.DependsOn){if(typeof L.DependsOn==="string")g[P].push(L.DependsOn);else if(Array.isArray(L.DependsOn))g[P].push(...L.DependsOn)}let z=Mc(L);g[P].push(...z)}let h=new Set,y=new Set,R=[];function v(P,L){h.add(P),y.add(P),L.push(P);let z=g[P]||[];for(let Ae of z)if(!h.has(Ae)){if(v(Ae,L))return!0}else if(y.has(Ae)){let he=L.indexOf(Ae);return R.push(...L.slice(he),Ae),!0}return L.pop(),y.delete(P),!1}for(let P of Object.keys(g))if(!h.has(P)){if(v(P,[]))return R}return[]}function Mc(u,g=[]){if(typeof u!=="object"||u===null)return g;if(Array.isArray(u)){for(let h of u)Mc(h,g);return g}if(u.Ref&&typeof u.Ref==="string"&&!u.Ref.startsWith("AWS::"))g.push(u.Ref);if(u["Fn::GetAtt"]){let h=u["Fn::GetAtt"];if(Array.isArray(h)&&h.length>0)g.push(h[0])}for(let h of Object.values(u))Mc(h,g);return g}function og(u){let g=[],h=[],y=new TextEncoder().encode(u).length,R=51200,v=460800;if(y>51200)if(y>460800)g.push({path:"template",message:`Template size (${y} bytes) exceeds maximum allowed size of 460800 bytes`,severity:"error"});else h.push({path:"template",message:`Template size (${y} bytes) exceeds direct upload limit (51200 bytes). You must upload to S3 first.`,severity:"warning"});return{valid:g.length===0,errors:g,warnings:h}}function sg(u){let g=[],h=[],y=u.Resources?Object.keys(u.Resources).length:0,R=u.Parameters?Object.keys(u.Parameters).length:0,v=u.Outputs?Object.keys(u.Outputs).length:0;if(y>500)g.push({path:"Resources",message:`Template has ${y} resources, exceeding the limit of 500`,severity:"error"});else if(y>200)h.push({path:"Resources",message:`Template has ${y} resources. Consider using nested stacks for better organization.`,severity:"warning"});if(R>200)g.push({path:"Parameters",message:`Template has ${R} parameters, exceeding the limit of 200`,severity:"error"});if(v>200)g.push({path:"Outputs",message:`Template has ${v} outputs, exceeding the limit of 200`,severity:"error"});return{valid:g.length===0,errors:g,warnings:h}}function dR(u){let{domains:g,email:h,staging:y=!1,challengeType:R="http-01",certPath:v="/etc/letsencrypt/live",autoRenew:P=!0}=u,L=g[0],z=g.map((he)=>`-d ${he}`).join(" "),Ae=y?"--staging":"";if(R==="http-01")return pg({domains:g,email:h,staging:y,certPath:v,autoRenew:P,domainFlags:z,stagingFlag:Ae,primaryDomain:L});else{let he=u.dnsProvider?.provider||(u.hostedZoneId?"route53":void 0);return gg({domains:g,email:h,staging:y,certPath:v,autoRenew:P,domainFlags:z,stagingFlag:Ae,primaryDomain:L,hostedZoneId:u.hostedZoneId,dnsProvider:u.dnsProvider,dnsProviderType:he})}}function pg(u){let{email:g,certPath:h,autoRenew:y,domainFlags:R,stagingFlag:v,primaryDomain:P}=u;return`
223
223
  # ==========================================
224
224
  # Let's Encrypt Certificate Setup (HTTP-01)
225
225
  # ==========================================
@@ -257,7 +257,7 @@ ${y?Wc(P):"# Auto-renewal disabled"}
257
257
 
258
258
  # Restart the application
259
259
  systemctl start stacks
260
- `}function gg(u){let{email:g,certPath:h,autoRenew:y,domainFlags:R,stagingFlag:v,primaryDomain:P,hostedZoneId:L,dnsProvider:z,dnsProviderType:he}=u;if(he==="route53"||L){if(!L)throw Error("hostedZoneId is required for DNS-01 challenge with Route53");return`
260
+ `}function gg(u){let{email:g,certPath:h,autoRenew:y,domainFlags:R,stagingFlag:v,primaryDomain:P,hostedZoneId:L,dnsProvider:z,dnsProviderType:Ae}=u;if(Ae==="route53"||L){if(!L)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
  # ==========================================
@@ -289,9 +289,9 @@ else
289
289
  fi
290
290
 
291
291
  ${y?Wc(P):"# Auto-renewal disabled"}
292
- `}if(!z)throw Error("dnsProvider configuration is required for DNS-01 challenge with external DNS providers");let fe=z.provider.toUpperCase(),Ct=Cg(z);return`
292
+ `}if(!z)throw Error("dnsProvider configuration is required for DNS-01 challenge with external DNS providers");let he=z.provider.toUpperCase(),Ct=Cg(z);return`
293
293
  # ==========================================
294
- # Let's Encrypt Certificate Setup (DNS-01 via ${fe})
294
+ # Let's Encrypt Certificate Setup (DNS-01 via ${he})
295
295
  # ==========================================
296
296
 
297
297
  # Install certbot
@@ -302,10 +302,10 @@ ${Ct}
302
302
  # Create DNS challenge hook scripts directory
303
303
  mkdir -p /etc/letsencrypt/hooks
304
304
 
305
- # Create authenticator hook for ${fe}
305
+ # Create authenticator hook for ${he}
306
306
  cat > /etc/letsencrypt/hooks/auth-hook.sh << 'AUTHHOOK'
307
307
  #!/bin/bash
308
- # DNS-01 authenticator hook for ${fe}
308
+ # DNS-01 authenticator hook for ${he}
309
309
  # This creates the TXT record for ACME challenge
310
310
 
311
311
  DOMAIN="$CERTBOT_DOMAIN"
@@ -321,10 +321,10 @@ AUTHHOOK
321
321
 
322
322
  chmod +x /etc/letsencrypt/hooks/auth-hook.sh
323
323
 
324
- # Create cleanup hook for ${fe}
324
+ # Create cleanup hook for ${he}
325
325
  cat > /etc/letsencrypt/hooks/cleanup-hook.sh << 'CLEANUPHOOK'
326
326
  #!/bin/bash
327
- # DNS-01 cleanup hook for ${fe}
327
+ # DNS-01 cleanup hook for ${he}
328
328
  # This removes the TXT record after validation
329
329
 
330
330
  DOMAIN="$CERTBOT_DOMAIN"
@@ -602,4 +602,4 @@ async function handleRequest(request: Request): Promise<Response> {
602
602
  return new Response('Hello from Stacks!')
603
603
  }
604
604
  `}async function Tg(u,g,h){let y=`_acme-challenge.${g}`;if(await wg(u,g,y,h))return;let R=await u.createRecord(g,{name:y,type:"TXT",content:h,ttl:60});if(!R.success)throw Error(`Failed to create DNS challenge record: ${R.message}`)}async function $g(u,g,h){let y=await u.deleteRecord(g,{name:`_acme-challenge.${g}`,type:"TXT",content:h});if(!y.success)console.warn(`Failed to delete DNS challenge record: ${y.message}`)}async function wg(u,g,h,y){try{let R=await u.listRecords(g,"TXT"),v=h.replace(/\.$/,"").toLowerCase();return(R.records??[]).some((P)=>P.name.replace(/\.$/,"").toLowerCase()===v&&P.content.replace(/^"|"$/g,"")===y)}catch{return!1}}function rd(u){let{hostedZoneId:g,dnsProvider:h,region:y="us-east-1"}=u;if(h)return N(h);if(g)return new ie(y,g);throw Error("Either dnsProvider or hostedZoneId must be provided")}async function mR(u){await Tg(rd(u),u.domain,u.challengeValue)}async function gR(u){await $g(rd(u),u.domain,u.challengeValue)}function fR(u){try{let{execSync:g}=st("node:child_process"),h=g(`openssl x509 -checkend 2592000 -noout -in ${u}/cert.pem`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return!1}catch{return!0}}import{createHash as nd,createSign as vg,generateKeyPairSync as ld}from"node:crypto";var ud={production:"https://acme-v02.api.letsencrypt.org/directory",staging:"https://acme-staging-v02.api.letsencrypt.org/directory"};class Lg{directoryUrl;email;accountKey;accountUrl=null;directory=null;nonce=null;constructor(u){this.directoryUrl=u.staging?ud.staging:ud.production,this.email=u.email,this.accountKey=u.accountKey||this.generateAccountKey()}generateAccountKey(){let{privateKey:u}=ld("ec",{namedCurve:"P-256"});return u.export({type:"pkcs8",format:"pem"})}async getDirectory(){if(this.directory)return this.directory;let u=await fetch(this.directoryUrl);if(!u.ok)throw Error(`Failed to fetch ACME directory: ${u.status}`);return this.directory=await u.json(),this.directory}async getNonce(){if(this.nonce){let y=this.nonce;return this.nonce=null,y}let u=await this.getDirectory(),h=(await fetch(u.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!h)throw Error("Failed to get nonce from ACME server");return h}getJwk(){let u=this.accountKey.split(`
605
- `).filter((v)=>!v.startsWith("-----")).join(""),g=Buffer.from(u,"base64"),h=g.length-65,y=g.subarray(h+1,h+33),R=g.subarray(h+33,h+65);return{kty:"EC",crv:"P-256",x:this.base64UrlEncode(y),y:this.base64UrlEncode(R)}}getJwkThumbprint(){let u=this.getJwk(),g=JSON.stringify({crv:u.crv,kty:u.kty,x:u.x,y:u.y}),h=nd("sha256").update(g).digest();return this.base64UrlEncode(h)}base64UrlEncode(u){return(typeof u==="string"?Buffer.from(u):u).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async signPayload(u,g){let h=await this.getNonce(),y=this.getJwk(),R={alg:"ES256",nonce:h,url:u};if(this.accountUrl)R.kid=this.accountUrl;else R.jwk=y;let v=this.base64UrlEncode(JSON.stringify(R)),P=g===""?"":this.base64UrlEncode(JSON.stringify(g)),L=`${v}.${P}`,z=vg("SHA256");z.update(L);let he=z.sign(this.accountKey),fe=he.subarray(4,4+he[3]),Ct=4+he[3]+2,It=he.subarray(Ct,Ct+he[Ct-1]),Ve=Buffer.alloc(32),Me=Buffer.alloc(32);fe.copy(Ve,32-fe.length),It.copy(Me,32-It.length);let We=Buffer.concat([Ve,Me]);return JSON.stringify({protected:v,payload:P,signature:this.base64UrlEncode(We)})}async acmeRequest(u,g){let h=await this.signPayload(u,g),y=await fetch(u,{method:"POST",headers:{"Content-Type":"application/jose+json"},body:h}),R=y.headers.get("replay-nonce");if(R)this.nonce=R;let v,P=y.headers.get("content-type");if(P?.includes("application/json")||P?.includes("application/problem+json"))v=await y.json();else v=await y.text();if(!y.ok)throw Error(`ACME request failed: ${JSON.stringify(v)}`);return{body:v,headers:y.headers}}async registerAccount(){let u=await this.getDirectory(),{body:g,headers:h}=await this.acmeRequest(u.newAccount,{termsOfServiceAgreed:!0,contact:[`mailto:${this.email}`]}),y=h.get("location");if(!y)throw Error("No account URL returned");return this.accountUrl=y,y}async createOrder(u){if(!this.accountUrl)await this.registerAccount();let g=await this.getDirectory(),{body:h,headers:y}=await this.acmeRequest(g.newOrder,{identifiers:u.map((v)=>({type:"dns",value:v}))}),R=y.get("location");if(!R)throw Error("No order URL returned");return{orderUrl:R,authorizations:h.authorizations,finalize:h.finalize}}async getAuthorization(u){let{body:g}=await this.acmeRequest(u,""),h=g.identifier.value,y=this.getJwkThumbprint(),R=g.challenges.filter((v)=>v.type==="http-01"||v.type==="dns-01").map((v)=>{let P=`${v.token}.${y}`;if(v.type==="http-01")return{type:"http-01",token:v.token,keyAuthorization:P,identifier:`/.well-known/acme-challenge/${v.token}`};else{let L=this.base64UrlEncode(nd("sha256").update(P).digest());return{type:"dns-01",token:v.token,keyAuthorization:P,identifier:`_acme-challenge.${h}`,dnsValue:L}}});return{domain:h,challenges:R}}async respondToChallenge(u){await this.acmeRequest(u,{})}async waitForAuthorization(u,g=30){for(let h=0;h<g;h++){let{body:y}=await this.acmeRequest(u,"");if(y.status==="valid")return;if(y.status==="invalid")throw Error(`Authorization failed: ${JSON.stringify(y)}`);await new Promise((R)=>setTimeout(R,2000))}throw Error("Authorization timed out")}generateCsr(u){let{privateKey:g}=ld("rsa",{modulusLength:2048}),h=g.export({type:"pkcs8",format:"pem"});return{csr:this.createSimpleCsr(u,g),privateKey:h}}createSimpleCsr(u,g){throw Error("CSR generation requires additional implementation. Consider using the shell-based certbot approach instead.")}async finalizeOrder(u,g){let{csr:h,privateKey:y}=this.generateCsr(g),{body:R}=await this.acmeRequest(u,{csr:this.base64UrlEncode(Buffer.from(h,"base64"))}),v=R.certificate;if(!v)throw Error("Certificate not immediately available - polling not implemented");let L=await(await fetch(v)).text(),z=L.split(/(?=-----BEGIN CERTIFICATE-----)/g),he=z[0],fe=z.slice(1).join("");return{certificate:he,privateKey:y,chain:fe,fullchain:L,expiresAt:new Date(Date.now()+7776000000)}}getAccountKey(){return this.accountKey}}var Vr=(u)=>u===void 0?void 0:u?"on":"off";function Vc(u){let g={ssl:u.ssl,always_use_https:Vr(u.alwaysUseHttps),automatic_https_rewrites:Vr(u.automaticHttpsRewrites),min_tls_version:u.minTlsVersion,tls_1_3:Vr(u.tls13),brotli:Vr(u.brotli),http3:Vr(u.http3),"0rtt":Vr(u.zeroRtt),early_hints:Vr(u.earlyHints),browser_cache_ttl:u.browserCacheTtl,always_online:Vr(u.alwaysOnline),websockets:Vr(u.websockets),email_obfuscation:Vr(u.emailObfuscation)};if(u.hsts)g.security_header={strict_transport_security:{enabled:u.hsts.enabled,max_age:u.hsts.maxAge??31536000,include_subdomains:u.hsts.includeSubdomains??!1,preload:u.hsts.preload??!1,nosniff:u.hsts.noSniff??!0}};for(let h of Object.keys(g))if(g[h]===void 0)delete g[h];return{...g,...u.raw??{}}}var wi={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 Fg}from"node:tls";async function zc(u){let{address:g,serverName:h,port:y=443,timeoutMs:R=5000}=u;return new Promise((v)=>{let P=!1,L=(he)=>{if(P)return;P=!0;try{z.destroy()}catch{}v(he)},z=Fg({host:g,port:y,servername:h,rejectUnauthorized:!1,timeout:R});z.once("secureConnect",()=>{if(z.authorized){L({reachable:!0,trusted:!0});return}L({reachable:!0,trusted:!1,reason:z.authorizationError?String(z.authorizationError):"origin certificate is not trusted for this hostname"})}),z.once("timeout",()=>{L({reachable:!1,trusted:!1,reason:`no TLS handshake within ${R}ms`})}),z.once("error",(he)=>{L({reachable:!1,trusted:!1,reason:he.message})})})}function Mg(u,g){let h=g.replace(/\.$/,"").toLowerCase();return u.some((y)=>{let R=y.replace(/\.$/,"").toLowerCase();if(R===h)return!0;if(!R.startsWith("*."))return!1;let v=R.slice(2);if(!h.endsWith(`.${v}`))return!1;return!h.slice(0,h.length-v.length-1).includes(".")})}async function Wg(u){let{provider:g,zone:h,hosts:y,ipv4:R,ipv6:v,proxied:P=!0,settings:L=wi,cache:z,originGuard:he,purge:fe=!0,ttl:Ct=300,skipOriginProbe:It=!1,skipEdgeCertificateCheck:Ve=!1}=u,Me={records:[],settingsChanged:[],cacheRules:0,originGuard:!1,purged:!1,deferredProxy:[],warnings:[]};if(y.length===0)return Me;let We=[],j=P&&!Ve?await g.listEdgeCertificateHosts(h):null;for(let G of y){let Ke=P;if(Ke&&j&&!Mg(j,G)){Ke=!1;let vt=j.length===0?"the zone has no active edge certificate yet":`no active edge certificate covers it (${j.join(", ")})`;Me.deferredProxy.push({host:G,reason:vt}),Me.warnings.push(`${G}: publishing DNS-only — ${vt}. 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(Ke&&!It){let vt=await zc({address:R,serverName:G});if(!vt.trusted){Ke=!1;let Et=vt.reason||"origin is not serving a trusted certificate";Me.deferredProxy.push({host:G,reason:Et}),Me.warnings.push(`${G}: publishing DNS-only for now — the origin does not yet serve a certificate this proxy can verify (${Et}). 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(Ke)We.push(G);let yt=[{type:"A",content:R}];if(v&&Yn(G))yt.push({type:"AAAA",content:v});for(let{type:vt,content:Et}of yt){let Zt=await g.upsertRecord(h,{name:G,type:vt,content:Et,ttl:Ct,proxied:Ke});if(Zt.success)Me.records.push({host:G,type:vt,content:Et,proxied:Ke});else Me.warnings.push(`${G} ${vt} → ${Et} failed: ${Zt.message||"unknown provider error"}`)}}if(We.length===0){if(P)Me.warnings.push("No host is proxied yet, so zone settings, cache rules and purge were skipped — they only take effect through the proxy.");return Me}try{let G=Vc(L),Ke=await g.applyZoneSettings(h,G);Me.settingsChanged=Ke.changed;for(let yt of Ke.failed)Me.warnings.push(`zone setting '${yt.id}' could not be applied: ${yt.error}`)}catch(G){Me.warnings.push(`zone settings could not be read: ${G instanceof Error?G.message:String(G)}`)}let ht=kc(We,z);if(ht.length>0){let G=await g.putManagedPhaseRules(h,"http_request_cache_settings",ht);if(G.success)Me.cacheRules=ht.length;else Me.warnings.push(`cache rules could not be written: ${G.message}`)}if(he){let G=Nc(We,he.header,he.value);if(G.length>0){let Ke=await g.putManagedPhaseRules(h,"http_request_late_transform",G);if(Ke.success)Me.originGuard=!0;else Me.warnings.push(`origin guard header could not be written: ${Ke.message}. `+"The gateway will reject requests that lack it — disable the guard or grant the token Transform Rules: Edit.")}}if(fe){if(Me.purged=await g.purgeCache(h,{hosts:We}),!Me.purged)Me.warnings.push("edge cache purge failed — new content may take until TTL expiry to appear.")}return Me}var Vg=(u)=>process.env[u];function dd(u,g){let h=u.replace(/\.$/,"").toLowerCase();if(g){let y=g.replace(/\.$/,"").toLowerCase();if(h===y||h.endsWith(`.${y}`))return y}return h.split(".").slice(-2).join(".")}function zg(u,g={}){let h=g.env??Vg,y=u.infrastructure?.compute?.proxy?.cdn,R=[];if(!y||y.provider!=="cloudflare")return{plan:null,errors:R};if(y.originDomain)R.push(`compute.proxy.cdn.originDomain (${y.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 v=h("CLOUDFLARE_API_TOKEN");if(!v)return R.push("CLOUDFLARE_API_TOKEN is not set — the Cloudflare CDN cannot be reconciled."),{plan:null,errors:R};let P=u.sites??{},L=y.frontedHosts?.length?[...new Set(y.frontedHosts.map((It)=>It.toLowerCase()))]:fo(P,{autoWww:u.infrastructure?.compute?.proxy?.autoWww!==!1});if(L.length===0)return R.push("No hostnames to front — set compute.proxy.cdn.frontedHosts, or give a site a domain."),{plan:null,errors:R};let z=u.infrastructure?.dns?.domain,he=new Set(L.map((It)=>dd(It,z)));if(he.size>1)return R.push(`Fronted hosts span more than one zone (${[...he].join(", ")}). A Cloudflare zone is configured as a unit, so run one CDN config per zone.`),{plan:null,errors:R};let fe=y.cloudflare??{},Ct=y.secret?{header:y.secretHeader??"X-Origin-Verify",value:y.secret}:void 0;return{plan:{zone:[...he][0],hosts:L,apiToken:v,zoneId:fe.zoneId??h("CLOUDFLARE_ZONE_ID"),accountId:fe.accountId??h("CLOUDFLARE_ACCOUNT_ID"),proxied:fe.proxied!==!1,settings:fe.settings??wi,cache:fe.cache,originGuard:Ct,purge:fe.purgeOnDeploy!==!1,skipOriginProbe:fe.skipOriginProbe===!0},errors:R}}var Hg=26214400;var Ug=new Set(["/_headers","/_redirects","/_routes.json","/_worker.js"]);class pd{name="cloudflare-pages";apiToken;accountId;constructor(u){if(!u.apiToken)throw Error("Cloudflare Pages needs an API token");if(!u.accountId)throw Error("Cloudflare Pages needs an account id");this.apiToken=u.apiToken,this.accountId=u.accountId}async request(u,g,h){return $s(u,`/accounts/${this.accountId}${g}`,`Bearer ${this.apiToken}`,h)}async getProject(u){try{return await this.request("GET",`/pages/projects/${u}`)}catch(g){if(g instanceof Error&&/\b8000007\b|not found/i.test(g.message))return null;throw g}}async ensureProject(u,g="main"){let h=await this.getProject(u);if(h)return h;return this.request("POST","/pages/projects",{name:u,production_branch:g})}async uploadToken(u){return(await this.request("GET",`/pages/projects/${u}/upload-token`)).jwt}async missingHashes(u,g){let h=await $s("POST","/pages/assets/check-missing",`Bearer ${u}`,{hashes:g});return new Set(h)}async upsertHashes(u,g){await $s("POST","/pages/assets/upsert-hashes",`Bearer ${u}`,{hashes:g})}async uploadBatch(u,g){let h=g.map((y)=>({key:y.hash,value:y.base64,metadata:{contentType:jg(y.extension)},base64:!0}));await $s("POST","/pages/assets/upload",`Bearer ${u}`,h)}async createDeployment(u,g,h){let y={};for(let v of g)y[v.path]=v.hash;let R=new FormData;if(R.append("manifest",JSON.stringify(y)),h)R.append("branch",h);return this.request("POST",`/pages/projects/${u}/deployments`,R)}async deployDirectory(u){let g=await ep(u.directory);if(g.length===0)throw Error(`No files to deploy in ${u.directory}`);let h=await this.uploadToken(u.project),y=await this.missingHashes(h,g.map((z)=>z.hash)),R=g.filter((z)=>y.has(z.hash)),v=[];for(let z=0;z<R.length;z+=100)v.push(R.slice(z,z+100));let P=0;for(let z=0;z<v.length;z+=4){let he=v.slice(z,z+4);await Promise.all(he.map((fe)=>this.uploadBatch(h,fe))),P+=he.reduce((fe,Ct)=>fe+Ct.length,0),u.onProgress?.(P,R.length)}return await this.upsertHashes(h,g.map((z)=>z.hash)),{deployment:await this.createDeployment(u.project,g,u.branch),total:g.length,uploaded:R.length,uploadedBytes:R.reduce((z,he)=>z+he.size,0)}}async listCustomDomains(u){return(await this.request("GET",`/pages/projects/${u}/domains`)).map((h)=>h.name)}async attachCustomDomain(u,g){if((await this.listCustomDomains(u)).includes(g))return!1;return await this.request("POST",`/pages/projects/${u}/domains`,{name:g}),!0}}function Gg(u,g){return{type:"CNAME",name:u,value:g.endsWith(".pages.dev")?g:`${g}.pages.dev`,ttl:1,proxied:!0}}async function gd(u,g){let{blake3:h}=await import("./chunk-4ccv5c4m.js").then((m)=>xS(m.default,1));return(await h(u+g)).slice(0,32)}async function ep(u){let{readdir:g}=await import("node:fs/promises"),{join:h,relative:y,sep:R}=await import("node:path"),v=[];async function P(L){let z=await g(L,{withFileTypes:!0});for(let he of z){let fe=h(L,he.name);if(he.isDirectory()){await P(fe);continue}if(!he.isFile())continue;let Ct=`/${y(u,fe).split(R).join("/")}`;if(Ug.has(Ct))continue;let It=await Bun.file(fe).bytes();if(It.byteLength>26214400)throw Error(`${Ct} is ${It.byteLength} bytes, over the Cloudflare Pages limit of 26214400`);let Ve=Buffer.from(It).toString("base64"),Me=he.name.lastIndexOf("."),We=Me>0?he.name.slice(Me+1):"";v.push({path:Ct,hash:await gd(Ve,We),base64:Ve,extension:We,size:It.byteLength})}}return await P(u),v.sort((L,z)=>L.path.localeCompare(z.path)),v}function jg(u){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"}[u.toLowerCase()]||"application/octet-stream"}async function $s(u,g,h,y){let R={Authorization:h},v;if(y instanceof FormData)v=y;else if(y!==void 0)R["Content-Type"]="application/json",v=JSON.stringify(y);let P=await fetch(`https://api.cloudflare.com/client/v4${g}`,{method:u,headers:R,body:v}),L=await P.text(),z;try{z=JSON.parse(L)}catch{throw Error(`Cloudflare Pages API returned ${P.status} with a non-JSON body: ${L.slice(0,200)}`)}if(!z.success){let he=(z.errors??[]).map((fe)=>`${fe.code}: ${fe.message}`).join(", ");throw Error(`Cloudflare Pages API error (${P.status}): ${he||L.slice(0,200)}`)}return z.result}import{createHash as Kg}from"node:crypto";var rp="https://api.cloudflare.com/client/v4",np=10042,qg=10006,Zg=10059;class Fn extends Error{status;errors;constructor(u,g,h=[]){super(u);this.name="R2ApiError",this.status=g,this.errors=h}hasCode(u){return this.errors.some((g)=>g.code===u)}}class An extends Fn{accountId;constructor(u,g,h=[]){super(`R2 is not enabled on Cloudflare account ${u}. Enable it once in the Cloudflare dashboard (R2 Object Storage, then follow the prompt to activate it), then re-run the deploy.`,g,h);this.name="R2NotEnabledError",this.accountId=u}}class ai{name="cloudflare-r2";apiToken;accountId;fetchImpl;constructor(u){if(!u.apiToken)throw Error("Cloudflare R2 needs an API token");if(!u.accountId)throw Error("Cloudflare R2 needs an account id");this.apiToken=u.apiToken,this.accountId=u.accountId,this.fetchImpl=u.fetch??((g,h)=>fetch(g,h))}async requestEnvelope(u,g,h,y={}){let R={Authorization:`Bearer ${this.apiToken}`};if(h!==void 0)R["Content-Type"]="application/json";if(y.jurisdiction&&y.jurisdiction!=="default")R["cf-r2-jurisdiction"]=y.jurisdiction;let v=await this.fetchImpl(`${rp}/accounts/${this.accountId}/r2${g}`,{method:u,headers:R,body:h===void 0?void 0:JSON.stringify(h)}),P=await v.text(),L;try{L=JSON.parse(P)}catch{throw new Fn(`Cloudflare R2 API returned ${v.status} with a non-JSON body: ${P.slice(0,200)}`,v.status)}if(!L.success){let z=L.errors??[];if(z.some((fe)=>fe.code===np))throw new An(this.accountId,v.status,z);let he=z.map((fe)=>`${fe.code}: ${fe.message}`).join(", ");throw new Fn(`Cloudflare R2 API error (${v.status}) on ${u} ${g}: ${he||P.slice(0,200)}`,v.status,z)}return L}async request(u,g,h,y){return(await this.requestEnvelope(u,g,h,y)).result}bucketPath(u){return`/buckets/${encodeURIComponent(u)}`}async listBuckets(u={}){let g=[],h;do{let y=new URLSearchParams({per_page:"1000"});if(h)y.set("cursor",h);let R=await this.requestEnvelope("GET",`/buckets?${y}`,void 0,u),v=R.result?.buckets??[];g.push(...v),h=v.length>0?R.result_info?.cursor||void 0:void 0}while(h);return g}async getBucket(u,g={}){try{return await this.request("GET",this.bucketPath(u),void 0,g)}catch(h){if(h instanceof An)throw h;if(h instanceof Fn&&(h.hasCode(qg)||h.status===404))return null;throw h}}async ensureBucket(u,g={}){let h={jurisdiction:g.jurisdiction},y=await this.getBucket(u,h);if(y)return{bucket:y,created:!1};let R={name:u};if(g.locationHint)R.locationHint=g.locationHint;let v=await this.request("POST","/buckets",R,h);return{bucket:{...v,name:v?.name||u},created:!0}}async getCors(u,g={}){try{return(await this.request("GET",`${this.bucketPath(u)}/cors`,void 0,g))?.rules??[]}catch(h){if(h instanceof Fn&&!(h instanceof An)&&(h.hasCode(Zg)||h.status===404))return[];throw h}}async putCors(u,g,h={}){if(g.length===0){await this.request("DELETE",`${this.bucketPath(u)}/cors`,void 0,h);return}await this.request("PUT",`${this.bucketPath(u)}/cors`,{rules:g},h)}async ensureCors(u,g,h={}){let y=await this.getCors(u,h);if(vs(y,g))return!1;return await this.putCors(u,g,h),!0}async getLifecycle(u,g={}){return(await this.request("GET",`${this.bucketPath(u)}/lifecycle`,void 0,g))?.rules??[]}async putLifecycle(u,g,h={}){await this.request("PUT",`${this.bucketPath(u)}/lifecycle`,{rules:g},h)}async ensureLifecycle(u,g,h={}){let y=await this.getLifecycle(u,h);if(xs(y,g))return!1;return await this.putLifecycle(u,g,h),!0}async listCustomDomains(u,g={}){return(await this.request("GET",`${this.bucketPath(u)}/domains/custom`,void 0,g))?.domains??[]}async attachCustomDomain(u,g,h={}){return this.request("POST",`${this.bucketPath(u)}/domains/custom`,{domain:g.domain,zoneId:g.zoneId,enabled:g.enabled??!0,minTLS:g.minTLS??"1.2"},h)}async updateCustomDomain(u,g,h,y={}){return this.request("PUT",`${this.bucketPath(u)}/domains/custom/${encodeURIComponent(g)}`,h,y)}async ensureCustomDomain(u,g,h={},y){let R=g.minTLS??"1.2",P=(y??await this.listCustomDomains(u,h)).find((he)=>he.domain.toLowerCase()===g.domain.toLowerCase());if(!P){let he=await this.attachCustomDomain(u,{...g,minTLS:R,enabled:!0},h);return{action:"attached",domain:{...he,domain:he?.domain||g.domain}}}let L=P.minTLS??"1.0";if(P.enabled&&L===R)return{action:"unchanged",domain:P};let z=await this.updateCustomDomain(u,P.domain,{enabled:!0,minTLS:R},h);return{action:"updated",domain:{...P,...z}}}async getManagedDomain(u,g={}){return this.request("GET",`${this.bucketPath(u)}/domains/managed`,void 0,g)}async setManagedDomain(u,g,h={}){let y=await this.getManagedDomain(u,h);if(y?.enabled===g)return{changed:!1,domain:y};return{changed:!0,domain:await this.request("PUT",`${this.bucketPath(u)}/domains/managed`,{enabled:g},h)}}}function ip(u){return`https://${u}.r2.cloudflarestorage.com`}async function Jg(u){let{apiToken:g,accountId:h}=u;if(!g)throw Error("r2S3Credentials needs an API token");if(!h)throw Error("r2S3Credentials needs an account id");let y=u.fetch??((P,L)=>fetch(P,L)),R=[],v;for(let P of[`/accounts/${h}/tokens/verify`,"/user/tokens/verify"]){let L=await y(`${rp}${P}`,{method:"GET",headers:{Authorization:`Bearer ${g}`}}),z=await L.json().catch(()=>null);if(L.ok&&z?.success&&z.result?.id){v=z.result.id;break}let he=z?.errors?.map((fe)=>`${fe.code}: ${fe.message}`).join(", ");R.push(`${P} -> ${L.status}${he?` (${he})`:""}`)}if(!v)throw Error(`Could not verify the Cloudflare API token to derive R2 credentials: ${R.join("; ")}`);return{accessKeyId:v,secretAccessKey:Kg("sha256").update(g).digest("hex"),endpoint:ip(h),region:"auto"}}function Ni(u){if(Array.isArray(u))return`[${u.map(Ni).join(",")}]`;if(u&&typeof u==="object")return`{${Object.entries(u).filter(([,h])=>h!==void 0).sort(([h],[y])=>h.localeCompare(y)).map(([h,y])=>`${JSON.stringify(h)}:${Ni(y)}`).join(",")}}`;return JSON.stringify(u)}function tp(u,g){let h=(y)=>y&&y.length>0?[...y].map(String).sort():void 0;return{id:g?u.id:void 0,allowed:{origins:h(u.allowed?.origins),methods:h(u.allowed?.methods?.map((y)=>y.toUpperCase())),headers:h(u.allowed?.headers?.map((y)=>y.toLowerCase()))},exposeHeaders:h(u.exposeHeaders?.map((y)=>y.toLowerCase())),maxAgeSeconds:u.maxAgeSeconds}}function vs(u,g){if(u.length!==g.length)return!1;return g.every((h,y)=>{let R=h.id!==void 0;return Ni(tp(u[y],R))===Ni(tp(h,R))})}function xs(u,g){if(u.length!==g.length)return!1;let h=(y)=>Ni([...y].map((R)=>({...R,storageClassTransitions:R.storageClassTransitions?.length?R.storageClassTransitions:void 0})).sort((R,v)=>R.id.localeCompare(v.id)));return h(u)===h(g)}var Yg="r2 cache",Xg=/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/;async function Qg(u,g={}){let h=g.log??(()=>{}),y={buckets:[],warnings:[]},R=u.infrastructure?.r2??u.r2,v=Object.entries(R?.buckets??{});if(v.length===0)return h("R2: no buckets declared, skipping."),y;if(!g.apiToken||!g.accountId){let fe=[!g.apiToken&&"CLOUDFLARE_API_TOKEN",!g.accountId&&"CLOUDFLARE_ACCOUNT_ID"].filter(Boolean).join(" and "),Ct=`R2: ${v.length} bucket(s) declared but ${fe} is not set, skipping.`;return h(Ct),y.warnings.push(Ct),y}let P=g.dryRun===!0,L=new ai({apiToken:g.apiToken,accountId:g.accountId,fetch:g.fetch}),z=new H(g.apiToken,{zoneId:g.zoneId,accountId:g.accountId}),he=new Map;for(let[fe,Ct]of v){let It=Ct?.name;if(!It||!Xg.test(It)){y.warnings.push(`R2: bucket '${fe}' has an invalid name '${It??""}' (3-63 chars: lowercase letters, digits, hyphens), skipping.`);continue}h(`R2: ${P?"checking":"reconciling"} bucket ${It}...`);let Ve={name:It,changes:[],domains:[]};if(y.buckets.push(Ve),await yh(Ct,{r2:L,cloudflare:z,dryRun:P,summary:Ve,warnings:y.warnings,claimed:he,log:h}),Ve.changes.length===0)h(`R2: ${It} is in sync.`);else for(let Me of Ve.changes)h(`R2: ${It}: ${Me}`)}return y}async function yh(u,g){let{r2:h,dryRun:y,summary:R,warnings:v}=g,P=u.name,L={jurisdiction:u.jurisdiction},z=(Ve,Me)=>{let We=y?Me&&`would ${Me}`:Ve;if(We)R.changes.push(We)},he;if(y)he=await h.getBucket(P,L)!==null;else{let{created:Ve}=await h.ensureBucket(P,{locationHint:u.locationHint,jurisdiction:u.jurisdiction});if(he=!0,Ve)z("created","")}if(!he)z("","create bucket");let fe=Sh(u.customDomains);await ro(g,`cors on ${P}`,async()=>{if(!u.cors)return;if(!he){z("cors updated","set cors");return}let Ve=await h.getCors(P,L);if(vs(Ve,u.cors))return;if(!y)await h.putCors(P,u.cors,L);z(u.cors.length===0?"cors removed":"cors updated",u.cors.length===0?"remove cors":"update cors")}),await ro(g,`lifecycle on ${P}`,async()=>{if(!u.lifecycle)return;let Ve=u.lifecycle.map(cp);if(he){let Me=await h.getLifecycle(P,L);if(xs(Me,Ve))return}if(!y)await h.putLifecycle(P,Ve,L);z("lifecycle updated","update lifecycle")}),await ro(g,`r2.dev URL on ${P}`,async()=>{let Ve=u.publicDevUrl===!0;if(!he){if(Ve)z("r2.dev URL enabled","enable r2.dev URL");return}if((await h.getManagedDomain(P,L))?.enabled===Ve)return;if(!y)await h.setManagedDomain(P,Ve,L);z(Ve?"r2.dev URL enabled":"r2.dev URL disabled",Ve?"enable r2.dev URL":"disable r2.dev URL")});let Ct=[];if(fe.length>0&&he)try{Ct=await h.listCustomDomains(P,L)}catch(Ve){if(Ve instanceof An)throw Ve;v.push(`R2: could not list custom domains on ${P}: ${Kc(Ve)}`)}let It=new Map;for(let{domain:Ve,minTLS:Me}of fe){let We=g.claimed.get(Ve);if(We&&We!==P){v.push(`R2: ${Ve} is declared on both ${We} and ${P}; leaving it on ${We}.`);continue}g.claimed.set(Ve,P);let j=Ct.find((G)=>G.domain.toLowerCase()===Ve),ht=Me??"1.2";if(j&&j.enabled&&(j.minTLS??"1.0")===ht){if(R.domains.push({domain:Ve,status:jc(j)}),j.zoneId)It.set(Ve,j.zoneId);continue}await ro(g,`custom domain ${Ve} on ${P}`,async()=>{if(j){if(!y)await h.updateCustomDomain(P,j.domain,{enabled:!0,minTLS:ht},L);if(z(`custom domain ${Ve} updated`,`update custom domain ${Ve}`),R.domains.push({domain:Ve,status:jc({...j,enabled:!0})}),j.zoneId)It.set(Ve,j.zoneId);return}let G=await g.cloudflare.zoneIdFor(Ve);if(It.set(Ve,G),!y)await h.ensureCustomDomain(P,{domain:Ve,zoneId:G,minTLS:ht},L,Ct);z(`custom domain ${Ve} attached`,`attach custom domain ${Ve}`),R.domains.push({domain:Ve,status:y?"not attached":"pending"})},()=>R.domains.push({domain:Ve,status:"error"}))}if(u.cache&&fe.length>0)await Ch(u,fe.map((Ve)=>Ve.domain).filter((Ve)=>g.claimed.get(Ve)===P),It,g,z)}async function Ch(u,g,h,y,R){let v=op(u.cache);if(!v||g.length===0)return;let P=new Map;for(let L of g){let z=h.get(L);if(!z)try{z=await y.cloudflare.zoneIdFor(L)}catch(he){y.warnings.push(`R2: could not resolve the zone for ${L}, cache rule skipped: ${Kc(he)}`);continue}P.set(z,[...P.get(z)??[],L])}for(let L of P.values()){let z={action:"set_cache_settings",description:`${Kt} ${Yg}`,expression:`(${zt(L)})`,enabled:!0,action_parameters:v};await ro(y,`cache rule for ${L.join(", ")}`,async()=>{let he=await y.cloudflare.getPhaseRules(L[0],"http_request_cache_settings");if(sp(he,z))return;if(!y.dryRun){let fe=await y.cloudflare.putManagedPhaseRules(L[0],"http_request_cache_settings",[z]);if(!fe.success)throw Error(fe.message||"cache rule write failed")}R(`cache rule updated for ${L.join(", ")}`,`update cache rule for ${L.join(", ")}`)})}}function op(u){if(u.edgeTtl===void 0&&u.browserTtl===void 0)return null;let g={cache:!0};if(u.edgeTtl!==void 0)g.edge_ttl={mode:"override_origin",default:u.edgeTtl};if(u.browserTtl!==void 0)g.browser_ttl={mode:"override_origin",default:u.browserTtl};return g}function sp(u,g){let h=Wt(g.expression),y=Kn(g.expression),R=(L)=>(L.description||"").startsWith(Kt),v=(L)=>L.action===g.action&&L.description===g.description&&(L.enabled??!0)===(g.enabled??!0)&&Kn(L.expression)===y&&Fs(L.action_parameters)===Fs(g.action_parameters),P=!1;for(let L of u){if(!R(L))continue;let z=Wt(L.expression);if(!h.some((fe)=>z.includes(fe)))continue;if(v(L)&&h.every((fe)=>z.includes(fe))&&!P){P=!0;continue}return!1}return P}function cp(u){let g={id:u.id,enabled:u.enabled??!0,conditions:{prefix:u.prefix??""}};if(u.expireAfterDays!==void 0)g.deleteObjectsTransition={condition:{type:"Age",maxAge:Hc(u.expireAfterDays)}};else if(u.expireOn!==void 0)g.deleteObjectsTransition={condition:{type:"Date",date:u.expireOn}};if(u.abortMultipartUploadsAfterDays!==void 0)g.abortMultipartUploadsTransition={condition:{type:"Age",maxAge:Hc(u.abortMultipartUploadsAfterDays)}};if(u.infrequentAccessAfterDays!==void 0)g.storageClassTransitions=[{storageClass:"InfrequentAccess",condition:{type:"Age",maxAge:Hc(u.infrequentAccessAfterDays)}}];return g}function Hc(u){return Math.round(u*86400)}function Sh(u){let g=new Set,h=[];for(let y of u??[]){let R=typeof y==="string"?{domain:y}:y,v=R.domain?.trim().replace(/\.$/,"").toLowerCase();if(!v||g.has(v))continue;g.add(v),h.push({domain:v,minTLS:R.minTLS})}return h}function jc(u){if(!u.enabled)return"disabled";let g=u.status?.ownership,h=u.status?.ssl;if(g==="active"&&h==="active")return"active";for(let y of[g,h])if(y==="error"||y==="blocked"||y==="deactivated")return y;return"pending"}async function ro(u,g,h,y){try{await h()}catch(R){if(R instanceof An)throw R;u.warnings.push(`R2: ${g} failed: ${Kc(R)}`),y?.()}}function Kc(u){return u instanceof Error?u.message:String(u)}function Fs(u){if(Array.isArray(u))return`[${u.map(Fs).join(",")}]`;if(u&&typeof u==="object")return`{${Object.entries(u).filter(([,h])=>h!==void 0).sort(([h],[y])=>h.localeCompare(y)).map(([h,y])=>`${JSON.stringify(h)}:${Fs(y)}`).join(",")}}`;return JSON.stringify(u)}import{basename as Dh,extname as kh}from"node:path";import{createHash as Rh}from"node:crypto";var bh="https://api.cloudflare.com/client/v4",xn="TS_CLOUD_CONTENT_HASH",no="2025-09-01",Zc="application/javascript+module",Ah=10007,Ph=[1e4,9109];class li extends Error{status;errors;constructor(u,g,h=[]){super(u);this.name="WorkersApiError",this.status=g,this.errors=h}hasCode(u){return this.errors.some((g)=>g.code===u)}}class Ms extends li{permission;constructor(u,g,h,y=[]){super(`The Cloudflare API token is missing the "${u}" permission (${g}). Edit the token in the Cloudflare dashboard (My Profile, API Tokens), add it, then re-run the deploy.`,h,y);this.name="WorkersPermissionError",this.permission=u}}class Bs{name="cloudflare-workers";apiToken;accountId;fetchImpl;constructor(u){if(!u.apiToken)throw Error("Cloudflare Workers needs an API token");if(!u.accountId)throw Error("Cloudflare Workers needs an account id");this.apiToken=u.apiToken,this.accountId=u.accountId,this.fetchImpl=u.fetch??((g,h)=>fetch(g,h))}async request(u,g,h){let y={Authorization:`Bearer ${this.apiToken}`},R;if(h instanceof FormData)R=h;else if(h!==void 0)y["Content-Type"]="application/json",R=JSON.stringify(h);let v=await this.fetchImpl(`${bh}/accounts/${this.accountId}/workers${g}`,{method:u,headers:y,body:R}),P=await v.text(),L;try{L=JSON.parse(P)}catch{throw new li(`Cloudflare Workers API returned ${v.status} with a non-JSON body: ${P.slice(0,200)}`,v.status)}if(!L.success){let z=L.errors??[],he=z.map((fe)=>`${fe.code}: ${fe.message}`).join(", ");if($h(v.status,z))throw new Ms(Ih(g),`${u} ${g} -> ${v.status}${he?`, ${he}`:""}`,v.status,z);throw new li(`Cloudflare Workers API error (${v.status}) on ${u} ${g}: ${he||P.slice(0,200)}`,v.status,z)}return L.result}scriptPath(u){return`/scripts/${encodeURIComponent(u)}`}async getSettings(u){try{return await this.request("GET",`${this.scriptPath(u)}/settings`)}catch(g){if(g instanceof Ms)throw g;if(g instanceof li&&(g.hasCode(Ah)||g.status===404))return null;throw g}}async getScript(u){return this.getSettings(u)}async uploadModuleScript(u,g){return this.request("PUT",this.scriptPath(u),up(g))}async ensureModuleScript(u,g){let h=io(g),y=await this.getSettings(u);if(y&&Zs(y,g,h))return{action:"unchanged",hash:h};return await this.uploadModuleScript(u,dp(g,h)),{action:y?"updated":"created",hash:h}}async listCustomDomains(u={}){let g=new URLSearchParams;if(u.service)g.set("service",u.service);if(u.hostname)g.set("hostname",u.hostname);if(u.zoneId)g.set("zone_id",u.zoneId);let h=g.toString(),y=h?`?${h}`:"";return await this.request("GET",`/domains${y}`)??[]}async attachCustomDomain(u,g){let h={hostname:u,service:g.service,environment:g.environment??"production"};if(g.zoneId)h.zone_id=g.zoneId;return this.request("PUT","/domains",h)}async detachCustomDomain(u){await this.request("DELETE",`/domains/${encodeURIComponent(u)}`)}async ensureCustomDomain(u,g,h){let R=(h??await this.listCustomDomains({hostname:u})).find((P)=>P.hostname.toLowerCase()===u.toLowerCase());if(R&&R.service===g.service)return{action:"unchanged",domain:R};if(R)throw Error(`${u} is attached to the Worker '${R.service}'. Detach it there first (Workers & Pages, ${R.service}, Settings, Domains & Routes); ts-cloud does not move it.`);let v=await this.attachCustomDomain(u,g);return{action:"attached",domain:{...v,hostname:v?.hostname||u}}}}function $h(u,g){if(g.some((h)=>Ph.includes(h.code)))return!0;return(u===401||u===403)&&g.length===0}function Ih(u){if(u.startsWith("/domains"))return"Workers Routes: Edit (zone, for Workers custom domains) and Workers Scripts: Edit (account)";return"Workers Scripts: Edit (account)"}function up(u){if(!u.modules.some((y)=>y.name===u.mainModule))throw Error(`Worker main module '${u.mainModule}' is not one of the uploaded modules`);let g={main_module:u.mainModule,bindings:u.bindings??[],compatibility_date:u.compatibilityDate??no,compatibility_flags:u.compatibilityFlags??[],keep_bindings:["secret_text"]},h=new FormData;h.append("metadata",JSON.stringify(g));for(let y of u.modules)h.append(y.name,new Blob([y.content],{type:y.type}),y.name);return h}function io(u){let g={mainModule:u.mainModule,modules:[...u.modules].sort((h,y)=>h.name.localeCompare(y.name)).map((h)=>({name:h.name,type:h.type,sha256:lp(h.content)})),bindings:[...u.bindings??[]].filter((h)=>h.name!==xn).sort((h,y)=>h.name.localeCompare(y.name)),compatibilityDate:u.compatibilityDate??no,compatibilityFlags:[...u.compatibilityFlags??[]].sort()};return lp(qc(g))}function dp(u,g=io(u)){return{...u,bindings:[...(u.bindings??[]).filter((h)=>h.name!==xn),{type:"plain_text",name:xn,text:g}]}}function Zs(u,g,h){let y=u.bindings??[],R=y.find((v)=>v.name===xn&&v.type==="plain_text");if(!R||R.text!==h)return!1;return(g.bindings??[]).every((v)=>{let P=y.find((z)=>z.name===v.name);if(!P||P.type!==v.type)return!1;let L=v.type==="r2_bucket"?"bucket_name":v.type==="plain_text"?"text":void 0;return!L||P[L]===v[L]})}function lp(u){return Rh("sha256").update(u).digest("hex")}function qc(u){if(Array.isArray(u))return`[${u.map(qc).join(",")}]`;if(u&&typeof u==="object")return`{${Object.entries(u).filter(([,h])=>h!==void 0).sort(([h],[y])=>h.localeCompare(y)).map(([h,y])=>`${JSON.stringify(h)}:${qc(y)}`).join(",")}}`;return JSON.stringify(u)}async function Jc(u){if(!await Bun.file(u).exists())throw Error(`Worker entry not found: ${u}`);let g;try{g=await Bun.build({entrypoints:[u],target:"browser",format:"esm",minify:!0,external:["cloudflare:*"]})}catch(R){throw Error(`Bundling Worker ${u} failed: ${Eh(R)}`)}if(!g.success)throw Error(`Bundling Worker ${u} failed: ${g.logs.map((R)=>String(R.message??R)).join("; ")}`);if(g.outputs.length!==1)throw Error(`Bundling Worker ${u} produced ${g.outputs.length} files (${g.outputs.map((R)=>R.path).join(", ")}); a Worker is uploaded as a single module, so remove the dynamic imports or asset imports that split it.`);let h=g.outputs[0];if(h.kind!=="entry-point")throw Error(`Bundling Worker ${u} produced a ${h.kind} instead of an entry module`);let y=await h.text();return{name:`${Dh(u,kh(u))}.js`,content:y,type:Zc,size:new TextEncoder().encode(y).byteLength}}function Eh(u){if(u instanceof AggregateError&&u.errors.length>0)return u.errors.map((g)=>g instanceof Error?g.message:String(g?.message??g)).join("; ");return u instanceof Error?u.message:String(u)}import{isAbsolute as Oh,resolve as Nh}from"node:path";var xh="https://api.cloudflare.com/client/v4",Lh=/^[a-z0-9][a-z0-9_-]{0,62}$/;async function _h(u,g={}){let h=g.log??(()=>{}),y={workers:[],warnings:[]},R=Object.entries(u.infrastructure?.workers??u.workers??{});if(R.length===0)return h("Workers: none declared, skipping."),y;if(!g.apiToken||!g.accountId){let L=[!g.apiToken&&"CLOUDFLARE_API_TOKEN",!g.accountId&&"CLOUDFLARE_ACCOUNT_ID"].filter(Boolean).join(" and "),z=`Workers: ${R.length} Worker(s) declared but ${L} is not set, skipping.`;return h(z),y.warnings.push(z),y}let v=u.infrastructure?.r2??u.r2,P={workers:new Bs({apiToken:g.apiToken,accountId:g.accountId,fetch:g.fetch}),r2:new ai({apiToken:g.apiToken,accountId:g.accountId,fetch:g.fetch}),cloudflare:new H(g.apiToken,{zoneId:g.zoneId,accountId:g.accountId}),apiToken:g.apiToken,fetch:g.fetch??((L,z)=>fetch(L,z)),projectRoot:g.projectRoot??process.cwd(),dryRun:g.dryRun===!0,warnings:y.warnings,log:h,r2ConfigDomains:Hh(v),r2Buckets:v,claimed:new Map};for(let[L,z]of R){let he=z?.name;if(!he||!Lh.test(he)){y.warnings.push(`Workers: '${L}' has an invalid name '${he??""}' (1-63 chars: lowercase letters, digits, '-' and '_'), skipping.`);continue}if(!z.entry){y.warnings.push(`Workers: ${he} has no entry, skipping.`);continue}h(`Workers: ${P.dryRun?"checking":"reconciling"} ${he}...`);let fe={name:he,changes:[],domains:[]};y.workers.push(fe),await Mh(z,fe,P);for(let Ct of fe.changes)h(`Workers: ${he}: ${Ct}`)}return y}async function Mh(u,g,h){let y=u.name,R=Oh(u.entry)?u.entry:Nh(h.projectRoot,u.entry),v;try{v=await Jc(R)}catch(L){throw Error(`Worker ${y}: ${di(L)}`)}g.changes.push(`bundled ${Gh(v.size)}`);let P={mainModule:v.name,modules:[{name:v.name,content:v.content,type:v.type}],bindings:pp(u,h),compatibilityDate:u.compatibilityDate??no,compatibilityFlags:u.compatibilityFlags??[]};if(h.dryRun){let L=await h.workers.getSettings(y);g.changes.push(L&&Zs(L,P,io(P))?"unchanged":"would upload")}else{let{action:L}=await h.workers.ensureModuleScript(y,P);g.changes.push(L==="unchanged"?"unchanged":"uploaded")}for(let L of Uh(u.customDomains))await Bh(y,L,g,h)}async function Bh(u,g,h,y){let R=(Ve)=>{h.domains.push({domain:g,status:Ve})},v=(Ve)=>{y.warnings.push(`Workers: ${Ve}`),R("conflict")},P=y.claimed.get(g);if(P&&P!==u){v(`${g} is declared on both ${P} and ${u}; leaving it on ${P}.`);return}y.claimed.set(g,u);let L=y.r2ConfigDomains.get(g);if(L){v(`${g} is also declared as a custom domain of the R2 bucket '${L}' (r2.buckets). A hostname serves either a bucket or a Worker. Remove it from the bucket's customDomains and detach it in the dashboard (R2, ${L}, Settings, Custom Domains) first; to serve the bucket through the Worker, bind it with bindings.r2Buckets instead.`);return}let z=await Wh(y);if(z===null){R("error");return}let he=z.find((Ve)=>Ve.hostname.toLowerCase()===g);if(he?.service===u){R("active");return}if(he){v(`${g} is attached to the Worker '${he.service}'. Detach it there first (Workers & Pages, ${he.service}, Settings, Domains & Routes); it is not moved automatically.`);return}let fe=(await Vh(y))?.get(g);if(fe){v(`${g} is attached to the R2 bucket '${fe}' as a custom domain. Detach it first (R2, ${fe}, Settings, Custom Domains, then re-run the deploy); it is not detached automatically. To serve the bucket through the Worker, bind it with bindings.r2Buckets.`);return}let Ct;try{Ct=await y.cloudflare.zoneIdFor(g)}catch(Ve){y.warnings.push(`Workers: could not resolve the zone for ${g}, not attached: ${di(Ve)}`),R("error");return}let It=await zh(y,Ct,g);if(It.length>0){let Ve=It.map((Me)=>`${Me.type} ${Me.content}`).join(", ");v(`${g} already has a DNS record (${Ve}). A Worker custom domain creates its own record, so Cloudflare will not attach over it. Delete the record first (DNS, Records), then re-run the deploy; it is not deleted automatically.`);return}if(y.dryRun){h.changes.push(`would attach custom domain ${g}`),R("not attached");return}try{await y.workers.ensureCustomDomain(g,{service:u,zoneId:Ct},z),h.changes.push(`custom domain ${g} attached`),z.push({id:"",hostname:g,service:u,zone_id:Ct}),R("pending")}catch(Ve){y.warnings.push(`Workers: custom domain ${g} on ${u} failed: ${di(Ve)}`),R("error")}}async function Wh(u){if(u.attached!==void 0)return u.attached;try{u.attached=await u.workers.listCustomDomains()}catch(g){u.warnings.push(`Workers: could not list Worker custom domains, none attached: ${di(g)}`),u.attached=null}return u.attached}async function Vh(u){if(u.r2AccountDomains!==void 0)return u.r2AccountDomains;let g=new Map;try{let h=(await u.r2.listBuckets()).map((y)=>({name:y.name}));for(let y of Object.values(u.r2Buckets?.buckets??{}))if(y.jurisdiction&&y.jurisdiction!=="default")h.push({name:y.name,jurisdiction:y.jurisdiction});for(let y of h){let R=await u.r2.listCustomDomains(y.name,{jurisdiction:y.jurisdiction}).catch(()=>[]);for(let v of R)g.set(v.domain.toLowerCase(),y.name)}u.r2AccountDomains=g}catch(h){u.log(`Workers: could not check R2 custom domains (${di(h)}); relying on the DNS check.`),u.r2AccountDomains=null}return u.r2AccountDomains}async function zh(u,g,h){try{let y=await u.fetch(`${xh}/zones/${g}/dns_records?name=${encodeURIComponent(h)}&per_page=100`,{method:"GET",headers:{Authorization:`Bearer ${u.apiToken}`}}),R=await y.json();if(!R?.success)throw Error(`HTTP ${y.status}`);return(R.result??[]).filter((v)=>v.name?.toLowerCase()===h).map((v)=>({type:v.type??"?",content:v.content??""}))}catch(y){return u.log(`Workers: could not read DNS records for ${h} (${di(y)}); attaching anyway.`),[]}}function pp(u,g){let h=[],y=new Set,R=(P)=>{if(P===xn)return g.warnings.push(`Workers: ${u.name}: binding name ${xn} is reserved for ts-cloud, ignored.`),!1;if(y.has(P))return g.warnings.push(`Workers: ${u.name}: binding ${P} is declared twice; the first one wins.`),!1;return y.add(P),!0},v=new Map;for(let P of Object.values(g.r2Buckets?.buckets??{}))if(P.jurisdiction&&P.jurisdiction!=="default")v.set(P.name,P.jurisdiction);for(let[P,L]of Object.entries(u.bindings?.r2Buckets??{})){if(!R(P))continue;let z=v.get(L);h.push(z?{type:"r2_bucket",name:P,bucket_name:L,jurisdiction:z}:{type:"r2_bucket",name:P,bucket_name:L})}for(let[P,L]of Object.entries(u.bindings?.vars??{}))if(R(P))h.push({type:"plain_text",name:P,text:String(L)});return h}function Hh(u){let g=new Map;for(let h of Object.values(u?.buckets??{}))for(let y of h?.customDomains??[]){let R=mp(typeof y==="string"?y:y.domain);if(R)g.set(R,h.name)}return g}function Uh(u){return[...new Set((u??[]).map(mp).filter(Boolean))]}function mp(u){return(u??"").trim().replace(/\.$/,"").toLowerCase()}function Gh(u){if(u<1024)return`${u} B`;if(u<1048576)return`${(u/1024).toFixed(1)} KB`;return`${(u/1024/1024).toFixed(1)} MB`}function di(u){return u instanceof Error?u.message:String(u)}export{Pl as ABTestManager,Se as ACMClient,xr as ACMDnsValidator,ud as ACME_DIRECTORIES,Oe as AI,gu as API_IDEMPOTENCY_TTL_MS,lu as API_TOKEN_DEFAULT_TTL_MS,uu as API_TOKEN_MAX_TTL_MS,ms as API_VERSION,be as AUTHORIZATION_CAPABILITIES,ou as AUTH_ACTION_TOKEN_TTL_MS,au as AUTH_MFA_CHALLENGE_TTL_MS,cu as AUTH_OIDC_TRANSACTION_TTL_MS,ot as AUTH_SESSION_ABSOLUTE_TTL_MS,su as AUTH_SESSION_IDLE_TTL_MS,vy as AWSAPIError,n as AWSClient,A as AWSCloudFormationClient,I as AWSCloudFrontClient,Tl as AWSConfigManager,XI as AWS_PSEUDO_PARAMETERS,_e as AWS_REGIONS,Lg as AcmeClient,sn as AlertEvaluator,Gi as AlertStore,Bo as AnomalyConfigStore,ml as ApiGateway,i as ApiServiceError,Tc as ApplicationAutoScalingClient,gn as Arn,_ as AssetHasher,Y as Auth,ds as AuthenticationStore,Ki as AutomationApiService,ls as AutomationIdentityStore,xa as AwsAuroraDataAdapter,Ma as AwsAuroraTransport,rc as AwsDatabaseBackupSource,$r as AwsDriver,Oa as AwsElastiCacheDataAdapter,Fa as AwsElastiCacheTransport,eh as AwsIamCapabilityScanner,ac as AwsInfrastructureBackupSource,Ba as AwsRdsDataAdapter,$a as AwsRdsTransport,ph as AwsRegionalDriver,dc as AwsSecretsManagerConfigurationBackend,hm as AwsSpendTransport,lc as AwsSsmConfigurationBackend,Ts as BackupCoordinator,El as BackupManager,ec as BackupStore,Pf as BatchProcessingManager,Gn as BedrockClient,Hn as BedrockRuntimeClient,Su as BitbucketSourceAdapter,Dl as BlueGreenManager,Sf as BounceComplaintHandler,lf as BuildOptimizationManager,Qu as BunDockerRuntime,Ag as BunDockerVolumeRuntime,hg as BunFilesystemArchiveRuntime,Ce as CDN,Xo as CHAIN_HEADER,Kt as CLOUDFLARE_MANAGED_RULE_PREFIX,dl as CLOUDFRONT_FAILOVER_STATUS_CODES,$C as COMMON_CROSS_ACCOUNT_ROLES,xn as CONTENT_HASH_BINDING,Je as CONTROL_PLANE_SCHEMA_VERSION,qo as Cache,rs as CanaryManager,af as CertificateManager,_A as CloudBlockVolumeDriver,so as CloudDriverFactory,nt as CloudError,xm as CloudFormationBuilder,A as CloudFormationClient,I as CloudFrontClient,wl as CloudTrailManager,we as CloudWatchLogsClient,pd as CloudflarePagesProvider,H as CloudflareProvider,qy as CommandHistory,ee as Communication,Zr as ComposeApplicationService,or as ComposeApplicationStore,Gt as ComprehendClient,a as Compute,Am as ComputeSpendTransport,Ko as ConfigurationError,gc as ConfigurationService,cc as ConfigurationStore,Un as ConnectClient,La as ContainerDataAdapter,Ol as ContainerRegistryManager,oc as ControlPlaneBackupSource,Ja as ControlPlaneCleanupDriver,Li as ControlPlaneStore,Po as CounterTracker,Ot as CredentialError,Km as CrossRegionReferenceManager,ly as DASHBOARD_ENTRY,uy as DASHBOARD_PORT_BASE,gy as DASHBOARD_PORT_SPAN,dy as DASHBOARD_STATE_DIR,oa as DEFAULT_ATTACK_MODE_HOURS,no as DEFAULT_COMPATIBILITY_DATE,Yd as DEFAULT_DDOS_THRESHOLDS,bm as DEFAULT_FAILOVER_STATUS_CODES,xd as DEFAULT_METER_MAPPINGS,Nd as DEFAULT_PRICE_BOOK,fn as DEFAULT_RECURSION_LIMITS,go as DEFAULT_RPX_CERTS_DIR,te as DEFAULT_SERVICE_LIMITS,rl as DEFAULT_STATE_DIR,kg as DEFAULT_STATIC_ASSET_EXTENSIONS,sy as DEFAULT_STORAGE_FAILOVER_STATUS_CODES,KA as DEFAULT_TELEMETRY_POLICY,em as DEFAULT_THRESHOLDS,kA as DEPLOYMENT_QUEUE_KINDS,Jo as DEPTH_HEADER,rn as DETECTABLE_SIGNALS,Lu as DIAGNOSTIC_PRESETS,Df as DLQMonitoringManager,W as DNS,Af as DNSSECManager,ys as DataServiceLifecycle,Na as DataServiceStore,ur as Database,sf as DatabaseUserManager,q as DebugLogger,iy as DependencyGraph,Z as Deployment,Ey as DeploymentError,vl as DisasterRecoveryManager,Xn as DnsProviderFactory,Ir as DockerDataTransport,Ta as DockerDiscoveryAdapter,Yr as DockerNamedVolumeDriver,sc as DockerVolumeBackupSource,c as DurableOperationQueue,Co as DurableQueueWorker,Ue as DynamoDBClient,qr as EC2Client,He as ECRClient,ut as ECSClient,Pr as EFSClient,bc as ELBv2Client,$A as ENFORCEMENT_ACTIONS,Qi as ENFORCEMENT_DESCRIPTIONS,O as ENFORCEMENT_SEVERITY,Dp as ENVIRONMENT_LABEL,Ou as EcsRuntimeAdapter,sa as EdgeRateLimiter,pt as ElastiCacheClient,f as Email,Ef as EmailAdvanced,If as EmailAnalyticsManager,zn as EmailClient,vf as EmailHandlers,Cf as EmailTemplateManager,Ua as EncryptedDataSecretStore,Ty as ErrorCodes,Rr as EventBridgeClient,lh as EventBridgeJobAdapter,uc as ExternalConfigurationBackend,Vo as FAILOVER_REPLICA_POLICY_SID,Rf as FIFOQueueManager,jh as FLY_MACHINES_API,cm as FOCUS_VERSION,Al as FileCache,tt as FileSystem,nc as FilesystemBackupSource,Ha as FleetService,Qa as FleetStore,Cs as FlyApiError,hp as FlyClient,e as Fn,Iu as GiteaSourceAdapter,Au as GithubSourceAdapter,yu as GitlabSourceAdapter,Wm as GlobalResourceManager,Ge as GoDaddyProvider,Rl as GuardDutyManager,Tt as HOST_SITES_DIR,Py as HashCache,Qf as HealthCheckManager,Ye as HealthCheckRunner,Hr as HetznerClient,Pe as HetznerDriver,Re as IAMClient,_c as IPV6_EXCLUDED_HOST_LABELS,df as ImageScanningManager,vp as InfrastructureGenerator,Id as InvalidOperationTransitionError,Bt as JobLoader,uh as JobProviderReconciler,Pa as JobService,ka as JobStore,wr as KendraClient,Ff as LARAVEL_SERVERLESS_BUILD_STEPS,T as LambdaClient,pf as LambdaConcurrencyManager,hf as LambdaDLQManager,mf as LambdaDestinationsManager,uf as LambdaLayersManager,_u as LambdaRuntimeAdapter,ff as LambdaVPCManager,gf as LambdaVersionsManager,On as LocalEncryptedConfigurationBackend,ic as LogicalDatabaseBackupSource,Nl as LogsManager,gS as MANAGED_NODE_VERSIONS,id as MANAGEMENT_DASHBOARD_SITE,Om as MANAGEMENT_DASHBOARD_SITE_PREFIX,as as MAX_CONTROL_HOURS,bd as MAX_CONTROL_PLANE_ERROR_BYTES,Wp as MAX_CONTROL_PLANE_JSON_BYTES,wo as METERS,LA as METER_KEYS,MA as MICRO_CENTS,tm as MIN_PROJECTION_CONFIDENCE,_g as MTA_STS_PORT,Wa as MaintenanceService,Ka as MaintenanceStore,ue as Messaging,tf as MetricsManager,rf as MigrationManager,Gm as MockCloudFormation,qm as MockDynamoDB,Vm as MockS3,jo as Monitoring,Ym as MultiAccountManager,zm as MultiRegionManager,Fy as MultiStepProgress,S as Network,Hf as NetworkSecurityManager,Vi as NotificationRouter,vm as ORIGIN_CONNECTION_ATTEMPTS,Tm as ORIGIN_CONNECTION_TIMEOUT,Cm as ORIGIN_GROUP_ALLOWED_METHODS,KI as ORIGIN_GROUP_ID_SUFFIX,Em as ORIGIN_GROUP_SELECTION_CRITERIA,Cc as OpenSearchClient,wt as OptimisticConcurrencyError,Zm as OrganizationManager,Hg as PAGES_MAX_FILE_BYTES,CS as PHP_DEFAULT_EXCLUDES,pS as PHP_LAYER_EXTENSIONS,Rp as PROJECT_LABEL,ft as PROXIABLE_RECORD_TYPES,D as ParameterStore,nf as PerformanceManager,le as Permissions,Ec as PersonalizeClient,rt as Phone,Tf as PhoneAdvanced,Nm as PhoneHandlers,Va as PlacementService,Ga as PlacementStore,Vn as PollyClient,Ae as PorkbunProvider,En as PreDeployScanner,bl as PreviewEnvironmentManager,Xr as PreviewEnvironmentService,Xe as PreviewEnvironmentStore,Cl as PreviewNotificationService,My as ProgressBar,kl as ProgressiveDeploymentManager,aa as ProtectionControlStore,ny as Pseudo,J as Queue,$i as QueueCancellationError,kf as QueueManagementManager,$I as QueuePresets,bo as QueueTimeoutError,Fn as R2ApiError,An as R2NotEnabledError,ai as R2Provider,np as R2_NOT_ENABLED_ERROR_CODE,Jl as RATE_LIMIT_KEY_SEPARATOR,ne as RDSClient,zy as RECOMMENDED_ACCOUNT_STRUCTURES,LC as RECOMMENDED_SCPS,Jf as RELEASE_QUEUE_KINDS,Hy as REPL,Vy as REPLCommandBuilder,Gy as REPLContext,Pp as ROLE_LABEL,ky as RateLimiter,MI as RealtimePresets,dm as RecordingSpendTransport,is as RecursionGuard,xt as Redirects,Jm as RegionPairManager,ja as RegionService,qa as RegionStore,et as Registry,Vt as RekognitionClient,_t as ReleaseService,ha as ReleaseStore,gh as RemoteBuildService,Bl as ReplicaManager,Gf as ResourceManagementManager,ae as RetryableOperationError,C as Route53Client,Ic as Route53DomainsClient,ie as Route53Provider,yf as Route53ResolverManager,Ll as Route53RoutingManager,ve as RuntimeOperationService,Ra as RuntimeStreamRegistry,tc as S3BackupDestinationAdapter,o as S3Client,V as S3Error,Eu as SECRET_PATTERNS,om as SENSITIVITY_THRESHOLDS,mt as SESClient,X as SMS,gt as SNSClient,fm as SPEND_CYCLE_SECONDS,jd as SPEND_GATE_SETTING,YA as SPEND_LEASE_SETTING,me as SQSClient,ke as SSH_BOOTSTRAP_VERSION,hi as SSH_PREFLIGHT_SCRIPT,Be as SSMClient,Sm as STATE_DIR_ENV_VAR,wi as STATIC_SITE_ZONE_SETTINGS,ul as STORAGE_FAILOVER_METADATA_KEY,Te as STSClient,qn as SchedulerClient,gr as Search,vn as SecretFindingScanner,Yi as Secrets,xl as SecretsManager,re as SecretsManagerClient,of as SecretsRotationManager,E as Security,fr as SecurityHubManager,Cn as SecurityPostureStore,Lt as SecurityScannerRunner,cf as SecurityScanningManager,bf as SenderReputationManager,dh as ServerCronJobAdapter,_a as ServerDataAdapter,To as ServerPathVolumeDriver,_l as ServiceMeshManager,pl as Sftp,Oo as SignalSource,wf as SmsAdvanced,jt as SmsClient,Bm as SmsHandlers,Dc as SmsVoiceClient,Aa as SourceConnectionStore,yr as SourceProviderError,zd as SpendCapError,nn as SpendGate,pm as SpendLoopLease,Fo as SpendNotificationRouter,mm as SpendRunner,cr as SpendService,Fi as SpendStore,Uy as Spinner,Gr as SshDriver,Rn as SshFleetDriver,Xm as StackDependencyManager,JI as StacksIntegration,Uf as StaticSiteManager,xe as Storage,zl as StorageAdvancedManager,jn as SupportClient,hr as SyntheticsManager,Hu as SystemFleetSshTransport,bt as SystemSshTransport,wa as SystemdDiscoveryAdapter,Yo as TRACE_HEADER,Qy as TaskList,Pt as TelemetryStore,al as TemplateBuilder,yl as TemplateCache,qt as TextractClient,Qn as TranscribeClient,Tr as TranslateClient,hh as TransportDisasterRecoveryDriver,fh as TransportPlatformMaintenanceDriver,Ss as TransportRemoteBuildDriver,Ea as TrivyImageScanner,fa as TsCloudApiError,pu as TsCloudClient,XA as URGENT_SPEND_EVENTS,rm as USER_VISIBLE_ACTIONS,za as UnavailableRegionalDriver,ye as UnifiedDnsValidator,yo as UnsupportedSchemaVersionError,Mm as ValidationError,Dr as VoiceClient,vo as VolumeService,sr as VolumeStore,Zc as WORKER_MODULE_TYPE,li as WorkersApiError,Ms as WorkersPermissionError,Bs as WorkersProvider,cy as Workflow,ef as XRayManager,rS as abTestManager,mu as activateImmutableRelease,Tg as addDns01ChallengeRecord,Pn as addSiteToCloudConfig,Mt as ageSeconds,_d as aggregateDeltas,jp as allocateSitePorts,km as amazonLinuxImageId,ay as amazonLinuxImageParameter,jI as analyzeStackDiff,Hi as anomalyOptionsForSignal,ca as applyControlsToDdos,tu as applyControlsToRateLimits,Vs as applyDeclaredZoneSettings,gi as applyHetznerVolumes,cn as applyMitigationFactor,uA as applyPlan,Ks as applyZoneMigration,$l as artifactKey,ru as assertComputeResidency,kt as assertOriginGroupMethods,us as assertReleaseStrategy,zA as assertSpendAllows,hA as attachConflicts,AA as attachIsViable,fA as attachPreconditions,Du as attachProvenanceToRelease,va as attachSbomToRelease,wu as attachVulnerabilitySummary,Kf as authEncryptionKeyFile,x as authorizeOrganization,ah as authorizeRuntimePath,gC as autocomplete,Jy as awsConfigManager,mg as backupCredentialStatus,Ky as backupManager,$b as batch,RE as batchProcessingManager,pa as beginOidcAuthorization,eS as blueGreenManager,bE as bounceComplaintHandler,Rt as budgetWindow,Ac as buildAndPushServerlessImage,kE as buildBunRuntimeLayerZip,EA as buildCertificatePackScript,IA as buildCertificateStateScript,vA as buildCertificateUnpackScript,fl as buildCloudFormationTemplate,Yc as buildCloudInitFirstBoot,Td as buildComposeLogsCommand,_I as buildComposeRuntimeCommand,LI as buildComposeScaleCommand,wd as buildComposeShellCommand,ti as buildComputeStorageInstallScript,Mr as buildComputeStorageSiteScript,Gp as buildDrainSourceScript,rA as buildDrainedSiteScanScript,gl as buildFailoverReplicaPolicyStatement,Cr as buildFunctionEnv,Hp as buildHealthGateScript,ni as buildHostCleanupDeployScript,to as buildHostCleanupInstallScript,ri as buildHostCleanupScript,Oi as buildHostSitePortsScript,Ji as buildMailEnv,co as buildManagementDashboardArtifact,JS as buildMediaCdnPlan,Og as buildMtaStsPolicy,Fh as buildMtaStsServer,PE as buildNodeRuntimeLayerZip,gE as buildOptimizationManager,ll as buildOriginGroup,un as buildOriginGroups,Nc as buildOriginGuardRule,_p as buildPauseWorkersScript,OE as buildPhpRuntimeLayerZip,Pm as buildReplicationConfiguration,Dm as buildReplicationRole,Fp as buildRestoreScript,B as buildRpxConfig,Ne as buildRpxFragmentRefreshScript,pA as buildSetHostnameScript,si as buildSiteDeployScript,Mp as buildSnapshotScript,Vp as buildSourceStateScript,ci as buildSshArgs,mi as buildSshBootstrapScript,kc as buildStaticSiteCacheRules,oi as buildStaticSiteDeployScript,Up as buildTargetStateScript,up as buildUploadForm,Lp as buildWorkersStateScript,Jc as bundleWorker,ku as bytes,op as cacheRuleParameters,tS as canaryManager,Dn as canonicalJson,$t as capabilities,br as capacity,jb as categorizeChanges,dE as certificateManager,CA as certificatesMatch,Rb as checkIAMPermissions,_f as checkInvocation,Pb as checkServiceQuotas,Ny as chunk,gR as cleanupDns01Challenge,PS as clearSigningKeyCache,Sa as cloneSourceBinding,By as cloudConfigSchema,ap as cloudDrivers,Xy as cloudTrailManager,ep as collectAssets,ra as collectPhpAppEntries,Ng as collectServerDnsDomains,Jp as completeComposeVolumeDeletion,ma as completeOidcAuthorization,fb as composePresets,Io as composeProjectName,Fl as composeServerlessAppTemplate,ey as compositeSpendTransport,Ht as compressBackup,LS as config,Pc as configOrigins,Fu as connectionGuidance,cS as containerRegistryManager,DA as controlPlaneDatabaseFile,yd as controlPlaneMigrations,nb as createApiBackendPreset,Ca as createApiV1Handler,qS as createAsgBuildDriver,fg as createBackupQueueHandlers,bS as createCliHandler,F as createCloudDriver,td as createCloudFrontPolicy,Eb as createCredentialProvider,pb as createDashboardSite,cb as createDataPipelinePreset,Uu as createDataServiceQueueHandlers,Rd as createDeploymentQueueHandlers,N as createDnsProvider,VS as createEcsBuildDriver,Kd as createEnforcementHandlers,Fm as createError,hl as createExistingStaticFullStackPreset,Gu as createFleetQueueHandlers,rb as createFullStackAppPreset,Xs as createGoDaddyValidator,xE as createHandlers,SS as createHttpHandler,sb as createJamstackPreset,Mu as createJobQueueHandlers,ub as createLaravelPreset,db as createMLApiPreset,Ju as createMaintenanceQueueHandlers,jS as createMediaAccessToken,ob as createMicroservicesPreset,eC as createMockAWS,ZI as createNodeJsServerPreset,eb as createNodeJsServerlessPreset,Ls as createObjectStorageClient,Js as createPorkbunValidator,hb as createPreset,na as createPresignedUrl,vS as createPresignedUrlAsync,IS as createQueueHandler,ab as createRealtimeAppPreset,qu as createRegionQueueHandlers,Ru as createReleaseProvenance,hu as createReleaseQueueHandlers,HS as createRemoteBuildQueueHandlers,Ys as createRoute53Validator,oh as createRuntimeAdapters,Cy as createS3Client,GS as createServerBuildDriver,gb as createServerlessLaravelPreset,tb as createServerlessNodePreset,Pg as createSmsInfrastructure,ct as createSourceAdapter,YI as createStaticSitePreset,lb as createTraditionalWebAppPreset,Dd as createVolumeQueueHandlers,ib as createWordPressPreset,it as createZip,IC as crossRegionReferenceManager,_n as dashboardActions,ao as dashboardCredentialsFile,wn as dataServiceCapabilities,aE as databaseUserManager,iu as decodeBase32,Fe as decompressBackup,wh as decryptBackup,da as defaultConfig,Hm as defaultLocalConfig,Yl as defaultRateLimitRules,Br as delegateZone,Hs as delegateZoneFromConfig,lg as deleteFailoverReplicaBuckets,fc as deleteStaticSite,od as deployAllComputeSites,Ya as deployServerlessApp,ug as deploySite,lo as deploySiteRelease,Ps as deployStaticSite,hc as deployStaticSiteFull,Ln as deployStaticSiteWithExternalDns,$n as deployStaticSiteWithExternalDnsFull,Jh as deployToFly,ol as deploymentCoexistenceError,py as deriveManagementDashboardPort,Gs as describeDelegation,eu as describePosture,qs as describeZoneSettings,ch as desiredJobProviderState,sm as detectAnomalies,Im as detectDeploymentTargets,Bc as detectDnsProvider,Gd as detectLatestAnomaly,Tb as detectMisconfigurations,Kl as detectServiceRegion,Ed as diffCompose,Gb as diffTemplates,ya as discoverGitRefs,ga as discoverOidcProvider,Nu as discoverRuntimeInventory,wE as dlqMonitoringManager,xc as dnsProviders,SE as dnssecManager,nh as dockerWorkloads,Is as documentDigest,jc as domainStatus,Wy as drManager,je as driverStatePath,Bu as ecsWorkloads,ir as effectiveCapabilities,CE as emailAnalyticsManager,vE as emailTemplateManager,cs as encodeBase32,Th as encryptBackup,Pu as ensureDefaultSecurityPolicies,ag as ensureFailoverReplicaBuckets,Ei as ensureFirewall,Ri as ensureManagementDashboard,vi as ensureServer,Ci as ensureSshKey,oe as escapeSecLang,$d as evaluateBudget,yi as evaluatePreflight,Mo as evaluateTelemetryAlertRules,$u as eventBridgeScheduleInput,yS as eventToRequest,VA as ewma,Cd as exportCompose,js as exportRoute53Zone,Lm as extendPreset,TE as fifoQueueManager,Lb as findChangedFiles,Yp as findMapping,Xp as findPriceEntry,Zh as flyDeployOptions,Qc as flyIpType,Cp as flyMachineConfig,QC as formatAccountStructure,yA as formatAttachPlan,iC as formatBytes,on as formatCents,zI as formatDiff,iA as formatDrainedSiteRefusal,sC as formatDuration,mC as formatFlagSuggestions,AC as formatHistory,yC as formatHistoryStats,cA as formatInventory,aC as formatKeyValue,oC as formatList,lA as formatPlan,Ii as formatPreflightFindings,nC as formatProgressBar,jy as formatRegion,BC as formatRegionList,Zf as formatScanResults,cC as formatSuggestion,tC as formatTable,tn as formatTimeToExhaustion,rC as formatTree,yy as fromEC2Metadata,Sy as fromECSMetadata,hy as fromEnvironment,Ay as fromSharedCredentials,Iy as fromWebIdentity,Hl as functionFingerprint,fo as gatewayHostnames,Ql as generateAppImageDockerfile,tE as generateApprovalConfig,Nf as generateBootstrap,_y as generateCleanupWorkflow,Ly as generateCostReportWorkflow,FC as generateCrossAccountRoleCF,vu as generateCycloneDxSbom,YC as generateDeploymentConfig,zC as generateDeploymentPipeline,HC as generateDeploymentWorkflow,mc as generateExternalDnsStaticSiteTemplate,pR as generateHttpsServerCode,Tu as generateImageSbom,dR as generateLetsEncryptUserData,t as generateLogicalId,XC as generateManualPipeline,jC as generateMatrixWorkflow,ZC as generateMultiEnvConfig,KC as generateMultiEnvPipeline,GC as generateMultiEnvWorkflow,VC as generatePRPreviewWorkflow,rE as generateParallelConfig,Mf as generatePhpFpmConfig,Bf as generatePhpLayerDockerfile,WC as generatePreviewPipeline,Oy as generatePreviewWorkflow,r as generateResourceName,eE as generateScheduledConfig,JC as generateScheduledPipeline,qC as generateScheduledWorkflow,Ds as generateStaticSiteTemplate,M as generateUbuntuAppCloudInit,$m as getAccountId,vC as getAllRegions,PC as getClosestRegion,fC as getCommandUsage,PA as getComposeTemplate,qf as getConfig,lC as getContextualHelp,es as getCredentials,zb as getDeploymentStrategy,Kb as getDiffStats,Vb as getDiffSummary,wy as getErrorDetails,Il as getLocalConfig,Yb as getLocalCredentials,Xb as getLocalEndpoint,Zb as getLocalEnvVars,kb as getQuotaUsageSummary,MC as getRecommendedStructure,ts as getRegion,xC as getRegionStats,wC as getRegionsByCompliance,TC as getRegionsByLocation,RC as getRegionsByPricingTier,Ry as getRequiredPermissions,kS as getSigningKeyCacheSize,Dg as getSmsInfrastructureStatus,FI as getTimestamp,ia as globMatches,uo as globToRegex,bC as globalResourceManager,Ui as governingLimitCents,cg as grantFailoverReplicaAccess,Yy as guardDutyManager,Uo as handleSpendRequest,mo as hasAutoWwwVariant,pr as hasManagementDashboardSite,Ad as hasProxyUpstream,Bb as hashBuffer,xb as hashDirectory,Um as hashFile,Ob as hashManifest,Qm as hashString,LE as healthCheckManager,Yn as hostAcceptsIpv6,zt as hostCondition,la as hotp,en as hourBucket,GA as hourBucketsBetween,uE as imageScanningManager,Es as infraEnvFromOutputs,Vl as inspectInvocation,hS as installRecursionFetch,Ns as invalidateCache,Of as invocationContext,oy as isArmInstanceType,dC as isLikelyTypo,_r as isLocalDatabase,Jb as isLocalDevelopment,mr as isManagementDashboardSiteName,kr as isNameserverRegistrar,NS as isNodeCryptoAvailable,Hd as isOperationAllowed,$o as isQuietHours,Go as isS3RestEndpoint,Pi as isSafePattern,il as isStateDirConfigured,sl as isStatePath,an as isValidCidr,DC as isValidRegion,Mi as isValidTimeZone,BS as isWebCryptoAvailable,Nr as isZoneHost,Tn as jobProviderCapability,_s as keyMatchesFilters,fE as lambdaConcurrencyManager,yE as lambdaDLQManager,hE as lambdaDestinationsManager,pE as lambdaLayersManager,AE as lambdaVPCManager,mE as lambdaVersionsManager,xu as lambdaWorkloads,ql as laravelServerlessEnvDefaults,Jr as listComposeTemplates,ps as listSourceReferences,nu as loadCloudConfig,dr as loadTelemetryPolicy,iS as logsManager,Vd as lookbackHoursForSignal,ry as mailEnabled,Ze as mailFirewallPorts,ln as mailWebmailSites,mh as maintenanceWindowOpen,Vf as makeAWSRequest,wS as makeAWSRequestAsync,TS as makeAWSRequestOnce,sp as managedRuleInSync,_m as managementDashboardSiteName,ju as manifestDigest,yn as matchTotpCounter,ZS as mediaObjectHeaders,No as median,nm as medianAbsoluteDeviation,Md as mergeDecisions,pn as mergeInfrastructure,QA as mergePriceBooks,Od as meterTelemetry,iE as metricsManager,Eg as migrateObjectStorage,sE as migrationManager,OC as multiAccountManager,SC as multiRegionManager,fR as needsRenewal,$E as networkSecurityManager,Ft as nextScheduleRuns,De as normalizePublicIpv6,Le as normalizeRuntimeStatus,dt as normalizeScheduleExpression,Xf as normalizeSourceEvent,qe as normalizeSshPublicKey,lm as normalizeTelemetryPolicy,xi as occupiedHostPorts,ba as openApiDocument,_o as optionsForSignal,_C as organizationManager,jl as packagePhpApp,mn as packageServerlessApp,gd as pagesAssetHash,Gg as pagesDnsRecord,Sl as parallel,Mb as parallelMap,Fb as parallelWithRetry,bA as parseCertificateState,Gl as parseChain,Wr as parseCompose,xI as parseComposeCatalog,rh as parseDockerInspect,yg as parseDotenv,nA as parseDrainedSites,_i as parseHostSiteFragments,DS as parseJSONResponse,Ai as parsePreflightFacts,qp as parseSourceDrained,ih as parseSystemdRecords,Qp as parseTargetReady,hd as parseUpstreamPort,$p as parseWorkersPaused,RS as parseXMLResponse,ji as pathTemplate,md as pendingSteps,ko as percentOfLimit,oE as performanceManager,Ul as phpLayerBuildStage,mS as phpLayerPackages,hn as phpRuntimeLayerAssets,OI as planComposeTemplateUpgrade,Fd as planEnforcement,ui as planHetznerVolumes,xp as planIsDestructive,ym as planMitigation,gA as planServerRename,TA as planSiteMove,zs as planZoneMigration,Jt as policyTag,Si as preflightFailed,xy as previewManager,$y as previewNotifications,Ut as previewSchedule,HA as previousBudgetWindow,Ro as priceUsage,FA as priceUsageLines,oA as probeHostRoutes,zc as probeOriginTls,Hb as processInChunks,bu as processSourceWebhook,hs as productionChangeReview,nS as progressiveDeploymentManager,Ld as projectSpend,Zo as propagationHeaders,yc as providerEndpoint,zu as publicKeyFingerprint,Wn as qualifyName,DE as queueManagementManager,_b as quickHash,ip as r2Endpoint,Jg as r2S3Credentials,Xl as rateLimitHeaders,os as rateLimitKey,ze as readDriverState,aA as reconcile,xg as reconcileAddressRecords,Wg as reconcileCloudflareCdn,_h as reconcileCloudflareWorkers,Qs as reconcileDeclaredRecords,QS as reconcileJobObservation,Qg as reconcileR2Buckets,bn as reconcileSourceWebhook,fs as recordDashboardHostPosture,MS as recordPreDeploySecretScan,FS as recordSkippedSecretScan,ea as recursionBlockedResponse,$e as redactRuntimeConfig,Xd as redactTelemetryText,qi as redactTelemetryValue,Nn as redeployServerlessApp,CC as regionPairManager,In as releaseStrategyCapabilities,Wf as releaseTrafficPlan,Di as reloadRpxGateway,Os as remapKey,Bg as removeAddressRecords,$g as removeDns01ChallengeRecord,kn as removeSiteFromCloudConfig,Cu as removeSourceWebhook,Oc as removeStaleServerAddressRecords,vd as renderComposeTemplate,Wi as renderDdosInstallScript,tl as renderNftablesRuleset,As as renderServerCron,el as renderSysctlFile,cd as renderWafConfig,ki as renderWafInstallScript,ad as renewRpxCertificates,oS as replicaManager,ty as requestHash,qb as requiresReplacement,NE as resetRecursionRuntime,BE as resolveApp,p as resolveAppDatabase,mA as resolveAttachTarget,at as resolveAuthEncryptionKey,ce as resolveCloudProvider,zg as resolveCloudflareCdnPlan,ei as resolveComputeVolumes,zo as resolveCredentials,Rs as resolveDashboardAction,sd as resolveDashboardAuth,my as resolveDashboardDomain,fy as resolveDashboardDomains,Us as resolveDeclaredRecords,qI as resolveDeployBucketName,K as resolveDeploymentMode,ii as resolveExecStart,Ho as resolveFailoverStatusCodes,Gc as resolveHetznerApiToken,Ur as resolveHostCleanupConfig,w as resolveMailProxy,b as resolveMailService,mb as resolveManagementDashboardSite,Zi as resolveManagementDashboardSites,Sc as resolveObjectStorage,de as resolveOriginConnection,dA as resolvePlan,m as resolveProjectStackName,Kr as resolveProxyUpstreams,Ml as resolveQueueNames,NA as resolveQueuedDeploymentCommand,Ar as resolveQueues,fS as resolveRecursionConfig,by as resolveRegion,pe as resolveRuntimeInventory,lr as resolveServerlessAppStackName,cl as resolveServerlessArtifactBucketName,Xi as resolveServerlessAssetBucketName,ns as resolveServerlessRuntime,GI as resolveSiteBucketName,Ao as resolveSiteDeployTarget,d as resolveSiteKind,HI as resolveSiteResourceName,QI as resolveSiteStackName,fi as resolveSshSettings,l as resolveStatePath,VI as resolveStorageBucketName,wm as resolveStorageFailover,tr as resolveUiSource,dd as resolveZoneApex,ME as resourceManagementManager,$f as responseToResult,im as robustZScore,nr as roleCapabilities,fu as rollbackImmutableRelease,Bn as rollbackServerlessApp,UA as roundCents,IE as route53ResolverManager,lS as route53RoutingManager,am as routeMatches,kp as routesFromFragments,ss as ruleMatches,uS as runBuildHooks,Ud as runEnforcement,ta as runPhpBuildHooks,lt as runRemoteCommand,Ee as runtimeId,Qe as s3OriginBucket,Rm as s3RegionalDomain,vs as sameCorsRules,xs as sameLifecycleRules,Jn as sameNameservers,ws as sanitizeCloudConfig,s as sanitizeControlPlaneValue,UI as sanitizeName,du as sanitizeOidcReturnPath,Wd as saveTelemetryPolicy,Yf as scanForSecrets,Sd as scopeContains,Dt as scopeKey,Fc as scpUpload,uC as searchCommands,So as searchControlPlane,aS as secretsManager,cE as secretsRotationManager,US as secureContainerRelease,Zy as securityHubManager,lE as securityScanningManager,ge as securityScope,dg as seedFailoverReplicas,Sn as sendAuthenticationEmail,EE as senderReputationManager,Ub as sequence,Sg as serializeDotenv,Ti as serverPublicIpv4,dS as serviceMeshManager,ng as setAttachToInCloudConfig,Er as setMaintenance,bs as setSitePropertyInCloudConfig,nl as setStateDir,mR as setupDns01Challenge,Rc as setupSmsInfrastructure,Wo as sha256,AS as sharedRecursionGuard,xf as sharedRuntimeLoop,Kp as shipsARelease,zS as signCloudFrontCookies,WS as signCloudFrontUrl,k as signRequest,Wl as signRequestAsync,xo as signalDefinition,U as siteInstallBase,Bi as siteMoveArchivePath,SA as siteMoveCertArchivePath,fd as siteUnitGlob,gm as spendNotificationText,Qo as spendOpenApiPaths,Qr as sshExec,Ie as sshExecOrThrow,EC as stackDependencyManager,pc as startLocalDashboardServer,ZA as startSpendLoop,dn as stateDir,Q as statePath,_E as staticSiteManager,ES as storageAdvancedManager,WI as storageFailoverReplicasFromTemplate,qA as streamFocusJsonl,Qd as strongestActiveAction,jm as suggestCommand,pC as suggestFlags,Db as suggestIAMPolicy,Nb as suggestQuotaIncrease,NC as suggestRegionPairs,kC as suggestRegions,gs as syncSourceRepositories,Pd as synchronizeComposeVolumes,Ig as synchronizeConfiguredConfiguration,Da as synchronizeConfiguredJobs,sS as syntheticsManager,Zd as sysctlHardening,sh as systemdWorkloads,JA as telemetryBucketLabel,zi as telemetryCursor,Jd as telemetryEstimatedMonthlyCost,WA as telemetryPercentile,um as telemetryPolicyKey,Dy as templateCache,Np as tenantsOf,Ia as testSourceConnection,kd as tieredMicroCents,cp as toApiLifecycleRule,Vc as toCloudflareZoneSettings,Lo as toFocusJsonl,qd as toFocusRecords,sA as toInventoryServer,jf as totp,ua as totpUri,Bp as unaccountedSites,th as unsupportedCapabilities,BA as unsupportedVolumeCapabilities,Wu as updateCompatibility,Xu as updateSiteInCloudConfig,ks as uploadStaticFiles,Zp as usageDeltaKey,ar as utcInstantOfLocal,UC as validateAccountStructure,Wb as validateAgainstSchema,OA as validateAttachment,vh as validateBackupDestination,hC as validateCommand,vb as validateConfiguration,wb as validateCredentials,zp as validateDeploymentConfig,xA as validateMountPath,Nt as validateOriginGroups,sg as validateResourceLimits,Op as validateServerName,Ep as validateTemplate,og as validateTemplateSize,Lc as verifyAddressRecord,$S as verifyArtifactSignature,KS as verifyMediaAccessToken,zf as verifyTotp,Ku as verifyUpdateSignature,Ws as verifyZoneParity,Eo as volumeCapabilities,bp as wafEventTelemetry,Uc as waitForCloudInit,At as waitForSsh,Sr as webhookEndpoint,bb as withCDN,Ib as withCache,dp as withContentHash,Sb as withDatabase,Lf as withInvocation,Ab as withMonitoring,Cb as withQueue,yb as withSecurity,Qb as withTimeout,pp as workerBindings,io as workerContentHash,Zs as workerInSync,se as wrapCloudInitUserData,St as writeDriverState,nE as xrayManager,Vu as zeroCapacity,jA as zeroFill,Bd as zoneOffsetMs,Do as zonedParts};
605
+ `).filter((v)=>!v.startsWith("-----")).join(""),g=Buffer.from(u,"base64"),h=g.length-65,y=g.subarray(h+1,h+33),R=g.subarray(h+33,h+65);return{kty:"EC",crv:"P-256",x:this.base64UrlEncode(y),y:this.base64UrlEncode(R)}}getJwkThumbprint(){let u=this.getJwk(),g=JSON.stringify({crv:u.crv,kty:u.kty,x:u.x,y:u.y}),h=nd("sha256").update(g).digest();return this.base64UrlEncode(h)}base64UrlEncode(u){return(typeof u==="string"?Buffer.from(u):u).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async signPayload(u,g){let h=await this.getNonce(),y=this.getJwk(),R={alg:"ES256",nonce:h,url:u};if(this.accountUrl)R.kid=this.accountUrl;else R.jwk=y;let v=this.base64UrlEncode(JSON.stringify(R)),P=g===""?"":this.base64UrlEncode(JSON.stringify(g)),L=`${v}.${P}`,z=vg("SHA256");z.update(L);let Ae=z.sign(this.accountKey),he=Ae.subarray(4,4+Ae[3]),Ct=4+Ae[3]+2,It=Ae.subarray(Ct,Ct+Ae[Ct-1]),Ve=Buffer.alloc(32),Me=Buffer.alloc(32);he.copy(Ve,32-he.length),It.copy(Me,32-It.length);let We=Buffer.concat([Ve,Me]);return JSON.stringify({protected:v,payload:P,signature:this.base64UrlEncode(We)})}async acmeRequest(u,g){let h=await this.signPayload(u,g),y=await fetch(u,{method:"POST",headers:{"Content-Type":"application/jose+json"},body:h}),R=y.headers.get("replay-nonce");if(R)this.nonce=R;let v,P=y.headers.get("content-type");if(P?.includes("application/json")||P?.includes("application/problem+json"))v=await y.json();else v=await y.text();if(!y.ok)throw Error(`ACME request failed: ${JSON.stringify(v)}`);return{body:v,headers:y.headers}}async registerAccount(){let u=await this.getDirectory(),{body:g,headers:h}=await this.acmeRequest(u.newAccount,{termsOfServiceAgreed:!0,contact:[`mailto:${this.email}`]}),y=h.get("location");if(!y)throw Error("No account URL returned");return this.accountUrl=y,y}async createOrder(u){if(!this.accountUrl)await this.registerAccount();let g=await this.getDirectory(),{body:h,headers:y}=await this.acmeRequest(g.newOrder,{identifiers:u.map((v)=>({type:"dns",value:v}))}),R=y.get("location");if(!R)throw Error("No order URL returned");return{orderUrl:R,authorizations:h.authorizations,finalize:h.finalize}}async getAuthorization(u){let{body:g}=await this.acmeRequest(u,""),h=g.identifier.value,y=this.getJwkThumbprint(),R=g.challenges.filter((v)=>v.type==="http-01"||v.type==="dns-01").map((v)=>{let P=`${v.token}.${y}`;if(v.type==="http-01")return{type:"http-01",token:v.token,keyAuthorization:P,identifier:`/.well-known/acme-challenge/${v.token}`};else{let L=this.base64UrlEncode(nd("sha256").update(P).digest());return{type:"dns-01",token:v.token,keyAuthorization:P,identifier:`_acme-challenge.${h}`,dnsValue:L}}});return{domain:h,challenges:R}}async respondToChallenge(u){await this.acmeRequest(u,{})}async waitForAuthorization(u,g=30){for(let h=0;h<g;h++){let{body:y}=await this.acmeRequest(u,"");if(y.status==="valid")return;if(y.status==="invalid")throw Error(`Authorization failed: ${JSON.stringify(y)}`);await new Promise((R)=>setTimeout(R,2000))}throw Error("Authorization timed out")}generateCsr(u){let{privateKey:g}=ld("rsa",{modulusLength:2048}),h=g.export({type:"pkcs8",format:"pem"});return{csr:this.createSimpleCsr(u,g),privateKey:h}}createSimpleCsr(u,g){throw Error("CSR generation requires additional implementation. Consider using the shell-based certbot approach instead.")}async finalizeOrder(u,g){let{csr:h,privateKey:y}=this.generateCsr(g),{body:R}=await this.acmeRequest(u,{csr:this.base64UrlEncode(Buffer.from(h,"base64"))}),v=R.certificate;if(!v)throw Error("Certificate not immediately available - polling not implemented");let L=await(await fetch(v)).text(),z=L.split(/(?=-----BEGIN CERTIFICATE-----)/g),Ae=z[0],he=z.slice(1).join("");return{certificate:Ae,privateKey:y,chain:he,fullchain:L,expiresAt:new Date(Date.now()+7776000000)}}getAccountKey(){return this.accountKey}}var Vr=(u)=>u===void 0?void 0:u?"on":"off";function Vc(u){let g={ssl:u.ssl,always_use_https:Vr(u.alwaysUseHttps),automatic_https_rewrites:Vr(u.automaticHttpsRewrites),min_tls_version:u.minTlsVersion,tls_1_3:Vr(u.tls13),brotli:Vr(u.brotli),http3:Vr(u.http3),"0rtt":Vr(u.zeroRtt),early_hints:Vr(u.earlyHints),browser_cache_ttl:u.browserCacheTtl,always_online:Vr(u.alwaysOnline),websockets:Vr(u.websockets),email_obfuscation:Vr(u.emailObfuscation)};if(u.hsts)g.security_header={strict_transport_security:{enabled:u.hsts.enabled,max_age:u.hsts.maxAge??31536000,include_subdomains:u.hsts.includeSubdomains??!1,preload:u.hsts.preload??!1,nosniff:u.hsts.noSniff??!0}};for(let h of Object.keys(g))if(g[h]===void 0)delete g[h];return{...g,...u.raw??{}}}var wi={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 Fg}from"node:tls";async function zc(u){let{address:g,serverName:h,port:y=443,timeoutMs:R=5000}=u;return new Promise((v)=>{let P=!1,L=(Ae)=>{if(P)return;P=!0;try{z.destroy()}catch{}v(Ae)},z=Fg({host:g,port:y,servername:h,rejectUnauthorized:!1,timeout:R});z.once("secureConnect",()=>{if(z.authorized){L({reachable:!0,trusted:!0});return}L({reachable:!0,trusted:!1,reason:z.authorizationError?String(z.authorizationError):"origin certificate is not trusted for this hostname"})}),z.once("timeout",()=>{L({reachable:!1,trusted:!1,reason:`no TLS handshake within ${R}ms`})}),z.once("error",(Ae)=>{L({reachable:!1,trusted:!1,reason:Ae.message})})})}function Mg(u,g){let h=g.replace(/\.$/,"").toLowerCase();return u.some((y)=>{let R=y.replace(/\.$/,"").toLowerCase();if(R===h)return!0;if(!R.startsWith("*."))return!1;let v=R.slice(2);if(!h.endsWith(`.${v}`))return!1;return!h.slice(0,h.length-v.length-1).includes(".")})}async function Wg(u){let{provider:g,zone:h,hosts:y,ipv4:R,ipv6:v,proxied:P=!0,settings:L=wi,cache:z,originGuard:Ae,purge:he=!0,ttl:Ct=300,skipOriginProbe:It=!1,skipEdgeCertificateCheck:Ve=!1}=u,Me={records:[],settingsChanged:[],cacheRules:0,originGuard:!1,purged:!1,deferredProxy:[],warnings:[]};if(y.length===0)return Me;let We=[],j=P&&!Ve?await g.listEdgeCertificateHosts(h):null;for(let G of y){let Ke=P;if(Ke&&j&&!Mg(j,G)){Ke=!1;let vt=j.length===0?"the zone has no active edge certificate yet":`no active edge certificate covers it (${j.join(", ")})`;Me.deferredProxy.push({host:G,reason:vt}),Me.warnings.push(`${G}: publishing DNS-only — ${vt}. 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(Ke&&!It){let vt=await zc({address:R,serverName:G});if(!vt.trusted){Ke=!1;let Et=vt.reason||"origin is not serving a trusted certificate";Me.deferredProxy.push({host:G,reason:Et}),Me.warnings.push(`${G}: publishing DNS-only for now — the origin does not yet serve a certificate this proxy can verify (${Et}). 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(Ke)We.push(G);let yt=[{type:"A",content:R}];if(v&&Yn(G))yt.push({type:"AAAA",content:v});for(let{type:vt,content:Et}of yt){let Zt=await g.upsertRecord(h,{name:G,type:vt,content:Et,ttl:Ct,proxied:Ke});if(Zt.success)Me.records.push({host:G,type:vt,content:Et,proxied:Ke});else Me.warnings.push(`${G} ${vt} → ${Et} failed: ${Zt.message||"unknown provider error"}`)}}if(We.length===0){if(P)Me.warnings.push("No host is proxied yet, so zone settings, cache rules and purge were skipped — they only take effect through the proxy.");return Me}try{let G=Vc(L),Ke=await g.applyZoneSettings(h,G);Me.settingsChanged=Ke.changed;for(let yt of Ke.failed)Me.warnings.push(`zone setting '${yt.id}' could not be applied: ${yt.error}`)}catch(G){Me.warnings.push(`zone settings could not be read: ${G instanceof Error?G.message:String(G)}`)}let ht=kc(We,z);if(ht.length>0){let G=await g.putManagedPhaseRules(h,"http_request_cache_settings",ht);if(G.success)Me.cacheRules=ht.length;else Me.warnings.push(`cache rules could not be written: ${G.message}`)}if(Ae){let G=Nc(We,Ae.header,Ae.value);if(G.length>0){let Ke=await g.putManagedPhaseRules(h,"http_request_late_transform",G);if(Ke.success)Me.originGuard=!0;else Me.warnings.push(`origin guard header could not be written: ${Ke.message}. `+"The gateway will reject requests that lack it — disable the guard or grant the token Transform Rules: Edit.")}}if(he){if(Me.purged=await g.purgeCache(h,{hosts:We}),!Me.purged)Me.warnings.push("edge cache purge failed — new content may take until TTL expiry to appear.")}return Me}var Vg=(u)=>process.env[u];function dd(u,g){let h=u.replace(/\.$/,"").toLowerCase();if(g){let y=g.replace(/\.$/,"").toLowerCase();if(h===y||h.endsWith(`.${y}`))return y}return h.split(".").slice(-2).join(".")}function zg(u,g={}){let h=g.env??Vg,y=u.infrastructure?.compute?.proxy?.cdn,R=[];if(!y||y.provider!=="cloudflare")return{plan:null,errors:R};if(y.originDomain)R.push(`compute.proxy.cdn.originDomain (${y.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 v=h("CLOUDFLARE_API_TOKEN");if(!v)return R.push("CLOUDFLARE_API_TOKEN is not set — the Cloudflare CDN cannot be reconciled."),{plan:null,errors:R};let P=u.sites??{},L=y.frontedHosts?.length?[...new Set(y.frontedHosts.map((It)=>It.toLowerCase()))]:fo(P,{autoWww:u.infrastructure?.compute?.proxy?.autoWww!==!1});if(L.length===0)return R.push("No hostnames to front — set compute.proxy.cdn.frontedHosts, or give a site a domain."),{plan:null,errors:R};let z=u.infrastructure?.dns?.domain,Ae=new Set(L.map((It)=>dd(It,z)));if(Ae.size>1)return R.push(`Fronted hosts span more than one zone (${[...Ae].join(", ")}). A Cloudflare zone is configured as a unit, so run one CDN config per zone.`),{plan:null,errors:R};let he=y.cloudflare??{},Ct=y.secret?{header:y.secretHeader??"X-Origin-Verify",value:y.secret}:void 0;return{plan:{zone:[...Ae][0],hosts:L,apiToken:v,zoneId:he.zoneId??h("CLOUDFLARE_ZONE_ID"),accountId:he.accountId??h("CLOUDFLARE_ACCOUNT_ID"),proxied:he.proxied!==!1,settings:he.settings??wi,cache:he.cache,originGuard:Ct,purge:he.purgeOnDeploy!==!1,skipOriginProbe:he.skipOriginProbe===!0},errors:R}}var Hg=26214400;var Ug=new Set(["/_headers","/_redirects","/_routes.json","/_worker.js"]);class pd{name="cloudflare-pages";apiToken;accountId;constructor(u){if(!u.apiToken)throw Error("Cloudflare Pages needs an API token");if(!u.accountId)throw Error("Cloudflare Pages needs an account id");this.apiToken=u.apiToken,this.accountId=u.accountId}async request(u,g,h){return $s(u,`/accounts/${this.accountId}${g}`,`Bearer ${this.apiToken}`,h)}async getProject(u){try{return await this.request("GET",`/pages/projects/${u}`)}catch(g){if(g instanceof Error&&/\b8000007\b|not found/i.test(g.message))return null;throw g}}async ensureProject(u,g="main"){let h=await this.getProject(u);if(h)return h;return this.request("POST","/pages/projects",{name:u,production_branch:g})}async uploadToken(u){return(await this.request("GET",`/pages/projects/${u}/upload-token`)).jwt}async missingHashes(u,g){let h=await $s("POST","/pages/assets/check-missing",`Bearer ${u}`,{hashes:g});return new Set(h)}async upsertHashes(u,g){await $s("POST","/pages/assets/upsert-hashes",`Bearer ${u}`,{hashes:g})}async uploadBatch(u,g){let h=g.map((y)=>({key:y.hash,value:y.base64,metadata:{contentType:jg(y.extension)},base64:!0}));await $s("POST","/pages/assets/upload",`Bearer ${u}`,h)}async createDeployment(u,g,h){let y={};for(let v of g)y[v.path]=v.hash;let R=new FormData;if(R.append("manifest",JSON.stringify(y)),h)R.append("branch",h);return this.request("POST",`/pages/projects/${u}/deployments`,R)}async deployDirectory(u){let g=await ep(u.directory);if(g.length===0)throw Error(`No files to deploy in ${u.directory}`);let h=await this.uploadToken(u.project),y=await this.missingHashes(h,g.map((z)=>z.hash)),R=g.filter((z)=>y.has(z.hash)),v=[];for(let z=0;z<R.length;z+=100)v.push(R.slice(z,z+100));let P=0;for(let z=0;z<v.length;z+=4){let Ae=v.slice(z,z+4);await Promise.all(Ae.map((he)=>this.uploadBatch(h,he))),P+=Ae.reduce((he,Ct)=>he+Ct.length,0),u.onProgress?.(P,R.length)}return await this.upsertHashes(h,g.map((z)=>z.hash)),{deployment:await this.createDeployment(u.project,g,u.branch),total:g.length,uploaded:R.length,uploadedBytes:R.reduce((z,Ae)=>z+Ae.size,0)}}async listCustomDomains(u){return(await this.request("GET",`/pages/projects/${u}/domains`)).map((h)=>h.name)}async attachCustomDomain(u,g){if((await this.listCustomDomains(u)).includes(g))return!1;return await this.request("POST",`/pages/projects/${u}/domains`,{name:g}),!0}}function Gg(u,g){return{type:"CNAME",name:u,value:g.endsWith(".pages.dev")?g:`${g}.pages.dev`,ttl:1,proxied:!0}}async function gd(u,g){let{blake3:h}=await import("./chunk-4ccv5c4m.js").then((m)=>xS(m.default,1));return(await h(u+g)).slice(0,32)}async function ep(u){let{readdir:g}=await import("node:fs/promises"),{join:h,relative:y,sep:R}=await import("node:path"),v=[];async function P(L){let z=await g(L,{withFileTypes:!0});for(let Ae of z){let he=h(L,Ae.name);if(Ae.isDirectory()){await P(he);continue}if(!Ae.isFile())continue;let Ct=`/${y(u,he).split(R).join("/")}`;if(Ug.has(Ct))continue;let It=await Bun.file(he).bytes();if(It.byteLength>26214400)throw Error(`${Ct} is ${It.byteLength} bytes, over the Cloudflare Pages limit of 26214400`);let Ve=Buffer.from(It).toString("base64"),Me=Ae.name.lastIndexOf("."),We=Me>0?Ae.name.slice(Me+1):"";v.push({path:Ct,hash:await gd(Ve,We),base64:Ve,extension:We,size:It.byteLength})}}return await P(u),v.sort((L,z)=>L.path.localeCompare(z.path)),v}function jg(u){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"}[u.toLowerCase()]||"application/octet-stream"}async function $s(u,g,h,y){let R={Authorization:h},v;if(y instanceof FormData)v=y;else if(y!==void 0)R["Content-Type"]="application/json",v=JSON.stringify(y);let P=await fetch(`https://api.cloudflare.com/client/v4${g}`,{method:u,headers:R,body:v}),L=await P.text(),z;try{z=JSON.parse(L)}catch{throw Error(`Cloudflare Pages API returned ${P.status} with a non-JSON body: ${L.slice(0,200)}`)}if(!z.success){let Ae=(z.errors??[]).map((he)=>`${he.code}: ${he.message}`).join(", ");throw Error(`Cloudflare Pages API error (${P.status}): ${Ae||L.slice(0,200)}`)}return z.result}import{createHash as Kg}from"node:crypto";var rp="https://api.cloudflare.com/client/v4",np=10042,qg=10006,Zg=10059;class Fn extends Error{status;errors;constructor(u,g,h=[]){super(u);this.name="R2ApiError",this.status=g,this.errors=h}hasCode(u){return this.errors.some((g)=>g.code===u)}}class An extends Fn{accountId;constructor(u,g,h=[]){super(`R2 is not enabled on Cloudflare account ${u}. Enable it once in the Cloudflare dashboard (R2 Object Storage, then follow the prompt to activate it), then re-run the deploy.`,g,h);this.name="R2NotEnabledError",this.accountId=u}}class ai{name="cloudflare-r2";apiToken;accountId;fetchImpl;constructor(u){if(!u.apiToken)throw Error("Cloudflare R2 needs an API token");if(!u.accountId)throw Error("Cloudflare R2 needs an account id");this.apiToken=u.apiToken,this.accountId=u.accountId,this.fetchImpl=u.fetch??((g,h)=>fetch(g,h))}async requestEnvelope(u,g,h,y={}){let R={Authorization:`Bearer ${this.apiToken}`};if(h!==void 0)R["Content-Type"]="application/json";if(y.jurisdiction&&y.jurisdiction!=="default")R["cf-r2-jurisdiction"]=y.jurisdiction;let v=await this.fetchImpl(`${rp}/accounts/${this.accountId}/r2${g}`,{method:u,headers:R,body:h===void 0?void 0:JSON.stringify(h)}),P=await v.text(),L;try{L=JSON.parse(P)}catch{throw new Fn(`Cloudflare R2 API returned ${v.status} with a non-JSON body: ${P.slice(0,200)}`,v.status)}if(!L.success){let z=L.errors??[];if(z.some((he)=>he.code===np))throw new An(this.accountId,v.status,z);let Ae=z.map((he)=>`${he.code}: ${he.message}`).join(", ");throw new Fn(`Cloudflare R2 API error (${v.status}) on ${u} ${g}: ${Ae||P.slice(0,200)}`,v.status,z)}return L}async request(u,g,h,y){return(await this.requestEnvelope(u,g,h,y)).result}bucketPath(u){return`/buckets/${encodeURIComponent(u)}`}async listBuckets(u={}){let g=[],h;do{let y=new URLSearchParams({per_page:"1000"});if(h)y.set("cursor",h);let R=await this.requestEnvelope("GET",`/buckets?${y}`,void 0,u),v=R.result?.buckets??[];g.push(...v),h=v.length>0?R.result_info?.cursor||void 0:void 0}while(h);return g}async getBucket(u,g={}){try{return await this.request("GET",this.bucketPath(u),void 0,g)}catch(h){if(h instanceof An)throw h;if(h instanceof Fn&&(h.hasCode(qg)||h.status===404))return null;throw h}}async ensureBucket(u,g={}){let h={jurisdiction:g.jurisdiction},y=await this.getBucket(u,h);if(y)return{bucket:y,created:!1};let R={name:u};if(g.locationHint)R.locationHint=g.locationHint;let v=await this.request("POST","/buckets",R,h);return{bucket:{...v,name:v?.name||u},created:!0}}async getCors(u,g={}){try{return(await this.request("GET",`${this.bucketPath(u)}/cors`,void 0,g))?.rules??[]}catch(h){if(h instanceof Fn&&!(h instanceof An)&&(h.hasCode(Zg)||h.status===404))return[];throw h}}async putCors(u,g,h={}){if(g.length===0){await this.request("DELETE",`${this.bucketPath(u)}/cors`,void 0,h);return}await this.request("PUT",`${this.bucketPath(u)}/cors`,{rules:g},h)}async ensureCors(u,g,h={}){let y=await this.getCors(u,h);if(vs(y,g))return!1;return await this.putCors(u,g,h),!0}async getLifecycle(u,g={}){return(await this.request("GET",`${this.bucketPath(u)}/lifecycle`,void 0,g))?.rules??[]}async putLifecycle(u,g,h={}){await this.request("PUT",`${this.bucketPath(u)}/lifecycle`,{rules:g},h)}async ensureLifecycle(u,g,h={}){let y=await this.getLifecycle(u,h);if(xs(y,g))return!1;return await this.putLifecycle(u,g,h),!0}async listCustomDomains(u,g={}){return(await this.request("GET",`${this.bucketPath(u)}/domains/custom`,void 0,g))?.domains??[]}async attachCustomDomain(u,g,h={}){return this.request("POST",`${this.bucketPath(u)}/domains/custom`,{domain:g.domain,zoneId:g.zoneId,enabled:g.enabled??!0,minTLS:g.minTLS??"1.2"},h)}async updateCustomDomain(u,g,h,y={}){return this.request("PUT",`${this.bucketPath(u)}/domains/custom/${encodeURIComponent(g)}`,h,y)}async ensureCustomDomain(u,g,h={},y){let R=g.minTLS??"1.2",P=(y??await this.listCustomDomains(u,h)).find((Ae)=>Ae.domain.toLowerCase()===g.domain.toLowerCase());if(!P){let Ae=await this.attachCustomDomain(u,{...g,minTLS:R,enabled:!0},h);return{action:"attached",domain:{...Ae,domain:Ae?.domain||g.domain}}}let L=P.minTLS??"1.0";if(P.enabled&&L===R)return{action:"unchanged",domain:P};let z=await this.updateCustomDomain(u,P.domain,{enabled:!0,minTLS:R},h);return{action:"updated",domain:{...P,...z}}}async getManagedDomain(u,g={}){return this.request("GET",`${this.bucketPath(u)}/domains/managed`,void 0,g)}async setManagedDomain(u,g,h={}){let y=await this.getManagedDomain(u,h);if(y?.enabled===g)return{changed:!1,domain:y};return{changed:!0,domain:await this.request("PUT",`${this.bucketPath(u)}/domains/managed`,{enabled:g},h)}}}function ip(u){return`https://${u}.r2.cloudflarestorage.com`}async function Jg(u){let{apiToken:g,accountId:h}=u;if(!g)throw Error("r2S3Credentials needs an API token");if(!h)throw Error("r2S3Credentials needs an account id");let y=u.fetch??((P,L)=>fetch(P,L)),R=[],v;for(let P of[`/accounts/${h}/tokens/verify`,"/user/tokens/verify"]){let L=await y(`${rp}${P}`,{method:"GET",headers:{Authorization:`Bearer ${g}`}}),z=await L.json().catch(()=>null);if(L.ok&&z?.success&&z.result?.id){v=z.result.id;break}let Ae=z?.errors?.map((he)=>`${he.code}: ${he.message}`).join(", ");R.push(`${P} -> ${L.status}${Ae?` (${Ae})`:""}`)}if(!v)throw Error(`Could not verify the Cloudflare API token to derive R2 credentials: ${R.join("; ")}`);return{accessKeyId:v,secretAccessKey:Kg("sha256").update(g).digest("hex"),endpoint:ip(h),region:"auto"}}function Ni(u){if(Array.isArray(u))return`[${u.map(Ni).join(",")}]`;if(u&&typeof u==="object")return`{${Object.entries(u).filter(([,h])=>h!==void 0).sort(([h],[y])=>h.localeCompare(y)).map(([h,y])=>`${JSON.stringify(h)}:${Ni(y)}`).join(",")}}`;return JSON.stringify(u)}function tp(u,g){let h=(y)=>y&&y.length>0?[...y].map(String).sort():void 0;return{id:g?u.id:void 0,allowed:{origins:h(u.allowed?.origins),methods:h(u.allowed?.methods?.map((y)=>y.toUpperCase())),headers:h(u.allowed?.headers?.map((y)=>y.toLowerCase()))},exposeHeaders:h(u.exposeHeaders?.map((y)=>y.toLowerCase())),maxAgeSeconds:u.maxAgeSeconds}}function vs(u,g){if(u.length!==g.length)return!1;return g.every((h,y)=>{let R=h.id!==void 0;return Ni(tp(u[y],R))===Ni(tp(h,R))})}function xs(u,g){if(u.length!==g.length)return!1;let h=(y)=>Ni([...y].map((R)=>({...R,storageClassTransitions:R.storageClassTransitions?.length?R.storageClassTransitions:void 0})).sort((R,v)=>R.id.localeCompare(v.id)));return h(u)===h(g)}var Yg="r2 cache",Xg=/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/;async function Qg(u,g={}){let h=g.log??(()=>{}),y={buckets:[],warnings:[]},R=u.infrastructure?.r2??u.r2,v=Object.entries(R?.buckets??{});if(v.length===0)return h("R2: no buckets declared, skipping."),y;if(!g.apiToken||!g.accountId){let he=[!g.apiToken&&"CLOUDFLARE_API_TOKEN",!g.accountId&&"CLOUDFLARE_ACCOUNT_ID"].filter(Boolean).join(" and "),Ct=`R2: ${v.length} bucket(s) declared but ${he} is not set, skipping.`;return h(Ct),y.warnings.push(Ct),y}let P=g.dryRun===!0,L=new ai({apiToken:g.apiToken,accountId:g.accountId,fetch:g.fetch}),z=new H(g.apiToken,{zoneId:g.zoneId,accountId:g.accountId}),Ae=new Map;for(let[he,Ct]of v){let It=Ct?.name;if(!It||!Xg.test(It)){y.warnings.push(`R2: bucket '${he}' has an invalid name '${It??""}' (3-63 chars: lowercase letters, digits, hyphens), skipping.`);continue}h(`R2: ${P?"checking":"reconciling"} bucket ${It}...`);let Ve={name:It,changes:[],domains:[]};if(y.buckets.push(Ve),await yh(Ct,{r2:L,cloudflare:z,dryRun:P,summary:Ve,warnings:y.warnings,claimed:Ae,log:h}),Ve.changes.length===0)h(`R2: ${It} is in sync.`);else for(let Me of Ve.changes)h(`R2: ${It}: ${Me}`)}return y}async function yh(u,g){let{r2:h,dryRun:y,summary:R,warnings:v}=g,P=u.name,L={jurisdiction:u.jurisdiction},z=(Ve,Me)=>{let We=y?Me&&`would ${Me}`:Ve;if(We)R.changes.push(We)},Ae;if(y)Ae=await h.getBucket(P,L)!==null;else{let{created:Ve}=await h.ensureBucket(P,{locationHint:u.locationHint,jurisdiction:u.jurisdiction});if(Ae=!0,Ve)z("created","")}if(!Ae)z("","create bucket");let he=Sh(u.customDomains);await ro(g,`cors on ${P}`,async()=>{if(!u.cors)return;if(!Ae){z("cors updated","set cors");return}let Ve=await h.getCors(P,L);if(vs(Ve,u.cors))return;if(!y)await h.putCors(P,u.cors,L);z(u.cors.length===0?"cors removed":"cors updated",u.cors.length===0?"remove cors":"update cors")}),await ro(g,`lifecycle on ${P}`,async()=>{if(!u.lifecycle)return;let Ve=u.lifecycle.map(cp);if(Ae){let Me=await h.getLifecycle(P,L);if(xs(Me,Ve))return}if(!y)await h.putLifecycle(P,Ve,L);z("lifecycle updated","update lifecycle")}),await ro(g,`r2.dev URL on ${P}`,async()=>{let Ve=u.publicDevUrl===!0;if(!Ae){if(Ve)z("r2.dev URL enabled","enable r2.dev URL");return}if((await h.getManagedDomain(P,L))?.enabled===Ve)return;if(!y)await h.setManagedDomain(P,Ve,L);z(Ve?"r2.dev URL enabled":"r2.dev URL disabled",Ve?"enable r2.dev URL":"disable r2.dev URL")});let Ct=[];if(he.length>0&&Ae)try{Ct=await h.listCustomDomains(P,L)}catch(Ve){if(Ve instanceof An)throw Ve;v.push(`R2: could not list custom domains on ${P}: ${Kc(Ve)}`)}let It=new Map;for(let{domain:Ve,minTLS:Me}of he){let We=g.claimed.get(Ve);if(We&&We!==P){v.push(`R2: ${Ve} is declared on both ${We} and ${P}; leaving it on ${We}.`);continue}g.claimed.set(Ve,P);let j=Ct.find((G)=>G.domain.toLowerCase()===Ve),ht=Me??"1.2";if(j&&j.enabled&&(j.minTLS??"1.0")===ht){if(R.domains.push({domain:Ve,status:jc(j)}),j.zoneId)It.set(Ve,j.zoneId);continue}await ro(g,`custom domain ${Ve} on ${P}`,async()=>{if(j){if(!y)await h.updateCustomDomain(P,j.domain,{enabled:!0,minTLS:ht},L);if(z(`custom domain ${Ve} updated`,`update custom domain ${Ve}`),R.domains.push({domain:Ve,status:jc({...j,enabled:!0})}),j.zoneId)It.set(Ve,j.zoneId);return}let G=await g.cloudflare.zoneIdFor(Ve);if(It.set(Ve,G),!y)await h.ensureCustomDomain(P,{domain:Ve,zoneId:G,minTLS:ht},L,Ct);z(`custom domain ${Ve} attached`,`attach custom domain ${Ve}`),R.domains.push({domain:Ve,status:y?"not attached":"pending"})},()=>R.domains.push({domain:Ve,status:"error"}))}if(u.cache&&he.length>0)await Ch(u,he.map((Ve)=>Ve.domain).filter((Ve)=>g.claimed.get(Ve)===P),It,g,z)}async function Ch(u,g,h,y,R){let v=op(u.cache);if(!v||g.length===0)return;let P=new Map;for(let L of g){let z=h.get(L);if(!z)try{z=await y.cloudflare.zoneIdFor(L)}catch(Ae){y.warnings.push(`R2: could not resolve the zone for ${L}, cache rule skipped: ${Kc(Ae)}`);continue}P.set(z,[...P.get(z)??[],L])}for(let L of P.values()){let z={action:"set_cache_settings",description:`${Kt} ${Yg}`,expression:`(${zt(L)})`,enabled:!0,action_parameters:v};await ro(y,`cache rule for ${L.join(", ")}`,async()=>{let Ae=await y.cloudflare.getPhaseRules(L[0],"http_request_cache_settings");if(sp(Ae,z))return;if(!y.dryRun){let he=await y.cloudflare.putManagedPhaseRules(L[0],"http_request_cache_settings",[z]);if(!he.success)throw Error(he.message||"cache rule write failed")}R(`cache rule updated for ${L.join(", ")}`,`update cache rule for ${L.join(", ")}`)})}}function op(u){if(u.edgeTtl===void 0&&u.browserTtl===void 0)return null;let g={cache:!0};if(u.edgeTtl!==void 0)g.edge_ttl={mode:"override_origin",default:u.edgeTtl};if(u.browserTtl!==void 0)g.browser_ttl={mode:"override_origin",default:u.browserTtl};return g}function sp(u,g){let h=Wt(g.expression),y=Kn(g.expression),R=(L)=>(L.description||"").startsWith(Kt),v=(L)=>L.action===g.action&&L.description===g.description&&(L.enabled??!0)===(g.enabled??!0)&&Kn(L.expression)===y&&Fs(L.action_parameters)===Fs(g.action_parameters),P=!1;for(let L of u){if(!R(L))continue;let z=Wt(L.expression);if(!h.some((he)=>z.includes(he)))continue;if(v(L)&&h.every((he)=>z.includes(he))&&!P){P=!0;continue}return!1}return P}function cp(u){let g={id:u.id,enabled:u.enabled??!0,conditions:{prefix:u.prefix??""}};if(u.expireAfterDays!==void 0)g.deleteObjectsTransition={condition:{type:"Age",maxAge:Hc(u.expireAfterDays)}};else if(u.expireOn!==void 0)g.deleteObjectsTransition={condition:{type:"Date",date:u.expireOn}};if(u.abortMultipartUploadsAfterDays!==void 0)g.abortMultipartUploadsTransition={condition:{type:"Age",maxAge:Hc(u.abortMultipartUploadsAfterDays)}};if(u.infrequentAccessAfterDays!==void 0)g.storageClassTransitions=[{storageClass:"InfrequentAccess",condition:{type:"Age",maxAge:Hc(u.infrequentAccessAfterDays)}}];return g}function Hc(u){return Math.round(u*86400)}function Sh(u){let g=new Set,h=[];for(let y of u??[]){let R=typeof y==="string"?{domain:y}:y,v=R.domain?.trim().replace(/\.$/,"").toLowerCase();if(!v||g.has(v))continue;g.add(v),h.push({domain:v,minTLS:R.minTLS})}return h}function jc(u){if(!u.enabled)return"disabled";let g=u.status?.ownership,h=u.status?.ssl;if(g==="active"&&h==="active")return"active";for(let y of[g,h])if(y==="error"||y==="blocked"||y==="deactivated")return y;return"pending"}async function ro(u,g,h,y){try{await h()}catch(R){if(R instanceof An)throw R;u.warnings.push(`R2: ${g} failed: ${Kc(R)}`),y?.()}}function Kc(u){return u instanceof Error?u.message:String(u)}function Fs(u){if(Array.isArray(u))return`[${u.map(Fs).join(",")}]`;if(u&&typeof u==="object")return`{${Object.entries(u).filter(([,h])=>h!==void 0).sort(([h],[y])=>h.localeCompare(y)).map(([h,y])=>`${JSON.stringify(h)}:${Fs(y)}`).join(",")}}`;return JSON.stringify(u)}import{basename as Dh,extname as kh}from"node:path";import{createHash as Rh}from"node:crypto";var bh="https://api.cloudflare.com/client/v4",xn="TS_CLOUD_CONTENT_HASH",no="2025-09-01",Zc="application/javascript+module",Ah=10007,Ph=[1e4,9109];class li extends Error{status;errors;constructor(u,g,h=[]){super(u);this.name="WorkersApiError",this.status=g,this.errors=h}hasCode(u){return this.errors.some((g)=>g.code===u)}}class Ms extends li{permission;constructor(u,g,h,y=[]){super(`The Cloudflare API token is missing the "${u}" permission (${g}). Edit the token in the Cloudflare dashboard (My Profile, API Tokens), add it, then re-run the deploy.`,h,y);this.name="WorkersPermissionError",this.permission=u}}class Bs{name="cloudflare-workers";apiToken;accountId;fetchImpl;constructor(u){if(!u.apiToken)throw Error("Cloudflare Workers needs an API token");if(!u.accountId)throw Error("Cloudflare Workers needs an account id");this.apiToken=u.apiToken,this.accountId=u.accountId,this.fetchImpl=u.fetch??((g,h)=>fetch(g,h))}async request(u,g,h){let y={Authorization:`Bearer ${this.apiToken}`},R;if(h instanceof FormData)R=h;else if(h!==void 0)y["Content-Type"]="application/json",R=JSON.stringify(h);let v=await this.fetchImpl(`${bh}/accounts/${this.accountId}/workers${g}`,{method:u,headers:y,body:R}),P=await v.text(),L;try{L=JSON.parse(P)}catch{throw new li(`Cloudflare Workers API returned ${v.status} with a non-JSON body: ${P.slice(0,200)}`,v.status)}if(!L.success){let z=L.errors??[],Ae=z.map((he)=>`${he.code}: ${he.message}`).join(", ");if($h(v.status,z))throw new Ms(Ih(g),`${u} ${g} -> ${v.status}${Ae?`, ${Ae}`:""}`,v.status,z);throw new li(`Cloudflare Workers API error (${v.status}) on ${u} ${g}: ${Ae||P.slice(0,200)}`,v.status,z)}return L.result}scriptPath(u){return`/scripts/${encodeURIComponent(u)}`}async getSettings(u){try{return await this.request("GET",`${this.scriptPath(u)}/settings`)}catch(g){if(g instanceof Ms)throw g;if(g instanceof li&&(g.hasCode(Ah)||g.status===404))return null;throw g}}async getScript(u){return this.getSettings(u)}async uploadModuleScript(u,g){return this.request("PUT",this.scriptPath(u),up(g))}async ensureModuleScript(u,g){let h=io(g),y=await this.getSettings(u);if(y&&Zs(y,g,h))return{action:"unchanged",hash:h};return await this.uploadModuleScript(u,dp(g,h)),{action:y?"updated":"created",hash:h}}async listCustomDomains(u={}){let g=new URLSearchParams;if(u.service)g.set("service",u.service);if(u.hostname)g.set("hostname",u.hostname);if(u.zoneId)g.set("zone_id",u.zoneId);let h=g.toString(),y=h?`?${h}`:"";return await this.request("GET",`/domains${y}`)??[]}async attachCustomDomain(u,g){let h={hostname:u,service:g.service,environment:g.environment??"production"};if(g.zoneId)h.zone_id=g.zoneId;return this.request("PUT","/domains",h)}async detachCustomDomain(u){await this.request("DELETE",`/domains/${encodeURIComponent(u)}`)}async ensureCustomDomain(u,g,h){let R=(h??await this.listCustomDomains({hostname:u})).find((P)=>P.hostname.toLowerCase()===u.toLowerCase());if(R&&R.service===g.service)return{action:"unchanged",domain:R};if(R)throw Error(`${u} is attached to the Worker '${R.service}'. Detach it there first (Workers & Pages, ${R.service}, Settings, Domains & Routes); ts-cloud does not move it.`);let v=await this.attachCustomDomain(u,g);return{action:"attached",domain:{...v,hostname:v?.hostname||u}}}}function $h(u,g){if(g.some((h)=>Ph.includes(h.code)))return!0;return(u===401||u===403)&&g.length===0}function Ih(u){if(u.startsWith("/domains"))return"Workers Routes: Edit (zone, for Workers custom domains) and Workers Scripts: Edit (account)";return"Workers Scripts: Edit (account)"}function up(u){if(!u.modules.some((y)=>y.name===u.mainModule))throw Error(`Worker main module '${u.mainModule}' is not one of the uploaded modules`);let g={main_module:u.mainModule,bindings:u.bindings??[],compatibility_date:u.compatibilityDate??no,compatibility_flags:u.compatibilityFlags??[],keep_bindings:["secret_text"]},h=new FormData;h.append("metadata",JSON.stringify(g));for(let y of u.modules)h.append(y.name,new Blob([y.content],{type:y.type}),y.name);return h}function io(u){let g={mainModule:u.mainModule,modules:[...u.modules].sort((h,y)=>h.name.localeCompare(y.name)).map((h)=>({name:h.name,type:h.type,sha256:lp(h.content)})),bindings:[...u.bindings??[]].filter((h)=>h.name!==xn).sort((h,y)=>h.name.localeCompare(y.name)),compatibilityDate:u.compatibilityDate??no,compatibilityFlags:[...u.compatibilityFlags??[]].sort()};return lp(qc(g))}function dp(u,g=io(u)){return{...u,bindings:[...(u.bindings??[]).filter((h)=>h.name!==xn),{type:"plain_text",name:xn,text:g}]}}function Zs(u,g,h){let y=u.bindings??[],R=y.find((v)=>v.name===xn&&v.type==="plain_text");if(!R||R.text!==h)return!1;return(g.bindings??[]).every((v)=>{let P=y.find((z)=>z.name===v.name);if(!P||P.type!==v.type)return!1;let L=v.type==="r2_bucket"?"bucket_name":v.type==="plain_text"?"text":void 0;return!L||P[L]===v[L]})}function lp(u){return Rh("sha256").update(u).digest("hex")}function qc(u){if(Array.isArray(u))return`[${u.map(qc).join(",")}]`;if(u&&typeof u==="object")return`{${Object.entries(u).filter(([,h])=>h!==void 0).sort(([h],[y])=>h.localeCompare(y)).map(([h,y])=>`${JSON.stringify(h)}:${qc(y)}`).join(",")}}`;return JSON.stringify(u)}async function Jc(u){if(!await Bun.file(u).exists())throw Error(`Worker entry not found: ${u}`);let g;try{g=await Bun.build({entrypoints:[u],target:"browser",format:"esm",minify:!0,external:["cloudflare:*"]})}catch(R){throw Error(`Bundling Worker ${u} failed: ${Eh(R)}`)}if(!g.success)throw Error(`Bundling Worker ${u} failed: ${g.logs.map((R)=>String(R.message??R)).join("; ")}`);if(g.outputs.length!==1)throw Error(`Bundling Worker ${u} produced ${g.outputs.length} files (${g.outputs.map((R)=>R.path).join(", ")}); a Worker is uploaded as a single module, so remove the dynamic imports or asset imports that split it.`);let h=g.outputs[0];if(h.kind!=="entry-point")throw Error(`Bundling Worker ${u} produced a ${h.kind} instead of an entry module`);let y=await h.text();return{name:`${Dh(u,kh(u))}.js`,content:y,type:Zc,size:new TextEncoder().encode(y).byteLength}}function Eh(u){if(u instanceof AggregateError&&u.errors.length>0)return u.errors.map((g)=>g instanceof Error?g.message:String(g?.message??g)).join("; ");return u instanceof Error?u.message:String(u)}import{isAbsolute as Oh,resolve as Nh}from"node:path";var xh="https://api.cloudflare.com/client/v4",Lh=/^[a-z0-9][a-z0-9_-]{0,62}$/;async function _h(u,g={}){let h=g.log??(()=>{}),y={workers:[],warnings:[]},R=Object.entries(u.infrastructure?.workers??u.workers??{});if(R.length===0)return h("Workers: none declared, skipping."),y;if(!g.apiToken||!g.accountId){let L=[!g.apiToken&&"CLOUDFLARE_API_TOKEN",!g.accountId&&"CLOUDFLARE_ACCOUNT_ID"].filter(Boolean).join(" and "),z=`Workers: ${R.length} Worker(s) declared but ${L} is not set, skipping.`;return h(z),y.warnings.push(z),y}let v=u.infrastructure?.r2??u.r2,P={workers:new Bs({apiToken:g.apiToken,accountId:g.accountId,fetch:g.fetch}),r2:new ai({apiToken:g.apiToken,accountId:g.accountId,fetch:g.fetch}),cloudflare:new H(g.apiToken,{zoneId:g.zoneId,accountId:g.accountId}),apiToken:g.apiToken,fetch:g.fetch??((L,z)=>fetch(L,z)),projectRoot:g.projectRoot??process.cwd(),dryRun:g.dryRun===!0,warnings:y.warnings,log:h,r2ConfigDomains:Hh(v),r2Buckets:v,claimed:new Map};for(let[L,z]of R){let Ae=z?.name;if(!Ae||!Lh.test(Ae)){y.warnings.push(`Workers: '${L}' has an invalid name '${Ae??""}' (1-63 chars: lowercase letters, digits, '-' and '_'), skipping.`);continue}if(!z.entry){y.warnings.push(`Workers: ${Ae} has no entry, skipping.`);continue}h(`Workers: ${P.dryRun?"checking":"reconciling"} ${Ae}...`);let he={name:Ae,changes:[],domains:[]};y.workers.push(he),await Mh(z,he,P);for(let Ct of he.changes)h(`Workers: ${Ae}: ${Ct}`)}return y}async function Mh(u,g,h){let y=u.name,R=Oh(u.entry)?u.entry:Nh(h.projectRoot,u.entry),v;try{v=await Jc(R)}catch(L){throw Error(`Worker ${y}: ${di(L)}`)}g.changes.push(`bundled ${Gh(v.size)}`);let P={mainModule:v.name,modules:[{name:v.name,content:v.content,type:v.type}],bindings:pp(u,h),compatibilityDate:u.compatibilityDate??no,compatibilityFlags:u.compatibilityFlags??[]};if(h.dryRun){let L=await h.workers.getSettings(y);g.changes.push(L&&Zs(L,P,io(P))?"unchanged":"would upload")}else{let{action:L}=await h.workers.ensureModuleScript(y,P);g.changes.push(L==="unchanged"?"unchanged":"uploaded")}for(let L of Uh(u.customDomains))await Bh(y,L,g,h)}async function Bh(u,g,h,y){let R=(Ve)=>{h.domains.push({domain:g,status:Ve})},v=(Ve)=>{y.warnings.push(`Workers: ${Ve}`),R("conflict")},P=y.claimed.get(g);if(P&&P!==u){v(`${g} is declared on both ${P} and ${u}; leaving it on ${P}.`);return}y.claimed.set(g,u);let L=y.r2ConfigDomains.get(g);if(L){v(`${g} is also declared as a custom domain of the R2 bucket '${L}' (r2.buckets). A hostname serves either a bucket or a Worker. Remove it from the bucket's customDomains and detach it in the dashboard (R2, ${L}, Settings, Custom Domains) first; to serve the bucket through the Worker, bind it with bindings.r2Buckets instead.`);return}let z=await Wh(y);if(z===null){R("error");return}let Ae=z.find((Ve)=>Ve.hostname.toLowerCase()===g);if(Ae?.service===u){R("active");return}if(Ae){v(`${g} is attached to the Worker '${Ae.service}'. Detach it there first (Workers & Pages, ${Ae.service}, Settings, Domains & Routes); it is not moved automatically.`);return}let he=(await Vh(y))?.get(g);if(he){v(`${g} is attached to the R2 bucket '${he}' as a custom domain. Detach it first (R2, ${he}, Settings, Custom Domains, then re-run the deploy); it is not detached automatically. To serve the bucket through the Worker, bind it with bindings.r2Buckets.`);return}let Ct;try{Ct=await y.cloudflare.zoneIdFor(g)}catch(Ve){y.warnings.push(`Workers: could not resolve the zone for ${g}, not attached: ${di(Ve)}`),R("error");return}let It=await zh(y,Ct,g);if(It.length>0){let Ve=It.map((Me)=>`${Me.type} ${Me.content}`).join(", ");v(`${g} already has a DNS record (${Ve}). A Worker custom domain creates its own record, so Cloudflare will not attach over it. Delete the record first (DNS, Records), then re-run the deploy; it is not deleted automatically.`);return}if(y.dryRun){h.changes.push(`would attach custom domain ${g}`),R("not attached");return}try{await y.workers.ensureCustomDomain(g,{service:u,zoneId:Ct},z),h.changes.push(`custom domain ${g} attached`),z.push({id:"",hostname:g,service:u,zone_id:Ct}),R("pending")}catch(Ve){y.warnings.push(`Workers: custom domain ${g} on ${u} failed: ${di(Ve)}`),R("error")}}async function Wh(u){if(u.attached!==void 0)return u.attached;try{u.attached=await u.workers.listCustomDomains()}catch(g){u.warnings.push(`Workers: could not list Worker custom domains, none attached: ${di(g)}`),u.attached=null}return u.attached}async function Vh(u){if(u.r2AccountDomains!==void 0)return u.r2AccountDomains;let g=new Map;try{let h=(await u.r2.listBuckets()).map((y)=>({name:y.name}));for(let y of Object.values(u.r2Buckets?.buckets??{}))if(y.jurisdiction&&y.jurisdiction!=="default")h.push({name:y.name,jurisdiction:y.jurisdiction});for(let y of h){let R=await u.r2.listCustomDomains(y.name,{jurisdiction:y.jurisdiction}).catch(()=>[]);for(let v of R)g.set(v.domain.toLowerCase(),y.name)}u.r2AccountDomains=g}catch(h){u.log(`Workers: could not check R2 custom domains (${di(h)}); relying on the DNS check.`),u.r2AccountDomains=null}return u.r2AccountDomains}async function zh(u,g,h){try{let y=await u.fetch(`${xh}/zones/${g}/dns_records?name=${encodeURIComponent(h)}&per_page=100`,{method:"GET",headers:{Authorization:`Bearer ${u.apiToken}`}}),R=await y.json();if(!R?.success)throw Error(`HTTP ${y.status}`);return(R.result??[]).filter((v)=>v.name?.toLowerCase()===h).map((v)=>({type:v.type??"?",content:v.content??""}))}catch(y){return u.log(`Workers: could not read DNS records for ${h} (${di(y)}); attaching anyway.`),[]}}function pp(u,g){let h=[],y=new Set,R=(P)=>{if(P===xn)return g.warnings.push(`Workers: ${u.name}: binding name ${xn} is reserved for ts-cloud, ignored.`),!1;if(y.has(P))return g.warnings.push(`Workers: ${u.name}: binding ${P} is declared twice; the first one wins.`),!1;return y.add(P),!0},v=new Map;for(let P of Object.values(g.r2Buckets?.buckets??{}))if(P.jurisdiction&&P.jurisdiction!=="default")v.set(P.name,P.jurisdiction);for(let[P,L]of Object.entries(u.bindings?.r2Buckets??{})){if(!R(P))continue;let z=v.get(L);h.push(z?{type:"r2_bucket",name:P,bucket_name:L,jurisdiction:z}:{type:"r2_bucket",name:P,bucket_name:L})}for(let[P,L]of Object.entries(u.bindings?.vars??{}))if(R(P))h.push({type:"plain_text",name:P,text:String(L)});return h}function Hh(u){let g=new Map;for(let h of Object.values(u?.buckets??{}))for(let y of h?.customDomains??[]){let R=mp(typeof y==="string"?y:y.domain);if(R)g.set(R,h.name)}return g}function Uh(u){return[...new Set((u??[]).map(mp).filter(Boolean))]}function mp(u){return(u??"").trim().replace(/\.$/,"").toLowerCase()}function Gh(u){if(u<1024)return`${u} B`;if(u<1048576)return`${(u/1024).toFixed(1)} KB`;return`${(u/1024/1024).toFixed(1)} MB`}function di(u){return u instanceof Error?u.message:String(u)}export{Pl as ABTestManager,Ie as ACMClient,xr as ACMDnsValidator,ud as ACME_DIRECTORIES,Oe as AI,gu as API_IDEMPOTENCY_TTL_MS,lu as API_TOKEN_DEFAULT_TTL_MS,uu as API_TOKEN_MAX_TTL_MS,ms as API_VERSION,Ce as AUTHORIZATION_CAPABILITIES,ou as AUTH_ACTION_TOKEN_TTL_MS,au as AUTH_MFA_CHALLENGE_TTL_MS,cu as AUTH_OIDC_TRANSACTION_TTL_MS,ot as AUTH_SESSION_ABSOLUTE_TTL_MS,su as AUTH_SESSION_IDLE_TTL_MS,vy as AWSAPIError,n as AWSClient,A as AWSCloudFormationClient,I as AWSCloudFrontClient,Tl as AWSConfigManager,XI as AWS_PSEUDO_PARAMETERS,_e as AWS_REGIONS,Lg as AcmeClient,sn as AlertEvaluator,Gi as AlertStore,Bo as AnomalyConfigStore,ml as ApiGateway,i as ApiServiceError,Tc as ApplicationAutoScalingClient,gn as Arn,_ as AssetHasher,Y as Auth,ds as AuthenticationStore,Ki as AutomationApiService,ls as AutomationIdentityStore,xa as AwsAuroraDataAdapter,Ma as AwsAuroraTransport,rc as AwsDatabaseBackupSource,$r as AwsDriver,Oa as AwsElastiCacheDataAdapter,Fa as AwsElastiCacheTransport,eh as AwsIamCapabilityScanner,ac as AwsInfrastructureBackupSource,Ba as AwsRdsDataAdapter,$a as AwsRdsTransport,ph as AwsRegionalDriver,dc as AwsSecretsManagerConfigurationBackend,hm as AwsSpendTransport,lc as AwsSsmConfigurationBackend,Ts as BackupCoordinator,El as BackupManager,ec as BackupStore,Pf as BatchProcessingManager,Gn as BedrockClient,Hn as BedrockRuntimeClient,Su as BitbucketSourceAdapter,Dl as BlueGreenManager,Sf as BounceComplaintHandler,lf as BuildOptimizationManager,Qu as BunDockerRuntime,Ag as BunDockerVolumeRuntime,hg as BunFilesystemArchiveRuntime,Ee as CDN,Xo as CHAIN_HEADER,Kt as CLOUDFLARE_MANAGED_RULE_PREFIX,dl as CLOUDFRONT_FAILOVER_STATUS_CODES,$C as COMMON_CROSS_ACCOUNT_ROLES,xn as CONTENT_HASH_BINDING,Je as CONTROL_PLANE_SCHEMA_VERSION,qo as Cache,rs as CanaryManager,af as CertificateManager,_A as CloudBlockVolumeDriver,so as CloudDriverFactory,nt as CloudError,xm as CloudFormationBuilder,A as CloudFormationClient,I as CloudFrontClient,wl as CloudTrailManager,Re as CloudWatchLogsClient,pd as CloudflarePagesProvider,H as CloudflareProvider,qy as CommandHistory,ee as Communication,Zr as ComposeApplicationService,or as ComposeApplicationStore,Gt as ComprehendClient,a as Compute,Am as ComputeSpendTransport,Ko as ConfigurationError,gc as ConfigurationService,cc as ConfigurationStore,Un as ConnectClient,La as ContainerDataAdapter,Ol as ContainerRegistryManager,oc as ControlPlaneBackupSource,Ja as ControlPlaneCleanupDriver,Li as ControlPlaneStore,Po as CounterTracker,Ot as CredentialError,Km as CrossRegionReferenceManager,ly as DASHBOARD_ENTRY,uy as DASHBOARD_PORT_BASE,gy as DASHBOARD_PORT_SPAN,dy as DASHBOARD_STATE_DIR,oa as DEFAULT_ATTACK_MODE_HOURS,no as DEFAULT_COMPATIBILITY_DATE,Yd as DEFAULT_DDOS_THRESHOLDS,bm as DEFAULT_FAILOVER_STATUS_CODES,xd as DEFAULT_METER_MAPPINGS,Nd as DEFAULT_PRICE_BOOK,fn as DEFAULT_RECURSION_LIMITS,go as DEFAULT_RPX_CERTS_DIR,te as DEFAULT_SERVICE_LIMITS,rl as DEFAULT_STATE_DIR,kg as DEFAULT_STATIC_ASSET_EXTENSIONS,sy as DEFAULT_STORAGE_FAILOVER_STATUS_CODES,KA as DEFAULT_TELEMETRY_POLICY,em as DEFAULT_THRESHOLDS,kA as DEPLOYMENT_QUEUE_KINDS,Jo as DEPTH_HEADER,rn as DETECTABLE_SIGNALS,Lu as DIAGNOSTIC_PRESETS,Df as DLQMonitoringManager,W as DNS,Af as DNSSECManager,ys as DataServiceLifecycle,Na as DataServiceStore,ur as Database,sf as DatabaseUserManager,q as DebugLogger,iy as DependencyGraph,Z as Deployment,Ey as DeploymentError,vl as DisasterRecoveryManager,Xn as DnsProviderFactory,Ir as DockerDataTransport,Ta as DockerDiscoveryAdapter,Yr as DockerNamedVolumeDriver,sc as DockerVolumeBackupSource,c as DurableOperationQueue,Co as DurableQueueWorker,Ue as DynamoDBClient,qr as EC2Client,He as ECRClient,ut as ECSClient,Pr as EFSClient,bc as ELBv2Client,$A as ENFORCEMENT_ACTIONS,Qi as ENFORCEMENT_DESCRIPTIONS,O as ENFORCEMENT_SEVERITY,Dp as ENVIRONMENT_LABEL,Ou as EcsRuntimeAdapter,sa as EdgeRateLimiter,pt as ElastiCacheClient,f as Email,Ef as EmailAdvanced,If as EmailAnalyticsManager,zn as EmailClient,vf as EmailHandlers,Cf as EmailTemplateManager,Ua as EncryptedDataSecretStore,Ty as ErrorCodes,Rr as EventBridgeClient,lh as EventBridgeJobAdapter,uc as ExternalConfigurationBackend,Vo as FAILOVER_REPLICA_POLICY_SID,Rf as FIFOQueueManager,jh as FLY_MACHINES_API,cm as FOCUS_VERSION,Al as FileCache,tt as FileSystem,nc as FilesystemBackupSource,Ha as FleetService,Qa as FleetStore,Cs as FlyApiError,hp as FlyClient,e as Fn,Iu as GiteaSourceAdapter,Au as GithubSourceAdapter,yu as GitlabSourceAdapter,Wm as GlobalResourceManager,Ge as GoDaddyProvider,Rl as GuardDutyManager,Tt as HOST_SITES_DIR,Py as HashCache,Qf as HealthCheckManager,Ye as HealthCheckRunner,Hr as HetznerClient,Pe as HetznerDriver,De as IAMClient,_c as IPV6_EXCLUDED_HOST_LABELS,df as ImageScanningManager,vp as InfrastructureGenerator,Id as InvalidOperationTransitionError,Bt as JobLoader,uh as JobProviderReconciler,Pa as JobService,ka as JobStore,wr as KendraClient,Ff as LARAVEL_SERVERLESS_BUILD_STEPS,T as LambdaClient,pf as LambdaConcurrencyManager,hf as LambdaDLQManager,mf as LambdaDestinationsManager,uf as LambdaLayersManager,_u as LambdaRuntimeAdapter,ff as LambdaVPCManager,gf as LambdaVersionsManager,On as LocalEncryptedConfigurationBackend,ic as LogicalDatabaseBackupSource,Nl as LogsManager,gS as MANAGED_NODE_VERSIONS,id as MANAGEMENT_DASHBOARD_SITE,Om as MANAGEMENT_DASHBOARD_SITE_PREFIX,as as MAX_CONTROL_HOURS,bd as MAX_CONTROL_PLANE_ERROR_BYTES,Wp as MAX_CONTROL_PLANE_JSON_BYTES,wo as METERS,LA as METER_KEYS,MA as MICRO_CENTS,tm as MIN_PROJECTION_CONFIDENCE,_g as MTA_STS_PORT,Wa as MaintenanceService,Ka as MaintenanceStore,ge as Messaging,tf as MetricsManager,rf as MigrationManager,Gm as MockCloudFormation,qm as MockDynamoDB,Vm as MockS3,jo as Monitoring,Ym as MultiAccountManager,zm as MultiRegionManager,Fy as MultiStepProgress,S as Network,Hf as NetworkSecurityManager,Vi as NotificationRouter,vm as ORIGIN_CONNECTION_ATTEMPTS,Tm as ORIGIN_CONNECTION_TIMEOUT,Cm as ORIGIN_GROUP_ALLOWED_METHODS,KI as ORIGIN_GROUP_ID_SUFFIX,Em as ORIGIN_GROUP_SELECTION_CRITERIA,Cc as OpenSearchClient,wt as OptimisticConcurrencyError,Zm as OrganizationManager,Hg as PAGES_MAX_FILE_BYTES,CS as PHP_DEFAULT_EXCLUDES,pS as PHP_LAYER_EXTENSIONS,Rp as PROJECT_LABEL,ft as PROXIABLE_RECORD_TYPES,D as ParameterStore,nf as PerformanceManager,ue as Permissions,Ec as PersonalizeClient,rt as Phone,Tf as PhoneAdvanced,Nm as PhoneHandlers,Va as PlacementService,Ga as PlacementStore,Vn as PollyClient,ye as PorkbunProvider,En as PreDeployScanner,bl as PreviewEnvironmentManager,Xr as PreviewEnvironmentService,Xe as PreviewEnvironmentStore,Cl as PreviewNotificationService,My as ProgressBar,kl as ProgressiveDeploymentManager,aa as ProtectionControlStore,ny as Pseudo,J as Queue,$i as QueueCancellationError,kf as QueueManagementManager,$I as QueuePresets,bo as QueueTimeoutError,Fn as R2ApiError,An as R2NotEnabledError,ai as R2Provider,np as R2_NOT_ENABLED_ERROR_CODE,Jl as RATE_LIMIT_KEY_SEPARATOR,ne as RDSClient,zy as RECOMMENDED_ACCOUNT_STRUCTURES,LC as RECOMMENDED_SCPS,Jf as RELEASE_QUEUE_KINDS,Hy as REPL,Vy as REPLCommandBuilder,Gy as REPLContext,Pp as ROLE_LABEL,ky as RateLimiter,MI as RealtimePresets,dm as RecordingSpendTransport,is as RecursionGuard,xt as Redirects,Jm as RegionPairManager,ja as RegionService,qa as RegionStore,et as Registry,Vt as RekognitionClient,_t as ReleaseService,ha as ReleaseStore,gh as RemoteBuildService,Bl as ReplicaManager,Gf as ResourceManagementManager,ce as RetryableOperationError,C as Route53Client,Ic as Route53DomainsClient,ie as Route53Provider,yf as Route53ResolverManager,Ll as Route53RoutingManager,Te as RuntimeOperationService,Ra as RuntimeStreamRegistry,tc as S3BackupDestinationAdapter,o as S3Client,V as S3Error,Eu as SECRET_PATTERNS,om as SENSITIVITY_THRESHOLDS,mt as SESClient,X as SMS,gt as SNSClient,fm as SPEND_CYCLE_SECONDS,jd as SPEND_GATE_SETTING,YA as SPEND_LEASE_SETTING,fe as SQSClient,ke as SSH_BOOTSTRAP_VERSION,hi as SSH_PREFLIGHT_SCRIPT,Be as SSMClient,Sm as STATE_DIR_ENV_VAR,wi as STATIC_SITE_ZONE_SETTINGS,ul as STORAGE_FAILOVER_METADATA_KEY,we as STSClient,qn as SchedulerClient,gr as Search,vn as SecretFindingScanner,Yi as Secrets,xl as SecretsManager,re as SecretsManagerClient,of as SecretsRotationManager,E as Security,fr as SecurityHubManager,Cn as SecurityPostureStore,Lt as SecurityScannerRunner,cf as SecurityScanningManager,bf as SenderReputationManager,dh as ServerCronJobAdapter,_a as ServerDataAdapter,To as ServerPathVolumeDriver,_l as ServiceMeshManager,pl as Sftp,Oo as SignalSource,wf as SmsAdvanced,jt as SmsClient,Bm as SmsHandlers,Dc as SmsVoiceClient,Aa as SourceConnectionStore,yr as SourceProviderError,zd as SpendCapError,nn as SpendGate,pm as SpendLoopLease,Fo as SpendNotificationRouter,mm as SpendRunner,cr as SpendService,Fi as SpendStore,Uy as Spinner,Gr as SshDriver,Rn as SshFleetDriver,Xm as StackDependencyManager,JI as StacksIntegration,Uf as StaticSiteManager,xe as Storage,zl as StorageAdvancedManager,jn as SupportClient,hr as SyntheticsManager,Hu as SystemFleetSshTransport,bt as SystemSshTransport,wa as SystemdDiscoveryAdapter,Yo as TRACE_HEADER,Qy as TaskList,Pt as TelemetryStore,al as TemplateBuilder,yl as TemplateCache,qt as TextractClient,Qn as TranscribeClient,Tr as TranslateClient,hh as TransportDisasterRecoveryDriver,fh as TransportPlatformMaintenanceDriver,Ss as TransportRemoteBuildDriver,Ea as TrivyImageScanner,fa as TsCloudApiError,pu as TsCloudClient,XA as URGENT_SPEND_EVENTS,rm as USER_VISIBLE_ACTIONS,za as UnavailableRegionalDriver,Se as UnifiedDnsValidator,yo as UnsupportedSchemaVersionError,Mm as ValidationError,Dr as VoiceClient,vo as VolumeService,sr as VolumeStore,Zc as WORKER_MODULE_TYPE,li as WorkersApiError,Ms as WorkersPermissionError,Bs as WorkersProvider,cy as Workflow,ef as XRayManager,rS as abTestManager,mu as activateImmutableRelease,Tg as addDns01ChallengeRecord,Pn as addSiteToCloudConfig,Mt as ageSeconds,_d as aggregateDeltas,jp as allocateSitePorts,km as amazonLinuxImageId,ay as amazonLinuxImageParameter,jI as analyzeStackDiff,Hi as anomalyOptionsForSignal,ca as applyControlsToDdos,tu as applyControlsToRateLimits,Vs as applyDeclaredZoneSettings,gi as applyHetznerVolumes,cn as applyMitigationFactor,uA as applyPlan,Ks as applyZoneMigration,$l as artifactKey,ru as assertComputeResidency,kt as assertOriginGroupMethods,us as assertReleaseStrategy,zA as assertSpendAllows,hA as attachConflicts,AA as attachIsViable,fA as attachPreconditions,Du as attachProvenanceToRelease,va as attachSbomToRelease,wu as attachVulnerabilitySummary,Kf as authEncryptionKeyFile,x as authorizeOrganization,ah as authorizeRuntimePath,gC as autocomplete,Jy as awsConfigManager,mg as backupCredentialStatus,Ky as backupManager,$b as batch,RE as batchProcessingManager,pa as beginOidcAuthorization,eS as blueGreenManager,bE as bounceComplaintHandler,Rt as budgetWindow,Ac as buildAndPushServerlessImage,kE as buildBunRuntimeLayerZip,EA as buildCertificatePackScript,IA as buildCertificateStateScript,vA as buildCertificateUnpackScript,fl as buildCloudFormationTemplate,Yc as buildCloudInitFirstBoot,Td as buildComposeLogsCommand,_I as buildComposeRuntimeCommand,LI as buildComposeScaleCommand,wd as buildComposeShellCommand,ti as buildComputeStorageInstallScript,Mr as buildComputeStorageSiteScript,Gp as buildDrainSourceScript,rA as buildDrainedSiteScanScript,gl as buildFailoverReplicaPolicyStatement,Cr as buildFunctionEnv,Hp as buildHealthGateScript,ni as buildHostCleanupDeployScript,to as buildHostCleanupInstallScript,ri as buildHostCleanupScript,Oi as buildHostSitePortsScript,Ji as buildMailEnv,co as buildManagementDashboardArtifact,JS as buildMediaCdnPlan,Og as buildMtaStsPolicy,Fh as buildMtaStsServer,PE as buildNodeRuntimeLayerZip,gE as buildOptimizationManager,ll as buildOriginGroup,un as buildOriginGroups,Nc as buildOriginGuardRule,_p as buildPauseWorkersScript,OE as buildPhpRuntimeLayerZip,Pm as buildReplicationConfiguration,Dm as buildReplicationRole,Fp as buildRestoreScript,B as buildRpxConfig,Ne as buildRpxFragmentRefreshScript,pA as buildSetHostnameScript,si as buildSiteDeployScript,Mp as buildSnapshotScript,Vp as buildSourceStateScript,ci as buildSshArgs,mi as buildSshBootstrapScript,kc as buildStaticSiteCacheRules,oi as buildStaticSiteDeployScript,Up as buildTargetStateScript,up as buildUploadForm,Lp as buildWorkersStateScript,Jc as bundleWorker,ku as bytes,op as cacheRuleParameters,tS as canaryManager,Dn as canonicalJson,$t as capabilities,br as capacity,jb as categorizeChanges,dE as certificateManager,CA as certificatesMatch,Rb as checkIAMPermissions,_f as checkInvocation,Pb as checkServiceQuotas,Ny as chunk,gR as cleanupDns01Challenge,PS as clearSigningKeyCache,Sa as cloneSourceBinding,By as cloudConfigSchema,ap as cloudDrivers,Xy as cloudTrailManager,ep as collectAssets,ra as collectPhpAppEntries,Ng as collectServerDnsDomains,Jp as completeComposeVolumeDeletion,ma as completeOidcAuthorization,fb as composePresets,Io as composeProjectName,Fl as composeServerlessAppTemplate,ey as compositeSpendTransport,Ht as compressBackup,LS as config,Pc as configOrigins,Fu as connectionGuidance,cS as containerRegistryManager,DA as controlPlaneDatabaseFile,yd as controlPlaneMigrations,nb as createApiBackendPreset,Ca as createApiV1Handler,qS as createAsgBuildDriver,fg as createBackupQueueHandlers,bS as createCliHandler,F as createCloudDriver,td as createCloudFrontPolicy,Eb as createCredentialProvider,pb as createDashboardSite,cb as createDataPipelinePreset,Uu as createDataServiceQueueHandlers,Rd as createDeploymentQueueHandlers,N as createDnsProvider,VS as createEcsBuildDriver,Kd as createEnforcementHandlers,Fm as createError,hl as createExistingStaticFullStackPreset,Gu as createFleetQueueHandlers,rb as createFullStackAppPreset,Xs as createGoDaddyValidator,xE as createHandlers,SS as createHttpHandler,sb as createJamstackPreset,Mu as createJobQueueHandlers,ub as createLaravelPreset,db as createMLApiPreset,Ju as createMaintenanceQueueHandlers,jS as createMediaAccessToken,ob as createMicroservicesPreset,eC as createMockAWS,ZI as createNodeJsServerPreset,eb as createNodeJsServerlessPreset,Ls as createObjectStorageClient,Js as createPorkbunValidator,hb as createPreset,na as createPresignedUrl,vS as createPresignedUrlAsync,IS as createQueueHandler,ab as createRealtimeAppPreset,qu as createRegionQueueHandlers,Ru as createReleaseProvenance,hu as createReleaseQueueHandlers,HS as createRemoteBuildQueueHandlers,Ys as createRoute53Validator,oh as createRuntimeAdapters,Cy as createS3Client,GS as createServerBuildDriver,gb as createServerlessLaravelPreset,tb as createServerlessNodePreset,Pg as createSmsInfrastructure,ct as createSourceAdapter,YI as createStaticSitePreset,lb as createTraditionalWebAppPreset,Dd as createVolumeQueueHandlers,ib as createWordPressPreset,it as createZip,IC as crossRegionReferenceManager,_n as dashboardActions,ao as dashboardCredentialsFile,wn as dataServiceCapabilities,aE as databaseUserManager,iu as decodeBase32,Fe as decompressBackup,wh as decryptBackup,da as defaultConfig,Hm as defaultLocalConfig,Yl as defaultRateLimitRules,Br as delegateZone,Hs as delegateZoneFromConfig,lg as deleteFailoverReplicaBuckets,fc as deleteStaticSite,od as deployAllComputeSites,Ya as deployServerlessApp,ug as deploySite,lo as deploySiteRelease,Ps as deployStaticSite,hc as deployStaticSiteFull,Ln as deployStaticSiteWithExternalDns,$n as deployStaticSiteWithExternalDnsFull,Jh as deployToFly,ol as deploymentCoexistenceError,py as deriveManagementDashboardPort,Gs as describeDelegation,eu as describePosture,qs as describeZoneSettings,ch as desiredJobProviderState,sm as detectAnomalies,Im as detectDeploymentTargets,Bc as detectDnsProvider,Gd as detectLatestAnomaly,Tb as detectMisconfigurations,Kl as detectServiceRegion,Ed as diffCompose,Gb as diffTemplates,ya as discoverGitRefs,ga as discoverOidcProvider,Nu as discoverRuntimeInventory,wE as dlqMonitoringManager,xc as dnsProviders,SE as dnssecManager,nh as dockerWorkloads,Is as documentDigest,jc as domainStatus,Wy as drManager,je as driverStatePath,Bu as ecsWorkloads,ir as effectiveCapabilities,CE as emailAnalyticsManager,vE as emailTemplateManager,cs as encodeBase32,Th as encryptBackup,Pu as ensureDefaultSecurityPolicies,ag as ensureFailoverReplicaBuckets,Ei as ensureFirewall,Ri as ensureManagementDashboard,vi as ensureServer,Ci as ensureSshKey,ae as escapeSecLang,$d as evaluateBudget,yi as evaluatePreflight,Mo as evaluateTelemetryAlertRules,$u as eventBridgeScheduleInput,yS as eventToRequest,VA as ewma,Cd as exportCompose,js as exportRoute53Zone,Lm as extendPreset,TE as fifoQueueManager,Lb as findChangedFiles,Yp as findMapping,Xp as findPriceEntry,Zh as flyDeployOptions,Qc as flyIpType,Cp as flyMachineConfig,QC as formatAccountStructure,yA as formatAttachPlan,iC as formatBytes,on as formatCents,zI as formatDiff,iA as formatDrainedSiteRefusal,sC as formatDuration,mC as formatFlagSuggestions,AC as formatHistory,yC as formatHistoryStats,cA as formatInventory,aC as formatKeyValue,oC as formatList,lA as formatPlan,Ii as formatPreflightFindings,nC as formatProgressBar,jy as formatRegion,BC as formatRegionList,Zf as formatScanResults,cC as formatSuggestion,tC as formatTable,tn as formatTimeToExhaustion,rC as formatTree,yy as fromEC2Metadata,Sy as fromECSMetadata,hy as fromEnvironment,Ay as fromSharedCredentials,Iy as fromWebIdentity,Hl as functionFingerprint,fo as gatewayHostnames,Ql as generateAppImageDockerfile,tE as generateApprovalConfig,Nf as generateBootstrap,_y as generateCleanupWorkflow,Ly as generateCostReportWorkflow,FC as generateCrossAccountRoleCF,vu as generateCycloneDxSbom,YC as generateDeploymentConfig,zC as generateDeploymentPipeline,HC as generateDeploymentWorkflow,mc as generateExternalDnsStaticSiteTemplate,pR as generateHttpsServerCode,Tu as generateImageSbom,dR as generateLetsEncryptUserData,t as generateLogicalId,XC as generateManualPipeline,jC as generateMatrixWorkflow,ZC as generateMultiEnvConfig,KC as generateMultiEnvPipeline,GC as generateMultiEnvWorkflow,VC as generatePRPreviewWorkflow,rE as generateParallelConfig,Mf as generatePhpFpmConfig,Bf as generatePhpLayerDockerfile,WC as generatePreviewPipeline,Oy as generatePreviewWorkflow,r as generateResourceName,eE as generateScheduledConfig,JC as generateScheduledPipeline,qC as generateScheduledWorkflow,Ds as generateStaticSiteTemplate,M as generateUbuntuAppCloudInit,$m as getAccountId,vC as getAllRegions,PC as getClosestRegion,fC as getCommandUsage,PA as getComposeTemplate,qf as getConfig,lC as getContextualHelp,es as getCredentials,zb as getDeploymentStrategy,Kb as getDiffStats,Vb as getDiffSummary,wy as getErrorDetails,Il as getLocalConfig,Yb as getLocalCredentials,Xb as getLocalEndpoint,Zb as getLocalEnvVars,kb as getQuotaUsageSummary,MC as getRecommendedStructure,ts as getRegion,xC as getRegionStats,wC as getRegionsByCompliance,TC as getRegionsByLocation,RC as getRegionsByPricingTier,Ry as getRequiredPermissions,kS as getSigningKeyCacheSize,Dg as getSmsInfrastructureStatus,FI as getTimestamp,ia as globMatches,uo as globToRegex,bC as globalResourceManager,Ui as governingLimitCents,cg as grantFailoverReplicaAccess,Yy as guardDutyManager,Uo as handleSpendRequest,mo as hasAutoWwwVariant,pr as hasManagementDashboardSite,Ad as hasProxyUpstream,Bb as hashBuffer,xb as hashDirectory,Um as hashFile,Ob as hashManifest,Qm as hashString,LE as healthCheckManager,Yn as hostAcceptsIpv6,zt as hostCondition,la as hotp,en as hourBucket,GA as hourBucketsBetween,uE as imageScanningManager,Es as infraEnvFromOutputs,Vl as inspectInvocation,hS as installRecursionFetch,Ns as invalidateCache,Of as invocationContext,oy as isArmInstanceType,dC as isLikelyTypo,_r as isLocalDatabase,Jb as isLocalDevelopment,mr as isManagementDashboardSiteName,kr as isNameserverRegistrar,NS as isNodeCryptoAvailable,Hd as isOperationAllowed,$o as isQuietHours,Go as isS3RestEndpoint,Pi as isSafePattern,il as isStateDirConfigured,sl as isStatePath,an as isValidCidr,DC as isValidRegion,Mi as isValidTimeZone,BS as isWebCryptoAvailable,Nr as isZoneHost,Tn as jobProviderCapability,_s as keyMatchesFilters,fE as lambdaConcurrencyManager,yE as lambdaDLQManager,hE as lambdaDestinationsManager,pE as lambdaLayersManager,AE as lambdaVPCManager,mE as lambdaVersionsManager,xu as lambdaWorkloads,ql as laravelServerlessEnvDefaults,Jr as listComposeTemplates,ps as listSourceReferences,nu as loadCloudConfig,dr as loadTelemetryPolicy,iS as logsManager,Vd as lookbackHoursForSignal,ry as mailEnabled,Ze as mailFirewallPorts,ln as mailWebmailSites,mh as maintenanceWindowOpen,Vf as makeAWSRequest,wS as makeAWSRequestAsync,TS as makeAWSRequestOnce,sp as managedRuleInSync,_m as managementDashboardSiteName,ju as manifestDigest,yn as matchTotpCounter,ZS as mediaObjectHeaders,No as median,nm as medianAbsoluteDeviation,Md as mergeDecisions,pn as mergeInfrastructure,QA as mergePriceBooks,Od as meterTelemetry,iE as metricsManager,Eg as migrateObjectStorage,sE as migrationManager,OC as multiAccountManager,SC as multiRegionManager,fR as needsRenewal,$E as networkSecurityManager,Ft as nextScheduleRuns,se as normalizePublicIpv6,Le as normalizeRuntimeStatus,dt as normalizeScheduleExpression,Xf as normalizeSourceEvent,qe as normalizeSshPublicKey,lm as normalizeTelemetryPolicy,xi as occupiedHostPorts,ba as openApiDocument,_o as optionsForSignal,_C as organizationManager,jl as packagePhpApp,mn as packageServerlessApp,gd as pagesAssetHash,Gg as pagesDnsRecord,Sl as parallel,Mb as parallelMap,Fb as parallelWithRetry,bA as parseCertificateState,Gl as parseChain,Wr as parseCompose,xI as parseComposeCatalog,rh as parseDockerInspect,yg as parseDotenv,nA as parseDrainedSites,_i as parseHostSiteFragments,DS as parseJSONResponse,Ai as parsePreflightFacts,qp as parseSourceDrained,ih as parseSystemdRecords,Qp as parseTargetReady,hd as parseUpstreamPort,$p as parseWorkersPaused,RS as parseXMLResponse,ji as pathTemplate,md as pendingSteps,ko as percentOfLimit,oE as performanceManager,Ul as phpLayerBuildStage,mS as phpLayerPackages,hn as phpRuntimeLayerAssets,OI as planComposeTemplateUpgrade,Fd as planEnforcement,ui as planHetznerVolumes,xp as planIsDestructive,ym as planMitigation,gA as planServerRename,TA as planSiteMove,zs as planZoneMigration,Jt as policyTag,Si as preflightFailed,xy as previewManager,$y as previewNotifications,Ut as previewSchedule,HA as previousBudgetWindow,Ro as priceUsage,FA as priceUsageLines,oA as probeHostRoutes,zc as probeOriginTls,Hb as processInChunks,bu as processSourceWebhook,hs as productionChangeReview,nS as progressiveDeploymentManager,Ld as projectSpend,Zo as propagationHeaders,yc as providerEndpoint,zu as publicKeyFingerprint,Wn as qualifyName,DE as queueManagementManager,_b as quickHash,ip as r2Endpoint,Jg as r2S3Credentials,Xl as rateLimitHeaders,os as rateLimitKey,ze as readDriverState,aA as reconcile,xg as reconcileAddressRecords,Wg as reconcileCloudflareCdn,_h as reconcileCloudflareWorkers,Qs as reconcileDeclaredRecords,QS as reconcileJobObservation,Qg as reconcileR2Buckets,bn as reconcileSourceWebhook,fs as recordDashboardHostPosture,MS as recordPreDeploySecretScan,FS as recordSkippedSecretScan,ea as recursionBlockedResponse,$e as redactRuntimeConfig,Xd as redactTelemetryText,qi as redactTelemetryValue,Nn as redeployServerlessApp,CC as regionPairManager,In as releaseStrategyCapabilities,Wf as releaseTrafficPlan,Di as reloadRpxGateway,Os as remapKey,Bg as removeAddressRecords,$g as removeDns01ChallengeRecord,kn as removeSiteFromCloudConfig,Cu as removeSourceWebhook,Oc as removeStaleServerAddressRecords,vd as renderComposeTemplate,Wi as renderDdosInstallScript,tl as renderNftablesRuleset,As as renderServerCron,el as renderSysctlFile,cd as renderWafConfig,ki as renderWafInstallScript,ad as renewRpxCertificates,oS as replicaManager,ty as requestHash,qb as requiresReplacement,NE as resetRecursionRuntime,BE as resolveApp,p as resolveAppDatabase,mA as resolveAttachTarget,at as resolveAuthEncryptionKey,de as resolveCloudProvider,zg as resolveCloudflareCdnPlan,ei as resolveComputeVolumes,zo as resolveCredentials,Rs as resolveDashboardAction,sd as resolveDashboardAuth,my as resolveDashboardDomain,fy as resolveDashboardDomains,Us as resolveDeclaredRecords,qI as resolveDeployBucketName,K as resolveDeploymentMode,ii as resolveExecStart,Ho as resolveFailoverStatusCodes,Gc as resolveHetznerApiToken,Ur as resolveHostCleanupConfig,w as resolveMailProxy,b as resolveMailService,mb as resolveManagementDashboardSite,Zi as resolveManagementDashboardSites,Sc as resolveObjectStorage,le as resolveOriginConnection,dA as resolvePlan,m as resolveProjectStackName,Kr as resolveProxyUpstreams,Ml as resolveQueueNames,NA as resolveQueuedDeploymentCommand,Ar as resolveQueues,fS as resolveRecursionConfig,by as resolveRegion,me as resolveRuntimeInventory,lr as resolveServerlessAppStackName,cl as resolveServerlessArtifactBucketName,Xi as resolveServerlessAssetBucketName,ns as resolveServerlessRuntime,GI as resolveSiteBucketName,Ao as resolveSiteDeployTarget,d as resolveSiteKind,HI as resolveSiteResourceName,QI as resolveSiteStackName,fi as resolveSshSettings,l as resolveStatePath,VI as resolveStorageBucketName,wm as resolveStorageFailover,tr as resolveUiSource,dd as resolveZoneApex,ME as resourceManagementManager,$f as responseToResult,im as robustZScore,nr as roleCapabilities,fu as rollbackImmutableRelease,Bn as rollbackServerlessApp,UA as roundCents,IE as route53ResolverManager,lS as route53RoutingManager,am as routeMatches,kp as routesFromFragments,ss as ruleMatches,uS as runBuildHooks,Ud as runEnforcement,ta as runPhpBuildHooks,lt as runRemoteCommand,ve as runtimeId,Qe as s3OriginBucket,Rm as s3RegionalDomain,vs as sameCorsRules,xs as sameLifecycleRules,Jn as sameNameservers,ws as sanitizeCloudConfig,s as sanitizeControlPlaneValue,UI as sanitizeName,du as sanitizeOidcReturnPath,Wd as saveTelemetryPolicy,Yf as scanForSecrets,Sd as scopeContains,Dt as scopeKey,Fc as scpUpload,uC as searchCommands,So as searchControlPlane,aS as secretsManager,cE as secretsRotationManager,US as secureContainerRelease,Zy as securityHubManager,lE as securityScanningManager,pe as securityScope,dg as seedFailoverReplicas,Sn as sendAuthenticationEmail,EE as senderReputationManager,Ub as sequence,Sg as serializeDotenv,Ti as serverPublicIpv4,dS as serviceMeshManager,ng as setAttachToInCloudConfig,Er as setMaintenance,bs as setSitePropertyInCloudConfig,nl as setStateDir,mR as setupDns01Challenge,Rc as setupSmsInfrastructure,Wo as sha256,AS as sharedRecursionGuard,xf as sharedRuntimeLoop,Kp as shipsARelease,zS as signCloudFrontCookies,WS as signCloudFrontUrl,k as signRequest,Wl as signRequestAsync,xo as signalDefinition,U as siteInstallBase,Bi as siteMoveArchivePath,SA as siteMoveCertArchivePath,fd as siteUnitGlob,gm as spendNotificationText,Qo as spendOpenApiPaths,Qr as sshExec,be as sshExecOrThrow,EC as stackDependencyManager,pc as startLocalDashboardServer,ZA as startSpendLoop,dn as stateDir,Q as statePath,_E as staticSiteManager,ES as storageAdvancedManager,WI as storageFailoverReplicasFromTemplate,qA as streamFocusJsonl,Qd as strongestActiveAction,jm as suggestCommand,pC as suggestFlags,Db as suggestIAMPolicy,Nb as suggestQuotaIncrease,NC as suggestRegionPairs,kC as suggestRegions,gs as syncSourceRepositories,Pd as synchronizeComposeVolumes,Ig as synchronizeConfiguredConfiguration,Da as synchronizeConfiguredJobs,sS as syntheticsManager,Zd as sysctlHardening,sh as systemdWorkloads,JA as telemetryBucketLabel,zi as telemetryCursor,Jd as telemetryEstimatedMonthlyCost,WA as telemetryPercentile,um as telemetryPolicyKey,Dy as templateCache,Np as tenantsOf,Ia as testSourceConnection,kd as tieredMicroCents,cp as toApiLifecycleRule,Vc as toCloudflareZoneSettings,Lo as toFocusJsonl,qd as toFocusRecords,sA as toInventoryServer,jf as totp,ua as totpUri,Bp as unaccountedSites,th as unsupportedCapabilities,BA as unsupportedVolumeCapabilities,Wu as updateCompatibility,Xu as updateSiteInCloudConfig,ks as uploadStaticFiles,Zp as usageDeltaKey,ar as utcInstantOfLocal,UC as validateAccountStructure,Wb as validateAgainstSchema,OA as validateAttachment,vh as validateBackupDestination,hC as validateCommand,vb as validateConfiguration,wb as validateCredentials,zp as validateDeploymentConfig,xA as validateMountPath,Nt as validateOriginGroups,sg as validateResourceLimits,Op as validateServerName,Ep as validateTemplate,og as validateTemplateSize,Lc as verifyAddressRecord,$S as verifyArtifactSignature,KS as verifyMediaAccessToken,zf as verifyTotp,Ku as verifyUpdateSignature,Ws as verifyZoneParity,Eo as volumeCapabilities,bp as wafEventTelemetry,Uc as waitForCloudInit,At as waitForSsh,Sr as webhookEndpoint,bb as withCDN,Ib as withCache,dp as withContentHash,Sb as withDatabase,Lf as withInvocation,Ab as withMonitoring,Cb as withQueue,yb as withSecurity,Qb as withTimeout,pp as workerBindings,io as workerContentHash,Zs as workerInSync,oe as wrapCloudInitUserData,St as writeDriverState,nE as xrayManager,Vu as zeroCapacity,jA as zeroFill,Bd as zoneOffsetMs,Do as zonedParts};