@stacksjs/ts-cloud 0.16.94 → 0.16.96

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 (67) hide show
  1. package/dist/bin/{chunk-d892pf66.js → chunk-18c0bsep.js} +131 -120
  2. package/dist/bin/{chunk-x9pqayv4.js → chunk-s2hqcbeq.js} +1 -1
  3. package/dist/bin/{chunk-1g2bnvz2.js → chunk-zbxfpe5p.js} +1 -1
  4. package/dist/bin/cli.js +5 -5
  5. package/dist/bin/dashboard-server.js +1 -1
  6. package/dist/{chunk-bxn4n4qa.js → chunk-jcxm737x.js} +1 -1
  7. package/dist/{chunk-71p77ycz.js → chunk-ybhjh309.js} +119 -108
  8. package/dist/deploy/index.js +1 -1
  9. package/dist/drivers/index.js +1 -1
  10. package/dist/drivers/shared/compute-storage.d.ts +1 -0
  11. package/dist/drivers/shared/persistent-storage-agent.d.ts +3 -0
  12. package/dist/index.js +1 -1
  13. package/dist/ui/404.html +1 -1
  14. package/dist/ui/accept-invitation.html +1 -1
  15. package/dist/ui/access-denied.html +1 -1
  16. package/dist/ui/account/automation.html +5 -5
  17. package/dist/ui/account/security.html +2 -2
  18. package/dist/ui/applications/compose.html +6 -6
  19. package/dist/ui/applications/new.html +2 -2
  20. package/dist/ui/data/backups.html +6 -6
  21. package/dist/ui/data/services.html +6 -6
  22. package/dist/ui/data/volumes.html +6 -6
  23. package/dist/ui/index.html +6 -6
  24. package/dist/ui/infrastructure/topology.html +5 -5
  25. package/dist/ui/integrations.html +2 -2
  26. package/dist/ui/operations/alerts.html +6 -6
  27. package/dist/ui/operations/configuration.html +6 -6
  28. package/dist/ui/operations/jobs.html +5 -5
  29. package/dist/ui/operations/maintenance.html +6 -6
  30. package/dist/ui/operations/observability.html +6 -6
  31. package/dist/ui/operations/previews.html +5 -5
  32. package/dist/ui/operations/queue.html +6 -6
  33. package/dist/ui/operations/regions.html +6 -6
  34. package/dist/ui/operations/releases.html +5 -5
  35. package/dist/ui/operations/spend.html +5 -5
  36. package/dist/ui/operations/workloads.html +5 -5
  37. package/dist/ui/security.html +2 -2
  38. package/dist/ui/server/actions.html +6 -6
  39. package/dist/ui/server/activity.html +1 -1
  40. package/dist/ui/server/capacity.html +6 -6
  41. package/dist/ui/server/database.html +5 -5
  42. package/dist/ui/server/deployments.html +5 -5
  43. package/dist/ui/server/diagnostics.html +2 -2
  44. package/dist/ui/server/firewall.html +6 -6
  45. package/dist/ui/server/fleet.html +6 -6
  46. package/dist/ui/server/logs.html +6 -6
  47. package/dist/ui/server/metrics.html +5 -5
  48. package/dist/ui/server/security.html +2 -2
  49. package/dist/ui/server/services.html +1 -1
  50. package/dist/ui/server/sites.html +6 -6
  51. package/dist/ui/server/ssh-keys.html +6 -6
  52. package/dist/ui/server/team.html +6 -6
  53. package/dist/ui/server/terminal.html +2 -2
  54. package/dist/ui/serverless/alarms.html +6 -6
  55. package/dist/ui/serverless/assets.html +2 -2
  56. package/dist/ui/serverless/cost.html +2 -2
  57. package/dist/ui/serverless/data.html +6 -6
  58. package/dist/ui/serverless/deployments.html +1 -1
  59. package/dist/ui/serverless/firewall.html +1 -1
  60. package/dist/ui/serverless/functions.html +6 -6
  61. package/dist/ui/serverless/logs.html +6 -6
  62. package/dist/ui/serverless/metrics.html +2 -2
  63. package/dist/ui/serverless/queues.html +6 -6
  64. package/dist/ui/serverless/secrets.html +6 -6
  65. package/dist/ui/serverless/traces.html +6 -6
  66. package/dist/ui/serverless.html +6 -6
  67. package/package.json +3 -3
