@stacksjs/bun-router 0.0.26 → 0.1.0

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 (103) hide show
  1. package/dist/chunk-0gjq8ttx.js +14 -0
  2. package/dist/chunk-0t5vz87j.js +35 -0
  3. package/dist/chunk-30rkn2ym.js +2 -0
  4. package/dist/chunk-38cmrard.js +2 -0
  5. package/dist/chunk-3qna6dwd.js +2 -0
  6. package/dist/chunk-4d5fmta0.js +2 -0
  7. package/dist/chunk-4x3b4b4q.js +2 -0
  8. package/dist/chunk-5be9x5cq.js +3 -0
  9. package/dist/chunk-5mxby3fd.js +1654 -0
  10. package/dist/chunk-5n0ckcmc.js +3 -0
  11. package/dist/chunk-5ncn73tp.js +3 -0
  12. package/dist/chunk-5s0pnsd6.js +12 -0
  13. package/dist/chunk-5s1pr62n.js +3 -0
  14. package/dist/chunk-67wgad4f.js +60 -0
  15. package/dist/chunk-6bbmkwng.js +3 -0
  16. package/dist/chunk-6s1kbajm.js +7851 -0
  17. package/dist/chunk-6sjvhy5f.js +3 -0
  18. package/dist/chunk-6xed4va1.js +2 -0
  19. package/dist/chunk-73k79n7q.js +15413 -0
  20. package/dist/chunk-748n6ydj.js +2 -0
  21. package/dist/chunk-7qnxdedn.js +321 -0
  22. package/dist/chunk-7rsf8tes.js +898 -0
  23. package/dist/chunk-8aspmtf1.js +2 -0
  24. package/dist/chunk-8wpj3fqe.js +351 -0
  25. package/dist/chunk-8yfdg595.js +2 -0
  26. package/dist/chunk-90eze7av.js +3 -0
  27. package/dist/chunk-9805tt8n.js +341 -0
  28. package/dist/chunk-9dvwyej7.js +2 -0
  29. package/dist/chunk-9ght4n4r.js +216 -0
  30. package/dist/chunk-a2w45krb.js +2 -0
  31. package/dist/chunk-a3wahyg7.js +3 -0
  32. package/dist/chunk-a547f2ab.js +48 -0
  33. package/dist/chunk-bqdycvtc.js +2 -0
  34. package/dist/chunk-brpgjyqg.js +3 -0
  35. package/dist/chunk-cd03rk3x.js +2 -0
  36. package/dist/chunk-csfrpsp7.js +185 -0
  37. package/dist/chunk-ct0m17q5.js +2 -0
  38. package/dist/chunk-dhbvvr5h.js +2 -0
  39. package/dist/chunk-dhptcsya.js +943 -0
  40. package/dist/chunk-dq93zag9.js +2 -0
  41. package/dist/chunk-dxg045wj.js +5 -0
  42. package/dist/chunk-e3qej0jr.js +4 -0
  43. package/dist/chunk-edrtesh7.js +2 -0
  44. package/dist/chunk-ejcws37w.js +2 -0
  45. package/dist/chunk-ex5fkjah.js +397 -0
  46. package/dist/chunk-ex890p45.js +51 -0
  47. package/dist/chunk-f69cpnhw.js +2 -0
  48. package/dist/chunk-fjf53b44.js +2 -0
  49. package/dist/chunk-fjzye4qj.js +2 -0
  50. package/dist/chunk-gfd23b6t.js +2 -0
  51. package/dist/chunk-habv0vef.js +12 -0
  52. package/dist/chunk-hmgedrmr.js +11 -0
  53. package/dist/chunk-hz6fc788.js +2 -0
  54. package/dist/chunk-jff6j9y3.js +10 -0
  55. package/dist/chunk-jmeb7n8k.js +70 -0
  56. package/dist/chunk-jrf5a2ap.js +2 -0
  57. package/dist/chunk-jy2jhcpy.js +246 -0
  58. package/dist/chunk-kc659vhx.js +4 -0
  59. package/dist/chunk-kjtjbcq4.js +71 -0
  60. package/dist/chunk-krkchy8v.js +4 -0
  61. package/dist/chunk-kxp888dn.js +4540 -0
  62. package/dist/chunk-m249t3je.js +3 -0
  63. package/dist/chunk-m9yabnjx.js +2 -0
  64. package/dist/chunk-mekrq9wd.js +2 -0
  65. package/dist/chunk-mmxv535f.js +82 -0
  66. package/dist/chunk-mypn7jss.js +2 -0
  67. package/dist/chunk-n18x1k3c.js +2 -0
  68. package/dist/chunk-nkddjzsa.js +2 -0
  69. package/dist/chunk-pjmhqmr9.js +2 -0
  70. package/dist/chunk-qyrnsaq1.js +2 -0
  71. package/dist/chunk-r19ff2qm.js +62 -0
  72. package/dist/chunk-r338fssq.js +2 -0
  73. package/dist/chunk-s36z58x2.js +29 -0
  74. package/dist/chunk-s3dn1kwx.js +231 -0
  75. package/dist/chunk-s79dd325.js +471 -0
  76. package/dist/chunk-sw0chtw4.js +4 -0
  77. package/dist/chunk-ta38j9em.js +2 -0
  78. package/dist/chunk-tpfgntwj.js +4211 -0
  79. package/dist/chunk-vr10sbbh.js +3 -0
  80. package/dist/chunk-vsh4390q.js +358 -0
  81. package/dist/chunk-vv3gb1m5.js +84 -0
  82. package/dist/chunk-vw8rwv6e.js +2 -0
  83. package/dist/chunk-w4r464v5.js +288 -0
  84. package/dist/chunk-wcrqs5z9.js +2 -0
  85. package/dist/chunk-x6d1rmwa.js +2 -0
  86. package/dist/chunk-x7ft15zz.js +2 -0
  87. package/dist/chunk-x8trwn7j.js +3 -0
  88. package/dist/chunk-xg9xscqz.js +1 -0
  89. package/dist/chunk-xhepdj1f.js +2 -0
  90. package/dist/chunk-xv2em0q4.js +4 -0
  91. package/dist/chunk-ypw6g0te.js +2 -0
  92. package/dist/chunk-z8szsm21.js +2 -0
  93. package/dist/chunk-zetqzgf3.js +194 -0
  94. package/dist/chunk-zfbh14qe.js +2 -0
  95. package/dist/chunk-zhx0hxdd.js +28 -0
  96. package/dist/cli.js +67 -3240
  97. package/dist/container/index.js +1 -321
  98. package/dist/index.js +80 -13987
  99. package/dist/types.d.ts +12 -2
  100. package/package.json +1 -1
  101. package/dist/chunk-1ahs68ys.js +0 -18
  102. package/dist/chunk-cgptvjdf.js +0 -18131
  103. package/dist/chunk-g3ybefhg.js +0 -1923
