@stacksjs/ts-cloud 0.16.80 → 0.16.82

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/{chunk-nbffypj8.js → chunk-08sws53b.js} +3 -3
  3. package/dist/bin/{chunk-6xx24qev.js → chunk-19mhwmfp.js} +1 -1
  4. package/dist/bin/chunk-1qez75tb.js +1 -0
  5. package/dist/bin/chunk-1rrmswhq.js +1 -0
  6. package/dist/bin/{chunk-gqstb8zn.js → chunk-1wgyq50e.js} +1 -1
  7. package/dist/bin/{chunk-0r8k7qth.js → chunk-20rfyk4x.js} +4 -4
  8. package/dist/bin/{chunk-jhydr9dp.js → chunk-33xqndrp.js} +91 -90
  9. package/dist/bin/{chunk-rdqcr78z.js → chunk-35325988.js} +2 -2
  10. package/dist/bin/chunk-3rjer1mp.js +1 -0
  11. package/dist/bin/{chunk-06hwds44.js → chunk-3wvpgb8m.js} +3 -3
  12. package/dist/bin/{chunk-jcehsvnm.js → chunk-462swbg5.js} +13 -13
  13. package/dist/bin/chunk-4c4q96vm.js +1 -0
  14. package/dist/bin/chunk-5hmrqjmq.js +1 -0
  15. package/dist/bin/chunk-5tzygzdy.js +1 -0
  16. package/dist/bin/{chunk-e12679p1.js → chunk-69mejej3.js} +1 -1
  17. package/dist/bin/{chunk-hyrvmjq0.js → chunk-6b6yr784.js} +2 -2
  18. package/dist/bin/chunk-6ybjfjbc.js +1 -0
  19. package/dist/bin/chunk-7848wre2.js +1 -0
  20. package/dist/bin/chunk-7haewmr7.js +1 -0
  21. package/dist/bin/chunk-7yhy2a7h.js +1 -0
  22. package/dist/bin/{chunk-k3cyh23p.js → chunk-83tt2t15.js} +5 -5
  23. package/dist/bin/{chunk-y5gx3dq2.js → chunk-89v3ec9n.js} +1 -1
  24. package/dist/bin/{chunk-33shhgye.js → chunk-8rkfwgb4.js} +7 -7
  25. package/dist/bin/{chunk-p35e4j11.js → chunk-9gp8p8hv.js} +2 -2
  26. package/dist/bin/chunk-9nen8018.js +1 -0
  27. package/dist/bin/chunk-9zwvysdn.js +1 -0
  28. package/dist/bin/chunk-abt0636a.js +1 -0
  29. package/dist/bin/{chunk-hhbmtgkq.js → chunk-b1cb27m8.js} +6 -6
  30. package/dist/bin/chunk-b9ersj22.js +1 -0
  31. package/dist/bin/{chunk-gbbcp2bw.js → chunk-bkx2kapc.js} +2 -2
  32. package/dist/bin/{chunk-540wkkhs.js → chunk-btrxye8p.js} +5 -5
  33. package/dist/bin/{chunk-9ktyfegk.js → chunk-cgyk48s5.js} +1 -1
  34. package/dist/bin/{chunk-th05q1gs.js → chunk-cxf9pmmw.js} +2 -2
  35. package/dist/bin/{chunk-0zydd9s4.js → chunk-d0m01m6d.js} +5 -5
  36. package/dist/bin/{chunk-eyzdhtp4.js → chunk-f7jzs1h1.js} +4 -4
  37. package/dist/bin/{chunk-ma0d990n.js → chunk-gn7rdyz7.js} +2 -2
  38. package/dist/bin/{chunk-f0djc6da.js → chunk-gy29teqh.js} +3 -3
  39. package/dist/bin/chunk-haezjam0.js +1 -0
  40. package/dist/bin/chunk-hp1cqk45.js +1 -0
  41. package/dist/bin/{chunk-tf5tf414.js → chunk-jqs2ywj2.js} +2 -2
  42. package/dist/bin/{chunk-c1znyyca.js → chunk-jx062xpq.js} +1 -1
  43. package/dist/bin/chunk-k9s81q0g.js +1 -0
  44. package/dist/bin/{chunk-0v5q5sh0.js → chunk-nzg624aj.js} +3 -3
  45. package/dist/bin/chunk-q3mtvtem.js +1 -0
  46. package/dist/bin/{chunk-s076q9sj.js → chunk-qmwqntnx.js} +2 -2
  47. package/dist/bin/{chunk-4m2k5mvd.js → chunk-qpasspad.js} +4 -4
  48. package/dist/bin/chunk-qpd51n1j.js +1 -0
  49. package/dist/bin/chunk-rtpc6djg.js +1 -0
  50. package/dist/bin/chunk-s9k81gq6.js +1 -0
  51. package/dist/bin/{chunk-wayhpmn7.js → chunk-sacx9p6f.js} +86 -86
  52. package/dist/bin/{chunk-fhqjr3ba.js → chunk-ssnvdxh4.js} +3 -3
  53. package/dist/bin/{chunk-kq526rgc.js → chunk-t0r1rdj2.js} +1 -1
  54. package/dist/bin/chunk-tpy9t3cv.js +1 -0
  55. package/dist/bin/{chunk-by7dtwtj.js → chunk-w40r35vn.js} +1 -1
  56. package/dist/bin/chunk-w9jfrf3v.js +11 -0
  57. package/dist/bin/chunk-wm0rq725.js +1 -0
  58. package/dist/bin/chunk-y9qdpwa6.js +1 -0
  59. package/dist/bin/chunk-ybekawxv.js +1 -0
  60. package/dist/bin/{chunk-4vtyjj7c.js → chunk-yf2drw7r.js} +1 -1
  61. package/dist/bin/{chunk-gq4htm3f.js → chunk-z9g7fa1w.js} +1 -1
  62. package/dist/bin/{chunk-0e7y7q0t.js → chunk-zfn3a9sx.js} +1 -1
  63. package/dist/bin/chunk-zg8nnq7k.js +1 -0
  64. package/dist/bin/{chunk-6kx0fddd.js → chunk-zn2efqcr.js} +46 -46
  65. package/dist/bin/{chunk-kyqe19mh.js → chunk-zn9wmqd1.js} +2 -2
  66. package/dist/bin/cli.js +215 -215
  67. package/dist/bin/dashboard-server.js +1 -1
  68. package/dist/bin/stacks-queue-worker.js +1 -1
  69. package/dist/bin/stacks-scheduler.js +1 -1
  70. package/dist/chunk-18dqxyz5.js +1 -0
  71. package/dist/{chunk-etv0rcjd.js → chunk-1h95atas.js} +1 -1
  72. package/dist/{chunk-nxj8pwa7.js → chunk-3wh3hsvp.js} +1 -1
  73. package/dist/{chunk-t7qgvz8z.js → chunk-5rds38z9.js} +55 -55
  74. package/dist/chunk-5v2wpf1k.js +1 -0
  75. package/dist/{chunk-tp37gyhc.js → chunk-7ea0q5tg.js} +1 -1
  76. package/dist/{chunk-dvma06m5.js → chunk-9w8qtr4p.js} +1 -1
  77. package/dist/{chunk-hg93a2g9.js → chunk-c71hhcsb.js} +2 -2
  78. package/dist/{chunk-w8sctn7m.js → chunk-cf274f07.js} +1 -1
  79. package/dist/{chunk-v6s9k1mp.js → chunk-cz4dw2hk.js} +1 -1
  80. package/dist/{chunk-0cgrk9g3.js → chunk-dh5m9b05.js} +1 -1
  81. package/dist/{chunk-z5c5amm1.js → chunk-dvw5dy32.js} +4 -4
  82. package/dist/{chunk-b6wsc7jp.js → chunk-eyc2tvze.js} +1 -1
  83. package/dist/{chunk-kjkkh11z.js → chunk-k8xv271s.js} +4 -4
  84. package/dist/{chunk-z52n96sa.js → chunk-n5qbdsbj.js} +89 -88
  85. package/dist/{chunk-8k44kaz0.js → chunk-pk8ppz98.js} +1 -1
  86. package/dist/{chunk-f4fggc5f.js → chunk-tb5hy7rm.js} +1 -1
  87. package/dist/deploy/index.js +1 -1
  88. package/dist/dns/index.js +1 -1
  89. package/dist/drivers/hetzner/driver.d.ts +1 -0
  90. package/dist/drivers/index.js +1 -1
  91. package/dist/drivers/shared/compute-provision.d.ts +2 -0
  92. package/dist/index.js +2 -2
  93. package/dist/mail/index.js +2 -2
  94. package/dist/operations/index.js +1 -1
  95. package/dist/protection/index.js +1 -1
  96. package/dist/spend/index.js +1 -1
  97. package/dist/ui/404.html +1 -1
  98. package/dist/ui/accept-invitation.html +1 -1
  99. package/dist/ui/access-denied.html +1 -1
  100. package/dist/ui/account/automation.html +6 -6
  101. package/dist/ui/account/security.html +2 -2
  102. package/dist/ui/applications/compose.html +6 -6
  103. package/dist/ui/applications/new.html +1 -1
  104. package/dist/ui/data/backups.html +5 -5
  105. package/dist/ui/data/services.html +5 -5
  106. package/dist/ui/data/volumes.html +6 -6
  107. package/dist/ui/index.html +6 -6
  108. package/dist/ui/infrastructure/topology.html +6 -6
  109. package/dist/ui/integrations.html +1 -1
  110. package/dist/ui/operations/alerts.html +5 -5
  111. package/dist/ui/operations/configuration.html +6 -6
  112. package/dist/ui/operations/jobs.html +5 -5
  113. package/dist/ui/operations/maintenance.html +6 -6
  114. package/dist/ui/operations/observability.html +6 -6
  115. package/dist/ui/operations/previews.html +6 -6
  116. package/dist/ui/operations/queue.html +6 -6
  117. package/dist/ui/operations/regions.html +6 -6
  118. package/dist/ui/operations/releases.html +6 -6
  119. package/dist/ui/operations/spend.html +6 -6
  120. package/dist/ui/operations/workloads.html +6 -6
  121. package/dist/ui/security.html +1 -1
  122. package/dist/ui/server/actions.html +6 -6
  123. package/dist/ui/server/activity.html +1 -1
  124. package/dist/ui/server/capacity.html +5 -5
  125. package/dist/ui/server/database.html +6 -6
  126. package/dist/ui/server/deployments.html +5 -5
  127. package/dist/ui/server/diagnostics.html +2 -2
  128. package/dist/ui/server/firewall.html +5 -5
  129. package/dist/ui/server/fleet.html +6 -6
  130. package/dist/ui/server/logs.html +5 -5
  131. package/dist/ui/server/metrics.html +5 -5
  132. package/dist/ui/server/security.html +2 -2
  133. package/dist/ui/server/services.html +2 -2
  134. package/dist/ui/server/sites.html +6 -6
  135. package/dist/ui/server/ssh-keys.html +6 -6
  136. package/dist/ui/server/team.html +6 -6
  137. package/dist/ui/server/terminal.html +2 -2
  138. package/dist/ui/serverless/alarms.html +6 -6
  139. package/dist/ui/serverless/assets.html +1 -1
  140. package/dist/ui/serverless/cost.html +2 -2
  141. package/dist/ui/serverless/data.html +6 -6
  142. package/dist/ui/serverless/deployments.html +2 -2
  143. package/dist/ui/serverless/firewall.html +1 -1
  144. package/dist/ui/serverless/functions.html +6 -6
  145. package/dist/ui/serverless/logs.html +6 -6
  146. package/dist/ui/serverless/metrics.html +2 -2
  147. package/dist/ui/serverless/queues.html +6 -6
  148. package/dist/ui/serverless/secrets.html +6 -6
  149. package/dist/ui/serverless/traces.html +6 -6
  150. package/dist/ui/serverless.html +5 -5
  151. package/package.json +3 -3
  152. package/dist/bin/chunk-00j7xxxg.js +0 -1
  153. package/dist/bin/chunk-1xfn93bc.js +0 -1
  154. package/dist/bin/chunk-413nb697.js +0 -1
  155. package/dist/bin/chunk-8esaawk6.js +0 -1
  156. package/dist/bin/chunk-8zc4kx6k.js +0 -1
  157. package/dist/bin/chunk-9t6wztvn.js +0 -1
  158. package/dist/bin/chunk-b074y2np.js +0 -1
  159. package/dist/bin/chunk-b77qsk6r.js +0 -1
  160. package/dist/bin/chunk-d73xkm0k.js +0 -1
  161. package/dist/bin/chunk-dmj5xv74.js +0 -1
  162. package/dist/bin/chunk-dnswjyen.js +0 -1
  163. package/dist/bin/chunk-h28tfah9.js +0 -1
  164. package/dist/bin/chunk-k1bdndgj.js +0 -1
  165. package/dist/bin/chunk-kkrp8100.js +0 -1
  166. package/dist/bin/chunk-m1w3p30q.js +0 -1
  167. package/dist/bin/chunk-nwcpck34.js +0 -1
  168. package/dist/bin/chunk-p96975b7.js +0 -1
  169. package/dist/bin/chunk-qssb91v3.js +0 -11
  170. package/dist/bin/chunk-rgwwr6x2.js +0 -1
  171. package/dist/bin/chunk-sky689gw.js +0 -1
  172. package/dist/bin/chunk-tx56y5qk.js +0 -1
  173. package/dist/bin/chunk-v0fkhtgq.js +0 -1
  174. package/dist/bin/chunk-v7dk21w9.js +0 -1
  175. package/dist/bin/chunk-ww4r3r7x.js +0 -1
  176. package/dist/bin/chunk-x9dep4ew.js +0 -1
  177. package/dist/bin/chunk-y5hsmt17.js +0 -1
  178. package/dist/bin/chunk-zfy6f6ph.js +0 -1
  179. package/dist/chunk-fmhqz3eg.js +0 -1
  180. package/dist/chunk-pev4cpbd.js +0 -1
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{$I,MI,rl,Sm,nl,il,dn,Q,l,sl,Im,K,ol,p,ry,C,Ze,Ji,ln,w,ce,al,ny,r,t,FI,UI,m,QI,HI,GI,VI,qI,lr,cl,Xi,iy,jI,zI,xe,et,dl,bm,Cm,KI,Em,vm,Tm,Ho,ll,de,un,kt,Go,Nt,Ce,sy,ul,Vo,wm,Rm,Dm,Pm,gl,WI,W,E,oy,ay,km,a,S,tt,f,Nm,rt,J,Bt,JI,Bm,X,pl,Oe,ur,qo,le,ml,ue,cy,jo,Y,Z,_,Yi,D,gr,xt,ee,e,gn,XI,xm,fl,YI,ZI,eb,tb,hl,rb,nb,ib,sb,ob,ab,cb,db,lb,ub,gb,pb,dy,ly,uy,gy,py,my,fy,pr,Om,_m,mr,Zi,mb,Lm,fb,hb,pn,Ab,yb,Sb,Ib,bb,Cb,hy,Ay,yy,Sy,Iy,es,Eb,zo,by,$m,V,Cy,nt,Ko,Ot,Ey,Mm,vy,Ty,wy,Fm,q,vb,Tb,wb,Rb,Ry,Db,te,Pb,kb,Nb,Al,yl,Dy,Um,Qm,Bb,xb,Ob,_b,Lb,Py,Sl,$b,Mb,Fb,Ub,Qb,ky,Ny,Hb,Gb,Vb,qb,jb,zb,Kb,By,Wb,Hm,Il,Jb,Xb,Yb,Zb,Gm,Vm,qm,eC,bl,xy,Oy,_y,Ly,Cl,$y,tC,rC,nC,iC,sC,oC,aC,My,Fy,Uy,Qy,jm,cC,dC,lC,uC,gC,pC,mC,fC,hC,Hy,Gy,Vy,qy,AC,yC,zm,SC,Km,Wm,Jm,Xm,IC,bC,CC,EC,_e,ts,vC,TC,wC,RC,DC,PC,kC,NC,jy,BC,xC,Ym,Zm,OC,_C,zy,LC,$C,MC,FC,UC,QC,HC,GC,VC,qC,jC,zC,KC,WC,JC,XC,YC,ZC,eE,tE,rE,El,Ky,vl,Wy,Tl,Jy,wl,Xy,Rl,Yy,fr,Zy,Dl,eS,rs,tS,Pl,rS,kl,nS,ef,nE,tf,iE,Nl,iS,hr,sS,rf,sE,Bl,oS,nf,oE,sf,aE,of,cE,xl,aS,af,dE,cf,lE,df,uE,lf,gE,Ol,cS,_l,dS,uf,pE,gf,mE,pf,fE,mf,hE,ff,AE,hf,yE,Ll,lS,Af,SE,yf,IE,Sf,bE,If,CE,bf,EE,Cf,vE,Ef,vf,Tf,wf,Rf,TE,Df,wE,Pf,RE,kf,DE,it,Nf,uS,Wo,$l,mn,gS,ns,Ar,Ml,Fl,pS,mS,Ul,Bf,Ql,xf,PE,kE,Jo,Xo,Yo,Hl,fn,Gl,Vl,is,Zo,ea,Of,fS,hS,AS,NE,_f,Lf,BE,yS,$f,SS,IS,bS,xE,Mf,hn,ql,Ff,OE,CS,ta,ra,jl,Uf,_E,zl,ES,Qf,LE,Hf,$E,Gf,ME}from"./chunk-t7qgvz8z.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-kjkkh11z.js";import{ru}from"./chunk-fjs0wgyw.js";import{U,Kr,Ad,Ao,d,zp,Kp}from"./chunk-0cgrk9g3.js";import{Tt,hd,xi,Oi,_i,jp}from"./chunk-nxj8pwa7.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-dvma06m5.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-b6wsc7jp.js";import{n}from"./chunk-m9szynnf.js";import{Re,mt,zn}from"./chunk-v6s9k1mp.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-tp37gyhc.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-8k44kaz0.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-z52n96sa.js";import{go,mo,fo,B,Ne}from"./chunk-w8sctn7m.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-z5c5amm1.js";import{Ac}from"./chunk-etv0rcjd.js";import{Pc,Qe,I}from"./chunk-z56sccfh.js";import{He}from"./chunk-fdf181e6.js";import{b}from"./chunk-hg93a2g9.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 {
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-5rds38z9.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-k8xv271s.js";import{ru}from"./chunk-fjs0wgyw.js";import{U,Kr,Ad,Ao,d,zp,Kp}from"./chunk-dh5m9b05.js";import{Tt,hd,xi,Oi,_i,jp}from"./chunk-3wh3hsvp.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-9w8qtr4p.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-eyc2tvze.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-n5qbdsbj.js";import{go,mo,fo,B,Ne}from"./chunk-cf274f07.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-1h95atas.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
2
  ${fe}
