@stacksjs/ts-cloud 0.16.50 → 0.16.51

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 (104) hide show
  1. package/dist/bin/{chunk-cw3rhg1c.js → chunk-20dp8658.js} +1 -1
  2. package/dist/bin/{chunk-k9f94hg4.js → chunk-45thdtvf.js} +165 -165
  3. package/dist/bin/{chunk-7cs9nnjy.js → chunk-5c4xh61a.js} +1 -1
  4. package/dist/bin/chunk-67vf8myy.js +1 -0
  5. package/dist/bin/{chunk-e6ewfmbp.js → chunk-83brtkvn.js} +1 -1
  6. package/dist/bin/chunk-87g6jcfm.js +1 -0
  7. package/dist/bin/{chunk-11y7yang.js → chunk-93yw46n7.js} +1 -1
  8. package/dist/bin/{chunk-qsfhb3x7.js → chunk-9qdrv6zp.js} +1 -1
  9. package/dist/bin/{chunk-j2wkxp7d.js → chunk-a7hhzbvm.js} +1 -1
  10. package/dist/bin/{chunk-hdqxyxs0.js → chunk-cjagqdk3.js} +5 -5
  11. package/dist/bin/{chunk-mdkd46c5.js → chunk-d24ztt54.js} +1 -1
  12. package/dist/bin/{chunk-f2t67d76.js → chunk-ddyd6f14.js} +1 -1
  13. package/dist/bin/{chunk-y12vn1h1.js → chunk-f0vedy45.js} +1 -1
  14. package/dist/bin/{chunk-w89fyres.js → chunk-f578z20t.js} +1 -1
  15. package/dist/bin/{chunk-e7pce8jb.js → chunk-f78wmcvb.js} +1 -1
  16. package/dist/bin/{chunk-vavwhhrp.js → chunk-fhe0mdjg.js} +1 -1
  17. package/dist/bin/chunk-g6ph425d.js +1 -0
  18. package/dist/bin/{chunk-7jj0g6jk.js → chunk-gc199s7a.js} +4 -4
  19. package/dist/bin/chunk-m5jvp6ph.js +1 -0
  20. package/dist/bin/{chunk-9ehb4hc6.js → chunk-n5kdne4p.js} +1 -1
  21. package/dist/bin/{chunk-tcj1z34y.js → chunk-ngmewar1.js} +1 -1
  22. package/dist/bin/{chunk-xaqkj8fn.js → chunk-p6wxv8yq.js} +1 -1
  23. package/dist/bin/{chunk-f4mpkpbf.js → chunk-vpt43nwa.js} +1 -1
  24. package/dist/bin/{chunk-kmpvqby6.js → chunk-wv8060cw.js} +1 -1
  25. package/dist/bin/{chunk-r524t8v8.js → chunk-zywk12mp.js} +1 -1
  26. package/dist/bin/cli.js +16 -16
  27. package/dist/bin/dashboard-server.js +1 -1
  28. package/dist/chunk-2gqm2h84.js +1 -0
  29. package/dist/{chunk-5hgcr7r2.js → chunk-53kyxata.js} +2 -2
  30. package/dist/{chunk-zbx9yehq.js → chunk-6gnmrtp9.js} +1 -1
  31. package/dist/{chunk-85fyadq0.js → chunk-dw0cvqdr.js} +13 -13
  32. package/dist/{chunk-a8hs75xd.js → chunk-p101nhg2.js} +1 -1
  33. package/dist/{chunk-18h7na1g.js → chunk-prtvb2fh.js} +27 -27
  34. package/dist/{chunk-cpba1hz2.js → chunk-pz33w7gv.js} +1 -1
  35. package/dist/{chunk-nnnhq6sx.js → chunk-qcv4twc6.js} +1 -1
  36. package/dist/{chunk-nmnf1ha6.js → chunk-x4qye2rc.js} +1 -1
  37. package/dist/{chunk-fqgvackc.js → chunk-xgc6hskd.js} +1 -1
  38. package/dist/deploy/index.js +1 -1
  39. package/dist/drivers/index.js +1 -1
  40. package/dist/index.js +1 -1
  41. package/dist/mail/index.js +2 -2
  42. package/dist/operations/index.js +1 -1
  43. package/dist/protection/index.js +1 -1
  44. package/dist/spend/index.js +1 -1
  45. package/dist/ui/404.html +1 -1
  46. package/dist/ui/accept-invitation.html +1 -1
  47. package/dist/ui/access-denied.html +1 -1
  48. package/dist/ui/account/automation.html +6 -6
  49. package/dist/ui/account/security.html +2 -2
  50. package/dist/ui/applications/compose.html +6 -6
  51. package/dist/ui/applications/new.html +2 -2
  52. package/dist/ui/data/backups.html +6 -6
  53. package/dist/ui/data/services.html +5 -5
  54. package/dist/ui/data/volumes.html +5 -5
  55. package/dist/ui/index.html +6 -6
  56. package/dist/ui/infrastructure/topology.html +5 -5
  57. package/dist/ui/integrations.html +1 -1
  58. package/dist/ui/operations/alerts.html +5 -5
  59. package/dist/ui/operations/configuration.html +6 -6
  60. package/dist/ui/operations/jobs.html +6 -6
  61. package/dist/ui/operations/maintenance.html +6 -6
  62. package/dist/ui/operations/observability.html +6 -6
  63. package/dist/ui/operations/previews.html +6 -6
  64. package/dist/ui/operations/queue.html +6 -6
  65. package/dist/ui/operations/regions.html +6 -6
  66. package/dist/ui/operations/releases.html +6 -6
  67. package/dist/ui/operations/spend.html +6 -6
  68. package/dist/ui/operations/workloads.html +6 -6
  69. package/dist/ui/security.html +1 -1
  70. package/dist/ui/server/actions.html +6 -6
  71. package/dist/ui/server/activity.html +2 -2
  72. package/dist/ui/server/capacity.html +6 -6
  73. package/dist/ui/server/database.html +6 -6
  74. package/dist/ui/server/deployments.html +5 -5
  75. package/dist/ui/server/diagnostics.html +2 -2
  76. package/dist/ui/server/firewall.html +6 -6
  77. package/dist/ui/server/fleet.html +5 -5
  78. package/dist/ui/server/logs.html +5 -5
  79. package/dist/ui/server/metrics.html +5 -5
  80. package/dist/ui/server/security.html +2 -2
  81. package/dist/ui/server/services.html +1 -1
  82. package/dist/ui/server/sites.html +6 -6
  83. package/dist/ui/server/ssh-keys.html +6 -6
  84. package/dist/ui/server/team.html +6 -6
  85. package/dist/ui/server/terminal.html +2 -2
  86. package/dist/ui/serverless/alarms.html +6 -6
  87. package/dist/ui/serverless/assets.html +2 -2
  88. package/dist/ui/serverless/cost.html +2 -2
  89. package/dist/ui/serverless/data.html +6 -6
  90. package/dist/ui/serverless/deployments.html +2 -2
  91. package/dist/ui/serverless/firewall.html +1 -1
  92. package/dist/ui/serverless/functions.html +6 -6
  93. package/dist/ui/serverless/logs.html +6 -6
  94. package/dist/ui/serverless/metrics.html +2 -2
  95. package/dist/ui/serverless/queues.html +6 -6
  96. package/dist/ui/serverless/secrets.html +6 -6
  97. package/dist/ui/serverless/traces.html +5 -5
  98. package/dist/ui/serverless.html +5 -5
  99. package/package.json +3 -3
  100. package/dist/bin/chunk-512ecg6y.js +0 -1
  101. package/dist/bin/chunk-7ewbxsan.js +0 -1
  102. package/dist/bin/chunk-q9awn1n3.js +0 -1
  103. package/dist/bin/chunk-v2qk9jeb.js +0 -1
  104. package/dist/chunk-r4kedmas.js +0 -1
