@stacksjs/ts-css 0.1.4 → 0.3.2

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 (56) hide show
  1. package/ENGINE.md +677 -0
  2. package/PLUGIN.md +217 -0
  3. package/dist/bin/cli.js +29 -38
  4. package/dist/bin/cssx.js +405 -0
  5. package/dist/chunk-0h48763m.js +2 -0
  6. package/dist/chunk-br9jax0b.js +2 -0
  7. package/dist/chunk-f9gzb0a5.js +3 -0
  8. package/dist/chunk-genwkevp.js +3 -0
  9. package/dist/chunk-jj3s4ctf.js +62 -0
  10. package/dist/chunk-mz87cw2e.js +2 -0
  11. package/dist/engine/build.d.ts +26 -0
  12. package/dist/engine/color-modifier.d.ts +8 -0
  13. package/dist/engine/config.d.ts +5 -0
  14. package/dist/engine/format.d.ts +20 -0
  15. package/dist/engine/generator.d.ts +14 -0
  16. package/dist/engine/index.d.ts +13 -0
  17. package/dist/engine/index.js +653 -0
  18. package/dist/engine/parser.d.ts +68 -0
  19. package/dist/engine/plugin.d.ts +22 -0
  20. package/dist/engine/preflight-forms.d.ts +6 -0
  21. package/dist/engine/preflight.d.ts +3 -0
  22. package/dist/engine/rules-advanced.d.ts +27 -0
  23. package/dist/engine/rules-effects.d.ts +35 -0
  24. package/dist/engine/rules-forms.d.ts +8 -0
  25. package/dist/engine/rules-grid.d.ts +13 -0
  26. package/dist/engine/rules-icons.d.ts +2 -0
  27. package/dist/engine/rules-interactivity.d.ts +41 -0
  28. package/dist/engine/rules-layout.d.ts +28 -0
  29. package/dist/engine/rules-transforms.d.ts +35 -0
  30. package/dist/engine/rules-typography.d.ts +47 -0
  31. package/dist/engine/rules.d.ts +56 -0
  32. package/dist/engine/scanner.d.ts +16 -0
  33. package/dist/engine/style/api.d.ts +95 -0
  34. package/dist/engine/style/collect.d.ts +10 -0
  35. package/dist/engine/style/evaluate.d.ts +11 -0
  36. package/dist/engine/style/hash.d.ts +15 -0
  37. package/dist/engine/style/index.d.ts +56 -0
  38. package/dist/engine/style/plugin.d.ts +27 -0
  39. package/dist/engine/style/priority.d.ts +12 -0
  40. package/dist/engine/style/registry.d.ts +56 -0
  41. package/dist/engine/style/types.d.ts +54 -0
  42. package/dist/engine/style/value.d.ts +15 -0
  43. package/dist/engine/transformer-compile-class.d.ts +34 -0
  44. package/dist/engine/types.d.ts +156 -0
  45. package/dist/index.js +1 -60
  46. package/dist/optimize/index.js +1 -1
  47. package/dist/parse/index.js +1 -1
  48. package/dist/parse/list.d.ts +1 -1
  49. package/dist/select/index.js +1 -1
  50. package/dist/what/index.js +1 -1
  51. package/package.json +35 -19
  52. package/dist/chunk-1kmkypmr.js +0 -3
  53. package/dist/chunk-2wsah70r.js +0 -2
  54. package/dist/chunk-9ep6bwwb.js +0 -2
  55. package/dist/chunk-edwg811g.js +0 -2
  56. package/dist/chunk-thy3p95k.js +0 -3
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{r}from"./chunk-br9jax0b.js";import{u}from"./chunk-genwkevp.js";var S={};u(S,{clearSelectorCache:()=>L,compile:()=>h,is:()=>R,parseAndCompile:()=>i,selectAll:()=>v,selectOne:()=>C});function Q(l,o,t,a){let d=[],f=[o],n=[0];for(;;){if(n[0]>=f[0].length){if(f.length===1)return d;f.shift(),n.shift();continue}let e=f[0][n[0]++];if(!t.isTag(e))continue;if(l(e))d.push(e);if(a||t.getName(e)!=="template"){let s=t.getChildren(e);if(s.length>0)f.unshift(s),n.unshift(0)}}}function x(l,o,t,a){let d=[o],f=[0];for(;;){if(f[0]>=d[0].length){if(d.length===1)return null;d.shift(),f.shift();continue}let n=d[0][f[0]++];if(!t.isTag(n))continue;if(l(n))return n;if(a||t.getName(n)!=="template"){let e=t.getChildren(n);if(e.length>0)d.unshift(e),f.unshift(0)}}}function O(l,o){if(Array.isArray(l))return o.removeSubsets(l);return o.getChildren(l)}var y=(l)=>!0;function V(l){return l===32||l===9||l===10||l===12||l===13}function b(l,o){let t=o.length,a=l.length;if(t===0||t>a)return!1;let d=l.indexOf(o);while(d>=0){let f=d===0||V(l.charCodeAt(d-1)),n=d+t,e=n===a||V(l.charCodeAt(n));if(f&&e)return!0;d=l.indexOf(o,d+1)}return!1}function q(l,o,t){if(o.ignoreCase===!0)return!0;if(o.ignoreCase===!1)return!1;if(o.ignoreCase==="quirks")return!t.xmlMode;return!1}function P(l,o,t){let a=o.adapter,{action:d,name:f,value:n}=l,e=q(n,l,o);if(e)n=n.toLowerCase();return D(d,f,n,e,a,t)}function D(l,o,t,a,d,f){let n=f===y;switch(l){case"exists":if(n)return(e)=>d.hasAttrib(e,o);return(e)=>d.hasAttrib(e,o)&&f(e);case"equals":if(!a){if(n)return(e)=>d.getAttributeValue(e,o)===t;return(e)=>d.getAttributeValue(e,o)===t&&f(e)}if(n)return(e)=>{let s=d.getAttributeValue(e,o);if(s==null)return!1;return s.toLowerCase()===t};return(e)=>{let s=d.getAttributeValue(e,o);if(s==null)return!1;return s.toLowerCase()===t&&f(e)};case"not":return(e)=>{let s=d.getAttributeValue(e,o);if(s==null)return f(e);return(a?s.toLowerCase():s)!==t&&f(e)};case"start":if(t==="")return()=>!1;if(n)return(e)=>{let s=d.getAttributeValue(e,o);if(s==null)return!1;return(a?s.toLowerCase():s).startsWith(t)};return(e)=>{let s=d.getAttributeValue(e,o);if(s==null)return!1;return(a?s.toLowerCase():s).startsWith(t)&&f(e)};case"end":if(t==="")return()=>!1;if(n)return(e)=>{let s=d.getAttributeValue(e,o);if(s==null)return!1;return(a?s.toLowerCase():s).endsWith(t)};return(e)=>{let s=d.getAttributeValue(e,o);if(s==null)return!1;return(a?s.toLowerCase():s).endsWith(t)&&f(e)};case"any":{if(t==="")return()=>!1;if(a){if(n)return(e)=>{let s=d.getAttributeValue(e,o);if(s==null)return!1;return s.toLowerCase().indexOf(t)>=0};return(e)=>{let s=d.getAttributeValue(e,o);if(s==null)return!1;return s.toLowerCase().indexOf(t)>=0&&f(e)}}if(n)return(e)=>{let s=d.getAttributeValue(e,o);if(s==null)return!1;return s.indexOf(t)>=0};return(e)=>{let s=d.getAttributeValue(e,o);if(s==null)return!1;return s.indexOf(t)>=0&&f(e)}}case"element":{if(t===""||/\s/.test(t))return()=>!1;if(a){if(n)return(e)=>{let s=d.getAttributeValue(e,o);if(s==null)return!1;return b(s.toLowerCase(),t)};return(e)=>{let s=d.getAttributeValue(e,o);if(s==null)return!1;return b(s.toLowerCase(),t)&&f(e)}}if(n)return(e)=>{let s=d.getAttributeValue(e,o);if(s==null)return!1;return b(s,t)};return(e)=>{let s=d.getAttributeValue(e,o);if(s==null)return!1;return b(s,t)&&f(e)}}case"hyphen":if(n)return(e)=>{let s=d.getAttributeValue(e,o);if(s==null)return!1;let c=a?s.toLowerCase():s;if(c===t)return!0;if(c.startsWith(t)&&c.charAt(t.length)==="-")return!0;return!1};return(e)=>{let s=d.getAttributeValue(e,o);if(s==null)return!1;let c=a?s.toLowerCase():s;if(c===t)return f(e);if(c.startsWith(t)&&c.charAt(t.length)==="-")return f(e);return!1}}return(e)=>!1}var k=new Set(["link","any-link","visited","hover","active","focus","focus-visible","focus-within","target","target-within","enabled","disabled","checked","required","optional","valid","invalid","selected","placeholder-shown","read-only","read-write","in-range","out-of-range","default","indeterminate"]),G=new Set(["is","where","matches","-moz-any","-webkit-any"]),I=new Set(["nth-child","nth-last-child","nth-of-type","nth-last-of-type"]);function W(l,o,t){let a=o.adapter,{name:d,data:f}=l;if(l.type==="pseudo"&&G.has(d)){if(!Array.isArray(f))return t;let n=f.map((e)=>i(e,o));if(n.length===1){let e=n[0];return(s)=>e(s)&&t(s)}return(e)=>{for(let s of n)if(s(e))return t(e);return!1}}if(l.type==="pseudo"&&d==="not"){if(!Array.isArray(f))return t;let n=f.map((e)=>i(e,o));if(n.length===1){let e=n[0];return(s)=>!e(s)&&t(s)}return(e)=>{for(let s of n)if(s(e))return!1;return t(e)}}if(l.type==="pseudo"&&d==="has"){if(!Array.isArray(f))return t;let n=f.map((s)=>i(s,o)),e=n.length===1?n[0]:(s)=>{for(let c of n)if(c(s))return!0;return!1};return(s)=>{let c=a.getChildren(s).slice();while(c.length>0){let m=c.pop();if(!a.isTag(m))continue;if(e(m))return t(s);let p=a.getChildren(m);for(let N=0;N<p.length;N++)c.push(p[N])}return!1}}if(l.type==="pseudo"&&I.has(d)){let n=F(typeof f==="string"?f:"",d,o);return(e)=>n(e)&&t(e)}if(l.type==="pseudo"&&d==="first-child")return(n)=>{let e=a.getSiblings(n);for(let s of e){if(!a.isTag(s))continue;return s===n&&t(n)}return!1};if(l.type==="pseudo"&&d==="last-child")return(n)=>{let e=a.getSiblings(n);for(let s=e.length-1;s>=0;s--){let c=e[s];if(!a.isTag(c))continue;return c===n&&t(n)}return!1};if(l.type==="pseudo"&&d==="first-of-type")return(n)=>{let e=a.getName(n),s=a.getSiblings(n);for(let c of s){if(!a.isTag(c)||a.getName(c)!==e)continue;return c===n&&t(n)}return!1};if(l.type==="pseudo"&&d==="last-of-type")return(n)=>{let e=a.getName(n),s=a.getSiblings(n);for(let c=s.length-1;c>=0;c--){let m=s[c];if(!a.isTag(m)||a.getName(m)!==e)continue;return m===n&&t(n)}return!1};if(l.type==="pseudo"&&d==="only-child")return(n)=>{let e=a.getSiblings(n),s=0,c=!1;for(let m of e){if(!a.isTag(m))continue;if(s++,s>1)return!1;if(m===n)c=!0}return s===1&&c&&t(n)};if(l.type==="pseudo"&&d==="only-of-type")return(n)=>{let e=a.getName(n),s=a.getSiblings(n),c=0,m=!1;for(let p of s){if(!a.isTag(p)||a.getName(p)!==e)continue;if(c++,c>1)return!1;if(p===n)m=!0}return c===1&&m&&t(n)};if(l.type==="pseudo"&&d==="empty")return(n)=>a.getChildren(n).length===0&&t(n);if(l.type==="pseudo"&&d==="root")return(n)=>{let e=a.getParent(n);return(e==null||!a.isTag(e))&&t(n)};if(l.type==="pseudo"&&d==="scope"){if(o.context&&Array.isArray(o.context)){let n=new Set(o.context);return(e)=>n.has(e)&&t(e)}if(o.context){let n=o.context;return(e)=>e===n&&t(e)}return(n)=>{let e=a.getParent(n);return(e==null||!a.isTag(e))&&t(n)}}if(l.type==="pseudo"&&k.has(d)){if(o.pseudos&&o.pseudos[d]){let n=o.pseudos[d];if(typeof n==="function")return(e)=>n(e,void 0)&&t(e)}return(n)=>!1}if(l.type==="pseudo-element")return t;if(o.pseudos&&o.pseudos[d]){let n=o.pseudos[d];if(typeof n==="function")return(e)=>n(e,typeof f==="string"?f:void 0)&&t(e);if(typeof n==="string"){let e=r(n),s=g(e,o);return(c)=>s(c)&&t(c)}}return(n)=>!1}function Y(l){let o=l.trim();if(o==="odd")return{a:2,b:1};if(o==="even")return{a:2,b:0};let t=/^([+-]?\d*)n([+-]\d+)?$/.exec(o.replace(/\s+/g,""));if(t){let d=t[1]===""||t[1]==="+"?1:t[1]==="-"?-1:Number(t[1]),f=t[2]?Number(t[2]):0;return{a:d,b:f}}let a=Number(o);if(!Number.isNaN(a))return{a:0,b:a};return null}function F(l,o,t){let a=Y(l);if(!a)return()=>!1;let{a:d,b:f}=a,n=t.adapter,e=o==="nth-of-type"||o==="nth-last-of-type",s=o==="nth-last-child"||o==="nth-last-of-type";return(c)=>{let m=n.getSiblings(c),p=e?n.getName(c):"",N=0,A=0;for(let T of m){if(!n.isTag(T))continue;if(e&&n.getName(T)!==p)continue;if(A++,T===c)N=A}if(N===0)return!1;let w=s?A-N+1:N;if(d===0)return w===f;return(w-f)/d>=0&&(w-f)%d===0}}function M(l,o,t){let a=o.adapter,d=t===y;switch(l.type){case"tag":{let f=o.lowerCaseTags!==!1&&!o.xmlMode?l.name.toLowerCase():l.name;if(d)return(n)=>a.getName(n)===f;return(n)=>a.getName(n)===f&&t(n)}case"universal":return t;case"attribute":return P(l,o,t);case"pseudo":case"pseudo-element":return W(l,o,t);case"descendant":case"child":case"parent":case"sibling":case"adjacent":case"column-combinator":return t}return(f)=>!1}var B={universal:50,tag:30,attribute:1,pseudo:0,"pseudo-element":0},z={exists:10,equals:8,not:7,start:6,end:6,hyphen:5,any:4,element:3};function U(l){let o=B[l.type]??0;if(l.type==="attribute")return o+(z[l.action]??0);return o}function g(l,o){if(l.length===1)return i(l[0],o);let t=l.map((a)=>i(a,o));return(a)=>t.some((d)=>d(a))}function i(l,o){let t=o.adapter,a=[[]],d=[];for(let n of l)if(n.type==="descendant"||n.type==="child"||n.type==="sibling"||n.type==="adjacent"||n.type==="parent"||n.type==="column-combinator")d.push(n),a.push([]);else a[a.length-1].push(n);let f=y;for(let n=0;n<a.length;n++){let e=a[n].slice().sort((s,c)=>U(s)-U(c));for(let s of e)f=M(s,o,f);if(n<d.length)f=H(d[n],f,t)}return f}function H(l,o,t){switch(l.type){case"descendant":case"column-combinator":return(a)=>{let d=t.getParent(a);while(d){if(t.isTag(d)&&o(d))return!0;d=t.getParent(d)}return!1};case"child":return(a)=>{let d=t.getParent(a);return d!=null&&t.isTag(d)&&o(d)};case"sibling":return(a)=>{let d=t.getSiblings(a);for(let f of d){if(f===a)return!1;if(t.isTag(f)&&o(f))return!0}return!1};case"adjacent":return(a)=>{let d=t.getSiblings(a),f=null;for(let n of d){if(n===a)return f!=null&&t.isTag(f)&&o(f);f=n}return!1};case"parent":return(a)=>t.existsOne(o,t.getChildren(a))}return(a)=>!1}function j(l){if(!l||!l.adapter)throw Error("css-select: adapter is required");return l.adapter}var E=new WeakMap;function J(l){return(l.xmlMode?1:0)<<0|(l.lowerCaseAttributeNames===!1?1:0)<<1|(l.lowerCaseTags===!1?1:0)<<2}function K(l,o){let t=E.get(l);if(!t)t=[],E.set(l,t);let a=t[o];if(!a)a=new Map,t[o]=a;return a}function _(l,o){let t=r(l,{xmlMode:o.xmlMode,lowerCaseAttributeNames:o.lowerCaseAttributeNames,lowerCaseTags:o.lowerCaseTags});return g(t,o)}function h(l,o){if(typeof l!=="string")return g(l,o);if(o.cacheResults===!1||!o.adapter)return _(l,o);let t=K(o.adapter,J(o)),a=t.get(l);if(a!==void 0)return a;return a=_(l,o),t.set(l,a),a}function L(l,o){if(o===void 0){E.delete(l);return}let t=E.get(l);if(!t)return;for(let a of t)if(a)a.delete(o)}function v(l,o,t){let a=j(t),d=typeof l==="function"?l:h(l,t),f=O(o,a);return Q(d,f,a,t.xmlMode===!0)}function C(l,o,t){let a=j(t),d=typeof l==="function"?l:h(l,t),f=O(o,a);return x(d,f,a,t.xmlMode===!0)}function R(l,o,t){return(typeof o==="function"?o:h(o,t))(l)}export{i,h,L,v,C,R,S};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{u}from"./chunk-genwkevp.js";var P={};u(P,{IgnoreCaseMode:()=>O,isTraversal:()=>w,parse:()=>r,stringify:()=>g});var E=/(?:\\(?:[\dA-Fa-f]{1,6} ?|[^])|[\w\-\u00B0-\uFFFF])+/y,_=/\\([\dA-Fa-f]{1,6} ?|[^])/g;function j(e){return e.replace(_,(a,i)=>{if(i.length>1&&/^[\dA-Fa-f]/.test(i)){let l=Number.parseInt(i,16);if(l>=55296&&l<=57343)return"\uFFFD";return String.fromCodePoint(l)}return i})}function I(e){return e.indexOf("\\")<0?e:j(e)}var U=new Set(["accept","accept-charset","align","alink","axis","bgcolor","charset","checked","clear","codetype","color","compact","declare","defer","dir","direction","disabled","enctype","face","frame","hreflang","http-equiv","lang","language","link","media","method","multiple","nohref","noresize","noshade","nowrap","readonly","rel","rev","rules","scope","scrolling","selected","shape","target","text","type","valign","valuetype","vlink"]);function L(e){switch(e){case 126:return"element";case 94:return"start";case 36:return"end";case 42:return"any";case 33:return"not";case 124:return"hyphen";default:return null}}function x(e){return e===32||e===9||e===10||e===13||e===12}function r(e,a={}){let i=[],l=R(i,e,a,0);if(l<e.length)throw Error(`Unmatched selector: ${e.slice(l)}`);return i}function h(e,a){E.lastIndex=a;let i=E.exec(e);if(!i)throw Error(`Expected name, found ${e.slice(a)}`);return{value:I(i[0]),end:a+i[0].length}}function C(e,a){while(a<e.length&&x(e.charCodeAt(a)))a++;return a}function R(e,a,i,l){let o=[],t=C(a,l),n=a.length,d=i.xmlMode===!0,p=i.lowerCaseAttributeNames!==!1&&!d,m=i.lowerCaseTags!==!1;while(t<n){let c=a.charCodeAt(t);if(x(c)){let s=t+1;while(s<n&&x(a.charCodeAt(s)))s++;if(o.length===0)return s;t=s,A(o,"descendant");continue}if(c===62||c===60||c===126||c===43||c===124){let s=t+1;while(s<n&&x(a.charCodeAt(s)))s++;switch(t=s,c){case 62:A(o,"child");break;case 60:A(o,"parent");break;case 126:A(o,"sibling");break;case 43:A(o,"adjacent");break;case 124:if(t<n&&a.charCodeAt(t)===124)t++,t=C(a,t),A(o,"column-combinator");else o.push({type:"tag",name:"",namespace:""});break}continue}if(c===44){if(o.length===0)throw Error("Empty sub-selector");e.push(o),o=[],t=C(a,t+1);continue}if(c===47&&a.charCodeAt(t+1)===42){let s=a.indexOf("*/",t+2);if(s<0)throw Error("Unmatched comment");t=C(a,s+2);continue}if(c===42){t++,o.push({type:"universal",namespace:null});continue}if(c===35){let s=h(a,t+1);t=s.end,o.push({type:"attribute",name:"id",action:"equals",value:s.value,namespace:null,ignoreCase:!1});continue}if(c===46){let s=h(a,t+1);t=s.end,o.push({type:"attribute",name:"class",action:"element",value:s.value,namespace:null,ignoreCase:!1});continue}if(c===91){t=F(a,t,o,i,d,p);continue}if(c===58){t=M(a,t,o,i);continue}if(c===124){t++;let s=h(a,t);t=s.end,o.push({type:"tag",name:m?s.value.toLowerCase():s.value,namespace:""});continue}{let s=h(a,t);if(t=s.end,t<n&&a.charCodeAt(t)===124&&a.charCodeAt(t+1)!==61){t++;let b=h(a,t);t=b.end,o.push({type:"tag",name:m?b.value.toLowerCase():b.value,namespace:s.value})}else o.push({type:"tag",name:m?s.value.toLowerCase():s.value,namespace:null})}}if(o.length>0)e.push(o);return t}function F(e,a,i,l,o,t){let n=a+1,d=e.length,p;if(e.charCodeAt(n)===124)throw Error("Empty namespace not supported");if(e.charCodeAt(n)===42&&e.charCodeAt(n+1)===124){n+=2;let f=h(e,n);n=f.end,p=f.value}else{let f=h(e,n);if(n=f.end,p=f.value,e.charCodeAt(n)===124&&e.charCodeAt(n+1)!==61){n++;let y=h(e,n);n=y.end,p=y.value}}n=C(e,n);let m="exists",c="",s=null,b=e.charCodeAt(n);if(b===61)m="equals",n++;else if(b===33&&e.charCodeAt(n+1)===61)m="not",n+=2;else{let f=L(b);if(f!==null&&e.charCodeAt(n+1)===61)m=f,n+=2}if(m!=="exists"){n=C(e,n);let f=e.charCodeAt(n);if(f===34||f===39){let S=q(e,n+1,f);c=I(e.slice(n+1,S)),n=S+1}else{let S=h(e,n);c=S.value,n=S.end}n=C(e,n);let y=e.charCodeAt(n);if(y===105||y===73)s=!0,n++;else if(y===115||y===83)s=!1,n++}if(e.charCodeAt(n)!==93)throw Error("Expected ]");if(n++,s===null&&!o&&U.has(p.toLowerCase()))s="quirks";return i.push({type:"attribute",name:t?p.toLowerCase():p,action:m,value:c,namespace:null,ignoreCase:s}),n}function M(e,a,i,l){if(e.charCodeAt(a+1)===58){let d=a+2,p=h(e,d);d=p.end;let m=p.value.toLowerCase(),c=null;if(e.charCodeAt(d)===40){let s=T(e,d);c=e.slice(d+1,s).trim(),d=s+1}return i.push({type:"pseudo-element",name:m,data:c}),d}let o=a+1,t=h(e,o);o=t.end;let n=t.value.toLowerCase();if(e.charCodeAt(o)===40){let d=T(e,o),p=e.slice(o+1,d);if(o=d+1,n==="is"||n==="not"||n==="where"||n==="has"||n==="matches"||n==="-moz-any"||n==="-webkit-any"){let m=[];R(m,p.trim(),l,0),i.push({type:"pseudo",name:n,data:m})}else i.push({type:"pseudo",name:n,data:p.trim()})}else i.push({type:"pseudo",name:n,data:null});return o}function A(e,a){if(e.length>0&&e[e.length-1].type==="descendant"&&a!=="descendant")e.pop();if(e.length>0&&e[e.length-1].type===a)return;e.push({type:a})}function q(e,a,i){let l=a,o=e.length;while(l<o){let t=e.charCodeAt(l);if(t===92){l+=2;continue}if(t===i)return l;l++}throw Error("Unterminated string")}function T(e,a){let i=1,l=a+1,o=e.length;while(l<o){let t=e.charCodeAt(l);if(t===92){l+=2;continue}if(t===34||t===39){l=q(e,l+1,t)+1;continue}if(t===40)i++;else if(t===41){if(i--,i===0)return l}l++}throw Error("Unterminated parenthesis")}var D={child:" > ",parent:" < ",sibling:" ~ ",adjacent:" + ",descendant:" ","column-combinator":" || "};function g(e){return e.map(z).join(", ")}function z(e){return e.map((a,i)=>B(a,e[i-1])).join("")}function B(e,a){switch(e.type){case"tag":return`${N(e.namespace)}${v(e.name)}`;case"universal":return`${N(e.namespace)}*`;case"attribute":{if(e.name==="id"&&e.action==="equals"&&!e.ignoreCase&&!e.namespace)return`#${v(e.value)}`;if(e.name==="class"&&e.action==="element"&&!e.ignoreCase&&!e.namespace)return`.${v(e.value)}`;let i=`[${N(e.namespace)}${v(e.name)}`;if(e.action!=="exists"){let l=K[e.action]??"=";if(i+=l,i+=`"${e.value.replace(/"/g,"\\\"")}"`,e.ignoreCase===!0)i+=" i";else if(e.ignoreCase===!1)i+=" s"}return i+="]",i}case"pseudo":if(e.data===null)return`:${e.name}`;if(typeof e.data==="string")return`:${e.name}(${e.data})`;return`:${e.name}(${g(e.data)})`;case"pseudo-element":return e.data===null?`::${e.name}`:`::${e.name}(${e.data})`;case"descendant":case"child":case"parent":case"sibling":case"adjacent":case"column-combinator":return D[e.type]??" "}return""}var K={equals:"=",element:"~=",start:"^=",end:"$=",any:"*=",not:"!=",hyphen:"|="};function N(e){if(e===null)return"";if(e==="")return"|";return`${v(e)}|`}var Q=/[^\w\u00B0-\uFFFF-]/g;function v(e){if(e==="")return"";return e.replace(Q,(a)=>`\\${a}`)}var V=new Set(["adjacent","child","descendant","parent","sibling","column-combinator"]);function w(e){return V.has(e.type)}var O={Unknown:null,QuirksMode:"quirks",IgnoreCase:!0,CaseSensitive:!1};export{r,g,w,O,P};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{e,o,n}from"./chunk-mz87cw2e.js";import{r}from"./chunk-br9jax0b.js";import{u}from"./chunk-genwkevp.js";var A={};u(A,{compressTree:()=>p,dedupeDeclarations:()=>f,minify:()=>m,minifyBlock:()=>l,removeComments:()=>a,specificity:()=>c,specificityToString:()=>E,syntax:()=>k});function a(i,t={}){let s=t.exclamation??!1,y=!1;n(i,(d,b,g)=>{if(d.type!=="Comment")return;let h=d.value.startsWith("!");if(s===!0&&h)return;if(s==="first-exclamation"&&h&&!y){y=!0;return}if(b&&g)g.remove(b)})}function f(i){n(i,(t)=>{if(t.type!=="Block"&&t.type!=="DeclarationList")return;if(!("children"in t)||!t.children)return;let s=t.children,y=s.head;if(y==null||y.next==null)return;let d=0;for(let h=y;h!=null;h=h.next)if(h.data.type==="Declaration"){if(d++,d>=2)break}if(d<2)return;let b=new Map,g=[];for(let h=y;h!=null;h=h.next){let x=h.data;if(x.type!=="Declaration")continue;let v=x.property,C=b.get(v);if(C){let z=!!C.decl.important,M=!!x.important;if(M||z===M)g.push(C.item),b.set(v,{item:h,decl:x});else g.push(h)}else b.set(v,{item:h,decl:x})}for(let h of g)s.remove(h)})}var G={black:"#000",fuchsia:"#f0f",white:"#fff",red:"#f00",cyan:"#0ff",blue:"#00f",yellow:"#ff0",magenta:"#f0f",lime:"#0f0",silver:"#c0c0c0",gray:"#808080",maroon:"#800000",olive:"#808000",green:"#008000",purple:"#800080",teal:"#008080",navy:"#000080"},U={"#f00":"red","#ff0000":"red","#000080":"navy","#008080":"teal"};function w(i){if(!i.startsWith("#"))return i;let t=i.slice(1);if(t.length===6){if(t[0]===t[1]&&t[2]===t[3]&&t[4]===t[5])return`#${t[0]}${t[2]}${t[4]}`}if(t.length===8){if(t[0]===t[1]&&t[2]===t[3]&&t[4]===t[5]&&t[6]===t[7])return`#${t[0]}${t[2]}${t[4]}${t[6]}`}return i}function W(i){let t=i.toLowerCase();return G[t]??null}function R(i){let t=i.toLowerCase();return U[t]??null}function X(i,t,s){let y=(i<<16|t<<8|s).toString(16).padStart(6,"0");return w(`#${y}`)}var j=/^rgba?\(\s*([+-]?\d*\.?\d+%?)\s*[,\s]\s*([+-]?\d*\.?\d+%?)\s*[,\s]\s*([+-]?\d*\.?\d+%?)\s*(?:[,/]\s*([+-]?\d*\.?\d+%?)\s*)?\)$/;function P(i){let t=j.exec(i.trim());if(!t)return i;let s=N(t[1]),y=N(t[2]),d=N(t[3]);if(t[4]!==void 0&&!V(t[4]))return i;return X(s,y,d)}function V(i){if(i.endsWith("%"))return Number.parseFloat(i)>=100;return Number.parseFloat(i)>=1}function N(i){if(i.endsWith("%"))return Math.max(0,Math.min(255,Math.round(Number.parseFloat(i)*2.55)));return Math.max(0,Math.min(255,Math.round(Number.parseFloat(i))))}var Z=new Set(["px","pt","pc","in","cm","mm","q","em","rem","ex","ch","cap","ic","lh","rlh","vw","vh","vi","vb","vmin","vmax","svw","svh","svi","svb","svmin","svmax","lvw","lvh","lvi","lvb","lvmin","lvmax","dvw","dvh","dvi","dvb","dvmin","dvmax","cqw","cqh","cqi","cqb","cqmin","cqmax"]);function S(i){if(i.charCodeAt(0)===43)i=i.slice(1);if(i.includes(".")){let t=i.replace(/(\.\d*?)0+($|[eE])/,"$1$2");t=t.replace(/\.($|[eE])/,"$1"),i=t}if(i.startsWith("0.")&&i.length>2)i=i.slice(1);else if(i.startsWith("-0.")&&i.length>3)i=`-${i.slice(2)}`;if(i==="-0"||i==="-.0"||i==="-0.0")i="0";return i}function T(i,t){let s=S(i);if((s==="0"||s==="-0")&&Z.has(t.toLowerCase()))return{value:"0",unit:""};return{value:s,unit:t}}function I(i){return S(i)}function H(i,t){let s=Number.parseFloat(i);if(!Number.isFinite(s))return i;let y=t<0?0:t;return s.toFixed(y)}var _=new Set(["color","background","background-color","border","border-color","border-top","border-top-color","border-right","border-right-color","border-bottom","border-bottom-color","border-left","border-left-color","border-block","border-block-color","border-block-start-color","border-block-end-color","border-inline","border-inline-color","border-inline-start-color","border-inline-end-color","outline","outline-color","caret-color","fill","stroke","flood-color","lighting-color","stop-color","column-rule","column-rule-color","text-decoration","text-decoration-color","text-emphasis","text-emphasis-color","text-shadow","box-shadow","accent-color","scrollbar-color"]);function D(i){if(!i||i.type!=="Operator")return!1;let t=i.value;return t===":"||t===","||t==="/"}function J(i){let t=i.children;if(!t)return;while(t.head&&t.head.data.type==="WhiteSpace")t.remove(t.head);while(t.tail&&t.tail.data.type==="WhiteSpace")t.remove(t.tail);let s=t.head;while(s){let y=s.next;if(s.data.type==="WhiteSpace"){let d=s.prev&&D(s.prev.data),b=y&&D(y.data);if(d||b)t.remove(s)}s=y}}function p(i,t={}){let s=t.floatPrecision??null,y=s===null?null:(d)=>H(d,s);n(i,{enter(d,b,g){switch(d.type){case"Number":{let h=y?y(d.value):d.value;d.value=S(h);return}case"Percentage":{let h=y?y(d.value):d.value;d.value=I(h);return}case"Dimension":{let h=y?y(d.value):d.value,x=T(h,d.unit);d.value=x.value,d.unit=x.unit;return}case"Hash":{let h=w(`#${d.name}`).slice(1);if(d.name=h,b&&g&&this.declaration&&_.has(this.declaration.property.toLowerCase())){let x=R(`#${h}`);if(x&&x.length<h.length+1){let v={type:"Identifier",name:x,loc:d.loc};g.replace(b,g.createItem(v))}}return}case"Identifier":{if(!b||!g||!this.declaration)return;if(!_.has(this.declaration.property.toLowerCase()))return;let h=W(d.name);if(h&&h.length<d.name.length){let x={type:"Hash",name:h.slice(1),loc:d.loc};g.replace(b,g.createItem(x))}return}case"Url":return;case"Function":{let h=d.name.toLowerCase();if((h==="rgb"||h==="rgba")&&b&&g)d.__rgbReplaceCandidate=!0}}},leave(d,b,g){if(d.type==="Parentheses"||d.type==="Function"||d.type==="Value")J(d);if(d.type==="Function"&&d.__rgbReplaceCandidate&&b&&g){let h=e(d),x=P(h);if(x!==h&&x.startsWith("#")){let v={type:"Hash",name:x.slice(1),loc:d.loc};g.replace(b,g.createItem(v))}}}})}function m(i,t={}){let s=o(i,{context:"stylesheet"});return L(s,t)}function l(i,t={}){let s=o(i,{context:"declarationList"});return L(s,t)}function L(i,t){if(t.comments===!1)a(i,{exclamation:!1});else if(t.comments==="first-exclamation")a(i,{exclamation:"first-exclamation"});else a(i,{exclamation:!0});return p(i,{floatPrecision:t.floatPrecision??null}),f(i),{css:e(i),ast:i}}function c(i){let t=[0,0,0];if(typeof i==="string"){let s=r(i);return F(s,t),t}if(Array.isArray(i)){if(i.length===0)return t;if(Array.isArray(i[0]))F(i,t);else O(i,t);return t}return q(i,t),t}function q(i,t){switch(i.type){case"IdSelector":t[0]++;return;case"ClassSelector":case"AttributeSelector":t[1]++;return;case"TypeSelector":if(i.name!=="*")t[2]++;return;case"PseudoClassSelector":{let s=i.name.toLowerCase();if(s==="is"||s==="matches"||s==="-moz-any"||s==="-webkit-any"||s==="not"||s==="has"){if(i.children){let y=[];for(let b of i.children)if(b.type==="SelectorList"&&"children"in b&&b.children)for(let g of b.children)y.push(g);else if(b.type==="Selector")y.push(b);let d=[0,0,0];for(let b of y){let g=c(b);if(B(g,d)>0)d=g}t[0]+=d[0],t[1]+=d[1],t[2]+=d[2]}return}if(s==="where")return;t[1]++;return}case"PseudoElementSelector":t[2]++;return;case"Selector":case"SelectorList":case"AtrulePrelude":if("children"in i&&i.children)for(let s of i.children)q(s,t);return;case"NestingSelector":return}}function F(i,t){for(let s of i)O(s,t)}function O(i,t){for(let s of i)switch(s.type){case"tag":if(s.name!=="*")t[2]++;break;case"attribute":if(s.name==="id"&&s.action==="equals")t[0]++;else t[1]++;break;case"pseudo":{let y=s.name.toLowerCase();if(y==="is"||y==="matches"||y==="not"||y==="has"||y==="-moz-any"||y==="-webkit-any"){if(Array.isArray(s.data)){let d=[0,0,0];for(let b of s.data){let g=[0,0,0];if(O(b,g),B(g,d)>0)d=g}t[0]+=d[0],t[1]+=d[1],t[2]+=d[2]}break}if(y==="where")break;t[1]++;break}case"pseudo-element":t[2]++;break}}function B(i,t){for(let s=0;s<3;s++)if(i[s]!==t[s])return i[s]-t[s];return 0}function E(i){return i.join(",")}var k={specificity:c};
3
+ export{a,f,p,m,l,c,E,k,A};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ var d=Object.defineProperty;var e=(a)=>a;function f(a,b){this[a]=e.bind(null,b)}var u=(a,b)=>{for(var c in b)d(a,c,{get:b[c],enumerable:!0,configurable:!0,set:f.bind(b,c)})};
3
+ export{u};
@@ -0,0 +1,62 @@
1
+ // @bun
2
+ import{existsSync as Gt,statSync as qt}from"fs";import{resolve as ye}from"path";import vn from"process";import{existsSync as En,mkdirSync as Ds,readdirSync as Ms,readFileSync as bn,writeFileSync as Ls}from"fs";import{homedir as ie}from"os";import{dirname as Is,resolve as G}from"path";import tt from"process";import{existsSync as Yt,statSync as Ht}from"fs";import{existsSync as xt,mkdirSync as xn,readdirSync as Sn,writeFileSync as Tn}from"fs";import{homedir as se}from"os";import{dirname as Zt,resolve as j}from"path";import ne from"process";import{join as kn,relative as An,resolve as Xt}from"path";import Ve from"process";import{existsSync as Br,mkdirSync as Ys,readdirSync as Hs,writeFileSync as Zs}from"fs";import{homedir as st}from"os";import{dirname as eo,resolve as L}from"path";import ve from"process";import{join as Fn,relative as On,resolve as Qt}from"path";import We from"process";import{existsSync as Ir,mkdirSync as so,readdirSync as oo,writeFileSync as ao}from"fs";import{dirname as lo,resolve as ze}from"path";import St from"process";import{Buffer as ee}from"buffer";import{createCipheriv as Rn,createDecipheriv as Nn,randomBytes as ot}from"crypto";import{closeSync as at,createReadStream as er,createWriteStream as Pn,existsSync as ct,fsyncSync as tr,openSync as rr,writeFileSync as Dn}from"fs";import{access as Mn,constants as nr,mkdir as Ln,readdir as be,rename as ir,stat as oe,unlink as xe,writeFile as lt}from"fs/promises";import{join as ae}from"path";import P from"process";import{pipeline as jn}from"stream/promises";import{createGzip as sr}from"zlib";import ce from"process";import H from"process";import{Buffer as q}from"buffer";import{createCipheriv as Bn,createDecipheriv as In,randomBytes as ft}from"crypto";import{closeSync as ut,createReadStream as or,createWriteStream as _n,existsSync as Se,fsyncSync as ar,openSync as cr,writeFileSync as Kn}from"fs";import{access as Vn,constants as lr,mkdir as Wn,readdir as Te,rename as fr,stat as le,unlink as ke,writeFile as gt}from"fs/promises";import{isAbsolute as zn,join as fe,resolve as Un}from"path";import C from"process";import{pipeline as Jn}from"stream/promises";import{createGzip as ur}from"zlib";import ue from"process";import Z from"process";import Ae from"process";import{existsSync as Fe}from"fs";import{resolve as ht}from"path";import{existsSync as Gn}from"fs";import{existsSync as qn,readdirSync as Yn}from"fs";import{extname as mt,resolve as gr}from"path";import Hn from"process";import{join as Zn,relative as Xn,resolve as hr}from"path";import Ue from"process";import{Buffer as Y}from"buffer";import{createCipheriv as Qn,createDecipheriv as ei,randomBytes as dt}from"crypto";import{closeSync as pt,createReadStream as mr,createWriteStream as ti,existsSync as Oe,fsyncSync as dr,openSync as pr,writeFileSync as ri}from"fs";import{access as ni,constants as yr,mkdir as ii,readdir as Re,rename as wr,stat as ge,unlink as Ne,writeFile as yt}from"fs/promises";import{isAbsolute as si,join as he,resolve as oi}from"path";import E from"process";import{pipeline as ai}from"stream/promises";import{createGzip as vr}from"zlib";import me from"process";import X from"process";import De from"process";import{existsSync as Me}from"fs";import{resolve as Pr}from"path";import{existsSync as ks}from"fs";class Dr{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],[,n])=>r.timestamp.getTime()-n.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,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),o=n??this.options.ttl,a=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:o,hits:0,size:a}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!Gt(e))return!0;return qt(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,n){try{let i=Gt(r)?qt(r):null,o=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},r,n)}catch{this.set(e,t,r,n)}}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((n,i)=>n+i.size,0),r=e.map((n)=>n.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 n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Mr{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let o=await t(),a=performance.now()-n;return this.recordMetric({operation:e,duration:a,timestamp:i,...r}),o}catch(o){let a=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:a,timestamp:i,...r}),o}}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((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,o)=>i+o,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}var Ke=new Dr,Lt=new Mr;var Lr=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function jr(e={}){let{name:t="",alias:r}=e,n=["config",".config"];if(t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let i=r===void 0?[]:Array.isArray(r)?r:[r];for(let o of i){if(!o)continue;if(n.push(o,`.${o}.config`,`${o}.config`,`.${o}`),t)n.push(`${t}.${o}.config`,`.${t}.${o}.config`)}return Array.from(new Set(n.filter(Boolean)))}function $n(e){return jr(e).flatMap((r)=>Lr.map((n)=>ye(e.directory,`${r}${n}`)))}function Cn(e={}){let t=ye(e.cwd||vn.cwd());return Array.from(new Set([t,ye(t,"config"),ye(t,".config"),e.configDir?ye(t,e.configDir):void 0].filter((r)=>Boolean(r))))}var ci=Object.defineProperty,li=(e)=>e;function fi(e,t){this[e]=li.bind(null,t)}var ui=(e,t)=>{for(var r in t)ci(e,r,{get:t[r],enumerable:!0,configurable:!0,set:fi.bind(t,r)})},gi=(e,t)=>()=>(e&&(t=e(e=0)),t),_r={};ui(_r,{withErrorRecovery:()=>Wr,tryLoadConfig:()=>Mi,loadConfigWithResult:()=>Pi,loadConfig:()=>qr,isRetryableError:()=>ki,isConfigNotFoundError:()=>Ti,isBunfigError:()=>zr,globalPerformanceMonitor:()=>Ee,globalCache:()=>de,getEnvOrDefault:()=>Ai,generateConfigTypes:()=>Li,defaultGeneratedDir:()=>rn,defaultConfigDir:()=>tn,deepMergeWithArrayStrategy:()=>Kt,deepMerge:()=>Ur,createLibraryConfig:()=>ji,config:()=>Di,bunfigPlugin:()=>Bi,applyEnvVarsToConfig:()=>we,TypeGenerationError:()=>Nt,SchemaValidationError:()=>Ce,PluginError:()=>Dt,PerformanceMonitor:()=>Bt,FileSystemError:()=>Rt,ErrorFactory:()=>te,EnvVarError:()=>Ze,EnvProcessor:()=>rt,ConfigValidator:()=>Vt,ConfigValidationError:()=>Ft,ConfigNotFoundError:()=>He,ConfigMergeError:()=>Ot,ConfigLoader:()=>Wt,ConfigLoadError:()=>$e,ConfigFileLoader:()=>nt,ConfigCache:()=>jt,CacheUtils:()=>Hr,BunfigError:()=>I,BrowserConfigError:()=>Pt,ArrayMergeStrategies:()=>Qr});class jt{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],[,n])=>r.timestamp.getTime()-n.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,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),o=n??this.options.ttl,a=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:o,hits:0,size:a}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!Yt(e))return!0;return Ht(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,n){try{let i=Yt(r)?Ht(r):null,o=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},r,n)}catch{this.set(e,t,r,n)}}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((n,i)=>n+i.size,0),r=e.map((n)=>n.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 n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Bt{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let o=await t(),a=performance.now()-n;return this.recordMetric({operation:e,duration:a,timestamp:i,...r}),o}catch(o){let a=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:a,timestamp:i,...r}),o}}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((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,o)=>i+o,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function hi(e,t={}){let n=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return n?`${e}:${n}`:e}function mi(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function di(e){return e.getStats().size*2}function It(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&S(t[0])&&"id"in t[0]&&t[0].id===3&&S(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(S(t)&&S(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(S(e)&&"arr"in e&&Array.isArray(e.arr)&&S(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&S(t[0])&&S(e[0])){let n=[...t];for(let i of e)if(S(i)&&"name"in i){if(!n.find((a)=>S(a)&&("name"in a)&&a.name===i.name))n.push(i)}else if(S(i)&&"path"in i){if(!n.find((a)=>S(a)&&("path"in a)&&a.path===i.path))n.push(i)}else if(!n.some((o)=>Je(o,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!S(t)||!S(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(S(i)&&S(r[n]))r[n]=It(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&S(i[0])&&S(r[n][0])){let o=[...i];for(let a of r[n])if(S(a)&&"name"in a){if(!o.find((c)=>S(c)&&("name"in c)&&c.name===a.name))o.push(a)}else if(S(a)&&"path"in a){if(!o.find((c)=>S(c)&&("path"in c)&&c.path===a.path))o.push(a)}else if(!o.some((l)=>Je(l,a)))o.push(a);r[n]=o}else if(i.every((o)=>typeof o==="string")&&r[n].every((o)=>typeof o==="string")){let o=[...i];for(let a of r[n])if(!o.includes(a))o.push(a);r[n]=o}else r[n]=i;else r[n]=i}return r}function Je(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(!Je(e[r],t[r]))return!1;return!0}if(S(e)&&S(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Je(e[i],t[i]))return!1}return!0}return!1}function S(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function pi(e,t){if(!Ir(e))return null;try{let r=await import(e),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return It(t,n)}catch{return null}}catch{return null}}async function yi({name:e="",cwd:t,defaultConfig:r}){let n=t||St.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],o=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let a of o)for(let l of i){let c=ze(n,`${a}${l}`),f=await pi(c,r);if(f!==null)return f}try{let a=ze(n,"package.json");if(Ir(a)){let c=(await import(a))[e];if(c&&typeof c==="object"&&!Array.isArray(c))try{return It(r,c)}catch{}}}catch{}return r}function wi(e,t={}){let r=We.cwd();while(r.includes("storage"))r=Qt(r,"..");let n=Qt(r,e||"");if(t?.relative)return On(We.cwd(),n);return n}async function vi(){try{let e=await yi({name:"clarity",defaultConfig:je,cwd:We.cwd(),endpoint:"",headers:{}});return{...je,...e}}catch{return je}}function T(){if(H.env.NODE_ENV==="test"||H.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function $i(){if(H.env.NODE_ENV==="test"||H.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof H<"u"){let e=H.type;if(e==="renderer"||e==="worker")return!1;return!!(H.versions&&(H.versions.node||H.versions.bun))}return!1}class Kr{async format(e){let t=await $i(),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:ce.pid,hostname:t(),environment:ce.env.NODE_ENV||"development",platform:ce.platform,version:ce.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ce.env.NODE_ENV||ce.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ge{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={...kt},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Kr,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??P.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),o=this.generateKey();this.currentKeyId=i,this.keys.set(i,o),this.encryptionKeys.set(i,{key:o,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Be,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Be};return{...Be,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:kt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let i,o=0,a=3,l=1000;while(o<a)try{try{try{await Mn(this.config.logDirectory,nr.F_OK|nr.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await Ln(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ee.from(e);try{if(!ct(this.currentLogFile))await lt(this.currentLogFile,"",{mode:420});if(i=rr(this.currentLogFile,"a",420),Dn(i,c,{flag:"a"}),tr(i),i!==void 0)at(i),i=void 0;if((await oe(this.currentLogFile)).size===0){if(await lt(this.currentLogFile,c,{flag:"w",mode:420}),(await oe(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let u=f;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(o<a-1){let g=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${o+1}/${a}:`,g);let m=l*2**o;await new Promise((h)=>setTimeout(h,m)),o++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(i!==void 0)try{at(i)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(c){if(o===a-1){let u=c,g=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",g),c}o++;let f=l*2**(o-1);await new Promise((u)=>setTimeout(u,f))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,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 ae(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 ae(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ae(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(T())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,l],[,c])=>c.createdAt.getTime()-l.createdAt.getTime()),o=typeof t.maxKeys==="number"?t.maxKeys:1,a=Math.max(1,o);if(i.length>a)for(let[l]of i.slice(a))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return ot(16).toString("hex")}generateKey(){return ot(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=ot(16),n=Rn("aes-256-gcm",t,r),i=ee.concat([n.update(e,"utf8"),n.final()]),o=n.getAuthTag();return{encrypted:ee.concat([r,i,o]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=sr(),i=[];n.on("data",(o)=>i.push(o)),n.on("end",()=>t(ee.from(ee.concat(i)))),n.on("error",r),n.write(e),n.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(T())return;let e=await oe(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,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await be(this.config.logDirectory),o=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${r}.${a}`;if(await oe(r).catch(()=>null))try{if(await ir(r,l),t.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await xe(l)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await lt(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),o=r.replace(/\.log$/,`-${i}.log`);if(await oe(r).catch(()=>null))await ir(r,o)}if(this.currentLogFile=n,t.maxFiles){let o=(await be(this.config.logDirectory)).filter((a)=>a.startsWith(this.name)).sort((a,l)=>l.localeCompare(a));for(let a of o.slice(t.maxFiles))await xe(ae(this.config.logDirectory,a))}}}async compressLogFile(e,t){let r=er(e),n=Pn(t),i=sr();await jn(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}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()})),ct(this.currentLogFile))try{let e=rr(this.currentLogFile,"r+");tr(e),at(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(!T()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await be(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await xe(ae(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}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?x.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:o,showTimestamp:a=!0}=e,l=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(a)h.push(t);if(o==="warning")h.push("WARN");else if(o==="error")h.push("ERROR");else if(r)h.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)h.push(n.replace(/[[\]]/g,""));return h.push(i),h.join(" ")}let c=P.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${r} ${i}`;else if(o==="info"||o==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${x.cyan(i)}`;if(!a)return f.trim();let u=l(f).trim().length,g=l(t).length,m=Math.max(1,c-2-u-g);return`${f.trim()}${" ".repeat(m)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,a)=>{let l=Number.parseInt(a,10);return l<t[0].length?String(t[0][l]):o});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(o,a)=>{if(a==="%")return"%";if(n>=t.length)return o;let l=t[n++];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 o}});if(n<t.length)i+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),o=this.formatFileTimestamp(n),a,l;if(t instanceof Error)a=t.message,l=t.stack;else a=this.formatMessage(t,r);if(this.fancy&&!T()){let f=Zr[e],u=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",g;switch(e){case"debug":g=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:x.gray(a),level:e}),console.error(g);break;case"info":g=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:a,level:e}),console.error(g);break;case"success":g=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:x.green(a),level:e}),console.error(g);break;case"warning":g=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:a,level:e}),console.warn(g);break;case"error":if(g=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:a,level:e}),console.error(g),l){let m=l.split(`
3
+ `);for(let h of m)if(h.trim()&&!h.includes(a))console.error(this.formatConsoleMessage({timestamp:i,message:x.gray(` ${h}`),level:e,showTimestamp:!1}))}break}}else if(!T()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${a}`),l)console.error(l)}if(!this.shouldLog(e))return;let c=`${o} ${this.environment}.${e.toUpperCase()}: ${a}
4
+ `;if(l)c+=`${l}
5
+ `;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(e){let t=performance.now();if(this.fancy&&!T()){let r=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:x.blue("\u25D0"),tag:r,message:`${x.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),o=`${e} completed in ${i}ms`,a=new Date,l=this.formatConsoleTimestamp(a),f=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${o}`;if(r)f+=` ${JSON.stringify(r)}`;if(f+=`
6
+ `,f=f.replace(this.ANSI_PATTERN,""),this.fancy&&!T()){let u=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:x.green("\u2713"),tag:u,message:`${o}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!T())console.error(f.trim());await this.writeToFile(f)}}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 Ge(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(T())throw Error("createReadStream is not supported in browser environments");if(!ct(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return er(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 n=ee.isBuffer(e)?e:ee.from(e,"base64"),i=n.slice(0,16),o=n.slice(-16),a=n.slice(16,-16),l=Nn("aes-256-gcm",r,i);return l.setAuthTag(o),ee.concat([l.update(a),l.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return T()}isServerMode(){return!T()}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),n=this.formatFileTimestamp(t);if(this.fancy&&!T()){let o=e.split(`
7
+ `),a=Math.max(...o.map((u)=>u.length))+2,l=`\u250C${"\u2500".repeat(a)}\u2510`,c=`\u2514${"\u2500".repeat(a)}\u2518`,f=o.map((u)=>{let g=" ".repeat(a-u.length-2);return`\u2502 ${u}${g} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:x.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:x.cyan(l)})),f.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:x.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:x.cyan(c),showTimestamp:!1}))}else if(!T())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let i=`${n} ${this.environment}.INFO: [BOX] ${e}
8
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(T())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${x.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();P.stdin.removeListener("data",r);try{if(typeof P.stdin.setRawMode==="function")P.stdin.setRawMode(!1)}catch{}P.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof P.stdin.setRawMode==="function")P.stdin.setRawMode(!0)}catch{}P.stdin.resume(),P.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,(c,f)=>{if(f==="%")return"%";if(l>=t.length)return c;let u=t[l++];switch(f){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return c}}),l<t.length)r+=` ${t.slice(l).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}if(this.fancy&&!T()){let a=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",l=x.blue("\u25D0");console.error(`${l} ${a} ${x.cyan(r)}`)}let o=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
9
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(o)}progress(e,t=""){if(!this.enabled||!this.fancy||T()||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:(a,l)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||T())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,a)),l!==void 0)this.activeProgressBar.message=l;let c=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,c)},finish:(a)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||T())return;if(this.activeProgressBar.current=this.activeProgressBar.total,a!==void 0)this.activeProgressBar.message=a;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(a,l="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||T())return;P.stdout.write(`${"\r".padEnd(P.stdout.columns||80)}\r`),this.log(l,a),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||T()||!P.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,o=x.green("\u2501".repeat(n)),a=x.gray("\u2501".repeat(i)),l=`[${o}${a}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=t||r===100?x.green("\u2713"):x.blue("\u25B6"),g=this.options.showTags!==!1&&this.name?` ${x.gray(this.formatTag(this.name))}`:"",m=`\r${u}${g} ${l} ${c}${f}`,h=P.stdout.columns||80,v=" ".repeat(Math.max(0,h-m.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${m}${v}`,P.stdout.write(e.lastRenderedLine),t)P.stdout.write(`
10
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||T()||!P.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(T()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await be(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let o=ae(this.config.logDirectory,n);if(e.before)try{if((await oe(o)).mtime>=e.before)continue}catch(a){console.error(`Failed to get stats for file ${o}:`,a);continue}r.push(o)}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 n of r)try{await xe(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function Le(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&b(t[0])&&"id"in t[0]&&t[0].id===3&&b(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(b(t)&&b(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(b(e)&&"arr"in e&&Array.isArray(e.arr)&&b(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&b(t[0])&&b(e[0])){let n=[...t];for(let i of e)if(b(i)&&"name"in i){if(!n.find((a)=>b(a)&&("name"in a)&&a.name===i.name))n.push(i)}else if(b(i)&&"path"in i){if(!n.find((a)=>b(a)&&("path"in a)&&a.path===i.path))n.push(i)}else if(!n.some((o)=>qe(o,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!b(t)||!b(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(b(i)&&b(r[n]))r[n]=Le(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&b(i[0])&&b(r[n][0])){let o=[...i];for(let a of r[n])if(b(a)&&"name"in a){if(!o.find((c)=>b(c)&&("name"in c)&&c.name===a.name))o.push(a)}else if(b(a)&&"path"in a){if(!o.find((c)=>b(c)&&("path"in c)&&c.path===a.path))o.push(a)}else if(!o.some((l)=>qe(l,a)))o.push(a);r[n]=o}else if(i.every((o)=>typeof o==="string")&&r[n].every((o)=>typeof o==="string")){let o=[...i];for(let a of r[n])if(!o.includes(a))o.push(a);r[n]=o}else r[n]=i;else r[n]=i}return r}function _t(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:Le(e,t);if(Array.isArray(e))return r==="replace"?t:Le(e,t);if(!b(t)||!b(e))return t;let n={...e};for(let i of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,i))continue;let o=t[i],a=n[i];if(o===null||o===void 0)continue;if(Array.isArray(o)||Array.isArray(a))if(r==="replace")n[i]=o;else n[i]=Le(a,o);else if(b(o)&&b(a))n[i]=_t(a,o,r);else n[i]=o}return n}function qe(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(!qe(e[r],t[r]))return!1;return!0}if(b(e)&&b(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!qe(e[i],t[i]))return!1}return!0}return!1}function b(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Pe(e,t,r="replace"){if(!Br(e))return null;try{let n=await import(e),i=n.default||n;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return _t(t,i,r)}catch{return null}}catch{return null}}function Ci(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function o(a,l=[]){let c={...a};for(let[f,u]of Object.entries(a)){let g=[...l,f],m=(d)=>d.replace(/([A-Z])/g,"_$1").toUpperCase(),h=`${n}_${g.map(m).join("_")}`,v=`${n}_${g.map((d)=>d.toUpperCase()).join("_")}`;if(r)M.info(`Checking environment variable ${h} for config ${e}.${g.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))c[f]=o(u,g);else{let d=ve.env[h]||ve.env[v];if(d!==void 0){if(r)M.info(`Using environment variable ${d?h:v} for config ${e}.${g.join(".")}`);if(typeof u==="number")c[f]=Number(d);else if(typeof u==="boolean")c[f]=d.toLowerCase()==="true";else if(Array.isArray(u))try{let p=JSON.parse(d);if(Array.isArray(p))c[f]=p;else c[f]=d.split(",").map((N)=>N.trim())}catch{c[f]=d.split(",").map((p)=>p.trim())}else c[f]=d}}}return c}return o(i)}async function Ei({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:o=!1,checkEnv:a=!0,arrayStrategy:l="replace"}){let c=a&&typeof i==="object"&&i!==null&&!Array.isArray(i)?Ci(e,i,o):i,f=r||ve.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(o)M.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${f}`);let g=[e,`.${e}`].filter(Boolean),m=[`${e}.config`,`.${e}.config`].filter(Boolean),h=t?[t,`.${t}`]:[],v=t?[`${t}.config`,`.${t}.config`]:[],d=Array.from(new Set([f,L(f,"config"),L(f,".config"),n?L(f,n):void 0].filter(Boolean)));for(let p of d){if(o)M.info(`Searching for configuration in: ${p}`);let k=[L(f,"config"),L(f,".config")].concat(n?[L(f,n)]:[]).includes(p)?[...g,...m,...h,...v]:[...m,...g,...v,...h];for(let V of k)for(let B of u){let W=L(p,`${V}${B}`),Jt=await Pe(W,c,l);if(Jt!==null){if(o)M.success(`Configuration loaded from: ${W}`);return Jt}}}if(e){let p=L(st(),".config",e),N=["config",`${e}.config`];if(t)N.push(`${t}.config`);if(o)M.info(`Checking user config directory: ${p}`);for(let k of N)for(let V of u){let B=L(p,`${k}${V}`),W=await Pe(B,c,l);if(W!==null){if(o)M.success(`Configuration loaded from user config directory: ${B}`);return W}}}if(e){let p=L(st(),".config"),N=[`.${e}.config`];if(t)N.push(`.${t}.config`);if(o)M.info(`Checking user config directory for dotfile configs: ${p}`);for(let k of N)for(let V of u){let B=L(p,`${k}${V}`),W=await Pe(B,c,l);if(W!==null){if(o)M.success(`Configuration loaded from user config directory dotfile: ${B}`);return W}}}if(e){let p=st(),N=[`.${e}.config`,`.${e}`];if(t)N.push(`.${t}.config`),N.push(`.${t}`);if(o)M.info(`Checking user home directory for dotfile configs: ${p}`);for(let k of N)for(let V of u){let B=L(p,`${k}${V}`),W=await Pe(B,c,l);if(W!==null){if(o)M.success(`Configuration loaded from user home directory: ${B}`);return W}}}try{let p=L(f,"package.json");if(Br(p)){let N=await import(p),k=N[e];if(!k&&t){if(k=N[t],k&&o)M.success(`Using alias "${t}" configuration from package.json`)}if(k&&typeof k==="object"&&!Array.isArray(k))try{if(o)M.success(`Configuration loaded from package.json: ${k===N[e]?e:t}`);return _t(c,k,l)}catch(V){if(o)M.warn("Failed to merge package.json config:",V)}}}catch(p){if(o)M.warn("Failed to load package.json:",p)}if(o)M.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function bi(e,t={}){let r=Ve.cwd();while(r.includes("storage"))r=Xt(r,"..");let n=Xt(r,e||"");if(t?.relative)return An(Ve.cwd(),n);return n}async function xi(){try{let e=await Ei({name:"clarity",alias:"logging",defaultConfig:Ie,cwd:Ve.cwd()});return{...Ie,...e||{}}}catch{return Ie}}function A(){if(Z.env.NODE_ENV==="test"||Z.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Si(){if(Z.env.NODE_ENV==="test"||Z.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Z<"u"){let e=Z.type;if(e==="renderer"||e==="worker")return!1;return!!(Z.versions&&(Z.versions.node||Z.versions.bun))}return!1}class Vr{async format(e){let t=await Si(),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:ue.pid,hostname:t(),environment:ue.env.NODE_ENV||"development",platform:ue.platform,version:ue.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ue.env.NODE_ENV||ue.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ye{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={...At},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Vr,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??C.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),o=this.generateKey();this.currentKeyId=i,this.keys.set(i,o),this.encryptionKeys.set(i,{key:o,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{..._e,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{..._e};return{..._e,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:At.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(([,n])=>n!==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 r=(async()=>{let i,o=0,a=3,l=1000;while(o<a)try{try{try{await Vn(this.config.logDirectory,lr.F_OK|lr.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await Wn(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:q.from(e);try{if(!Se(this.currentLogFile))await gt(this.currentLogFile,"",{mode:420});if(i=cr(this.currentLogFile,"a",420),Kn(i,c,{flag:"a"}),ar(i),i!==void 0)ut(i),i=void 0;if((await le(this.currentLogFile)).size===0){if(await gt(this.currentLogFile,c,{flag:"w",mode:420}),(await le(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let u=f;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(o<a-1){let g=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${o+1}/${a}:`,g);let m=l*2**o;await new Promise((h)=>setTimeout(h,m)),o++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(i!==void 0)try{ut(i)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(c){if(o===a-1){let u=c,g=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",g),c}o++;let f=l*2**(o-1);await new Promise((u)=>setTimeout(u,f))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,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 fe(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 fe(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return fe(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 t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,l],[,c])=>c.createdAt.getTime()-l.createdAt.getTime()),o=typeof t.maxKeys==="number"?t.maxKeys:1,a=Math.max(1,o);if(i.length>a)for(let[l]of i.slice(a))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return ft(16).toString("hex")}generateKey(){return ft(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=ft(16),n=Bn("aes-256-gcm",t,r),i=q.isBuffer(e)?e:q.from(e,"utf8"),o=n.update(i),a=n.final(),l=o.length+a.length,c=n.getAuthTag(),f=q.allocUnsafe(16+l+16);return r.copy(f,0),o.copy(f,16),a.copy(f,16+o.length),c.copy(f,16+l),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=ur(),i=[];n.on("data",(o)=>i.push(o)),n.on("end",()=>t(q.from(q.concat(i)))),n.on("error",r),n.write(e),n.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 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,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Te(this.config.logDirectory),o=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${r}.${a}`;if(await le(r).catch(()=>null))try{if(await fr(r,l),t.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await ke(l)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await gt(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),o=r.replace(/\.log$/,`-${i}.log`);if(await le(r).catch(()=>null))await fr(r,o)}if(this.currentLogFile=n,t.maxFiles){let o=(await Te(this.config.logDirectory)).filter((a)=>a.startsWith(this.name)).sort((a,l)=>l.localeCompare(a));for(let a of o.slice(t.maxFiles))await ke(fe(this.config.logDirectory,a))}}}async compressLogFile(e,t){let r=or(e),n=_n(t),i=ur();await Jn(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}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()})),Se(this.currentLogFile))try{let e=cr(this.currentLogFile,"r+");ar(e),ut(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 t=(await Te(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await ke(fe(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}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 C.env.NO_COLOR<"u",t=C.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof C.stderr<"u"&&C.stderr.isTTY||typeof C.stdout<"u"&&C.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:o,showTimestamp:a=!0}=e,l=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(a)h.push(t);if(o==="warning")h.push("WARN");else if(o==="error")h.push("ERROR");else if(r)h.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)h.push(n.replace(/[[\]]/g,""));return h.push(i),h.join(" ")}let c=C.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${r} ${i}`;else if(o==="info"||o==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${y.cyan(i)}`;if(!a)return f.trim();let u=l(f).trim().length,g=l(t).length,m=Math.max(1,c-2-u-g);return`${f.trim()}${" ".repeat(m)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,a)=>{let l=Number.parseInt(a,10);return l<t[0].length?String(t[0][l]):o});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(o,a)=>{if(a==="%")return"%";if(n>=t.length)return o;let l=t[n++];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 o}});if(n<t.length)i+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let o=y.underline(y.blue(n)),a=this.toAbsoluteFilePath(i);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(a)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${l}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),t=t.replace(/`([^`]+)`/g,(r,n)=>y.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>y.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>y.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>y.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>y.strikethrough(n)),t}supportsHyperlinks(){if(A())return!1;let e=C.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=C.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(zn(t)||t.startsWith("./")||t.startsWith("../"))t=Un(t);else return null;return Se(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 n=new Date,i=this.formatConsoleTimestamp(n),o=this.formatFileTimestamp(n),a,l;if(t instanceof Error)a=t.message,l=t.stack;else a=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let g=this.options.showIcons===!1?"":Xr[e],m=this.options.showTags!==!1&&this.name?y.gray(this.formatTag(this.name)):"",h;switch(e){case"debug":h=this.formatConsoleMessage({timestamp:i,icon:g,tag:m,message:y.gray(c),level:e}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:i,icon:g,tag:m,message:c,level:e}),console.warn(h);break;case"success":h=this.formatConsoleMessage({timestamp:i,icon:g,tag:m,message:y.green(c),level:e}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:i,icon:g,tag:m,message:c,level:e}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:i,icon:g,tag:m,message:c,level:e}),console.error(h),l){let v=l.split(`
11
+ `);for(let d of v)if(d.trim()&&!d.includes(a))console.error(this.formatConsoleMessage({timestamp:i,message:y.gray(` ${d}`),level:e,showTimestamp:!1}))}break}}else if(!A()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${a}`),l)console.error(l)}if(!this.shouldLog(e))return;let u=`${o} ${this.environment}.${e.toUpperCase()}: ${f}
12
+ `;if(l)u+=`${l}
13
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(l,c)=>{},finish:(l)=>{},interrupt:(l,c)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!A()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(l,c)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,l),this.activeProgressBar.total),c!==void 0)this.activeProgressBar.message=c;if(this.shouldStyleConsole()&&!A()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(l)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,l)},interrupt:(l,c="info")=>{if(!A()&&C.stdout.isTTY)C.stdout.write(`
14
+ `);if(this[c==="warning"?"warn":c](l),this.activeProgressBar&&this.shouldStyleConsole()&&!A()&&C.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)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":y.blue("\u25D0"),tag:r,message:`${y.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),o=`${e} completed in ${i}ms`,a=new Date,l=this.formatConsoleTimestamp(a),f=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${o}`;if(r)f+=` ${JSON.stringify(r)}`;if(f+=`
15
+ `,f=f.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=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:u,message:`${o}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!A())console.error(f.trim());if(this.shouldWriteToFile())await this.writeToFile(f)}}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 Ye(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(!Se(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return or(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 n=q.isBuffer(e)?e:q.from(e,"base64"),i=n.subarray(0,16),o=n.subarray(n.length-16),a=n.subarray(16,n.length-16),l=In("aes-256-gcm",r,i);l.setAuthTag(o);let c=l.update(a),f=l.final(),u=c.length+f.length,g=q.allocUnsafe(u);return c.copy(g,0),f.copy(g,c.length),g.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}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),n=this.formatFileTimestamp(t),{consoleText:i,fileText:o}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let l=i.split(`
16
+ `),c=Math.max(...l.map((m)=>m.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,g=l.map((m)=>this.formatConsoleMessage({timestamp:r,message:y.cyan(m),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:y.cyan(f),showTimestamp:!1})),g.forEach((m)=>console.error(m)),console.error(this.formatConsoleMessage({timestamp:r,message:y.cyan(u),showTimestamp:!1}))}else if(!A())console.error(`${n} ${this.environment}.INFO: [BOX] ${o}`);let a=`${n} ${this.environment}.INFO: [BOX] ${o}
17
+ `.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=(n)=>{let i=n.toString().trim().toLowerCase();C.stdin.removeListener("data",r);try{if(typeof C.stdin.setRawMode==="function")C.stdin.setRawMode(!1)}catch{}C.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof C.stdin.setRawMode==="function")C.stdin.setRawMode(!0)}catch{}C.stdin.resume(),C.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 c=/%([sdijfo%])/g,f=0;if(r=e.replace(c,(u,g)=>{if(g==="%")return"%";if(f>=t.length)return u;let m=t[f++];switch(g){case"s":return String(m);case"d":case"i":return Number(m).toString();case"j":case"o":return JSON.stringify(m,null,2);default:return u}}),f<t.length)r+=` ${t.slice(f).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?y.gray(this.formatTag(this.name)):"",f=this.options.showIcons===!1?"":`${y.blue("\u25D0")} `;console.error(`${f}${c} ${y.cyan(n)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
18
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!C.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,o=y.green("\u2501".repeat(n)),a=y.gray("\u2501".repeat(i)),l=`[${o}${a}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?y.green("\u2713"):y.blue("\u25B6"),g=this.options.showTags!==!1&&this.name?` ${y.gray(this.formatTag(this.name))}`:"",m=`\r${u}${g} ${l} ${c}${f}`,h=C.stdout.columns||80,v=" ".repeat(Math.max(0,h-m.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${m}${v}`,C.stdout.write(e.lastRenderedLine),t)C.stdout.write(`
19
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||A()||!C.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 Te(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let o=fe(this.config.logDirectory,n);if(e.before)try{if((await le(o)).mtime>=e.before)continue}catch(a){console.error(`Failed to get stats for file ${o}:`,a);continue}r.push(o)}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 n of r)try{await ke(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Wr(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:o}=t,a=Error("Unknown error occurred");for(let l=0;l<=r;l++)try{return await e()}catch(c){if(a=c instanceof Error?c:Error(String(c)),l===r||!i(a))break;if(n>0)await new Promise((f)=>setTimeout(f,n))}if(o!==void 0)return o;throw a instanceof Error?a:Error(`Unknown error: ${String(a)}`)}function zr(e){return e instanceof I}function Ti(e){return e instanceof He}function ki(e){if(zr(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>e.message.toLowerCase().includes(r.toLowerCase()))}class rt{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:n,useCamelCase:i=!0,useBackwardCompatibility:o=!0,customParsers:a={},verbose:l=!1,trackPerformance:c=!0}=r,f=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),g={...t};return this.processObject(g,[],u,{useCamelCase:i,useBackwardCompatibility:o,customParsers:a,verbose:l,configName:e}),{config:g,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return Ee.track("applyEnvironmentVariables",f,{configName:e});return f()}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,n){for(let[i,o]of Object.entries(e)){let a=[...t,i],l=a.map((u)=>this.formatEnvKey(u,n.useCamelCase)),c=`${r}_${l.join("_")}`,f=n.useBackwardCompatibility?`${r}_${a.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.processObject(o,a,r,n);else{let u=Ae.env[c]||(f?Ae.env[f]:void 0);if(u!==void 0){if(n.verbose){let g=Ae.env[c]?c:f}try{e[i]=this.parseEnvironmentValue(u,typeof o,c,n.customParsers,n.configName)}catch(g){if(g instanceof Ze)throw g;throw te.envVar(c,u,typeof o,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[o,a]of Object.entries(n))try{return a(e)}catch{continue}for(let o of this.defaultParsers)if(o.canParse(e,t))try{return o.parse(e)}catch{throw te.envVar(r,e,`${t} (via ${o.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(Ae.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,o=n||this.generateEnvPrefix(e),a=[];switch(this.extractEnvVarInfo(t,[],o,a),i){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,n){for(let[i,o]of Object.entries(e)){let a=[...t,i],l=`${r}_${a.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.extractEnvVarInfo(o,a,r,n);else n.push({key:l,type:Array.isArray(o)?"array":typeof o,description:`Configuration for ${a.join(".")}`,example:this.generateExample(o)})}}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 n of e)r+=`${n.key}
22
+ `,r+=` Type: ${n.type}
23
+ `,r+=` Description: ${n.description}
24
+ `,r+=` Example: ${n.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 n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
31
+ `;return r}}function Ai(e,t){let r=Yr("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function Ur(e,t,r={}){return Jr(e,t,r,new WeakMap)}function Jr(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:o=!1,customMerger:a}=r;if(t===null||t===void 0)return o?e:t;if(a){let l=a(e,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(e))return Gr(e,t,i,n);if(!_(t)||!_(e))return t;return Ni(e,t,r,n)}function Gr(e,t,r,n){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 Fi(e,t);case"smart":return Oi(e,t,n);default:return t}return t}function Fi(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Tt(i,n)))r.push(n);return r}function Oi(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(_(t[0])&&_(e[0]))return Ri(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function Ri(e,t,r){let n=[...t];for(let i of e){if(!_(i)){n.push(i);continue}let o=["id","name","key","path","type"],a=!1;for(let l of o)if(l in i){if(n.find((f)=>_(f)&&(l in f)&&f[l]===i[l])){a=!0;break}}if(!a)n.push(i)}return n}function Ni(e,t,r,n){let i=t;if(_(i)&&n.has(i))return n.get(i);let o={...e};if(_(i))n.set(i,o);for(let a in i){if(!Object.prototype.hasOwnProperty.call(i,a))continue;let l=i[a],c=o[a];if(r.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){o[a]=l;continue}if(_(l)&&_(c))o[a]=Jr(c,l,r,n);else if(Array.isArray(l)||Array.isArray(c))o[a]=Gr(c,l,r.arrayMergeMode||"smart",n);else o[a]=l}return o}function Kt(e,t,r="replace"){return Ur(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Tt(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(!Tt(e[r],t[r]))return!1;return!0}if(_(e)&&_(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Tt(e[i],t[i]))return!1}return!0}return!1}function _(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class nt{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:o,trackPerformance:a=!0,verbose:l=!1}=r;if(i){let f=de.getWithFileCheck("file",e);if(f){if(l)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!Fe(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),g=u.default||u,m="default"in u,h=Object.keys(u).length>0;if(!m&&!h)throw new $e(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof g!=="object"||g===null||Array.isArray(g))throw new $e(e,Error("Configuration must export a valid object"),"unknown");let p={config:Kt(t,g,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)de.setWithFileCheck("file",p,e,o);return p}catch(f){throw f instanceof Error?te.configLoad(e,f):te.configLoad(e,Error(String(f)))}};if(a)return Ee.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let o of n)for(let a of this.extensions)i.push(ht(t,`${o}${a}`));return i}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 Wr(async()=>Fe(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Fe(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let o of i)for(let a of this.extensions){let l=ht(e,`${o}${a}`);if(await this.checkFileAccess(l))n.push(l)}}else try{let{readdirSync:i}=await import("fs"),o=i(e);for(let a of o)if(this.looksLikeConfigFile(a)){let l=ht(e,a);if(await this.checkFileAccess(l))n.push(l)}}catch{return[]}return n}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((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!Fe(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),o=i(e,"utf8");JSON.parse(o)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}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(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class Vt{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:o=!0,customRules:a=[],trackPerformance:l=!0,verbose:c=!1}=r,f=async()=>{let u=[],g=[],m={stopOnFirstError:n,validateRequired:i,validateTypes:o,customRules:a,trackPerformance:l,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,m);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...a],m);else return this.validateWithJSONSchema(e,t,m)}catch(h){return u.push({path:"",message:`Validation failed: ${h}`,rule:"system"}),{isValid:!1,errors:u,warnings:g}}};if(l)return await Ee.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!Gn(t))throw new Ce(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new Ce(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,o){if(o.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(n.push({path:r,message:`Expected type ${l.join(" or ")}, got ${a}`,expected:l.join(" or "),actual:a,rule:"type"}),o.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),o.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.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)n.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))n.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)n.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)n.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,n,i,o),o.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let a=e;if(o.validateRequired&&t.required){for(let l of t.required)if(!(l in a)){if(n.push({path:r?`${r}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[l,c]of Object.entries(t.properties))if(l in a){let f=r?`${r}.${l}`:l;if(this.validateObjectAgainstSchema(a[l],c,f,n,i,o),o.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(a))if(!l.has(c))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let o of t)try{let a=this.getValueByPath(e,o.path),l=this.validateWithRule(a,o,o.path);if(n.push(...l),r.stopOnFirstError&&n.length>0)break}catch(a){n.push({path:o.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.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))n.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 i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,o,a]=n;t.push({path:i,required:!o,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:en},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Wt{fileLoader=new nt;envProcessor=new rt;validator=new Vt;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:o,...a}=e;try{if(r?.enabled){let c=this.checkCache(a.name||"",a);if(c)return c}let l;try{l=await this.loadConfigurationStrategies(a,!0,r)}catch(c){let f=a.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;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(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),g=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),m=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(m||u))throw c;if(g&&(!f||!m))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(!f)l={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else l={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(i||o)await this.validateConfiguration(l.config,i,o,a.name);if(r?.enabled&&l)this.cacheResult(a.name||"",l,r,a);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:a.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)U.warn(`Slow configuration loading detected: ${c.duration}ms for ${a.name}`);l.metrics=c}return l}catch(l){let c=Date.now()-t;throw U.error(`Configuration loading failed after ${c}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:o,configDir:a,defaultConfig:l,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,g=o||ne.cwd(),m=[],h=await this.loadLocalConfiguration(n,i,g,a,l,f,u,c,r);if(h)return m.push(...this.getLocalSearchPaths(n,i,g,a)),this.finalizeResult(h,m,c,n,u);let v=await this.loadHomeConfiguration(n,i,l,f,u,c);if(v)return m.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(v,m,c,n,u);let d=await this.loadPackageJsonConfiguration(n,i,g,l,f,u,c);if(d)return m.push(j(g,"package.json")),this.finalizeResult(d,m,c,n,u);if(m.push(...this.getAllSearchPaths(n,i,g,a)),t)throw te.configNotFound(n,m,i);return{...await this.applyEnvironmentVariables(n,l,c,u),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,o,a,l,c){let f=l?we(e,i,a):i,u=this.getLocalDirectories(r,n);for(let g of u){if(a)U.info(`Searching for configuration in: ${g}`);let m=this.fileLoader.generateConfigPaths(e,g,t),h=await this.fileLoader.tryLoadFromPaths(m,f,{arrayStrategy:o,verbose:a,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(h){if(a)U.success(`Configuration loaded from: ${h.source.path}`);return h}}return null}async loadHomeConfiguration(e,t,r,n,i,o){if(!e)return null;let a=o?we(e,r,i):r,l=[j(se(),".config",e),j(se(),".config"),se()];for(let c of l){if(i)U.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,a,{arrayStrategy:n,verbose:i});if(u){if(i)U.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,o,a){let l=a?we(e,n,o):n;try{let c=j(r,"package.json");if(!xt(c))return null;let f=await import(c),u=f[e],g=e;if(!u&&t)u=f[t],g=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(o)U.success(`Configuration loaded from package.json: ${g}`);return{config:Kt(l,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(o)U.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:we(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let o=r(e);if(o)i.push(...o)}if(t){let o=await this.validator.validateConfiguration(e,t);if(!o.isValid)i.push(...o.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(i.length>0)throw te.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return de.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);de.set(i,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,j(e,"config"),j(e,".config"),t?j(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(j(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),o=[];for(let a of i)o.push(...this.fileLoader.generateConfigPaths(e,a,t));return o}getHomeSearchPaths(e,t){if(!e)return[];let r=[j(se(),".config",e),j(se(),".config"),se()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function $r(e){let r=!(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")),n=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return r||n}async function Pi(e){return Q.loadConfig({...e,__strictErrorHandling:!0})}async function qr(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 n;if(r)n=await Q.loadConfig(e);else n=await Q.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",o=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||o.includes("config"))&&e.verbose)U.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let l=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await Q.applyEnvironmentVariables(l.name||"",t,!0,l.verbose||!1))?.config??t;return t}}async function Di(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await Q.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"&&$r(r)))return(await Q.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await Q.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"&&$r(t)))return(await Q.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Mi(e,t,r="replace"){let n=new nt;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function we(e,t,r=!1){let n=new rt,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(a,l=[]){let c={...a};for(let[f,u]of Object.entries(a)){let g=[...l,f],m=[`${i}_${g.join("_").toUpperCase()}`,`${i}_${g.map((d)=>d.toUpperCase()).join("")}`,`${i}_${g.map((d)=>d.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],h,v;for(let d of m)if(h=ne.env[d],h!==void 0){v=d;break}if(h!==void 0&&v)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(h.toLowerCase());else if(typeof u==="number"){let d=Number(h);if(!Number.isNaN(d))c[f]=d}else if(Array.isArray(u))try{c[f]=JSON.parse(h)}catch{c[f]=h.split(",").map((d)=>d.trim())}else c[f]=h;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=o(u,g)}return c}return o(t)}function Li(e){let t=j(ne.cwd(),e.configDir),r=j(ne.cwd(),e.generatedDir),n=j(r,"config-types.ts");if(!xt(Zt(n)))xn(Zt(n),{recursive:!0,mode:511});let i=xt(t)?Sn(t).map((a)=>a.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],o=`// Generated by bunfig v${us}
32
+ export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
33
+ `;Tn(n,o,{mode:438})}function ji(e){let t=null,r=null,n=()=>{if(!r)r=qr(e).then((o)=>(t=o,o),(o)=>{let a="defaultConfig"in e?e.defaultConfig:{};if(t=a,"verbose"in e&&e.verbose)U.warn("Config loading failed, using defaults:",[o instanceof Error?o:Error(String(o))]);return a});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(o,a){if(t)return t[a];let l=i[a];return n(),l},has(o,a){return a in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(o,a){return Object.getOwnPropertyDescriptor(t||i,a)},set(o,a,l){if(!t)t={...i};return t[a]=l,!0}})}function Bi(e){let t=gr(Hn.cwd(),e?.configDir||"./config");function r(){if(!qn(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),o=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],a=Yn(t).filter((c)=>i.has(mt(c))).map((c)=>({base:c.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:c})),l=new Map;for(let{base:c,file:f}of a){let u=mt(f).toLowerCase(),g=l.get(c);if(!g){l.set(c,f);continue}let m=mt(g).toLowerCase();if(o.indexOf(u)<o.indexOf(m))l.set(c,f)}return Array.from(l.entries()).map(([c,f])=>({base:c,file:f})).sort((c,f)=>c.base.localeCompare(f.base))}function n(){let i=r(),o=i.map((f)=>f.base),a=o.length?o.map((f)=>`'${f}'`).join(" | "):"string",l=i.length?`{
34
+ ${i.map((f)=>{let u=gr(t,f.file).replace(/\\/g,"/");return` '${f.base}': typeof import('${u}').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(i){i.onResolve({filter:/^virtual:bunfig-types$/},(o)=>({path:o.path,namespace:"bunfig-virtual"})),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:n(),loader:"ts"}))}}}var Yr,de,Ee,Hr,Ii,_i,Cr,je,kt,D,x,Ki,Er,Vi,br,Wi,zi,wt,Ui,xr,Sr,vt,Ji,Gi,qi,Yi,Be,Zr,Hi,M,Zi,Xi,Tr,Ie,At,F,y,Qi,kr,es,Ar,ts,rs,$t,ns,Fr,Or,is,Ct,ss,os,as,cs,ls,_e,Xr,fs,us="0.15.6",I,He,$e,Ft,Ot,Ze,Rt,Nt,Ce,Pt,Dt,te,Qr,en,U,Q,tn,rn,gs=gi(async()=>{Yr=import.meta.require,de=new jt,Ee=new Bt,Hr={createKey:hi,isEquivalent:mi,estimateMemoryUsage:di},Ii=ze(St.cwd(),"config"),_i=ze(St.cwd(),"src/generated"),Cr=We.env.CLARITY_LOG_DIR||Fn(wi(),"logs"),je={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Cr,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},kt=await vi(),D={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"},x=D,Ki=D.red,Er=D.green,Vi=D.yellow,br=D.blue,Wi=D.magenta,zi=D.cyan,wt=D.white,Ui=D.gray,xr=D.bgRed,Sr=D.bgYellow,vt=D.bold,Ji=D.dim,Gi=D.italic,qi=D.underline,Yi=D.reset,Be={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Zr={debug:"\uD83D\uDD0D",info:br("\u2139"),success:Er("\u2713"),warning:Sr(wt(vt(" WARN "))),error:xr(wt(vt(" ERROR ")))},Hi=new Ge("stacks"),M=new Ge("bunfig",{showTags:!0}),Zi=L(ve.cwd(),"config"),Xi=L(ve.cwd(),"src/generated"),Tr=Ve.env.CLARITY_LOG_DIR||kn(bi(),"logs"),Ie={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Tr,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},At=await xi(),F={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=F,Qi=F.red,kr=F.green,es=F.yellow,Ar=F.blue,ts=F.magenta,rs=F.cyan,$t=F.white,ns=F.gray,Fr=F.bgRed,Or=F.bgYellow,is=F.bgGray,Ct=F.bold,ss=F.dim,os=F.italic,as=F.underline,cs=F.strikethrough,ls=F.reset,_e={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Xr={debug:"\uD83D\uDD0D",info:Ar("\u2139"),success:kr("\u2713"),warning:Or($t(Ct(" WARN "))),error:Fr($t(Ct(" ERROR ")))},fs=new Ye("stacks"),I=class extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,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 t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},He=class extends I{code="CONFIG_NOT_FOUND";constructor(t,r,n){let i=n?` or alias "${n}"`:"";super(`Configuration "${t}"${i} not found`,{configName:t,alias:n,searchPaths:r,searchPathCount:r.length})}},$e=class extends I{code="CONFIG_LOAD_ERROR";constructor(t,r,n){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Ft=class extends I{code="CONFIG_VALIDATION_ERROR";constructor(t,r,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:r,errorCount:r.length})}},Ot=class extends I{code="CONFIG_MERGE_ERROR";constructor(t,r,n,i){super(`Failed to merge configuration from "${t}" with "${r}": ${n.message}`,{sourcePath:t,targetPath:r,configName:i,originalError:n.name,originalMessage:n.message});this.cause=n}},Ze=class extends I{code="ENV_VAR_ERROR";constructor(t,r,n,i){super(`Failed to parse environment variable "${t}" with value "${r}" as ${n}`,{envKey:t,envValue:r,expectedType:n,configName:i})}},Rt=class extends I{code="FILE_SYSTEM_ERROR";constructor(t,r,n){super(`File system ${t} failed for "${r}": ${n.message}`,{operation:t,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Nt=class extends I{code="TYPE_GENERATION_ERROR";constructor(t,r,n){super(`Failed to generate types from "${t}" to "${r}": ${n.message}`,{configDir:t,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Ce=class extends I{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:r,errorCount:r.length})}},Pt=class extends I{code="BROWSER_CONFIG_ERROR";constructor(t,r,n,i){super(`Failed to fetch configuration from "${t}": ${r} ${n}`,{endpoint:t,status:r,statusText:n,configName:i})}},Dt=class extends I{code="PLUGIN_ERROR";constructor(t,r,n){super(`Plugin "${t}" failed during ${r}: ${n.message}`,{pluginName:t,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}},te={configNotFound(e,t,r){return new He(e,t,r)},configLoad(e,t,r){return new $e(e,t,r)},configValidation(e,t,r){return new Ft(e,t,r)},configMerge(e,t,r,n){return new Ot(e,t,r,n)},envVar(e,t,r,n){return new Ze(e,t,r,n)},fileSystem(e,t,r){return new Rt(e,t,r)},typeGeneration(e,t,r){return new Nt(e,t,r)},schemaValidation(e,t,r){return new Ce(e,t,r)},browserConfig(e,t,r,n){return new Pt(e,t,r,n)},plugin(e,t,r){return new Dt(e,t,r)}},Qr={replace:"replace",concat:"concat",smart:"smart"},en=/^https?:\/\//,U=new Ye("bunfig",{showTags:!0}),Q=new Wt,tn=j(ne.cwd(),"config"),rn=j(ne.cwd(),"src/generated")});function hs(e,t={}){let r=Ue.cwd();while(r.includes("storage"))r=hr(r,"..");let n=hr(r,e||"");if(t?.relative)return Xn(Ue.cwd(),n);return n}var ms=Ue.env.CLARITY_LOG_DIR||Zn(hs(),"logs"),nn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ms,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Xe={...nn},Zo=(async()=>{try{let{loadConfig:e}=await gs().then(()=>_r),t=await e({name:"clarity",alias:"logging",defaultConfig:nn,cwd:Ue.cwd()});if(t)Object.assign(Xe,t)}catch{}return Xe})();function O(){if(X.env.NODE_ENV==="test"||X.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ds(){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 sn{async format(e){let t=await ds(),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:me.pid,hostname:t(),environment:me.env.NODE_ENV||"development",platform:me.platform,version:me.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:me.env.NODE_ENV||me.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var R={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"},w=R,{red:Xo,green:ps,yellow:Qo,blue:ys,magenta:ea,cyan:ta,white:Rr,gray:ra,bgRed:ws,bgYellow:vs,bgGray:na,bold:Nr,dim:ia,italic:sa,underline:oa,strikethrough:aa,reset:ca}=R,Et={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},$s={debug:"\uD83D\uDD0D",info:ys("\u2139"),success:ps("\u2713"),warning:vs(Rr(Nr(" WARN "))),error:ws(Rr(Nr(" ERROR ")))};class it{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={...Xe},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new sn,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??E.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),o=this.generateKey();this.currentKeyId=i,this.keys.set(i,o),this.encryptionKeys.set(i,{key:o,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{...Et,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Et};return{...Et,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Xe.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(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!O()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,o=0,a=3,l=1000;while(o<a)try{try{try{await ni(this.config.logDirectory,yr.F_OK|yr.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await ii(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Y.from(e);try{if(!Oe(this.currentLogFile))await yt(this.currentLogFile,"",{mode:420});if(i=pr(this.currentLogFile,"a",420),ri(i,c,{flag:"a"}),dr(i),i!==void 0)pt(i),i=void 0;if((await ge(this.currentLogFile)).size===0){if(await yt(this.currentLogFile,c,{flag:"w",mode:420}),(await ge(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let u=f;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(o<a-1){let g=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${o+1}/${a}:`,g);let m=l*2**o;await new Promise((h)=>setTimeout(h,m)),o++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(i!==void 0)try{pt(i)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(c){if(o===a-1){let u=c,g=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",g),c}o++;let f=l*2**(o-1);await new Promise((u)=>setTimeout(u,f))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,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 he(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 he(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return he(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(O())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 t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,l],[,c])=>c.createdAt.getTime()-l.createdAt.getTime()),o=typeof t.maxKeys==="number"?t.maxKeys:1,a=Math.max(1,o);if(i.length>a)for(let[l]of i.slice(a))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return dt(16).toString("hex")}generateKey(){return dt(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=dt(16),n=Qn("aes-256-gcm",t,r),i=Y.isBuffer(e)?e:Y.from(e,"utf8"),o=n.update(i),a=n.final(),l=o.length+a.length,c=n.getAuthTag(),f=Y.allocUnsafe(16+l+16);return r.copy(f,0),o.copy(f,16),a.copy(f,16+o.length),c.copy(f,16+l),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=vr(),i=[];n.on("data",(o)=>i.push(o)),n.on("end",()=>t(Y.from(Y.concat(i)))),n.on("error",r),n.write(e),n.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(O())return;if(!this.shouldWriteToFile())return;let e=await ge(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,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Re(this.config.logDirectory),o=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${r}.${a}`;if(await ge(r).catch(()=>null))try{if(await wr(r,l),t.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await Ne(l)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await yt(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),o=r.replace(/\.log$/,`-${i}.log`);if(await ge(r).catch(()=>null))await wr(r,o)}if(this.currentLogFile=n,t.maxFiles){let o=(await Re(this.config.logDirectory)).filter((a)=>a.startsWith(this.name)).sort((a,l)=>l.localeCompare(a));for(let a of o.slice(t.maxFiles))await Ne(he(this.config.logDirectory,a))}}}async compressLogFile(e,t){let r=mr(e),n=ti(t),i=vr();await ai(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}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=pr(this.currentLogFile,"r+");dr(e),pt(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(!O()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Re(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Ne(he(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}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()?w.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||O())return!1;let e=typeof E.env.NO_COLOR<"u",t=E.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof E.stderr<"u"&&E.stderr.isTTY||typeof E.stdout<"u"&&E.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:o,showTimestamp:a=!0}=e,l=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(a)h.push(t);if(o==="warning")h.push("WARN");else if(o==="error")h.push("ERROR");else if(r)h.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)h.push(n.replace(/[[\]]/g,""));return h.push(i),h.join(" ")}let c=E.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${r} ${i}`;else if(o==="info"||o==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${w.cyan(i)}`;if(!a)return f.trim();let u=l(f).trim().length,g=l(t).length,m=Math.max(1,c-2-u-g);return`${f.trim()}${" ".repeat(m)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,a)=>{let l=Number.parseInt(a,10);return l<t[0].length?String(t[0][l]):o});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(o,a)=>{if(a==="%")return"%";if(n>=t.length)return o;let l=t[n++];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 o}});if(n<t.length)i+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let o=w.underline(w.blue(n)),a=this.toAbsoluteFilePath(i);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(a)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${l}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),t=t.replace(/`([^`]+)`/g,(r,n)=>w.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>w.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>w.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>w.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>w.strikethrough(n)),t}supportsHyperlinks(){if(O())return!1;let e=E.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=E.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(si(t)||t.startsWith("./")||t.startsWith("../"))t=oi(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){if(!this.shouldLog(e))return;let n=new Date,i=this.formatConsoleTimestamp(n),o=this.formatFileTimestamp(n),a,l;if(t instanceof Error)a=t.message,l=t.stack;else a=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let g=this.options.showIcons===!1?"":$s[e],m=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",h;switch(e){case"debug":h=this.formatConsoleMessage({timestamp:i,icon:g,tag:m,message:w.gray(c),level:e}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:i,icon:g,tag:m,message:c,level:e}),console.warn(h);break;case"success":h=this.formatConsoleMessage({timestamp:i,icon:g,tag:m,message:w.green(c),level:e}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:i,icon:g,tag:m,message:c,level:e}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:i,icon:g,tag:m,message:c,level:e}),console.error(h),l){let v=l.split(`
41
+ `);for(let d of v)if(d.trim()&&!d.includes(a))console.error(this.formatConsoleMessage({timestamp:i,message:w.gray(` ${d}`),level:e,showTimestamp:!1}))}break}}else if(!O()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${a}`),l)console.error(l)}let u=`${o} ${this.environment}.${e.toUpperCase()}: ${f}
42
+ `;if(l)u+=`${l}
43
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(l,c)=>{},finish:(l)=>{},interrupt:(l,c)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!O()&&E.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(l,c)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,l),this.activeProgressBar.total),c!==void 0)this.activeProgressBar.message=c;if(this.shouldStyleConsole()&&!O()&&E.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(l)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,l)},interrupt:(l,c="info")=>{if(!O()&&E.stdout.isTTY)E.stdout.write(`
44
+ `);if(this[c==="warning"?"warn":c](l),this.activeProgressBar&&this.shouldStyleConsole()&&!O()&&E.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":w.blue("\u25D0"),tag:r,message:`${w.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),o=`${e} completed in ${i}ms`,a=new Date,l=this.formatConsoleTimestamp(a),f=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${o}`;if(r)f+=` ${JSON.stringify(r)}`;if(f+=`
45
+ `,f=f.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":w.green("\u2713"),tag:u,message:`${o}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!O())console.error(f.trim());if(this.shouldWriteToFile())await this.writeToFile(f)}}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 it(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(O())throw Error("createReadStream is not supported in browser environments");if(!Oe(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return mr(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 n=Y.isBuffer(e)?e:Y.from(e,"base64"),i=n.subarray(0,16),o=n.subarray(n.length-16),a=n.subarray(16,n.length-16),l=ei("aes-256-gcm",r,i);l.setAuthTag(o);let c=l.update(a),f=l.final(),u=c.length+f.length,g=Y.allocUnsafe(u);return c.copy(g,0),f.copy(g,c.length),g.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return O()}isServerMode(){return!O()}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),n=this.formatFileTimestamp(t),{consoleText:i,fileText:o}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let l=i.split(`
46
+ `),c=Math.max(...l.map((m)=>m.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,g=l.map((m)=>this.formatConsoleMessage({timestamp:r,message:w.cyan(m),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:w.cyan(f),showTimestamp:!1})),g.forEach((m)=>console.error(m)),console.error(this.formatConsoleMessage({timestamp:r,message:w.cyan(u),showTimestamp:!1}))}else if(!O())console.error(`${n} ${this.environment}.INFO: [BOX] ${o}`);let a=`${n} ${this.environment}.INFO: [BOX] ${o}
47
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}async prompt(e){if(O())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${w.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();E.stdin.removeListener("data",r);try{if(typeof E.stdin.setRawMode==="function")E.stdin.setRawMode(!1)}catch{}E.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof E.stdin.setRawMode==="function")E.stdin.setRawMode(!0)}catch{}E.stdin.resume(),E.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 c=/%([sdijfo%])/g,f=0;if(r=e.replace(c,(u,g)=>{if(g==="%")return"%";if(f>=t.length)return u;let m=t[f++];switch(g){case"s":return String(m);case"d":case"i":return Number(m).toString();case"j":case"o":return JSON.stringify(m,null,2);default:return u}}),f<t.length)r+=` ${t.slice(f).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",f=this.options.showIcons===!1?"":`${w.blue("\u25D0")} `;console.error(`${f}${c} ${w.cyan(n)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
48
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!E.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,o=w.green("\u2501".repeat(n)),a=w.gray("\u2501".repeat(i)),l=`[${o}${a}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?w.green("\u2713"):w.blue("\u25B6"),g=this.options.showTags!==!1&&this.name?` ${w.gray(this.formatTag(this.name))}`:"",m=`\r${u}${g} ${l} ${c}${f}`,h=E.stdout.columns||80,v=" ".repeat(Math.max(0,h-m.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${m}${v}`,E.stdout.write(e.lastRenderedLine),t)E.stdout.write(`
49
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||O()||!E.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(O()){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 n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let o=he(this.config.logDirectory,n);if(e.before)try{if((await ge(o)).mtime>=e.before)continue}catch(a){console.error(`Failed to get stats for file ${o}:`,a);continue}r.push(o)}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 n of r)try{await Ne(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var la=new it("stacks");class J 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 on extends J{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],i="";if(n.length===1)i=` or alias "${n[0]}"`;else if(n.length>1)i=` or aliases ${n.map((o)=>`"${o}"`).join(", ")}`;super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}}class Qe extends J{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 an extends J{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class cn extends J{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class zt extends J{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}}class ln extends J{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 fn extends J{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 et extends J{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 un extends J{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}}class gn extends J{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 re={configNotFound(e,t,r){return new on(e,t,r)},configLoad(e,t,r){return new Qe(e,t,r)},configValidation(e,t,r){return new an(e,t,r)},configMerge(e,t,r,n){return new cn(e,t,r,n)},envVar(e,t,r,n){return new zt(e,t,r,n)},fileSystem(e,t,r){return new ln(e,t,r)},typeGeneration(e,t,r){return new fn(e,t,r)},schemaValidation(e,t,r){return new et(e,t,r)},browserConfig(e,t,r,n){return new un(e,t,r,n)},plugin(e,t,r){return new gn(e,t,r)}};async function Cs(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:o}=t,a=Error("Unknown error occurred");for(let l=0;l<=r;l++)try{return await e()}catch(c){if(a=c instanceof Error?c:Error(String(c)),l===r||!i(a))break;if(n>0)await new Promise((f)=>setTimeout(f,n))}if(o!==void 0)return o;throw a instanceof Error?a:Error(`Unknown error: ${String(a)}`)}class Ut{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:n,useCamelCase:i=!0,useBackwardCompatibility:o=!0,customParsers:a={},verbose:l=!1,trackPerformance:c=!0}=r,f=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),g={...t};return this.processObject(g,[],u,{useCamelCase:i,useBackwardCompatibility:o,customParsers:a,verbose:l,configName:e}),{config:g,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return Lt.track("applyEnvironmentVariables",f,{configName:e});return f()}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,n){for(let[i,o]of Object.entries(e)){let a=[...t,i],l=a.map((u)=>this.formatEnvKey(u,n.useCamelCase)),c=`${r}_${l.join("_")}`,f=n.useBackwardCompatibility?`${r}_${a.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.processObject(o,a,r,n);else{let u=De.env[c]||(f?De.env[f]:void 0);if(u!==void 0){if(n.verbose){let g=De.env[c]?c:f}try{e[i]=this.parseEnvironmentValue(u,typeof o,c,n.customParsers,n.configName)}catch(g){if(g instanceof zt)throw g;throw re.envVar(c,u,typeof o,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[o,a]of Object.entries(n))try{return a(e)}catch{continue}for(let o of this.defaultParsers)if(o.canParse(e,t))try{return o.parse(e)}catch{throw re.envVar(r,e,`${t} (via ${o.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(De.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,o=n||this.generateEnvPrefix(e),a=[];switch(this.extractEnvVarInfo(t,[],o,a),i){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,n){for(let[i,o]of Object.entries(e)){let a=[...t,i],l=`${r}_${a.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.extractEnvVarInfo(o,a,r,n);else n.push({key:l,type:Array.isArray(o)?"array":typeof o,description:`Configuration for ${a.join(".")}`,example:this.generateExample(o)})}}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 n of e)r+=`${n.key}
52
+ `,r+=` Type: ${n.type}
53
+ `,r+=` Description: ${n.description}
54
+ `,r+=` Example: ${n.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 n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
61
+ `;return r}}function Es(e,t,r={}){return hn(e,t,r,new WeakMap)}function hn(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:o=!1,customMerger:a}=r;if(t===null||t===void 0)return o?e:t;if(a){let l=a(e,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(e))return mn(e,t,i,n);if(!K(t)||!K(e))return t;return Ts(e,t,r,n)}function mn(e,t,r,n){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 bs(e,t);case"smart":return xs(e,t,n);default:return t}return t}function bs(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Mt(i,n)))r.push(n);return r}function xs(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(K(t[0])&&K(e[0]))return Ss(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function Ss(e,t,r){let n=[...t];for(let i of e){if(!K(i)){n.push(i);continue}let o=["id","name","key","path","type"],a=!1;for(let l of o)if(l in i){if(n.find((f)=>K(f)&&(l in f)&&f[l]===i[l])){a=!0;break}}if(!a)n.push(i)}return n}function Ts(e,t,r,n){let i=t;if(K(i)&&n.has(i))return n.get(i);let o={...e};if(K(i))n.set(i,o);for(let a in i){if(!Object.prototype.hasOwnProperty.call(i,a))continue;let l=i[a],c=o[a];if(r.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){o[a]=l;continue}if(K(l)&&K(c))o[a]=hn(c,l,r,n);else if(Array.isArray(l)||Array.isArray(c))o[a]=mn(c,l,r.arrayMergeMode||"smart",n);else o[a]=l}return o}function dn(e,t,r="replace"){return Es(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Mt(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(!Mt(e[r],t[r]))return!1;return!0}if(K(e)&&K(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Mt(e[i],t[i]))return!1}return!0}return!1}function K(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class pn{extensions=Lr;async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:o,trackPerformance:a=!0,verbose:l=!1}=r;if(i){let f=Ke.getWithFileCheck("file",e);if(f){if(l)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!Me(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),g=u.default||u,m="default"in u,h=Object.keys(u).length>0;if(!m&&!h)throw new Qe(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof g!=="object"||g===null||Array.isArray(g))throw new Qe(e,Error("Configuration must export a valid object"),"unknown");let p={config:dn(t,g,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)Ke.setWithFileCheck("file",p,e,o);return p}catch(f){throw f instanceof Error?re.configLoad(e,f):re.configLoad(e,Error(String(f)))}};if(a)return Lt.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){return $n({name:e,directory:t,alias:r})}generateNamePatterns(e,t){return jr({name:e,alias:t})}checkFileAccess(e){return Cs(async()=>Me(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Me(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let o of i)for(let a of this.extensions){let l=Pr(e,`${o}${a}`);if(await this.checkFileAccess(l))n.push(l)}}else try{let{readdirSync:i}=await import("fs"),o=i(e);for(let a of o)if(this.looksLikeConfigFile(a)){let l=Pr(e,a);if(await this.checkFileAccess(l))n.push(l)}}catch{return[]}return n}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((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!Me(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),o=i(e,"utf8");JSON.parse(o)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}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(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}var As=/^https?:\/\//;class yn{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:o=!0,customRules:a=[],trackPerformance:l=!0,verbose:c=!1}=r,f=async()=>{let u=[],g=[],m={stopOnFirstError:n,validateRequired:i,validateTypes:o,customRules:a,trackPerformance:l,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,m);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...a],m);else return this.validateWithJSONSchema(e,t,m)}catch(h){return u.push({path:"",message:`Validation failed: ${h}`,rule:"system"}),{isValid:!1,errors:u,warnings:g}}};if(l)return await Lt.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!ks(t))throw new et(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new et(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,o){if(o.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(n.push({path:r,message:`Expected type ${l.join(" or ")}, got ${a}`,expected:l.join(" or "),actual:a,rule:"type"}),o.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),o.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.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)n.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))n.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)n.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)n.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,n,i,o),o.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let a=e;if(o.validateRequired&&t.required){for(let l of t.required)if(!(l in a)){if(n.push({path:r?`${r}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[l,c]of Object.entries(t.properties))if(l in a){let f=r?`${r}.${l}`:l;if(this.validateObjectAgainstSchema(a[l],c,f,n,i,o),o.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(a))if(!l.has(c))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let o of t)try{let a=this.getValueByPath(e,o.path),l=this.validateWithRule(a,o,o.path);if(n.push(...l),r.stopOnFirstError&&n.length>0)break}catch(a){n.push({path:o.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.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))n.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 i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,o,a]=n;t.push({path:i,required:!o,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:As},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var z=new it("bunfig",{showTags:!0});function Fs(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 wn{fileLoader=new pn;envProcessor=new Ut;validator=new yn;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:o,...a}=e;try{if(r?.enabled){let c=this.checkCache(a.name||"",a);if(c)return c}let l;try{l=await this.loadConfigurationStrategies(a,!0,r)}catch(c){if(a.configFile)throw c;let f=a.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;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(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),g=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),m=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(m||u))throw c;if(g&&(!f||!m))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(!f)l={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else l={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(i||o)await this.validateConfiguration(l.config,i,o,a.name);if(r?.enabled&&l)this.cacheResult(a.name||"",l,r,a);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:a.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)z.warn(`Slow configuration loading detected: ${c.duration}ms for ${a.name}`);l.metrics=c}return l}catch(l){if(l instanceof Error&&l.name==="ConfigNotFoundError")throw l;let c=Date.now()-t;throw z.error(`Configuration loading failed after ${c}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,configFile:o,cwd:a,configDir:l,defaultConfig:c,checkEnv:f=!0,arrayStrategy:u="replace",verbose:g=!1}=e,m=a||tt.cwd(),h=[];if(o){let k=G(m,o);h.push(k);let V=f?pe(n,c,g):c,B=await this.fileLoader.tryLoadFromPaths([k],V,{arrayStrategy:u,verbose:g,cacheTtl:r?.ttl,useCache:!r?.ttl||r.ttl>100});if(!B)throw re.configNotFound(n||o,h,i);if(g)z.success(`Configuration loaded from explicit path: ${k}`);return this.finalizeResult(B,h,f,n,g)}let v=await this.loadLocalConfiguration(n,i,m,l,c,u,g,f,r);if(v)return h.push(...this.getLocalSearchPaths(n,i,m,l)),this.finalizeResult(v,h,f,n,g);let d=await this.loadHomeConfiguration(n,i,c,u,g,f);if(d)return h.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(d,h,f,n,g);let p=await this.loadPackageJsonConfiguration(n,i,m,c,u,g,f);if(p)return h.push(G(m,"package.json")),this.finalizeResult(p,h,f,n,g);if(h.push(...this.getAllSearchPaths(n,i,m,l)),t)throw re.configNotFound(n,h,i);return{...await this.applyEnvironmentVariables(n,c,f,g),warnings:[`No configuration file found for "${n}"${Fs(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,o,a,l,c){let f=l?pe(e,i,a):i,u=this.getLocalDirectories(r,n);for(let g of u){if(a)z.info(`Searching for configuration in: ${g}`);let m=this.fileLoader.generateConfigPaths(e,g,t),h=await this.fileLoader.tryLoadFromPaths(m,f,{arrayStrategy:o,verbose:a,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(h){if(a)z.success(`Configuration loaded from: ${h.source.path}`);return h}}return null}async loadHomeConfiguration(e,t,r,n,i,o){if(!e)return null;let a=o?pe(e,r,i):r,l=[G(ie(),".config",e),G(ie(),".config"),ie()];for(let c of l){if(i)z.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,a,{arrayStrategy:n,verbose:i});if(u){if(i)z.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,o,a){let l=a?pe(e,n,o):n;try{let c=G(r,"package.json");if(!En(c))return null;let f={};try{f=JSON.parse(bn(c,"utf8"))}catch(m){if(o)z.warn("Failed to parse package.json:",[m instanceof Error?m:Error(String(m))]);return null}let u=f[e],g=e;if(!u&&t){let m=Array.isArray(t)?t:[t];for(let h of m){if(!h)continue;if(f[h]){u=f[h],g=h;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(o)z.success(`Configuration loaded from package.json: ${g}`);return{config:dn(l,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(o)z.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:pe(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let o=r(e);if(o)i.push(...o)}if(t){let o=await this.validator.validateConfiguration(e,t);if(!o.isValid)i.push(...o.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(i.length>0)throw re.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Ke.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);Ke.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configFile)r.push(`configFile:${t.configFile}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Cn({cwd:e,configDir:t})}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(G(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),o=[];for(let a of i)o.push(...this.fileLoader.generateConfigPaths(e,a,t));return o}getHomeSearchPaths(e,t){if(!e)return[];let r=[G(ie(),".config",e),G(ie(),".config"),ie()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}var bt=new wn;async function s(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 n;if(r)n=await bt.loadConfig(e);else n=await bt.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){if(e.configFile)throw n;let i=n instanceof Error?n.name:"UnknownError",o=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||o.includes("config"))&&e.verbose)z.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let l=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await bt.applyEnvironmentVariables(l.name||"",t,!0,l.verbose||!1))?.config??t;return t}}function pe(e,t,r=!1){let n=new Ut,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(a,l=[]){let c={...a};for(let[f,u]of Object.entries(a)){let g=[...l,f],m=[`${i}_${g.join("_").toUpperCase()}`,`${i}_${g.map((d)=>d.toUpperCase()).join("")}`,`${i}_${g.map((d)=>d.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],h,v;for(let d of m)if(h=tt.env[d],h!==void 0){v=d;break}if(h!==void 0&&v)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(h.toLowerCase());else if(typeof u==="number"){let d=Number(h);if(!Number.isNaN(d))c[f]=d}else if(Array.isArray(u))try{c[f]=JSON.parse(h)}catch{c[f]=h.split(",").map((d)=>d.trim())}else c[f]=h;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=o(u,g)}return c}return o(t)}var ma=G(tt.cwd(),"config"),da=G(tt.cwd(),"src/generated");
62
+ export{s};