@@ -0,0 +1,62 @@
1
+ // @bun
2
+ import{Zu as Q}from"./chunk-a3wahyg7.js";import re from"process";import{existsSync as $r,statSync as Cr}from"fs";import{existsSync as Gi,mkdirSync as pa,readdirSync as ya,readFileSync as Vi,writeFileSync as ba}from"fs";import{homedir as ae}from"os";import{dirname as $a,resolve as L}from"path";import ot from"process";import{existsSync as Er,statSync as kr}from"fs";import{existsSync as Mt,mkdirSync as Zi,readdirSync as qi,writeFileSync as Yi}from"fs";import{homedir as oe}from"os";import{dirname as Sr,resolve as D}from"path";import ne from"process";import{join as Xi,relative as es,resolve as xr}from"path";import He from"process";import{existsSync as li,mkdirSync as Na,readdirSync as Pa,writeFileSync as Ba}from"fs";import{homedir as ft}from"os";import{dirname as Da,resolve as R}from"path";import $e from"process";import{join as ts,relative as rs,resolve as Ar}from"path";import Ge from"process";import{existsSync as ci,mkdirSync as Ua,readdirSync as Qa,writeFileSync as Wa}from"fs";import{dirname as za,resolve as Ve}from"path";import Nt from"process";import{Buffer as ie}from"buffer";import{createCipheriv as is,createDecipheriv as ss,randomBytes as ut}from"crypto";import{closeSync as gt,createReadStream as Tr,createWriteStream as ns,existsSync as mt,fsyncSync as Or,openSync as Mr,writeFileSync as as}from"fs";import{access as os,constants as Nr,mkdir as ls,readdir as Ae,rename as Pr,stat as le,unlink as Te,writeFile as dt}from"fs/promises";import{join as ce}from"path";import N from"process";import{pipeline as cs}from"stream/promises";import{createGzip as Br}from"zlib";import he from"process";import Y from"process";import{Buffer as V}from"buffer";import{createCipheriv as hs,createDecipheriv as fs,randomBytes as pt}from"crypto";import{closeSync as yt,createReadStream as Ir,createWriteStream as us,existsSync as Oe,fsyncSync as Rr,openSync as Dr,writeFileSync as gs}from"fs";import{access as ms,constants as Fr,mkdir as ds,readdir as Me,rename as jr,stat as fe,unlink as Ne,writeFile as bt}from"fs/promises";import{isAbsolute as ps,join as ue,resolve as ys}from"path";import b from"process";import{pipeline as bs}from"stream/promises";import{createGzip as Lr}from"zlib";import ge from"process";import X from"process";import Pe from"process";import{existsSync as Be}from"fs";import{resolve as wt}from"path";import{existsSync as ws}from"fs";import{existsSync as vs,readdirSync as $s}from"fs";import{extname as vt,resolve as _r}from"path";import Cs from"process";import{join as Es,relative as ks,resolve as Ur}from"path";import Ze from"process";import{Buffer as Z}from"buffer";import{createCipheriv as Ss,createDecipheriv as xs,randomBytes as $t}from"crypto";import{closeSync as Ct,createReadStream as Qr,createWriteStream as As,existsSync as Ie,fsyncSync as Wr,openSync as Kr,writeFileSync as Ts}from"fs";import{access as Os,constants as zr,mkdir as Ms,readdir as Re,rename as Jr,stat as me,unlink as De,writeFile as Et}from"fs/promises";import{isAbsolute as Ns,join as de,resolve as Ps}from"path";import w from"process";import{pipeline as Bs}from"stream/promises";import{createGzip as Hr}from"zlib";import pe from"process";import ee from"process";import Fe from"process";import{existsSync as je}from"fs";import{resolve as kt}from"path";import{existsSync as Is}from"fs";import{Buffer as Ue}from"buffer";import sa from"process";import na from"process";import we from"process";import{Buffer as aa}from"buffer";import oa from"process";class Qt{config;pendingAcks=new Map;timeouts=new Map;constructor(e={}){this.config={enabled:e.enabled??!1,timeout:e.timeout??5000,retryAttempts:e.retryAttempts??3}}isEnabled(){return this.config.enabled}register(e,t,r,i,s){if(!this.config.enabled)return Promise.resolve(!0);return new Promise((n,a)=>{let l={messageId:e,channel:t,event:r,data:i,socketId:s,timestamp:Date.now(),attempts:1,resolve:n,reject:a};this.pendingAcks.set(e,l);let o=setTimeout(()=>{this.handleTimeout(e)},this.config.timeout);this.timeouts.set(e,o)})}acknowledge(e){let t=this.pendingAcks.get(e);if(!t)return!1;let r=this.timeouts.get(e);if(r)clearTimeout(r),this.timeouts.delete(e);return t.resolve(!0),this.pendingAcks.delete(e),!0}handleTimeout(e){let t=this.pendingAcks.get(e);if(!t)return;if(t.attempts<this.config.retryAttempts){t.attempts++,t.timestamp=Date.now();let r=setTimeout(()=>{this.handleTimeout(e)},this.config.timeout);this.timeouts.set(e,r)}else t.reject(Error(`Message acknowledgment timeout after ${t.attempts} attempts`)),this.pendingAcks.delete(e),this.timeouts.delete(e)}getPending(){return Array.from(this.pendingAcks.values())}getPendingById(e){return this.pendingAcks.get(e)}clear(){for(let e of this.timeouts.values())clearTimeout(e);for(let e of this.pendingAcks.values())e.reject(Error("Acknowledgment cleared"));this.pendingAcks.clear(),this.timeouts.clear()}getStats(){if(this.pendingAcks.size===0)return{pending:0};let e=Array.from(this.pendingAcks.values()).map((r)=>r.timestamp),t=Math.min(...e);return{pending:this.pendingAcks.size,oldest:t}}}class Wt{config;channelManager;constructor(e={},t){this.config={enabled:e.enabled??!0,maxBatchSize:e.maxBatchSize??50,debounceMs:e.debounceMs??0},this.channelManager=t}async batchSubscribe(e,t){if(!this.config.enabled)throw Error("Batch operations are disabled");let{channels:r,channelData:i}=t;if(r.length>this.config.maxBatchSize)throw Error(`Batch size exceeds maximum: ${r.length} > ${this.config.maxBatchSize}`);let s={succeeded:[],failed:{}};for(let n of r)try{let a=i?.[n];if(await this.channelManager.subscribe(e,n,a))s.succeeded.push(n);else s.failed[n]="Authorization failed"}catch(a){s.failed[n]=a instanceof Error?a.message:"Unknown error"}return s}batchUnsubscribe(e,t){if(!this.config.enabled)throw Error("Batch operations are disabled");if(t.length>this.config.maxBatchSize)throw Error(`Batch size exceeds maximum: ${t.length} > ${this.config.maxBatchSize}`);let r={succeeded:[],failed:{}};for(let i of t)try{this.channelManager.unsubscribe(e,i),r.succeeded.push(i)}catch(s){r.failed[i]=s instanceof Error?s.message:"Unknown error"}return r}batchBroadcast(e,t){if(!this.config.enabled)throw Error("Batch operations are disabled");let{channels:r,event:i,data:s,excludeSocketId:n}=t;if(r.length>this.config.maxBatchSize)throw Error(`Batch size exceeds maximum: ${r.length} > ${this.config.maxBatchSize}`);let a={succeeded:[],failed:{}};for(let l of r)try{e(l,i,s,n),a.succeeded.push(l)}catch(o){a.failed[l]=o instanceof Error?o.message:"Unknown error"}return a}}class Kt{server;config;queue=null;constructor(e,t){this.server=e,this.config=t}setQueue(e){return this.queue=e,this}async broadcast(e){if(!e.shouldBroadcast())return;if(e.broadcastWhen&&!e.broadcastWhen())return;let t=this.normalizeChannels(e.broadcastOn()),r=e.broadcastAs?e.broadcastAs():e.constructor.name,i=e.broadcastWith?e.broadcastWith():{},s={event:r,channel:t[0],data:i},n=e.broadcastQueue?.();if(n||this.queue)await this.queueBroadcast(s,t,n);else this.sendBroadcast(s,t)}send(e,t,r){let i=this.normalizeChannels(e),s={event:t,channel:i[0],data:r};this.sendBroadcast(s,i)}toOthers(e){return new zt(this,e)}sendBroadcast(e,t){for(let r of t)this.server.broadcast(r,e.event,e.data,e.socketId)}async queueBroadcast(e,t,r){let i=this.server.queueManager;if(i&&i.isEnabled()){if(this.config.verbose)console.warn(`Queueing broadcast to queue: ${r||this.queue?.queue||"default"}`);await i.queueBroadcast(t,e.event,e.data,{excludeSocketId:e.socketId})}else{if(this.config.verbose)console.warn("Queue not available, broadcasting immediately");this.sendBroadcast(e,t)}}normalizeChannels(e){return Array.isArray(e)?e:[e]}}class zt{broadcaster;excludeSocketId;constructor(e,t){this.broadcaster=e,this.excludeSocketId=t}async broadcast(e){await this.broadcaster.broadcast(e)}send(e,t,r){this.broadcaster.send(e,t,r)}}class Jt{config;state=new Map;constructor(e={}){this.config={enabled:e.enabled??!0,ttl:e.ttl??3600,maxSize:e.maxSize??1048576}}set(e,t,r){if(!this.config.enabled)return;if(!this.state.has(e))this.state.set(e,new Map);let i=this.state.get(e),s=JSON.stringify(r).length;if(s>this.config.maxSize)throw Error(`State value exceeds max size: ${s} > ${this.config.maxSize}`);i.set(t,r)}get(e,t){return this.state.get(e)?.get(t)}getAll(e){let t=this.state.get(e);if(!t)return{};return Object.fromEntries(t)}delete(e,t){this.state.get(e)?.delete(t)}clear(e){this.state.delete(e)}has(e,t){if(t)return this.state.get(e)?.has(t)??!1;return this.state.has(e)}getSize(e){let t=this.state.get(e);if(!t)return 0;return JSON.stringify(Object.fromEntries(t)).length}}class Ht{config;constructor(e={}){this.config={enabled:e.enabled??!1,separator:e.separator||":",validateNamespace:e.validateNamespace||(()=>!0)}}parse(e){if(!this.config.enabled)return{channel:e};let t=e.split(this.config.separator);if(t.length>1){let r=t[t.length-1],i=t.slice(0,-1).join(this.config.separator);if(this.config.validateNamespace(i))return{namespace:i,channel:r}}return{channel:e}}format(e,t){if(!this.config.enabled)return t;return`${e}${this.config.separator}${t}`}belongsTo(e,t){let r=this.parse(e);if(!r.namespace)return!1;return r.namespace===t||r.namespace.startsWith(t+this.config.separator)}getChannelsInNamespace(e,t){return e.filter((r)=>this.belongsTo(r,t))}}class Gt{channels=new Map;authorizers=new Map;channel(e,t){return this.authorizers.set(e,t),this}getChannel(e){if(!this.channels.has(e)){let t=this.getChannelType(e),r={name:e,type:t,subscribers:new Set};if(t==="presence")r.members=new Map;this.channels.set(e,r)}return this.channels.get(e)}getChannelType(e){if(e.startsWith("presence-"))return"presence";if(e.startsWith("private-"))return"private";return"public"}async subscribe(e,t,r){let i=this.getChannel(t),s=null;if(i.type!=="public"){let n=await this.authorize(e,t,r);if(!n)return!1;if(i.type==="presence"&&typeof n==="object")i.members.set(e.data.socketId,n),s=n}return i.subscribers.add(e.data.socketId),e.data.channels.add(t),e.subscribe(t),s||!0}unsubscribe(e,t){let r=this.channels.get(t);if(!r)return;if(r.subscribers.delete(e.data.socketId),e.data.channels.delete(t),e.unsubscribe(t),r.type==="presence")r.members.delete(e.data.socketId);if(r.subscribers.size===0)this.channels.delete(t)}unsubscribeAll(e){let t=Array.from(e.data.channels);for(let r of t)this.unsubscribe(e,r)}async authorize(e,t,r){for(let[i,s]of this.authorizers){let n=this.extractParams(i,t);if(n!==null)if(typeof s==="function")return await s(e,n);else return await s.join(e,n)}return!1}extractParams(e,t){let r=[],i=e.replace(/\{([^}]+)\}/g,(l,o)=>{return r.push(o),"([^.]+)"}),s=new RegExp(`^${i}$`),n=t.match(s);if(!n)return null;let a={};for(let l=0;l<r.length;l++)a[r[l]]=n[l+1];return a}patternToRegex(e){let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{[^}]+\\\}/g,"[^.]+");return new RegExp(`^${t}$`)}getSubscribers(e){return this.channels.get(e)?.subscribers||new Set}getPresenceMembers(e){let t=this.channels.get(e);if(t?.type==="presence")return t.members;return null}getSubscriberCount(e){return this.channels.get(e)?.subscribers.size||0}hasChannel(e){return this.channels.has(e)}getChannelNames(){return Array.from(this.channels.keys())}getChannelCount(){return this.channels.size}}class hi{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],[,i])=>r.timestamp.getTime()-i.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,i){if(!this.options.enabled)return;let s=this.generateKey(e,r),n=i??this.options.ttl,a=this.estimateSize(t);this.cache.set(s,{value:t,timestamp:new Date,ttl:n,hits:0,size:a}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!$r(e))return!0;return Cr(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,i){try{let s=$r(r)?Cr(r):null,n=s?s.mtime:new Date;this.set(e,{value:t,fileTimestamp:n},r,i)}catch{this.set(e,t,r,i)}}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((i,s)=>i+s.size,0),r=e.map((i)=>i.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 i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class fi{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),s=new Date;try{let n=await t(),a=performance.now()-i;return this.recordMetric({operation:e,duration:a,timestamp:s,...r}),n}catch(n){let a=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:a,timestamp:s,...r}),n}}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((s)=>s.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((s)=>s.duration),i=r.reduce((s,n)=>s+n,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}var qe=new hi,Vt=new fi,Rs=Object.defineProperty,Ds=(e)=>e;function Fs(e,t){this[e]=Ds.bind(null,t)}var js=(e,t)=>{for(var r in t)Rs(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Fs.bind(t,r)})},Ls=(e,t)=>()=>(e&&(t=e(e=0)),t),ui={};js(ui,{withErrorRecovery:()=>di,tryLoadConfig:()=>cn,loadConfigWithResult:()=>on,loadConfig:()=>vi,isRetryableError:()=>en,isConfigNotFoundError:()=>Xs,isBunfigError:()=>pi,globalPerformanceMonitor:()=>ke,globalCache:()=>ye,getEnvOrDefault:()=>tn,generateConfigTypes:()=>hn,defaultGeneratedDir:()=>Ti,defaultConfigDir:()=>Ai,deepMergeWithArrayStrategy:()=>er,deepMerge:()=>yi,createLibraryConfig:()=>fn,config:()=>ln,bunfigPlugin:()=>un,applyEnvVarsToConfig:()=>ve,TypeGenerationError:()=>jt,SchemaValidationError:()=>Ee,PluginError:()=>_t,PerformanceMonitor:()=>qt,FileSystemError:()=>Ft,ErrorFactory:()=>se,EnvVarError:()=>it,EnvProcessor:()=>lt,ConfigValidator:()=>tr,ConfigValidationError:()=>Rt,ConfigNotFoundError:()=>rt,ConfigMergeError:()=>Dt,ConfigLoader:()=>rr,ConfigLoadError:()=>Ce,ConfigFileLoader:()=>ct,ConfigCache:()=>Zt,CacheUtils:()=>Ci,BunfigError:()=>F,BrowserConfigError:()=>Lt,ArrayMergeStrategies:()=>Si});class Zt{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],[,i])=>r.timestamp.getTime()-i.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,i){if(!this.options.enabled)return;let s=this.generateKey(e,r),n=i??this.options.ttl,a=this.estimateSize(t);this.cache.set(s,{value:t,timestamp:new Date,ttl:n,hits:0,size:a}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!Er(e))return!0;return kr(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,i){try{let s=Er(r)?kr(r):null,n=s?s.mtime:new Date;this.set(e,{value:t,fileTimestamp:n},r,i)}catch{this.set(e,t,r,i)}}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((i,s)=>i+s.size,0),r=e.map((i)=>i.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 i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class qt{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),s=new Date;try{let n=await t(),a=performance.now()-i;return this.recordMetric({operation:e,duration:a,timestamp:s,...r}),n}catch(n){let a=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:a,timestamp:s,...r}),n}}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((s)=>s.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((s)=>s.duration),i=r.reduce((s,n)=>s+n,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function _s(e,t={}){let r=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return r?`${e}:${r}`:e}function Us(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Qs(e){return e.getStats().size*2}function Yt(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&C(t[0])&&"id"in t[0]&&t[0].id===3&&C(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(C(t)&&C(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(C(e)&&"arr"in e&&Array.isArray(e.arr)&&C(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&C(t[0])&&C(e[0])){let i=[...t];for(let s of e)if(C(s)&&"name"in s){if(!i.find((n)=>C(n)&&("name"in n)&&n.name===s.name))i.push(s)}else if(C(s)&&"path"in s){if(!i.find((n)=>C(n)&&("path"in n)&&n.path===s.path))i.push(s)}else if(!i.some((n)=>Ye(n,s)))i.push(s);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let s of e)if(!i.includes(s))i.push(s);return i}return t}if(!C(t)||!C(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let s=t[i];if(s===null||s===void 0)continue;else if(C(s)&&C(r[i]))r[i]=Yt(r[i],s);else if(Array.isArray(s)&&Array.isArray(r[i]))if(s.length>0&&r[i].length>0&&C(s[0])&&C(r[i][0])){let n=[...s];for(let a of r[i])if(C(a)&&"name"in a){if(!n.find((l)=>C(l)&&("name"in l)&&l.name===a.name))n.push(a)}else if(C(a)&&"path"in a){if(!n.find((l)=>C(l)&&("path"in l)&&l.path===a.path))n.push(a)}else if(!n.some((l)=>Ye(l,a)))n.push(a);r[i]=n}else if(s.every((n)=>typeof n==="string")&&r[i].every((n)=>typeof n==="string")){let n=[...s];for(let a of r[i])if(!n.includes(a))n.push(a);r[i]=n}else r[i]=s;else r[i]=s}return r}function Ye(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(!Ye(e[r],t[r]))return!1;return!0}if(C(e)&&C(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!Ye(e[s],t[s]))return!1}return!0}return!1}function C(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Ws(e,t){if(!ci(e))return null;try{let r=await import(e),i=r.default||r;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return Yt(t,i)}catch{return null}}catch{return null}}async function Ks({name:e="",cwd:t,defaultConfig:r}){let i=t||Nt.cwd(),s=[".ts",".js",".mjs",".cjs",".json"],n=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let a of n)for(let l of s){let o=Ve(i,`${a}${l}`),c=await Ws(o,r);if(c!==null)return c}try{let a=Ve(i,"package.json");if(ci(a)){let l=(await import(a))[e];if(l&&typeof l==="object"&&!Array.isArray(l))try{return Yt(r,l)}catch{}}}catch{}return r}function zs(e,t={}){let r=Ge.cwd();while(r.includes("storage"))r=Ar(r,"..");let i=Ar(r,e||"");if(t?.relative)return rs(Ge.cwd(),i);return i}async function Js(){try{let e=await Ks({name:"clarity",defaultConfig:We,cwd:Ge.cwd(),endpoint:"",headers:{}});return{...We,...e}}catch{return We}}function k(){if(Y.env.NODE_ENV==="test"||Y.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Hs(){if(Y.env.NODE_ENV==="test"||Y.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Y<"u"){let e=Y.type;if(e==="renderer"||e==="worker")return!1;return!!(Y.versions&&(Y.versions.node||Y.versions.bun))}return!1}class gi{async format(e){let t=await Hs(),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:he.pid,hostname:t(),environment:he.env.NODE_ENV||"development",platform:he.platform,version:he.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:he.env.NODE_ENV||he.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Xe{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={...Bt},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new gi,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??N.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),n=this.generateKey();this.currentKeyId=s,this.keys.set(s,n),this.encryptionKeys.set(s,{key:n,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Ke,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Ke};return{...Ke,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Bt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let t=(async()=>{let i,s=0,n=3,a=1000;while(s<n)try{try{try{await os(this.config.logDirectory,Nr.F_OK|Nr.W_OK)}catch(o){if(o instanceof Error&&"code"in o)if(o.code==="ENOENT")await ls(this.config.logDirectory,{recursive:!0,mode:493});else if(o.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw o;else throw o}}catch(o){throw console.error("Debug: [writeToFile] Failed to create log directory:",o),o}let l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ie.from(e);try{if(!mt(this.currentLogFile))await dt(this.currentLogFile,"",{mode:420});if(i=Mr(this.currentLogFile,"a",420),as(i,l,{flag:"a"}),Or(i),i!==void 0)gt(i),i=void 0;if((await le(this.currentLogFile)).size===0){if(await dt(this.currentLogFile,l,{flag:"w",mode:420}),(await le(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(o){let c=o;if(c.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(c.code)){if(s<n-1){let h=typeof c.message==="string"?c.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${n}:`,h);let f=a*2**s;await new Promise((g)=>setTimeout(g,f)),s++;continue}}if(c?.code&&["ENOSPC","EDQUOT"].includes(c.code))throw Error(`Disk quota exceeded or no space left on device: ${c.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",c),c}finally{if(i!==void 0)try{gt(i)}catch(o){console.error("Debug: [writeToFile] Error closing file descriptor:",o)}}}catch(l){if(s===n-1){let c=l,h=typeof c.message==="string"?c.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),l}s++;let o=a*2**(s-1);await new Promise((c)=>setTimeout(c,o))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,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 ce(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 ce(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ce(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(k())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 e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,a],[,l])=>l.createdAt.getTime()-a.createdAt.getTime()),s=typeof e.maxKeys==="number"?e.maxKeys:1,n=Math.max(1,s);if(i.length>n)for(let[a]of i.slice(n))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return ut(16).toString("hex")}generateKey(){return ut(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=ut(16),i=is("aes-256-gcm",t,r),s=ie.concat([i.update(e,"utf8"),i.final()]),n=i.getAuthTag();return{encrypted:ie.concat([r,s,n]),iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Br(),s=[];i.on("data",(n)=>s.push(n)),i.on("end",()=>t(ie.from(ie.concat(s)))),i.on("error",r),i.write(e),i.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(k())return;let e=await le(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,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await Ae(this.config.logDirectory),n=s.filter((o)=>o.startsWith(this.name)&&/\.log\.\d+$/.test(o)).sort((o,c)=>{let h=Number.parseInt(o.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),a=n.length>0?Number.parseInt(n[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${r}.${a}`;if(await le(r).catch(()=>null))try{if(await Pr(r,l),t.compress)try{let o=`${l}.gz`;await this.compressLogFile(l,o),await Te(l)}catch(o){console.error("Error compressing rotated file:",o)}if(n.length===0&&!s.some((o)=>o.endsWith(".log.1")))try{let o=`${r}.1`;await dt(o,"")}catch(o){console.error("Error creating backup file:",o)}}catch(o){console.error(`Error during rotation: ${o instanceof Error?o.message:String(o)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),n=r.replace(/\.log$/,`-${s}.log`);if(await le(r).catch(()=>null))await Pr(r,n)}if(this.currentLogFile=i,t.maxFiles){let s=(await Ae(this.config.logDirectory)).filter((n)=>n.startsWith(this.name)).sort((n,a)=>a.localeCompare(n));for(let n of s.slice(t.maxFiles))await Te(ce(this.config.logDirectory,n))}}}async compressLogFile(e,t){let r=Tr(e),i=ns(t),s=Br();await cs(r,s,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);await this.writeToFile(i),console.log(i)}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()})),mt(this.currentLogFile))try{let e=Mr(this.currentLogFile,"r+");Or(e),gt(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(!k()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Ae(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Te(ce(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}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?$.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:s,level:n,showTimestamp:a=!0}=e,l=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(a)u.push(t);if(n==="warning")u.push("WARN");else if(n==="error")u.push("ERROR");else if(r)u.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)u.push(i.replace(/[[\]]/g,""));return u.push(s),u.join(" ")}let o=N.stdout.columns||120,c="";if(n==="warning"||n==="error")c=`${r} ${s}`;else if(n==="info"||n==="success")c=`${r} ${i} ${s}`;else c=`${r} ${i} ${$.cyan(s)}`;if(!a)return c.trim();let h=l(c).trim().length,f=l(t).length,g=Math.max(1,o-2-h-f);return`${c.trim()}${" ".repeat(g)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(n,a)=>{let l=Number.parseInt(a,10);return l<t[0].length?String(t[0][l]):n});let r=/%([sdijfo%])/g,i=0,s=e.replace(r,(n,a)=>{if(a==="%")return"%";if(i>=t.length)return n;let l=t[i++];switch(a){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return n}});if(i<t.length)s+=` ${t.slice(i).map((n)=>typeof n==="object"?JSON.stringify(n,null,2):String(n)).join(" ")}`;return s}async log(e,t,...r){let i=new Date,s=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),a,l;if(t instanceof Error)a=t.message,l=t.stack;else a=this.formatMessage(t,r);if(this.fancy&&!k()){let c=Ei[e],h=this.options.showTags!==!1&&this.name?$.gray(this.formatTag(this.name)):"",f;switch(e){case"debug":f=this.formatConsoleMessage({timestamp:s,icon:c,tag:h,message:$.gray(a),level:e}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:s,icon:c,tag:h,message:a,level:e}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:s,icon:c,tag:h,message:$.green(a),level:e}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:s,icon:c,tag:h,message:a,level:e}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:s,icon:c,tag:h,message:a,level:e}),console.error(f),l){let g=l.split(`
3
+ `);for(let u of g)if(u.trim()&&!u.includes(a))console.error(this.formatConsoleMessage({timestamp:s,message:$.gray(` ${u}`),level:e,showTimestamp:!1}))}break}}else if(!k()){if(console.error(`${n} ${this.environment}.${e.toUpperCase()}: ${a}`),l)console.error(l)}if(!this.shouldLog(e))return;let o=`${n} ${this.environment}.${e.toUpperCase()}: ${a}
4
+ `;if(l)o+=`${l}
5
+ `;o=o.replace(this.ANSI_PATTERN,""),await this.writeToFile(o)}time(e){let t=performance.now();if(this.fancy&&!k()){let r=this.options.showTags!==!1&&this.name?$.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:$.blue("\u25D0"),tag:r,message:`${$.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),s=Math.round(i-t),n=`${e} completed in ${s}ms`,a=new Date,l=this.formatConsoleTimestamp(a),o=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${n}`;if(r)o+=` ${JSON.stringify(r)}`;if(o+=`
6
+ `,o=o.replace(this.ANSI_PATTERN,""),this.fancy&&!k()){let c=this.options.showTags!==!1&&this.name?$.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:$.green("\u2713"),tag:c,message:`${n}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!k())console.error(o.trim());await this.writeToFile(o)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Xe(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(k())throw Error("createReadStream is not supported in browser environments");if(!mt(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Tr(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=ie.isBuffer(e)?e:ie.from(e,"base64"),s=i.slice(0,16),n=i.slice(-16),a=i.slice(16,-16),l=ss("aes-256-gcm",r,s);return l.setAuthTag(n),ie.concat([l.update(a),l.final()]).toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return k()}isServerMode(){return!k()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t);if(this.fancy&&!k()){let n=e.split(`
7
+ `),a=Math.max(...n.map((h)=>h.length))+2,l=`\u250C${"\u2500".repeat(a)}\u2510`,o=`\u2514${"\u2500".repeat(a)}\u2518`,c=n.map((h)=>{let f=" ".repeat(a-h.length-2);return`\u2502 ${h}${f} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:$.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:$.cyan(l)})),c.forEach((h)=>console.error(this.formatConsoleMessage({timestamp:r,message:$.cyan(h),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:$.cyan(o),showTimestamp:!1}))}else if(!k())console.error(`${i} ${this.environment}.INFO: [BOX] ${e}`);let s=`${i} ${this.environment}.INFO: [BOX] ${e}
8
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(s)}async prompt(e){if(k())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${$.cyan("?")} ${e} (y/n) `);let r=(i)=>{let s=i.toString().trim().toLowerCase();N.stdin.removeListener("data",r);try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!1)}catch{}N.stdin.pause(),console.error(""),t(s==="y"||s==="yes")};try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!0)}catch{}N.stdin.resume(),N.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let s=/%([sdijfo%])/g,n=0;if(r=e.replace(s,(a,l)=>{if(l==="%")return"%";if(n>=t.length)return a;let o=t[n++];switch(l){case"s":return String(o);case"d":case"i":return Number(o).toString();case"j":case"o":return JSON.stringify(o,null,2);default:return a}}),n<t.length)r+=` ${t.slice(n).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}if(this.fancy&&!k()){let s=this.options.showTags!==!1&&this.name?$.gray(this.formatTag(this.name)):"",n=$.blue("\u25D0");console.error(`${n} ${s} ${$.cyan(r)}`)}let i=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
9
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}progress(e,t=""){if(!this.enabled||!this.fancy||k()||e<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(i,s)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,i)),s!==void 0)this.activeProgressBar.message=s;let n=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,n)},finish:(i)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;if(this.activeProgressBar.current=this.activeProgressBar.total,i!==void 0)this.activeProgressBar.message=i;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(i,s="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;N.stdout.write(`${"\r".padEnd(N.stdout.columns||80)}\r`),this.log(s,i),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||k()||!N.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),s=e.barLength-i,n=$.green("\u2501".repeat(i)),a=$.gray("\u2501".repeat(s)),l=`[${n}${a}]`,o=`${r}%`.padStart(4),c=e.message?` ${e.message}`:"",h=t||r===100?$.green("\u2713"):$.blue("\u25B6"),f=this.options.showTags!==!1&&this.name?` ${$.gray(this.formatTag(this.name))}`:"",g=`\r${h}${f} ${l} ${o}${c}`,u=N.stdout.columns||80,d=" ".repeat(Math.max(0,u-g.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${g}${d}`,N.stdout.write(e.lastRenderedLine),t)N.stdout.write(`
10
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||k()||!N.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(k()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ae(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let s=ce(this.config.logDirectory,i);if(e.before)try{if((await le(s)).mtime>=e.before)continue}catch(n){console.error(`Failed to get stats for file ${s}:`,n);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await Te(i),console.warn(`Deleted log file: ${i}`)}catch(s){console.error(`Failed to delete log file ${i}:`,s)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function Qe(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&v(t[0])&&"id"in t[0]&&t[0].id===3&&v(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(v(t)&&v(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(v(e)&&"arr"in e&&Array.isArray(e.arr)&&v(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&v(t[0])&&v(e[0])){let i=[...t];for(let s of e)if(v(s)&&"name"in s){if(!i.find((n)=>v(n)&&("name"in n)&&n.name===s.name))i.push(s)}else if(v(s)&&"path"in s){if(!i.find((n)=>v(n)&&("path"in n)&&n.path===s.path))i.push(s)}else if(!i.some((n)=>et(n,s)))i.push(s);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let s of e)if(!i.includes(s))i.push(s);return i}return t}if(!v(t)||!v(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let s=t[i];if(s===null||s===void 0)continue;else if(v(s)&&v(r[i]))r[i]=Qe(r[i],s);else if(Array.isArray(s)&&Array.isArray(r[i]))if(s.length>0&&r[i].length>0&&v(s[0])&&v(r[i][0])){let n=[...s];for(let a of r[i])if(v(a)&&"name"in a){if(!n.find((l)=>v(l)&&("name"in l)&&l.name===a.name))n.push(a)}else if(v(a)&&"path"in a){if(!n.find((l)=>v(l)&&("path"in l)&&l.path===a.path))n.push(a)}else if(!n.some((l)=>et(l,a)))n.push(a);r[i]=n}else if(s.every((n)=>typeof n==="string")&&r[i].every((n)=>typeof n==="string")){let n=[...s];for(let a of r[i])if(!n.includes(a))n.push(a);r[i]=n}else r[i]=s;else r[i]=s}return r}function Xt(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:Qe(e,t);if(Array.isArray(e))return r==="replace"?t:Qe(e,t);if(!v(t)||!v(e))return t;let i={...e};for(let s of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,s))continue;let n=t[s],a=i[s];if(n===null||n===void 0)continue;if(Array.isArray(n)||Array.isArray(a))if(r==="replace")i[s]=n;else i[s]=Qe(a,n);else if(v(n)&&v(a))i[s]=Xt(a,n,r);else i[s]=n}return i}function et(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(!et(e[r],t[r]))return!1;return!0}if(v(e)&&v(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!et(e[s],t[s]))return!1}return!0}return!1}function v(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Le(e,t,r="replace"){if(!li(e))return null;try{let i=await import(e),s=i.default||i;if(typeof s!=="object"||s===null||Array.isArray(s))return null;try{return Xt(t,s,r)}catch{return null}}catch{return null}}function Gs(e,t,r=!1){if(!e)return t;let i=e.toUpperCase().replace(/-/g,"_"),s={...t};function n(a,l=[]){let o={...a};for(let[c,h]of Object.entries(a)){let f=[...l,c],g=(m)=>m.replace(/([A-Z])/g,"_$1").toUpperCase(),u=`${i}_${f.map(g).join("_")}`,d=`${i}_${f.map((m)=>m.toUpperCase()).join("_")}`;if(r)B.info(`Checking environment variable ${u} for config ${e}.${f.join(".")}`);if(typeof h==="object"&&h!==null&&!Array.isArray(h))o[c]=n(h,f);else{let m=$e.env[u]||$e.env[d];if(m!==void 0){if(r)B.info(`Using environment variable ${m?u:d} for config ${e}.${f.join(".")}`);if(typeof h==="number")o[c]=Number(m);else if(typeof h==="boolean")o[c]=m.toLowerCase()==="true";else if(Array.isArray(h))try{let E=JSON.parse(m);if(Array.isArray(E))o[c]=E;else o[c]=m.split(",").map((M)=>M.trim())}catch{o[c]=m.split(",").map((E)=>E.trim())}else o[c]=m}}}return o}return n(s)}async function Vs({name:e="",alias:t,cwd:r,configDir:i,defaultConfig:s,verbose:n=!1,checkEnv:a=!0,arrayStrategy:l="replace"}){let o=a&&typeof s==="object"&&s!==null&&!Array.isArray(s)?Gs(e,s,n):s,c=r||$e.cwd(),h=[".ts",".js",".mjs",".cjs",".json"];if(n)B.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${c}`);let f=[e,`.${e}`].filter(Boolean),g=[`${e}.config`,`.${e}.config`].filter(Boolean),u=t?[t,`.${t}`]:[],d=t?[`${t}.config`,`.${t}.config`]:[],m=Array.from(new Set([c,R(c,"config"),R(c,".config"),i?R(c,i):void 0].filter(Boolean)));for(let E of m){if(n)B.info(`Searching for configuration in: ${E}`);let M=[R(c,"config"),R(c,".config")].concat(i?[R(c,i)]:[]).includes(E)?[...f,...g,...u,...d]:[...g,...f,...d,...u];for(let I of M)for(let G of h){let K=R(E,`${I}${G}`),z=await Le(K,o,l);if(z!==null){if(n)B.success(`Configuration loaded from: ${K}`);return z}}}if(e){let E=R(ft(),".config",e),M=["config",`${e}.config`];if(t)M.push(`${t}.config`);if(n)B.info(`Checking user config directory: ${E}`);for(let I of M)for(let G of h){let K=R(E,`${I}${G}`),z=await Le(K,o,l);if(z!==null){if(n)B.success(`Configuration loaded from user config directory: ${K}`);return z}}}if(e){let E=R(ft(),".config"),M=[`.${e}.config`];if(t)M.push(`.${t}.config`);if(n)B.info(`Checking user config directory for dotfile configs: ${E}`);for(let I of M)for(let G of h){let K=R(E,`${I}${G}`),z=await Le(K,o,l);if(z!==null){if(n)B.success(`Configuration loaded from user config directory dotfile: ${K}`);return z}}}if(e){let E=ft(),M=[`.${e}.config`,`.${e}`];if(t)M.push(`.${t}.config`),M.push(`.${t}`);if(n)B.info(`Checking user home directory for dotfile configs: ${E}`);for(let I of M)for(let G of h){let K=R(E,`${I}${G}`),z=await Le(K,o,l);if(z!==null){if(n)B.success(`Configuration loaded from user home directory: ${K}`);return z}}}try{let E=R(c,"package.json");if(li(E)){let M=await import(E),I=M[e];if(!I&&t){if(I=M[t],I&&n)B.success(`Using alias "${t}" configuration from package.json`)}if(I&&typeof I==="object"&&!Array.isArray(I))try{if(n)B.success(`Configuration loaded from package.json: ${I===M[e]?e:t}`);return Xt(o,I,l)}catch(G){if(n)B.warn("Failed to merge package.json config:",G)}}}catch(E){if(n)B.warn("Failed to load package.json:",E)}if(n)B.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return o}function Zs(e,t={}){let r=He.cwd();while(r.includes("storage"))r=xr(r,"..");let i=xr(r,e||"");if(t?.relative)return es(He.cwd(),i);return i}async function qs(){try{let e=await Vs({name:"clarity",alias:"logging",defaultConfig:ze,cwd:He.cwd()});return{...ze,...e||{}}}catch{return ze}}function S(){if(X.env.NODE_ENV==="test"||X.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ys(){if(X.env.NODE_ENV==="test"||X.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof X<"u"){let e=X.type;if(e==="renderer"||e==="worker")return!1;return!!(X.versions&&(X.versions.node||X.versions.bun))}return!1}class mi{async format(e){let t=await Ys(),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:ge.pid,hostname:t(),environment:ge.env.NODE_ENV||"development",platform:ge.platform,version:ge.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ge.env.NODE_ENV||ge.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class tt{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...It},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new mi,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??b.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),n=this.generateKey();this.currentKeyId=s,this.keys.set(s,n),this.encryptionKeys.set(s,{key:n,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Je,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Je};return{...Je,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:It.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!S()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,s=0,n=3,a=1000;while(s<n)try{try{try{await ms(this.config.logDirectory,Fr.F_OK|Fr.W_OK)}catch(o){if(o instanceof Error&&"code"in o)if(o.code==="ENOENT")await ds(this.config.logDirectory,{recursive:!0,mode:493});else if(o.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw o;else throw o}}catch(o){throw console.error("Debug: [writeToFile] Failed to create log directory:",o),o}let l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:V.from(e);try{if(!Oe(this.currentLogFile))await bt(this.currentLogFile,"",{mode:420});if(i=Dr(this.currentLogFile,"a",420),gs(i,l,{flag:"a"}),Rr(i),i!==void 0)yt(i),i=void 0;if((await fe(this.currentLogFile)).size===0){if(await bt(this.currentLogFile,l,{flag:"w",mode:420}),(await fe(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(o){let c=o;if(c.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(c.code)){if(s<n-1){let h=typeof c.message==="string"?c.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${n}:`,h);let f=a*2**s;await new Promise((g)=>setTimeout(g,f)),s++;continue}}if(c?.code&&["ENOSPC","EDQUOT"].includes(c.code))throw Error(`Disk quota exceeded or no space left on device: ${c.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",c),c}finally{if(i!==void 0)try{yt(i)}catch(o){console.error("Debug: [writeToFile] Error closing file descriptor:",o)}}}catch(l){if(s===n-1){let c=l,h=typeof c.message==="string"?c.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),l}s++;let o=a*2**(s-1);await new Promise((c)=>setTimeout(c,o))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,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 ue(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 ue(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ue(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(S())return;if(!this.shouldWriteToFile())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 e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,a],[,l])=>l.createdAt.getTime()-a.createdAt.getTime()),s=typeof e.maxKeys==="number"?e.maxKeys:1,n=Math.max(1,s);if(i.length>n)for(let[a]of i.slice(n))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return pt(16).toString("hex")}generateKey(){return pt(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=pt(16),i=hs("aes-256-gcm",t,r),s=V.isBuffer(e)?e:V.from(e,"utf8"),n=i.update(s),a=i.final(),l=n.length+a.length,o=i.getAuthTag(),c=V.allocUnsafe(16+l+16);return r.copy(c,0),n.copy(c,16),a.copy(c,16+n.length),o.copy(c,16+l),{encrypted:c,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Lr(),s=[];i.on("data",(n)=>s.push(n)),i.on("end",()=>t(V.from(V.concat(s)))),i.on("error",r),i.write(e),i.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(S())return;if(!this.shouldWriteToFile())return;let e=await fe(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,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await Me(this.config.logDirectory),n=s.filter((o)=>o.startsWith(this.name)&&/\.log\.\d+$/.test(o)).sort((o,c)=>{let h=Number.parseInt(o.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),a=n.length>0?Number.parseInt(n[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${r}.${a}`;if(await fe(r).catch(()=>null))try{if(await jr(r,l),t.compress)try{let o=`${l}.gz`;await this.compressLogFile(l,o),await Ne(l)}catch(o){console.error("Error compressing rotated file:",o)}if(n.length===0&&!s.some((o)=>o.endsWith(".log.1")))try{let o=`${r}.1`;await bt(o,"")}catch(o){console.error("Error creating backup file:",o)}}catch(o){console.error(`Error during rotation: ${o instanceof Error?o.message:String(o)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),n=r.replace(/\.log$/,`-${s}.log`);if(await fe(r).catch(()=>null))await jr(r,n)}if(this.currentLogFile=i,t.maxFiles){let s=(await Me(this.config.logDirectory)).filter((n)=>n.startsWith(this.name)).sort((n,a)=>a.localeCompare(n));for(let n of s.slice(t.maxFiles))await Ne(ue(this.config.logDirectory,n))}}}async compressLogFile(e,t){let r=Ir(e),i=us(t),s=Lr();await bs(r,s,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}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()})),Oe(this.currentLogFile))try{let e=Dr(this.currentLogFile,"r+");Rr(e),yt(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(!S()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Me(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Ne(ue(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}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.shouldStyleConsole()?p.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||S())return!1;let e=typeof b.env.NO_COLOR<"u",t=b.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof b.stderr<"u"&&b.stderr.isTTY||typeof b.stdout<"u"&&b.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:s,level:n,showTimestamp:a=!0}=e,l=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(a)u.push(t);if(n==="warning")u.push("WARN");else if(n==="error")u.push("ERROR");else if(r)u.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)u.push(i.replace(/[[\]]/g,""));return u.push(s),u.join(" ")}let o=b.stdout.columns||120,c="";if(n==="warning"||n==="error")c=`${r} ${s}`;else if(n==="info"||n==="success")c=`${r} ${i} ${s}`;else c=`${r} ${i} ${p.cyan(s)}`;if(!a)return c.trim();let h=l(c).trim().length,f=l(t).length,g=Math.max(1,o-2-h-f);return`${c.trim()}${" ".repeat(g)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(n,a)=>{let l=Number.parseInt(a,10);return l<t[0].length?String(t[0][l]):n});let r=/%([sdijfo%])/g,i=0,s=e.replace(r,(n,a)=>{if(a==="%")return"%";if(i>=t.length)return n;let l=t[i++];switch(a){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return n}});if(i<t.length)s+=` ${t.slice(i).map((n)=>typeof n==="object"?JSON.stringify(n,null,2):String(n)).join(" ")}`;return s}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,s)=>{let n=p.underline(p.blue(i)),a=this.toAbsoluteFilePath(s);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(a)}`,o="\x1B]8;;",c="\x1B\\";return`\x1B]8;;${l}\x1B\\${n}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${s}\x1B\\${n}\x1B]8;;\x1B\\`;return n}),t=t.replace(/`([^`]+)`/g,(r,i)=>p.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>p.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>p.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>p.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>p.strikethrough(i)),t}supportsHyperlinks(){if(S())return!1;let e=b.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=b.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(ps(t)||t.startsWith("./")||t.startsWith("../"))t=ys(t);else return null;return Oe(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let i=new Date,s=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),a,l;if(t instanceof Error)a=t.message,l=t.stack;else a=this.formatMessage(t,r);let{consoleText:o,fileText:c}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":ki[e],g=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"",u;switch(e){case"debug":u=this.formatConsoleMessage({timestamp:s,icon:f,tag:g,message:p.gray(o),level:e}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:s,icon:f,tag:g,message:o,level:e}),console.warn(u);break;case"success":u=this.formatConsoleMessage({timestamp:s,icon:f,tag:g,message:p.green(o),level:e}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:s,icon:f,tag:g,message:o,level:e}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:s,icon:f,tag:g,message:o,level:e}),console.error(u),l){let d=l.split(`
11
+ `);for(let m of d)if(m.trim()&&!m.includes(a))console.error(this.formatConsoleMessage({timestamp:s,message:p.gray(` ${m}`),level:e,showTimestamp:!1}))}break}}else if(!S()){if(console.error(`${n} ${this.environment}.${e.toUpperCase()}: ${a}`),l)console.error(l)}if(!this.shouldLog(e))return;let h=`${n} ${this.environment}.${e.toUpperCase()}: ${c}
12
+ `;if(l)h+=`${l}
13
+ `;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(e,t=""){let r={update:(s,n)=>{},finish:(s)=>{},interrupt:(s,n)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!S()&&b.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(s,n)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,s),this.activeProgressBar.total),n!==void 0)this.activeProgressBar.message=n;if(this.shouldStyleConsole()&&!S()&&b.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(s)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,s)},interrupt:(s,n="info")=>{if(!S()&&b.stdout.isTTY)b.stdout.write(`
14
+ `);if(this[n==="warning"?"warn":n](s),this.activeProgressBar&&this.shouldStyleConsole()&&!S()&&b.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":p.blue("\u25D0"),tag:r,message:`${p.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),s=Math.round(i-t),n=`${e} completed in ${s}ms`,a=new Date,l=this.formatConsoleTimestamp(a),o=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${n}`;if(r)o+=` ${JSON.stringify(r)}`;if(o+=`
15
+ `,o=o.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":p.green("\u2713"),tag:c,message:`${n}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!S())console.error(o.trim());if(this.shouldWriteToFile())await this.writeToFile(o)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new tt(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(S())throw Error("createReadStream is not supported in browser environments");if(!Oe(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ir(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=V.isBuffer(e)?e:V.from(e,"base64"),s=i.subarray(0,16),n=i.subarray(i.length-16),a=i.subarray(16,i.length-16),l=fs("aes-256-gcm",r,s);l.setAuthTag(n);let o=l.update(a),c=l.final(),h=o.length+c.length,f=V.allocUnsafe(h);return o.copy(f,0),c.copy(f,o.length),f.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return S()}isServerMode(){return!S()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t),{consoleText:s,fileText:n}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let l=s.split(`
16
+ `),o=Math.max(...l.map((g)=>g.length))+2,c=`\u250C${"\u2500".repeat(o)}\u2510`,h=`\u2514${"\u2500".repeat(o)}\u2518`,f=l.map((g)=>{return this.formatConsoleMessage({timestamp:r,message:p.cyan(g),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:p.cyan(c),showTimestamp:!1})),f.forEach((g)=>console.error(g)),console.error(this.formatConsoleMessage({timestamp:r,message:p.cyan(h),showTimestamp:!1}))}else if(!S())console.error(`${i} ${this.environment}.INFO: [BOX] ${n}`);let a=`${i} ${this.environment}.INFO: [BOX] ${n}
17
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}async prompt(e){if(S())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${p.cyan("?")} ${e} (y/n) `);let r=(i)=>{let s=i.toString().trim().toLowerCase();b.stdin.removeListener("data",r);try{if(typeof b.stdin.setRawMode==="function")b.stdin.setRawMode(!1)}catch{}b.stdin.pause(),console.error(""),t(s==="y"||s==="yes")};try{if(typeof b.stdin.setRawMode==="function")b.stdin.setRawMode(!0)}catch{}b.stdin.resume(),b.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(o,c)=>{if(c==="%")return"%";if(l>=t.length)return o;let h=t[l++];switch(c){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return o}}),l<t.length)r+=` ${t.slice(l).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`}let{consoleText:i,fileText:s}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${p.blue("\u25D0")} `;console.error(`${l}${a} ${p.cyan(i)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${s}
18
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(n)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!b.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),s=e.barLength-i,n=p.green("\u2501".repeat(i)),a=p.gray("\u2501".repeat(s)),l=`[${n}${a}]`,o=`${r}%`.padStart(4),c=e.message?` ${e.message}`:"",h=this.options.showIcons===!1?"":t||r===100?p.green("\u2713"):p.blue("\u25B6"),f=this.options.showTags!==!1&&this.name?` ${p.gray(this.formatTag(this.name))}`:"",g=`\r${h}${f} ${l} ${o}${c}`,u=b.stdout.columns||80,d=" ".repeat(Math.max(0,u-g.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${g}${d}`,b.stdout.write(e.lastRenderedLine),t)b.stdout.write(`
19
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||S()||!b.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(S()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Me(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let s=ue(this.config.logDirectory,i);if(e.before)try{if((await fe(s)).mtime>=e.before)continue}catch(n){console.error(`Failed to get stats for file ${s}:`,n);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await Ne(i),console.warn(`Deleted log file: ${i}`)}catch(s){console.error(`Failed to delete log file ${i}:`,s)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function di(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:s=()=>!0,fallback:n}=t,a=Error("Unknown error occurred");for(let l=0;l<=r;l++)try{return await e()}catch(o){if(a=o instanceof Error?o:Error(String(o)),l===r||!s(a))break;if(i>0)await new Promise((c)=>setTimeout(c,i))}if(n!==void 0)return n;throw a instanceof Error?a:Error(`Unknown error: ${String(a)}`)}function pi(e){return e instanceof F}function Xs(e){return e instanceof rt}function en(e){if(pi(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((t)=>e.message.toLowerCase().includes(t.toLowerCase()))}class lt{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:i,useCamelCase:s=!0,useBackwardCompatibility:n=!0,customParsers:a={},verbose:l=!1,trackPerformance:o=!0}=r,c=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=i||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],h,{useCamelCase:s,useBackwardCompatibility:n,customParsers:a,verbose:l,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(o)return ke.track("applyEnvironmentVariables",c,{configName:e});return c()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,i){for(let[s,n]of Object.entries(e)){let a=[...t,s],l=a.map((h)=>this.formatEnvKey(h,i.useCamelCase)),o=`${r}_${l.join("_")}`,c=i.useBackwardCompatibility?`${r}_${a.map((h)=>h.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof n==="object"&&n!==null&&!Array.isArray(n))this.processObject(n,a,r,i);else{let h=Pe.env[o]||(c?Pe.env[c]:void 0);if(h!==void 0){if(i.verbose){let f=Pe.env[o]?o:c}try{e[s]=this.parseEnvironmentValue(h,typeof n,o,i.customParsers,i.configName)}catch(f){if(f instanceof it)throw f;throw se.envVar(o,h,typeof n,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,s){for(let[n,a]of Object.entries(i))try{return a(e)}catch{continue}for(let n of this.defaultParsers)if(n.canParse(e,t))try{return n.parse(e)}catch{throw se.envVar(r,e,`${t} (via ${n.name} parser)`,s)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,s]of Object.entries(Pe.env))if(i.startsWith(r)&&s!==void 0)t[i]=s;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(s){i.push(`Cannot parse value "${t}" as ${r}: ${s}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:s="text"}=r,n=i||this.generateEnvPrefix(e),a=[];switch(this.extractEnvVarInfo(t,[],n,a),s){case"markdown":return this.formatAsMarkdown(a,e);case"json":return JSON.stringify(a,null,2);default:return this.formatAsText(a,e)}}extractEnvVarInfo(e,t,r,i){for(let[s,n]of Object.entries(e)){let a=[...t,s],l=`${r}_${a.map((o)=>this.formatEnvKey(o,!0)).join("_")}`;if(typeof n==="object"&&n!==null&&!Array.isArray(n))this.extractEnvVarInfo(n,a,r,i);else i.push({key:l,type:Array.isArray(n)?"array":typeof n,description:`Configuration for ${a.join(".")}`,example:this.generateExample(n)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
20
+
21
+ `;for(let i of e)r+=`${i.key}
22
+ `,r+=` Type: ${i.type}
23
+ `,r+=` Description: ${i.description}
24
+ `,r+=` Example: ${i.example}
25
+
26
+ `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
27
+
28
+ `;r+=`| Variable | Type | Description | Example |
29
+ `,r+=`|----------|------|-------------|----------|
30
+ `;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
31
+ `;return r}}function tn(e,t){let r=$i("process");if(typeof r>"u"||!r.env)return t;let i=r.env[e];return i!==void 0?i:t}function yi(e,t,r={}){return bi(e,t,r,new WeakMap)}function bi(e,t,r,i){let{arrayMergeMode:s="replace",skipNullish:n=!1,customMerger:a}=r;if(t===null||t===void 0)return n?e:t;if(a){let l=a(e,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(e))return wi(e,t,s,i);if(!_(t)||!_(e))return t;return an(e,t,r,i)}function wi(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return rn(e,t);case"smart":return sn(e,t,i);default:return t}return t}function rn(e,t){let r=[...t];for(let i of e)if(!r.some((s)=>Pt(s,i)))r.push(i);return r}function sn(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(_(t[0])&&_(e[0]))return nn(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let s of e)if(!i.includes(s))i.push(s);return i}return t}function nn(e,t,r){let i=[...t];for(let s of e){if(!_(s)){i.push(s);continue}let n=["id","name","key","path","type"],a=!1;for(let l of n)if(l in s){if(i.find((o)=>_(o)&&(l in o)&&o[l]===s[l])){a=!0;break}}if(!a)i.push(s)}return i}function an(e,t,r,i){let s=t;if(_(s)&&i.has(s))return i.get(s);let n={...e};if(_(s))i.set(s,n);for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;let l=s[a],o=n[a];if(r.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){n[a]=l;continue}if(_(l)&&_(o))n[a]=bi(o,l,r,i);else if(Array.isArray(l)||Array.isArray(o))n[a]=wi(o,l,r.arrayMergeMode||"smart",i);else n[a]=l}return n}function er(e,t,r="replace"){return yi(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Pt(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(!Pt(e[r],t[r]))return!1;return!0}if(_(e)&&_(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!Pt(e[s],t[s]))return!1}return!0}return!1}function _(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class ct{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:s=!0,cacheTtl:n,trackPerformance:a=!0,verbose:l=!1}=r;if(s){let c=ye.getWithFileCheck("file",e);if(c){if(l)console.log(`Configuration loaded from cache: ${e}`);return c}}let o=async()=>{if(!Be(e))return null;try{let c=`?t=${Date.now()}`,h=await import(e+c),f=h.default||h,g="default"in h,u=Object.keys(h).length>0;if(!g&&!u)throw new Ce(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new Ce(e,Error("Configuration must export a valid object"),"unknown");let d={config:er(t,f,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(s)ye.setWithFileCheck("file",d,e,n);return d}catch(c){throw c instanceof Error?se.configLoad(e,c):se.configLoad(e,Error(String(c)))}};if(a)return ke.track("loadFromPath",o,{path:e});return o()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let s=await this.loadFromPath(i,t,r);if(s)return s}catch(s){if(s instanceof Error&&s.name==="ConfigLoadError")throw s;if(r.verbose)console.warn(`Failed to load config from ${i}:`,s)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),s=[];for(let n of i)for(let a of this.extensions)s.push(wt(t,`${n}${a}`));return s}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return di(async()=>{return Be(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!Be(e))return i;if(t||r){let s=this.generateNamePatterns(t||"",r);for(let n of s)for(let a of this.extensions){let l=wt(e,`${n}${a}`);if(await this.checkFileAccess(l))i.push(l)}}else try{let{readdirSync:s}=await import("fs"),n=s(e);for(let a of n)if(this.looksLikeConfigFile(a)){let l=wt(e,a);if(await this.checkFileAccess(l))i.push(l)}}catch{return[]}return i}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!Be(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:s}=await import("fs"),n=s(e,"utf8");JSON.parse(n)}catch(s){t.push(`Invalid JSON syntax: ${s}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let s=await this.loadFromPath(i,{},t);if(s)r.set(i,s.config)}catch(s){if(t.verbose)console.warn(`Failed to preload ${i}:`,s)}})),r}}class tr{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:s=!0,validateTypes:n=!0,customRules:a=[],trackPerformance:l=!0,verbose:o=!1}=r,c=async()=>{let h=[],f=[],g={stopOnFirstError:i,validateRequired:s,validateTypes:n,customRules:a,trackPerformance:l,verbose:o};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,g);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...a],g);else return this.validateWithJSONSchema(e,t,g)}catch(u){return h.push({path:"",message:`Validation failed: ${u}`,rule:"system"}),{isValid:!1,errors:h,warnings:f}}};if(l)return await ke.track("validateConfiguration",c);return c()}async validateWithSchemaFile(e,t,r){try{if(!ws(t))throw new Ee(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),s=i.default||i;if(Array.isArray(s))return this.validateWithRules(e,s,r);else return this.validateWithJSONSchema(e,s,r)}catch(i){throw new Ee(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],s=[];return this.validateObjectAgainstSchema(e,t,"",i,s,r),{isValid:i.length===0,errors:i,warnings:s}}validateObjectAgainstSchema(e,t,r,i,s,n){if(n.validateTypes&&t.type){let a=Array.isArray(e)?"array":typeof e,l=Array.isArray(t.type)?t.type:[t.type];if(!l.includes(a)){if(i.push({path:r,message:`Expected type ${l.join(" or ")}, got ${a}`,expected:l.join(" or "),actual:a,rule:"type"}),n.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),n.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let a=0;a<e.length;a++){let l=r?`${r}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(e[a],t.items,l,i,s,n),n.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let a=e;if(n.validateRequired&&t.required){for(let l of t.required)if(!(l in a)){if(i.push({path:r?`${r}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),n.stopOnFirstError)return}}if(t.properties){for(let[l,o]of Object.entries(t.properties))if(l in a){let c=r?`${r}.${l}`:l;if(this.validateObjectAgainstSchema(a[l],o,c,i,s,n),n.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let o of Object.keys(a))if(!l.has(o))s.push({path:r?`${r}.${o}`:o,message:`Additional property '${o}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],s=[];for(let n of t)try{let a=this.getValueByPath(e,n.path),l=this.validateWithRule(a,n,n.path);if(i.push(...l),r.stopOnFirstError&&i.length>0)break}catch(a){i.push({path:n.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:s}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let s=Array.isArray(e)?"array":typeof e;if(s!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${s}`,expected:t.type,actual:s,rule:"type"})}if(t.min!==void 0){let s=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(s<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:s,rule:"min"})}if(t.max!==void 0){let s=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(s>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:s,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let s=t.validator(e);if(s)i.push({path:r,message:t.message||s,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let s of r)if(i&&typeof i==="object"&&s in i)i=i[s];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,s,n,a]=i;t.push({path:s,required:!n,type:this.mapTypeScriptType(a)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:xi},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class rr{fileLoader=new ct;envProcessor=new lt;validator=new tr;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:s,validate:n,...a}=e;try{if(r?.enabled){let o=this.checkCache(a.name||"",a);if(o)return o}let l;try{l=await this.loadConfigurationStrategies(a,!0,r)}catch(o){let c=a.__strictErrorHandling;if(o instanceof Error&&o.name==="ConfigNotFoundError"){if(c)throw o;l={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`No configuration file found for "${a.name||"config"}", using defaults with environment variables`]}}else if(o instanceof Error&&o.name==="ConfigLoadError"){let h=o.message.includes("EACCES")||o.message.includes("EPERM")||o.message.includes("permission denied"),f=!h&&(o.message.includes("syntax")||o.message.includes("Expected")||o.message.includes("Unexpected")||o.message.includes("BuildMessage")||o.message.includes("errors building")),g=o.message.includes("Configuration must export a valid object")||o.message.includes("Configuration file is empty and exports nothing");if(c&&(g||h))throw o;if(f&&(!c||!g))l={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!c)l={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${o.message}`]};else throw o}else l={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${o instanceof Error?o.message:String(o)}`]}}if(s||n)await this.validateConfiguration(l.config,s,n,a.name);if(r?.enabled&&l)this.cacheResult(a.name||"",l,r,a);if(i?.enabled){let o={operation:"loadConfig",duration:Date.now()-t,configName:a.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(o);if(i.slowThreshold&&o.duration>i.slowThreshold)J.warn(`Slow configuration loading detected: ${o.duration}ms for ${a.name}`);l.metrics=o}return l}catch(l){let o=Date.now()-t;throw J.error(`Configuration loading failed after ${o}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:s,cwd:n,configDir:a,defaultConfig:l,checkEnv:o=!0,arrayStrategy:c="replace",verbose:h=!1}=e,f=n||ne.cwd(),g=[],u=await this.loadLocalConfiguration(i,s,f,a,l,c,h,o,r);if(u)return g.push(...this.getLocalSearchPaths(i,s,f,a)),this.finalizeResult(u,g,o,i,h);let d=await this.loadHomeConfiguration(i,s,l,c,h,o);if(d)return g.push(...this.getHomeSearchPaths(i,s)),this.finalizeResult(d,g,o,i,h);let m=await this.loadPackageJsonConfiguration(i,s,f,l,c,h,o);if(m)return g.push(D(f,"package.json")),this.finalizeResult(m,g,o,i,h);if(g.push(...this.getAllSearchPaths(i,s,f,a)),t)throw se.configNotFound(i,g,s);return{...await this.applyEnvironmentVariables(i,l,o,h),warnings:[`No configuration file found for "${i}"${s?` or alias "${s}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,s,n,a,l,o){let c=l?ve(e,s,a):s,h=this.getLocalDirectories(r,i);for(let f of h){if(a)J.info(`Searching for configuration in: ${f}`);let g=this.fileLoader.generateConfigPaths(e,f,t),u=await this.fileLoader.tryLoadFromPaths(g,c,{arrayStrategy:n,verbose:a,cacheTtl:o?.ttl,useCache:!o?.ttl||o.ttl>100});if(u){if(a)J.success(`Configuration loaded from: ${u.source.path}`);return u}}return null}async loadHomeConfiguration(e,t,r,i,s,n){if(!e)return null;let a=n?ve(e,r,s):r,l=[D(oe(),".config",e),D(oe(),".config"),oe()];for(let o of l){if(s)J.info(`Checking home directory: ${o}`);let c=this.fileLoader.generateConfigPaths(e,o,t),h=await this.fileLoader.tryLoadFromPaths(c,a,{arrayStrategy:i,verbose:s});if(h){if(s)J.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(e,t,r,i,s,n,a){let l=a?ve(e,i,n):i;try{let o=D(r,"package.json");if(!Mt(o))return null;let c=await import(o),h=c[e],f=e;if(!h&&t)h=c[t],f=t;if(h&&typeof h==="object"&&!Array.isArray(h)){if(n)J.success(`Configuration loaded from package.json: ${f}`);return{config:er(l,h,s),source:{type:"package.json",path:o,priority:30,timestamp:new Date}}}}catch(o){if(n)J.warn("Failed to load package.json:",[o instanceof Error?o:Error(String(o))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:ve(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,s){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let s=[];if(r){let n=r(e);if(n)s.push(...n)}if(t){let n=await this.validator.validateConfiguration(e,t);if(!n.isValid)s.push(...n.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(s.length>0)throw se.configValidation(i||"unknown",s,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return ye.get(r)||null}cacheResult(e,t,r,i){let s=this.generateCacheKey(e,i);ye.set(s,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,D(e,"config"),D(e,".config"),t?D(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let s=[];return s.push(...this.getLocalSearchPaths(e,t,r,i)),s.push(...this.getHomeSearchPaths(e,t)),s.push(D(r,"package.json")),s}getLocalSearchPaths(e,t,r,i){let s=this.getLocalDirectories(r,i),n=[];for(let a of s)n.push(...this.fileLoader.generateConfigPaths(e,a,t));return n}getHomeSearchPaths(e,t){if(!e)return[];let r=[D(oe(),".config",e),D(oe(),".config"),oe()],i=[];for(let s of r)i.push(...this.fileLoader.generateConfigPaths(e,s,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function Gr(e){let t=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),r=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return t||r}async function on(e){return te.loadConfig({...e,__strictErrorHandling:!0})}async function vi(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let i;if(r)i=await te.loadConfig(e);else i=await te.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??t}catch(i){let s=i instanceof Error?i.name:"UnknownError",n=i instanceof Error?i.message:String(i);if(!(s==="ConfigNotFoundError"||s==="ConfigLoadError"||s==="ConfigValidationError"||n.includes("config"))&&e.verbose)J.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let a=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await te.applyEnvironmentVariables(a.name||"",t,!0,a.verbose||!1))?.config??t;return t}}async function ln(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await te.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Gr(r)))return(await te.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await te.loadConfig({...e,cwd:e.cwd||ne.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Gr(t)))return(await te.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function cn(e,t,r="replace"){let i=new ct;try{let s=await i.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return s?s.config:null}catch{return null}}function ve(e,t,r=!1){let i=new lt,s=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function n(a,l=[]){let o={...a};for(let[c,h]of Object.entries(a)){let f=[...l,c],g=[`${s}_${f.join("_").toUpperCase()}`,`${s}_${f.map((m)=>m.toUpperCase()).join("")}`,`${s}_${f.map((m)=>m.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],u,d;for(let m of g)if(u=ne.env[m],u!==void 0){d=m;break}if(u!==void 0&&d)if(typeof h==="boolean")o[c]=["true","1","yes"].includes(u.toLowerCase());else if(typeof h==="number"){let m=Number(u);if(!Number.isNaN(m))o[c]=m}else if(Array.isArray(h))try{o[c]=JSON.parse(u)}catch{o[c]=u.split(",").map((m)=>m.trim())}else o[c]=u;else if(h&&typeof h==="object"&&!Array.isArray(h))o[c]=n(h,f)}return o}return n(t)}function hn(e){let t=D(ne.cwd(),e.configDir),r=D(ne.cwd(),e.generatedDir),i=D(r,"config-types.ts");if(!Mt(Sr(i)))Zi(Sr(i),{recursive:!0,mode:511});let s=Mt(t)?qi(t).map((a)=>a.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],n=`// Generated by bunfig v${Ln}
32
+ export type ConfigNames = ${s.length?`'${s.join("' | '")}'`:"string"}
33
+ `;Yi(i,n,{mode:438})}function fn(e){let t=null,r=null,i=()=>{if(!r)r=vi(e).then((n)=>{return t=n,n},(n)=>{let a="defaultConfig"in e?e.defaultConfig:{};if(t=a,"verbose"in e&&e.verbose)J.warn("Config loading failed, using defaults:",[n instanceof Error?n:Error(String(n))]);return a});return r},s="defaultConfig"in e?e.defaultConfig:{};return t=s,i(),new Proxy({},{get(n,a){if(t)return t[a];let l=s[a];return i(),l},has(n,a){return a in(t||s)},ownKeys(){return Object.keys(t||s)},getOwnPropertyDescriptor(n,a){return Object.getOwnPropertyDescriptor(t||s,a)},set(n,a,l){if(!t)t={...s};return t[a]=l,!0}})}function un(e){let t=_r(Cs.cwd(),e?.configDir||"./config");function r(){if(!vs(t))return[];let s=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),n=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],a=$s(t).filter((o)=>s.has(vt(o))).map((o)=>({base:o.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:o})),l=new Map;for(let{base:o,file:c}of a){let h=vt(c).toLowerCase(),f=l.get(o);if(!f){l.set(o,c);continue}let g=vt(f).toLowerCase();if(n.indexOf(h)<n.indexOf(g))l.set(o,c)}return Array.from(l.entries()).map(([o,c])=>({base:o,file:c})).sort((o,c)=>o.base.localeCompare(c.base))}function i(){let s=r(),n=s.map((o)=>o.base),a=n.length?n.map((o)=>`'${o}'`).join(" | "):"string",l=s.length?`{
34
+ ${s.map((o)=>{let c=_r(t,o.file).replace(/\\/g,"/");return` '${o.base}': typeof import('${c}').default`}).join(`,
35
+ `)}
36
+ }`:"Record<string, any>";return`export type ConfigNames = ${a}
37
+ export type ConfigByName = ${l}
38
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
39
+ export type ConfigOf = Config
40
+ `}return{name:"bunfig-plugin",setup(s){s.onResolve({filter:/^virtual:bunfig-types$/},(n)=>{return{path:n.path,namespace:"bunfig-virtual"}}),s.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:i(),loader:"ts"}})}}}var $i,ye,ke,Ci,gn,mn,Vr,We,Bt,P,$,dn,Zr,pn,qr,yn,bn,St,wn,Yr,Xr,xt,vn,$n,Cn,En,Ke,Ei,kn,B,Sn,xn,ei,ze,It,x,p,An,ti,Tn,ri,On,Mn,At,Nn,ii,si,Pn,Tt,Bn,In,Rn,Dn,Fn,Je,ki,jn,Ln="0.15.6",F,rt,Ce,Rt,Dt,it,Ft,jt,Ee,Lt,_t,se,Si,xi,J,te,Ai,Ti,_n=Ls(async()=>{$i=import.meta.require,ye=new Zt,ke=new qt,Ci={createKey:_s,isEquivalent:Us,estimateMemoryUsage:Qs},gn=Ve(Nt.cwd(),"config"),mn=Ve(Nt.cwd(),"src/generated"),Vr=Ge.env.CLARITY_LOG_DIR||ts(zs(),"logs"),We={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Vr,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Bt=await Js(),P={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},$=P,dn=P.red,Zr=P.green,pn=P.yellow,qr=P.blue,yn=P.magenta,bn=P.cyan,St=P.white,wn=P.gray,Yr=P.bgRed,Xr=P.bgYellow,xt=P.bold,vn=P.dim,$n=P.italic,Cn=P.underline,En=P.reset,Ke={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ei={debug:"\uD83D\uDD0D",info:qr("\u2139"),success:Zr("\u2713"),warning:Xr(St(xt(" WARN "))),error:Yr(St(xt(" ERROR ")))},kn=new Xe("stacks"),B=new Xe("bunfig",{showTags:!0}),Sn=R($e.cwd(),"config"),xn=R($e.cwd(),"src/generated"),ei=He.env.CLARITY_LOG_DIR||Xi(Zs(),"logs"),ze={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ei,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},It=await qs(),x={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},p=x,An=x.red,ti=x.green,Tn=x.yellow,ri=x.blue,On=x.magenta,Mn=x.cyan,At=x.white,Nn=x.gray,ii=x.bgRed,si=x.bgYellow,Pn=x.bgGray,Tt=x.bold,Bn=x.dim,In=x.italic,Rn=x.underline,Dn=x.strikethrough,Fn=x.reset,Je={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ki={debug:"\uD83D\uDD0D",info:ri("\u2139"),success:ti("\u2713"),warning:si(At(Tt(" WARN "))),error:ii(At(Tt(" ERROR ")))},jn=new tt("stacks"),F=class extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},rt=class extends F{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r?` or alias "${r}"`:"";super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},Ce=class extends F{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},Rt=class extends F{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Dt=class extends F{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}},it=class extends F{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}},Ft=class extends F{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},jt=class extends F{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Ee=class extends F{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Lt=class extends F{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}},_t=class extends F{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},se={configNotFound(e,t,r){return new rt(e,t,r)},configLoad(e,t,r){return new Ce(e,t,r)},configValidation(e,t,r){return new Rt(e,t,r)},configMerge(e,t,r,i){return new Dt(e,t,r,i)},envVar(e,t,r,i){return new it(e,t,r,i)},fileSystem(e,t,r){return new Ft(e,t,r)},typeGeneration(e,t,r){return new jt(e,t,r)},schemaValidation(e,t,r){return new Ee(e,t,r)},browserConfig(e,t,r,i){return new Lt(e,t,r,i)},plugin(e,t,r){return new _t(e,t,r)}},Si={replace:"replace",concat:"concat",smart:"smart"},xi=/^https?:\/\//,J=new tt("bunfig",{showTags:!0}),te=new rr,Ai=D(ne.cwd(),"config"),Ti=D(ne.cwd(),"src/generated")});function Un(e,t={}){let r=Ze.cwd();while(r.includes("storage"))r=Ur(r,"..");let i=Ur(r,e||"");if(t?.relative)return ks(Ze.cwd(),i);return i}var Qn=Ze.env.CLARITY_LOG_DIR||Es(Un(),"logs"),Oi={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Qn,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},st={...Oi},Fo=(async()=>{try{let{loadConfig:e}=await _n().then(()=>ui),t=await e({name:"clarity",alias:"logging",defaultConfig:Oi,cwd:Ze.cwd()});if(t)Object.assign(st,t)}catch{}return st})();function A(){if(ee.env.NODE_ENV==="test"||ee.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Wn(){if(ee.env.NODE_ENV==="test"||ee.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ee<"u"){let e=ee.type;if(e==="renderer"||e==="worker")return!1;return!!(ee.versions&&(ee.versions.node||ee.versions.bun))}return!1}class Mi{async format(e){let t=await Wn(),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:pe.pid,hostname:t(),environment:pe.env.NODE_ENV||"development",platform:pe.platform,version:pe.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:pe.env.NODE_ENV||pe.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var T={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},y=T,jo=T.red,Kn=T.green,Lo=T.yellow,zn=T.blue,_o=T.magenta,Uo=T.cyan,ni=T.white,Qo=T.gray,Jn=T.bgRed,Hn=T.bgYellow,Wo=T.bgGray,ai=T.bold,Ko=T.dim,zo=T.italic,Jo=T.underline,Ho=T.strikethrough,Go=T.reset,Ot={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Gn={debug:"\uD83D\uDD0D",info:zn("\u2139"),success:Kn("\u2713"),warning:Hn(ni(ai(" WARN "))),error:Jn(ni(ai(" ERROR ")))};class ht{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...st},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Mi,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??w.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),n=this.generateKey();this.currentKeyId=s,this.keys.set(s,n),this.encryptionKeys.set(s,{key:n,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Ot,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Ot};return{...Ot,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:st.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!A()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,s=0,n=3,a=1000;while(s<n)try{try{try{await Os(this.config.logDirectory,zr.F_OK|zr.W_OK)}catch(o){if(o instanceof Error&&"code"in o)if(o.code==="ENOENT")await Ms(this.config.logDirectory,{recursive:!0,mode:493});else if(o.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw o;else throw o}}catch(o){throw console.error("Debug: [writeToFile] Failed to create log directory:",o),o}let l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Z.from(e);try{if(!Ie(this.currentLogFile))await Et(this.currentLogFile,"",{mode:420});if(i=Kr(this.currentLogFile,"a",420),Ts(i,l,{flag:"a"}),Wr(i),i!==void 0)Ct(i),i=void 0;if((await me(this.currentLogFile)).size===0){if(await Et(this.currentLogFile,l,{flag:"w",mode:420}),(await me(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(o){let c=o;if(c.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(c.code)){if(s<n-1){let h=typeof c.message==="string"?c.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${n}:`,h);let f=a*2**s;await new Promise((g)=>setTimeout(g,f)),s++;continue}}if(c?.code&&["ENOSPC","EDQUOT"].includes(c.code))throw Error(`Disk quota exceeded or no space left on device: ${c.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",c),c}finally{if(i!==void 0)try{Ct(i)}catch(o){console.error("Debug: [writeToFile] Error closing file descriptor:",o)}}}catch(l){if(s===n-1){let c=l,h=typeof c.message==="string"?c.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),l}s++;let o=a*2**(s-1);await new Promise((c)=>setTimeout(c,o))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,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 de(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 de(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return de(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(A())return;if(!this.shouldWriteToFile())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 e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,a],[,l])=>l.createdAt.getTime()-a.createdAt.getTime()),s=typeof e.maxKeys==="number"?e.maxKeys:1,n=Math.max(1,s);if(i.length>n)for(let[a]of i.slice(n))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return $t(16).toString("hex")}generateKey(){return $t(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=$t(16),i=Ss("aes-256-gcm",t,r),s=Z.isBuffer(e)?e:Z.from(e,"utf8"),n=i.update(s),a=i.final(),l=n.length+a.length,o=i.getAuthTag(),c=Z.allocUnsafe(16+l+16);return r.copy(c,0),n.copy(c,16),a.copy(c,16+n.length),o.copy(c,16+l),{encrypted:c,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Hr(),s=[];i.on("data",(n)=>s.push(n)),i.on("end",()=>t(Z.from(Z.concat(s)))),i.on("error",r),i.write(e),i.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(A())return;if(!this.shouldWriteToFile())return;let e=await me(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,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await Re(this.config.logDirectory),n=s.filter((o)=>o.startsWith(this.name)&&/\.log\.\d+$/.test(o)).sort((o,c)=>{let h=Number.parseInt(o.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),a=n.length>0?Number.parseInt(n[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${r}.${a}`;if(await me(r).catch(()=>null))try{if(await Jr(r,l),t.compress)try{let o=`${l}.gz`;await this.compressLogFile(l,o),await De(l)}catch(o){console.error("Error compressing rotated file:",o)}if(n.length===0&&!s.some((o)=>o.endsWith(".log.1")))try{let o=`${r}.1`;await Et(o,"")}catch(o){console.error("Error creating backup file:",o)}}catch(o){console.error(`Error during rotation: ${o instanceof Error?o.message:String(o)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),n=r.replace(/\.log$/,`-${s}.log`);if(await me(r).catch(()=>null))await Jr(r,n)}if(this.currentLogFile=i,t.maxFiles){let s=(await Re(this.config.logDirectory)).filter((n)=>n.startsWith(this.name)).sort((n,a)=>a.localeCompare(n));for(let n of s.slice(t.maxFiles))await De(de(this.config.logDirectory,n))}}}async compressLogFile(e,t){let r=Qr(e),i=As(t),s=Hr();await Bs(r,s,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}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()})),Ie(this.currentLogFile))try{let e=Kr(this.currentLogFile,"r+");Wr(e),Ct(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(!A()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Re(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await De(de(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}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.shouldStyleConsole()?y.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||A())return!1;let e=typeof w.env.NO_COLOR<"u",t=w.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof w.stderr<"u"&&w.stderr.isTTY||typeof w.stdout<"u"&&w.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:s,level:n,showTimestamp:a=!0}=e,l=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(a)u.push(t);if(n==="warning")u.push("WARN");else if(n==="error")u.push("ERROR");else if(r)u.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)u.push(i.replace(/[[\]]/g,""));return u.push(s),u.join(" ")}let o=w.stdout.columns||120,c="";if(n==="warning"||n==="error")c=`${r} ${s}`;else if(n==="info"||n==="success")c=`${r} ${i} ${s}`;else c=`${r} ${i} ${y.cyan(s)}`;if(!a)return c.trim();let h=l(c).trim().length,f=l(t).length,g=Math.max(1,o-2-h-f);return`${c.trim()}${" ".repeat(g)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(n,a)=>{let l=Number.parseInt(a,10);return l<t[0].length?String(t[0][l]):n});let r=/%([sdijfo%])/g,i=0,s=e.replace(r,(n,a)=>{if(a==="%")return"%";if(i>=t.length)return n;let l=t[i++];switch(a){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return n}});if(i<t.length)s+=` ${t.slice(i).map((n)=>typeof n==="object"?JSON.stringify(n,null,2):String(n)).join(" ")}`;return s}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,s)=>{let n=y.underline(y.blue(i)),a=this.toAbsoluteFilePath(s);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(a)}`,o="\x1B]8;;",c="\x1B\\";return`\x1B]8;;${l}\x1B\\${n}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${s}\x1B\\${n}\x1B]8;;\x1B\\`;return n}),t=t.replace(/`([^`]+)`/g,(r,i)=>y.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>y.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>y.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>y.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>y.strikethrough(i)),t}supportsHyperlinks(){if(A())return!1;let e=w.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=w.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Ns(t)||t.startsWith("./")||t.startsWith("../"))t=Ps(t);else return null;return Ie(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let i=new Date,s=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),a,l;if(t instanceof Error)a=t.message,l=t.stack;else a=this.formatMessage(t,r);let{consoleText:o,fileText:c}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":Gn[e],g=this.options.showTags!==!1&&this.name?y.gray(this.formatTag(this.name)):"",u;switch(e){case"debug":u=this.formatConsoleMessage({timestamp:s,icon:f,tag:g,message:y.gray(o),level:e}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:s,icon:f,tag:g,message:o,level:e}),console.warn(u);break;case"success":u=this.formatConsoleMessage({timestamp:s,icon:f,tag:g,message:y.green(o),level:e}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:s,icon:f,tag:g,message:o,level:e}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:s,icon:f,tag:g,message:o,level:e}),console.error(u),l){let d=l.split(`
41
+ `);for(let m of d)if(m.trim()&&!m.includes(a))console.error(this.formatConsoleMessage({timestamp:s,message:y.gray(` ${m}`),level:e,showTimestamp:!1}))}break}}else if(!A()){if(console.error(`${n} ${this.environment}.${e.toUpperCase()}: ${a}`),l)console.error(l)}let h=`${n} ${this.environment}.${e.toUpperCase()}: ${c}
42
+ `;if(l)h+=`${l}
43
+ `;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(e,t=""){let r={update:(s,n)=>{},finish:(s)=>{},interrupt:(s,n)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!A()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(s,n)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,s),this.activeProgressBar.total),n!==void 0)this.activeProgressBar.message=n;if(this.shouldStyleConsole()&&!A()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(s)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,s)},interrupt:(s,n="info")=>{if(!A()&&w.stdout.isTTY)w.stdout.write(`
44
+ `);if(this[n==="warning"?"warn":n](s),this.activeProgressBar&&this.shouldStyleConsole()&&!A()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?y.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":y.blue("\u25D0"),tag:r,message:`${y.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),s=Math.round(i-t),n=`${e} completed in ${s}ms`,a=new Date,l=this.formatConsoleTimestamp(a),o=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${n}`;if(r)o+=` ${JSON.stringify(r)}`;if(o+=`
45
+ `,o=o.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?y.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":y.green("\u2713"),tag:c,message:`${n}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!A())console.error(o.trim());if(this.shouldWriteToFile())await this.writeToFile(o)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new ht(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(A())throw Error("createReadStream is not supported in browser environments");if(!Ie(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Qr(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=Z.isBuffer(e)?e:Z.from(e,"base64"),s=i.subarray(0,16),n=i.subarray(i.length-16),a=i.subarray(16,i.length-16),l=xs("aes-256-gcm",r,s);l.setAuthTag(n);let o=l.update(a),c=l.final(),h=o.length+c.length,f=Z.allocUnsafe(h);return o.copy(f,0),c.copy(f,o.length),f.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return A()}isServerMode(){return!A()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t),{consoleText:s,fileText:n}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let l=s.split(`
46
+ `),o=Math.max(...l.map((g)=>g.length))+2,c=`\u250C${"\u2500".repeat(o)}\u2510`,h=`\u2514${"\u2500".repeat(o)}\u2518`,f=l.map((g)=>{return this.formatConsoleMessage({timestamp:r,message:y.cyan(g),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:y.cyan(c),showTimestamp:!1})),f.forEach((g)=>console.error(g)),console.error(this.formatConsoleMessage({timestamp:r,message:y.cyan(h),showTimestamp:!1}))}else if(!A())console.error(`${i} ${this.environment}.INFO: [BOX] ${n}`);let a=`${i} ${this.environment}.INFO: [BOX] ${n}
47
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}async prompt(e){if(A())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${y.cyan("?")} ${e} (y/n) `);let r=(i)=>{let s=i.toString().trim().toLowerCase();w.stdin.removeListener("data",r);try{if(typeof w.stdin.setRawMode==="function")w.stdin.setRawMode(!1)}catch{}w.stdin.pause(),console.error(""),t(s==="y"||s==="yes")};try{if(typeof w.stdin.setRawMode==="function")w.stdin.setRawMode(!0)}catch{}w.stdin.resume(),w.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(o,c)=>{if(c==="%")return"%";if(l>=t.length)return o;let h=t[l++];switch(c){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return o}}),l<t.length)r+=` ${t.slice(l).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`}let{consoleText:i,fileText:s}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?y.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${y.blue("\u25D0")} `;console.error(`${l}${a} ${y.cyan(i)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${s}
48
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(n)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!w.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),s=e.barLength-i,n=y.green("\u2501".repeat(i)),a=y.gray("\u2501".repeat(s)),l=`[${n}${a}]`,o=`${r}%`.padStart(4),c=e.message?` ${e.message}`:"",h=this.options.showIcons===!1?"":t||r===100?y.green("\u2713"):y.blue("\u25B6"),f=this.options.showTags!==!1&&this.name?` ${y.gray(this.formatTag(this.name))}`:"",g=`\r${h}${f} ${l} ${o}${c}`,u=w.stdout.columns||80,d=" ".repeat(Math.max(0,u-g.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${g}${d}`,w.stdout.write(e.lastRenderedLine),t)w.stdout.write(`
49
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||A()||!w.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(A()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Re(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let s=de(this.config.logDirectory,i);if(e.before)try{if((await me(s)).mtime>=e.before)continue}catch(n){console.error(`Failed to get stats for file ${s}:`,n);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await De(i),console.warn(`Deleted log file: ${i}`)}catch(s){console.error(`Failed to delete log file ${i}:`,s)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var Vo=new ht("stacks");class H extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}}class Ni extends H{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],s="";if(i.length===1)s=` or alias "${i[0]}"`;else if(i.length>1)s=` or aliases ${i.map((n)=>`"${n}"`).join(", ")}`;super(`Configuration "${e}"${s} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}}class nt extends H{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}}class Pi extends H{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class Bi extends H{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class ir extends H{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}}class Ii extends H{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class Ri extends H{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class at extends H{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class Di extends H{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}}class Fi extends H{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}}var be={configNotFound(e,t,r){return new Ni(e,t,r)},configLoad(e,t,r){return new nt(e,t,r)},configValidation(e,t,r){return new Pi(e,t,r)},configMerge(e,t,r,i){return new Bi(e,t,r,i)},envVar(e,t,r,i){return new ir(e,t,r,i)},fileSystem(e,t,r){return new Ii(e,t,r)},typeGeneration(e,t,r){return new Ri(e,t,r)},schemaValidation(e,t,r){return new at(e,t,r)},browserConfig(e,t,r,i){return new Di(e,t,r,i)},plugin(e,t,r){return new Fi(e,t,r)}};async function Vn(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:s=()=>!0,fallback:n}=t,a=Error("Unknown error occurred");for(let l=0;l<=r;l++)try{return await e()}catch(o){if(a=o instanceof Error?o:Error(String(o)),l===r||!s(a))break;if(i>0)await new Promise((c)=>setTimeout(c,i))}if(n!==void 0)return n;throw a instanceof Error?a:Error(`Unknown error: ${String(a)}`)}class sr{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:i,useCamelCase:s=!0,useBackwardCompatibility:n=!0,customParsers:a={},verbose:l=!1,trackPerformance:o=!0}=r,c=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=i||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],h,{useCamelCase:s,useBackwardCompatibility:n,customParsers:a,verbose:l,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(o)return Vt.track("applyEnvironmentVariables",c,{configName:e});return c()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,i){for(let[s,n]of Object.entries(e)){let a=[...t,s],l=a.map((h)=>this.formatEnvKey(h,i.useCamelCase)),o=`${r}_${l.join("_")}`,c=i.useBackwardCompatibility?`${r}_${a.map((h)=>h.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof n==="object"&&n!==null&&!Array.isArray(n))this.processObject(n,a,r,i);else{let h=Fe.env[o]||(c?Fe.env[c]:void 0);if(h!==void 0){if(i.verbose){let f=Fe.env[o]?o:c}try{e[s]=this.parseEnvironmentValue(h,typeof n,o,i.customParsers,i.configName)}catch(f){if(f instanceof ir)throw f;throw be.envVar(o,h,typeof n,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,s){for(let[n,a]of Object.entries(i))try{return a(e)}catch{continue}for(let n of this.defaultParsers)if(n.canParse(e,t))try{return n.parse(e)}catch{throw be.envVar(r,e,`${t} (via ${n.name} parser)`,s)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,s]of Object.entries(Fe.env))if(i.startsWith(r)&&s!==void 0)t[i]=s;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(s){i.push(`Cannot parse value "${t}" as ${r}: ${s}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:s="text"}=r,n=i||this.generateEnvPrefix(e),a=[];switch(this.extractEnvVarInfo(t,[],n,a),s){case"markdown":return this.formatAsMarkdown(a,e);case"json":return JSON.stringify(a,null,2);default:return this.formatAsText(a,e)}}extractEnvVarInfo(e,t,r,i){for(let[s,n]of Object.entries(e)){let a=[...t,s],l=`${r}_${a.map((o)=>this.formatEnvKey(o,!0)).join("_")}`;if(typeof n==="object"&&n!==null&&!Array.isArray(n))this.extractEnvVarInfo(n,a,r,i);else i.push({key:l,type:Array.isArray(n)?"array":typeof n,description:`Configuration for ${a.join(".")}`,example:this.generateExample(n)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
50
+
51
+ `;for(let i of e)r+=`${i.key}
52
+ `,r+=` Type: ${i.type}
53
+ `,r+=` Description: ${i.description}
54
+ `,r+=` Example: ${i.example}
55
+
56
+ `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
57
+
58
+ `;r+=`| Variable | Type | Description | Example |
59
+ `,r+=`|----------|------|-------------|----------|
60
+ `;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
61
+ `;return r}}function Zn(e,t,r={}){return ji(e,t,r,new WeakMap)}function ji(e,t,r,i){let{arrayMergeMode:s="replace",skipNullish:n=!1,customMerger:a}=r;if(t===null||t===void 0)return n?e:t;if(a){let l=a(e,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(e))return Li(e,t,s,i);if(!U(t)||!U(e))return t;return ea(e,t,r,i)}function Li(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return qn(e,t);case"smart":return Yn(e,t,i);default:return t}return t}function qn(e,t){let r=[...t];for(let i of e)if(!r.some((s)=>Ut(s,i)))r.push(i);return r}function Yn(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(U(t[0])&&U(e[0]))return Xn(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let s of e)if(!i.includes(s))i.push(s);return i}return t}function Xn(e,t,r){let i=[...t];for(let s of e){if(!U(s)){i.push(s);continue}let n=["id","name","key","path","type"],a=!1;for(let l of n)if(l in s){if(i.find((o)=>U(o)&&(l in o)&&o[l]===s[l])){a=!0;break}}if(!a)i.push(s)}return i}function ea(e,t,r,i){let s=t;if(U(s)&&i.has(s))return i.get(s);let n={...e};if(U(s))i.set(s,n);for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;let l=s[a],o=n[a];if(r.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){n[a]=l;continue}if(U(l)&&U(o))n[a]=ji(o,l,r,i);else if(Array.isArray(l)||Array.isArray(o))n[a]=Li(o,l,r.arrayMergeMode||"smart",i);else n[a]=l}return n}function _i(e,t,r="replace"){return Zn(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Ut(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(!Ut(e[r],t[r]))return!1;return!0}if(U(e)&&U(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!Ut(e[s],t[s]))return!1}return!0}return!1}function U(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Ui{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:s=!0,cacheTtl:n,trackPerformance:a=!0,verbose:l=!1}=r;if(s){let c=qe.getWithFileCheck("file",e);if(c){if(l)console.log(`Configuration loaded from cache: ${e}`);return c}}let o=async()=>{if(!je(e))return null;try{let c=`?t=${Date.now()}`,h=await import(e+c),f=h.default||h,g="default"in h,u=Object.keys(h).length>0;if(!g&&!u)throw new nt(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new nt(e,Error("Configuration must export a valid object"),"unknown");let d={config:_i(t,f,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(s)qe.setWithFileCheck("file",d,e,n);return d}catch(c){throw c instanceof Error?be.configLoad(e,c):be.configLoad(e,Error(String(c)))}};if(a)return Vt.track("loadFromPath",o,{path:e});return o()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let s=await this.loadFromPath(i,t,r);if(s)return s}catch(s){if(s instanceof Error&&s.name==="ConfigLoadError")throw s;if(r.verbose)console.warn(`Failed to load config from ${i}:`,s)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),s=[];for(let n of i)for(let a of this.extensions)s.push(kt(t,`${n}${a}`));return s}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let i=t===void 0?[]:Array.isArray(t)?t:[t];for(let n of i){if(!n)continue;if(r.push(n,`.${n}.config`,`${n}.config`,`.${n}`),e)r.push(`${e}.${n}.config`,`.${e}.${n}.config`)}let s=new Set;return r.filter((n)=>{if(!n||s.has(n))return!1;return s.add(n),!0})}checkFileAccess(e){return Vn(async()=>{return je(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!je(e))return i;if(t||r){let s=this.generateNamePatterns(t||"",r);for(let n of s)for(let a of this.extensions){let l=kt(e,`${n}${a}`);if(await this.checkFileAccess(l))i.push(l)}}else try{let{readdirSync:s}=await import("fs"),n=s(e);for(let a of n)if(this.looksLikeConfigFile(a)){let l=kt(e,a);if(await this.checkFileAccess(l))i.push(l)}}catch{return[]}return i}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!je(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:s}=await import("fs"),n=s(e,"utf8");JSON.parse(n)}catch(s){t.push(`Invalid JSON syntax: ${s}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let s=await this.loadFromPath(i,{},t);if(s)r.set(i,s.config)}catch(s){if(t.verbose)console.warn(`Failed to preload ${i}:`,s)}})),r}}var ta=/^https?:\/\//;class Qi{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:s=!0,validateTypes:n=!0,customRules:a=[],trackPerformance:l=!0,verbose:o=!1}=r,c=async()=>{let h=[],f=[],g={stopOnFirstError:i,validateRequired:s,validateTypes:n,customRules:a,trackPerformance:l,verbose:o};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,g);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...a],g);else return this.validateWithJSONSchema(e,t,g)}catch(u){return h.push({path:"",message:`Validation failed: ${u}`,rule:"system"}),{isValid:!1,errors:h,warnings:f}}};if(l)return await Vt.track("validateConfiguration",c);return c()}async validateWithSchemaFile(e,t,r){try{if(!Is(t))throw new at(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),s=i.default||i;if(Array.isArray(s))return this.validateWithRules(e,s,r);else return this.validateWithJSONSchema(e,s,r)}catch(i){throw new at(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],s=[];return this.validateObjectAgainstSchema(e,t,"",i,s,r),{isValid:i.length===0,errors:i,warnings:s}}validateObjectAgainstSchema(e,t,r,i,s,n){if(n.validateTypes&&t.type){let a=Array.isArray(e)?"array":typeof e,l=Array.isArray(t.type)?t.type:[t.type];if(!l.includes(a)){if(i.push({path:r,message:`Expected type ${l.join(" or ")}, got ${a}`,expected:l.join(" or "),actual:a,rule:"type"}),n.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),n.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let a=0;a<e.length;a++){let l=r?`${r}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(e[a],t.items,l,i,s,n),n.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let a=e;if(n.validateRequired&&t.required){for(let l of t.required)if(!(l in a)){if(i.push({path:r?`${r}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),n.stopOnFirstError)return}}if(t.properties){for(let[l,o]of Object.entries(t.properties))if(l in a){let c=r?`${r}.${l}`:l;if(this.validateObjectAgainstSchema(a[l],o,c,i,s,n),n.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let o of Object.keys(a))if(!l.has(o))s.push({path:r?`${r}.${o}`:o,message:`Additional property '${o}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],s=[];for(let n of t)try{let a=this.getValueByPath(e,n.path),l=this.validateWithRule(a,n,n.path);if(i.push(...l),r.stopOnFirstError&&i.length>0)break}catch(a){i.push({path:n.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:s}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let s=Array.isArray(e)?"array":typeof e;if(s!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${s}`,expected:t.type,actual:s,rule:"type"})}if(t.min!==void 0){let s=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(s<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:s,rule:"min"})}if(t.max!==void 0){let s=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(s>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:s,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let s=t.validator(e);if(s)i.push({path:r,message:t.message||s,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let s of r)if(i&&typeof i==="object"&&s in i)i=i[s];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,s,n,a]=i;t.push({path:s,required:!n,type:this.mapTypeScriptType(a)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:ta},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var q=new ht("bunfig",{showTags:!0});function ra(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class Wi{fileLoader=new Ui;envProcessor=new sr;validator=new Qi;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:s,validate:n,...a}=e;try{if(r?.enabled){let o=this.checkCache(a.name||"",a);if(o)return o}let l;try{l=await this.loadConfigurationStrategies(a,!0,r)}catch(o){let c=a.__strictErrorHandling;if(o instanceof Error&&o.name==="ConfigNotFoundError"){if(c)throw o;l={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`No configuration file found for "${a.name||"config"}", using defaults with environment variables`]}}else if(o instanceof Error&&o.name==="ConfigLoadError"){let h=o.message.includes("EACCES")||o.message.includes("EPERM")||o.message.includes("permission denied"),f=!h&&(o.message.includes("syntax")||o.message.includes("Expected")||o.message.includes("Unexpected")||o.message.includes("BuildMessage")||o.message.includes("errors building")),g=o.message.includes("Configuration must export a valid object")||o.message.includes("Configuration file is empty and exports nothing");if(c&&(g||h))throw o;if(f&&(!c||!g))l={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!c)l={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${o.message}`]};else throw o}else l={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${o instanceof Error?o.message:String(o)}`]}}if(s||n)await this.validateConfiguration(l.config,s,n,a.name);if(r?.enabled&&l)this.cacheResult(a.name||"",l,r,a);if(i?.enabled){let o={operation:"loadConfig",duration:Date.now()-t,configName:a.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(o);if(i.slowThreshold&&o.duration>i.slowThreshold)q.warn(`Slow configuration loading detected: ${o.duration}ms for ${a.name}`);l.metrics=o}return l}catch(l){if(l instanceof Error&&l.name==="ConfigNotFoundError")throw l;let o=Date.now()-t;throw q.error(`Configuration loading failed after ${o}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:s,cwd:n,configDir:a,defaultConfig:l,checkEnv:o=!0,arrayStrategy:c="replace",verbose:h=!1}=e,f=n||ot.cwd(),g=[],u=await this.loadLocalConfiguration(i,s,f,a,l,c,h,o,r);if(u)return g.push(...this.getLocalSearchPaths(i,s,f,a)),this.finalizeResult(u,g,o,i,h);let d=await this.loadHomeConfiguration(i,s,l,c,h,o);if(d)return g.push(...this.getHomeSearchPaths(i,s)),this.finalizeResult(d,g,o,i,h);let m=await this.loadPackageJsonConfiguration(i,s,f,l,c,h,o);if(m)return g.push(L(f,"package.json")),this.finalizeResult(m,g,o,i,h);if(g.push(...this.getAllSearchPaths(i,s,f,a)),t)throw be.configNotFound(i,g,s);return{...await this.applyEnvironmentVariables(i,l,o,h),warnings:[`No configuration file found for "${i}"${ra(s)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,s,n,a,l,o){let c=l?_e(e,s,a):s,h=this.getLocalDirectories(r,i);for(let f of h){if(a)q.info(`Searching for configuration in: ${f}`);let g=this.fileLoader.generateConfigPaths(e,f,t),u=await this.fileLoader.tryLoadFromPaths(g,c,{arrayStrategy:n,verbose:a,cacheTtl:o?.ttl,useCache:!o?.ttl||o.ttl>100});if(u){if(a)q.success(`Configuration loaded from: ${u.source.path}`);return u}}return null}async loadHomeConfiguration(e,t,r,i,s,n){if(!e)return null;let a=n?_e(e,r,s):r,l=[L(ae(),".config",e),L(ae(),".config"),ae()];for(let o of l){if(s)q.info(`Checking home directory: ${o}`);let c=this.fileLoader.generateConfigPaths(e,o,t),h=await this.fileLoader.tryLoadFromPaths(c,a,{arrayStrategy:i,verbose:s});if(h){if(s)q.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(e,t,r,i,s,n,a){let l=a?_e(e,i,n):i;try{let o=L(r,"package.json");if(!Gi(o))return null;let c={};try{c=JSON.parse(Vi(o,"utf8"))}catch(g){if(n)q.warn("Failed to parse package.json:",[g instanceof Error?g:Error(String(g))]);return null}let h=c[e],f=e;if(!h&&t){let g=Array.isArray(t)?t:[t];for(let u of g){if(!u)continue;if(c[u]){h=c[u],f=u;break}}}if(h&&typeof h==="object"&&!Array.isArray(h)){if(n)q.success(`Configuration loaded from package.json: ${f}`);return{config:_i(l,h,s),source:{type:"package.json",path:o,priority:30,timestamp:new Date}}}}catch(o){if(n)q.warn("Failed to load package.json:",[o instanceof Error?o:Error(String(o))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:_e(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,s){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let s=[];if(r){let n=r(e);if(n)s.push(...n)}if(t){let n=await this.validator.validateConfiguration(e,t);if(!n.isValid)s.push(...n.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(s.length>0)throw be.configValidation(i||"unknown",s,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return qe.get(r)||null}cacheResult(e,t,r,i){let s=this.generateCacheKey(e,i);qe.set(s,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let i=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${i}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,L(e,"config"),L(e,".config"),t?L(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let s=[];return s.push(...this.getLocalSearchPaths(e,t,r,i)),s.push(...this.getHomeSearchPaths(e,t)),s.push(L(r,"package.json")),s}getLocalSearchPaths(e,t,r,i){let s=this.getLocalDirectories(r,i),n=[];for(let a of s)n.push(...this.fileLoader.generateConfigPaths(e,a,t));return n}getHomeSearchPaths(e,t){if(!e)return[];let r=[L(ae(),".config",e),L(ae(),".config"),ae()],i=[];for(let s of r)i.push(...this.fileLoader.generateConfigPaths(e,s,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}var Zo=new Wi;function _e(e,t,r=!1){let i=new sr,s=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function n(a,l=[]){let o={...a};for(let[c,h]of Object.entries(a)){let f=[...l,c],g=[`${s}_${f.join("_").toUpperCase()}`,`${s}_${f.map((m)=>m.toUpperCase()).join("")}`,`${s}_${f.map((m)=>m.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],u,d;for(let m of g)if(u=ot.env[m],u!==void 0){d=m;break}if(u!==void 0&&d)if(typeof h==="boolean")o[c]=["true","1","yes"].includes(u.toLowerCase());else if(typeof h==="number"){let m=Number(u);if(!Number.isNaN(m))o[c]=m}else if(Array.isArray(h))try{o[c]=JSON.parse(u)}catch{o[c]=u.split(",").map((m)=>m.trim())}else o[c]=u;else if(h&&typeof h==="object"&&!Array.isArray(h))o[c]=n(h,f)}return o}return n(t)}var qo=L(ot.cwd(),"config"),Yo=L(ot.cwd(),"src/generated"),ia={verbose:!1,driver:"bun",default:"bun",connections:{bun:{driver:"bun",host:"0.0.0.0",port:6001,scheme:"ws",options:{idleTimeout:120,maxPayloadLength:16777216,backpressureLimit:1048576,closeOnBackpressureLimit:!1,sendPings:!0,publishToSelf:!1,perMessageDeflate:!0}},reverb:{driver:"reverb",host:"127.0.0.1",port:8080,scheme:"ws",key:re.env.REVERB_APP_KEY,secret:re.env.REVERB_APP_SECRET,appId:re.env.REVERB_APP_ID,options:{idleTimeout:120,maxPayloadLength:16777216}},pusher:{driver:"pusher",key:re.env.PUSHER_APP_KEY,secret:re.env.PUSHER_APP_SECRET,appId:re.env.PUSHER_APP_ID,cluster:re.env.PUSHER_APP_CLUSTER||"mt1",useTLS:!0},ably:{driver:"ably",key:re.env.ABLY_KEY},log:{driver:"log"},null:{driver:"null"}}};class nr{config;keys=new Map;channelKeys=new Map;constructor(e={}){this.config={enabled:e.enabled??!1,algorithm:e.algorithm||"aes-256-gcm",keyRotationInterval:e.keyRotationInterval||86400000,channelKeys:e.channelKeys||new Map},this.channelKeys=new Map(this.config.channelKeys)}isEnabled(){return this.config.enabled}async setChannelKey(e,t){this.channelKeys.set(e,t);let r=Ue.from(t,"hex"),i=await crypto.subtle.importKey("raw",r,{name:"AES-GCM"},!1,["encrypt","decrypt"]);this.keys.set(e,i)}async generateChannelKey(e){let t=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),r=await crypto.subtle.exportKey("raw",t),i=Ue.from(r).toString("hex");return await this.setChannelKey(e,i),i}async encrypt(e,t){if(!this.config.enabled){if(t===void 0)return"undefined";return JSON.stringify(t)}let r=this.keys.get(e);if(!r)throw Error(`No encryption key found for channel: ${e}`);let i=t===void 0?"undefined":JSON.stringify(t),s=crypto.getRandomValues(new Uint8Array(12)),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},r,new TextEncoder().encode(i)),a=new Uint8Array(s.length+n.byteLength);return a.set(s,0),a.set(new Uint8Array(n),s.length),Ue.from(a).toString("base64")}async decrypt(e,t){if(!this.config.enabled){if(t==="undefined")return;return JSON.parse(t)}let r=this.keys.get(e);if(!r)throw Error(`No encryption key found for channel: ${e}`);let i=Ue.from(t,"base64"),s=i.slice(0,12),n=i.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},r,n),l=new TextDecoder().decode(a);if(l==="undefined")return;return JSON.parse(l)}hasChannelKey(e){return this.channelKeys.has(e)}getChannelKey(e){return this.channelKeys.get(e)}async rotateChannelKey(e){return this.generateChannelKey(e)}removeChannelKey(e){this.channelKeys.delete(e),this.keys.delete(e)}}class ar{server;broadcaster;constructor(e,t){this.server=e,this.broadcaster=t}toUser(e,t,r){this.broadcaster.send(`private-user.${e}`,t,r)}toUsers(e,t,r){let i=e.map((s)=>`private-user.${s}`);this.broadcaster.send(i,t,r)}exceptUsers(e,t,r,i){let s=this.server.channels.getSubscribers(t),n=new Set(e.map((a)=>`private-user.${a}`));for(let a of s)if(!Array.from(n).some((l)=>this.server.channels.getChannel(l).subscribers.has(a))){this.broadcaster.send(t,r,i);break}}toAll(e,t){this.broadcaster.send("broadcast",e,t)}toRole(e,t,r){this.broadcaster.send(`role.${e}`,t,r)}notify(e,t){this.toUser(e,"notification",t)}notifyUsers(e,t){this.toUsers(e,"notification",t)}systemMessage(e,t="info"){this.toAll("system.message",{message:e,type:t,timestamp:Date.now()})}modelUpdated(e,t,r){this.broadcaster.send(`model.${e}.${t}`,"updated",r)}modelCreated(e,t){this.broadcaster.send(`model.${e}`,"created",t)}modelDeleted(e,t){this.broadcaster.send(`model.${e}.${t}`,"deleted",{id:t})}getUserConnectionCount(e){return this.server.channels.getSubscriberCount(`private-user.${e}`)}isUserOnline(e){return this.getUserConnectionCount(e)>0}getOnlineUsers(e){let t=e.startsWith("presence-")?e:`presence-${e}`,r=this.server.channels.getPresenceMembers(t);if(!r)return[];return Array.from(r.values())}getPresenceCount(e){let t=e.startsWith("presence-")?e:`presence-${e}`;return this.server.channels.getSubscriberCount(t)}}class or{hooks=new Map;on(e,t){if(!this.hooks.has(e))this.hooks.set(e,new Set);this.hooks.get(e).add(t)}off(e,t){this.hooks.get(e)?.delete(t)}async fire(e){let t=this.hooks.get(e.event);if(t)for(let i of t)try{await i(e)}catch(s){console.error(`Error in lifecycle hook for ${e.event}:`,s)}let r=this.hooks.get("all");if(r)for(let i of r)try{await i(e)}catch(s){console.error("Error in 'all' lifecycle hook:",s)}}async channelCreated(e,t){await this.fire({channel:e,event:"created",timestamp:Date.now(),socketId:t})}async channelSubscribed(e,t,r){await this.fire({channel:e,event:"subscribed",timestamp:Date.now(),socketId:t,subscriberCount:r})}async channelUnsubscribed(e,t,r){await this.fire({channel:e,event:"unsubscribed",timestamp:Date.now(),socketId:t,subscriberCount:r})}async channelEmpty(e){await this.fire({channel:e,event:"empty",timestamp:Date.now(),subscriberCount:0})}async channelDestroyed(e){await this.fire({channel:e,event:"destroyed",timestamp:Date.now()})}}class lr{config;connectionCount=0;channelCount=0;channelsPerConnection=new Map;constructor(e={}){this.config={maxConnections:e.maxConnections??1e4,maxChannelsPerConnection:e.maxChannelsPerConnection??100,maxGlobalChannels:e.maxGlobalChannels??50000,shedLoadAt:e.shedLoadAt??90,backpressureThreshold:e.backpressureThreshold??1048576}}canAcceptConnection(){return this.connectionCount<this.config.maxConnections}shouldShedLoad(){let e=this.connectionCount/this.config.maxConnections*100,t=this.channelCount/this.config.maxGlobalChannels*100;return e>=this.config.shedLoadAt||t>=this.config.shedLoadAt}registerConnection(e){this.connectionCount++,this.channelsPerConnection.set(e,0)}unregisterConnection(e){this.connectionCount=Math.max(0,this.connectionCount-1);let t=this.channelsPerConnection.get(e)||0;this.channelCount=Math.max(0,this.channelCount-t),this.channelsPerConnection.delete(e)}canSubscribe(e){if((this.channelsPerConnection.get(e)||0)>=this.config.maxChannelsPerConnection)return!1;if(this.channelCount>=this.config.maxGlobalChannels)return!1;return!0}registerSubscription(e){let t=this.channelsPerConnection.get(e)||0;this.channelsPerConnection.set(e,t+1),this.channelCount++}unregisterSubscription(e){let t=this.channelsPerConnection.get(e)||0;if(t>0)this.channelsPerConnection.set(e,t-1),this.channelCount=Math.max(0,this.channelCount-1)}shouldApplyBackpressure(e){return e>this.config.backpressureThreshold}getStats(){let e=Array.from(this.channelsPerConnection.values()).reduce((r,i)=>r+i,0),t=this.connectionCount>0?e/this.connectionCount:0;return{connections:this.connectionCount,channels:this.channelCount,averageChannelsPerConnection:t,memoryUsage:sa.memoryUsage().heapUsed,isOverloaded:this.shouldShedLoad()}}getConnectionUsage(){return this.connectionCount/this.config.maxConnections*100}getChannelUsage(){return this.channelCount/this.config.maxGlobalChannels*100}}class cr{callback=null;config;constructor(e={}){this.config={enabled:e.enabled??!0,cookie:{name:e.cookie?.name||"auth_token",secure:e.cookie?.secure??!0},jwt:{secret:e.jwt?.secret||na.env.JWT_SECRET||"",algorithm:e.jwt?.algorithm||"HS256"},session:{key:e.session?.key||"session_id"}}}authenticate(e){this.callback=e}async authenticateRequest(e){if(!this.config.enabled)return null;if(this.callback)return await this.callback(e);let t=e.headers.get("cookie");if(t){let i=this.parseCookies(t)[this.config.cookie.name];if(i)return this.verifyToken(i)}let r=e.headers.get("authorization");if(r?.startsWith("Bearer ")){let i=r.slice(7);return this.verifyToken(i)}return null}parseCookies(e){let t={};for(let r of e.split(";")){let[i,...s]=r.split("=");t[i.trim()]=s.join("=").trim()}return t}async verifyToken(e){try{let t=e.split(".");if(t.length===3){let r=JSON.parse(atob(t[1]));return{id:r.sub||r.id,...r}}}catch(t){console.error("Error verifying token:",t)}return null}}class hr{limits=new Map;config;cleanupTimer;constructor(e){this.config={max:e.max||100,window:e.window||60000,perChannel:e.perChannel??!1,perUser:e.perUser??!1},this.cleanupTimer=setInterval(()=>this.cleanup(),60000)}check(e,t){let r=this.getKey(e,t),i=Date.now(),s=this.limits.get(r);if(!s||s.resetAt<i)return this.limits.set(r,{count:1,resetAt:i+this.config.window}),!1;if(s.count>=this.config.max)return!0;return s.count++,!1}getRemaining(e,t){let r=this.getKey(e,t),i=this.limits.get(r);if(!i||i.resetAt<Date.now())return this.config.max;return Math.max(0,this.config.max-i.count)}getResetAt(e,t){let r=this.getKey(e,t);return this.limits.get(r)?.resetAt||Date.now()}getKey(e,t){let r=[];if(this.config.perUser&&e.data.user)r.push(`user:${e.data.user.id}`);else r.push(`socket:${e.data.socketId}`);if(this.config.perChannel&&t)r.push(`channel:${t}`);return r.join(":")}cleanup(){let e=Date.now();for(let[t,r]of this.limits.entries())if(r.resetAt<e)this.limits.delete(t)}clear(){this.limits.clear()}stop(){clearInterval(this.cleanupTimer)}}class fr{validators=new Set;addValidator(e){this.validators.add(e)}removeValidator(e){this.validators.delete(e)}validate(e){for(let t of this.validators){let r=t(e);if(r===!1)return{valid:!1,error:"Validation failed"};if(typeof r==="string")return{valid:!1,error:r}}return{valid:!0}}}class ur{callbacks=new Map;metrics=new Map;on(e,t){if(!this.callbacks.has(e))this.callbacks.set(e,new Set);this.callbacks.get(e).add(t)}off(e,t){let r=this.callbacks.get(e);if(r)r.delete(t)}emit(e){this.incrementMetric(e.type);let t=this.callbacks.get(e.type);if(t)for(let i of t)i(e);let r=this.callbacks.get("all");if(r)for(let i of r)i(e)}incrementMetric(e,t=1){let r=this.metrics.get(e)||0;this.metrics.set(e,r+t)}getMetric(e){return this.metrics.get(e)||0}getMetrics(){return Object.fromEntries(this.metrics)}resetMetrics(){this.metrics.clear()}}class gr{config;constructor(e={}){this.config={cors:{enabled:e.cors?.enabled??!0,origins:e.cors?.origins||["*"],credentials:e.cors?.credentials??!0},maxPayloadSize:e.maxPayloadSize||1048576,sanitizeMessages:e.sanitizeMessages??!0}}checkOrigin(e){if(!this.config.cors?.enabled)return!0;if(this.config.cors.origins?.includes("*"))return!0;return this.config.cors.origins?.includes(e)??!1}sanitize(e){if(!this.config.sanitizeMessages)return e;if(typeof e==="string")return e.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/\x27/g,"&#x27;").replace(/\//g,"&#x2F;");if(Array.isArray(e))return e.map((t)=>this.sanitize(t));if(e&&typeof e==="object"){let t={};for(let[r,i]of Object.entries(e))t[r]=this.sanitize(i);return t}return e}checkSize(e){return e.length<=this.config.maxPayloadSize}}class mr{config;redis;inMemoryStore=new Map;constructor(e={},t){this.config={enabled:e.enabled??!1,ttl:e.ttl??3600,maxMessages:e.maxMessages??100,excludeEvents:e.excludeEvents||["ping","pong"]},this.redis=t}async store(e,t,r,i){if(!this.config.enabled)return;if(this.config.excludeEvents.includes(t))return;let s={id:crypto.randomUUID(),event:t,data:r,timestamp:Date.now(),socketId:i};if(this.redis)await this.storeInRedis(e,s);else this.storeInMemory(e,s)}async getHistory(e,t,r){if(!this.config.enabled)return[];if(this.redis)return this.getHistoryFromRedis(e,t,r);return this.getHistoryFromMemory(e,t,r)}async clear(e){if(this.redis){let t=this.getRedisKey(e),r=this.redis;if(r.publisher)await r.publisher.del(t)}else this.inMemoryStore.delete(e)}async storeInRedis(e,t){if(!this.redis)return;let r=this.getRedisKey(e),i=JSON.stringify(t),s=this.redis;if(!s.publisher)return;await s.publisher.zadd(r,t.timestamp,i);let n=-this.config.maxMessages-1;await s.publisher.send("ZREMRANGEBYRANK",[r,"0",n.toString()]),await s.publisher.expire(r,this.config.ttl)}async getHistoryFromRedis(e,t,r){if(!this.redis)return[];let i=this.getRedisKey(e),s=t?.toString()||"-inf",n="+inf",a=r||this.config.maxMessages,l=this.redis;if(!l.publisher)return[];return(await l.publisher.send("ZRANGEBYSCORE",[i,s,n,"LIMIT","0",a.toString()])).map((o)=>JSON.parse(o))}storeInMemory(e,t){if(!this.inMemoryStore.has(e))this.inMemoryStore.set(e,[]);let r=this.inMemoryStore.get(e);if(r.push(t),r.length>this.config.maxMessages)r.shift();let i=Date.now()-this.config.ttl*1000,s=r.filter((n)=>n.timestamp>i);this.inMemoryStore.set(e,s)}getHistoryFromMemory(e,t,r){let i=this.inMemoryStore.get(e)||[],s=i;if(t!==void 0)s=i.filter((n)=>n.timestamp>=t);if(r)s=s.slice(0,r);return s}getRedisKey(e){return`history:${e}`}async getStats(){if(this.redis){let r=this.redis;if(!r.publisher)return{totalChannels:0,totalMessages:0,channels:{}};let i=await r.publisher.send("KEYS",["history:*"]),s=0,n={};for(let a of i){let l=await r.publisher.send("ZCARD",[a]),o=a.replace("history:",""),c=Number(l);n[o]=c,s+=c}return{totalChannels:i.length,totalMessages:s,channels:n}}let e=0,t={};for(let[r,i]of this.inMemoryStore.entries())t[r]=i.length,e+=i.length;return{totalChannels:this.inMemoryStore.size,totalMessages:e,channels:t}}}class dr{config;presenceUsers=new Map;heartbeatTimer;onRemove;constructor(e={}){this.config={enabled:e.enabled??!0,interval:e.interval??30000,timeout:e.timeout??60000,requireClientHeartbeat:e.requireClientHeartbeat??!0}}start(){if(!this.config.enabled)return;this.heartbeatTimer=setInterval(()=>{this.checkHeartbeats()},this.config.interval)}stop(){if(this.heartbeatTimer)clearInterval(this.heartbeatTimer)}onUserRemove(e){this.onRemove=e}heartbeat(e,t,r){if(!this.config.enabled)return;if(!this.presenceUsers.has(e))this.presenceUsers.set(e,new Map);let i=this.presenceUsers.get(e),s=i.get(t);i.set(t,{socketId:t,lastSeen:Date.now(),data:r||s?.data})}remove(e,t){let r=this.presenceUsers.get(e);if(r){if(r.delete(t),r.size===0)this.presenceUsers.delete(e)}}checkHeartbeats(){let e=Date.now(),t=this.config.timeout;for(let[r,i]of this.presenceUsers.entries()){let s=[];for(let[n,a]of i.entries())if(e-a.lastSeen>t)s.push(n);for(let n of s){let a=i.get(n);if(i.delete(n),this.onRemove&&a)this.onRemove(r,n,a.data)}if(i.size===0)this.presenceUsers.delete(r)}}getActiveUsers(e){let t=this.presenceUsers.get(e);if(!t)return[];return Array.from(t.values())}isActive(e,t){let r=this.presenceUsers.get(e)?.get(t);if(!r)return!1;return Date.now()-r.lastSeen<this.config.timeout}getStats(){let e=0;for(let t of this.presenceUsers.values())e+=t.size;return{channels:this.presenceUsers.size,totalUsers:e}}}var{RedisClient:oi}=globalThis.Bun;class pr{publisher;subscriber;config;serverId;messageHandlers=new Set;get client(){return this.publisher}constructor(e){this.serverId=crypto.randomUUID(),this.config={host:e.host||we.env.REDIS_HOST||"localhost",port:e.port||Number.parseInt(we.env.REDIS_PORT||"6379"),password:e.password||we.env.REDIS_PASSWORD||"",database:e.database||Number.parseInt(we.env.REDIS_DB||"0"),url:e.url||we.env.REDIS_URL||"",keyPrefix:e.keyPrefix||"broadcasting:"};let t=this.config.url||this.buildRedisUrl();this.publisher=new oi(t||"redis://localhost:6379"),this.subscriber=new oi(t||"redis://localhost:6379")}buildRedisUrl(){return`redis://${this.config.password?`:${this.config.password}@`:""}${this.config.host}:${this.config.port}/${this.config.database}`}async connect(){await Promise.all([this.publisher.connect(),this.subscriber.connect()]),await this.subscriber.subscribe(`${this.config.keyPrefix}channel`,(e)=>{this.handleRedisMessage(e)})}close(){this.publisher.close(),this.subscriber.close()}async broadcast(e,t,r,i){let s={type:"broadcast",channel:e,event:t,data:r,socketId:i,serverId:this.serverId};await this.publisher.publish(`${this.config.keyPrefix}channel`,JSON.stringify(s))}onMessage(e){this.messageHandlers.add(e)}offMessage(e){this.messageHandlers.delete(e)}handleRedisMessage(e){try{let t=JSON.parse(e);if(t.serverId===this.serverId)return;for(let r of this.messageHandlers)r(t)}catch(t){console.error("Error handling Redis message:",t)}}async storeChannel(e,t){let r=`${this.config.keyPrefix}channels:${e}`;await this.publisher.sadd(r,t),await this.publisher.expire(r,3600)}async removeChannel(e,t){let r=`${this.config.keyPrefix}channels:${e}`;await this.publisher.srem(r,t)}async getChannelSubscribers(e){let t=`${this.config.keyPrefix}channels:${e}`;return await this.publisher.smembers(t)}async storePresenceMember(e,t,r){let i=`${this.config.keyPrefix}presence:${e}`;await this.publisher.hmset(i,[t,JSON.stringify(r)]),await this.publisher.expire(i,3600)}async removePresenceMember(e,t){let r=`${this.config.keyPrefix}presence:${e}`;await this.publisher.send("HDEL",[r,t])}async getPresenceMembers(e){let t=`${this.config.keyPrefix}presence:${e}`,r=await this.publisher.send("HGETALL",[t]),i=new Map;for(let s=0;s<r.length;s+=2){let n=r[s],a=r[s+1];try{i.set(n,JSON.parse(a))}catch{console.error(`Error parsing presence member data for ${n}`)}}return i}async incrementStat(e){let t=`${this.config.keyPrefix}stats:${e}`;await this.publisher.incr(t)}async getStats(){let e=await this.publisher.send("KEYS",[`${this.config.keyPrefix}stats:*`]),t={};for(let r of e){let i=await this.publisher.get(r),s=r.replace(`${this.config.keyPrefix}stats:`,"");t[s]=Number.parseInt(i||"0")}return t}async storeConnection(e,t){let r=`${this.config.keyPrefix}connections:${e}`;await this.publisher.set(r,JSON.stringify(t)),await this.publisher.expire(r,7200)}async removeConnection(e){let t=`${this.config.keyPrefix}connections:${e}`;await this.publisher.del(t)}async getConnection(e){let t=`${this.config.keyPrefix}connections:${e}`,r=await this.publisher.get(t);if(!r)return null;try{return JSON.parse(r)}catch{return console.error(`Error parsing connection data for ${e}`),null}}async getTotalConnections(){return(await this.publisher.send("KEYS",[`${this.config.keyPrefix}connections:*`])).length}async getTotalChannels(){return(await this.publisher.send("KEYS",[`${this.config.keyPrefix}channels:*`])).length}async healthCheck(){try{return await this.publisher.send("PING",[]),!0}catch{return!1}}getServerId(){return this.serverId}}class yr{config;endpoints;constructor(e={}){this.config={enabled:e.enabled??!1,endpoints:e.endpoints||[],retryAttempts:e.retryAttempts??3,retryDelay:e.retryDelay??1000,timeout:e.timeout??5000,secret:e.secret||""},this.endpoints=this.config.endpoints}register(e){this.endpoints.push(e)}async fire(e,t){if(!this.config.enabled)return;let r={event:e,timestamp:Date.now(),data:t};if(this.config.secret)r.signature=await this.generateSignature(r);let i=this.endpoints.filter((s)=>s.events.includes(e)).map((s)=>this.sendWebhook(s,r));await Promise.allSettled(i)}async sendWebhook(e,t,r=1){try{let i=new AbortController,s=setTimeout(()=>i.abort(),this.config.timeout),n=await fetch(e.url,{method:e.method||"POST",headers:{"Content-Type":"application/json","User-Agent":"ts-broadcasting/1.0","X-Webhook-Signature":t.signature||"",...e.headers},body:JSON.stringify(t),signal:i.signal});if(clearTimeout(s),!n.ok&&n.status>=500&&r<=this.config.retryAttempts)return await new Promise((a)=>setTimeout(a,this.config.retryDelay*r)),this.sendWebhook(e,t,r+1)}catch{if(r<=this.config.retryAttempts)return await new Promise((i)=>setTimeout(i,this.config.retryDelay*r)),this.sendWebhook(e,t,r+1)}}async generateSignature(e){let t=new TextEncoder,r=t.encode(JSON.stringify(e)),i=await crypto.subtle.importKey("raw",t.encode(this.config.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),s=await crypto.subtle.sign("HMAC",i,r);return aa.from(s).toString("hex")}async verifySignature(e,t){if(!this.config.secret)return!0;let r=await this.generateSignature(e);return t===r}}class Se{server;connections=new Map;config;channels;broadcaster;helpers;redis;auth;rateLimit;monitoring;validator;security;encryption;webhooks;persistence;channelState;namespace;presenceHeartbeat;acknowledgments;batchOps;lifecycle;loadManager;queueManager;constructor(e){if(this.config=e,this.channels=new Gt,this.broadcaster=new Kt(this,e),this.helpers=new ar(this,this.broadcaster),e.auth)this.auth=new cr(e.auth);if(e.rateLimit)this.rateLimit=new hr(e.rateLimit);if(e.security)this.security=new gr(e.security);if(this.monitoring=new ur,this.validator=new fr,e.encryption)this.encryption=new nr(e.encryption);if(e.webhooks)this.webhooks=new yr(e.webhooks);if(e.persistence)this.persistence=new mr(e.persistence);if(this.channelState=new Jt,this.namespace=new Ht,e.heartbeat)this.presenceHeartbeat=new dr(e.heartbeat);if(e.acknowledgments)this.acknowledgments=new Qt(e.acknowledgments);if(e.batch)this.batchOps=new Wt(e.batch,this.channels);if(this.lifecycle=new or,e.loadManagement)this.loadManager=new lr(e.loadManagement);if(e.queue?.enabled)this.initializeQueueManager();if(this.presenceHeartbeat)this.presenceHeartbeat.onUserRemove((t,r,i)=>{if(this.broadcast(t,"member_removed",{id:r,user:i},r),this.config.verbose)console.warn(`Removed inactive user ${r} from ${t}`)});this.setupDefaultValidators()}async initializeQueueManager(){try{let{BroadcastQueueManager:e}=await import("./chunk-dq93zag9.js");if(this.queueManager=new e(this,this.config.queue),this.config.verbose)console.warn("Queue manager initialized")}catch(e){console.error("Failed to initialize queue manager:",e)}}async start(){if(this.presenceHeartbeat){if(this.presenceHeartbeat.start(),this.config.verbose)console.warn("Started presence heartbeat monitoring")}if(this.config.redis){if(this.redis=new pr(this.config.redis),await this.redis.connect(),this.redis.onMessage((i)=>{if(i.type==="broadcast")this.broadcast(i.channel,i.event,i.data,i.socketId)}),this.config.verbose)console.warn("Connected to Redis for horizontal scaling")}let e=this.config.connections?.[this.config.default||"bun"],t=e?.host??this.config.host??"0.0.0.0",r=e?.port??this.config.port??6001;if(this.server=Bun.serve({hostname:t,port:r,fetch:async(i,s)=>{let n=new URL(i.url);if(n.pathname==="/health"){let a={status:"ok",redis:this.redis?await this.redis.healthCheck():null};return Response.json(a)}if(n.pathname==="/stats")return Response.json(await this.getStats());if(n.pathname==="/metrics"){let{PrometheusExporter:a}=await import("./chunk-jrf5a2ap.js"),l=await new a(this).export();return new Response(l,{headers:{"Content-Type":"text/plain; version=0.0.4"}})}if(n.pathname==="/app"||n.pathname==="/ws"){let a=null;if(this.auth)a=await this.auth.authenticateRequest(i);if(s.upgrade(i,{data:{id:crypto.randomUUID(),socketId:crypto.randomUUID(),channels:new Set,connectedAt:Date.now(),user:a??void 0}}))return;return new Response("WebSocket upgrade failed",{status:400})}return new Response("Not found",{status:404})},websocket:{open:(i)=>{this.handleOpen(i)},message:(i,s)=>{this.handleMessage(i,s)},close:(i,s,n)=>{this.handleClose(i,s,n)},drain:(i)=>{this.handleDrain(i)},idleTimeout:e?.options?.idleTimeout,maxPayloadLength:e?.options?.maxPayloadLength,backpressureLimit:e?.options?.backpressureLimit,closeOnBackpressureLimit:e?.options?.closeOnBackpressureLimit,sendPings:e?.options?.sendPings,perMessageDeflate:e?.options?.perMessageDeflate}}),this.config.verbose)console.warn(`Broadcasting server started on ${t}:${r}`);this.monitoring?.emit({type:"connection",timestamp:Date.now(),socketId:"server",data:{event:"server_start"}})}async stop(){if(this.rateLimit)this.rateLimit.stop();if(this.presenceHeartbeat)this.presenceHeartbeat.stop();if(this.acknowledgments)this.acknowledgments.clear();if(this.queueManager)await this.queueManager.close();if(this.redis)this.redis.close();if(this.server){if(this.server.stop(),this.connections.clear(),this.config.verbose)console.warn("Broadcasting server stopped")}this.monitoring?.emit({type:"disconnection",timestamp:Date.now(),socketId:"server",data:{event:"server_stop"}})}handleOpen(e){if(this.loadManager&&!this.loadManager.canAcceptConnection()){e.close(1008,"Server at capacity");return}if(this.loadManager?.shouldShedLoad()){e.close(1008,"Server load too high");return}if(this.loadManager)this.loadManager.registerConnection(e.data.socketId);if(this.connections.set(e.data.socketId,e),this.redis)this.redis.storeConnection(e.data.socketId,{connectedAt:e.data.connectedAt,channels:Array.from(e.data.channels),user:e.data.user}).catch((t)=>console.error("Redis store connection error:",t));if(this.webhooks)this.webhooks.fire("connection",{socketId:e.data.socketId,connectedAt:e.data.connectedAt,user:e.data.user}).catch((t)=>console.error("Webhook error:",t));if(this.send(e,{event:"connection_established",data:{socket_id:e.data.socketId,activity_timeout:this.config.connections?.[this.config.default||"bun"]?.options?.idleTimeout||120}}),this.monitoring?.emit({type:"connection",timestamp:Date.now(),socketId:e.data.socketId}),this.config.verbose)console.warn(`WebSocket connected: ${e.data.socketId}`)}async handleMessage(e,t){if(this.rateLimit&&this.rateLimit.check(e)){this.send(e,{event:"error",data:{type:"RateLimitExceeded",error:"Too many requests",retryAfter:this.rateLimit.getResetAt(e)}});return}let r=typeof t==="string"?t:t.toString();if(this.security&&!this.security.checkSize(r)){this.send(e,{event:"error",data:{type:"PayloadTooLarge",error:"Message size exceeds maximum allowed"}});return}try{let i=JSON.parse(r);if(this.validator){let n=this.validator.validate(i);if(!n.valid){this.send(e,{event:"error",data:{type:"ValidationError",error:n.error}});return}}let s=this.security?this.security.sanitize(i):i;switch(this.monitoring?.emit({type:"message",timestamp:Date.now(),socketId:e.data.socketId,data:{event:s.event}}),s.event){case"subscribe":await this.handleSubscribe(e,s);break;case"unsubscribe":await this.handleUnsubscribe(e,s);break;case"batch_subscribe":await this.handleBatchSubscribe(e,s);break;case"batch_unsubscribe":await this.handleBatchUnsubscribe(e,s);break;case"heartbeat":case"presence_heartbeat":await this.handleHeartbeat(e,s);break;case"ping":this.send(e,{event:"pong"});break;default:if(this.acknowledgments&&s.ack&&s.messageId)this.send(e,{event:"ack",messageId:s.messageId});if(s.event.startsWith("client-"))await this.handleClientEvent(e,s);break}}catch(i){if(this.monitoring?.emit({type:"error",timestamp:Date.now(),socketId:e.data.socketId,data:{error:i instanceof Error?i.message:"Unknown error"}}),this.config.verbose)console.error("Error handling message:",i)}}async handleSubscribe(e,t){let{channel:r,channel_data:i}=t;try{if(this.loadManager&&!this.loadManager.canSubscribe(e.data.socketId)){this.send(e,{event:"subscription_error",channel:r,data:{type:"CapacityError",error:"Subscription limit reached",status:429}});return}let s=await this.channels.subscribe(e,r,i);if(!s){this.send(e,{event:"subscription_error",channel:r,data:{type:"AuthError",error:"Unauthorized",status:401}});return}if(this.loadManager)this.loadManager.registerSubscription(e.data.socketId);if(this.redis){if(await this.redis.storeChannel(r,e.data.socketId),this.channels.getChannelType(r)==="presence"&&typeof s==="object")await this.redis.storePresenceMember(r,e.data.socketId,s)}let n=this.channels.getChannelType(r);if(this.lifecycle){if(this.channels.getSubscriberCount(r)===1)await this.lifecycle.channelCreated(r,e.data.socketId);await this.lifecycle.channelSubscribed(r,e.data.socketId,this.channels.getSubscriberCount(r))}if(n==="presence"){if(this.presenceHeartbeat&&typeof s==="object")this.presenceHeartbeat.heartbeat(r,e.data.socketId,s);let a=this.channels.getPresenceMembers(r),l={presence:{ids:Array.from(a?.keys()||[]),hash:Object.fromEntries(a||[]),count:a?.size||0}};if(this.send(e,{event:"subscription_succeeded",channel:r,data:l}),typeof s==="object")this.broadcast(r,"member_added",s,e.data.socketId)}else this.send(e,{event:"subscription_succeeded",channel:r});if(this.webhooks)this.webhooks.fire("subscribe",{socketId:e.data.socketId,channel:r,channelData:i}).catch((a)=>console.error("Webhook error:",a));if(this.monitoring?.emit({type:"subscribe",timestamp:Date.now(),socketId:e.data.socketId,channel:r}),this.config.verbose)console.warn(`Socket ${e.data.socketId} subscribed to ${r}`)}catch(s){this.send(e,{event:"subscription_error",channel:r,data:{type:"ServerError",error:s instanceof Error?s.message:"Internal server error",status:500}})}}async handleUnsubscribe(e,t){let{channel:r}=t,i=this.channels.getChannelType(r),s=null;if(i==="presence")s=this.channels.getPresenceMembers(r)?.get(e.data.socketId);if(this.redis){if(await this.redis.removeChannel(r,e.data.socketId),i==="presence")await this.redis.removePresenceMember(r,e.data.socketId)}if(this.channels.unsubscribe(e,r),i==="presence"&&s)this.broadcast(r,"member_removed",s,e.data.socketId);if(this.monitoring?.emit({type:"unsubscribe",timestamp:Date.now(),socketId:e.data.socketId,channel:r}),this.config.verbose)console.warn(`Socket ${e.data.socketId} unsubscribed from ${r}`)}async handleClientEvent(e,t){let{event:r,channel:i,data:s}=t;if(this.channels.getChannelType(i)==="public")return;this.broadcast(i,r,s,e.data.socketId)}handleClose(e,t,r){let i=new Map;for(let s of e.data.channels)if(this.channels.getChannelType(s)==="presence"){let n=this.channels.getPresenceMembers(s)?.get(e.data.socketId);if(n)i.set(s,n)}this.channels.unsubscribeAll(e);for(let[s,n]of i)this.broadcast(s,"member_removed",n,e.data.socketId);if(this.loadManager)this.loadManager.unregisterConnection(e.data.socketId);if(this.connections.delete(e.data.socketId),this.redis)this.redis.removeConnection(e.data.socketId).catch((s)=>console.error("Redis remove connection error:",s));if(this.webhooks)this.webhooks.fire("disconnection",{socketId:e.data.socketId,code:t,reason:r}).catch((s)=>console.error("Webhook error:",s));if(this.monitoring?.emit({type:"disconnection",timestamp:Date.now(),socketId:e.data.socketId,data:{code:t,reason:r}}),this.config.verbose)console.warn(`WebSocket closed: ${e.data.socketId} (${t}: ${r})`)}handleError(e,t){if(this.monitoring?.emit({type:"error",timestamp:Date.now(),socketId:e.data.socketId,data:{error:t.message}}),this.config.verbose)console.error(`WebSocket error for ${e.data.socketId}:`,t)}handleDrain(e){if(this.config.verbose)console.warn(`WebSocket drained: ${e.data.socketId}`)}send(e,t){return e.send(JSON.stringify(t))}broadcast(e,t,r,i){let s=JSON.stringify({event:t,channel:e,data:r});if(this.server)if(i){let n=this.channels.getSubscribers(e);for(let a of n)if(a!==i){let l=this.connections.get(a);if(l)l.send(s)}}else this.server.publish(e,s);if(this.redis)this.redis.broadcast(e,t,r,i).catch((n)=>{console.error("Redis broadcast error:",n)});this.monitoring?.emit({type:"broadcast",timestamp:Date.now(),socketId:i||"server",channel:e,data:{event:t,dataSize:JSON.stringify(r).length}})}getConnectionCount(){return this.connections.size}getSubscriberCount(e){return this.channels.getSubscriberCount(e)}async getStats(){let e={connections:this.getConnectionCount(),channels:this.channels.getChannelCount(),uptime:oa.uptime()};if(this.redis){let t={totalConnections:await this.redis.getTotalConnections(),totalChannels:await this.redis.getTotalChannels(),redisHealthy:await this.redis.healthCheck(),serverId:this.redis.getServerId()};return{...e,...t,metrics:this.monitoring?.getMetrics()||{}}}return{...e,metrics:this.monitoring?.getMetrics()||{}}}async handleBatchSubscribe(e,t){if(!this.batchOps){this.send(e,{event:"error",data:{type:"NotSupported",error:"Batch operations are not enabled"}});return}try{let r=await this.batchOps.batchSubscribe(e,{channels:t.channels,channelData:t.channelData});this.send(e,{event:"batch_subscribe_result",messageId:t.messageId,data:r})}catch(r){this.send(e,{event:"error",data:{type:"BatchError",error:r instanceof Error?r.message:"Batch subscribe failed"}})}}handleBatchUnsubscribe(e,t){if(!this.batchOps){this.send(e,{event:"error",data:{type:"NotSupported",error:"Batch operations are not enabled"}});return}try{let r=this.batchOps.batchUnsubscribe(e,t.channels);this.send(e,{event:"batch_unsubscribe_result",messageId:t.messageId,data:r})}catch(r){this.send(e,{event:"error",data:{type:"BatchError",error:r instanceof Error?r.message:"Batch unsubscribe failed"}})}}async handleHeartbeat(e,t){if(!this.presenceHeartbeat)return;if(t.channel)this.presenceHeartbeat.heartbeat(t.channel,e.data.socketId)}setupDefaultValidators(){if(!this.validator)return;this.validator.addValidator((e)=>{if(!e||typeof e!=="object")return"Invalid message format";if(!e.event||typeof e.event!=="string")return"Missing or invalid event name";if(e.channel&&typeof e.channel!=="string")return"Invalid channel name";return!0}),this.validator.addValidator((e)=>{let t=e.event;if(t.length>100)return"Event name too long";if(!/^[\w.-]+$/.test(t))return"Event name contains invalid characters";return!0})}}var W=null;class O{static setServer(e){W=e}static getServer(){return W}static get broadcaster(){if(!W)throw Error("Broadcast server not initialized. Call Broadcast.setServer() first.");return W.broadcaster}static get channels(){if(!W)throw Error("Broadcast server not initialized. Call Broadcast.setServer() first.");return W.channels}static channel(e,t){if(!W)throw Error("Broadcast server not initialized. Call Broadcast.setServer() first.");return W.channels.channel(e,t),O}static async event(e){return O.broadcaster.broadcast(e)}static send(e,t,r){O.broadcaster.send(e,t,r)}static private(e,t,r){let i=e.startsWith("private-")?e:`private-${e}`;O.send(i,t,r)}static presence(e,t,r){let i=e.startsWith("presence-")?e:`presence-${e}`;O.send(i,t,r)}static toUser(e,t,r){O.private(`user.${e}`,t,r)}static toUsers(e,t,r){let i=e.map((s)=>`private-user.${s}`);O.send(i,t,r)}static toOthers(e){return O.broadcaster.toOthers(e)}static getConnectionCount(){if(!W)return 0;return W.getConnectionCount()}static getSubscriberCount(e){if(!W)return 0;return W.getSubscriberCount(e)}}function la(e,t){O.channel(e,t)}class Ki{eventCallbacks=new Map;on(e,t){if(!this.eventCallbacks.has(e))this.eventCallbacks.set(e,new Set);this.eventCallbacks.get(e).add(t)}off(e,t){if(!t)this.eventCallbacks.delete(e);else this.eventCallbacks.get(e)?.delete(t)}emit(e,t){let r=this.eventCallbacks.get(e);if(r)for(let i of r)i(t)}}class ca{ws=null;config;channels=new Map;_socketId=null;reconnectAttempts=0;reconnectTimer=null;messageQueue=[];heartbeatTimer=null;pendingAcks=new Map;encryptionKeys=new Map;connector=new Ki;constructor(e){if(this.config={broadcaster:e.broadcaster||"bun",host:e.host||"localhost",port:e.port||6001,scheme:e.scheme||"ws",key:e.key||"",cluster:e.cluster||"",encrypted:e.encrypted??!1,auth:e.auth||{},autoConnect:e.autoConnect??!0,reconnect:e.reconnect??e.autoReconnect??!0,autoReconnect:e.autoReconnect??e.reconnect??!0,reconnectDelay:(e.reconnectDelay??e.reconnectInterval)||1000,reconnectInterval:(e.reconnectInterval??e.reconnectDelay)||1000,maxReconnectAttempts:e.maxReconnectAttempts||10,encryption:{enabled:e.encryption?.enabled??!1,keys:e.encryption?.keys||{}},acknowledgments:{enabled:e.acknowledgments?.enabled??!1,timeout:e.acknowledgments?.timeout||5000},batch:{enabled:e.batch?.enabled??!0,maxBatchSize:e.batch?.maxBatchSize||50},heartbeat:{enabled:e.heartbeat?.enabled??!1,interval:e.heartbeat?.interval||30000},offlineQueue:{enabled:e.offlineQueue?.enabled??!0,maxSize:e.offlineQueue?.maxSize||100}},this.config.encryption.enabled&&this.config.encryption.keys)for(let[t,r]of Object.entries(this.config.encryption.keys))this.encryptionKeys.set(t,r);if(this.config.autoConnect)this.connect()}connect(){if(this.ws?.readyState===WebSocket.OPEN)return;let e=`${this.config.scheme}://${this.config.host}:${this.config.port}/ws`;this.ws=new WebSocket(e),this.ws.onopen=()=>{if(this.reconnectAttempts=0,this.connector.emit("connect"),this.config.heartbeat.enabled)this.startHeartbeat();while(this.messageQueue.length>0){let t=this.messageQueue.shift();if(t){if(this.ws?.send(t.message),t.ack&&t.messageId)this.waitForAck(t.messageId)}}},this.ws.onmessage=(t)=>{this.handleMessage(t.data)},this.ws.onclose=()=>{if(this._socketId=null,this.stopHeartbeat(),this.connector.emit("disconnect"),this.config.reconnect&&this.reconnectAttempts<this.config.maxReconnectAttempts){this.reconnectAttempts++;let t=Math.min(this.config.reconnectDelay*2**(this.reconnectAttempts-1),30000);this.reconnectTimer=setTimeout(()=>this.connect(),t)}},this.ws.onerror=(t)=>{this.connector.emit("error",t),console.error("WebSocket error:",t)}}disconnect(){if(this.reconnectTimer)clearTimeout(this.reconnectTimer),this.reconnectTimer=null;this.stopHeartbeat();for(let e of this.pendingAcks.values())clearTimeout(e.timeout),e.reject(Error("Connection closed"));this.pendingAcks.clear();for(let e of this.channels.values())e.unsubscribe();if(this.ws)this.ws.close(),this.ws=null;this.channels.clear(),this._socketId=null}isConnected(){return this.ws?.readyState===WebSocket.OPEN}socketId(){return this._socketId}channel(e){if(!this.channels.has(e)){let t=new br(this,e);this.channels.set(e,t),t.subscribe()}return this.channels.get(e)}private(e){let t=e.startsWith("private-")?e:`private-${e}`;if(!this.channels.has(t)){let r=new wr(this,t);this.channels.set(t,r),r.subscribe()}return this.channels.get(t)}join(e){let t=e.startsWith("presence-")?e:`presence-${e}`;if(!this.channels.has(t)){let r=new Ji(this,t);this.channels.set(t,r),r.subscribe()}return this.channels.get(t)}leave(e){let t=this.channels.get(e);if(t)t.unsubscribe(),this.channels.delete(e)}leaveAll(){for(let e of this.channels.values())e.unsubscribe();this.channels.clear()}async batchSubscribe(e,t){if(!this.config.batch?.enabled)throw Error("Batch operations are disabled");if(e.length>(this.config.batch?.maxBatchSize??50))throw Error(`Batch size exceeds maximum: ${e.length} > ${this.config.batch.maxBatchSize}`);return new Promise((r,i)=>{let s=crypto.randomUUID();this.send({event:"batch_subscribe",channels:e,channelData:t,messageId:s});let n=setTimeout(()=>{i(Error("Batch subscribe timeout"))},1e4),a=(l)=>{if(l?.messageId===s)clearTimeout(n),r(l)};this.listen("batch_subscribe_result",a)})}async batchUnsubscribe(e){if(!this.config.batch?.enabled)throw Error("Batch operations are disabled");if(e.length>(this.config.batch?.maxBatchSize??50))throw Error(`Batch size exceeds maximum: ${e.length} > ${this.config.batch.maxBatchSize}`);return new Promise((t,r)=>{let i=crypto.randomUUID();this.send({event:"batch_unsubscribe",channels:e,messageId:i});let s=setTimeout(()=>{r(Error("Batch unsubscribe timeout"))},1e4),n=(a)=>{if(a?.messageId===i)clearTimeout(s),t(a)};this.listen("batch_unsubscribe_result",n)})}getSocketId(){return this._socketId}setEncryptionKey(e,t){this.encryptionKeys.set(e,t)}getEncryptionKey(e){return this.encryptionKeys.get(e)}async sendWithAck(e,t=!1){if(!t||!this.config.acknowledgments.enabled)return this.send(e),Promise.resolve(!0);let r=crypto.randomUUID(),i={...e,messageId:r,ack:!0};return new Promise((s,n)=>{this.send(i),this.waitForAck(r).then(s).catch(n)})}waitForAck(e){return new Promise((t,r)=>{let i=setTimeout(()=>{this.pendingAcks.delete(e),r(Error(`Acknowledgment timeout for message ${e}`))},this.config.acknowledgments.timeout);this.pendingAcks.set(e,{messageId:e,resolve:t,reject:r,timeout:i})})}handleAck(e){let t=this.pendingAcks.get(e);if(t)clearTimeout(t.timeout),t.resolve(!0),this.pendingAcks.delete(e)}startHeartbeat(){if(this.heartbeatTimer)return;this.heartbeatTimer=setInterval(()=>{this.send({event:"heartbeat",timestamp:Date.now()})},this.config.heartbeat.interval)}stopHeartbeat(){if(this.heartbeatTimer)clearInterval(this.heartbeatTimer),this.heartbeatTimer=null}globalCallbacks=new Map;listen(e,t){if(!this.globalCallbacks.has(e))this.globalCallbacks.set(e,new Set);this.globalCallbacks.get(e).add(t)}stopListening(e,t){if(!t)this.globalCallbacks.delete(e);else this.globalCallbacks.get(e)?.delete(t)}send(e){let t=JSON.stringify(e);if(this.ws?.readyState===WebSocket.OPEN)this.ws.send(t);else if(this.config.offlineQueue?.enabled)if(this.messageQueue.length<(this.config.offlineQueue.maxSize??100))this.messageQueue.push({message:t});else console.warn("Message queue is full, dropping message")}handleMessage(e){try{let t=JSON.parse(e);if(t.event==="connection_established"){this._socketId=t.data.socket_id;return}if(t.event==="ack"&&t.messageId){this.handleAck(t.messageId);return}let r=this.globalCallbacks.get(t.event);if(r)for(let i of r)i(t.data);if(t.channel){let i=this.channels.get(t.channel);if(i)i.handleEvent(t.event,t.data)}}catch(t){console.error("Error parsing message:",t)}}}class zi{client;name;callbacks=new Map;isSubscribed=!1;constructor(e,t){this.client=e,this.name=t}subscribe(){if(this.isSubscribed)return;this.client.send({event:"subscribe",channel:this.name})}unsubscribe(){if(!this.isSubscribed)return;this.client.send({event:"unsubscribe",channel:this.name}),this.isSubscribed=!1,this.callbacks.clear()}listen(e,t){if(!this.callbacks.has(e))this.callbacks.set(e,new Set);return this.callbacks.get(e).add(t),this}stopListening(e,t){if(!t)this.callbacks.delete(e);else{let r=this.callbacks.get(e);if(r)r.delete(t)}return this}handleEvent(e,t){if(e==="subscription_succeeded")this.isSubscribed=!0;else if(e==="subscription_error")this.isSubscribed=!1;let r=this.callbacks.get(e);if(r)for(let i of r)i(t)}getName(){return this.name}}class br extends zi{subscribed(e){return this.listen("subscription_succeeded",e)}error(e){return this.listen("subscription_error",e)}}class wr extends br{whisper(e,t){return this.client.send({event:`client-${e}`,channel:this.name,data:t}),this}listenForWhisper(e,t){return this.listen(`client-${e}`,t)}}class Ji extends wr{members=new Map;presenceHeartbeatTimer=null;subscribe(){super.subscribe(),this.startPresenceHeartbeat()}unsubscribe(){this.stopPresenceHeartbeat(),super.unsubscribe()}startPresenceHeartbeat(){this.presenceHeartbeatTimer=setInterval(()=>{this.client.send({event:"presence_heartbeat",channel:this.name,timestamp:Date.now()})},30000)}stopPresenceHeartbeat(){if(this.presenceHeartbeatTimer)clearInterval(this.presenceHeartbeatTimer),this.presenceHeartbeatTimer=null}handleEvent(e,t){if(e==="subscription_succeeded"&&t?.presence){for(let[i,s]of Object.entries(t.presence.hash))this.members.set(i,s);let r=this.callbacks.get("here");if(r){let i=Array.from(this.members.values());for(let s of r)s(i)}}else if(e==="member_added"){this.members.set(t.id,t);let r=this.callbacks.get("joining");if(r)for(let i of r)i(t)}else if(e==="member_removed"){this.members.delete(t.id);let r=this.callbacks.get("leaving");if(r)for(let i of r)i(t)}super.handleEvent(e,t)}here(e){return this.listen("here",e)}joining(e){return this.listen("joining",e)}leaving(e){return this.listen("leaving",e)}getMembers(){return Array.from(this.members.values())}getMember(e){return this.members.get(e)||null}}var j=null,vr=[];function Bl(){return j}async function Il(e){if(j)return j;let t=e.driver??"bun",r=e.host??"0.0.0.0",i=e.port??6001,s=e.scheme??"ws",n={verbose:e.verbose??!1,driver:t,default:t,connections:{[t]:{driver:t,host:r,port:i,scheme:s}}};return j=new Se(n),O.setServer(j),await j.start(),j}async function Rl(){for(let e of vr)clearInterval(e);if(vr.length=0,!j)return;await j.stop(),j=null}async function Dl(e){let t=await import(e),r=t.default??t;if(typeof r!=="function")throw Error(`routes/channels.ts must export a default function, got ${typeof r}`);let i=0;return r({channel(s,n){if(i++,n.authorize&&j)j.channels.channel(s,n.authorize);if(n.interval&&n.data){let a=n.event??`${s}.updated`,l=n.data,o=setInterval(async()=>{try{let c=await l();ha(s,a,c)}catch{}},n.interval);vr.push(o)}}}),i}var Hi=!1;function xe(){if(j)return!0;if(!Hi)Hi=!0,console.warn("[stx] broadcast() called before server started \u2014 messages will be sent once broadcasting is ready");return!1}function ha(e,t,r){if(!xe())return;O.send(e,t,r)}function Fl(e,t,r){if(!xe())return;O.toUser(e,t,r)}function jl(e,t,r){if(!xe())return;O.toUsers(e,t,r)}function Ll(e,t,r){if(!xe())return;O.send(`private-${e}`,t,r)}function _l(e,t,r){if(!xe())return;O.presence(e,t,r)}
62
+ export{Se as a,O as b,la as c,Bl as d,Il as e,Rl as f,Dl as g,ha as h,Fl as i,jl as j,Ll as k,_l as l};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{jj as c,kj as d,lj as e,mj as f,nj as g,oj as h,pj as i,qg as a,qj as j,rg as b,rj as k}from"./chunk-tpfgntwj.js";import"./chunk-jff6j9y3.js";import"./chunk-csfrpsp7.js";import"./chunk-0t5vz87j.js";import"./chunk-krkchy8v.js";import"./chunk-brpgjyqg.js";import"./chunk-5mxby3fd.js";import"./chunk-5be9x5cq.js";import"./chunk-jmeb7n8k.js";import"./chunk-kc659vhx.js";import"./chunk-a3wahyg7.js";export{b as stripCommentsAndLiterals,d as renderVendorStyleTags,k as processClientScript,f as injectBrowserCoreAutoImports,j as generateServerDataBridge,h as generateBrowserAutoImportDestructuring,g as generateAutoImportDestructuring,a as findInterpolationEnd,i as extractBridgeData,c as extractAndStripCssImports,e as STX_AUTO_IMPORTS};