3
3
  }`:` handle ${z.path} {
4
4
  ${fe}
@@ -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,b 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,C 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 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};
@@ -1,3 +1,3 @@
1
- import{C,Ze,Ji,ln,w}from"../chunk-t7qgvz8z.js";import"../chunk-928z0h9b.js";import"../chunk-0cgrk9g3.js";import{B,R,Et,G}from"../chunk-w8sctn7m.js";function a(t){return`'${t.replace(/'/g,"'\\''")}'`}function f(t,e="/etc/mail/mail.env",r="/usr/local/bin/bun"){let i={SMTP_ENABLE_WEBMAIL:String(t.webmail.enabled),SMTP_WEBMAIL_PORT:String(t.webmail.port),SMTP_WEBMAIL_TLS:String(t.webmail.tls),SMTP_WEBMAIL_SECURE_COOKIES:String(t.webmail.secureCookies),SMTP_WEBMAIL_ATTACHMENT_MAX_FILE:String(t.webmail.attachmentMaxFileBytes),SMTP_WEBMAIL_ATTACHMENT_MAX_TOTAL:String(t.webmail.attachmentMaxTotalBytes),SMTP_WEBMAIL_ATTACHMENT_MAX_COUNT:String(t.webmail.attachmentMaxCount),SMTP_WEBMAIL_UNDO_SEND_SECONDS:String(t.webmail.undoSendSeconds)},s="const fs=require('node:fs');const path=process.argv[1];const settings=JSON.parse(process.argv[2]);const before=fs.readFileSync(path,'utf8');const lines=before.split(/\\r?\\n/).filter(line=>line!==''&&!Object.hasOwn(settings,line.split('=',1)[0]));const after=lines.concat(Object.entries(settings).map(([key,value])=>key+'='+value)).join('\\n')+'\\n';if(after===before){console.log('unchanged')}else{const stat=fs.statSync(path);const backup=path+'.bak-webmail';fs.copyFileSync(path,backup);fs.chmodSync(backup,stat.mode&511);fs.chownSync(backup,stat.uid,stat.gid);const temporary=path+'.webmail-'+process.pid;fs.writeFileSync(temporary,after,{mode:stat.mode&511});fs.chownSync(temporary,stat.uid,stat.gid);fs.chmodSync(temporary,stat.mode&511);fs.renameSync(temporary,path);console.log('changed')}";return`${a(r)} --eval ${a("const fs=require('node:fs');const path=process.argv[1];const settings=JSON.parse(process.argv[2]);const before=fs.readFileSync(path,'utf8');const lines=before.split(/\\r?\\n/).filter(line=>line!==''&&!Object.hasOwn(settings,line.split('=',1)[0]));const after=lines.concat(Object.entries(settings).map(([key,value])=>key+'='+value)).join('\\n')+'\\n';if(after===before){console.log('unchanged')}else{const stat=fs.statSync(path);const backup=path+'.bak-webmail';fs.copyFileSync(path,backup);fs.chmodSync(backup,stat.mode&511);fs.chownSync(backup,stat.uid,stat.gid);const temporary=path+'.webmail-'+process.pid;fs.writeFileSync(temporary,after,{mode:stat.mode&511});fs.chownSync(temporary,stat.uid,stat.gid);fs.chmodSync(temporary,stat.mode&511);fs.renameSync(temporary,path);console.log('changed')}")} ${a(e)} ${a(JSON.stringify(i))}`}function h(t,e){let r=e.environment??"production",i=C(t,{environment:r});if(!i.enabled||!i.webmail.enabled)return"";if(!i.webmail.domain)throw Error("Mail webmail deployment needs a hostname; set mail.webmail.domain or use compute provisioning for a local catcher");if(i.webmail.tls)throw Error("Gateway webmail uses loopback HTTP: set mail.webmail.tls to false, or domain to false for a direct TLS listener");let s=w(t,{environment:r}),o=e.slug??t.project.slug,n=e.bunBin??"/usr/local/bin/bun",l=e.envFile??"/etc/mail/mail.env",c=e.service??"mail.service",m=e.healthPath??"/login";if(!/^[a-z0-9@._-]+$/i.test(c)||c.startsWith("-"))throw Error("Invalid mail service unit");if(!l.startsWith("/")||!m.startsWith("/")||/[\r\n]/.test(l+m))throw Error("Mail environment path must be absolute and health path must start with /");let p=B({},{proxy:s,slug:o,mail:i}),u=e.gateway!=="provision",d=["set -euo pipefail",`test -f ${a(l)}`,...u?[`test -x ${Et}`,`test -d ${R}/node_modules/@stacksjs/rpx`,...s.onDemandTls?[`test -f ${R}/node_modules/@stacksjs/tlsx/dist/bin/cli.js`]:[]]:[],`__tsc_mail_changed="$(${f(i,l,n)})"`,`if [ "$__tsc_mail_changed" = changed ] || ! systemctl is-active --quiet ${a(c)}; then systemctl restart ${a(c)}; fi`,`curl --fail --silent --show-error --retry 30 --retry-all-errors --retry-delay 1 --max-time 5 ${a(`http://127.0.0.1:${i.webmail.port}${m}`)} >/dev/null`,...G({config:p,proxy:s,slug:o,bunBin:n,tenant:u})];if(e.verify!==!1)for(let b of[i.webmail.domain,...i.webmail.aliases])d.push(`__tsc_mail_status="$(curl --fail --silent --show-error --retry 10 --retry-connrefused --retry-delay 3 --max-time 15 --output /dev/null --write-out '%{http_code}' ${a(`https://${b}${m}`)})"`,`if [ "$__tsc_mail_status" != 200 ]; then echo ${a(`ts-cloud: webmail verification failed for ${b}`)} >&2; exit 1; fi`);return d.push(`echo ${a(`[ts-cloud] Webmail deployed: ${[i.webmail.domain,...i.webmail.aliases].join(", ")}`)}`),`${d.join(`
1
+ import{b,Ze,Ji,ln,w}from"../chunk-5rds38z9.js";import"../chunk-928z0h9b.js";import"../chunk-dh5m9b05.js";import{B,R,Et,G}from"../chunk-cf274f07.js";function a(t){return`'${t.replace(/'/g,"'\\''")}'`}function h(t,e="/etc/mail/mail.env",r="/usr/local/bin/bun"){let i={SMTP_ENABLE_WEBMAIL:String(t.webmail.enabled),SMTP_WEBMAIL_PORT:String(t.webmail.port),SMTP_WEBMAIL_TLS:String(t.webmail.tls),SMTP_WEBMAIL_SECURE_COOKIES:String(t.webmail.secureCookies),SMTP_WEBMAIL_ATTACHMENT_MAX_FILE:String(t.webmail.attachmentMaxFileBytes),SMTP_WEBMAIL_ATTACHMENT_MAX_TOTAL:String(t.webmail.attachmentMaxTotalBytes),SMTP_WEBMAIL_ATTACHMENT_MAX_COUNT:String(t.webmail.attachmentMaxCount),SMTP_WEBMAIL_UNDO_SEND_SECONDS:String(t.webmail.undoSendSeconds)},s="const fs=require('node:fs');const path=process.argv[1];const settings=JSON.parse(process.argv[2]);const before=fs.readFileSync(path,'utf8');const lines=before.split(/\\r?\\n/).filter(line=>line!==''&&!Object.hasOwn(settings,line.split('=',1)[0]));const after=lines.concat(Object.entries(settings).map(([key,value])=>key+'='+value)).join('\\n')+'\\n';if(after===before){console.log('unchanged')}else{const stat=fs.statSync(path);const backup=path+'.bak-webmail';fs.copyFileSync(path,backup);fs.chmodSync(backup,stat.mode&511);fs.chownSync(backup,stat.uid,stat.gid);const temporary=path+'.webmail-'+process.pid;fs.writeFileSync(temporary,after,{mode:stat.mode&511});fs.chownSync(temporary,stat.uid,stat.gid);fs.chmodSync(temporary,stat.mode&511);fs.renameSync(temporary,path);console.log('changed')}";return`${a(r)} --eval ${a("const fs=require('node:fs');const path=process.argv[1];const settings=JSON.parse(process.argv[2]);const before=fs.readFileSync(path,'utf8');const lines=before.split(/\\r?\\n/).filter(line=>line!==''&&!Object.hasOwn(settings,line.split('=',1)[0]));const after=lines.concat(Object.entries(settings).map(([key,value])=>key+'='+value)).join('\\n')+'\\n';if(after===before){console.log('unchanged')}else{const stat=fs.statSync(path);const backup=path+'.bak-webmail';fs.copyFileSync(path,backup);fs.chmodSync(backup,stat.mode&511);fs.chownSync(backup,stat.uid,stat.gid);const temporary=path+'.webmail-'+process.pid;fs.writeFileSync(temporary,after,{mode:stat.mode&511});fs.chownSync(temporary,stat.uid,stat.gid);fs.chmodSync(temporary,stat.mode&511);fs.renameSync(temporary,path);console.log('changed')}")} ${a(e)} ${a(JSON.stringify(i))}`}function p(t,e){let r=e.environment??"production",i=b(t,{environment:r});if(!i.enabled||!i.webmail.enabled)return"";if(!i.webmail.domain)throw Error("Mail webmail deployment needs a hostname; set mail.webmail.domain or use compute provisioning for a local catcher");if(i.webmail.tls)throw Error("Gateway webmail uses loopback HTTP: set mail.webmail.tls to false, or domain to false for a direct TLS listener");let s=w(t,{environment:r}),o=e.slug??t.project.slug,n=e.bunBin??"/usr/local/bin/bun",l=e.envFile??"/etc/mail/mail.env",c=e.service??"mail.service",m=e.healthPath??"/login";if(!/^[a-z0-9@._-]+$/i.test(c)||c.startsWith("-"))throw Error("Invalid mail service unit");if(!l.startsWith("/")||!m.startsWith("/")||/[\r\n]/.test(l+m))throw Error("Mail environment path must be absolute and health path must start with /");let g=B({},{proxy:s,slug:o,mail:i}),u=e.gateway!=="provision",d=["set -euo pipefail",`test -f ${a(l)}`,...u?[`test -x ${Et}`,`test -d ${R}/node_modules/@stacksjs/rpx`,...s.onDemandTls?[`test -f ${R}/node_modules/@stacksjs/tlsx/dist/bin/cli.js`]:[]]:[],`__tsc_mail_changed="$(${h(i,l,n)})"`,`if [ "$__tsc_mail_changed" = changed ] || ! systemctl is-active --quiet ${a(c)}; then systemctl restart ${a(c)}; fi`,`curl --fail --silent --show-error --retry 30 --retry-all-errors --retry-delay 1 --max-time 5 ${a(`http://127.0.0.1:${i.webmail.port}${m}`)} >/dev/null`,...G({config:g,proxy:s,slug:o,bunBin:n,tenant:u})];if(e.verify!==!1)for(let f of[i.webmail.domain,...i.webmail.aliases])d.push(`__tsc_mail_status="$(curl --fail --silent --show-error --retry 10 --retry-connrefused --retry-delay 3 --max-time 15 --output /dev/null --write-out '%{http_code}' ${a(`https://${f}${m}`)})"`,`if [ "$__tsc_mail_status" != 200 ]; then echo ${a(`ts-cloud: webmail verification failed for ${f}`)} >&2; exit 1; fi`);return d.push(`echo ${a(`[ts-cloud] Webmail deployed: ${[i.webmail.domain,...i.webmail.aliases].join(", ")}`)}`),`${d.join(`
2
2
  `)}
3
- `}async function g(t,e){let r=h(t,e);if(!r)return;if(!/^(?:[a-z_][a-z0-9._-]*@)?[a-z0-9.:[\]_-]+$/i.test(e.target)||e.target.startsWith("-"))throw Error("Invalid SSH target");let i=["ssh","-T","-o","BatchMode=yes","-o","ConnectTimeout=15",...e.sshKeyPath?["-i",e.sshKeyPath]:[],e.target,"bash","-se"],s=Bun.spawn(i,{stdin:new Blob([r]),stdout:"inherit",stderr:"inherit"}),o=setTimeout(()=>s.kill(),e.timeoutMs??300000);try{let n=await s.exited;if(n!==0)throw Error(`Mail webmail deployment failed (SSH exit ${n})`)}finally{clearTimeout(o)}}export{Ji as buildMailEnv,h as buildMailWebmailDeploymentScript,f as buildMailWebmailEnvPatch,g as deployMailWebmail,Ze as mailFirewallPorts,ln as mailWebmailSites,w as resolveMailProxy,C as resolveMailService};
3
+ `}async function y(t,e){let r=p(t,e);if(!r)return;if(!/^(?:[a-z_][a-z0-9._-]*@)?[a-z0-9.:[\]_-]+$/i.test(e.target)||e.target.startsWith("-"))throw Error("Invalid SSH target");let i=["ssh","-T","-o","BatchMode=yes","-o","ConnectTimeout=15",...e.sshKeyPath?["-i",e.sshKeyPath]:[],e.target,"bash","-se"],s=Bun.spawn(i,{stdin:new Blob([r]),stdout:"inherit",stderr:"inherit"}),o=setTimeout(()=>s.kill(),e.timeoutMs??300000);try{let n=await s.exited;if(n!==0)throw Error(`Mail webmail deployment failed (SSH exit ${n})`)}finally{clearTimeout(o)}}export{Ji as buildMailEnv,p as buildMailWebmailDeploymentScript,h as buildMailWebmailEnvPatch,y as deployMailWebmail,Ze as mailFirewallPorts,ln as mailWebmailSites,w as resolveMailProxy,b as resolveMailService};
@@ -1 +1 @@
1
- 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-dvma06m5.js";import"../chunk-nxj8pwa7.js";import"../chunk-0cgrk9g3.js";import"../chunk-t7qgvz8z.js";import"../chunk-928z0h9b.js";export{Dp as ENVIRONMENT_LABEL,Rp as PROJECT_LABEL,Pp as ROLE_LABEL,uA as applyPlan,hA as attachConflicts,AA as attachIsViable,fA as attachPreconditions,EA as buildCertificatePackScript,IA as buildCertificateStateScript,vA as buildCertificateUnpackScript,Gp as buildDrainSourceScript,rA as buildDrainedSiteScanScript,Hp as buildHealthGateScript,_p as buildPauseWorkersScript,Fp as buildRestoreScript,pA as buildSetHostnameScript,Mp as buildSnapshotScript,Vp as buildSourceStateScript,Up as buildTargetStateScript,Lp as buildWorkersStateScript,CA as certificatesMatch,yA as formatAttachPlan,iA as formatDrainedSiteRefusal,cA as formatInventory,lA as formatPlan,bA as parseCertificateState,nA as parseDrainedSites,qp as parseSourceDrained,Qp as parseTargetReady,$p as parseWorkersPaused,md as pendingSteps,xp as planIsDestructive,gA as planServerRename,TA as planSiteMove,oA as probeHostRoutes,aA as reconcile,mA as resolveAttachTarget,dA as resolvePlan,kp as routesFromFragments,Bi as siteMoveArchivePath,SA as siteMoveCertArchivePath,fd as siteUnitGlob,Np as tenantsOf,sA as toInventoryServer,Bp as unaccountedSites,Op as validateServerName};
1
+ 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-9w8qtr4p.js";import"../chunk-3wh3hsvp.js";import"../chunk-dh5m9b05.js";import"../chunk-5rds38z9.js";import"../chunk-928z0h9b.js";export{Dp as ENVIRONMENT_LABEL,Rp as PROJECT_LABEL,Pp as ROLE_LABEL,uA as applyPlan,hA as attachConflicts,AA as attachIsViable,fA as attachPreconditions,EA as buildCertificatePackScript,IA as buildCertificateStateScript,vA as buildCertificateUnpackScript,Gp as buildDrainSourceScript,rA as buildDrainedSiteScanScript,Hp as buildHealthGateScript,_p as buildPauseWorkersScript,Fp as buildRestoreScript,pA as buildSetHostnameScript,Mp as buildSnapshotScript,Vp as buildSourceStateScript,Up as buildTargetStateScript,Lp as buildWorkersStateScript,CA as certificatesMatch,yA as formatAttachPlan,iA as formatDrainedSiteRefusal,cA as formatInventory,lA as formatPlan,bA as parseCertificateState,nA as parseDrainedSites,qp as parseSourceDrained,Qp as parseTargetReady,$p as parseWorkersPaused,md as pendingSteps,xp as planIsDestructive,gA as planServerRename,TA as planSiteMove,oA as probeHostRoutes,aA as reconcile,mA as resolveAttachTarget,dA as resolvePlan,kp as routesFromFragments,Bi as siteMoveArchivePath,SA as siteMoveCertArchivePath,fd as siteUnitGlob,Np as tenantsOf,sA as toInventoryServer,Bp as unaccountedSites,Op as validateServerName};
@@ -1 +1 @@
1
- import{Jl,ia,ss,os,sa,Xl,Yl,Zl,as,oa,aa,eu,tu,ca,_S}from"../chunk-jx1zz1pw.js";import{oe,Pi,uo,cd,ki,bp}from"../chunk-42vtybcm.js";import{Yd,an,Zd,el,tl,Wi,ym,cn}from"../chunk-84z2a1xn.js";import{Jo,Xo,Yo,Hl,fn,Gl,Vl,is,Zo,ea}from"../chunk-t7qgvz8z.js";import"../chunk-928z0h9b.js";export{Xo as CHAIN_HEADER,oa as DEFAULT_ATTACK_MODE_HOURS,Yd as DEFAULT_DDOS_THRESHOLDS,fn as DEFAULT_RECURSION_LIMITS,Jo as DEPTH_HEADER,as as MAX_CONTROL_HOURS,Zl as PROTECTION_SETTING,aa as ProtectionControlStore,Jl as RATE_LIMIT_KEY_SEPARATOR,sa as RateLimiter,is as RecursionGuard,Yo as TRACE_HEADER,ca as applyControlsToDdos,tu as applyControlsToRateLimits,cn as applyMitigationFactor,Yl as defaultRateLimitRules,eu as describePosture,oe as escapeSecLang,Hl as functionFingerprint,ia as globMatches,uo as globToRegex,Vl as inspectInvocation,Pi as isSafePattern,an as isValidCidr,_S as mergeControlsIntoConfig,Gl as parseChain,ym as planMitigation,Zo as propagationHeaders,Xl as rateLimitHeaders,os as rateLimitKey,ea as recursionBlockedResponse,Wi as renderDdosInstallScript,tl as renderNftablesRuleset,el as renderSysctlFile,cd as renderWafConfig,ki as renderWafInstallScript,ss as ruleMatches,Zd as sysctlHardening,bp as wafEventTelemetry};
1
+ import{Jl,ia,ss,os,sa,Xl,Yl,Zl,as,oa,aa,eu,tu,ca,_S}from"../chunk-jx1zz1pw.js";import{oe,Pi,uo,cd,ki,bp}from"../chunk-42vtybcm.js";import{Yd,an,Zd,el,tl,Wi,ym,cn}from"../chunk-84z2a1xn.js";import{Jo,Xo,Yo,Hl,fn,Gl,Vl,is,Zo,ea}from"../chunk-5rds38z9.js";import"../chunk-928z0h9b.js";export{Xo as CHAIN_HEADER,oa as DEFAULT_ATTACK_MODE_HOURS,Yd as DEFAULT_DDOS_THRESHOLDS,fn as DEFAULT_RECURSION_LIMITS,Jo as DEPTH_HEADER,as as MAX_CONTROL_HOURS,Zl as PROTECTION_SETTING,aa as ProtectionControlStore,Jl as RATE_LIMIT_KEY_SEPARATOR,sa as RateLimiter,is as RecursionGuard,Yo as TRACE_HEADER,ca as applyControlsToDdos,tu as applyControlsToRateLimits,cn as applyMitigationFactor,Yl as defaultRateLimitRules,eu as describePosture,oe as escapeSecLang,Hl as functionFingerprint,ia as globMatches,uo as globToRegex,Vl as inspectInvocation,Pi as isSafePattern,an as isValidCidr,_S as mergeControlsIntoConfig,Gl as parseChain,ym as planMitigation,Zo as propagationHeaders,Xl as rateLimitHeaders,os as rateLimitKey,ea as recursionBlockedResponse,Wi as renderDdosInstallScript,tl as renderNftablesRuleset,el as renderSysctlFile,cd as renderWafConfig,ki as renderWafInstallScript,ss as ruleMatches,Zd as sysctlHardening,bp as wafEventTelemetry};
@@ -1 +1 @@
1
- import{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,XA,on,gm,Fo,YA,pm,mm,fm,ZA,hm,Am,ey,Uo,Qo}from"../chunk-b6wsc7jp.js";import"../chunk-t7qgvz8z.js";import"../chunk-928z0h9b.js";export{Bo as AnomalyConfigStore,hm as AwsSpendTransport,Am as ComputeSpendTransport,Po as CounterTracker,xd as DEFAULT_METER_MAPPINGS,Nd as DEFAULT_PRICE_BOOK,em as DEFAULT_THRESHOLDS,rn as DETECTABLE_SIGNALS,$A as ENFORCEMENT_ACTIONS,Qi as ENFORCEMENT_DESCRIPTIONS,O as ENFORCEMENT_SEVERITY,cm as FOCUS_VERSION,wo as METERS,LA as METER_KEYS,MA as MICRO_CENTS,tm as MIN_PROJECTION_CONFIDENCE,dm as RecordingSpendTransport,om as SENSITIVITY_THRESHOLDS,fm as SPEND_CYCLE_SECONDS,jd as SPEND_GATE_SETTING,YA as SPEND_LEASE_SETTING,Oo as SignalSource,zd as SpendCapError,nn as SpendGate,pm as SpendLoopLease,Fo as SpendNotificationRouter,mm as SpendRunner,cr as SpendService,Fi as SpendStore,XA as URGENT_SPEND_EVENTS,rm as USER_VISIBLE_ACTIONS,_d as aggregateDeltas,Hi as anomalyOptionsForSignal,zA as assertSpendAllows,Rt as budgetWindow,ey as compositeSpendTransport,Kd as createEnforcementHandlers,sm as detectAnomalies,Gd as detectLatestAnomaly,$d as evaluateBudget,VA as ewma,Yp as findMapping,Xp as findPriceEntry,on as formatCents,tn as formatTimeToExhaustion,Ui as governingLimitCents,Uo as handleSpendRequest,en as hourBucket,GA as hourBucketsBetween,Hd as isOperationAllowed,Mi as isValidTimeZone,Vd as lookbackHoursForSignal,No as median,nm as medianAbsoluteDeviation,Md as mergeDecisions,QA as mergePriceBooks,Od as meterTelemetry,_o as optionsForSignal,ko as percentOfLimit,Fd as planEnforcement,HA as previousBudgetWindow,Ro as priceUsage,FA as priceUsageLines,Ld as projectSpend,im as robustZScore,UA as roundCents,am as routeMatches,Ud as runEnforcement,Dt as scopeKey,xo as signalDefinition,gm as spendNotificationText,Qo as spendOpenApiPaths,ZA as startSpendLoop,qA as streamFocusJsonl,Qd as strongestActiveAction,kd as tieredMicroCents,Lo as toFocusJsonl,qd as toFocusRecords,Zp as usageDeltaKey,ar as utcInstantOfLocal,jA as zeroFill,Bd as zoneOffsetMs,Do as zonedParts};
1
+ import{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,XA,on,gm,Fo,YA,pm,mm,fm,ZA,hm,Am,ey,Uo,Qo}from"../chunk-eyc2tvze.js";import"../chunk-5rds38z9.js";import"../chunk-928z0h9b.js";export{Bo as AnomalyConfigStore,hm as AwsSpendTransport,Am as ComputeSpendTransport,Po as CounterTracker,xd as DEFAULT_METER_MAPPINGS,Nd as DEFAULT_PRICE_BOOK,em as DEFAULT_THRESHOLDS,rn as DETECTABLE_SIGNALS,$A as ENFORCEMENT_ACTIONS,Qi as ENFORCEMENT_DESCRIPTIONS,O as ENFORCEMENT_SEVERITY,cm as FOCUS_VERSION,wo as METERS,LA as METER_KEYS,MA as MICRO_CENTS,tm as MIN_PROJECTION_CONFIDENCE,dm as RecordingSpendTransport,om as SENSITIVITY_THRESHOLDS,fm as SPEND_CYCLE_SECONDS,jd as SPEND_GATE_SETTING,YA as SPEND_LEASE_SETTING,Oo as SignalSource,zd as SpendCapError,nn as SpendGate,pm as SpendLoopLease,Fo as SpendNotificationRouter,mm as SpendRunner,cr as SpendService,Fi as SpendStore,XA as URGENT_SPEND_EVENTS,rm as USER_VISIBLE_ACTIONS,_d as aggregateDeltas,Hi as anomalyOptionsForSignal,zA as assertSpendAllows,Rt as budgetWindow,ey as compositeSpendTransport,Kd as createEnforcementHandlers,sm as detectAnomalies,Gd as detectLatestAnomaly,$d as evaluateBudget,VA as ewma,Yp as findMapping,Xp as findPriceEntry,on as formatCents,tn as formatTimeToExhaustion,Ui as governingLimitCents,Uo as handleSpendRequest,en as hourBucket,GA as hourBucketsBetween,Hd as isOperationAllowed,Mi as isValidTimeZone,Vd as lookbackHoursForSignal,No as median,nm as medianAbsoluteDeviation,Md as mergeDecisions,QA as mergePriceBooks,Od as meterTelemetry,_o as optionsForSignal,ko as percentOfLimit,Fd as planEnforcement,HA as previousBudgetWindow,Ro as priceUsage,FA as priceUsageLines,Ld as projectSpend,im as robustZScore,UA as roundCents,am as routeMatches,Ud as runEnforcement,Dt as scopeKey,xo as signalDefinition,gm as spendNotificationText,Qo as spendOpenApiPaths,ZA as startSpendLoop,qA as streamFocusJsonl,Qd as strongestActiveAction,kd as tieredMicroCents,Lo as toFocusJsonl,qd as toFocusRecords,Zp as usageDeltaKey,ar as utcInstantOfLocal,jA as zeroFill,Bd as zoneOffsetMs,Do as zonedParts};
package/dist/ui/404.html CHANGED
@@ -2,7 +2,7 @@
2
2
  <html lang="en" data-theme="dark">
3
3
  <head>
4
4
  <meta charset="UTF-8">
5
- <meta name="stx-build" content="mvu5cyku57muls">
5
+ <meta name="stx-build" content="mvu6he7jpnel5l">
6
6
 
7
7
  <!-- stx SEO Tags -->
8
8
  <meta name="title" content="Page not found · ts-cloud">
@@ -1,4 +1,4 @@
1
- <!DOCTYPE html><html lang="en" data-theme="dark"><head><meta charset="UTF-8"><meta name="stx-build" content="mvu588e1dj99ma"><meta name="title" content="stx Project"><meta name="description" content="A website built with stx templating engine"><meta property="og:title" content="stx Project"><meta property="og:description" content="A website built with stx templating engine"><meta property="og:type" content="website"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="stx Project"><meta name="twitter:description" content="A website built with stx templating engine"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>ts-cloud - Accept invitation</title><link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect x='3' y='3' width='26' height='26' rx='8' fill='%235a8be0'/%3E%3C/svg%3E"><link rel="preconnect" href="https://fonts.googleapis.com"><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet"><link rel="stylesheet" href="/_stx/style.448ab192.css"><style data-stx-cloak>[x-cloak]{display:none !important}</style><link data-crosswind="generated" rel="stylesheet" href="/_stx/crosswind.616c25f3.css"></head><body class="auth-page"><main class="auth-card" id="main-content"><a class="brand" href="/"><span class="dot"></span><span>ts-cloud</span></a><div><span class="context-label">Organization invitation</span><h1>Join your team</h1><p>Choose the dashboard username and password you will use after this invitation is accepted.</p></div><form id="accept-invitation-form" class="auth-form"><div class="field-block"><label for="invite-name">Name</label><input id="invite-name" name="name" autocomplete="name" placeholder="Chris Breuer"></div><div class="field-block"><label for="invite-username">Username</label><input id="invite-username" name="username" autocomplete="username" minlength="2" maxlength="32" required></div><div class="field-block"><label for="invite-password">Password</label><input id="invite-password" name="password" type="password" autocomplete="new-password" minlength="12" required><small>At least 12 characters.</small></div><button class="btn" type="submit">Accept invitation</button><div id="invitation-status" class="auth-status" role="status"></div></form><p class="note">If this link expired or was already used, ask an organization owner to resend the invitation.</p></main> <script data-stx-scoped data-stx-run="always">
1
+ <!DOCTYPE html><html lang="en" data-theme="dark"><head><meta charset="UTF-8"><meta name="stx-build" content="mvu6c667y93vlr"><meta name="title" content="stx Project"><meta name="description" content="A website built with stx templating engine"><meta property="og:title" content="stx Project"><meta property="og:description" content="A website built with stx templating engine"><meta property="og:type" content="website"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="stx Project"><meta name="twitter:description" content="A website built with stx templating engine"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>ts-cloud - Accept invitation</title><link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect x='3' y='3' width='26' height='26' rx='8' fill='%235a8be0'/%3E%3C/svg%3E"><link rel="preconnect" href="https://fonts.googleapis.com"><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet"><link rel="stylesheet" href="/_stx/style.448ab192.css"><style data-stx-cloak>[x-cloak]{display:none !important}</style><link data-crosswind="generated" rel="stylesheet" href="/_stx/crosswind.616c25f3.css"></head><body class="auth-page"><main class="auth-card" id="main-content"><a class="brand" href="/"><span class="dot"></span><span>ts-cloud</span></a><div><span class="context-label">Organization invitation</span><h1>Join your team</h1><p>Choose the dashboard username and password you will use after this invitation is accepted.</p></div><form id="accept-invitation-form" class="auth-form"><div class="field-block"><label for="invite-name">Name</label><input id="invite-name" name="name" autocomplete="name" placeholder="Chris Breuer"></div><div class="field-block"><label for="invite-username">Username</label><input id="invite-username" name="username" autocomplete="username" minlength="2" maxlength="32" required></div><div class="field-block"><label for="invite-password">Password</label><input id="invite-password" name="password" type="password" autocomplete="new-password" minlength="12" required><small>At least 12 characters.</small></div><button class="btn" type="submit">Accept invitation</button><div id="invitation-status" class="auth-status" role="status"></div></form><p class="note">If this link expired or was already used, ask an organization owner to resend the invitation.</p></main> <script data-stx-scoped data-stx-run="always">
2
2
  ;(function() {
3
3
  'use strict';
4
4
  (() => {