@@ -1 +1 @@
1
- import"./chunk-k9f94hg4.js";import"./chunk-33ntxz01.js";import"./chunk-kmpvqby6.js";import"./chunk-7cs9nnjy.js";import{dr}from"./chunk-7jj0g6jk.js";import"./chunk-z06jkvvr.js";import"./chunk-dv2he3vc.js";import"./chunk-0wtshht7.js";import"./chunk-tcj1z34y.js";import"./chunk-mdkd46c5.js";import"./chunk-hhmqsrfc.js";import"./chunk-f2t67d76.js";import"./chunk-te52z1wk.js";import"./chunk-da6dmacg.js";import"./chunk-7czb1kgg.js";import"./chunk-we2raqk3.js";import"./chunk-q2rqmc2x.js";import"./chunk-yfa84s0c.js";import"./chunk-5ny7rggt.js";import"./chunk-hdqxyxs0.js";import"./chunk-9ehb4hc6.js";import"./chunk-t970yjvz.js";import"./chunk-j2wkxp7d.js";import"./chunk-e7pce8jb.js";import"./chunk-gr1ra9nj.js";import"./chunk-ppd463ev.js";import"./chunk-rwbdtxte.js";import n from"node:process";function r(o){let e=n.argv.indexOf(o);return e===-1?void 0:n.argv[e+1]}function t(o){return n.argv.includes(o)}async function i(){let o=await dr({host:r("--host")??"127.0.0.1",port:Number(r("--port")??7676),environment:r("--env"),box:t("--box"),verbose:t("--verbose")});console.log("ts-cloud Local Dashboard"),console.log(`Serving ${o.url}`),await new Promise((e)=>{let s=()=>{o.server.stop(!0),e()};n.once("SIGINT",s),n.once("SIGTERM",s)})}i();
1
+ import"./chunk-45thdtvf.js";import"./chunk-33ntxz01.js";import"./chunk-wv8060cw.js";import"./chunk-5c4xh61a.js";import{dr}from"./chunk-gc199s7a.js";import"./chunk-z06jkvvr.js";import"./chunk-dv2he3vc.js";import"./chunk-0wtshht7.js";import"./chunk-ngmewar1.js";import"./chunk-d24ztt54.js";import"./chunk-hhmqsrfc.js";import"./chunk-ddyd6f14.js";import"./chunk-te52z1wk.js";import"./chunk-da6dmacg.js";import"./chunk-7czb1kgg.js";import"./chunk-we2raqk3.js";import"./chunk-q2rqmc2x.js";import"./chunk-yfa84s0c.js";import"./chunk-5ny7rggt.js";import"./chunk-cjagqdk3.js";import"./chunk-n5kdne4p.js";import"./chunk-t970yjvz.js";import"./chunk-a7hhzbvm.js";import"./chunk-f78wmcvb.js";import"./chunk-gr1ra9nj.js";import"./chunk-ppd463ev.js";import"./chunk-rwbdtxte.js";import n from"node:process";function r(o){let e=n.argv.indexOf(o);return e===-1?void 0:n.argv[e+1]}function t(o){return n.argv.includes(o)}async function i(){let o=await dr({host:r("--host")??"127.0.0.1",port:Number(r("--port")??7676),environment:r("--env"),box:t("--box"),verbose:t("--verbose")});console.log("ts-cloud Local Dashboard"),console.log(`Serving ${o.url}`),await new Promise((e)=>{let s=()=>{o.server.stop(!0),e()};n.once("SIGINT",s),n.once("SIGTERM",s)})}i();
@@ -0,0 +1 @@
1
+ import{ac}from"./chunk-p101nhg2.js";import"./chunk-qcj3hkba.js";import"./chunk-ca191b00.js";import"./chunk-prtvb2fh.js";import"./chunk-6m8p1n88.js";export{ac as buildAndPushServerlessImage};
@@ -1,4 +1,4 @@
1
- import{jd,Q,l,Kd,K,g,be,p,sr,Xd,Gi,Oo,tl,il,sl,wl,ln,Wi,gr,Rl,Dl,Ol,_l}from"./chunk-18h7na1g.js";import{Ie,Yt,x,Zt,s,Di,co,jr,md,fd,ae,c,go,We,zr,hd,mo,Ad,Kr,fo,er,Wr,ki,nr,_i,Li,Je,ir,Md,Fd,Mi,Fi,vt,Do,i,Ui,No,ko}from"./chunk-zbx9yehq.js";import{n}from"./chunk-ca191b00.js";import{Re}from"./chunk-0qgfe5ff.js";import{o}from"./chunk-j99nkav5.js";import{Te,Sr,Ps,dt,re,pe,v,we,Cr,me,ut,vr}from"./chunk-jytama4e.js";import{ne}from"./chunk-4abbccq7.js";import{T,Nr,qs,Kt,kr,vg,Wt,Tg,wg,Bc,qe,ht,oi,F,Jt,Fr}from"./chunk-85fyadq0.js";import{U,d}from"./chunk-cpba1hz2.js";import{xn}from"./chunk-8b2mxhcm.js";import{On,dg,vs,L,P,Ts,lg}from"./chunk-a8hs75xd.js";import{S}from"./chunk-0cz2s19h.js";import{He}from"./chunk-qcj3hkba.js";import{Be}from"./chunk-thdfk76k.js";import{h}from"./chunk-zf5wdx6v.js";import{existsSync as DI}from"node:fs";import{join as Xh}from"node:path";import{pathToFileURL as OI}from"node:url";import{existsSync as Vm,statSync as Wm}from"fs";import{resolve as Ks}from"path";import ww from"process";import{existsSync as Ew,mkdirSync as yT,readdirSync as vT,readFileSync as Rw,writeFileSync as bT}from"fs";import{homedir as Lo}from"os";import{dirname as kT,resolve as Zn}from"path";import ld from"process";import{existsSync as Hm,statSync as Km}from"fs";import{existsSync as op,mkdirSync as Aw,readdirSync as Cw,writeFileSync as Pw}from"fs";import{homedir as Fo}from"os";import{dirname as Jm,resolve as Jr}from"path";import io from"process";import{join as _w,relative as Tw,resolve as Gm}from"path";import Yc from"process";import{existsSync as vh,mkdirSync as DT,readdirSync as OT,writeFileSync as $T}from"fs";import{homedir as Pl}from"os";import{dirname as BT,resolve as Hr}from"path";import Gs from"process";import{join as xw,relative as Dw,resolve as Qm}from"path";import Zc from"process";import{existsSync as bh,mkdirSync as UT,readdirSync as qT,writeFileSync as VT}from"fs";import{dirname as HT,resolve as Xc}from"path";import sp from"process";import{Buffer as Pi}from"buffer";import{createCipheriv as Ow,createDecipheriv as $w,randomBytes as Tl}from"crypto";import{closeSync as xl,createReadStream as Ym,createWriteStream as Nw,existsSync as $l,fsyncSync as Zm,openSync as Xm,writeFileSync as jw}from"fs";import{access as Bw,constants as ef,mkdir as Mw,readdir as xc,rename as tf,stat as zo,unlink as Dc,writeFile as Nl}from"fs/promises";import{join as Uo}from"path";import Tr from"process";import{pipeline as Lw}from"stream/promises";import{createGzip as rf}from"zlib";import qo from"process";import li from"process";import{Buffer as ci}from"buffer";import{createCipheriv as Fw,createDecipheriv as zw,randomBytes as Bl}from"crypto";import{closeSync as Ml,createReadStream as nf,createWriteStream as Uw,existsSync as Oc,fsyncSync as of,openSync as sf,writeFileSync as qw}from"fs";import{access as Vw,constants as af,mkdir as Ww,readdir as $c,rename as cf,stat as Vo,unlink as Nc,writeFile as Ll}from"fs/promises";import{isAbsolute as Hw,join as Wo,resolve as Kw}from"path";import At from"process";import{pipeline as Jw}from"stream/promises";import{createGzip as df}from"zlib";import Ho from"process";import ui from"process";import jc from"process";import{existsSync as Mc}from"fs";import{resolve as Fl}from"path";import{existsSync as Gw}from"fs";import{existsSync as Qw,readdirSync as Yw}from"fs";import{extname as Ul,resolve as lf}from"path";import Zw from"process";import{join as Xw,relative as ek,resolve as uf}from"path";import ed from"process";import{Buffer as di}from"buffer";import{createCipheriv as tk,createDecipheriv as rk,randomBytes as Vl}from"crypto";import{closeSync as Hl,createReadStream as pf,createWriteStream as nk,existsSync as Lc,fsyncSync as gf,openSync as mf,writeFileSync as ik}from"fs";import{access as ok,constants as ff,mkdir as sk,readdir as Fc,rename as hf,stat as Ko,unlink as zc,writeFile as Gl}from"fs/promises";import{isAbsolute as ak,join as Jo,resolve as ck}from"path";import Ct from"process";import{pipeline as dk}from"stream/promises";import{createGzip as yf}from"zlib";import Go from"process";import pi from"process";import qc from"process";import{existsSync as Vc}from"fs";import{resolve as gh}from"path";import{existsSync as _I}from"fs";class mh{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,a])=>r.timestamp.getTime()-a.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,a){if(!this.options.enabled)return;let u=this.generateKey(e,r),m=a??this.options.ttl,f=this.estimateSize(t);this.cache.set(u,{value:t,timestamp:new Date,ttl:m,hits:0,size:f}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),a=this.cache.get(r);if(!a){this.totalMisses++;return}if(this.isExpired(a)){this.cache.delete(r),this.totalMisses++;return}return a.hits++,this.totalHits++,a.value}isFileModified(e,t){try{if(!Vm(e))return!0;return Wm(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,a){try{let u=Vm(r)?Wm(r):null,m=u?u.mtime:new Date;this.set(e,{value:t,fileTimestamp:m},r,a)}catch{this.set(e,t,r,a)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((a,u)=>a+u.size,0),r=e.map((a)=>a.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let a=r;this.cache.set(t,{value:a.value,timestamp:new Date(a.timestamp),ttl:a.ttl,hits:a.hits,size:a.size})}}}class fh{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),u=new Date;try{let m=await t(),f=performance.now()-a;return this.recordMetric({operation:e,duration:f,timestamp:u,...r}),m}catch(m){let f=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:f,timestamp:u,...r}),m}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((u)=>u.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((u)=>u.duration),a=r.reduce((u,m)=>u+m,0);return{count:t.length,averageDuration:a/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:a,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}var Qc=new mh,yp=new fh;var hh=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function yh(e={}){let{name:t="",alias:r}=e,a=["config",".config"];if(t)a.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let u=r===void 0?[]:Array.isArray(r)?r:[r];for(let m of u){if(!m)continue;if(a.push(m,`.${m}.config`,`${m}.config`,`.${m}`),t)a.push(`${t}.${m}.config`,`.${t}.${m}.config`)}return Array.from(new Set(a.filter(Boolean)))}function kw(e){return yh(e).flatMap((r)=>hh.map((a)=>Ks(e.directory,`${r}${a}`)))}function Iw(e={}){let t=Ks(e.cwd||ww.cwd());return Array.from(new Set([t,Ks(t,"config"),Ks(t,".config"),e.configDir?Ks(t,e.configDir):void 0].filter((r)=>Boolean(r))))}var lk=Object.defineProperty,uk=(e)=>e;function pk(e,t){this[e]=uk.bind(null,t)}var gk=(e,t)=>{for(var r in t)lk(e,r,{get:t[r],enumerable:!0,configurable:!0,set:pk.bind(t,r)})},mk=(e,t)=>()=>(e&&(t=e(e=0)),t),Sh={};gk(Sh,{withErrorRecovery:()=>Ih,tryLoadConfig:()=>Bk,loadConfigWithResult:()=>Nk,loadConfig:()=>Ph,isRetryableError:()=>_k,isConfigNotFoundError:()=>Pk,isBunfigError:()=>Eh,globalPerformanceMonitor:()=>Zs,globalCache:()=>Qo,getEnvOrDefault:()=>Tk,generateConfigTypes:()=>Mk,defaultGeneratedDir:()=>jh,defaultConfigDir:()=>Nh,deepMergeWithArrayStrategy:()=>kp,deepMerge:()=>Rh,createLibraryConfig:()=>Lk,config:()=>jk,bunfigPlugin:()=>Fk,applyEnvVarsToConfig:()=>Js,TypeGenerationError:()=>gp,SchemaValidationError:()=>Ys,PluginError:()=>fp,PerformanceMonitor:()=>bp,FileSystemError:()=>pp,ErrorFactory:()=>Ti,EnvVarError:()=>sd,EnvProcessor:()=>ud,ConfigValidator:()=>Ip,ConfigValidationError:()=>lp,ConfigNotFoundError:()=>od,ConfigMergeError:()=>up,ConfigLoader:()=>Ep,ConfigLoadError:()=>Qs,ConfigFileLoader:()=>pd,ConfigCache:()=>vp,CacheUtils:()=>Th,BunfigError:()=>cn,BrowserConfigError:()=>mp,ArrayMergeStrategies:()=>Oh});class vp{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,a])=>r.timestamp.getTime()-a.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,a){if(!this.options.enabled)return;let u=this.generateKey(e,r),m=a??this.options.ttl,f=this.estimateSize(t);this.cache.set(u,{value:t,timestamp:new Date,ttl:m,hits:0,size:f}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),a=this.cache.get(r);if(!a){this.totalMisses++;return}if(this.isExpired(a)){this.cache.delete(r),this.totalMisses++;return}return a.hits++,this.totalHits++,a.value}isFileModified(e,t){try{if(!Hm(e))return!0;return Km(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,a){try{let u=Hm(r)?Km(r):null,m=u?u.mtime:new Date;this.set(e,{value:t,fileTimestamp:m},r,a)}catch{this.set(e,t,r,a)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((a,u)=>a+u.size,0),r=e.map((a)=>a.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let a=r;this.cache.set(t,{value:a.value,timestamp:new Date(a.timestamp),ttl:a.ttl,hits:a.hits,size:a.size})}}}class bp{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),u=new Date;try{let m=await t(),f=performance.now()-a;return this.recordMetric({operation:e,duration:f,timestamp:u,...r}),m}catch(m){let f=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:f,timestamp:u,...r}),m}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((u)=>u.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((u)=>u.duration),a=r.reduce((u,m)=>u+m,0);return{count:t.length,averageDuration:a/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:a,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function fk(e,t={}){let a=Object.keys(t).sort().map((u)=>`${u}:${t[u]}`).join("|");return a?`${e}:${a}`:e}function hk(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function yk(e){return e.getStats().size*2}function Sp(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Vt(t[0])&&"id"in t[0]&&t[0].id===3&&Vt(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Vt(t)&&Vt(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(Vt(e)&&"arr"in e&&Array.isArray(e.arr)&&Vt(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Vt(t[0])&&Vt(e[0])){let a=[...t];for(let u of e)if(Vt(u)&&"name"in u){if(!a.find((f)=>Vt(f)&&("name"in f)&&f.name===u.name))a.push(u)}else if(Vt(u)&&"path"in u){if(!a.find((f)=>Vt(f)&&("path"in f)&&f.path===u.path))a.push(u)}else if(!a.some((m)=>td(m,u)))a.push(u);return a}if(t.every((a)=>typeof a==="string")&&e.every((a)=>typeof a==="string")){let a=[...t];for(let u of e)if(!a.includes(u))a.push(u);return a}return t}if(!Vt(t)||!Vt(e))return t;let r={...e};for(let a in t)if(Object.prototype.hasOwnProperty.call(t,a)){let u=t[a];if(u===null||u===void 0)continue;else if(Vt(u)&&Vt(r[a]))r[a]=Sp(r[a],u);else if(Array.isArray(u)&&Array.isArray(r[a]))if(u.length>0&&r[a].length>0&&Vt(u[0])&&Vt(r[a][0])){let m=[...u];for(let f of r[a])if(Vt(f)&&"name"in f){if(!m.find((w)=>Vt(w)&&("name"in w)&&w.name===f.name))m.push(f)}else if(Vt(f)&&"path"in f){if(!m.find((w)=>Vt(w)&&("path"in w)&&w.path===f.path))m.push(f)}else if(!m.some((b)=>td(b,f)))m.push(f);r[a]=m}else if(u.every((m)=>typeof m==="string")&&r[a].every((m)=>typeof m==="string")){let m=[...u];for(let f of r[a])if(!m.includes(f))m.push(f);r[a]=m}else r[a]=u;else r[a]=u}return r}function td(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!td(e[r],t[r]))return!1;return!0}if(Vt(e)&&Vt(t)){let r=Object.keys(e),a=Object.keys(t);if(r.length!==a.length)return!1;for(let u of r){if(!Object.prototype.hasOwnProperty.call(t,u))return!1;if(!td(e[u],t[u]))return!1}return!0}return!1}function Vt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function vk(e,t){if(!bh(e))return null;try{let r=await import(e),a=r.default||r;if(typeof a!=="object"||a===null||Array.isArray(a))return null;try{return Sp(t,a)}catch{return null}}catch{return null}}async function bk({name:e="",cwd:t,defaultConfig:r}){let a=t||sp.cwd(),u=[".ts",".js",".mjs",".cjs",".json"],m=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let f of m)for(let b of u){let w=Xc(a,`${f}${b}`),y=await vk(w,r);if(y!==null)return y}try{let f=Xc(a,"package.json");if(bh(f)){let w=(await import(f))[e];if(w&&typeof w==="object"&&!Array.isArray(w))try{return Sp(r,w)}catch{}}}catch{}return r}function Sk(e,t={}){let r=Zc.cwd();while(r.includes("storage"))r=Qm(r,"..");let a=Qm(r,e||"");if(t?.relative)return Dw(Zc.cwd(),a);return a}async function wk(){try{let e=await bk({name:"clarity",defaultConfig:Hc,cwd:Zc.cwd(),endpoint:"",headers:{}});return{...Hc,...e}}catch{return Hc}}function tr(){if(li.env.NODE_ENV==="test"||li.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function kk(){if(li.env.NODE_ENV==="test"||li.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof li<"u"){let e=li.type;if(e==="renderer"||e==="worker")return!1;return!!(li.versions&&(li.versions.node||li.versions.bun))}return!1}class wh{async format(e){let t=await kk(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:qo.pid,hostname:t(),environment:qo.env.NODE_ENV||"development",platform:qo.platform,version:qo.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:qo.env.NODE_ENV||qo.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class rd{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...cp},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new wh,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Tr.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},a=t.timestamp!==void 0;if(a)delete r.timestamp;if(this.config={...this.config,...r,timestamp:a||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let u=this.generateKeyId(),m=this.generateKey();this.currentKeyId=u,this.keys.set(u,m),this.encryptionKeys.set(u,{key:m,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Kc,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Kc};return{...Kc,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:cp.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,a])=>a!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let u,m=0,f=3,b=1000;while(m<f)try{try{try{await Bw(this.config.logDirectory,ef.F_OK|ef.W_OK)}catch(y){if(y instanceof Error&&"code"in y)if(y.code==="ENOENT")await Mw(this.config.logDirectory,{recursive:!0,mode:493});else if(y.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw y;else throw y}}catch(y){throw console.error("Debug: [writeToFile] Failed to create log directory:",y),y}let w=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Pi.from(e);try{if(!$l(this.currentLogFile))await Nl(this.currentLogFile,"",{mode:420});if(u=Xm(this.currentLogFile,"a",420),jw(u,w,{flag:"a"}),Zm(u),u!==void 0)xl(u),u=void 0;if((await zo(this.currentLogFile)).size===0){if(await Nl(this.currentLogFile,w,{flag:"w",mode:420}),(await zo(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(y){let I=y;if(I.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(I.code)){if(m<f-1){let A=typeof I.message==="string"?I.message:"Unknown error";console.error(`Network error during write attempt ${m+1}/${f}:`,A);let D=b*2**m;await new Promise((O)=>setTimeout(O,D)),m++;continue}}if(I?.code&&["ENOSPC","EDQUOT"].includes(I.code))throw Error(`Disk quota exceeded or no space left on device: ${I.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",I),I}finally{if(u!==void 0)try{xl(u)}catch(y){console.error("Debug: [writeToFile] Error closing file descriptor:",y)}}}catch(w){if(m===f-1){let I=w,A=typeof I.message==="string"?I.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),w}m++;let y=b*2**(m-1);await new Promise((I)=>setTimeout(I,y))}})();this.pendingOperations.push(r);let a=this.pendingOperations.length-1;try{await r}catch(u){throw console.error("Debug: [writeToFile] Error in operation:",u),u}finally{this.pendingOperations.splice(a,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Uo(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Uo(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Uo(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(tr())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,a=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((u)=>{console.error("Error rotating keys:",u)})},a)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),a=this.generateKey();this.currentKeyId=r,this.keys.set(r,a),this.encryptionKeys.set(r,{key:a,createdAt:new Date});let u=Array.from(this.encryptionKeys.entries()).sort(([,b],[,w])=>w.createdAt.getTime()-b.createdAt.getTime()),m=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,m);if(u.length>f)for(let[b]of u.slice(f))this.encryptionKeys.delete(b),this.keys.delete(b)}generateKeyId(){return Tl(16).toString("hex")}generateKey(){return Tl(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Tl(16),a=Ow("aes-256-gcm",t,r),u=Pi.concat([a.update(e,"utf8"),a.final()]),m=a.getAuthTag();return{encrypted:Pi.concat([r,u,m]),iv:r}}async compressData(e){return new Promise((t,r)=>{let a=rf(),u=[];a.on("data",(m)=>u.push(m)),a.on("end",()=>t(Pi.from(Pi.concat(u)))),a.on("error",r),a.write(e),a.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(tr())return;let e=await zo(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,a=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let u=await xc(this.config.logDirectory),m=u.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,y)=>{let I=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-I}),f=m.length>0?Number.parseInt(m[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,b=`${r}.${f}`;if(await zo(r).catch(()=>null))try{if(await tf(r,b),t.compress)try{let w=`${b}.gz`;await this.compressLogFile(b,w),await Dc(b)}catch(w){console.error("Error compressing rotated file:",w)}if(m.length===0&&!u.some((w)=>w.endsWith(".log.1")))try{let w=`${r}.1`;await Nl(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let u=new Date().toISOString().replace(/[:.]/g,"-"),m=r.replace(/\.log$/,`-${u}.log`);if(await zo(r).catch(()=>null))await tf(r,m)}if(this.currentLogFile=a,t.maxFiles){let m=(await xc(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,b)=>b.localeCompare(f));for(let f of m.slice(t.maxFiles))await Dc(Uo(this.config.logDirectory,f))}}}async compressLogFile(e,t){let r=Ym(e),a=Nw(t),u=rf();await Lw(r,u,a)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let a=await this.formatter.format(r);await this.writeToFile(a),console.log(a)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),$l(this.currentLogFile))try{let e=Xm(this.currentLogFile,"r+");Zm(e),xl(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!tr()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await xc(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Dc(Uo(this.config.logDirectory,r))}catch(a){console.error(`Failed to delete temp file ${r}:`,a)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?Mt.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:a="",message:u,level:m,showTimestamp:f=!0}=e,b=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(f)O.push(t);if(m==="warning")O.push("WARN");else if(m==="error")O.push("ERROR");else if(r)O.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(a)O.push(a.replace(/[[\]]/g,""));return O.push(u),O.join(" ")}let w=Tr.stdout.columns||120,y="";if(m==="warning"||m==="error")y=`${r} ${u}`;else if(m==="info"||m==="success")y=`${r} ${a} ${u}`;else y=`${r} ${a} ${Mt.cyan(u)}`;if(!f)return y.trim();let I=b(y).trim().length,A=b(t).length,D=Math.max(1,w-2-I-A);return`${y.trim()}${" ".repeat(D)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(m,f)=>{let b=Number.parseInt(f,10);return b<t[0].length?String(t[0][b]):m});let r=/%([sdijfo%])/g,a=0,u=e.replace(r,(m,f)=>{if(f==="%")return"%";if(a>=t.length)return m;let b=t[a++];switch(f){case"s":return String(b);case"d":case"i":return Number(b).toString();case"j":case"o":return JSON.stringify(b,null,2);default:return m}});if(a<t.length)u+=` ${t.slice(a).map((m)=>typeof m==="object"?JSON.stringify(m,null,2):String(m)).join(" ")}`;return u}async log(e,t,...r){let a=new Date,u=this.formatConsoleTimestamp(a),m=this.formatFileTimestamp(a),f,b;if(t instanceof Error)f=t.message,b=t.stack;else f=this.formatMessage(t,r);if(this.fancy&&!tr()){let y=xh[e],I=this.options.showTags!==!1&&this.name?Mt.gray(this.formatTag(this.name)):"",A;switch(e){case"debug":A=this.formatConsoleMessage({timestamp:u,icon:y,tag:I,message:Mt.gray(f),level:e}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:u,icon:y,tag:I,message:f,level:e}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:u,icon:y,tag:I,message:Mt.green(f),level:e}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:u,icon:y,tag:I,message:f,level:e}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:u,icon:y,tag:I,message:f,level:e}),console.error(A),b){let D=b.split(`
1
+ import{jd,Q,l,Kd,K,g,be,p,sr,Xd,Gi,Oo,tl,il,sl,wl,ln,Wi,gr,Rl,Dl,Ol,_l}from"./chunk-prtvb2fh.js";import{Ie,Yt,x,Zt,s,Di,co,jr,md,fd,ae,c,go,We,zr,hd,mo,Ad,Kr,fo,er,Wr,ki,nr,_i,Li,Je,ir,Md,Fd,Mi,Fi,vt,Do,i,Ui,No,ko}from"./chunk-6gnmrtp9.js";import{n}from"./chunk-ca191b00.js";import{Re}from"./chunk-0qgfe5ff.js";import{o}from"./chunk-j99nkav5.js";import{Te,Sr,Ps,dt,re,pe,v,we,Cr,me,ut,vr}from"./chunk-jytama4e.js";import{ne}from"./chunk-4abbccq7.js";import{T,Nr,qs,Kt,kr,vg,Wt,Tg,wg,Bc,qe,ht,oi,F,Jt,Fr}from"./chunk-dw0cvqdr.js";import{U,d}from"./chunk-pz33w7gv.js";import{xn}from"./chunk-8b2mxhcm.js";import{On,dg,vs,L,P,Ts,lg}from"./chunk-p101nhg2.js";import{S}from"./chunk-0cz2s19h.js";import{He}from"./chunk-qcj3hkba.js";import{Be}from"./chunk-thdfk76k.js";import{h}from"./chunk-zf5wdx6v.js";import{existsSync as DI}from"node:fs";import{join as Xh}from"node:path";import{pathToFileURL as OI}from"node:url";import{existsSync as Vm,statSync as Wm}from"fs";import{resolve as Ks}from"path";import ww from"process";import{existsSync as Ew,mkdirSync as yT,readdirSync as vT,readFileSync as Rw,writeFileSync as bT}from"fs";import{homedir as Lo}from"os";import{dirname as kT,resolve as Zn}from"path";import ld from"process";import{existsSync as Hm,statSync as Km}from"fs";import{existsSync as op,mkdirSync as Aw,readdirSync as Cw,writeFileSync as Pw}from"fs";import{homedir as Fo}from"os";import{dirname as Jm,resolve as Jr}from"path";import io from"process";import{join as _w,relative as Tw,resolve as Gm}from"path";import Yc from"process";import{existsSync as vh,mkdirSync as DT,readdirSync as OT,writeFileSync as $T}from"fs";import{homedir as Pl}from"os";import{dirname as BT,resolve as Hr}from"path";import Gs from"process";import{join as xw,relative as Dw,resolve as Qm}from"path";import Zc from"process";import{existsSync as bh,mkdirSync as UT,readdirSync as qT,writeFileSync as VT}from"fs";import{dirname as HT,resolve as Xc}from"path";import sp from"process";import{Buffer as Pi}from"buffer";import{createCipheriv as Ow,createDecipheriv as $w,randomBytes as Tl}from"crypto";import{closeSync as xl,createReadStream as Ym,createWriteStream as Nw,existsSync as $l,fsyncSync as Zm,openSync as Xm,writeFileSync as jw}from"fs";import{access as Bw,constants as ef,mkdir as Mw,readdir as xc,rename as tf,stat as zo,unlink as Dc,writeFile as Nl}from"fs/promises";import{join as Uo}from"path";import Tr from"process";import{pipeline as Lw}from"stream/promises";import{createGzip as rf}from"zlib";import qo from"process";import li from"process";import{Buffer as ci}from"buffer";import{createCipheriv as Fw,createDecipheriv as zw,randomBytes as Bl}from"crypto";import{closeSync as Ml,createReadStream as nf,createWriteStream as Uw,existsSync as Oc,fsyncSync as of,openSync as sf,writeFileSync as qw}from"fs";import{access as Vw,constants as af,mkdir as Ww,readdir as $c,rename as cf,stat as Vo,unlink as Nc,writeFile as Ll}from"fs/promises";import{isAbsolute as Hw,join as Wo,resolve as Kw}from"path";import At from"process";import{pipeline as Jw}from"stream/promises";import{createGzip as df}from"zlib";import Ho from"process";import ui from"process";import jc from"process";import{existsSync as Mc}from"fs";import{resolve as Fl}from"path";import{existsSync as Gw}from"fs";import{existsSync as Qw,readdirSync as Yw}from"fs";import{extname as Ul,resolve as lf}from"path";import Zw from"process";import{join as Xw,relative as ek,resolve as uf}from"path";import ed from"process";import{Buffer as di}from"buffer";import{createCipheriv as tk,createDecipheriv as rk,randomBytes as Vl}from"crypto";import{closeSync as Hl,createReadStream as pf,createWriteStream as nk,existsSync as Lc,fsyncSync as gf,openSync as mf,writeFileSync as ik}from"fs";import{access as ok,constants as ff,mkdir as sk,readdir as Fc,rename as hf,stat as Ko,unlink as zc,writeFile as Gl}from"fs/promises";import{isAbsolute as ak,join as Jo,resolve as ck}from"path";import Ct from"process";import{pipeline as dk}from"stream/promises";import{createGzip as yf}from"zlib";import Go from"process";import pi from"process";import qc from"process";import{existsSync as Vc}from"fs";import{resolve as gh}from"path";import{existsSync as _I}from"fs";class mh{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,a])=>r.timestamp.getTime()-a.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,a){if(!this.options.enabled)return;let u=this.generateKey(e,r),m=a??this.options.ttl,f=this.estimateSize(t);this.cache.set(u,{value:t,timestamp:new Date,ttl:m,hits:0,size:f}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),a=this.cache.get(r);if(!a){this.totalMisses++;return}if(this.isExpired(a)){this.cache.delete(r),this.totalMisses++;return}return a.hits++,this.totalHits++,a.value}isFileModified(e,t){try{if(!Vm(e))return!0;return Wm(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,a){try{let u=Vm(r)?Wm(r):null,m=u?u.mtime:new Date;this.set(e,{value:t,fileTimestamp:m},r,a)}catch{this.set(e,t,r,a)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((a,u)=>a+u.size,0),r=e.map((a)=>a.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let a=r;this.cache.set(t,{value:a.value,timestamp:new Date(a.timestamp),ttl:a.ttl,hits:a.hits,size:a.size})}}}class fh{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),u=new Date;try{let m=await t(),f=performance.now()-a;return this.recordMetric({operation:e,duration:f,timestamp:u,...r}),m}catch(m){let f=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:f,timestamp:u,...r}),m}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((u)=>u.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((u)=>u.duration),a=r.reduce((u,m)=>u+m,0);return{count:t.length,averageDuration:a/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:a,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}var Qc=new mh,yp=new fh;var hh=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function yh(e={}){let{name:t="",alias:r}=e,a=["config",".config"];if(t)a.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let u=r===void 0?[]:Array.isArray(r)?r:[r];for(let m of u){if(!m)continue;if(a.push(m,`.${m}.config`,`${m}.config`,`.${m}`),t)a.push(`${t}.${m}.config`,`.${t}.${m}.config`)}return Array.from(new Set(a.filter(Boolean)))}function kw(e){return yh(e).flatMap((r)=>hh.map((a)=>Ks(e.directory,`${r}${a}`)))}function Iw(e={}){let t=Ks(e.cwd||ww.cwd());return Array.from(new Set([t,Ks(t,"config"),Ks(t,".config"),e.configDir?Ks(t,e.configDir):void 0].filter((r)=>Boolean(r))))}var lk=Object.defineProperty,uk=(e)=>e;function pk(e,t){this[e]=uk.bind(null,t)}var gk=(e,t)=>{for(var r in t)lk(e,r,{get:t[r],enumerable:!0,configurable:!0,set:pk.bind(t,r)})},mk=(e,t)=>()=>(e&&(t=e(e=0)),t),Sh={};gk(Sh,{withErrorRecovery:()=>Ih,tryLoadConfig:()=>Bk,loadConfigWithResult:()=>Nk,loadConfig:()=>Ph,isRetryableError:()=>_k,isConfigNotFoundError:()=>Pk,isBunfigError:()=>Eh,globalPerformanceMonitor:()=>Zs,globalCache:()=>Qo,getEnvOrDefault:()=>Tk,generateConfigTypes:()=>Mk,defaultGeneratedDir:()=>jh,defaultConfigDir:()=>Nh,deepMergeWithArrayStrategy:()=>kp,deepMerge:()=>Rh,createLibraryConfig:()=>Lk,config:()=>jk,bunfigPlugin:()=>Fk,applyEnvVarsToConfig:()=>Js,TypeGenerationError:()=>gp,SchemaValidationError:()=>Ys,PluginError:()=>fp,PerformanceMonitor:()=>bp,FileSystemError:()=>pp,ErrorFactory:()=>Ti,EnvVarError:()=>sd,EnvProcessor:()=>ud,ConfigValidator:()=>Ip,ConfigValidationError:()=>lp,ConfigNotFoundError:()=>od,ConfigMergeError:()=>up,ConfigLoader:()=>Ep,ConfigLoadError:()=>Qs,ConfigFileLoader:()=>pd,ConfigCache:()=>vp,CacheUtils:()=>Th,BunfigError:()=>cn,BrowserConfigError:()=>mp,ArrayMergeStrategies:()=>Oh});class vp{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,a])=>r.timestamp.getTime()-a.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,a){if(!this.options.enabled)return;let u=this.generateKey(e,r),m=a??this.options.ttl,f=this.estimateSize(t);this.cache.set(u,{value:t,timestamp:new Date,ttl:m,hits:0,size:f}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),a=this.cache.get(r);if(!a){this.totalMisses++;return}if(this.isExpired(a)){this.cache.delete(r),this.totalMisses++;return}return a.hits++,this.totalHits++,a.value}isFileModified(e,t){try{if(!Hm(e))return!0;return Km(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,a){try{let u=Hm(r)?Km(r):null,m=u?u.mtime:new Date;this.set(e,{value:t,fileTimestamp:m},r,a)}catch{this.set(e,t,r,a)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((a,u)=>a+u.size,0),r=e.map((a)=>a.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let a=r;this.cache.set(t,{value:a.value,timestamp:new Date(a.timestamp),ttl:a.ttl,hits:a.hits,size:a.size})}}}class bp{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),u=new Date;try{let m=await t(),f=performance.now()-a;return this.recordMetric({operation:e,duration:f,timestamp:u,...r}),m}catch(m){let f=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:f,timestamp:u,...r}),m}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((u)=>u.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((u)=>u.duration),a=r.reduce((u,m)=>u+m,0);return{count:t.length,averageDuration:a/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:a,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function fk(e,t={}){let a=Object.keys(t).sort().map((u)=>`${u}:${t[u]}`).join("|");return a?`${e}:${a}`:e}function hk(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function yk(e){return e.getStats().size*2}function Sp(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Vt(t[0])&&"id"in t[0]&&t[0].id===3&&Vt(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Vt(t)&&Vt(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(Vt(e)&&"arr"in e&&Array.isArray(e.arr)&&Vt(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Vt(t[0])&&Vt(e[0])){let a=[...t];for(let u of e)if(Vt(u)&&"name"in u){if(!a.find((f)=>Vt(f)&&("name"in f)&&f.name===u.name))a.push(u)}else if(Vt(u)&&"path"in u){if(!a.find((f)=>Vt(f)&&("path"in f)&&f.path===u.path))a.push(u)}else if(!a.some((m)=>td(m,u)))a.push(u);return a}if(t.every((a)=>typeof a==="string")&&e.every((a)=>typeof a==="string")){let a=[...t];for(let u of e)if(!a.includes(u))a.push(u);return a}return t}if(!Vt(t)||!Vt(e))return t;let r={...e};for(let a in t)if(Object.prototype.hasOwnProperty.call(t,a)){let u=t[a];if(u===null||u===void 0)continue;else if(Vt(u)&&Vt(r[a]))r[a]=Sp(r[a],u);else if(Array.isArray(u)&&Array.isArray(r[a]))if(u.length>0&&r[a].length>0&&Vt(u[0])&&Vt(r[a][0])){let m=[...u];for(let f of r[a])if(Vt(f)&&"name"in f){if(!m.find((w)=>Vt(w)&&("name"in w)&&w.name===f.name))m.push(f)}else if(Vt(f)&&"path"in f){if(!m.find((w)=>Vt(w)&&("path"in w)&&w.path===f.path))m.push(f)}else if(!m.some((b)=>td(b,f)))m.push(f);r[a]=m}else if(u.every((m)=>typeof m==="string")&&r[a].every((m)=>typeof m==="string")){let m=[...u];for(let f of r[a])if(!m.includes(f))m.push(f);r[a]=m}else r[a]=u;else r[a]=u}return r}function td(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!td(e[r],t[r]))return!1;return!0}if(Vt(e)&&Vt(t)){let r=Object.keys(e),a=Object.keys(t);if(r.length!==a.length)return!1;for(let u of r){if(!Object.prototype.hasOwnProperty.call(t,u))return!1;if(!td(e[u],t[u]))return!1}return!0}return!1}function Vt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function vk(e,t){if(!bh(e))return null;try{let r=await import(e),a=r.default||r;if(typeof a!=="object"||a===null||Array.isArray(a))return null;try{return Sp(t,a)}catch{return null}}catch{return null}}async function bk({name:e="",cwd:t,defaultConfig:r}){let a=t||sp.cwd(),u=[".ts",".js",".mjs",".cjs",".json"],m=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let f of m)for(let b of u){let w=Xc(a,`${f}${b}`),y=await vk(w,r);if(y!==null)return y}try{let f=Xc(a,"package.json");if(bh(f)){let w=(await import(f))[e];if(w&&typeof w==="object"&&!Array.isArray(w))try{return Sp(r,w)}catch{}}}catch{}return r}function Sk(e,t={}){let r=Zc.cwd();while(r.includes("storage"))r=Qm(r,"..");let a=Qm(r,e||"");if(t?.relative)return Dw(Zc.cwd(),a);return a}async function wk(){try{let e=await bk({name:"clarity",defaultConfig:Hc,cwd:Zc.cwd(),endpoint:"",headers:{}});return{...Hc,...e}}catch{return Hc}}function tr(){if(li.env.NODE_ENV==="test"||li.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function kk(){if(li.env.NODE_ENV==="test"||li.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof li<"u"){let e=li.type;if(e==="renderer"||e==="worker")return!1;return!!(li.versions&&(li.versions.node||li.versions.bun))}return!1}class wh{async format(e){let t=await kk(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:qo.pid,hostname:t(),environment:qo.env.NODE_ENV||"development",platform:qo.platform,version:qo.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:qo.env.NODE_ENV||qo.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class rd{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...cp},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new wh,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Tr.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},a=t.timestamp!==void 0;if(a)delete r.timestamp;if(this.config={...this.config,...r,timestamp:a||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let u=this.generateKeyId(),m=this.generateKey();this.currentKeyId=u,this.keys.set(u,m),this.encryptionKeys.set(u,{key:m,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Kc,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Kc};return{...Kc,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:cp.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,a])=>a!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let u,m=0,f=3,b=1000;while(m<f)try{try{try{await Bw(this.config.logDirectory,ef.F_OK|ef.W_OK)}catch(y){if(y instanceof Error&&"code"in y)if(y.code==="ENOENT")await Mw(this.config.logDirectory,{recursive:!0,mode:493});else if(y.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw y;else throw y}}catch(y){throw console.error("Debug: [writeToFile] Failed to create log directory:",y),y}let w=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Pi.from(e);try{if(!$l(this.currentLogFile))await Nl(this.currentLogFile,"",{mode:420});if(u=Xm(this.currentLogFile,"a",420),jw(u,w,{flag:"a"}),Zm(u),u!==void 0)xl(u),u=void 0;if((await zo(this.currentLogFile)).size===0){if(await Nl(this.currentLogFile,w,{flag:"w",mode:420}),(await zo(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(y){let I=y;if(I.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(I.code)){if(m<f-1){let A=typeof I.message==="string"?I.message:"Unknown error";console.error(`Network error during write attempt ${m+1}/${f}:`,A);let D=b*2**m;await new Promise((O)=>setTimeout(O,D)),m++;continue}}if(I?.code&&["ENOSPC","EDQUOT"].includes(I.code))throw Error(`Disk quota exceeded or no space left on device: ${I.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",I),I}finally{if(u!==void 0)try{xl(u)}catch(y){console.error("Debug: [writeToFile] Error closing file descriptor:",y)}}}catch(w){if(m===f-1){let I=w,A=typeof I.message==="string"?I.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),w}m++;let y=b*2**(m-1);await new Promise((I)=>setTimeout(I,y))}})();this.pendingOperations.push(r);let a=this.pendingOperations.length-1;try{await r}catch(u){throw console.error("Debug: [writeToFile] Error in operation:",u),u}finally{this.pendingOperations.splice(a,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Uo(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Uo(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Uo(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(tr())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,a=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((u)=>{console.error("Error rotating keys:",u)})},a)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),a=this.generateKey();this.currentKeyId=r,this.keys.set(r,a),this.encryptionKeys.set(r,{key:a,createdAt:new Date});let u=Array.from(this.encryptionKeys.entries()).sort(([,b],[,w])=>w.createdAt.getTime()-b.createdAt.getTime()),m=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,m);if(u.length>f)for(let[b]of u.slice(f))this.encryptionKeys.delete(b),this.keys.delete(b)}generateKeyId(){return Tl(16).toString("hex")}generateKey(){return Tl(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Tl(16),a=Ow("aes-256-gcm",t,r),u=Pi.concat([a.update(e,"utf8"),a.final()]),m=a.getAuthTag();return{encrypted:Pi.concat([r,u,m]),iv:r}}async compressData(e){return new Promise((t,r)=>{let a=rf(),u=[];a.on("data",(m)=>u.push(m)),a.on("end",()=>t(Pi.from(Pi.concat(u)))),a.on("error",r),a.write(e),a.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(tr())return;let e=await zo(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,a=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let u=await xc(this.config.logDirectory),m=u.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,y)=>{let I=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-I}),f=m.length>0?Number.parseInt(m[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,b=`${r}.${f}`;if(await zo(r).catch(()=>null))try{if(await tf(r,b),t.compress)try{let w=`${b}.gz`;await this.compressLogFile(b,w),await Dc(b)}catch(w){console.error("Error compressing rotated file:",w)}if(m.length===0&&!u.some((w)=>w.endsWith(".log.1")))try{let w=`${r}.1`;await Nl(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let u=new Date().toISOString().replace(/[:.]/g,"-"),m=r.replace(/\.log$/,`-${u}.log`);if(await zo(r).catch(()=>null))await tf(r,m)}if(this.currentLogFile=a,t.maxFiles){let m=(await xc(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,b)=>b.localeCompare(f));for(let f of m.slice(t.maxFiles))await Dc(Uo(this.config.logDirectory,f))}}}async compressLogFile(e,t){let r=Ym(e),a=Nw(t),u=rf();await Lw(r,u,a)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let a=await this.formatter.format(r);await this.writeToFile(a),console.log(a)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),$l(this.currentLogFile))try{let e=Xm(this.currentLogFile,"r+");Zm(e),xl(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!tr()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await xc(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Dc(Uo(this.config.logDirectory,r))}catch(a){console.error(`Failed to delete temp file ${r}:`,a)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?Mt.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:a="",message:u,level:m,showTimestamp:f=!0}=e,b=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(f)O.push(t);if(m==="warning")O.push("WARN");else if(m==="error")O.push("ERROR");else if(r)O.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(a)O.push(a.replace(/[[\]]/g,""));return O.push(u),O.join(" ")}let w=Tr.stdout.columns||120,y="";if(m==="warning"||m==="error")y=`${r} ${u}`;else if(m==="info"||m==="success")y=`${r} ${a} ${u}`;else y=`${r} ${a} ${Mt.cyan(u)}`;if(!f)return y.trim();let I=b(y).trim().length,A=b(t).length,D=Math.max(1,w-2-I-A);return`${y.trim()}${" ".repeat(D)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(m,f)=>{let b=Number.parseInt(f,10);return b<t[0].length?String(t[0][b]):m});let r=/%([sdijfo%])/g,a=0,u=e.replace(r,(m,f)=>{if(f==="%")return"%";if(a>=t.length)return m;let b=t[a++];switch(f){case"s":return String(b);case"d":case"i":return Number(b).toString();case"j":case"o":return JSON.stringify(b,null,2);default:return m}});if(a<t.length)u+=` ${t.slice(a).map((m)=>typeof m==="object"?JSON.stringify(m,null,2):String(m)).join(" ")}`;return u}async log(e,t,...r){let a=new Date,u=this.formatConsoleTimestamp(a),m=this.formatFileTimestamp(a),f,b;if(t instanceof Error)f=t.message,b=t.stack;else f=this.formatMessage(t,r);if(this.fancy&&!tr()){let y=xh[e],I=this.options.showTags!==!1&&this.name?Mt.gray(this.formatTag(this.name)):"",A;switch(e){case"debug":A=this.formatConsoleMessage({timestamp:u,icon:y,tag:I,message:Mt.gray(f),level:e}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:u,icon:y,tag:I,message:f,level:e}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:u,icon:y,tag:I,message:Mt.green(f),level:e}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:u,icon:y,tag:I,message:f,level:e}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:u,icon:y,tag:I,message:f,level:e}),console.error(A),b){let D=b.split(`
2
2
  `);for(let O of D)if(O.trim()&&!O.includes(f))console.error(this.formatConsoleMessage({timestamp:u,message:Mt.gray(` ${O}`),level:e,showTimestamp:!1}))}break}}else if(!tr()){if(console.error(`${m} ${this.environment}.${e.toUpperCase()}: ${f}`),b)console.error(b)}if(!this.shouldLog(e))return;let w=`${m} ${this.environment}.${e.toUpperCase()}: ${f}
3
3
  `;if(b)w+=`${b}
4
4
  `;w=w.replace(this.ANSI_PATTERN,""),await this.writeToFile(w)}time(e){let t=performance.now();if(this.fancy&&!tr()){let r=this.options.showTags!==!1&&this.name?Mt.gray(this.formatTag(this.name)):"",a=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:a,icon:Mt.blue("◐"),tag:r,message:`${Mt.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let a=performance.now(),u=Math.round(a-t),m=`${e} completed in ${u}ms`,f=new Date,b=this.formatConsoleTimestamp(f),y=`${this.formatFileTimestamp(f)} ${this.environment}.INFO: ${m}`;if(r)y+=` ${JSON.stringify(r)}`;if(y+=`
@@ -176,7 +176,7 @@ export const handler = async (event) => {
176
176
  body: JSON.stringify({ ok: statusCode === 200, service: 'ts-cloud-static-api', path, coldStart: currentColdStart, initializedAt })
177
177
  }
178
178
  }
179
- `;function Rv(e){let t=e;return String(t?.code||t?.name||t?.statusCode||"")}function RA(e){return["NoSuchEntity","ResourceNotFoundException","404"].includes(Rv(e))}function Iv(e){return["EntityAlreadyExists","ResourceAlreadyExistsException","ResourceConflictException","409"].includes(Rv(e))}function Ev(e,t){let r=e?.Items;if(!r)return[];if(Array.isArray(r))return r;let a=r[t];if(a===void 0)return[];return Array.isArray(a)?a:[a]}function Pg(e){let t=e?.Aliases?.Items,r=t?.CNAME??t;if(Array.isArray(r))return r.map(String);if(typeof r==="string")return[r];return[]}function AA(e){if(!/^[A-Z0-9]{8,32}$/.test(e.distributionId))throw Error("CloudFront distribution ID is invalid");if(!/^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9-]{2,63}$/.test(e.expectedAlias))throw Error("Expected CloudFront alias is invalid");if(!/^[A-Za-z0-9-_]{1,64}$/.test(e.functionName))throw Error("Lambda function name is invalid");let t=e.pathPattern?.startsWith("/")?e.pathPattern:`/${e.pathPattern||"api/*"}`;if(t==="/"||t==="/*"||!t.endsWith("*"))throw Error("API path must be a non-default wildcard pattern such as /api/*");let r=e.originId||`${e.functionName}-url`,a=e.roleName||`${e.functionName}-execution`;if(!/^[A-Za-z0-9_.-]{1,64}$/.test(a))throw Error("IAM role name is invalid");let u=e.memorySize??256,m=e.timeout??10,f=e.logRetentionDays??14;if(u<128||u>10240)throw Error("Lambda memory must be between 128 and 10240 MB");if(m<1||m>900)throw Error("Lambda timeout must be between 1 and 900 seconds");return{region:e.region||"us-east-1",pathPattern:t,originId:r,roleName:a,memorySize:u,timeout:m,logRetentionDays:f}}function rh(e){let t=e.region||"us-east-1";return{cloudfront:new S(e.profile),iam:new Re(t,e.profile),lambda:new v(t,e.profile),logs:new we(t,e.profile),sts:new Te(t,e.profile),sleep:(r)=>new Promise((a)=>setTimeout(a,r))}}async function xS(e,t){let r=AA(e),a=t||rh({profile:e.profile,region:r.region}),[u,m,f]=await Promise.all([a.sts.getCallerIdentity(),a.cloudfront.getDistribution(e.distributionId),a.cloudfront.getDistributionConfig(e.distributionId)]);if(!u.Account)throw Error("AWS identity did not return an account ID");if(!m.Enabled)throw Error(`CloudFront distribution ${e.distributionId} is disabled`);if(!(Pg(m).length?Pg(m):Pg(f.DistributionConfig)).includes(e.expectedAlias))throw Error(`Distribution ${e.distributionId} does not contain expected alias ${e.expectedAlias}`);let w,y=!0;try{w=await a.iam.getRole({RoleName:r.roleName})}catch(Ze){if(!RA(Ze))throw Ze;y=!1}let I=w?.Arn||`arn:aws:iam::${u.Account}:role/${r.roleName}`,A=await a.lambda.functionExists(e.functionName),D=A?await a.lambda.getFunctionUrl(e.functionName):null,O=await a.cloudfront.listOriginAccessControls(),M=`${e.functionName}-lambda-url`,z=O.some((Ze)=>Ze.Name===M&&Ze.OriginAccessControlOriginType==="lambda"),J=Ev(f.DistributionConfig.Origins,"Origin"),Z=Ev(f.DistributionConfig.CacheBehaviors,"CacheBehavior"),oe=J.some((Ze)=>String(Ze.Id)===r.originId),G=Z.some((Ze)=>String(Ze.PathPattern)===r.pathPattern),te=[...!y?[`create IAM execution role ${r.roleName}`]:[`reconcile IAM execution policy ${r.roleName}`],...A?[`update Lambda ${e.functionName} code and configuration`]:[`create Lambda ${e.functionName}`],...!D?["create private AWS_IAM function URL"]:[],...!z?[`create Lambda origin access control ${M}`]:[],"grant CloudFront function-URL and invocation permissions",`${G?"reconcile":"add"} ${r.pathPattern} behavior without changing the default behavior`],he={command:`cloud cdn:origin:remove ${e.distributionId} FUNCTION_URL_HOST --id ${r.originId} --path '${r.pathPattern}' --apply --confirm 'remove:${e.distributionId}:${r.pathPattern}'`,removeFunction:!A,removeRole:!y},ye={mode:e.apply?"apply":"plan",accountId:u.Account,identityArn:u.Arn,distribution:{id:m.Id,arn:m.ARN,alias:e.expectedAlias,domainName:m.DomainName,status:m.Status},function:{name:e.functionName,existed:A,runtime:"nodejs22.x",urlExisted:!!D,url:D?.FunctionUrl},role:{name:r.roleName,existed:y,arn:I},origin:{id:r.originId,pathPattern:r.pathPattern,existed:oe,behaviorExisted:G,accessControlExisted:z},changes:te,rollback:he,applied:!1};if(!e.apply)return ye;let ie=`${e.distributionId}:${r.pathPattern}`;if(e.confirm!==ie)throw Error(`Pass exact confirmation token ${ie} to mutate the live distribution`);if(!w)w=await a.iam.createRole({RoleName:r.roleName,Description:`Execution role for ${e.functionName}`,AssumeRolePolicyDocument:JSON.stringify({Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]}),Tags:[{Key:"ManagedBy",Value:"ts-cloud"}]});await a.iam.putRolePolicy({RoleName:r.roleName,PolicyName:"lambda-logs",PolicyDocument:JSON.stringify({Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogStream","logs:PutLogEvents"],Resource:`arn:aws:logs:${r.region}:${u.Account}:log-group:/aws/lambda/${e.functionName}:*`}]})});try{await a.logs.createLogGroup(`/aws/lambda/${e.functionName}`,{ManagedBy:"ts-cloud"})}catch(Ze){if(!Iv(Ze))throw Ze}await a.logs.putRetentionPolicy(`/aws/lambda/${e.functionName}`,r.logRetentionDays);let xe=e.code||EA;if(A)await a.lambda.updateFunctionCodeInline(e.functionName,xe,"index.mjs"),await a.lambda.waitForFunctionActive(e.functionName),await a.lambda.updateFunctionConfiguration({FunctionName:e.functionName,Runtime:"nodejs22.x",Role:w.Arn,Handler:"index.handler",Description:`Private API origin for ${e.expectedAlias}`,Timeout:r.timeout,MemorySize:r.memorySize});else{let Ze;for(let wt=0;wt<8;wt++)try{await a.lambda.createFunctionWithCode({FunctionName:e.functionName,Runtime:"nodejs22.x",Role:w.Arn,Handler:"index.handler",Code:xe,Filename:"index.mjs",Description:`Private API origin for ${e.expectedAlias}`,Timeout:r.timeout,MemorySize:r.memorySize}),Ze=void 0;break}catch(zt){if(Ze=zt,!String(zt.message).toLowerCase().includes("role"))throw zt;await a.sleep(1000)}if(Ze)throw Ze}await a.lambda.waitForFunctionActive(e.functionName);let ee=D||await a.lambda.createFunctionUrl({FunctionName:e.functionName,AuthType:"AWS_IAM",InvokeMode:"BUFFERED"});if(!ee.FunctionUrl)throw Error("Lambda did not return a function URL");let De=new URL(ee.FunctionUrl).hostname,Ge=await a.cloudfront.findOrCreateOriginAccessControl(M,"lambda"),pt=m.ARN||`arn:aws:cloudfront::${u.Account}:distribution/${e.distributionId}`,Ft=[{FunctionName:e.functionName,StatementId:"AllowCloudFrontFunctionUrl",Action:"lambda:InvokeFunctionUrl",Principal:"cloudfront.amazonaws.com",SourceArn:pt,FunctionUrlAuthType:"AWS_IAM"},{FunctionName:e.functionName,StatementId:"AllowCloudFrontInvoke",Action:"lambda:InvokeFunction",Principal:"cloudfront.amazonaws.com",SourceArn:pt,InvokedViaFunctionUrl:!0}];for(let Ze of Ft)try{await a.lambda.addPermission(Ze)}catch(wt){if(!Iv(wt))throw wt}return await a.cloudfront.upsertExistingDistributionOrigin(e.distributionId,{id:r.originId,domainName:De,pathPattern:r.pathPattern,originAccessControlId:Ge.Id}),{...ye,function:{...ye.function,url:ee.FunctionUrl},applied:!0}}async function OS(e){let t=`https://${e.alias}/`,r=`https://${e.alias}/api/health`,a=await fetch(t,{redirect:"follow",headers:{"cache-control":"no-cache"}}),u=new Uint8Array(await a.arrayBuffer()),m=IA("sha256").update(u).digest("hex"),f=Date.now(),b=await fetch(r,{redirect:"follow",headers:{"cache-control":"no-cache"}}),w=Date.now()-f,y=await b.text(),I=y;try{I=JSON.parse(y)}catch{}let A;if(e.logs&&e.functionName){let D=await e.logs.filterLogEvents({logGroupName:`/aws/lambda/${e.functionName}`,startTime:f-60000,filterPattern:'"Init Duration"',limit:25});for(let O of D.events||[]){let M=O.message?.match(/Init Duration:\s*([0-9.]+)\s*ms/i);if(M)A=Number(M[1])}}return{frontend:{url:t,status:a.status,sha256:m,unchanged:e.expectedFrontendSha256?m===e.expectedFrontendSha256:void 0,bytes:u.byteLength},api:{url:r,status:b.status,latencyMs:w,healthy:b.ok&&!!I?.ok,body:I},coldStart:{observed:A!==void 0,initDurationMs:A},verifiedAt:(e.now?.()||new Date).toISOString()}}function _S(e){let t=(e.memoryMb||256)/1024,r=Math.max(0,e.requests-(e.includeFreeTier===!1?0:1e6)),a=Math.max(0,e.requests*(e.averageDurationMs/1000)*t-(e.includeFreeTier===!1?0:400000)),u=r/1e6*0.2+a*0.0000166667,m=9.010025,f=16.425;return{lambdaUsd:Number(u.toFixed(2)),alwaysOnFargateAndAlbUsd:Number(25.435025000000003 .toFixed(2)),assumptions:["us-east-1 public list rates snapshot, July 2026","Lambda x86 request and duration pricing with optional monthly free tier","Fargate comparison uses one always-on 0.25 vCPU/0.5 GB task plus one ALB before LCU charges","excludes CloudFront, data transfer, logs, taxes, and application data services"]}}import{createHash as CA}from"node:crypto";function PA(e){let t=e;return String(t?.code||t?.name||t?.statusCode||"")}function _A(e){return PA(e)==="ValidationError"&&String(e.message).includes("does not exist")}function TA(e){return Object.fromEntries((e||[]).map((t)=>[t.OutputKey,t.OutputValue]))}function xA(e){let t=e?.Aliases?.Items??e?.Aliases,r=t?.CNAME??t;if(Array.isArray(r))return r.map(String);if(typeof r==="string")return[r];return[]}function Av(e){if(!/^[a-z][a-z0-9-]{1,62}$/.test(e.slug))throw Error("Slug must be a lowercase DNS-safe identifier");if(!/^[A-Z0-9]{8,32}$/.test(e.distributionId))throw Error("CloudFront distribution ID is invalid");if(!/^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9-]{2,63}$/.test(e.expectedAlias))throw Error("Expected distribution alias is invalid");let t=e.imageUri.match(/@((?:sha256:)[a-f0-9]{64})$/i)?.[1];if(!t)throw Error("Container image must use an immutable ECR digest URI ending in @sha256:<64 hex>");let r=e.stackName||`${e.slug}-backend`;if(!/^[A-Za-z][A-Za-z0-9-]{0,127}$/.test(r))throw Error("CloudFormation stack name is invalid");let a=e.pathPattern||"/api/*";if(!/^\/[A-Za-z0-9_.*?~!$&'()+,;=:@%/-]+\*$/.test(a)||a==="/*")throw Error("Backend path must be a non-default wildcard pattern");let u=e.originId||`${e.slug}-backend`;if(!/^[A-Za-z0-9_.-]{1,128}$/.test(u))throw Error("CloudFront origin ID is invalid");if(e.originVerifySecret&&e.originVerifySecret.length<24)throw Error("Origin verification secret must contain at least 24 characters");if(!!e.originDomain!==!!e.certificateArn)throw Error("A custom origin domain and matching ACM certificate ARN must be provided together");return{stackName:r,region:e.region||"us-east-1",pathPattern:a,originId:u,digest:t}}function nh(e){let t=e.region||"us-east-1";return{cloudformation:new h(t,e.profile),cloudfront:new S(e.profile),sts:new Te(t,e.profile),fetch,sleep:(r)=>new Promise((a)=>setTimeout(a,r))}}function ih(e){let t=Av(e),r=sl({name:e.name,slug:e.slug,domain:e.originDomain||e.expectedAlias,imageUri:e.imageUri,certificateArn:e.certificateArn,originVerifySecret:e.originVerifySecret,desiredCount:e.desiredCount,database:e.database,cache:e.cache,queue:e.queue}),a=il(r);return a.Description=`Managed backend for existing static frontend ${e.expectedAlias}`,a.Metadata={ManagedBy:"ts-cloud",ExistingDistributionId:e.distributionId,ExistingDistributionAlias:e.expectedAlias,BackendPathPattern:t.pathPattern,ContainerDigest:t.digest},a}async function DA(e,t,r){let a;for(let u=0;u<30;u++){let m=Date.now();try{let f=await e.fetch(t,{redirect:"manual",headers:r?{"x-origin-verify":r}:void 0}),b=Date.now()-m,w=await f.text(),y=w;try{y=JSON.parse(w)}catch{}if(f.ok)return{url:t,status:f.status,latencyMs:b,body:y};a=Error(`origin returned ${f.status}`)}catch(f){a=f}if(u<29)await e.sleep(1e4)}throw Error(`Backend origin did not become healthy: ${a instanceof Error?a.message:String(a)}`)}async function LS(e,t){let r=Av(e),a=t||nh({region:r.region,profile:e.profile}),[u,m]=await Promise.all([a.sts.getCallerIdentity(),a.cloudfront.getDistribution(e.distributionId)]);if(!u.Account)throw Error("AWS identity did not return an account ID");if(!m.Enabled)throw Error(`CloudFront distribution ${e.distributionId} is disabled`);if(!xA(m).includes(e.expectedAlias))throw Error(`Distribution ${e.distributionId} does not contain expected alias ${e.expectedAlias}`);let f;try{f=(await a.cloudformation.describeStacks({stackName:r.stackName})).Stacks[0]}catch(te){if(!_A(te))throw te}let b=ih(e),w=JSON.stringify(b);if(Buffer.byteLength(w)>51200)throw Error("Generated template exceeds the direct CloudFormation template body limit");let y=Object.values(b.Resources||{}).reduce((te,he)=>(te[he.Type]=(te[he.Type]||0)+1,te),{}),I=[`cloud cdn:origin:remove ${e.distributionId} ${e.originDomain||"ALB_HOST"} --id ${r.originId} --path '${r.pathPattern}' --profile ${e.profile||"default"} --apply --confirm 'remove:${e.distributionId}:${r.pathPattern}'`,`After CloudFront is deployed, restore external DNS if changed and delete stack ${r.stackName} only with an approved data-retention decision.`],A={mode:e.apply?"apply":"plan",accountId:u.Account,stack:{name:r.stackName,existed:!!f,status:f?.StackStatus,templateSha256:CA("sha256").update(w).digest("hex"),resourceCount:Object.keys(b.Resources||{}).length,resourceTypes:y},distribution:{id:m.Id,alias:e.expectedAlias,domainName:m.DomainName,status:m.Status,pathPattern:r.pathPattern,originId:r.originId},artifact:{imageUri:e.imageUri,digest:r.digest},services:{database:e.database!==!1,cache:e.cache!==!1,queue:e.queue!==!1,mail:"ses",desiredCount:e.desiredCount||1},cloudFrontApplied:!1,dnsApplied:!1,applied:!1,rollback:I};if(!e.apply)return A;let D=`${e.distributionId}:${r.pathPattern}:${r.stackName}`;if(e.confirm!==D)throw Error(`Pass exact confirmation token ${D} to provision the backend and change live routing`);if(f)try{await a.cloudformation.updateStack({stackName:r.stackName,templateBody:w,capabilities:["CAPABILITY_NAMED_IAM"],tags:[{Key:"ManagedBy",Value:"ts-cloud"},{Key:"Application",Value:e.slug}]}),await a.cloudformation.waitForStack(r.stackName,"stack-update-complete")}catch(te){if(!String(te.message).includes("No updates are to be performed"))throw te}else await a.cloudformation.createStack({stackName:r.stackName,templateBody:w,capabilities:["CAPABILITY_NAMED_IAM"],onFailure:"ROLLBACK",tags:[{Key:"ManagedBy",Value:"ts-cloud"},{Key:"Application",Value:e.slug}]}),await a.cloudformation.waitForStack(r.stackName,"stack-create-complete");let O=(await a.cloudformation.describeStacks({stackName:r.stackName})).Stacks[0],M=TA(O?.Outputs),z=M.AppLoadBalancerDnsName;if(!z)throw Error("Backend stack did not return AppLoadBalancerDnsName");let J=!1;if(e.originDomain&&e.originDomain!==z){if(!a.dns)throw Error(`External DNS provider is required to map ${e.originDomain} to ${z}`);let te=await a.dns.upsertRecord(e.originDomain,{name:e.originDomain,type:"CNAME",content:z,ttl:300});if(!te.success)throw Error(te.message||"External DNS update failed");J=!0}let Z=e.originDomain||z,oe=e.certificateArn?"https-only":"http-only",G=e.skipHealthCheck?void 0:await DA(a,`${oe==="https-only"?"https":"http"}://${Z}/api/health`,e.originVerifySecret);return await a.cloudfront.upsertExistingDistributionOrigin(e.distributionId,{id:r.originId,domainName:Z,pathPattern:r.pathPattern,protocolPolicy:oe,customHeaders:e.originVerifySecret?{"X-Origin-Verify":e.originVerifySecret}:void 0}),{...A,outputs:M,health:G,cloudFrontApplied:!0,dnsApplied:J,applied:!0}}function $S(e={}){let r={fargate:730*(e.desiredCount||1)*0.012342500000000001,applicationLoadBalancer:16.425,natGateway:32.85,postgres:730*(e.multiAzDatabase?0.032:0.016),redis:23.36};return{monthlyUsd:Number(Object.values(r).reduce((a,u)=>a+u,0).toFixed(2)),components:Object.fromEntries(Object.entries(r).map(([a,u])=>[a,Number(u.toFixed(2))])),assumptions:["us-east-1 public on-demand rate snapshot, July 2026","one 0.25 vCPU/0.5 GB Linux Fargate task unless desiredCount is changed","one ALB before LCU charges and one NAT gateway before data processing","single-AZ db.t4g.micro PostgreSQL by default and two cache.t4g.micro Redis nodes","excludes storage, backups, CloudFront, data transfer, public IPv4, logs, email, queue requests, taxes, and free-tier credits"]}}import{execFileSync as OA}from"node:child_process";import{createHash as $A}from"node:crypto";import{existsSync as Cv,mkdirSync as NA,mkdtempSync as jA,readdirSync as BA,readFileSync as MA,rmSync as LA,statSync as Pv,writeFileSync as FA}from"node:fs";import{tmpdir as zA}from"node:os";import{basename as UA,join as xs,relative as qA,resolve as _g}from"node:path";var VA=new Set([".git","node_modules","dist","coverage"]);function _v(e,t=e){let r=[];for(let a of BA(e).sort()){if(VA.has(a))continue;let u=xs(e,a);if(Kd(u,t))continue;let m=Pv(u);if(m.isDirectory())r.push(..._v(u,t));else if(m.isFile())r.push(qA(t,u))}return r}function sh(e){let t=_g(e);if(!Cv(t)||!Pv(t).isDirectory())throw Error(`Container context does not exist: ${t}`);let r=$A("sha256");for(let a of _v(t))r.update(a),r.update("\x00"),r.update(MA(xs(t,a))),r.update("\x00");return r.digest("hex")}function oh(e){return{ecr:new He(e.region||"us-east-1",e.profile),run:(t,r,a)=>{OA(t,r,{cwd:a?.cwd,env:a?.env,stdio:a?.stdio||"inherit"})}}}async function MS(e,t){let r=_g(e.context),a=_g(e.dockerfile||xs(r,"Dockerfile"));if(!Cv(a))throw Error(`Dockerfile does not exist: ${a}`);if(!e.repository.split("/").every((M)=>/^[a-z0-9][a-z0-9._-]*$/.test(M)&&!/[._-]$/.test(M)&&!/[._-]{2}/.test(M)))throw Error("ECR repository name is invalid");let f=t||oh(e),b=sh(r),w=`sha-${b.slice(0,20)}`,y="";try{y=(await f.ecr.describeRepositories({repositoryNames:[e.repository]})).repositories?.[0]?.repositoryUri||""}catch{}if(!y)y=(await f.ecr.createRepository({repositoryName:e.repository,imageTagMutability:"IMMUTABLE",imageScanningConfiguration:{scanOnPush:!0},tags:[{Key:"ManagedBy",Value:"ts-cloud"}]})).repository?.repositoryUri||"";if(!y)throw Error(`Could not resolve ECR repository URI for ${e.repository}`);await f.ecr.putLifecyclePolicy({repositoryName:e.repository,lifecyclePolicyText:JSON.stringify({rules:[{rulePriority:1,description:"Retain the newest 25 release images",selection:{tagStatus:"any",countType:"imageCountMoreThan",countNumber:25},action:{type:"expire"}}]})});let I=`${y}:${w}`,A=jA(xs(zA(),"ts-cloud-container-"));try{f.run("docker",["version"],{stdio:"ignore"}),f.run("docker",["build","--platform",e.platform||"linux/amd64","--provenance=false","--sbom=false","--file",a,"--tag",I,r],{cwd:r});let M=(await f.ecr.getAuthorizationToken()).authorizationData?.[0];if(!M?.authorizationToken||!M.proxyEndpoint)throw Error("ECR did not return Docker authorization data");let z=M.proxyEndpoint.replace(/^https?:\/\//,""),J=xs(A,"docker");NA(J,{recursive:!0}),FA(xs(J,"config.json"),JSON.stringify({auths:{[z]:{auth:M.authorizationToken}}}),{mode:384}),f.run("docker",["push",I],{env:{...process.env,DOCKER_CONFIG:J}})}finally{LA(A,{recursive:!0,force:!0})}let O=(await f.ecr.describeImages({repositoryName:e.repository,imageIds:[{imageTag:w}]})).imageDetails?.[0]?.imageDigest;if(!O||!/^sha256:[a-f0-9]{64}$/i.test(O))throw Error(`ECR did not return an immutable digest for ${UA(I)}`);return{repository:e.repository,tag:w,imageUri:I,digest:O,digestUri:`${y}@${O}`,contextSha256:b}}import{existsSync as WA,readdirSync as HA,readFileSync as KA,statSync as JA}from"node:fs";import{join as Tv,relative as GA}from"node:path";function Io(e,t){let r=e.environments?.[t]?.app;if(!r)throw Error(`No serverless app configured for environment '${t}'. Add environments.${t}.app to your config.`);let a=e.project.slug,u=e.environments?.[t]?.region||e.project.region||"us-east-1";return{app:r,slug:a,region:u,stackName:sr(e,t),artifactBucket:Xd(a,t),assetsBucket:Gi(a,t)}}async function wo(e,t=8){let r;for(let a=0;a<t;a++)try{return await e()}catch(u){let m=u?.code||u?.name||"",f=String(u?.message||"");if(m==="ResourceConflictException"||/update is in progress|currently in the following state/i.test(f)){r=u,await new Promise((b)=>setTimeout(b,3000));continue}throw u}throw r}var xv=(e,t)=>`releases/${e}/${t}/current.json`;async function Ud(e,t,r,a){try{return await e.getObjectJson(t,xv(r,a))}catch{return null}}async function Dv(e,t,r,a,u){await e.putObjectJson(t,xv(r,a),u)}async function QA(e,t){if(!e.secrets)return{};let r=new re(t),a={},u=Array.isArray(e.secrets)?e.secrets.map((m)=>({envName:m.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:m})):Object.entries(e.secrets).map(([m,f])=>({envName:m,secretId:f}));if(Array.isArray(e.secrets)){let m=new Map;for(let{envName:b,secretId:w}of u)m.set(b,[...m.get(b)??[],w]);let f=[...m.entries()].filter(([,b])=>b.length>1);if(f.length){let b=f.map(([w,y])=>`${w} ← ${y.join(", ")}`).join("; ");throw Error(`serverless secrets: multiple secrets map to the same env var (${b}). Use the map form { ENV_NAME: 'secret/id' } to disambiguate.`)}}for(let{envName:m,secretId:f}of u){let w=(await r.getSecretValue({SecretId:f})).SecretString??"";try{let y=JSON.parse(w);if(y&&typeof y==="object"&&!Array.isArray(y)){for(let[I,A]of Object.entries(y))a[I]=String(A);continue}}catch{}a[m]=w}return a}function fs(e,t){let r={},a=t.DbProxyEndpoint||t.DbEndpoint;if(a)r.DB_CONNECTION="mysql",r.DB_HOST=a,r.DB_PORT="3306",r.DB_DATABASE=r.DB_DATABASE||"app";if(t.CacheEndpoint){if(r.REDIS_HOST=t.CacheEndpoint,r.REDIS_PORT="6379",e.cache?.driver==="elasticache")r.CACHE_STORE="redis",r.CACHE_DRIVER="redis",r.SESSION_DRIVER="redis"}return r}function Ar(e,t,r,a,u,m,f,b={}){let w=e.kind==="php"?Ol({cacheDriver:e.cache?.driver==="elasticache"?"redis":"dynamodb"}):{};return{TSCLOUD_LAMBDA_MODE:a,TSCLOUD_ENV:r,MAINTENANCE_MODE:"0",...e.octane?{TSCLOUD_OCTANE:"1"}:{},...e.serveAssets?{TSCLOUD_SERVE_ASSETS:"1"}:{},...e.redirectRobotsTxt===!1?{TSCLOUD_REDIRECT_ROBOTS_TXT:"0"}:{},...w,...b,...t.app.cache?.driver!=="elasticache"?{TSCLOUD_CACHE_TABLE:`${t.slug}-${r}-cache`}:{},...f?{TSCLOUD_QUEUE:f,SQS_QUEUE:f}:{},...m?{ASSET_URL:m}:{},...e.env??{},...u}}function YA(e){let t=e.slice(e.lastIndexOf(".")).toLowerCase();return{".html":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".json":"application/json",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".txt":"text/plain",".map":"application/json"}[t]??"application/octet-stream"}function*Ov(e){for(let t of HA(e)){let r=Tv(e,t);if(JA(r).isDirectory())yield*Ov(r);else yield r}}async function ZA(e,t,r,a,u=!1){let m=0;for(let f of Ov(r)){let b=GA(r,f).replace(/\\/g,"/");if(!u&&b.split("/").some((w)=>w.startsWith(".")))continue;await e.putObject({bucket:t,key:`${a}/${b}`,body:KA(f),contentType:YA(f),cacheControl:"public, max-age=31536000, immutable"}),m++}return m}function XA(e,t){let r=Object.entries(t).reduce((a,[u,m])=>a+Buffer.byteLength(`${u}=${m}`,"utf8"),0);if(r>4096){let a=Object.entries(t).map(([u,m])=>[u,Buffer.byteLength(`${u}=${m}`,"utf8")]).sort((u,m)=>m[1]-u[1]).slice(0,5).map(([u,m])=>`${u} (${m}B)`).join(", ");throw Error(`${e}: environment variables total ${r}B, over AWS's 4096B limit (${r-4096}B too large). Largest: ${a}. Move large/secret values out of env — store them in Secrets Manager and fetch at cold start.`)}}async function uc(e,t,r,a){XA(t,r),await wo(()=>e.updateFunctionConfiguration({FunctionName:t,Environment:{Variables:r}})),await e.waitForFunctionActive(t,120);let u=a.kind==="image"?{FunctionName:t,ImageUri:a.imageUri}:{FunctionName:t,S3Bucket:a.bucket,S3Key:a.key};await wo(()=>e.updateFunctionCode(u)),await e.waitForFunctionActive(t,120)}async function zd(e,t){let a=(await wo(()=>e.publishVersion({FunctionName:t}))).Version;if(!a)throw Error(`publishVersion returned no version for ${t}`);return await wo(()=>e.updateAlias({FunctionName:t,Name:"live",FunctionVersion:a})),a}async function Ha(e,t,r={}){let a=Io(e,t),{app:u,slug:m,region:f,stackName:b,artifactBucket:w}=a,y=r.projectRoot??process.cwd();Ts(`Deploying serverless app: ${m} (${t})`),L(`Stack: ${b}`),L(`Region: ${f}`);let I=new o(f),A=new h(f),D=new v(f),O=u.kind==="php",M=u.packaging==="image",z=Wi(u),J,Z,oe,G,te=[];if(M&&z.usesLayer&&z.layerKind!=="php")throw Error(`packaging: 'image' currently supports PHP and managed Node runtimes. ${z.kind}${z.kind==="node"?` ${z.version}`:""} uses a custom runtime — `+"use the default zip packaging (the runtime layer is built + attached automatically).");if(M){P("Building + pushing container image");let{buildAndPushServerlessImage:le}=await import("./chunk-r4kedmas.js"),Ce=await le({app:u,projectRoot:y,region:f,repository:`${m}-${t}`,skipBuild:r.skipBuild,onStep:(gt)=>L(` ${gt}`)});J=Ce.handlers,Z={kind:"image",imageUri:Ce.imageUri},oe=Ce.tag,te.push({ParameterKey:"ImageUri",ParameterValue:Ce.imageUri})}else{P("Packaging application");let le=O?_l({projectRoot:y,app:u,skipBuild:r.skipBuild,onStep:(It)=>L(` ${It}`)}):await ln({projectRoot:y,app:u,skipBuild:r.skipBuild,onStep:(It)=>L(` ${It}`)}),Ce=wl(m,t,le.sha256);if(L(`Artifact: ${le.sha256.slice(0,12)} (${(le.zip.length/1024).toFixed(0)} KB)`),J=le.handlers,oe=le.sha256,z.usesLayer){let It=z.layerEnvVar?process.env[z.layerEnvVar]:void 0;if(G=u.layers??(It?[It]:void 0),!G?.length){let _e=z.layerKind==="php"?"serverless:build-php-layer":z.layerKind==="bun"?"serverless:build-bun-layer":"serverless:build-node-layer";throw Error(`${z.kind} apps on provided.al2023 need a runtime layer. Set environments.<env>.app.layers or the ${z.layerEnvVar} env var (build one with \`cloud ${_e}\`)${z.kind==="node"?", or use a managed Node version (18/20/22)":""}.`)}}if(!await I.bucketExists(w))P(`Creating artifact bucket ${w}`),await I.createBucket(w);if(await I.headObject(w,Ce).then((It)=>It!==null).catch(()=>!1))L("Artifact already uploaded — reusing");else P("Uploading artifact"),await I.putObject({bucket:w,key:Ce,body:le.zip,contentType:"application/zip"});Z={kind:"zip",bucket:w,key:Ce},te.push({ParameterKey:"ArtifactBucket",ParameterValue:w},{ParameterKey:"ArtifactKey",ParameterValue:Ce})}let he=Dl({config:e,environment:t,app:u,handlers:J,runtimeLayers:G}),ye=JSON.stringify(he.template),ie=["CAPABILITY_NAMED_IAM"],xe=await A.describeStacks({stackName:b}).then((le)=>le.Stacks[0]?.StackStatus).catch(()=>{return}),ee=xe!==void 0;if(xe&&/DELETE_IN_PROGRESS/.test(xe))P("Waiting for an in-progress stack delete to finish"),await A.waitForStack(b,"stack-delete-complete").catch(()=>{}),ee=!1;else if(xe&&/(?:ROLLBACK_COMPLETE|REVIEW_IN_PROGRESS|CREATE_FAILED)/.test(xe))P(`Deleting unusable stack (status ${xe}) before recreate`),await A.deleteStack(b),await A.waitForStack(b,"stack-delete-complete").catch(()=>{}),ee=!1;P(ee?"Updating infrastructure stack":"Creating infrastructure stack");try{if(ee)await A.updateStack({stackName:b,templateBody:ye,parameters:te,capabilities:ie}),await A.waitForStack(b,"stack-update-complete");else await A.createStack({stackName:b,templateBody:ye,parameters:te,capabilities:ie,onFailure:"DELETE"}),await A.waitForStack(b,"stack-create-complete")}catch(le){if(/No updates are to be performed/i.test(String(le?.message)))L("No infrastructure changes");else throw le}let De=await A.getStackOutputs(b).catch(()=>({})),Ge;if(u.assets){let le=Tv(y,u.assets);if(WA(le)){let Ce=u.assetDomain||De.AssetsCdnDomain;Ge=Ce?`https://${Ce}/${oe}`:void 0,P(`Syncing assets from ${u.assets}`);let gt=await ZA(I,a.assetsBucket,le,oe,u.dotFilesAsAssets);L(`Uploaded ${gt} asset(s)${Ge?` → ${Ge}`:""}`)}else vs(`Assets directory not found: ${le}`)}P("Resolving secrets");let pt=await QA(u,f);if(u.database?.connection==="aurora-serverless")try{let Ce=await new re(f).getSecretValue({SecretId:`${m}/${t}/db`}),gt=JSON.parse(Ce.SecretString??"{}");if(gt.username)pt.DB_USERNAME=gt.username;if(gt.password)pt.DB_PASSWORD=gt.password}catch(le){vs(`Could not resolve Aurora DB credentials: ${le.message}`)}if(!await I.bucketExists(w))await I.createBucket(w);let Ft=await Ud(I,w,m,t),Ze={},wt=he.queueNames[0],zt=fs(u,De);if(P("Activating functions"),Ze.http=Ar(u,a,t,"http",pt,Ge,wt,zt),await uc(D,he.functionNames.http,Ze.http,Z),Ze.cli=Ar(u,a,t,"cli",pt,Ge,wt,zt),await uc(D,he.functionNames.cli,Ze.cli,Z),he.queueNames.length)Ze.queue=Ar(u,a,t,"queue",pt,Ge,wt,zt),await uc(D,he.functionNames.queue,Ze.queue,Z);let rt=(u.provisionedConcurrency??0)>0,W={};if(rt){if(P("Publishing versions + flipping live alias"),W.http=await zd(D,he.functionNames.http),W.cli=await zd(D,he.functionNames.cli),he.queueNames.length)W.queue=await zd(D,he.functionNames.queue)}if(await Dv(I,w,m,t,{sha:oe,code:Z,previousSha:Ft?.sha,previousCode:Ft?.code,previousFunctionEnv:Ft?.functionEnv,...rt?{functionVersions:W,previousFunctionVersions:Ft?.functionVersions}:{},functionEnv:Ze,functionNames:{http:he.functionNames.http,cli:he.functionNames.cli,...he.queueNames.length?{queue:he.functionNames.queue}:{}},assetUrl:Ge,timestamp:new Date().toISOString()}),!r.skipDeployHooks&&u.deploy?.length){P("Running deploy hooks");for(let le of u.deploy){L(` deploy: ${le}`);let Ce=await D.invoke({FunctionName:he.functionNames.cli,InvocationType:"RequestResponse",Payload:{command:le},LogType:"Tail"});if(Ce.FunctionError)throw dg("Deploy hook failed — the new build is ALREADY LIVE."),L(` Roll back with: cloud serverless:rollback --env ${t}`),Error(`Deploy hook failed (${le}): ${Ce.Payload}`)}}let se=De.HttpApiEndpoint;if(!r.skipHealthCheck&&se){P("Health check");try{let le=await fetch(se,{method:"GET"});L(`GET ${se} → ${le.status}`)}catch(le){vs(`Health check could not reach ${se}: ${le.message}`)}}lg(["Serverless deploy complete","",se?`URL: ${se}`:"",`Stack: ${b}`,`Build: ${oe.slice(0,12)}`].filter(Boolean).join(`
179
+ `;function Rv(e){let t=e;return String(t?.code||t?.name||t?.statusCode||"")}function RA(e){return["NoSuchEntity","ResourceNotFoundException","404"].includes(Rv(e))}function Iv(e){return["EntityAlreadyExists","ResourceAlreadyExistsException","ResourceConflictException","409"].includes(Rv(e))}function Ev(e,t){let r=e?.Items;if(!r)return[];if(Array.isArray(r))return r;let a=r[t];if(a===void 0)return[];return Array.isArray(a)?a:[a]}function Pg(e){let t=e?.Aliases?.Items,r=t?.CNAME??t;if(Array.isArray(r))return r.map(String);if(typeof r==="string")return[r];return[]}function AA(e){if(!/^[A-Z0-9]{8,32}$/.test(e.distributionId))throw Error("CloudFront distribution ID is invalid");if(!/^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9-]{2,63}$/.test(e.expectedAlias))throw Error("Expected CloudFront alias is invalid");if(!/^[A-Za-z0-9-_]{1,64}$/.test(e.functionName))throw Error("Lambda function name is invalid");let t=e.pathPattern?.startsWith("/")?e.pathPattern:`/${e.pathPattern||"api/*"}`;if(t==="/"||t==="/*"||!t.endsWith("*"))throw Error("API path must be a non-default wildcard pattern such as /api/*");let r=e.originId||`${e.functionName}-url`,a=e.roleName||`${e.functionName}-execution`;if(!/^[A-Za-z0-9_.-]{1,64}$/.test(a))throw Error("IAM role name is invalid");let u=e.memorySize??256,m=e.timeout??10,f=e.logRetentionDays??14;if(u<128||u>10240)throw Error("Lambda memory must be between 128 and 10240 MB");if(m<1||m>900)throw Error("Lambda timeout must be between 1 and 900 seconds");return{region:e.region||"us-east-1",pathPattern:t,originId:r,roleName:a,memorySize:u,timeout:m,logRetentionDays:f}}function rh(e){let t=e.region||"us-east-1";return{cloudfront:new S(e.profile),iam:new Re(t,e.profile),lambda:new v(t,e.profile),logs:new we(t,e.profile),sts:new Te(t,e.profile),sleep:(r)=>new Promise((a)=>setTimeout(a,r))}}async function xS(e,t){let r=AA(e),a=t||rh({profile:e.profile,region:r.region}),[u,m,f]=await Promise.all([a.sts.getCallerIdentity(),a.cloudfront.getDistribution(e.distributionId),a.cloudfront.getDistributionConfig(e.distributionId)]);if(!u.Account)throw Error("AWS identity did not return an account ID");if(!m.Enabled)throw Error(`CloudFront distribution ${e.distributionId} is disabled`);if(!(Pg(m).length?Pg(m):Pg(f.DistributionConfig)).includes(e.expectedAlias))throw Error(`Distribution ${e.distributionId} does not contain expected alias ${e.expectedAlias}`);let w,y=!0;try{w=await a.iam.getRole({RoleName:r.roleName})}catch(Ze){if(!RA(Ze))throw Ze;y=!1}let I=w?.Arn||`arn:aws:iam::${u.Account}:role/${r.roleName}`,A=await a.lambda.functionExists(e.functionName),D=A?await a.lambda.getFunctionUrl(e.functionName):null,O=await a.cloudfront.listOriginAccessControls(),M=`${e.functionName}-lambda-url`,z=O.some((Ze)=>Ze.Name===M&&Ze.OriginAccessControlOriginType==="lambda"),J=Ev(f.DistributionConfig.Origins,"Origin"),Z=Ev(f.DistributionConfig.CacheBehaviors,"CacheBehavior"),oe=J.some((Ze)=>String(Ze.Id)===r.originId),G=Z.some((Ze)=>String(Ze.PathPattern)===r.pathPattern),te=[...!y?[`create IAM execution role ${r.roleName}`]:[`reconcile IAM execution policy ${r.roleName}`],...A?[`update Lambda ${e.functionName} code and configuration`]:[`create Lambda ${e.functionName}`],...!D?["create private AWS_IAM function URL"]:[],...!z?[`create Lambda origin access control ${M}`]:[],"grant CloudFront function-URL and invocation permissions",`${G?"reconcile":"add"} ${r.pathPattern} behavior without changing the default behavior`],he={command:`cloud cdn:origin:remove ${e.distributionId} FUNCTION_URL_HOST --id ${r.originId} --path '${r.pathPattern}' --apply --confirm 'remove:${e.distributionId}:${r.pathPattern}'`,removeFunction:!A,removeRole:!y},ye={mode:e.apply?"apply":"plan",accountId:u.Account,identityArn:u.Arn,distribution:{id:m.Id,arn:m.ARN,alias:e.expectedAlias,domainName:m.DomainName,status:m.Status},function:{name:e.functionName,existed:A,runtime:"nodejs22.x",urlExisted:!!D,url:D?.FunctionUrl},role:{name:r.roleName,existed:y,arn:I},origin:{id:r.originId,pathPattern:r.pathPattern,existed:oe,behaviorExisted:G,accessControlExisted:z},changes:te,rollback:he,applied:!1};if(!e.apply)return ye;let ie=`${e.distributionId}:${r.pathPattern}`;if(e.confirm!==ie)throw Error(`Pass exact confirmation token ${ie} to mutate the live distribution`);if(!w)w=await a.iam.createRole({RoleName:r.roleName,Description:`Execution role for ${e.functionName}`,AssumeRolePolicyDocument:JSON.stringify({Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]}),Tags:[{Key:"ManagedBy",Value:"ts-cloud"}]});await a.iam.putRolePolicy({RoleName:r.roleName,PolicyName:"lambda-logs",PolicyDocument:JSON.stringify({Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogStream","logs:PutLogEvents"],Resource:`arn:aws:logs:${r.region}:${u.Account}:log-group:/aws/lambda/${e.functionName}:*`}]})});try{await a.logs.createLogGroup(`/aws/lambda/${e.functionName}`,{ManagedBy:"ts-cloud"})}catch(Ze){if(!Iv(Ze))throw Ze}await a.logs.putRetentionPolicy(`/aws/lambda/${e.functionName}`,r.logRetentionDays);let xe=e.code||EA;if(A)await a.lambda.updateFunctionCodeInline(e.functionName,xe,"index.mjs"),await a.lambda.waitForFunctionActive(e.functionName),await a.lambda.updateFunctionConfiguration({FunctionName:e.functionName,Runtime:"nodejs22.x",Role:w.Arn,Handler:"index.handler",Description:`Private API origin for ${e.expectedAlias}`,Timeout:r.timeout,MemorySize:r.memorySize});else{let Ze;for(let wt=0;wt<8;wt++)try{await a.lambda.createFunctionWithCode({FunctionName:e.functionName,Runtime:"nodejs22.x",Role:w.Arn,Handler:"index.handler",Code:xe,Filename:"index.mjs",Description:`Private API origin for ${e.expectedAlias}`,Timeout:r.timeout,MemorySize:r.memorySize}),Ze=void 0;break}catch(zt){if(Ze=zt,!String(zt.message).toLowerCase().includes("role"))throw zt;await a.sleep(1000)}if(Ze)throw Ze}await a.lambda.waitForFunctionActive(e.functionName);let ee=D||await a.lambda.createFunctionUrl({FunctionName:e.functionName,AuthType:"AWS_IAM",InvokeMode:"BUFFERED"});if(!ee.FunctionUrl)throw Error("Lambda did not return a function URL");let De=new URL(ee.FunctionUrl).hostname,Ge=await a.cloudfront.findOrCreateOriginAccessControl(M,"lambda"),pt=m.ARN||`arn:aws:cloudfront::${u.Account}:distribution/${e.distributionId}`,Ft=[{FunctionName:e.functionName,StatementId:"AllowCloudFrontFunctionUrl",Action:"lambda:InvokeFunctionUrl",Principal:"cloudfront.amazonaws.com",SourceArn:pt,FunctionUrlAuthType:"AWS_IAM"},{FunctionName:e.functionName,StatementId:"AllowCloudFrontInvoke",Action:"lambda:InvokeFunction",Principal:"cloudfront.amazonaws.com",SourceArn:pt,InvokedViaFunctionUrl:!0}];for(let Ze of Ft)try{await a.lambda.addPermission(Ze)}catch(wt){if(!Iv(wt))throw wt}return await a.cloudfront.upsertExistingDistributionOrigin(e.distributionId,{id:r.originId,domainName:De,pathPattern:r.pathPattern,originAccessControlId:Ge.Id}),{...ye,function:{...ye.function,url:ee.FunctionUrl},applied:!0}}async function OS(e){let t=`https://${e.alias}/`,r=`https://${e.alias}/api/health`,a=await fetch(t,{redirect:"follow",headers:{"cache-control":"no-cache"}}),u=new Uint8Array(await a.arrayBuffer()),m=IA("sha256").update(u).digest("hex"),f=Date.now(),b=await fetch(r,{redirect:"follow",headers:{"cache-control":"no-cache"}}),w=Date.now()-f,y=await b.text(),I=y;try{I=JSON.parse(y)}catch{}let A;if(e.logs&&e.functionName){let D=await e.logs.filterLogEvents({logGroupName:`/aws/lambda/${e.functionName}`,startTime:f-60000,filterPattern:'"Init Duration"',limit:25});for(let O of D.events||[]){let M=O.message?.match(/Init Duration:\s*([0-9.]+)\s*ms/i);if(M)A=Number(M[1])}}return{frontend:{url:t,status:a.status,sha256:m,unchanged:e.expectedFrontendSha256?m===e.expectedFrontendSha256:void 0,bytes:u.byteLength},api:{url:r,status:b.status,latencyMs:w,healthy:b.ok&&!!I?.ok,body:I},coldStart:{observed:A!==void 0,initDurationMs:A},verifiedAt:(e.now?.()||new Date).toISOString()}}function _S(e){let t=(e.memoryMb||256)/1024,r=Math.max(0,e.requests-(e.includeFreeTier===!1?0:1e6)),a=Math.max(0,e.requests*(e.averageDurationMs/1000)*t-(e.includeFreeTier===!1?0:400000)),u=r/1e6*0.2+a*0.0000166667,m=9.010025,f=16.425;return{lambdaUsd:Number(u.toFixed(2)),alwaysOnFargateAndAlbUsd:Number(25.435025000000003 .toFixed(2)),assumptions:["us-east-1 public list rates snapshot, July 2026","Lambda x86 request and duration pricing with optional monthly free tier","Fargate comparison uses one always-on 0.25 vCPU/0.5 GB task plus one ALB before LCU charges","excludes CloudFront, data transfer, logs, taxes, and application data services"]}}import{createHash as CA}from"node:crypto";function PA(e){let t=e;return String(t?.code||t?.name||t?.statusCode||"")}function _A(e){return PA(e)==="ValidationError"&&String(e.message).includes("does not exist")}function TA(e){return Object.fromEntries((e||[]).map((t)=>[t.OutputKey,t.OutputValue]))}function xA(e){let t=e?.Aliases?.Items??e?.Aliases,r=t?.CNAME??t;if(Array.isArray(r))return r.map(String);if(typeof r==="string")return[r];return[]}function Av(e){if(!/^[a-z][a-z0-9-]{1,62}$/.test(e.slug))throw Error("Slug must be a lowercase DNS-safe identifier");if(!/^[A-Z0-9]{8,32}$/.test(e.distributionId))throw Error("CloudFront distribution ID is invalid");if(!/^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9-]{2,63}$/.test(e.expectedAlias))throw Error("Expected distribution alias is invalid");let t=e.imageUri.match(/@((?:sha256:)[a-f0-9]{64})$/i)?.[1];if(!t)throw Error("Container image must use an immutable ECR digest URI ending in @sha256:<64 hex>");let r=e.stackName||`${e.slug}-backend`;if(!/^[A-Za-z][A-Za-z0-9-]{0,127}$/.test(r))throw Error("CloudFormation stack name is invalid");let a=e.pathPattern||"/api/*";if(!/^\/[A-Za-z0-9_.*?~!$&'()+,;=:@%/-]+\*$/.test(a)||a==="/*")throw Error("Backend path must be a non-default wildcard pattern");let u=e.originId||`${e.slug}-backend`;if(!/^[A-Za-z0-9_.-]{1,128}$/.test(u))throw Error("CloudFront origin ID is invalid");if(e.originVerifySecret&&e.originVerifySecret.length<24)throw Error("Origin verification secret must contain at least 24 characters");if(!!e.originDomain!==!!e.certificateArn)throw Error("A custom origin domain and matching ACM certificate ARN must be provided together");return{stackName:r,region:e.region||"us-east-1",pathPattern:a,originId:u,digest:t}}function nh(e){let t=e.region||"us-east-1";return{cloudformation:new h(t,e.profile),cloudfront:new S(e.profile),sts:new Te(t,e.profile),fetch,sleep:(r)=>new Promise((a)=>setTimeout(a,r))}}function ih(e){let t=Av(e),r=sl({name:e.name,slug:e.slug,domain:e.originDomain||e.expectedAlias,imageUri:e.imageUri,certificateArn:e.certificateArn,originVerifySecret:e.originVerifySecret,desiredCount:e.desiredCount,database:e.database,cache:e.cache,queue:e.queue}),a=il(r);return a.Description=`Managed backend for existing static frontend ${e.expectedAlias}`,a.Metadata={ManagedBy:"ts-cloud",ExistingDistributionId:e.distributionId,ExistingDistributionAlias:e.expectedAlias,BackendPathPattern:t.pathPattern,ContainerDigest:t.digest},a}async function DA(e,t,r){let a;for(let u=0;u<30;u++){let m=Date.now();try{let f=await e.fetch(t,{redirect:"manual",headers:r?{"x-origin-verify":r}:void 0}),b=Date.now()-m,w=await f.text(),y=w;try{y=JSON.parse(w)}catch{}if(f.ok)return{url:t,status:f.status,latencyMs:b,body:y};a=Error(`origin returned ${f.status}`)}catch(f){a=f}if(u<29)await e.sleep(1e4)}throw Error(`Backend origin did not become healthy: ${a instanceof Error?a.message:String(a)}`)}async function LS(e,t){let r=Av(e),a=t||nh({region:r.region,profile:e.profile}),[u,m]=await Promise.all([a.sts.getCallerIdentity(),a.cloudfront.getDistribution(e.distributionId)]);if(!u.Account)throw Error("AWS identity did not return an account ID");if(!m.Enabled)throw Error(`CloudFront distribution ${e.distributionId} is disabled`);if(!xA(m).includes(e.expectedAlias))throw Error(`Distribution ${e.distributionId} does not contain expected alias ${e.expectedAlias}`);let f;try{f=(await a.cloudformation.describeStacks({stackName:r.stackName})).Stacks[0]}catch(te){if(!_A(te))throw te}let b=ih(e),w=JSON.stringify(b);if(Buffer.byteLength(w)>51200)throw Error("Generated template exceeds the direct CloudFormation template body limit");let y=Object.values(b.Resources||{}).reduce((te,he)=>(te[he.Type]=(te[he.Type]||0)+1,te),{}),I=[`cloud cdn:origin:remove ${e.distributionId} ${e.originDomain||"ALB_HOST"} --id ${r.originId} --path '${r.pathPattern}' --profile ${e.profile||"default"} --apply --confirm 'remove:${e.distributionId}:${r.pathPattern}'`,`After CloudFront is deployed, restore external DNS if changed and delete stack ${r.stackName} only with an approved data-retention decision.`],A={mode:e.apply?"apply":"plan",accountId:u.Account,stack:{name:r.stackName,existed:!!f,status:f?.StackStatus,templateSha256:CA("sha256").update(w).digest("hex"),resourceCount:Object.keys(b.Resources||{}).length,resourceTypes:y},distribution:{id:m.Id,alias:e.expectedAlias,domainName:m.DomainName,status:m.Status,pathPattern:r.pathPattern,originId:r.originId},artifact:{imageUri:e.imageUri,digest:r.digest},services:{database:e.database!==!1,cache:e.cache!==!1,queue:e.queue!==!1,mail:"ses",desiredCount:e.desiredCount||1},cloudFrontApplied:!1,dnsApplied:!1,applied:!1,rollback:I};if(!e.apply)return A;let D=`${e.distributionId}:${r.pathPattern}:${r.stackName}`;if(e.confirm!==D)throw Error(`Pass exact confirmation token ${D} to provision the backend and change live routing`);if(f)try{await a.cloudformation.updateStack({stackName:r.stackName,templateBody:w,capabilities:["CAPABILITY_NAMED_IAM"],tags:[{Key:"ManagedBy",Value:"ts-cloud"},{Key:"Application",Value:e.slug}]}),await a.cloudformation.waitForStack(r.stackName,"stack-update-complete")}catch(te){if(!String(te.message).includes("No updates are to be performed"))throw te}else await a.cloudformation.createStack({stackName:r.stackName,templateBody:w,capabilities:["CAPABILITY_NAMED_IAM"],onFailure:"ROLLBACK",tags:[{Key:"ManagedBy",Value:"ts-cloud"},{Key:"Application",Value:e.slug}]}),await a.cloudformation.waitForStack(r.stackName,"stack-create-complete");let O=(await a.cloudformation.describeStacks({stackName:r.stackName})).Stacks[0],M=TA(O?.Outputs),z=M.AppLoadBalancerDnsName;if(!z)throw Error("Backend stack did not return AppLoadBalancerDnsName");let J=!1;if(e.originDomain&&e.originDomain!==z){if(!a.dns)throw Error(`External DNS provider is required to map ${e.originDomain} to ${z}`);let te=await a.dns.upsertRecord(e.originDomain,{name:e.originDomain,type:"CNAME",content:z,ttl:300});if(!te.success)throw Error(te.message||"External DNS update failed");J=!0}let Z=e.originDomain||z,oe=e.certificateArn?"https-only":"http-only",G=e.skipHealthCheck?void 0:await DA(a,`${oe==="https-only"?"https":"http"}://${Z}/api/health`,e.originVerifySecret);return await a.cloudfront.upsertExistingDistributionOrigin(e.distributionId,{id:r.originId,domainName:Z,pathPattern:r.pathPattern,protocolPolicy:oe,customHeaders:e.originVerifySecret?{"X-Origin-Verify":e.originVerifySecret}:void 0}),{...A,outputs:M,health:G,cloudFrontApplied:!0,dnsApplied:J,applied:!0}}function $S(e={}){let r={fargate:730*(e.desiredCount||1)*0.012342500000000001,applicationLoadBalancer:16.425,natGateway:32.85,postgres:730*(e.multiAzDatabase?0.032:0.016),redis:23.36};return{monthlyUsd:Number(Object.values(r).reduce((a,u)=>a+u,0).toFixed(2)),components:Object.fromEntries(Object.entries(r).map(([a,u])=>[a,Number(u.toFixed(2))])),assumptions:["us-east-1 public on-demand rate snapshot, July 2026","one 0.25 vCPU/0.5 GB Linux Fargate task unless desiredCount is changed","one ALB before LCU charges and one NAT gateway before data processing","single-AZ db.t4g.micro PostgreSQL by default and two cache.t4g.micro Redis nodes","excludes storage, backups, CloudFront, data transfer, public IPv4, logs, email, queue requests, taxes, and free-tier credits"]}}import{execFileSync as OA}from"node:child_process";import{createHash as $A}from"node:crypto";import{existsSync as Cv,mkdirSync as NA,mkdtempSync as jA,readdirSync as BA,readFileSync as MA,rmSync as LA,statSync as Pv,writeFileSync as FA}from"node:fs";import{tmpdir as zA}from"node:os";import{basename as UA,join as xs,relative as qA,resolve as _g}from"node:path";var VA=new Set([".git","node_modules","dist","coverage"]);function _v(e,t=e){let r=[];for(let a of BA(e).sort()){if(VA.has(a))continue;let u=xs(e,a);if(Kd(u,t))continue;let m=Pv(u);if(m.isDirectory())r.push(..._v(u,t));else if(m.isFile())r.push(qA(t,u))}return r}function sh(e){let t=_g(e);if(!Cv(t)||!Pv(t).isDirectory())throw Error(`Container context does not exist: ${t}`);let r=$A("sha256");for(let a of _v(t))r.update(a),r.update("\x00"),r.update(MA(xs(t,a))),r.update("\x00");return r.digest("hex")}function oh(e){return{ecr:new He(e.region||"us-east-1",e.profile),run:(t,r,a)=>{OA(t,r,{cwd:a?.cwd,env:a?.env,stdio:a?.stdio||"inherit"})}}}async function MS(e,t){let r=_g(e.context),a=_g(e.dockerfile||xs(r,"Dockerfile"));if(!Cv(a))throw Error(`Dockerfile does not exist: ${a}`);if(!e.repository.split("/").every((M)=>/^[a-z0-9][a-z0-9._-]*$/.test(M)&&!/[._-]$/.test(M)&&!/[._-]{2}/.test(M)))throw Error("ECR repository name is invalid");let f=t||oh(e),b=sh(r),w=`sha-${b.slice(0,20)}`,y="";try{y=(await f.ecr.describeRepositories({repositoryNames:[e.repository]})).repositories?.[0]?.repositoryUri||""}catch{}if(!y)y=(await f.ecr.createRepository({repositoryName:e.repository,imageTagMutability:"IMMUTABLE",imageScanningConfiguration:{scanOnPush:!0},tags:[{Key:"ManagedBy",Value:"ts-cloud"}]})).repository?.repositoryUri||"";if(!y)throw Error(`Could not resolve ECR repository URI for ${e.repository}`);await f.ecr.putLifecyclePolicy({repositoryName:e.repository,lifecyclePolicyText:JSON.stringify({rules:[{rulePriority:1,description:"Retain the newest 25 release images",selection:{tagStatus:"any",countType:"imageCountMoreThan",countNumber:25},action:{type:"expire"}}]})});let I=`${y}:${w}`,A=jA(xs(zA(),"ts-cloud-container-"));try{f.run("docker",["version"],{stdio:"ignore"}),f.run("docker",["build","--platform",e.platform||"linux/amd64","--provenance=false","--sbom=false","--file",a,"--tag",I,r],{cwd:r});let M=(await f.ecr.getAuthorizationToken()).authorizationData?.[0];if(!M?.authorizationToken||!M.proxyEndpoint)throw Error("ECR did not return Docker authorization data");let z=M.proxyEndpoint.replace(/^https?:\/\//,""),J=xs(A,"docker");NA(J,{recursive:!0}),FA(xs(J,"config.json"),JSON.stringify({auths:{[z]:{auth:M.authorizationToken}}}),{mode:384}),f.run("docker",["push",I],{env:{...process.env,DOCKER_CONFIG:J}})}finally{LA(A,{recursive:!0,force:!0})}let O=(await f.ecr.describeImages({repositoryName:e.repository,imageIds:[{imageTag:w}]})).imageDetails?.[0]?.imageDigest;if(!O||!/^sha256:[a-f0-9]{64}$/i.test(O))throw Error(`ECR did not return an immutable digest for ${UA(I)}`);return{repository:e.repository,tag:w,imageUri:I,digest:O,digestUri:`${y}@${O}`,contextSha256:b}}import{existsSync as WA,readdirSync as HA,readFileSync as KA,statSync as JA}from"node:fs";import{join as Tv,relative as GA}from"node:path";function Io(e,t){let r=e.environments?.[t]?.app;if(!r)throw Error(`No serverless app configured for environment '${t}'. Add environments.${t}.app to your config.`);let a=e.project.slug,u=e.environments?.[t]?.region||e.project.region||"us-east-1";return{app:r,slug:a,region:u,stackName:sr(e,t),artifactBucket:Xd(a,t),assetsBucket:Gi(a,t)}}async function wo(e,t=8){let r;for(let a=0;a<t;a++)try{return await e()}catch(u){let m=u?.code||u?.name||"",f=String(u?.message||"");if(m==="ResourceConflictException"||/update is in progress|currently in the following state/i.test(f)){r=u,await new Promise((b)=>setTimeout(b,3000));continue}throw u}throw r}var xv=(e,t)=>`releases/${e}/${t}/current.json`;async function Ud(e,t,r,a){try{return await e.getObjectJson(t,xv(r,a))}catch{return null}}async function Dv(e,t,r,a,u){await e.putObjectJson(t,xv(r,a),u)}async function QA(e,t){if(!e.secrets)return{};let r=new re(t),a={},u=Array.isArray(e.secrets)?e.secrets.map((m)=>({envName:m.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:m})):Object.entries(e.secrets).map(([m,f])=>({envName:m,secretId:f}));if(Array.isArray(e.secrets)){let m=new Map;for(let{envName:b,secretId:w}of u)m.set(b,[...m.get(b)??[],w]);let f=[...m.entries()].filter(([,b])=>b.length>1);if(f.length){let b=f.map(([w,y])=>`${w} ← ${y.join(", ")}`).join("; ");throw Error(`serverless secrets: multiple secrets map to the same env var (${b}). Use the map form { ENV_NAME: 'secret/id' } to disambiguate.`)}}for(let{envName:m,secretId:f}of u){let w=(await r.getSecretValue({SecretId:f})).SecretString??"";try{let y=JSON.parse(w);if(y&&typeof y==="object"&&!Array.isArray(y)){for(let[I,A]of Object.entries(y))a[I]=String(A);continue}}catch{}a[m]=w}return a}function fs(e,t){let r={},a=t.DbProxyEndpoint||t.DbEndpoint;if(a)r.DB_CONNECTION="mysql",r.DB_HOST=a,r.DB_PORT="3306",r.DB_DATABASE=r.DB_DATABASE||"app";if(t.CacheEndpoint){if(r.REDIS_HOST=t.CacheEndpoint,r.REDIS_PORT="6379",e.cache?.driver==="elasticache")r.CACHE_STORE="redis",r.CACHE_DRIVER="redis",r.SESSION_DRIVER="redis"}return r}function Ar(e,t,r,a,u,m,f,b={}){let w=e.kind==="php"?Ol({cacheDriver:e.cache?.driver==="elasticache"?"redis":"dynamodb"}):{};return{TSCLOUD_LAMBDA_MODE:a,TSCLOUD_ENV:r,MAINTENANCE_MODE:"0",...e.octane?{TSCLOUD_OCTANE:"1"}:{},...e.serveAssets?{TSCLOUD_SERVE_ASSETS:"1"}:{},...e.redirectRobotsTxt===!1?{TSCLOUD_REDIRECT_ROBOTS_TXT:"0"}:{},...w,...b,...t.app.cache?.driver!=="elasticache"?{TSCLOUD_CACHE_TABLE:`${t.slug}-${r}-cache`}:{},...f?{TSCLOUD_QUEUE:f,SQS_QUEUE:f}:{},...m?{ASSET_URL:m}:{},...e.env??{},...u}}function YA(e){let t=e.slice(e.lastIndexOf(".")).toLowerCase();return{".html":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".json":"application/json",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".txt":"text/plain",".map":"application/json"}[t]??"application/octet-stream"}function*Ov(e){for(let t of HA(e)){let r=Tv(e,t);if(JA(r).isDirectory())yield*Ov(r);else yield r}}async function ZA(e,t,r,a,u=!1){let m=0;for(let f of Ov(r)){let b=GA(r,f).replace(/\\/g,"/");if(!u&&b.split("/").some((w)=>w.startsWith(".")))continue;await e.putObject({bucket:t,key:`${a}/${b}`,body:KA(f),contentType:YA(f),cacheControl:"public, max-age=31536000, immutable"}),m++}return m}function XA(e,t){let r=Object.entries(t).reduce((a,[u,m])=>a+Buffer.byteLength(`${u}=${m}`,"utf8"),0);if(r>4096){let a=Object.entries(t).map(([u,m])=>[u,Buffer.byteLength(`${u}=${m}`,"utf8")]).sort((u,m)=>m[1]-u[1]).slice(0,5).map(([u,m])=>`${u} (${m}B)`).join(", ");throw Error(`${e}: environment variables total ${r}B, over AWS's 4096B limit (${r-4096}B too large). Largest: ${a}. Move large/secret values out of env — store them in Secrets Manager and fetch at cold start.`)}}async function uc(e,t,r,a){XA(t,r),await wo(()=>e.updateFunctionConfiguration({FunctionName:t,Environment:{Variables:r}})),await e.waitForFunctionActive(t,120);let u=a.kind==="image"?{FunctionName:t,ImageUri:a.imageUri}:{FunctionName:t,S3Bucket:a.bucket,S3Key:a.key};await wo(()=>e.updateFunctionCode(u)),await e.waitForFunctionActive(t,120)}async function zd(e,t){let a=(await wo(()=>e.publishVersion({FunctionName:t}))).Version;if(!a)throw Error(`publishVersion returned no version for ${t}`);return await wo(()=>e.updateAlias({FunctionName:t,Name:"live",FunctionVersion:a})),a}async function Ha(e,t,r={}){let a=Io(e,t),{app:u,slug:m,region:f,stackName:b,artifactBucket:w}=a,y=r.projectRoot??process.cwd();Ts(`Deploying serverless app: ${m} (${t})`),L(`Stack: ${b}`),L(`Region: ${f}`);let I=new o(f),A=new h(f),D=new v(f),O=u.kind==="php",M=u.packaging==="image",z=Wi(u),J,Z,oe,G,te=[];if(M&&z.usesLayer&&z.layerKind!=="php")throw Error(`packaging: 'image' currently supports PHP and managed Node runtimes. ${z.kind}${z.kind==="node"?` ${z.version}`:""} uses a custom runtime — `+"use the default zip packaging (the runtime layer is built + attached automatically).");if(M){P("Building + pushing container image");let{buildAndPushServerlessImage:le}=await import("./chunk-2gqm2h84.js"),Ce=await le({app:u,projectRoot:y,region:f,repository:`${m}-${t}`,skipBuild:r.skipBuild,onStep:(gt)=>L(` ${gt}`)});J=Ce.handlers,Z={kind:"image",imageUri:Ce.imageUri},oe=Ce.tag,te.push({ParameterKey:"ImageUri",ParameterValue:Ce.imageUri})}else{P("Packaging application");let le=O?_l({projectRoot:y,app:u,skipBuild:r.skipBuild,onStep:(It)=>L(` ${It}`)}):await ln({projectRoot:y,app:u,skipBuild:r.skipBuild,onStep:(It)=>L(` ${It}`)}),Ce=wl(m,t,le.sha256);if(L(`Artifact: ${le.sha256.slice(0,12)} (${(le.zip.length/1024).toFixed(0)} KB)`),J=le.handlers,oe=le.sha256,z.usesLayer){let It=z.layerEnvVar?process.env[z.layerEnvVar]:void 0;if(G=u.layers??(It?[It]:void 0),!G?.length){let _e=z.layerKind==="php"?"serverless:build-php-layer":z.layerKind==="bun"?"serverless:build-bun-layer":"serverless:build-node-layer";throw Error(`${z.kind} apps on provided.al2023 need a runtime layer. Set environments.<env>.app.layers or the ${z.layerEnvVar} env var (build one with \`cloud ${_e}\`)${z.kind==="node"?", or use a managed Node version (18/20/22)":""}.`)}}if(!await I.bucketExists(w))P(`Creating artifact bucket ${w}`),await I.createBucket(w);if(await I.headObject(w,Ce).then((It)=>It!==null).catch(()=>!1))L("Artifact already uploaded — reusing");else P("Uploading artifact"),await I.putObject({bucket:w,key:Ce,body:le.zip,contentType:"application/zip"});Z={kind:"zip",bucket:w,key:Ce},te.push({ParameterKey:"ArtifactBucket",ParameterValue:w},{ParameterKey:"ArtifactKey",ParameterValue:Ce})}let he=Dl({config:e,environment:t,app:u,handlers:J,runtimeLayers:G}),ye=JSON.stringify(he.template),ie=["CAPABILITY_NAMED_IAM"],xe=await A.describeStacks({stackName:b}).then((le)=>le.Stacks[0]?.StackStatus).catch(()=>{return}),ee=xe!==void 0;if(xe&&/DELETE_IN_PROGRESS/.test(xe))P("Waiting for an in-progress stack delete to finish"),await A.waitForStack(b,"stack-delete-complete").catch(()=>{}),ee=!1;else if(xe&&/(?:ROLLBACK_COMPLETE|REVIEW_IN_PROGRESS|CREATE_FAILED)/.test(xe))P(`Deleting unusable stack (status ${xe}) before recreate`),await A.deleteStack(b),await A.waitForStack(b,"stack-delete-complete").catch(()=>{}),ee=!1;P(ee?"Updating infrastructure stack":"Creating infrastructure stack");try{if(ee)await A.updateStack({stackName:b,templateBody:ye,parameters:te,capabilities:ie}),await A.waitForStack(b,"stack-update-complete");else await A.createStack({stackName:b,templateBody:ye,parameters:te,capabilities:ie,onFailure:"DELETE"}),await A.waitForStack(b,"stack-create-complete")}catch(le){if(/No updates are to be performed/i.test(String(le?.message)))L("No infrastructure changes");else throw le}let De=await A.getStackOutputs(b).catch(()=>({})),Ge;if(u.assets){let le=Tv(y,u.assets);if(WA(le)){let Ce=u.assetDomain||De.AssetsCdnDomain;Ge=Ce?`https://${Ce}/${oe}`:void 0,P(`Syncing assets from ${u.assets}`);let gt=await ZA(I,a.assetsBucket,le,oe,u.dotFilesAsAssets);L(`Uploaded ${gt} asset(s)${Ge?` → ${Ge}`:""}`)}else vs(`Assets directory not found: ${le}`)}P("Resolving secrets");let pt=await QA(u,f);if(u.database?.connection==="aurora-serverless")try{let Ce=await new re(f).getSecretValue({SecretId:`${m}/${t}/db`}),gt=JSON.parse(Ce.SecretString??"{}");if(gt.username)pt.DB_USERNAME=gt.username;if(gt.password)pt.DB_PASSWORD=gt.password}catch(le){vs(`Could not resolve Aurora DB credentials: ${le.message}`)}if(!await I.bucketExists(w))await I.createBucket(w);let Ft=await Ud(I,w,m,t),Ze={},wt=he.queueNames[0],zt=fs(u,De);if(P("Activating functions"),Ze.http=Ar(u,a,t,"http",pt,Ge,wt,zt),await uc(D,he.functionNames.http,Ze.http,Z),Ze.cli=Ar(u,a,t,"cli",pt,Ge,wt,zt),await uc(D,he.functionNames.cli,Ze.cli,Z),he.queueNames.length)Ze.queue=Ar(u,a,t,"queue",pt,Ge,wt,zt),await uc(D,he.functionNames.queue,Ze.queue,Z);let rt=(u.provisionedConcurrency??0)>0,W={};if(rt){if(P("Publishing versions + flipping live alias"),W.http=await zd(D,he.functionNames.http),W.cli=await zd(D,he.functionNames.cli),he.queueNames.length)W.queue=await zd(D,he.functionNames.queue)}if(await Dv(I,w,m,t,{sha:oe,code:Z,previousSha:Ft?.sha,previousCode:Ft?.code,previousFunctionEnv:Ft?.functionEnv,...rt?{functionVersions:W,previousFunctionVersions:Ft?.functionVersions}:{},functionEnv:Ze,functionNames:{http:he.functionNames.http,cli:he.functionNames.cli,...he.queueNames.length?{queue:he.functionNames.queue}:{}},assetUrl:Ge,timestamp:new Date().toISOString()}),!r.skipDeployHooks&&u.deploy?.length){P("Running deploy hooks");for(let le of u.deploy){L(` deploy: ${le}`);let Ce=await D.invoke({FunctionName:he.functionNames.cli,InvocationType:"RequestResponse",Payload:{command:le},LogType:"Tail"});if(Ce.FunctionError)throw dg("Deploy hook failed — the new build is ALREADY LIVE."),L(` Roll back with: cloud serverless:rollback --env ${t}`),Error(`Deploy hook failed (${le}): ${Ce.Payload}`)}}let se=De.HttpApiEndpoint;if(!r.skipHealthCheck&&se){P("Health check");try{let le=await fetch(se,{method:"GET"});L(`GET ${se} → ${le.status}`)}catch(le){vs(`Health check could not reach ${se}: ${le.message}`)}}lg(["Serverless deploy complete","",se?`URL: ${se}`:"",`Stack: ${b}`,`Build: ${oe.slice(0,12)}`].filter(Boolean).join(`
180
180
  `),"green")}async function Rn(e,t){let r=Io(e,t),a=new o(r.region),u=new v(r.region),m=await Ud(a,r.artifactBucket,r.slug,t);if(!m)throw Error("No previous release to redeploy. Run a full deploy first.");Ts(`Redeploying ${r.slug} (${t}) — build ${m.sha.slice(0,12)}`);for(let[f,b]of Object.entries(m.functionNames)){if(!b)continue;P(`Re-activating ${f} (${b})`),await uc(u,b,m.functionEnv[f]??{},m.code);let w=m.functionVersions?.[f];if(w)await wo(()=>u.updateAlias({FunctionName:b,Name:"live",FunctionVersion:w}))}On("Redeploy complete")}async function Dn(e,t){let r=Io(e,t),a=new o(r.region),u=new v(r.region),m=await Ud(a,r.artifactBucket,r.slug,t);if(!m?.previousCode)throw Error("No previous release to roll back to.");Ts(`Rolling back ${r.slug} (${t}) → ${m.previousSha?.slice(0,12)}`);for(let[f,b]of Object.entries(m.functionNames)){if(!b)continue;P(`Restoring ${f} (${b})`);let w=m.previousFunctionEnv?.[f]??m.functionEnv[f]??{};await uc(u,b,w,m.previousCode);let y=m.previousFunctionVersions?.[f];if(y)await wo(()=>u.updateAlias({FunctionName:b,Name:"live",FunctionVersion:y}))}await Dv(a,r.artifactBucket,r.slug,t,{...m,sha:m.previousSha??m.sha,code:m.previousCode,functionEnv:m.previousFunctionEnv??m.functionEnv,functionVersions:m.previousFunctionVersions??m.functionVersions,previousSha:void 0,previousCode:void 0,previousFunctionEnv:void 0,previousFunctionVersions:void 0,timestamp:new Date().toISOString()}),On("Rollback complete")}async function yr(e,t,r,a){let u=Io(e,t),m=new v(u.region),f=`${u.slug}-${t}-http`,w={...(await m.getFunction(f)).Configuration?.Environment?.Variables??{}};if(w.MAINTENANCE_MODE=r?"1":"0",r&&a)w.MAINTENANCE_BYPASS_SECRET=a;if(!r)delete w.MAINTENANCE_BYPASS_SECRET;if(await wo(()=>m.updateFunctionConfiguration({FunctionName:f,Environment:{Variables:w}})),(u.app.provisionedConcurrency??0)>0)await m.waitForFunctionActive(f,120),await zd(m,f);On(r?"Application is now in maintenance mode (503)":"Application is live")}async function ct(e,t,r){let a=Io(e,t),u=new v(a.region),m=`${a.slug}-${t}-cli`,f=await u.invoke({FunctionName:m,InvocationType:"RequestResponse",Payload:{command:r},LogType:"Tail"});if(f.FunctionError)throw Error(`Command failed: ${f.Payload}`);return f.Payload??""}async function Er(e,t){let r=Io(e,t),a=new h(r.region),u=new v(r.region),m=new o(r.region),f="not deployed",b={};try{let{Stacks:M}=await a.describeStacks({stackName:r.stackName});f=M?.[0]?.StackStatus??f;for(let z of M?.[0]?.Outputs??[])if(z.OutputKey)b[z.OutputKey]=z.OutputValue??""}catch{}let w=Rl(r.app,r.slug,t),y=r.app.provisionedConcurrency??0,I=["http","cli",...w.length?["queue"]:[]],A=`${r.slug}-${t}`,D=[];for(let M of I){let z=`${A}-${M}`,J={mode:M,name:z,version:"$LATEST"};if(y>0){let Z=await u.getAlias(z,"live").catch(()=>null);if(Z?.FunctionVersion){J.version=Z.FunctionVersion;let oe=await u.getProvisionedConcurrencyConfig(z,"live").catch(()=>null);if(oe)J.provisioned={status:oe.Status??"-",allocated:oe.AllocatedProvisionedConcurrentExecutions??0,requested:oe.RequestedProvisionedConcurrentExecutions??0}}}D.push(J)}let O=await Ud(m,r.artifactBucket,r.slug,t).catch(()=>null);return{slug:r.slug,environment:t,region:r.region,stackStatus:f,endpoint:b.HttpApiEndpoint,assetUrl:O?.assetUrl,scheduler:r.app.scheduler??"on",queues:w,provisionedConcurrency:y,functions:D,lastRelease:O?{sha:O.sha,timestamp:O.timestamp}:void 0}}function eC(e,t){return`${e}-${t}-db`}async function $v(e,t,r,a){let u=Io(e,t);if(u.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");let{RDSClient:m}=await import("./chunk-qbsrs1gp.js"),f=new m(u.region),b=eC(u.slug,t);P(`Scaling ${b} → ${r}–${a} ACUs`),await f.modifyDBCluster({DBClusterIdentifier:b,ServerlessV2ScalingConfiguration:{MinCapacity:r,MaxCapacity:a},ApplyImmediately:!0}),On(`Scaling applied to ${b} (takes effect shortly).`)}class xg{client;region;constructor(e="us-east-1"){this.region=e,this.client=new n}async call(e,t){return this.client.request({service:"wafv2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSWAF_20190729.${e}`},body:JSON.stringify(t)})}async listWebACLs(e="REGIONAL"){return(await this.call("ListWebACLs",{Scope:e,Limit:100}))?.WebACLs??[]}async getWebACLRules(e,t,r="REGIONAL"){return((await this.call("GetWebACL",{Name:e,Id:t,Scope:r}))?.WebACL?.Rules??[]).map((m)=>({Name:m.Name,Priority:m.Priority,Action:m.Action?Object.keys(m.Action)[0]:m.OverrideAction?Object.keys(m.OverrideAction)[0]:"count"}))}}var tC=[{index:0,id:"clients",label:"Clients"},{index:1,id:"dns",label:"DNS & TLS"},{index:2,id:"edge",label:"Edge"},{index:3,id:"routing",label:"Routing"},{index:4,id:"apps",label:"Applications"},{index:5,id:"runtime",label:"Background runtime"},{index:6,id:"data",label:"Data services"},{index:7,id:"durability",label:"Durability"}],rC=[{index:0,id:"clients",label:"Clients"},{index:1,id:"dns",label:"DNS & TLS"},{index:2,id:"edge",label:"Edge"},{index:3,id:"entry",label:"Entry points"},{index:4,id:"compute",label:"Compute"},{index:5,id:"messaging",label:"Messaging & pooling"},{index:6,id:"data",label:"Data services"},{index:7,id:"durability",label:"Durability"}],nC=[{match:/^redis/,kind:"cache",label:"Redis"},{match:/^(?:mysql|mariadb)/,kind:"database",label:"MySQL"},{match:/^postgres/,kind:"database",label:"PostgreSQL"},{match:/^meilisearch/,kind:"database",label:"Meilisearch"},{match:/^vitess|^vtgate/,kind:"database",label:"Vitess"},{match:/^memcached/,kind:"cache",label:"Memcached"}],iC=/^(?:rpx-gateway|nginx|caddy|traefik|haproxy)$/;function Pe(e,t=""){let r=e==null?"":String(e).trim();return r&&r!=="-"&&r!=="—"?r:t}function oC(e){return Array.isArray(e)?e.length:0}function Jn(e){let t=Pe(e).toLowerCase();if(!t)return"unknown";if(["running","live","active","available","success","ok","healthy","enabled"].includes(t))return"ok";if(["failed","stopped","unreachable","error","critical","disabled"].includes(t))return"bad";if(["configured","creating","pending","degraded","shadowed","warn","unknown"].includes(t))return"warn";return"warn"}function Xt(e,t,r){if(r.has(t.source)&&r.has(t.target))e.push(t)}function Lt(e,t={}){let r=[],a=[],u=[],m=e.server??{},f=Array.isArray(e.sites)?e.sites:[],b=Array.isArray(e.services)?e.services:[],w=Array.isArray(e.workers)?e.workers:[],y=e.security??{},I=!!e._serverReachable&&!e.metricsUnavailable,A="box";if(!I)u.push("The compute box could not be probed, so live service state is missing; the shape comes from your cloud config.");r.push({id:"internet",label:"Internet",kind:"internet",layer:0,status:"ok",sub:"Public traffic",facts:[],external:!0});let D=[...new Set(f.map((ie)=>Pe(ie.domain)||Pe(ie.route).split("/")[0]).filter((ie)=>ie&&ie!=="internal"&&ie!=="loopback"))],O=Array.isArray(y.tlsCertificates)?y.tlsCertificates:[],M=O.filter((ie)=>Number(ie?.daysRemaining??999)<21).length;r.push({id:"dns",label:D.length===1?D[0]:"Public domains",kind:"dns",layer:1,status:M?"warn":D.length?"ok":"unknown",sub:D.length>1?`${D.length} domains`:"DNS & certificates",facts:[{label:"Domains",value:D.length?D.slice(0,6).join(", "):"none resolved"},{label:"Certificates",value:O.length?`${O.length} issued`:"none reported"},...M?[{label:"Expiring",value:`${M} within 21 days`}]:[]],href:"/server/security",external:!0});let z=y.firewall??{},J=Array.isArray(y.ports)?y.ports:[];r.push({id:"firewall",label:"Host firewall",kind:"firewall",layer:2,status:Jn(z.status),sub:Pe(z.summary,"Inbound filtering"),facts:[{label:"State",value:Pe(z.status,"unknown")},{label:"Open ports",value:J.length?J.map((ie)=>Pe(ie.listen)).join(", "):"not reported"}],href:"/server/firewall",group:"box"});let Z=b.find((ie)=>iC.test(Pe(ie.name)));r.push({id:"proxy",label:Pe(Z?.name,"Reverse proxy"),kind:"proxy",layer:3,status:Z?Jn(Z.status):"unknown",sub:"TLS termination & routing",facts:[{label:"Service",value:Pe(Z?.name,"not detected")},{label:"State",value:Pe(Z?.status,I?"not running":"not probed")},{label:"Routes",value:`${f.length} site${f.length===1?"":"s"}`}],href:"/server/services",group:"box"});for(let ie of f){let xe=`site:${Pe(ie.name)}`;if(!Pe(ie.name))continue;r.push({id:xe,label:Pe(ie.name),kind:"site",layer:4,status:Jn(ie.status),sub:Pe(ie.runtime,"runtime"),facts:[{label:"Route",value:Pe(ie.route,"internal")},{label:"Runtime",value:Pe(ie.runtime,"unknown")},{label:"Delivery",value:Pe(ie.deploy,"unknown")},{label:"TLS",value:Pe(ie.tls,"unknown")},...ie.responseMs!=null?[{label:"Response",value:`${Math.round(Number(ie.responseMs))} ms`}]:[],...ie.httpStatus!=null?[{label:"HTTP",value:String(ie.httpStatus)}]:[]],href:"/server/sites",group:"box"})}for(let ie of w){let xe=`worker:${Pe(ie.name)}`;if(!Pe(ie.name))continue;r.push({id:xe,label:Pe(ie.name),kind:"worker",layer:5,status:Jn(ie.status),sub:`${Number(ie.processes??1)} process${Number(ie.processes??1)===1?"":"es"}`,facts:[{label:"Processes",value:String(ie.processes??1)},{label:"State",value:Pe(ie.status,"unknown")},...Pe(ie.site)?[{label:"Site",value:Pe(ie.site)}]:[]],href:"/operations/jobs",group:"box"})}let oe=e.serverScheduler??{};if(oe.enabled)r.push({id:"scheduler",label:"Scheduler",kind:"scheduler",layer:5,status:"ok",sub:"Cron dispatch",facts:[{label:"Last run",value:Pe(oe.lastRun,"unknown")}],href:"/operations/jobs",group:"box"});let G=b.map((ie)=>{let xe=Pe(ie.name),ee=nC.find((De)=>De.match.test(xe));return ee?{service:ie,name:xe,...ee}:null}).filter((ie)=>!!ie);for(let ie of G)r.push({id:`data:${ie.name}`,label:ie.label,kind:ie.kind,layer:6,status:Jn(ie.service.status),sub:ie.name,facts:[{label:"Unit",value:ie.name},{label:"State",value:Pe(ie.service.status,"unknown")}],href:"/data/services",group:"box"});let te=e.backup??{};if(te.enabled)r.push({id:"backup",label:"Backups",kind:"backup",layer:7,status:"ok",sub:Pe(te.destination,"destination"),facts:[{label:"Destination",value:Pe(te.destination,"unknown")},{label:"Schedule",value:Pe(te.schedule,"unknown")},{label:"Retention",value:`${te.retention??0} copies`},{label:"Last run",value:Pe(te.last,"unknown")}],href:"/data/backups"});let he=new Set(r.map((ie)=>ie.id));Xt(a,{source:"internet",target:"dns",flow:"request",label:"https"},he),Xt(a,{source:"dns",target:"firewall",flow:"request",label:"443/80"},he),Xt(a,{source:"firewall",target:"proxy",flow:"request"},he);for(let ie of f){let xe=`site:${Pe(ie.name)}`;Xt(a,{source:"proxy",target:xe,flow:"request",label:Pe(ie.path)||void 0,status:Jn(ie.status)},he)}for(let ie of w){let xe=`worker:${Pe(ie.name)}`,ee=`site:${Pe(ie.site)}`;if(he.has(ee))Xt(a,{source:ee,target:xe,flow:"async",label:"queue"},he);else Xt(a,{source:"proxy",target:xe,flow:"async",label:"queue"},he)}for(let ie of w)Xt(a,{source:"scheduler",target:`worker:${Pe(ie.name)}`,flow:"async",label:"dispatch"},he);let ye=[...f.map((ie)=>`site:${Pe(ie.name)}`),...w.map((ie)=>`worker:${Pe(ie.name)}`)];for(let ie of G)for(let xe of ye)Xt(a,{source:xe,target:`data:${ie.name}`,flow:"data",label:"localhost"},he);if(G.length&&ye.length)u.push("Data-service edges show co-location on the box: every process on it can reach localhost. They are not a declared per-site binding.");for(let ie of G)Xt(a,{source:`data:${ie.name}`,target:"backup",flow:"backup",label:"snapshot"},he);for(let ie of f)Xt(a,{source:`site:${Pe(ie.name)}`,target:"backup",flow:"backup"},he);return{mode:"server",project:Pe(t.project)||Pe(e.project?.name)||Pe(m.name,"project"),environment:Pe(t.environment)||Pe(e.environment,"production"),provider:Pe(m.provider,"unknown"),region:Pe(m.region,"unknown"),generatedAt:new Date().toISOString(),layers:tC,groups:[{id:"box",label:Pe(m.name,"App server"),sub:[Pe(m.provider),Pe(m.region),Pe(m.ip)].filter(Boolean).join(" · ")}],nodes:r,links:a,notes:u}}function hs(e,t={}){let r=[],a=[],u=[],m=e.app??{},f=Array.isArray(e.functions)?e.functions:[],b=Array.isArray(e.queues)?e.queues:[],w=e.metrics??{};if(!f.length)u.push("No Lambda functions were read for this environment, so the compute layer is empty rather than assumed.");r.push({id:"internet",label:"Internet",kind:"internet",layer:0,status:"ok",sub:"Public traffic",facts:[],external:!0});let y=Pe(m.url),I=y.replace(/^https?:\/\//,"").split("/")[0];r.push({id:"dns",label:I||"Application domain",kind:"dns",layer:1,status:I?"ok":"unknown",sub:"DNS & certificates",facts:[{label:"Endpoint",value:y||"not resolved"}],external:!0});let A=e.waf;if(A)r.push({id:"waf",label:"WAF",kind:"waf",layer:2,status:Jn(A.status??"active"),sub:Pe(A.scope,"Managed rules"),facts:[{label:"Web ACL",value:Pe(A.name,"unnamed")},...A.blocked!=null?[{label:"Blocked (24h)",value:String(A.blocked)}]:[],{label:"Rules",value:String(oC(e.wafRules))}],href:"/serverless/firewall"});let D=e.assetsInfo;if(D)r.push({id:"cdn",label:"Asset CDN",kind:"cdn",layer:2,status:"ok",sub:Pe(D.cdn,"CloudFront"),facts:[{label:"Distribution",value:Pe(D.cdn,"unknown")},{label:"Custom domain",value:Pe(D.customDomain,"none")}],href:"/serverless/assets"}),r.push({id:"assets",label:"Asset bucket",kind:"storage",layer:6,status:"ok",sub:Pe(D.bucket,"S3"),facts:[{label:"Bucket",value:Pe(D.bucket,"unknown")},...D.files?[{label:"Objects",value:String(D.files)}]:[],...D.sizeMb?[{label:"Size",value:`${D.sizeMb} MB`}]:[]],href:"/serverless/assets"});let O=f.find((ee)=>Pe(ee.key).startsWith("http"));r.push({id:"gateway",label:"HTTP entry point",kind:"gateway",layer:3,status:O?"ok":"unknown",sub:"Function URL / API Gateway",facts:[{label:"Endpoint",value:y||"not resolved"},{label:"Invocations (24h)",value:String(w.invocations??0)},...w.errorRatePct!=null?[{label:"Error rate",value:`${w.errorRatePct}%`}]:[]],href:"/serverless/metrics"});for(let ee of f){let De=`fn:${Pe(ee.name)}`;if(!Pe(ee.name))continue;let Ge=Number(ee.errors??0),pt=Number(ee.invocations??0);r.push({id:De,label:Pe(ee.key,Pe(ee.name)),kind:"function",layer:4,status:Ge>0?pt&&Ge/pt>0.02?"bad":"warn":pt?"ok":"idle",sub:Pe(ee.runtime,"lambda"),facts:[{label:"Function",value:Pe(ee.name)},{label:"Memory",value:`${ee.memory??0} MB`},{label:"Timeout",value:`${ee.timeout??0}s`},{label:"Invocations (24h)",value:String(pt)},{label:"Errors (24h)",value:String(Ge)},{label:"p95",value:`${ee.p95??0} ms`},...ee.provisioned?[{label:"Provisioned",value:Pe(ee.provisioned)}]:[]],href:"/serverless/functions"})}for(let ee of b){let De=`queue:${Pe(ee.name)}`;if(!Pe(ee.name))continue;let Ge=Number(ee.dlq??0);r.push({id:De,label:Pe(ee.name),kind:"queue",layer:5,status:Ge>0?"bad":Number(ee.visible??0)>0?"warn":"ok",sub:"SQS",facts:[{label:"Visible",value:String(ee.visible??0)},{label:"In flight",value:String(ee.inFlight??0)},{label:"Processed (24h)",value:String(ee.processed??0)},{label:"Dead letter",value:String(Ge)}],href:"/serverless/queues"})}let M=e.aurora;if(M)r.push({id:"database",label:"Aurora Serverless",kind:"database",layer:6,status:Jn(M.status),sub:Pe(M.engine,"aurora"),facts:[{label:"Cluster",value:Pe(M.id,"unknown")},{label:"Capacity",value:`${M.currentAcu??0} ACU (${M.minAcu??0}–${M.maxAcu??0})`},{label:"Connections",value:String(M.connections??0)}],href:"/serverless/data"});let z=e.proxy;if(z)r.push({id:"rds-proxy",label:"RDS Proxy",kind:"database",layer:5,status:Jn(z.status),sub:"Connection pooling",facts:[{label:"Proxy",value:Pe(z.name,"unknown")},{label:"Endpoint",value:Pe(z.endpoint,"unknown")},{label:"Pooled",value:String(z.pooledConns??0)}],href:"/serverless/data"});let J=e.redis;if(J)r.push({id:"cache",label:"ElastiCache",kind:"cache",layer:6,status:Jn(J.status),sub:Pe(J.node,"redis"),facts:[{label:"Group",value:Pe(J.id,"unknown")},{label:"Hit rate",value:`${J.hitRate??0}%`}],href:"/serverless/data"});let Z=e.efs;if(Z)r.push({id:"efs",label:"EFS",kind:"filesystem",layer:6,status:Jn(Z.status),sub:Pe(Z.mount,"/mnt/local"),facts:[{label:"File system",value:Pe(Z.id,"unknown")},{label:"Mount",value:Pe(Z.mount,"unknown")},{label:"Size",value:`${Z.sizeMb??0} MB`}],href:"/data/volumes"});let oe=e.scheduler??{};if(oe.enabled)r.push({id:"scheduler",label:"Scheduler",kind:"scheduler",layer:3,status:"ok",sub:Pe(oe.expression,"rate(1 minute)"),facts:[{label:"Expression",value:Pe(oe.expression,"unknown")},{label:"Last run",value:Pe(oe.lastRun,"unknown")}],href:"/operations/jobs"});let G=new Set(r.map((ee)=>ee.id)),te=G.has("waf")?"waf":"gateway";Xt(a,{source:"internet",target:"dns",flow:"request",label:"https"},G),Xt(a,{source:"dns",target:te,flow:"request"},G),Xt(a,{source:"dns",target:"cdn",flow:"request",label:"assets"},G),Xt(a,{source:"waf",target:"gateway",flow:"request",label:"allowed"},G),Xt(a,{source:"cdn",target:"assets",flow:"data",label:"origin"},G);let he=f.filter((ee)=>Pe(ee.key).startsWith("http")),ye=f.filter((ee)=>Pe(ee.key).startsWith("queue")),ie=f.filter((ee)=>Pe(ee.key).startsWith("cli"));for(let ee of he)Xt(a,{source:"gateway",target:`fn:${Pe(ee.name)}`,flow:"request",label:"invoke"},G);for(let ee of ie)Xt(a,{source:"scheduler",target:`fn:${Pe(ee.name)}`,flow:"async",label:"schedule"},G);for(let ee of b){for(let De of he)Xt(a,{source:`fn:${Pe(De.name)}`,target:`queue:${Pe(ee.name)}`,flow:"async",label:"publish"},G);for(let De of ye)Xt(a,{source:`queue:${Pe(ee.name)}`,target:`fn:${Pe(De.name)}`,flow:"async",label:"consume"},G)}let xe=["rds-proxy","database","cache","efs","assets"];for(let ee of f){let De=`fn:${Pe(ee.name)}`;if(G.has("rds-proxy"))Xt(a,{source:De,target:"rds-proxy",flow:"data",label:"pooled"},G);else Xt(a,{source:De,target:"database",flow:"data",label:"sql"},G);for(let Ge of xe.filter((pt)=>pt!=="rds-proxy"&&pt!=="database"))Xt(a,{source:De,target:Ge,flow:"data"},G)}return Xt(a,{source:"rds-proxy",target:"database",flow:"data",label:"sql"},G),{mode:"serverless",project:Pe(t.project)||Pe(m.name,"application"),environment:Pe(t.environment)||Pe(m.env,"production"),provider:"aws",region:Pe(m.region,"unknown"),generatedAt:new Date().toISOString(),layers:rC,groups:[],nodes:r,links:a,notes:u}}function ah(e,t,r={}){return e==="serverless"?hs(t,r):Lt(t,r)}function Nv(e){return String(e).padStart(2,"0")}function Ds(e){return`${e.getUTCFullYear()}-${Nv(e.getUTCMonth()+1)}-${Nv(e.getUTCDate())}`}function sC(e){let t=Math.max(0,Math.round((Date.now()-e)/1000));if(t<60)return`${t}s ago`;let r=Math.round(t/60);if(r<60)return`${r}m ago`;let a=Math.round(r/60);if(a<48)return`${a}h ago`;return`${Math.round(a/24)}d ago`}async function pc(e,t,r,a,u,m){let f=await e.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:r,Dimensions:[{Name:"FunctionName",Value:t}],StartTime:u,EndTime:m,Period:86400,Statistics:[a]}).catch(()=>[]);if(!f.length)return 0;if(a==="Sum")return f.reduce((b,w)=>b+(w.Sum??0),0);if(a==="Maximum")return Math.max(...f.map((b)=>b.Maximum??0));return f.reduce((b,w)=>b+(w.Average??0),0)/f.length}async function gc(e,t,r,a,u,m,f){let b=await e.getMetricStatistics({Namespace:t,MetricName:r,Dimensions:a,StartTime:m,EndTime:f,Period:86400,Statistics:[u]}).catch(()=>[]);if(!b.length)return 0;if(u==="Sum")return b.reduce((w,y)=>w+(y.Sum??0),0);if(u==="Maximum")return Math.max(...b.map((w)=>w.Maximum??0));return b.reduce((w,y)=>w+(y.Average??0),0)/b.length}async function Dg(e,t,r,a,u){let m=await e.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Duration",Dimensions:[{Name:"FunctionName",Value:t}],StartTime:a,EndTime:u,Period:86400,ExtendedStatistics:[r]}).catch(()=>[]);return Math.round(m.reduce((f,b)=>f+(b.Percentiles?.[r]??0),0))}async function Pn(e,t){let r=await Er(e,t),a=r.region,u=new me(a),m=new v(a),f=new we(a),b=new Date,w=new Date(b.getTime()-86400000),y=e.environments?.[t]?.app,I={};I.app={name:r.slug,env:t,region:a,runtime:y?.kind==="php"?`php-${y?.phpVersion??"8.3"} (fpm)`:y?.kind??"node",url:r.endpoint??"",build:r.lastRelease?.sha?.slice(0,7)??"—",deployedAt:r.lastRelease?.timestamp??"—"},I.maintenance={enabled:!1},I.scheduler={enabled:r.scheduler!=="off",expression:r.scheduler==="sub-minute"?"rate(1 minute) · sub-minute":"rate(1 minute)",lastRun:"—"};let A=0,D=0,O=0,M=[],z=[],J=[];for(let te of r.functions){let[he,ye,ie,xe,ee,De,Ge,pt,Ft]=await Promise.all([pc(u,te.name,"Invocations","Sum",w,b),pc(u,te.name,"Errors","Sum",w,b),pc(u,te.name,"Throttles","Sum",w,b),pc(u,te.name,"Duration","Average",w,b),m.getFunction(te.name).catch(()=>null),Dg(u,te.name,"p50",w,b),Dg(u,te.name,"p95",w,b),Dg(u,te.name,"p99",w,b),u.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:te.name}],StartTime:new Date(b.getTime()-43200000),EndTime:b,Period:3600,Stat:"Sum"}).catch(()=>[])]);A+=he,D+=ye,O=Math.max(O,xe);let Ze=ee?.Configuration?.MemorySize??0,wt=Object.keys(ee?.Configuration?.Environment?.Variables??{}),zt=[],rt=0;try{let{events:se=[]}=await f.filterLogEvents({logGroupName:`/aws/lambda/${te.name}`,startTime:w.getTime(),limit:120});for(let le of se){let Ce=(le.message??"").trim(),gt=/Max Memory Used:\s*(\d+)\s*MB/.exec(Ce);if(gt)rt=Math.max(rt,Number(gt[1]));if(Ce&&!/^(?:START|END|REPORT|INIT_START)/.test(Ce))J.push({source:te.mode||te.name,timestamp:new Date(le.timestamp??0).toISOString(),when:sC(le.timestamp??0),message:Ce.slice(0,400),level:/error|exception|fatal|panic|traceback/i.test(Ce)?"error":/warn|warning|timeout|retr(?:y|ies)|throttl/i.test(Ce)?"warn":"info"})}zt=se.filter((le)=>!/^(?:START|END|REPORT|INIT_START)/.test((le.message??"").trim())).slice(-6).map((le)=>({ts:new Date(le.timestamp??0).toISOString().slice(11,19),msg:(le.message??"").trim().slice(0,120),err:/error|exception|fatal/i.test(le.message??"")}))}catch{}let W=Math.max(1,...Ft);M.push({key:te.mode,name:te.name,version:te.version,memory:Ze,timeout:ee?.Configuration?.Timeout??0,runtime:ee?.Configuration?.Runtime??"provided.al2023",invocations:Math.round(he),errors:Math.round(ye),p95:Ge||Math.round(xe),status:"active",provisioned:te.provisioned?`${te.provisioned.allocated}/${te.provisioned.requested}`:void 0}),z.push({key:te.mode,name:te.name,runtime:ee?.Configuration?.Runtime??"provided.al2023",arch:ee?.Configuration?.Architectures?.[0]??"x86_64",memory:Ze,timeout:ee?.Configuration?.Timeout??0,ephemeral:ee?.Configuration?.EphemeralStorage?.Size??512,version:te.version,concurrency:y?.concurrency??"—",invocations:Math.round(he),errors:Math.round(ye),throttles:Math.round(ie),p50:De||Math.round(xe),p95:Ge||Math.round(xe),p99:pt||Math.round(xe),maxMem:rt,spark:Ft.length?Ft.map((se)=>Math.round(se/W*100)):[0],env:wt.length?wt:["(none)"],recent:zt.length?zt:[{ts:"—",msg:"no recent events",err:!1}]})}I.functions=M,I.functionsDetail=z,I.serverlessLogs=J.sort((te,he)=>String(he.timestamp).localeCompare(String(te.timestamp))).slice(0,600),I.serverlessLogsEmptyReason=J.length?void 0:"No recent function logs were found in CloudWatch for this environment.";let Z=A?Number((D/A*100).toFixed(2)):0,oe=Math.round(await pc(u,r.functions[0]?.name??"","ConcurrentExecutions","Maximum",w,b));I.metrics={invocations:Math.round(A),errorRatePct:Z,p95Ms:Math.round(O),coldStartPct:void 0,concurrency:oe,estCostUsd:void 0};try{let te=new pe(a),he=[],ye=[],ie=0;try{let{QueueUrl:ee}=await te.getQueueUrl(`${r.slug}-${t}-dlq`),{Attributes:De}=await te.getQueueAttributes(ee);ie=Number(De.ApproximateNumberOfMessages??0)}catch{}let xe=y?gr(y,r.slug,t):[];for(let ee of xe){let De=ee.name.replace(`${r.slug}-${t}-`,""),Ge=0,pt=0;try{let{QueueUrl:Ze}=await te.getQueueUrl(ee.name),{Attributes:wt}=await te.getQueueAttributes(Ze);Ge=Number(wt.ApproximateNumberOfMessages??0),pt=Number(wt.ApproximateNumberOfMessagesNotVisible??0)}catch{}let Ft=Math.round(await gc(u,"AWS/SQS","NumberOfMessagesDeleted",[{Name:"QueueName",Value:ee.name}],"Sum",w,b));he.push({name:De,visible:Ge,inFlight:pt,processed:Ft,dlq:ie}),ye.push({name:ee.name,short:De,visible:Ge,inFlight:pt,delayed:0,processed:Ft,oldestSec:0,concurrency:ee.concurrency??y?.queueConcurrency??"—",tries:y?.queueTries??3,visTimeout:(y?.queueTimeout??120)*6,dlq:ie})}if(he.length)I.queues=he;if(ye.length)I.queuesDetail=ye;I.dlqItems=[]}catch{}try{let te=new h(a),{Stacks:he}=await te.describeStacks({stackName:sr(e,t)}),ye={};for(let ie of he?.[0]?.Outputs??[])if(ie.OutputKey)ye[ie.OutputKey]=ie.OutputValue??"";if(y?.database?.connection==="aurora-serverless"){let ie=`${r.slug}-${t}-db`,xe=[{Name:"DBClusterIdentifier",Value:ie}],[ee,De]=await Promise.all([gc(u,"AWS/RDS","ServerlessDatabaseCapacity",xe,"Average",w,b),gc(u,"AWS/RDS","DatabaseConnections",xe,"Maximum",w,b)]);if(I.aurora={id:ie,engine:"aurora-mysql",minAcu:y?.database?.minCapacity??0.5,maxAcu:y?.database?.maxCapacity??4,currentAcu:ee?Number(ee.toFixed(1)):y?.database?.minCapacity??0.5,database:"app",connections:Math.round(De),status:ye.DbEndpoint?"available":"creating"},y?.rdsProxy)I.proxy={name:`${r.slug}-${t}-proxy`,endpoint:ye.DbProxyEndpoint??"—",pooledConns:Math.round(De),status:"available"}}if(y?.cache?.driver==="elasticache"){let ie=`${r.slug}-${t}-cache`,xe=[{Name:"CacheClusterId",Value:`${ie}-001`}],[ee,De]=await Promise.all([gc(u,"AWS/ElastiCache","CacheHits",xe,"Sum",w,b),gc(u,"AWS/ElastiCache","CacheMisses",xe,"Sum",w,b)]),Ge=ee+De>0?Number((ee/(ee+De)*100).toFixed(1)):0;I.redis={id:ie,node:"cache.t4g.micro",engine:"redis",hitRate:Ge,status:ye.CacheEndpoint?"available":"creating"}}if(y?.efs){let ie=0;try{if(ye.EfsFileSystemId){let xe=new vr(a),{FileSystems:ee}=await xe.describeFileSystems({FileSystemId:ye.EfsFileSystemId});ie=Number(((ee?.[0]?.SizeInBytes?.Value??0)/1048576).toFixed(1))}}catch{}I.efs={id:ye.EfsFileSystemId??"efs",mount:"/mnt/local",sizeMb:ie,status:"available"}}I.assetsInfo=ye.AssetsCdnDomain?{bucket:ye.AssetsBucketName??`${r.slug}-${t}-assets`,cdn:ye.AssetsCdnDomain,customDomain:y?.assetDomain??"—",assetUrl:r.assetUrl??"—",files:0,sizeMb:0,cacheHitPct:0,build:I.app.build}:void 0}catch{}if(I.assetsInfo)try{let he=await new o(a).list({bucket:I.assetsInfo.bucket,maxKeys:1000});I.assetsInfo.files=he.length,I.assetsInfo.sizeMb=Number((he.reduce((ye,ie)=>ye+(ie.Size??0),0)/1048576).toFixed(1)),I.assetsRecent=he.slice(0,8).map((ye)=>({path:`/${ye.Key}`,size:`${Math.max(1,Math.round((ye.Size??0)/1024))} KB`,type:ye.Key.split(".").pop()??""}))}catch{}try{if(y?.secrets){let te=Array.isArray(y.secrets)?y.secrets.map((he)=>({key:he.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),source:he})):Object.entries(y.secrets).map(([he,ye])=>({key:he,source:String(ye)}));I.secretsList=te.map((he)=>({...he,updated:"—"}))}}catch{}try{let te=new o(a),he=`${r.slug}-${t}-deployments`,ye=await te.getObjectJson(he,`deployments/${r.slug}/${t}/history.json`).catch(()=>null);if(ye?.records?.length)I.deploymentsDetail=ye.records.slice(-12).reverse().map((ie)=>({sha:(ie.sha??"").slice(0,7),status:ie.status??"success",when:ie.timestamp??"—",took:ie.took??"—",by:ie.by??"—",version:ie.version??"—",hooks:ie.hooks??[]}))}catch{}I.metricsTotals={invocations:I.metrics.invocations,errors:Math.round(D),errorRatePct:Z,p95Ms:I.metrics.p95Ms,throttles:z.reduce((te,he)=>te+he.throttles,0),coldStartPct:void 0,estCostUsd:void 0,concurrency:oe},I.metricsPerFn=z.map((te)=>({key:te.key,invocations:te.invocations,errors:te.errors,throttles:te.throttles,avgMs:te.p50,maxMs:te.p99,costUsd:void 0}));try{I.invSpark=await u.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:r.functions.find((te)=>te.mode==="http")?.name??""}],StartTime:new Date(b.getTime()-86400000),EndTime:b,Period:3600,Stat:"Sum"})}catch{}try{let te=new Ps,he=b,ye=new Date(Date.UTC(he.getUTCFullYear(),he.getUTCMonth(),1)),ie=new Date(Date.UTC(he.getUTCFullYear(),he.getUTCMonth()-1,1)),[xe,ee]=await Promise.all([te.getCostByService({start:Ds(ye),end:Ds(he),granularity:"MONTHLY"}).catch(()=>[]),te.getCostByService({start:Ds(ie),end:Ds(ye),granularity:"MONTHLY"}).catch(()=>[])]);if(xe.length){let De=xe.reduce((rt,W)=>rt+W.amount,0),Ge=ee.reduce((rt,W)=>rt+W.amount,0),pt=he.getUTCDate(),Ft=new Date(Date.UTC(he.getUTCFullYear(),he.getUTCMonth()+1,0)).getUTCDate();I.costSummary={monthToDateUsd:Number(De.toFixed(2)),projectedUsd:Number((De/pt*Ft).toFixed(2)),lastMonthUsd:Number(Ge.toFixed(2)),dailyAvgUsd:Number((De/pt).toFixed(2))},I.costServices=xe.filter((rt)=>rt.amount>0).sort((rt,W)=>W.amount-rt.amount).slice(0,12).map((rt)=>({name:rt.service,usd:Number(rt.amount.toFixed(2)),note:""})),I.metrics.estCostUsd=Number((De/pt).toFixed(2)),I.metricsTotals.estCostUsd=I.metrics.estCostUsd,I.costTrend=await te.getDailyTotals({start:Ds(ye),end:Ds(he)}).catch(()=>[]);let Ze=xe.find((rt)=>/lambda/i.test(rt.service))?.amount??0,wt=(rt)=>rt.invocations*(rt.p50/1000)*(rt.memory/1024),zt=z.reduce((rt,W)=>rt+wt(W),0)||1;I.costPerFn=z.map((rt)=>({key:rt.key,requests:rt.invocations,gbSec:Math.round(wt(rt)),usd:Number((Ze*(wt(rt)/zt)).toFixed(2))}))}}catch{}if(y?.firewall)try{let te=await u.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"BlockedRequests",StartTime:w,EndTime:b,Period:86400,Statistics:["Sum"]}).catch(()=>[]),he=await u.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"AllowedRequests",StartTime:w,EndTime:b,Period:86400,Statistics:["Sum"]}).catch(()=>[]);I.waf={enabled:!0,scope:"REGIONAL",acl:`${r.slug}-${t}-waf`,allowed24h:Math.round(he.reduce((ye,ie)=>ye+(ie.Sum??0),0)),blocked24h:Math.round(te.reduce((ye,ie)=>ye+(ie.Sum??0),0))};try{let ye=new xg(a),ie=await ye.listWebACLs("REGIONAL"),xe=ie.find((ee)=>ee.Name?.includes(`${r.slug}-${t}`))??ie[0];if(xe?.Name&&xe.Id){I.waf.acl=xe.Name;let ee=await ye.getWebACLRules(xe.Name,xe.Id,"REGIONAL");if(ee.length)I.wafRules=ee.map((De)=>({name:De.Name??"—",detail:`priority ${De.Priority??0}`,action:De.Action??"count",blocked24h:0}))}}catch{}}catch{}let G=[];if(I.aurora)G.push({name:"Aurora Serverless v2",detail:`${I.aurora.id} · ${I.aurora.minAcu}-${I.aurora.maxAcu} ACU`,status:I.aurora.status});if(I.proxy)G.push({name:"RDS Proxy",detail:I.proxy.name,status:I.proxy.status});if(I.redis)G.push({name:`ElastiCache (${I.redis.engine})`,detail:`${I.redis.node} · ${I.redis.hitRate}% hit rate`,status:I.redis.status});if(I.efs)G.push({name:"EFS",detail:`${I.efs.mount} · ${I.efs.sizeMb} MB`,status:I.efs.status});if(G.length)I.dataServices=G;if(r.scheduler!=="off"&&y?.kind==="php")try{let te=await ct(e,t,"schedule:list"),he=[];for(let ye of(te||"").split(`
181
181
  `)){let ie=/^\s*([\d*/,\-\s]+?)\s{2,}(.+?)(?:\s{2,}Next Due.*)?$/.exec(ye);if(ie&&/[*\d]/.test(ie[1])&&ie[1].trim().split(/\s+/).length===5)he.push({command:ie[2].trim().replace(/^php artisan /,""),cron:ie[1].trim(),desc:"",lastRun:"—",lastStatus:"ok"})}if(he.length)I.schedulerTasks=he}catch{}return I.topology=hs(I,{project:e.project.name,environment:t}),I}function Hi(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:null}function aC(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return null;let t=Date.parse(`${e}T12:00:00.000Z`);return Number.isFinite(t)?new Date(t).toISOString():null}function eg(e,t){if(!e||typeof e!=="object")return[];let r={source:t.name},a=[],u=t.now,m=(y,I,A,D=u)=>{if(I!==null)a.push({name:y,value:I,unit:A,timestamp:D,attributes:r})};m("storage.egress.month",Hi(e.monthBytes),"bytes"),m("storage.egress.today",Hi(e.todayBytes),"bytes"),m("storage.egress.projected_month",Hi(e.projectedMonthBytes),"bytes");let f=Hi(e.budgetBytes);if(f!==null&&f>0){m("storage.egress.budget",f,"bytes");let y=e.budgetUsedPercent,I=typeof y==="number"&&Number.isFinite(y)?y:Hi(e.monthBytes)!==null?Math.round(Hi(e.monthBytes)/f*1000)/10:null;m("storage.egress.budget_used_percent",I,"percent")}let b=t.maxReplayDays??45,w=Array.isArray(e.days)?e.days.slice(-b):[];for(let y of w){let I=aC(String(y?.date??"")),A=Hi(y?.bytes);if(!I||A===null)continue;a.push({name:"storage.egress.day",value:A,unit:"bytes",timestamp:I,attributes:r});let D=Hi(y?.downloads);if(D!==null)a.push({name:"storage.egress.day_downloads",value:D,unit:"count",timestamp:I,attributes:r})}return a}async function tg(e,t=process.env,r=fetch){let a=e.tokenEnv?t[e.tokenEnv]:void 0,u=await r(e.url,{headers:a?{Authorization:`Bearer ${a}`}:{},signal:AbortSignal.timeout(1e4)});if(!u.ok)throw Error(`HTTP ${u.status}`);return await u.json()}async function Ga(e,t){let r=[],a=[];if(!Array.isArray(e)||e.length===0)return{metrics:r,errors:a};let u=await Promise.all(e.map(async(m)=>{if(!m?.name||!m?.url)return{endpoint:m,error:"egress endpoint needs both a name and a url"};try{let f=await tg(m,t.env,t.fetchImpl);return{endpoint:m,report:f}}catch(f){return{endpoint:m,error:f instanceof Error?f.message:String(f)}}}));for(let m of u){let f=`egress:${m.endpoint?.name??"unnamed"}`;if("error"in m&&m.error){a.push({source:f,message:m.error});continue}r.push(...eg(m.report,{name:m.endpoint.name,now:t.now}))}return{metrics:r,errors:a}}import{createHash as O_}from"node:crypto";import{existsSync as Si,mkdtempSync as km,readdirSync as QS,rmSync as To,statSync as aw}from"node:fs";import{readFile as ni,writeFile as Po}from"node:fs/promises";import{tmpdir as yl}from"node:os";import{dirname as $_,extname as Ic,join as Tt,normalize as N_,relative as j_,resolve as B_,sep as M_}from"node:path";import{fileURLToPath as L_}from"node:url";import{isIP as jv}from"node:net";var yt=(e)=>e==null?void 0:String(e),qd=(e)=>Number(e)===1,Ki=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}};function Bv(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),name:String(e.name),provider:String(e.provider),endpoint:yt(e.endpoint),endpointPolicy:String(e.endpoint_policy),bucket:yt(e.bucket),prefix:String(e.prefix),region:yt(e.region),forcePathStyle:qd(e.force_path_style),credentialRef:yt(e.credential_ref),encryption:String(e.encryption),encryptionKeyRef:yt(e.encryption_key_ref),immutability:Ki(e.immutability,{}),status:String(e.status),lastTestedAt:yt(e.last_tested_at),lastSuccessAt:yt(e.last_success_at),lastFailureAt:yt(e.last_failure_at),lastError:yt(e.last_error),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Og(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:yt(e.environment_id),resourceId:yt(e.resource_id),dataServiceId:yt(e.data_service_id),destinationId:String(e.destination_id),name:String(e.name),resourceKind:String(e.resource_kind),schedule:String(e.schedule),timezone:String(e.timezone),retention:Ki(e.retention,{}),compression:String(e.compression),encryption:String(e.encryption),includePatterns:Ki(e.include_patterns,[]),excludePatterns:Ki(e.exclude_patterns,[]),expectedRpoMinutes:Number(e.expected_rpo_minutes),expectedRtoMinutes:Number(e.expected_rto_minutes),healthCheckId:yt(e.health_check_id),enabled:qd(e.enabled),nextRunAt:yt(e.next_run_at),lastRunAt:yt(e.last_run_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function $g(e){return{id:String(e.id),projectId:String(e.project_id),policyId:yt(e.policy_id),destinationId:String(e.destination_id),resourceId:yt(e.resource_id),dataServiceId:yt(e.data_service_id),backupJobId:yt(e.backup_job_id),kind:String(e.kind),pointInTime:String(e.point_in_time),uri:String(e.uri),sizeBytes:Number(e.size_bytes),checksum:String(e.checksum),manifest:Ki(e.manifest,{}),toolVersion:yt(e.tool_version),engineVersion:yt(e.engine_version),expiresAt:yt(e.expires_at),lockedUntil:yt(e.locked_until),held:qd(e.held),pinned:qd(e.pinned),status:String(e.status),verificationState:String(e.verification_state),verifiedAt:yt(e.verified_at),durationMs:e.duration_ms==null?void 0:Number(e.duration_ms),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Ng(e){return{id:String(e.id),projectId:String(e.project_id),policyId:yt(e.policy_id),recoveryPointId:yt(e.recovery_point_id),operationId:yt(e.operation_id),kind:String(e.kind),status:String(e.status),idempotencyKey:String(e.idempotency_key),target:Ki(e.target,{}),restoreMode:yt(e.restore_mode),cancellability:String(e.cancellability),safetyBackupId:yt(e.safety_backup_id),healthResult:e.health_result?Ki(e.health_result,{}):void 0,progress:Ki(e.progress,{}),error:yt(e.error),startedAt:yt(e.started_at),finishedAt:yt(e.finished_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function cC(e){let t=e.toLowerCase();if(t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal"))return!0;if(jv(t)===6)return t==="::1"||t.startsWith("fe80:");if(jv(t)!==4)return!1;let[r,a]=t.split(".").map(Number);return r===10||r===127||r===0||r===169&&a===254||r===172&&a>=16&&a<=31||r===192&&a===168}function ch(e){if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(e.name))throw Error("Backup destination names must be 2-63 lowercase letters, numbers, or dashes.");if(e.provider!=="aws_backup"&&!e.bucket)throw Error("S3 backup destinations require a bucket.");if(e.provider==="s3_compatible"&&!e.endpoint)throw Error("S3-compatible destinations require an explicit endpoint.");if(e.provider==="s3_compatible"&&!e.credentialRef)throw Error("S3-compatible destinations require a credential reference.");if(e.encryption!=="provider"&&!e.encryptionKeyRef)throw Error("Client-side encryption requires an encryption key reference.");if(e.endpoint){let t=new URL(e.endpoint);if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw Error("Backup endpoints must be origin-only HTTPS URLs without credentials, paths, queries, or fragments.");if(cC(t.hostname)&&e.endpointPolicy!=="allow_private")throw Error("Private backup endpoints require endpointPolicy allow_private.")}}class Va{controlPlane;now;constructor(e,t=()=>new Date){this.controlPlane=e;this.now=t}createDestination(e){ch(e);let t=crypto.randomUUID(),r=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO backup_destinations (id,organization_id,project_id,name,provider,endpoint,endpoint_policy,bucket,prefix,region,force_path_style,credential_ref,encryption,encryption_key_ref,immutability,status,last_tested_at,last_success_at,last_failure_at,last_error,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.projectId,e.name,e.provider,e.endpoint??null,e.endpointPolicy,e.bucket??null,e.prefix,e.region??null,e.forcePathStyle?1:0,e.credentialRef??null,e.encryption,e.encryptionKeyRef??null,JSON.stringify(e.immutability),e.status,e.lastTestedAt??null,e.lastSuccessAt??null,e.lastFailureAt??null,e.lastError??null,1,r,r]),this.getDestination(t)}getDestination(e){let t=this.controlPlane.database.query("SELECT * FROM backup_destinations WHERE id=?").get(e);return t?Bv(t):void 0}listDestinations(e){return this.controlPlane.database.query("SELECT * FROM backup_destinations WHERE project_id=? ORDER BY name").all(e).map(Bv)}recordDestinationTest(e,t){let r=this.now().toISOString();return this.controlPlane.database.run("UPDATE backup_destinations SET status=?,last_tested_at=?,last_success_at=CASE WHEN ? THEN ? ELSE last_success_at END,last_failure_at=CASE WHEN ? THEN last_failure_at ELSE ? END,last_error=?,version=version+1,updated_at=? WHERE id=?",[t.ok?"healthy":"failing",r,t.ok?1:0,r,t.ok?1:0,r,t.ok?null:String(t.error??"Destination test failed.").slice(0,1000),r,e]),this.getDestination(e)}createPolicy(e){if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(e.name))throw Error("Backup policy names must be lowercase slugs.");if(!e.resourceId&&!e.dataServiceId&&!["control_plane","infrastructure"].includes(e.resourceKind))throw Error("A backup policy requires a resource or data service target.");let t=this.getDestination(e.destinationId);if(!t||t.projectId!==e.projectId)throw Error("Backup destination was not found.");if(e.resourceKind==="control_plane"&&t.encryption==="provider")throw Error("Control-plane backups require client-side destination encryption.");if(["logical_database","volume","files","control_plane"].includes(e.resourceKind)&&t.provider==="aws_backup")throw Error(`${e.resourceKind} backups require an object-storage destination.`);if(e.resourceKind==="infrastructure"&&t.provider!=="aws_backup")throw Error("Infrastructure backups require an AWS Backup destination.");let r=at(e.schedule),a=Ot(r.normalized,e.timezone,this.now(),1)[0],u=crypto.randomUUID(),m=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO backup_policies (id,organization_id,project_id,environment_id,resource_id,data_service_id,destination_id,name,resource_kind,schedule,timezone,retention,compression,encryption,include_patterns,exclude_patterns,expected_rpo_minutes,expected_rto_minutes,health_check_id,enabled,next_run_at,last_run_at,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[u,e.organizationId,e.projectId,e.environmentId??null,e.resourceId??null,e.dataServiceId??null,e.destinationId,e.name,e.resourceKind,r.normalized,e.timezone,JSON.stringify(e.retention),e.compression,e.encryption,JSON.stringify(e.includePatterns),JSON.stringify(e.excludePatterns),e.expectedRpoMinutes,e.expectedRtoMinutes,e.healthCheckId??null,e.enabled?1:0,a,e.lastRunAt??null,1,m,m]),this.getPolicy(u)}getPolicy(e){let t=this.controlPlane.database.query("SELECT * FROM backup_policies WHERE id=?").get(e);return t?Og(t):void 0}listPolicies(e,t){return this.controlPlane.database.query(`SELECT * FROM backup_policies WHERE project_id=?${t?" AND environment_id=?":""} ORDER BY name`).all(e,...t?[t]:[]).map(Og)}duePolicies(e=this.now()){return this.controlPlane.database.query("SELECT * FROM backup_policies WHERE enabled=1 AND next_run_at<=? ORDER BY next_run_at,id").all(e.toISOString()).map(Og)}advancePolicy(e,t){let r=this.getPolicy(e);if(!r)throw Error("Backup policy was not found.");let a=Ot(r.schedule,r.timezone,new Date(t),1)[0];return this.controlPlane.database.run("UPDATE backup_policies SET last_run_at=?,next_run_at=?,version=version+1,updated_at=? WHERE id=?",[t,a,this.now().toISOString(),e]),this.getPolicy(e)}createJob(e){let t=this.controlPlane.database.query("SELECT * FROM backup_jobs WHERE idempotency_key=?").get(e.idempotencyKey);if(t)return Ng(t);let r=crypto.randomUUID(),a=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO backup_jobs (id,project_id,policy_id,recovery_point_id,operation_id,kind,status,idempotency_key,target,restore_mode,cancellability,safety_backup_id,health_result,progress,error,started_at,finished_at,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.projectId,e.policyId??null,e.recoveryPointId??null,e.operationId??null,e.kind,e.status,e.idempotencyKey,JSON.stringify(e.target),e.restoreMode??null,e.cancellability,e.safetyBackupId??null,e.healthResult?JSON.stringify(e.healthResult):null,JSON.stringify(e.progress),e.error??null,e.startedAt??null,e.finishedAt??null,a,a]),this.getJob(r)}getJob(e){let t=this.controlPlane.database.query("SELECT * FROM backup_jobs WHERE id=?").get(e);return t?Ng(t):void 0}listJobs(e){return this.controlPlane.database.query("SELECT * FROM backup_jobs WHERE project_id=? ORDER BY created_at DESC").all(e).map(Ng)}updateJob(e,t){let r=this.getJob(e);if(!r)throw Error("Backup job was not found.");let a={...r,...t};return this.controlPlane.database.run("UPDATE backup_jobs SET status=?,operation_id=?,recovery_point_id=?,progress=?,health_result=?,error=?,started_at=?,finished_at=?,safety_backup_id=?,updated_at=? WHERE id=?",[a.status,a.operationId??null,a.recoveryPointId??null,JSON.stringify(a.progress),a.healthResult?JSON.stringify(a.healthResult):null,a.error??null,a.startedAt??null,a.finishedAt??null,a.safetyBackupId??null,this.now().toISOString(),e]),this.getJob(e)}createRecoveryPoint(e){if(!/^sha256:[a-f0-9]{64}$/i.test(e.checksum))throw Error("Recovery points require a SHA-256 checksum.");if(typeof e.uri!=="string"||!["s3:","aws-backup:","file:"].some((a)=>e.uri.startsWith(a)))throw Error("Recovery point URI uses an unsupported destination scheme.");let t=crypto.randomUUID(),r=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO recovery_points (id,project_id,policy_id,destination_id,resource_id,data_service_id,backup_job_id,kind,point_in_time,uri,size_bytes,checksum,manifest,tool_version,engine_version,expires_at,locked_until,held,pinned,status,verification_state,verified_at,duration_ms,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.projectId,e.policyId??null,e.destinationId,e.resourceId??null,e.dataServiceId??null,e.backupJobId??null,e.kind,e.pointInTime,e.uri,e.sizeBytes,e.checksum,JSON.stringify(e.manifest),e.toolVersion??null,e.engineVersion??null,e.expiresAt??null,e.lockedUntil??null,e.held?1:0,e.pinned?1:0,e.status,e.verificationState,e.verifiedAt??null,e.durationMs??null,r,r]),this.getRecoveryPoint(t)}getRecoveryPoint(e){let t=this.controlPlane.database.query("SELECT * FROM recovery_points WHERE id=?").get(e);return t?$g(t):void 0}listRecoveryPoints(e,t){return this.controlPlane.database.query(`SELECT * FROM recovery_points WHERE project_id=?${t?" AND policy_id=?":""} ORDER BY point_in_time DESC`).all(e,...t?[t]:[]).map($g)}updateRecoveryPoint(e,t){let r=this.getRecoveryPoint(e);if(!r)throw Error("Recovery point was not found.");let a={...r,...t};return this.controlPlane.database.run("UPDATE recovery_points SET status=?,verification_state=?,verified_at=?,held=?,pinned=?,manifest=?,duration_ms=?,updated_at=? WHERE id=?",[a.status,a.verificationState,a.verifiedAt??null,a.held?1:0,a.pinned?1:0,JSON.stringify(a.manifest),a.durationMs??null,this.now().toISOString(),e]),this.getRecoveryPoint(e)}retentionCandidates(e=this.now()){let t=this.controlPlane.database.query(`SELECT rp.* FROM recovery_points rp
182
182
  WHERE rp.status='available' AND rp.held=0 AND rp.pinned=0
@@ -1,4 +1,4 @@
1
- import{Q,l}from"./chunk-18h7na1g.js";import{nn}from"./chunk-3ncnrrvm.js";var Ke=40,ad=[{version:1,name:"core_control_plane",sql:`
1
+ import{Q,l}from"./chunk-prtvb2fh.js";import{nn}from"./chunk-3ncnrrvm.js";var Ke=40,ad=[{version:1,name:"core_control_plane",sql:`
2
2
  CREATE TABLE projects (
3
3
  id TEXT PRIMARY KEY,
4
4
  slug TEXT NOT NULL UNIQUE,