@@ -1,4 +1,4 @@
1
- import{pl,H,l,fl,J,p,ge,m,ur,yl,es,Xo,Cl,Tl,wl,zl,hn,ds,yr,Kl,Wl,tu,ru}from"./chunk-316cbffs.js";import{Te,ir,O,sr,s,Fi,wo,Xr,_d,Ld,ue,c,Po,et,Yr,$d,No,Md,Zr,Bo,or,en,Hi,dr,ji,zi,tt,lr,sl,ol,Wi,Ji,kt,qo,i,Xi,zo,Ko}from"./chunk-n6tgqd7d.js";import{n}from"./chunk-vaczx33v.js";import{Be}from"./chunk-kken64a9.js";import{ke,Tr,Vs,pt,ie,ye,w,Ne,Dr,Se,ft,kr}from"./chunk-4bysqvjh.js";import{o}from"./chunk-byt4re1c.js";import{y}from"./chunk-cjqw4ns4.js";import{Le}from"./chunk-93xknw91.js";import{b}from"./chunk-4afz3x6w.js";import{je}from"./chunk-7y1pknej.js";import{se}from"./chunk-sp0ne2ax.js";import{u,yt,oo,Ke,$r,jg,er,zg,Kg,Yc,Je,Ct,fi,U,rr,qr}from"./chunk-71p77ycz.js";import{Q,d}from"./chunk-zpkf2jt2.js";import{Un}from"./chunk-z1087cap.js";import{Qn,Ng,Fs,M,P,Us,Bg}from"./chunk-stqg97mh.js";import{existsSync as OI}from"node:fs";import{join as ey}from"node:path";import{pathToFileURL as $I}from"node:url";import{existsSync as Wm,statSync as Hm}from"fs";import{resolve as Hs}from"path";import lw from"process";import{existsSync as gw,mkdirSync as ST,readdirSync as wT,readFileSync as mw,writeFileSync as kT}from"fs";import{homedir as Do}from"os";import{dirname as RT,resolve as Zn}from"path";import ld from"process";import{existsSync as Km,statSync as Jm}from"fs";import{existsSync as Gl,mkdirSync as fw,readdirSync as hw,writeFileSync as yw}from"fs";import{homedir as Oo}from"os";import{dirname as Gm,resolve as Vr}from"path";import ro from"process";import{join as vw,relative as bw,resolve as Qm}from"path";import Qc from"process";import{existsSync as Bf,mkdirSync as NT,readdirSync as jT,writeFileSync as BT}from"fs";import{homedir as Rl}from"os";import{dirname as FT,resolve as Ur}from"path";import Js from"process";import{join as Sw,relative as ww,resolve as Ym}from"path";import Zc from"process";import{existsSync as Mf,mkdirSync as WT,readdirSync as HT,writeFileSync as KT}from"fs";import{dirname as GT,resolve as Xc}from"path";import Ql from"process";import{Buffer as Ci}from"buffer";import{createCipheriv as kw,createDecipheriv as Iw,randomBytes as Al}from"crypto";import{closeSync as Pl,createReadStream as Zm,createWriteStream as Ew,existsSync as _l,fsyncSync as Xm,openSync as ef,writeFileSync as Rw}from"fs";import{access as Aw,constants as tf,mkdir as Cw,readdir as xc,rename as rf,stat as $o,unlink as Dc,writeFile as xl}from"fs/promises";import{join as jo}from"path";import Pr from"process";import{pipeline as Pw}from"stream/promises";import{createGzip as nf}from"zlib";import Mo from"process";import di from"process";import{Buffer as ai}from"buffer";import{createCipheriv as _w,createDecipheriv as Tw,randomBytes as Dl}from"crypto";import{closeSync as Ol,createReadStream as of,createWriteStream as xw,existsSync as Oc,fsyncSync as sf,openSync as af,writeFileSync as Dw}from"fs";import{access as Ow,constants as cf,mkdir as $w,readdir as $c,rename as df,stat as Lo,unlink as Nc,writeFile as $l}from"fs/promises";import{isAbsolute as Nw,join as Fo,resolve as jw}from"path";import At from"process";import{pipeline as Bw}from"stream/promises";import{createGzip as lf}from"zlib";import Uo from"process";import li from"process";import jc from"process";import{existsSync as Bc}from"fs";import{resolve as Nl}from"path";import{existsSync as Mw}from"fs";import{existsSync as Lw,readdirSync as Fw}from"fs";import{extname as jl,resolve as uf}from"path";import zw from"process";import{join as Uw,relative as qw,resolve as pf}from"path";import ed from"process";import{Buffer as ci}from"buffer";import{createCipheriv as Vw,createDecipheriv as Ww,randomBytes as Bl}from"crypto";import{closeSync as Ml,createReadStream as gf,createWriteStream as Hw,existsSync as Mc,fsyncSync as mf,openSync as ff,writeFileSync as Kw}from"fs";import{access as Jw,constants as hf,mkdir as Gw,readdir as Lc,rename as yf,stat as Vo,unlink as Fc,writeFile as Ll}from"fs/promises";import{isAbsolute as Qw,join as Wo,resolve as Yw}from"path";import Pt from"process";import{pipeline as Zw}from"stream/promises";import{createGzip as vf}from"zlib";import Ho from"process";import ui from"process";import Uc from"process";import{existsSync as qc}from"fs";import{resolve as Df}from"path";import{existsSync as TI}from"fs";class Of{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 g=this.generateKey(e,r),f=a??this.options.ttl,h=this.estimateSize(t);this.cache.set(g,{value:t,timestamp:new Date,ttl:f,hits:0,size:h}),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(!Wm(e))return!0;return Hm(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 g=Wm(r)?Hm(r):null,f=g?g.mtime:new Date;this.set(e,{value:t,fileTimestamp:f},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,g)=>a+g.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 $f{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),g=new Date;try{let f=await t(),h=performance.now()-a;return this.recordMetric({operation:e,duration:h,timestamp:g,...r}),f}catch(f){let h=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:h,timestamp:g,...r}),f}}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((g)=>g.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((g)=>g.duration),a=r.reduce((g,f)=>g+f,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 Gc=new Of,du=new $f;var Nf=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function jf(e={}){let{name:t="",alias:r}=e,a=["config",".config"];if(t)a.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let g=r===void 0?[]:Array.isArray(r)?r:[r];for(let f of g){if(!f)continue;if(a.push(f,`.${f}.config`,`${f}.config`,`.${f}`),t)a.push(`${t}.${f}.config`,`.${t}.${f}.config`)}return Array.from(new Set(a.filter(Boolean)))}function uw(e){return jf(e).flatMap((r)=>Nf.map((a)=>Hs(e.directory,`${r}${a}`)))}function pw(e={}){let t=Hs(e.cwd||lw.cwd());return Array.from(new Set([t,Hs(t,"config"),Hs(t,".config"),e.configDir?Hs(t,e.configDir):void 0].filter((r)=>Boolean(r))))}var Xw=Object.defineProperty,ek=(e)=>e;function tk(e,t){this[e]=ek.bind(null,t)}var rk=(e,t)=>{for(var r in t)Xw(e,r,{get:t[r],enumerable:!0,configurable:!0,set:tk.bind(t,r)})},nk=(e,t)=>()=>(e&&(t=e(e=0)),t),Lf={};rk(Lf,{withErrorRecovery:()=>Uf,tryLoadConfig:()=>Ak,loadConfigWithResult:()=>Ek,loadConfig:()=>Kf,isRetryableError:()=>vk,isConfigNotFoundError:()=>yk,isBunfigError:()=>qf,globalPerformanceMonitor:()=>Ys,globalCache:()=>Jo,getEnvOrDefault:()=>bk,generateConfigTypes:()=>Ck,defaultGeneratedDir:()=>th,defaultConfigDir:()=>eh,deepMergeWithArrayStrategy:()=>tp,deepMerge:()=>Vf,createLibraryConfig:()=>Pk,config:()=>Rk,bunfigPlugin:()=>_k,applyEnvVarsToConfig:()=>Ks,TypeGenerationError:()=>ou,SchemaValidationError:()=>Qs,PluginError:()=>au,PerformanceMonitor:()=>uu,FileSystemError:()=>iu,ErrorFactory:()=>Pi,EnvVarError:()=>sd,EnvProcessor:()=>ud,ConfigValidator:()=>rp,ConfigValidationError:()=>eu,ConfigNotFoundError:()=>od,ConfigMergeError:()=>nu,ConfigLoader:()=>np,ConfigLoadError:()=>Gs,ConfigFileLoader:()=>pd,ConfigCache:()=>lu,CacheUtils:()=>Gf,BunfigError:()=>cn,BrowserConfigError:()=>su,ArrayMergeStrategies:()=>Zf});class lu{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 g=this.generateKey(e,r),f=a??this.options.ttl,h=this.estimateSize(t);this.cache.set(g,{value:t,timestamp:new Date,ttl:f,hits:0,size:h}),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(!Km(e))return!0;return Jm(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 g=Km(r)?Jm(r):null,f=g?g.mtime:new Date;this.set(e,{value:t,fileTimestamp:f},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,g)=>a+g.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 uu{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),g=new Date;try{let f=await t(),h=performance.now()-a;return this.recordMetric({operation:e,duration:h,timestamp:g,...r}),f}catch(f){let h=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:h,timestamp:g,...r}),f}}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((g)=>g.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((g)=>g.duration),a=r.reduce((g,f)=>g+f,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 ik(e,t={}){let a=Object.keys(t).sort().map((g)=>`${g}:${t[g]}`).join("|");return a?`${e}:${a}`:e}function ok(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function sk(e){return e.getStats().size*2}function gu(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&qt(t[0])&&"id"in t[0]&&t[0].id===3&&qt(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(qt(t)&&qt(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(qt(e)&&"arr"in e&&Array.isArray(e.arr)&&qt(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&qt(t[0])&&qt(e[0])){let a=[...t];for(let g of e)if(qt(g)&&"name"in g){if(!a.find((h)=>qt(h)&&("name"in h)&&h.name===g.name))a.push(g)}else if(qt(g)&&"path"in g){if(!a.find((h)=>qt(h)&&("path"in h)&&h.path===g.path))a.push(g)}else if(!a.some((f)=>td(f,g)))a.push(g);return a}if(t.every((a)=>typeof a==="string")&&e.every((a)=>typeof a==="string")){let a=[...t];for(let g of e)if(!a.includes(g))a.push(g);return a}return t}if(!qt(t)||!qt(e))return t;let r={...e};for(let a in t)if(Object.prototype.hasOwnProperty.call(t,a)){let g=t[a];if(g===null||g===void 0)continue;else if(qt(g)&&qt(r[a]))r[a]=gu(r[a],g);else if(Array.isArray(g)&&Array.isArray(r[a]))if(g.length>0&&r[a].length>0&&qt(g[0])&&qt(r[a][0])){let f=[...g];for(let h of r[a])if(qt(h)&&"name"in h){if(!f.find((k)=>qt(k)&&("name"in k)&&k.name===h.name))f.push(h)}else if(qt(h)&&"path"in h){if(!f.find((k)=>qt(k)&&("path"in k)&&k.path===h.path))f.push(h)}else if(!f.some((S)=>td(S,h)))f.push(h);r[a]=f}else if(g.every((f)=>typeof f==="string")&&r[a].every((f)=>typeof f==="string")){let f=[...g];for(let h of r[a])if(!f.includes(h))f.push(h);r[a]=f}else r[a]=g;else r[a]=g}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(qt(e)&&qt(t)){let r=Object.keys(e),a=Object.keys(t);if(r.length!==a.length)return!1;for(let g of r){if(!Object.prototype.hasOwnProperty.call(t,g))return!1;if(!td(e[g],t[g]))return!1}return!0}return!1}function qt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function ak(e,t){if(!Mf(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 gu(t,a)}catch{return null}}catch{return null}}async function ck({name:e="",cwd:t,defaultConfig:r}){let a=t||Ql.cwd(),g=[".ts",".js",".mjs",".cjs",".json"],f=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let h of f)for(let S of g){let k=Xc(a,`${h}${S}`),v=await ak(k,r);if(v!==null)return v}try{let h=Xc(a,"package.json");if(Mf(h)){let k=(await import(h))[e];if(k&&typeof k==="object"&&!Array.isArray(k))try{return gu(r,k)}catch{}}}catch{}return r}function dk(e,t={}){let r=Zc.cwd();while(r.includes("storage"))r=Ym(r,"..");let a=Ym(r,e||"");if(t?.relative)return ww(Zc.cwd(),a);return a}async function lk(){try{let e=await ck({name:"clarity",defaultConfig:Wc,cwd:Zc.cwd(),endpoint:"",headers:{}});return{...Wc,...e}}catch{return Wc}}function Yt(){if(di.env.NODE_ENV==="test"||di.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function uk(){if(di.env.NODE_ENV==="test"||di.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof di<"u"){let e=di.type;if(e==="renderer"||e==="worker")return!1;return!!(di.versions&&(di.versions.node||di.versions.bun))}return!1}class Ff{async format(e){let t=await uk(),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:Mo.pid,hostname:t(),environment:Mo.env.NODE_ENV||"development",platform:Mo.platform,version:Mo.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Mo.env.NODE_ENV||Mo.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={...Zl},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ff,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??Pr.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 g=this.generateKeyId(),f=this.generateKey();this.currentKeyId=g,this.keys.set(g,f),this.encryptionKeys.set(g,{key:f,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Hc,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Hc};return{...Hc,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Zl.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 g,f=0,h=3,S=1000;while(f<h)try{try{try{await Aw(this.config.logDirectory,tf.F_OK|tf.W_OK)}catch(v){if(v instanceof Error&&"code"in v)if(v.code==="ENOENT")await Cw(this.config.logDirectory,{recursive:!0,mode:493});else if(v.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw v;else throw v}}catch(v){throw console.error("Debug: [writeToFile] Failed to create log directory:",v),v}let k=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Ci.from(e);try{if(!_l(this.currentLogFile))await xl(this.currentLogFile,"",{mode:420});if(g=ef(this.currentLogFile,"a",420),Rw(g,k,{flag:"a"}),Xm(g),g!==void 0)Pl(g),g=void 0;if((await $o(this.currentLogFile)).size===0){if(await xl(this.currentLogFile,k,{flag:"w",mode:420}),(await $o(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(v){let E=v;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(f<h-1){let A=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${h}:`,A);let x=S*2**f;await new Promise((D)=>setTimeout(D,x)),f++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(g!==void 0)try{Pl(g)}catch(v){console.error("Debug: [writeToFile] Error closing file descriptor:",v)}}}catch(k){if(f===h-1){let E=k,A=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),k}f++;let v=S*2**(f-1);await new Promise((E)=>setTimeout(E,v))}})();this.pendingOperations.push(r);let a=this.pendingOperations.length-1;try{await r}catch(g){throw console.error("Debug: [writeToFile] Error in operation:",g),g}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 jo(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 jo(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return jo(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Yt())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((g)=>{console.error("Error rotating keys:",g)})},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 g=Array.from(this.encryptionKeys.entries()).sort(([,S],[,k])=>k.createdAt.getTime()-S.createdAt.getTime()),f=typeof t.maxKeys==="number"?t.maxKeys:1,h=Math.max(1,f);if(g.length>h)for(let[S]of g.slice(h))this.encryptionKeys.delete(S),this.keys.delete(S)}generateKeyId(){return Al(16).toString("hex")}generateKey(){return Al(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=Al(16),a=kw("aes-256-gcm",t,r),g=Ci.concat([a.update(e,"utf8"),a.final()]),f=a.getAuthTag();return{encrypted:Ci.concat([r,g,f]),iv:r}}async compressData(e){return new Promise((t,r)=>{let a=nf(),g=[];a.on("data",(f)=>g.push(f)),a.on("end",()=>t(Ci.from(Ci.concat(g)))),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(Yt())return;let e=await $o(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 g=await xc(this.config.logDirectory),f=g.filter((k)=>k.startsWith(this.name)&&/\.log\.\d+$/.test(k)).sort((k,v)=>{let E=Number.parseInt(k.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(v.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),h=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,S=`${r}.${h}`;if(await $o(r).catch(()=>null))try{if(await rf(r,S),t.compress)try{let k=`${S}.gz`;await this.compressLogFile(S,k),await Dc(S)}catch(k){console.error("Error compressing rotated file:",k)}if(f.length===0&&!g.some((k)=>k.endsWith(".log.1")))try{let k=`${r}.1`;await xl(k,"")}catch(k){console.error("Error creating backup file:",k)}}catch(k){console.error(`Error during rotation: ${k instanceof Error?k.message:String(k)}`)}}else{let g=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${g}.log`);if(await $o(r).catch(()=>null))await rf(r,f)}if(this.currentLogFile=a,t.maxFiles){let f=(await xc(this.config.logDirectory)).filter((h)=>h.startsWith(this.name)).sort((h,S)=>S.localeCompare(h));for(let h of f.slice(t.maxFiles))await Dc(jo(this.config.logDirectory,h))}}}async compressLogFile(e,t){let r=Zm(e),a=Ew(t),g=nf();await Pw(r,g,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=ef(this.currentLogFile,"r+");Xm(e),Pl(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(!Yt()&&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(jo(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?Ot.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:a="",message:g,level:f,showTimestamp:h=!0}=e,S=(D)=>D.replace(this.ANSI_PATTERN,"");if(!this.fancy){let D=[];if(h)D.push(t);if(f==="warning")D.push("WARN");else if(f==="error")D.push("ERROR");else if(r)D.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(a)D.push(a.replace(/[[\]]/g,""));return D.push(g),D.join(" ")}let k=Pr.stdout.columns||120,v="";if(f==="warning"||f==="error")v=`${r} ${g}`;else if(f==="info"||f==="success")v=`${r} ${a} ${g}`;else v=`${r} ${a} ${Ot.cyan(g)}`;if(!h)return v.trim();let E=S(v).trim().length,A=S(t).length,x=Math.max(1,k-2-E-A);return`${v.trim()}${" ".repeat(x)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(f,h)=>{let S=Number.parseInt(h,10);return S<t[0].length?String(t[0][S]):f});let r=/%([sdijfo%])/g,a=0,g=e.replace(r,(f,h)=>{if(h==="%")return"%";if(a>=t.length)return f;let S=t[a++];switch(h){case"s":return String(S);case"d":case"i":return Number(S).toString();case"j":case"o":return JSON.stringify(S,null,2);default:return f}});if(a<t.length)g+=` ${t.slice(a).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return g}async log(e,t,...r){let a=new Date,g=this.formatConsoleTimestamp(a),f=this.formatFileTimestamp(a),h,S;if(t instanceof Error)h=t.message,S=t.stack;else h=this.formatMessage(t,r);if(this.fancy&&!Yt()){let v=Qf[e],E=this.options.showTags!==!1&&this.name?Ot.gray(this.formatTag(this.name)):"",A;switch(e){case"debug":A=this.formatConsoleMessage({timestamp:g,icon:v,tag:E,message:Ot.gray(h),level:e}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:g,icon:v,tag:E,message:h,level:e}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:g,icon:v,tag:E,message:Ot.green(h),level:e}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:g,icon:v,tag:E,message:h,level:e}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:g,icon:v,tag:E,message:h,level:e}),console.error(A),S){let x=S.split(`
1
+ import{pl,H,l,fl,J,p,ge,m,ur,yl,es,Xo,Cl,Tl,wl,zl,hn,ds,yr,Kl,Wl,tu,ru}from"./chunk-316cbffs.js";import{Te,ir,O,sr,s,Fi,wo,Xr,_d,Ld,ue,c,Po,et,Yr,$d,No,Md,Zr,Bo,or,en,Hi,dr,ji,zi,tt,lr,sl,ol,Wi,Ji,kt,qo,i,Xi,zo,Ko}from"./chunk-n6tgqd7d.js";import{n}from"./chunk-vaczx33v.js";import{Be}from"./chunk-kken64a9.js";import{ke,Tr,Vs,pt,ie,ye,w,Ne,Dr,Se,ft,kr}from"./chunk-4bysqvjh.js";import{o}from"./chunk-byt4re1c.js";import{y}from"./chunk-cjqw4ns4.js";import{Le}from"./chunk-93xknw91.js";import{b}from"./chunk-4afz3x6w.js";import{je}from"./chunk-7y1pknej.js";import{se}from"./chunk-sp0ne2ax.js";import{u,yt,oo,Ke,$r,jg,er,zg,Kg,Yc,Je,Ct,fi,U,rr,qr}from"./chunk-ybhjh309.js";import{Q,d}from"./chunk-zpkf2jt2.js";import{Un}from"./chunk-z1087cap.js";import{Qn,Ng,Fs,M,P,Us,Bg}from"./chunk-stqg97mh.js";import{existsSync as OI}from"node:fs";import{join as ey}from"node:path";import{pathToFileURL as $I}from"node:url";import{existsSync as Wm,statSync as Hm}from"fs";import{resolve as Hs}from"path";import lw from"process";import{existsSync as gw,mkdirSync as ST,readdirSync as wT,readFileSync as mw,writeFileSync as kT}from"fs";import{homedir as Do}from"os";import{dirname as RT,resolve as Zn}from"path";import ld from"process";import{existsSync as Km,statSync as Jm}from"fs";import{existsSync as Gl,mkdirSync as fw,readdirSync as hw,writeFileSync as yw}from"fs";import{homedir as Oo}from"os";import{dirname as Gm,resolve as Vr}from"path";import ro from"process";import{join as vw,relative as bw,resolve as Qm}from"path";import Qc from"process";import{existsSync as Bf,mkdirSync as NT,readdirSync as jT,writeFileSync as BT}from"fs";import{homedir as Rl}from"os";import{dirname as FT,resolve as Ur}from"path";import Js from"process";import{join as Sw,relative as ww,resolve as Ym}from"path";import Zc from"process";import{existsSync as Mf,mkdirSync as WT,readdirSync as HT,writeFileSync as KT}from"fs";import{dirname as GT,resolve as Xc}from"path";import Ql from"process";import{Buffer as Ci}from"buffer";import{createCipheriv as kw,createDecipheriv as Iw,randomBytes as Al}from"crypto";import{closeSync as Pl,createReadStream as Zm,createWriteStream as Ew,existsSync as _l,fsyncSync as Xm,openSync as ef,writeFileSync as Rw}from"fs";import{access as Aw,constants as tf,mkdir as Cw,readdir as xc,rename as rf,stat as $o,unlink as Dc,writeFile as xl}from"fs/promises";import{join as jo}from"path";import Pr from"process";import{pipeline as Pw}from"stream/promises";import{createGzip as nf}from"zlib";import Mo from"process";import di from"process";import{Buffer as ai}from"buffer";import{createCipheriv as _w,createDecipheriv as Tw,randomBytes as Dl}from"crypto";import{closeSync as Ol,createReadStream as of,createWriteStream as xw,existsSync as Oc,fsyncSync as sf,openSync as af,writeFileSync as Dw}from"fs";import{access as Ow,constants as cf,mkdir as $w,readdir as $c,rename as df,stat as Lo,unlink as Nc,writeFile as $l}from"fs/promises";import{isAbsolute as Nw,join as Fo,resolve as jw}from"path";import At from"process";import{pipeline as Bw}from"stream/promises";import{createGzip as lf}from"zlib";import Uo from"process";import li from"process";import jc from"process";import{existsSync as Bc}from"fs";import{resolve as Nl}from"path";import{existsSync as Mw}from"fs";import{existsSync as Lw,readdirSync as Fw}from"fs";import{extname as jl,resolve as uf}from"path";import zw from"process";import{join as Uw,relative as qw,resolve as pf}from"path";import ed from"process";import{Buffer as ci}from"buffer";import{createCipheriv as Vw,createDecipheriv as Ww,randomBytes as Bl}from"crypto";import{closeSync as Ml,createReadStream as gf,createWriteStream as Hw,existsSync as Mc,fsyncSync as mf,openSync as ff,writeFileSync as Kw}from"fs";import{access as Jw,constants as hf,mkdir as Gw,readdir as Lc,rename as yf,stat as Vo,unlink as Fc,writeFile as Ll}from"fs/promises";import{isAbsolute as Qw,join as Wo,resolve as Yw}from"path";import Pt from"process";import{pipeline as Zw}from"stream/promises";import{createGzip as vf}from"zlib";import Ho from"process";import ui from"process";import Uc from"process";import{existsSync as qc}from"fs";import{resolve as Df}from"path";import{existsSync as TI}from"fs";class Of{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 g=this.generateKey(e,r),f=a??this.options.ttl,h=this.estimateSize(t);this.cache.set(g,{value:t,timestamp:new Date,ttl:f,hits:0,size:h}),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(!Wm(e))return!0;return Hm(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 g=Wm(r)?Hm(r):null,f=g?g.mtime:new Date;this.set(e,{value:t,fileTimestamp:f},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,g)=>a+g.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 $f{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),g=new Date;try{let f=await t(),h=performance.now()-a;return this.recordMetric({operation:e,duration:h,timestamp:g,...r}),f}catch(f){let h=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:h,timestamp:g,...r}),f}}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((g)=>g.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((g)=>g.duration),a=r.reduce((g,f)=>g+f,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 Gc=new Of,du=new $f;var Nf=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function jf(e={}){let{name:t="",alias:r}=e,a=["config",".config"];if(t)a.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let g=r===void 0?[]:Array.isArray(r)?r:[r];for(let f of g){if(!f)continue;if(a.push(f,`.${f}.config`,`${f}.config`,`.${f}`),t)a.push(`${t}.${f}.config`,`.${t}.${f}.config`)}return Array.from(new Set(a.filter(Boolean)))}function uw(e){return jf(e).flatMap((r)=>Nf.map((a)=>Hs(e.directory,`${r}${a}`)))}function pw(e={}){let t=Hs(e.cwd||lw.cwd());return Array.from(new Set([t,Hs(t,"config"),Hs(t,".config"),e.configDir?Hs(t,e.configDir):void 0].filter((r)=>Boolean(r))))}var Xw=Object.defineProperty,ek=(e)=>e;function tk(e,t){this[e]=ek.bind(null,t)}var rk=(e,t)=>{for(var r in t)Xw(e,r,{get:t[r],enumerable:!0,configurable:!0,set:tk.bind(t,r)})},nk=(e,t)=>()=>(e&&(t=e(e=0)),t),Lf={};rk(Lf,{withErrorRecovery:()=>Uf,tryLoadConfig:()=>Ak,loadConfigWithResult:()=>Ek,loadConfig:()=>Kf,isRetryableError:()=>vk,isConfigNotFoundError:()=>yk,isBunfigError:()=>qf,globalPerformanceMonitor:()=>Ys,globalCache:()=>Jo,getEnvOrDefault:()=>bk,generateConfigTypes:()=>Ck,defaultGeneratedDir:()=>th,defaultConfigDir:()=>eh,deepMergeWithArrayStrategy:()=>tp,deepMerge:()=>Vf,createLibraryConfig:()=>Pk,config:()=>Rk,bunfigPlugin:()=>_k,applyEnvVarsToConfig:()=>Ks,TypeGenerationError:()=>ou,SchemaValidationError:()=>Qs,PluginError:()=>au,PerformanceMonitor:()=>uu,FileSystemError:()=>iu,ErrorFactory:()=>Pi,EnvVarError:()=>sd,EnvProcessor:()=>ud,ConfigValidator:()=>rp,ConfigValidationError:()=>eu,ConfigNotFoundError:()=>od,ConfigMergeError:()=>nu,ConfigLoader:()=>np,ConfigLoadError:()=>Gs,ConfigFileLoader:()=>pd,ConfigCache:()=>lu,CacheUtils:()=>Gf,BunfigError:()=>cn,BrowserConfigError:()=>su,ArrayMergeStrategies:()=>Zf});class lu{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 g=this.generateKey(e,r),f=a??this.options.ttl,h=this.estimateSize(t);this.cache.set(g,{value:t,timestamp:new Date,ttl:f,hits:0,size:h}),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(!Km(e))return!0;return Jm(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 g=Km(r)?Jm(r):null,f=g?g.mtime:new Date;this.set(e,{value:t,fileTimestamp:f},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,g)=>a+g.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 uu{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),g=new Date;try{let f=await t(),h=performance.now()-a;return this.recordMetric({operation:e,duration:h,timestamp:g,...r}),f}catch(f){let h=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:h,timestamp:g,...r}),f}}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((g)=>g.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((g)=>g.duration),a=r.reduce((g,f)=>g+f,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 ik(e,t={}){let a=Object.keys(t).sort().map((g)=>`${g}:${t[g]}`).join("|");return a?`${e}:${a}`:e}function ok(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function sk(e){return e.getStats().size*2}function gu(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&qt(t[0])&&"id"in t[0]&&t[0].id===3&&qt(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(qt(t)&&qt(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(qt(e)&&"arr"in e&&Array.isArray(e.arr)&&qt(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&qt(t[0])&&qt(e[0])){let a=[...t];for(let g of e)if(qt(g)&&"name"in g){if(!a.find((h)=>qt(h)&&("name"in h)&&h.name===g.name))a.push(g)}else if(qt(g)&&"path"in g){if(!a.find((h)=>qt(h)&&("path"in h)&&h.path===g.path))a.push(g)}else if(!a.some((f)=>td(f,g)))a.push(g);return a}if(t.every((a)=>typeof a==="string")&&e.every((a)=>typeof a==="string")){let a=[...t];for(let g of e)if(!a.includes(g))a.push(g);return a}return t}if(!qt(t)||!qt(e))return t;let r={...e};for(let a in t)if(Object.prototype.hasOwnProperty.call(t,a)){let g=t[a];if(g===null||g===void 0)continue;else if(qt(g)&&qt(r[a]))r[a]=gu(r[a],g);else if(Array.isArray(g)&&Array.isArray(r[a]))if(g.length>0&&r[a].length>0&&qt(g[0])&&qt(r[a][0])){let f=[...g];for(let h of r[a])if(qt(h)&&"name"in h){if(!f.find((k)=>qt(k)&&("name"in k)&&k.name===h.name))f.push(h)}else if(qt(h)&&"path"in h){if(!f.find((k)=>qt(k)&&("path"in k)&&k.path===h.path))f.push(h)}else if(!f.some((S)=>td(S,h)))f.push(h);r[a]=f}else if(g.every((f)=>typeof f==="string")&&r[a].every((f)=>typeof f==="string")){let f=[...g];for(let h of r[a])if(!f.includes(h))f.push(h);r[a]=f}else r[a]=g;else r[a]=g}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(qt(e)&&qt(t)){let r=Object.keys(e),a=Object.keys(t);if(r.length!==a.length)return!1;for(let g of r){if(!Object.prototype.hasOwnProperty.call(t,g))return!1;if(!td(e[g],t[g]))return!1}return!0}return!1}function qt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function ak(e,t){if(!Mf(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 gu(t,a)}catch{return null}}catch{return null}}async function ck({name:e="",cwd:t,defaultConfig:r}){let a=t||Ql.cwd(),g=[".ts",".js",".mjs",".cjs",".json"],f=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let h of f)for(let S of g){let k=Xc(a,`${h}${S}`),v=await ak(k,r);if(v!==null)return v}try{let h=Xc(a,"package.json");if(Mf(h)){let k=(await import(h))[e];if(k&&typeof k==="object"&&!Array.isArray(k))try{return gu(r,k)}catch{}}}catch{}return r}function dk(e,t={}){let r=Zc.cwd();while(r.includes("storage"))r=Ym(r,"..");let a=Ym(r,e||"");if(t?.relative)return ww(Zc.cwd(),a);return a}async function lk(){try{let e=await ck({name:"clarity",defaultConfig:Wc,cwd:Zc.cwd(),endpoint:"",headers:{}});return{...Wc,...e}}catch{return Wc}}function Yt(){if(di.env.NODE_ENV==="test"||di.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function uk(){if(di.env.NODE_ENV==="test"||di.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof di<"u"){let e=di.type;if(e==="renderer"||e==="worker")return!1;return!!(di.versions&&(di.versions.node||di.versions.bun))}return!1}class Ff{async format(e){let t=await uk(),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:Mo.pid,hostname:t(),environment:Mo.env.NODE_ENV||"development",platform:Mo.platform,version:Mo.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Mo.env.NODE_ENV||Mo.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={...Zl},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ff,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??Pr.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 g=this.generateKeyId(),f=this.generateKey();this.currentKeyId=g,this.keys.set(g,f),this.encryptionKeys.set(g,{key:f,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Hc,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Hc};return{...Hc,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Zl.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 g,f=0,h=3,S=1000;while(f<h)try{try{try{await Aw(this.config.logDirectory,tf.F_OK|tf.W_OK)}catch(v){if(v instanceof Error&&"code"in v)if(v.code==="ENOENT")await Cw(this.config.logDirectory,{recursive:!0,mode:493});else if(v.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw v;else throw v}}catch(v){throw console.error("Debug: [writeToFile] Failed to create log directory:",v),v}let k=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Ci.from(e);try{if(!_l(this.currentLogFile))await xl(this.currentLogFile,"",{mode:420});if(g=ef(this.currentLogFile,"a",420),Rw(g,k,{flag:"a"}),Xm(g),g!==void 0)Pl(g),g=void 0;if((await $o(this.currentLogFile)).size===0){if(await xl(this.currentLogFile,k,{flag:"w",mode:420}),(await $o(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(v){let E=v;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(f<h-1){let A=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${h}:`,A);let x=S*2**f;await new Promise((D)=>setTimeout(D,x)),f++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(g!==void 0)try{Pl(g)}catch(v){console.error("Debug: [writeToFile] Error closing file descriptor:",v)}}}catch(k){if(f===h-1){let E=k,A=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),k}f++;let v=S*2**(f-1);await new Promise((E)=>setTimeout(E,v))}})();this.pendingOperations.push(r);let a=this.pendingOperations.length-1;try{await r}catch(g){throw console.error("Debug: [writeToFile] Error in operation:",g),g}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 jo(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 jo(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return jo(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Yt())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((g)=>{console.error("Error rotating keys:",g)})},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 g=Array.from(this.encryptionKeys.entries()).sort(([,S],[,k])=>k.createdAt.getTime()-S.createdAt.getTime()),f=typeof t.maxKeys==="number"?t.maxKeys:1,h=Math.max(1,f);if(g.length>h)for(let[S]of g.slice(h))this.encryptionKeys.delete(S),this.keys.delete(S)}generateKeyId(){return Al(16).toString("hex")}generateKey(){return Al(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=Al(16),a=kw("aes-256-gcm",t,r),g=Ci.concat([a.update(e,"utf8"),a.final()]),f=a.getAuthTag();return{encrypted:Ci.concat([r,g,f]),iv:r}}async compressData(e){return new Promise((t,r)=>{let a=nf(),g=[];a.on("data",(f)=>g.push(f)),a.on("end",()=>t(Ci.from(Ci.concat(g)))),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(Yt())return;let e=await $o(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 g=await xc(this.config.logDirectory),f=g.filter((k)=>k.startsWith(this.name)&&/\.log\.\d+$/.test(k)).sort((k,v)=>{let E=Number.parseInt(k.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(v.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),h=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,S=`${r}.${h}`;if(await $o(r).catch(()=>null))try{if(await rf(r,S),t.compress)try{let k=`${S}.gz`;await this.compressLogFile(S,k),await Dc(S)}catch(k){console.error("Error compressing rotated file:",k)}if(f.length===0&&!g.some((k)=>k.endsWith(".log.1")))try{let k=`${r}.1`;await xl(k,"")}catch(k){console.error("Error creating backup file:",k)}}catch(k){console.error(`Error during rotation: ${k instanceof Error?k.message:String(k)}`)}}else{let g=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${g}.log`);if(await $o(r).catch(()=>null))await rf(r,f)}if(this.currentLogFile=a,t.maxFiles){let f=(await xc(this.config.logDirectory)).filter((h)=>h.startsWith(this.name)).sort((h,S)=>S.localeCompare(h));for(let h of f.slice(t.maxFiles))await Dc(jo(this.config.logDirectory,h))}}}async compressLogFile(e,t){let r=Zm(e),a=Ew(t),g=nf();await Pw(r,g,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=ef(this.currentLogFile,"r+");Xm(e),Pl(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(!Yt()&&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(jo(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?Ot.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:a="",message:g,level:f,showTimestamp:h=!0}=e,S=(D)=>D.replace(this.ANSI_PATTERN,"");if(!this.fancy){let D=[];if(h)D.push(t);if(f==="warning")D.push("WARN");else if(f==="error")D.push("ERROR");else if(r)D.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(a)D.push(a.replace(/[[\]]/g,""));return D.push(g),D.join(" ")}let k=Pr.stdout.columns||120,v="";if(f==="warning"||f==="error")v=`${r} ${g}`;else if(f==="info"||f==="success")v=`${r} ${a} ${g}`;else v=`${r} ${a} ${Ot.cyan(g)}`;if(!h)return v.trim();let E=S(v).trim().length,A=S(t).length,x=Math.max(1,k-2-E-A);return`${v.trim()}${" ".repeat(x)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(f,h)=>{let S=Number.parseInt(h,10);return S<t[0].length?String(t[0][S]):f});let r=/%([sdijfo%])/g,a=0,g=e.replace(r,(f,h)=>{if(h==="%")return"%";if(a>=t.length)return f;let S=t[a++];switch(h){case"s":return String(S);case"d":case"i":return Number(S).toString();case"j":case"o":return JSON.stringify(S,null,2);default:return f}});if(a<t.length)g+=` ${t.slice(a).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return g}async log(e,t,...r){let a=new Date,g=this.formatConsoleTimestamp(a),f=this.formatFileTimestamp(a),h,S;if(t instanceof Error)h=t.message,S=t.stack;else h=this.formatMessage(t,r);if(this.fancy&&!Yt()){let v=Qf[e],E=this.options.showTags!==!1&&this.name?Ot.gray(this.formatTag(this.name)):"",A;switch(e){case"debug":A=this.formatConsoleMessage({timestamp:g,icon:v,tag:E,message:Ot.gray(h),level:e}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:g,icon:v,tag:E,message:h,level:e}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:g,icon:v,tag:E,message:Ot.green(h),level:e}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:g,icon:v,tag:E,message:h,level:e}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:g,icon:v,tag:E,message:h,level:e}),console.error(A),S){let x=S.split(`
2
2
  `);for(let D of x)if(D.trim()&&!D.includes(h))console.error(this.formatConsoleMessage({timestamp:g,message:Ot.gray(` ${D}`),level:e,showTimestamp:!1}))}break}}else if(!Yt()){if(console.error(`${f} ${this.environment}.${e.toUpperCase()}: ${h}`),S)console.error(S)}if(!this.shouldLog(e))return;let k=`${f} ${this.environment}.${e.toUpperCase()}: ${h}
3
3
  `;if(S)k+=`${S}
4
4
  `;k=k.replace(this.ANSI_PATTERN,""),await this.writeToFile(k)}time(e){let t=performance.now();if(this.fancy&&!Yt()){let r=this.options.showTags!==!1&&this.name?Ot.gray(this.formatTag(this.name)):"",a=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:a,icon:Ot.blue("◐"),tag:r,message:`${Ot.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let a=performance.now(),g=Math.round(a-t),f=`${e} completed in ${g}ms`,h=new Date,S=this.formatConsoleTimestamp(h),v=`${this.formatFileTimestamp(h)} ${this.environment}.INFO: ${f}`;if(r)v+=` ${JSON.stringify(r)}`;if(v+=`