@stacksjs/ts-css 0.1.2 → 0.1.3
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.
- package/CHANGELOG.md +14 -0
- package/dist/chunk-1kmkypmr.js +3 -0
- package/dist/chunk-2wsah70r.js +2 -0
- package/dist/chunk-9ep6bwwb.js +2 -0
- package/dist/chunk-edwg811g.js +2 -0
- package/dist/chunk-thy3p95k.js +3 -0
- package/dist/index.js +51 -51
- package/dist/optimize/index.js +1 -1
- package/dist/parse/index.js +1 -1
- package/dist/select/index.js +1 -1
- package/dist/what/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,61 +1,61 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var C9=Object.defineProperty;var x9=($)=>$;function P9($,X){this[$]=x9.bind(null,X)}var Z8=($,X)=>{for(var Q in X)C9($,Q,{get:X[Q],enumerable:!0,configurable:!0,set:P9.bind(X,Q)})};var H0=import.meta.require;var DX={};Z8(DX,{walk:()=>W0,parse:()=>C0,makeList:()=>HX,generate:()=>f,decodeName:()=>Y8,clone:()=>e8,Tokenizer:()=>o0,TokenType:()=>J8,List:()=>d});function U0($){return{prev:null,next:null,data:$}}class d{head=null;tail=null;cursors=[];allocateCursor($,X){let Q={prev:$,next:X};return this.cursors.push(Q),Q}releaseCursor(){this.cursors.pop()}updateCursors($,X,Q,Z){for(let J of this.cursors){if(J.prev===$)J.prev=X;if(J.next===Q)J.next=Z}}static createItem($){return U0($)}createItem($){return U0($)}get isEmpty(){return this.head===null}get first(){return this.head?.data??null}get last(){return this.tail?.data??null}*[Symbol.iterator](){for(let $=this.head;$!=null;$=$.next)yield $.data}fromArray($){let X=null;this.head=null;for(let Q of $){let Z=U0(Q);if(Z.prev=X,X)X.next=Z;else this.head=Z;X=Z}return this.tail=X,this}toArray(){let $=[];for(let X=this.head;X!=null;X=X.next)$.push(X.data);return $}toJSON(){return this.toArray()}forEach($,X){let Q=this.allocateCursor(null,this.head);while(Q.next!==null){let Z=Q.next;Q.prev=Z,Q.next=Z.next,$.call(X,Z.data,Z,this)}this.releaseCursor()}forEachRight($,X){let Q=this.allocateCursor(this.tail,null);while(Q.prev!==null){let Z=Q.prev;Q.next=Z,Q.prev=Z.prev,$.call(X,Z.data,Z,this)}this.releaseCursor()}reduce($,X){let Q=X,Z=0;for(let J=this.head;J!=null;J=J.next)Q=$(Q,J.data,Z++,this);return Q}some($){let X=0;for(let Q=this.head;Q!=null;Q=Q.next)if($(Q.data,X++,this))return!0;return!1}map($){let X=new d,Q=null,Z=0;for(let J=this.head;J!=null;J=J.next){let Y=U0($(J.data,Z++,this));if(Y.prev=Q,Q)Q.next=Y;else X.head=Y;Q=Y}return X.tail=Q,X}filter($){let X=new d,Q=null,Z=0;for(let J=this.head;J!=null;J=J.next)if($(J.data,Z++,this)){let Y=U0(J.data);if(Y.prev=Q,Q)Q.next=Y;else X.head=Y;Q=Y}return X.tail=Q,X}clear(){let $=this.head;while($){let X=$.next;$.prev=null,$.next=null,$=X}this.head=null,this.tail=null}copy(){let $=new d,X=null;for(let Q=this.head;Q!=null;Q=Q.next){let Z=U0(Q.data);if(Z.prev=X,X)X.next=Z;else $.head=Z;X=Z}return $.tail=X,$}prepend($){return this.insert($,this.head)}prependData($){return this.insert(U0($),this.head)}append($){return this.insert($,null)}appendData($){return this.insert(U0($),null)}insert($,X=null){if(X!=null)if(this.updateCursors(X.prev,$,X,$),X.prev===null){if(this.head!==X)throw Error("before doesn't belong to list");this.head=$,X.prev=$,$.next=X,this.updateCursors(null,$,null,null)}else X.prev.next=$,$.prev=X.prev,X.prev=$,$.next=X;else if(this.updateCursors(this.tail,$,null,$),this.tail!==null)this.tail.next=$,$.prev=this.tail,this.tail=$;else this.head=$,this.tail=$;return this}insertData($,X=null){return this.insert(U0($),X)}remove($){if(this.updateCursors($,$.prev,$,$.next),$.prev!==null)$.prev.next=$.next;else if(this.head===$)this.head=$.next;else throw Error("item doesn't belong to list");if($.next!==null)$.next.prev=$.prev;else if(this.tail===$)this.tail=$.prev;else throw Error("item doesn't belong to list");return $.prev=null,$.next=null,$}push($){this.insert(U0($),null)}pop(){if(this.tail===null)return null;return this.remove(this.tail)}unshift($){this.prependData($)}shift(){if(this.head===null)return null;return this.remove(this.head)}prependList($){return this.insertList($,this.head)}appendList($){return this.insertList($,null)}insertList($,X=null){if($.head===null)return this;if(X!==null){if(this.updateCursors(X.prev,$.tail,X,$.head),X.prev!==null)X.prev.next=$.head,$.head.prev=X.prev;else this.head=$.head;X.prev=$.tail,$.tail.next=X}else{if(this.updateCursors(this.tail,$.tail,null,$.head),this.tail!==null)this.tail.next=$.head,$.head.prev=this.tail;else this.head=$.head;this.tail=$.tail}return $.head=null,$.tail=null,this}replace($,X){if(X instanceof d)this.insertList(X,$),this.remove($);else this.insert(X,$),this.remove($)}}function HX(){return new d}function e8($){return n0($)}function n0($){if($===null||typeof $!=="object")return $;if($ instanceof d){let Q=new d;for(let Z of $)Q.appendData(n0(Z));return Q}if(Array.isArray($))return $.map(n0);if("type"in $&&typeof $.type==="string"){let Q={type:$.type};for(let Z of Object.keys($)){if(Z==="type")continue;Q[Z]=n0($[Z])}return Q}let X={};for(let Q of Object.keys($))X[Q]=n0($[Q]);return X}function f($){switch($.type){case"StyleSheet":return s($.children,"");case"Rule":return`${f($.prelude)}{${f($.block)}}`;case"Block":return b9($.children);case"Atrule":{let X=`@${$.name}`;if($.prelude){let Q=f($.prelude);if(Q)X+=` ${Q}`}if($.block)X+=`{${f($.block)}}`;else X+=";";return X}case"AtrulePrelude":return s($.children,"");case"SelectorList":return s($.children,",");case"Selector":return s($.children,"");case"TypeSelector":return $.name;case"IdSelector":return`#${$.name}`;case"ClassSelector":return`.${$.name}`;case"NestingSelector":return"&";case"AttributeSelector":{let X=`[${$.name.name}`;if($.matcher&&$.value)if(X+=$.matcher,$.value.type==="String")X+=`"${$$($.value.value)}"`;else X+=$.value.name;if($.flags)X+=` ${$.flags}`;return X+="]",X}case"PseudoClassSelector":return $.children?`:${$.name}(${s($.children,"")})`:`:${$.name}`;case"PseudoElementSelector":return $.children?`::${$.name}(${s($.children,"")})`:`::${$.name}`;case"Combinator":return $.name===" "?" ":$.name;case"Declaration":return`${$.property}:${f($.value)}${$.important?"!important":""}`;case"DeclarationList":return s($.children,";");case"Value":return s($.children,"");case"Identifier":return $.name;case"Number":return $.value;case"Percentage":return`${$.value}%`;case"Dimension":return $.value+$.unit;case"String":return`"${$$($.value)}"`;case"Url":return/[\s"'()\\\u0000-\u001F\u007F]/.test($.value)?`url("${$$($.value)}")`:`url(${$.value})`;case"Hash":return`#${$.name}`;case"Operator":return $.value;case"Function":return`${$.name}(${s($.children,"")})`;case"Parentheses":return`(${s($.children,"")})`;case"Brackets":return`[${s($.children,"")}]`;case"Raw":return $.value;case"Comment":return $.value.startsWith("!")?`/*${$.value}*/`:"";case"WhiteSpace":return" ";case"CDO":return"<!--";case"CDC":return"-->";case"AnPlusB":{let X=$.a??"",Q=$.b??"";if(X&&Q){let Z=Number(Q);return`${X==="1"?"":X==="-1"?"-":X}n${Z>=0?`+${Q}`:Q}`}if(X)return`${X==="1"?"":X==="-1"?"-":X}n`;return Q}case"Ratio":return`${$.left.value}/${$.right.value}`;case"UnicodeRange":return $.value;case"Nth":return $.selector?`${f($.nth)} of ${f($.selector)}`:f($.nth);case"MediaQueryList":return s($.children,",");case"MediaQuery":return s($.children,"");case"MediaFeature":{let X=`(${$.name}`;if($.value)X+=`:${f($.value)}`;return X+=")",X}}return""}function s($,X){let Q="",Z=!0,J=null,Y=$.head;while(Y!=null){let G=Y.data;if(G.type==="WhiteSpace"){let U=Y.next?Y.next.data:null;if(UX(J)||UX(U)){Y=Y.next;continue}}let H=f(G);if(!H){Y=Y.next;continue}if(!Z&&X&&!k9(J))Q+=X;Z=!1,Q+=H,J=G,Y=Y.next}return Q}function b9($){let X="",Q=null,Z=$.head;while(Z!=null){let J=Z.data,Y=f(J);if(!Y){Z=Z.next;continue}if(Q&&T9(Q,J))X+=";";X+=Y,Q=J,Z=Z.next}return X}function T9($,X){return $.type==="Declaration"&&X.type!=="Comment"}function UX($){if(!$||$.type!=="Operator")return!1;let X=$.value;return X===":"||X===","||X==="/"}function k9($){if(!$)return!1;return $.type==="Operator"||$.type==="Combinator"}function $$($){let X="";for(let Q=0;Q<$.length;Q++){let Z=$.charCodeAt(Q);if(Z===92)X+="\\\\";else if(Z===34)X+="\\\"";else if(Z<32||Z===127){let J=Z.toString(16),Y=Q+1<$.length?$.charCodeAt(Q+1):-1,G=Y===32||Y===9||Y===10||Y===12||Y===13||Y>=48&&Y<=57||Y>=65&&Y<=70||Y>=97&&Y<=102;X+=`\\${J}${G?" ":""}`}else X+=$[Q]}return X}var J8;((R)=>{R[R.EOF=0]="EOF";R[R.Ident=1]="Ident";R[R.Function=2]="Function";R[R.AtKeyword=3]="AtKeyword";R[R.Hash=4]="Hash";R[R.String=5]="String";R[R.BadString=6]="BadString";R[R.Url=7]="Url";R[R.BadUrl=8]="BadUrl";R[R.Delim=9]="Delim";R[R.Number=10]="Number";R[R.Percentage=11]="Percentage";R[R.Dimension=12]="Dimension";R[R.WhiteSpace=13]="WhiteSpace";R[R.CDO=14]="CDO";R[R.CDC=15]="CDC";R[R.Colon=16]="Colon";R[R.Semicolon=17]="Semicolon";R[R.Comma=18]="Comma";R[R.LeftSquareBracket=19]="LeftSquareBracket";R[R.RightSquareBracket=20]="RightSquareBracket";R[R.LeftParenthesis=21]="LeftParenthesis";R[R.RightParenthesis=22]="RightParenthesis";R[R.LeftCurlyBracket=23]="LeftCurlyBracket";R[R.RightCurlyBracket=24]="RightCurlyBracket";R[R.Comment=25]="Comment"})(J8||={});var V0=(()=>{let $=new Uint8Array(128);for(let X=0;X<128;X++){let Q=0;if(X===32||X===9||X===10||X===12||X===13)Q|=1;if(X>=48&&X<=57)Q|=2;if(X>=48&&X<=57||X>=65&&X<=70||X>=97&&X<=102)Q|=4;if(X>=65&&X<=90||X>=97&&X<=122||X===95)Q|=8;if(X===10||X===12||X===13)Q|=16;$[X]=Q}return $})();function Q0($){return $<128&&(V0[$]&2)!==0}function i0($){return $<128&&(V0[$]&4)!==0}function qX($){return $>=128||$<128&&(V0[$]&8)!==0}function y9($){return $===45||$>=128||$<128&&(V0[$]&10)!==0}function h9($){return $>=0&&$<=8||$===11||$>=14&&$<=31||$===127}function Q$($){return $<128&&(V0[$]&16)!==0}function _0($){return $<128&&(V0[$]&1)!==0}function D0($,X){if($!==92)return!1;if(Q$(X))return!1;return!0}function X$($,X,Q){if($===45)return qX(X)||X===45||D0(X,Q);if(qX($))return!0;if($===92)return D0($,X);return!1}function v9($,X,Q){if($===43||$===45){if(Q0(X))return!0;if(X===46&&Q0(Q))return!0;return!1}if($===46)return Q0(X);return Q0($)}class o0{source;offset=0;types;starts;ends;count=0;_tokens=null;_lineStarts=null;constructor($){this.source=$;let X=Math.max(64,Math.ceil($.length/3));this.types=new Uint8Array(X),this.starts=new Uint32Array(X),this.ends=new Uint32Array(X),this.tokenize()}get lineStarts(){if(this._lineStarts==null)this._lineStarts=f9(this.source);return this._lineStarts}get tokens(){if(this._tokens!=null)return this._tokens;let $=Array.from({length:this.count});for(let X=0;X<this.count;X++)$[X]={type:this.types[X],start:this.starts[X],end:this.ends[X]};return this._tokens=$,$}addToken($,X,Q){if(this.count>=this.types.length)this.grow();this.types[this.count]=$,this.starts[this.count]=X,this.ends[this.count]=Q,this.count++}grow(){let X=this.types.length*2,Q=new Uint8Array(X);Q.set(this.types),this.types=Q;let Z=new Uint32Array(X);Z.set(this.starts),this.starts=Z;let J=new Uint32Array(X);J.set(this.ends),this.ends=J}tokenize(){let $=this.source,X=0,Q=$.length;while(X<Q){let Z=$.charCodeAt(X);if(Z===47&&$.charCodeAt(X+1)===42){let G=X;X+=2;while(X<Q&&!($.charCodeAt(X)===42&&$.charCodeAt(X+1)===47))X++;X=X<Q?X+2:Q,this.addToken(25,G,X);continue}if(_0(Z)){let G=X;while(X<Q&&_0($.charCodeAt(X)))X++;this.addToken(13,G,X);continue}if(Z===34||Z===39){X=this.consumeString(Z,X);continue}if(Z===35){if(X+1<Q&&(y9($.charCodeAt(X+1))||D0($.charCodeAt(X+1),$.charCodeAt(X+2)))){let G=X;X++,X=this.consumeName(X),this.addToken(4,G,X);continue}this.addToken(9,X,X+1),X++;continue}switch(Z){case 40:this.addToken(21,X,X+1),X++;continue;case 41:this.addToken(22,X,X+1),X++;continue;case 91:this.addToken(19,X,X+1),X++;continue;case 93:this.addToken(20,X,X+1),X++;continue;case 123:this.addToken(23,X,X+1),X++;continue;case 125:this.addToken(24,X,X+1),X++;continue;case 44:this.addToken(18,X,X+1),X++;continue;case 58:this.addToken(16,X,X+1),X++;continue;case 59:this.addToken(17,X,X+1),X++;continue}if(Z===60&&$.startsWith("!--",X+1)){this.addToken(14,X,X+4),X+=4;continue}if(Z===45&&$.startsWith("->",X+1)){this.addToken(15,X,X+3),X+=3;continue}if(Z===64){let G=$.charCodeAt(X+1),H=$.charCodeAt(X+2),U=$.charCodeAt(X+3);if(X$(G,H,U)){let q=X;X++,X=this.consumeName(X),this.addToken(3,q,X);continue}this.addToken(9,X,X+1),X++;continue}let J=$.charCodeAt(X+1),Y=$.charCodeAt(X+2);if(v9(Z,J,Y)){X=this.consumeNumeric(X);continue}if(X$(Z,J,Y)){X=this.consumeIdentLike(X);continue}if(Z===92){if(D0(Z,J)){X=this.consumeIdentLike(X);continue}this.addToken(9,X,X+1),X++;continue}this.addToken(9,X,X+1),X++}this.addToken(0,Q,Q)}consumeString($,X){let Q=this.source,Z=Q.length,J=X+1;while(J<Z){let Y=Q.charCodeAt(J);if(Y===$)return J++,this.addToken(5,X,J),J;if(Q$(Y))return this.addToken(6,X,J),J;if(Y===92){let G=Q.charCodeAt(J+1);if(Q$(G)){J+=2;continue}if(J+1<Z){J=this.consumeEscapeSkip(J+1);continue}}J++}return this.addToken(5,X,J),J}consumeEscapeSkip($){let X=this.source;if($>=X.length)return $;let Q=X.charCodeAt($);if(i0(Q)){let Z=1;$++;while(Z<6&&$<X.length&&i0(X.charCodeAt($)))$++,Z++;if($<X.length&&_0(X.charCodeAt($)))$++;return $}return $+1}consumeName($){let X=this.source,Q=X.length,Z=$;while(Z<Q){let J=X.charCodeAt(Z);if(J<128&&(V0[J]&10)!==0){Z++;continue}if(J===45){Z++;continue}if(J>=128){Z++;continue}if(J===92&&D0(J,X.charCodeAt(Z+1))){Z=this.consumeEscapeSkip(Z+1);continue}break}return Z}consumeNumber($){let X=this.source,Q=$;if(X.charCodeAt(Q)===43||X.charCodeAt(Q)===45)Q++;while(Q<X.length&&Q0(X.charCodeAt(Q)))Q++;if(X.charCodeAt(Q)===46&&Q0(X.charCodeAt(Q+1))){Q+=2;while(Q<X.length&&Q0(X.charCodeAt(Q)))Q++}let Z=X.charCodeAt(Q);if(Z===69||Z===101){let J=X.charCodeAt(Q+1),Y=X.charCodeAt(Q+2);if(Q0(J)){Q+=2;while(Q<X.length&&Q0(X.charCodeAt(Q)))Q++}else if((J===43||J===45)&&Q0(Y)){Q+=3;while(Q<X.length&&Q0(X.charCodeAt(Q)))Q++}}return Q}consumeNumeric($){let X=this.source,Q=this.consumeNumber($),Z=X.charCodeAt(Q),J=X.charCodeAt(Q+1),Y=X.charCodeAt(Q+2);if(X$(Z,J,Y)){let G=this.consumeName(Q);return this.addToken(12,$,G),G}if(Z===37)return this.addToken(11,$,Q+1),Q+1;return this.addToken(10,$,Q),Q}consumeIdentLike($){let X=this.source,Q=this.consumeName($),Z=X.charCodeAt(Q);if(Z===40&&Q-$===3){let J=X.charCodeAt($)|32,Y=X.charCodeAt($+1)|32,G=X.charCodeAt($+2)|32;if(J===117&&Y===114&&G===108){let H=Q+1;while(H<X.length&&_0(X.charCodeAt(H)))H++;let U=X.charCodeAt(H);if(U===34||U===39)return this.addToken(2,$,Q+1),Q+1;return this.consumeUrl($,Q)}}if(Z===40)return this.addToken(2,$,Q+1),Q+1;return this.addToken(1,$,Q),Q}consumeUrl($,X){let Q=this.source,Z=Q.length,J=X+1;while(J<Z&&_0(Q.charCodeAt(J)))J++;while(J<Z){let Y=Q.charCodeAt(J);if(Y===41)return J++,this.addToken(7,$,J),J;if(_0(Y)){let G=J;while(J<Z&&_0(Q.charCodeAt(J)))J++;if(J>=Z)return this.addToken(7,$,J),J;if(Q.charCodeAt(J)===41)return J++,this.addToken(7,$,J),J;return this.consumeBadUrl($,G)}if(Y===34||Y===39||Y===40||h9(Y))return this.consumeBadUrl($,J);if(Y===92){if(D0(Y,Q.charCodeAt(J+1))){J=this.consumeEscapeSkip(J+1);continue}return this.consumeBadUrl($,J)}J++}return this.addToken(7,$,J),J}consumeBadUrl($,X){let Q=this.source,Z=X;while(Z<Q.length){let J=Q.charCodeAt(Z);if(J===41){Z++;break}if(J===92&&D0(J,Q.charCodeAt(Z+1))){Z=this.consumeEscapeSkip(Z+1);continue}Z++}return this.addToken(8,$,Z),Z}locate($){let X=this.lineStarts,Q=0,Z=X.length-1;while(Q<Z){let Y=Q+Z+1>>1;if(X[Y]<=$)Q=Y;else Z=Y-1}let J=X[Q];return{line:Q+1,column:$-J+1}}}function f9($){let X=[0],Q=$.length;for(let Z=0;Z<Q;Z++){let J=$.charCodeAt(Z);if(J===10)X.push(Z+1);else if(J===13){if($.charCodeAt(Z+1)!==10)X.push(Z+1)}}return X}function Z$($,X,Q){for(let Z=X;Z<Q;Z++)if($.charCodeAt(Z)===92)return g9($,X,Q,Z);return $.slice(X,Q)}function g9($,X,Q,Z){let J=$.slice(X,Z),Y=Z;while(Y<Q){if($.charCodeAt(Y)!==92){J+=$[Y],Y++;continue}if(Y+1>=Q){Y++;continue}let H=$.charCodeAt(Y+1);if(H===10){Y+=2;continue}if(H===13){Y+=$.charCodeAt(Y+2)===10?3:2;continue}if(i0(H)){let U=Y+1,q="";while(q.length<6&&U<Q&&i0($.charCodeAt(U)))q+=$[U],U++;let z=Number.parseInt(q,16);if(U<Q&&_0($.charCodeAt(U)))U++;J+=z===0||z>=55296&&z<=57343||z>1114111?String.fromCodePoint(65533):String.fromCodePoint(z),Y=U;continue}J+=$[Y+1],Y+=2}return J}function Y8($,X,Q){for(let Z=X;Z<Q;Z++)if($.charCodeAt(Z)===92)return d9($,X,Q,Z);return $.slice(X,Q)}function d9($,X,Q,Z){let J=$.slice(X,Z),Y=Z;while(Y<Q){if($.charCodeAt(Y)!==92){J+=$[Y],Y++;continue}let H=Y+1,U="";while(U.length<6&&H<Q&&i0($.charCodeAt(H)))U+=$[H],H++;if(U.length>0){let q=Number.parseInt(U,16);if(H<Q&&_0($.charCodeAt(H)))H++;J+=q===0||q>=55296&&q<=57343||q>1114111?String.fromCodePoint(65533):String.fromCodePoint(q),Y=H;continue}if(H<Q){J+=$[H],Y=H+1;continue}J+=String.fromCodePoint(65533),Y=H}return J}function RX($,X){let Q=new o0($);return{source:$,types:Q.types,starts:Q.starts,ends:Q.ends,count:Q.count,end:Q.count,pos:0,positions:X.positions??!1,filename:X.filename,parseValue:X.parseValue??!0,parseAtrulePrelude:X.parseAtrulePrelude??!0,parseCustomProperty:X.parseCustomProperty??!1,parseRulePrelude:X.parseRulePrelude??!0,onParseError:X.onParseError,tokenizer:Q}}function F($){return $.pos<$.end?$.types[$.pos]:0}function j($){let X=$.pos;if(X>=$.end)return{type:0,start:$.starts[X]??$.source.length,end:$.ends[X]??$.source.length};return{type:$.types[X],start:$.starts[X],end:$.ends[X]}}function L($){let X=$.pos++;if(X>=$.end)return{type:0,start:$.starts[X]??$.source.length,end:$.ends[X]??$.source.length};return{type:$.types[X],start:$.starts[X],end:$.ends[X]}}function q0($,X){return $.source.slice(X.start,X.end)}function Z0($){let{types:X,end:Q}=$;while($.pos<Q){let Z=X[$.pos];if(Z===13||Z===25)$.pos++;else break}}function zX($){let{types:X,end:Q}=$;while($.pos<Q&&X[$.pos]===13)$.pos++}function w($,X,Q){if(!$.positions)return null;let Z=$.tokenizer.locate(X.start),J=$.tokenizer.locate(Q.end);return{source:$.filename??"<unknown>",start:{offset:X.start,line:Z.line,column:Z.column},end:{offset:Q.end,line:J.line,column:J.column}}}function FX($){if(!$.positions)return null;let X=j($),Q=$.tokenizer.locate(X.start);return{source:$.filename??"<unknown>",start:{offset:X.start,line:Q.line,column:Q.column},end:{offset:X.start,line:Q.line,column:Q.column}}}function G8($,X,Q,Z){return{type:"Raw",value:$,loc:w(Z,X,Q)}}function n(){return new d}function J$($,X,Q,Z){if($.onParseError){let{line:J,column:Y}=$.tokenizer.locate(Q.start),G=SyntaxError(`${$.filename??"<input>"}:${J}:${Y}: ${X}`);G.line=J,G.column=Y,G.offset=Q.start,$.onParseError(G,Z)}return Z}function C0($,X={}){let Q=RX($,X);switch(X.context??"stylesheet"){case"stylesheet":return AX(Q);case"atrule":return U8(Q)??_X(Q);case"atrulePrelude":return p9(Q);case"mediaQuery":case"mediaQueryList":return WX(Q);case"rule":return G$(Q);case"selectorList":return q$(Q);case"selector":return wX(Q);case"block":return H$(Q);case"declarationList":return n9(Q);case"declaration":return U$(Q)??_X(Q);case"value":return i9(Q);case"raw":return WX(Q);default:return AX(Q)}}function _X($){return{type:"StyleSheet",children:n(),loc:FX($)}}function WX($){let X=j($),Q=X;while(F($)!==0)Q=L($);return{type:"Raw",value:$.source.slice(X.start,Q.end),loc:w($,X,Q)}}function AX($){let X=j($),Q=n(),Z=$.types,J=$.end;while($.pos<J){let H=Z[$.pos];if(H===13){$.pos++;continue}if(H===25){let z={type:25,start:$.starts[$.pos],end:$.ends[$.pos]},_=Y$($,z);$.pos++,Q.appendData(_);continue}if(H===0)break;if(H===14||H===15){$.pos++;continue}if(H===3){let z=U8($);if(z)Q.appendData(z);continue}if(H===24){$.pos++;continue}let U=$.pos,q=G$($);if(Q.appendData(q),$.pos===U)$.pos++}let Y=$.end-1,G=Y>=0?{type:$.types[Y],start:$.starts[Y],end:$.ends[Y]}:{type:0,start:0,end:0};return{type:"StyleSheet",children:Q,loc:w($,X,G)}}function Y$($,X){return{type:"Comment",value:$.source.slice(X.start+2,X.end-2),loc:w($,X,X)}}function U8($){let X=j($);if(X.type!==3)return null;$.pos++;let Q=H8($.source,X.start+1,X.end);Z0($);let Z=$.pos,J=j($),Y=$.types,G=$.end,H=Z,U=Z;while(H<G){let _=Y[H];if(_===0||_===17||_===23)break;if(_!==13&&_!==25)U=H+1;H++}let q=null;if(U>Z){let _=$.starts[Z],A=$.ends[U-1],W={type:Y[U-1],start:$.starts[U-1],end:A},K=$.source.slice(_,A).trim();if(K.length>0)if($.parseAtrulePrelude)try{let B=$.end;$.end=U,$.pos=Z;let M=n();while(F($)!==0){let x=O0($);if(x)M.appendData(x)}if(MX(M),$.end=B,$.pos=H,M.isEmpty)q=G8(K,J,W,$);else q={type:"AtrulePrelude",children:M,loc:null}}catch(B){let M=G8(K,J,W,$);J$($,`Failed to parse @${Q} prelude: ${B.message}`,J,M),q=M,$.pos=H}else q=G8(K,J,W,$),$.pos=H;else $.pos=H}else $.pos=H;let z=null;if(F($)===17)L($);else if(F($)===23)z=H$($,u9.has(Q));return{type:"Atrule",name:Q,prelude:q,block:z,loc:w($,X,j($))}}var m9=new Set(["is","not","where","has","matches","-moz-any","-webkit-any"]),u9=new Set(["media","supports","document","layer","container","scope","starting-style","-moz-document","keyframes","-webkit-keyframes","-moz-keyframes","-o-keyframes"]);function p9($){let X=j($),Q=n();while(F($)!==0){if(j($).type===13){$.pos++;continue}let J=O0($);if(J)Q.appendData(J)}return{type:"AtrulePrelude",children:Q,loc:w($,X,j($))}}function G$($){let X=j($),Q;if($.parseRulePrelude)Q=q$($);else{let J=j($),Y=J;while(F($)!==0&&F($)!==23)Y=L($);let G=$.source.slice(J.start,Y.end).trim();Q=G8(G,J,Y,$)}let Z=H$($,!0);return{type:"Rule",prelude:Q,block:Z,loc:w($,X,j($))}}function H$($,X=!1){let Q=j($);if(F($)!==23)return{type:"Block",children:n(),loc:FX($)};$.pos++;let Z=n(),J=$.types,Y=$.end;while($.pos<Y){let G=J[$.pos];if(G===24||G===0)break;if(G===13){$.pos++;continue}if(G===25){let U={type:25,start:$.starts[$.pos],end:$.ends[$.pos]};$.pos++,Z.appendData(Y$($,U));continue}if(G===3){let U=U8($);if(U)Z.appendData(U);continue}if(X&&c9($,l9)){let U=G$($);Z.appendData(U);continue}let H=U$($);if(H)Z.appendData(H);if($.pos<Y&&J[$.pos]===17)$.pos++}if(F($)===24)$.pos++;return{type:"Block",children:Z,loc:w($,Q,j($))}}function c9($,X){let Q=$.pos,Z=X($);return $.pos=Q,Z}function l9($){let{types:X,end:Q}=$;while($.pos<Q){let Z=X[$.pos];if(Z===23)return!0;if(Z===17||Z===24||Z===0)return!1;$.pos++}return!1}function n9($){let X=j($),Q=n();while(F($)!==0&&F($)!==24){let Z=j($);if(Z.type===13){$.pos++;continue}if(Z.type===25){Q.appendData(Y$($,L($)));continue}if(Z.type===17){$.pos++;continue}if(Z.type===3){let Y=U8($);if(Y)Q.appendData(Y);continue}let J=U$($);if(J)Q.appendData(J);if(F($)===17)L($)}return{type:"DeclarationList",children:Q,loc:w($,X,j($))}}function U$($){Z0($);let X=j($);if(X.type!==1&&X.type!==4&&!(X.type===9&&$.source[X.start]==="*"&&$.source[X.start+1]===" "))if(X.type===9&&$.source[X.start]==="*")$.pos++;else{J$($,"Expected property name",X,{type:"Raw",value:"",loc:null});let{types:E,end:c}=$;while($.pos<c){let v=E[$.pos];if(v===0||v===17||v===24)break;$.pos++}return null}let Q=$.starts[$.pos],Z=$.ends[$.pos];$.pos++;let J=$.source.slice(Q,Z);if(zX($),F($)!==16){J$($,`Expected ':' after property "${J}"`,j($),{type:"Raw",value:"",loc:null});let{types:E,end:c}=$;while($.pos<c){let v=E[$.pos];if(v===0||v===17||v===24)break;$.pos++}return null}$.pos++,zX($);let{types:Y,starts:G,end:H,pos:U}=$,q=U,z=U,_=-1,A=-1;while(q<H){let E=Y[q];if(E===0||E===17||E===24)break;if(E===9&&$.source.charCodeAt(G[q])===33){let c=q+1;while(c<H&&Y[c]===13)c++;if(c<H&&Y[c]===1){let v=G[c];if($.ends[c]-v===9&&($.source.charCodeAt(v)|32)===105&&($.source.charCodeAt(v+1)|32)===109&&($.source.charCodeAt(v+2)|32)===112&&($.source.charCodeAt(v+3)|32)===111&&($.source.charCodeAt(v+4)|32)===114&&($.source.charCodeAt(v+5)|32)===116&&($.source.charCodeAt(v+6)|32)===97&&($.source.charCodeAt(v+7)|32)===110&&($.source.charCodeAt(v+8)|32)===116){A=q,_=c,q=c+1;continue}}}if(E!==13&&E!==25)z=q+1;q++}let W=z,K=_>=0?{type:1,start:G[_],end:$.ends[_]}:null,B=J.startsWith("--"),M,x=G[U],T=W>U?$.ends[W-1]:x,r={type:Y[U],start:x,end:$.ends[U]},a=W>U?{type:Y[W-1],start:G[W-1],end:T}:r;if(B&&!$.parseCustomProperty||!$.parseValue)M={type:"Raw",value:$.source.slice(x,T).trim(),loc:w($,r,a)};else if(W===U)M={type:"Value",children:n(),loc:w($,r,a)};else{let E=$.end;$.end=W,$.pos=U,M=jX($),$.end=E}return $.pos=q,{type:"Declaration",property:J,important:K?!0:!1,value:M,loc:w($,X,j($))}}function i9($){return jX($)}function jX($){let X=j($),Q=n();while(F($)!==0&&F($)!==17&&F($)!==24&&F($)!==22&&F($)!==20){let Z=O0($);if(Z)Q.appendData(Z)}return LX(Q),{type:"Value",children:Q,loc:w($,X,j($))}}function MX($){for(let X of $)if("children"in X&&X.children instanceof d)MX(X.children);LX($)}function LX($){let X=$.head;while(X){if(X.data.type==="Number"){let Q=X.next;while(Q&&Q.data.type==="WhiteSpace")Q=Q.next;if(Q&&Q.data.type==="Operator"&&Q.data.value==="/"){let Z=Q.next;while(Z&&Z.data.type==="WhiteSpace")Z=Z.next;if(Z&&Z.data.type==="Number"){let J={type:"Ratio",left:X.data,right:Z.data,loc:null},Y=X.next;while(Y&&Y!==Z.next){let G=Y.next;$.remove(Y),Y=G}$.replace(X,$.createItem(J)),X=$.head;continue}}}X=X.next}}function O0($){let X=$.pos;if(X>=$.end)return null;let Q=$.types[X],Z=$.starts[X],J=$.ends[X],Y=$.source;switch(Q){case 13:return $.pos++,$.positions?{type:"WhiteSpace",value:" ",loc:l($,Z,J)}:{type:"WhiteSpace",value:" ",loc:null};case 25:return $.pos++,{type:"Comment",value:Y.slice(Z+2,J-2),loc:$.positions?l($,Z,J):null};case 10:return $.pos++,{type:"Number",value:Y.slice(Z,J),loc:$.positions?l($,Z,J):null};case 11:return $.pos++,{type:"Percentage",value:Y.slice(Z,J-1),loc:$.positions?l($,Z,J):null};case 12:{$.pos++;let G=Z,H=Y.charCodeAt(G);if(H===43||H===45)G++;let U=!1;while(G<J){let z=Y.charCodeAt(G);if(z>=48&&z<=57){G++;continue}if(z===46&&!U){U=!0,G++;continue}break}let q=Y.charCodeAt(G);if(q===69||q===101){let z=G+1,_=Y.charCodeAt(z);if(_===43||_===45)z++;let A=!1;while(z<J){let W=Y.charCodeAt(z);if(W>=48&&W<=57){z++,A=!0;continue}break}if(A)G=z}return{type:"Dimension",value:Y.slice(Z,G),unit:Y.slice(G,J),loc:$.positions?l($,Z,J):null}}case 1:return $.pos++,{type:"Identifier",name:Y8(Y,Z,J),loc:$.positions?l($,Z,J):null};case 5:{$.pos++;let G=Z+1,U=J-Z>=2&&Y.charCodeAt(J-1)===Y.charCodeAt(Z)?J-1:J;return{type:"String",value:Z$(Y,G,U),loc:$.positions?l($,Z,J):null}}case 7:{$.pos++;let G=Z+4;while(G<J&&BX(Y.charCodeAt(G)))G++;let H=J;if(H>G&&Y.charCodeAt(H-1)===41)H--;while(H>G&&BX(Y.charCodeAt(H-1)))H--;let U;if(H-G>=2){let q=Y.charCodeAt(G),z=Y.charCodeAt(H-1);if((q===34||q===39)&&q===z)U=Y.slice(G+1,H-1);else U=Y.slice(G,H)}else U=Y.slice(G,H);return{type:"Url",value:U,loc:$.positions?l($,Z,J):null}}case 4:return $.pos++,{type:"Hash",name:Y.slice(Z+1,J),loc:$.positions?l($,Z,J):null};case 2:return r9($);case 21:return a9($);case 18:return $.pos++,{type:"Operator",value:",",loc:$.positions?l($,Z,J):null};case 16:return $.pos++,{type:"Operator",value:":",loc:$.positions?l($,Z,J):null};case 9:{$.pos++;let G=Y.charCodeAt(Z),H=Y[Z];if(o9(G))return{type:"Operator",value:H,loc:$.positions?l($,Z,J):null};return{type:"Identifier",name:H,loc:$.positions?l($,Z,J):null}}case 19:{$.pos++;let G=n();while(F($)!==0&&F($)!==20){let U=O0($);if(U)G.appendData(U)}let H=$.pos<$.end?$.ends[$.pos]:J;if(F($)===20)$.pos++;return{type:"Brackets",children:G,loc:$.positions?l($,Z,H):null}}case 3:case 23:case 24:case 22:case 20:case 17:case 0:case 14:case 15:case 6:case 8:return $.pos++,{type:"Raw",value:Y.slice(Z,J),loc:$.positions?l($,Z,J):null}}return $.pos++,null}function BX($){return $===32||$===9||$===10||$===12||$===13}function o9($){return $===47||$===43||$===45||$===42||$===61||$===62||$===60||$===126||$===124||$===36||$===94||$===33||$===38}function H8($,X,Q){for(let Z=X;Z<Q;Z++){let J=$.charCodeAt(Z);if(J>=65&&J<=90)return $.slice(X,Q).toLowerCase()}return $.slice(X,Q)}function l($,X,Q){let Z=$.tokenizer.locate(X),J=$.tokenizer.locate(Q);return{source:$.filename??"<unknown>",start:{offset:X,line:Z.line,column:Z.column},end:{offset:Q,line:J.line,column:J.column}}}function r9($){let X=L($),Q=H8($.source,X.start,X.end-1),Z=n();while(F($)!==0&&F($)!==22){let J=O0($);if(J)Z.appendData(J)}if(F($)===22)L($);if(Q==="url"){for(let J=Z.head;J!=null;J=J.next)if(J.data.type==="String")return{type:"Url",value:J.data.value,loc:w($,X,j($))}}return{type:"Function",name:Q,children:Z,loc:w($,X,j($))}}function a9($){let X=L($),Q=n();while(F($)!==0&&F($)!==22){let Z=O0($);if(Z)Q.appendData(Z)}if(F($)===22)L($);return{type:"Parentheses",children:Q,loc:w($,X,j($))}}function q$($){let X=j($),Q=n();while(F($)!==0){if(Z0($),F($)===0||F($)===23)break;let Z=wX($);if(Z.children.head!==null)Q.appendData(Z);if(Z0($),F($)===18){L($);continue}break}return{type:"SelectorList",children:Q,loc:w($,X,j($))}}function wX($){let X=j($),Q=n(),Z=!0;while(F($)!==0&&F($)!==18&&F($)!==23){let J=j($);if(J.type===13){if(L($),!Z&&F($)!==0&&F($)!==18&&F($)!==23&&!KX($)&&!s9($)){let G={type:"Combinator",name:" ",loc:w($,J,J)};Q.appendData(G),Z=!0}continue}if(J.type===9&&$.source.charCodeAt(J.start)===124&&$.types[$.pos+1]===9&&$.source.charCodeAt($.starts[$.pos+1])===124){let G=j($);L($);let H=L($),U={type:"Combinator",name:"||",loc:w($,G,H)};Q.appendData(U),Z=!0,Z0($);continue}if(KX($)){let G=L($),U={type:"Combinator",name:$.source[G.start],loc:w($,G,G)};Q.appendData(U),Z=!0,Z0($);continue}let Y=t9($);if(!Y)break;Q.appendData(Y),Z=!1}while(Q.tail&&Q.tail.data.type==="Combinator")Q.remove(Q.tail);return{type:"Selector",children:Q,loc:w($,X,j($))}}function KX($){let X=j($);if(X.type!==9)return!1;let Q=$.source[X.start];return Q===">"||Q==="+"||Q==="~"}function s9($){if($.types[$.pos]!==9)return!1;if($.source.charCodeAt($.starts[$.pos])!==124)return!1;if($.types[$.pos+1]!==9)return!1;return $.source.charCodeAt($.starts[$.pos+1])===124}function t9($){let X=j($);switch(X.type){case 1:{if(L($),F($)===9&&$.source[j($).start]==="|"&&$.source[j($).start+1]!=="="&&!($.types[$.pos+1]===9&&$.source.charCodeAt($.starts[$.pos+1])===124)){if(L($),F($)===1){let Z=L($);return{type:"TypeSelector",name:`${q0($,X)}|${q0($,Z)}`,loc:w($,X,Z)}}if(F($)===9&&$.source[j($).start]==="*"){let Z=L($);return{type:"TypeSelector",name:`${q0($,X)}|*`,loc:w($,X,Z)}}}return{type:"TypeSelector",name:q0($,X),loc:w($,X,X)}}case 11:return L($),{type:"TypeSelector",name:q0($,X),loc:w($,X,X)};case 10:return L($),{type:"TypeSelector",name:q0($,X),loc:w($,X,X)};case 9:{let Q=$.source[X.start];if(Q==="*")return L($),{type:"TypeSelector",name:"*",loc:w($,X,X)};if(Q==="."){if(L($),F($)===1){let Z=L($);return{type:"ClassSelector",name:q0($,Z),loc:w($,X,Z)}}return null}if(Q==="&")return L($),{type:"NestingSelector",loc:w($,X,X)};return L($),null}case 4:return L($),{type:"IdSelector",name:$.source.slice(X.start+1,X.end),loc:w($,X,X)};case 16:{L($);let Q=F($)===16;if(Q)L($);return e9($,Q,X)}case 19:return $Z($)}return null}function e9($,X,Q){let Z=j($);if(Z.type===1){L($);let J=H8($.source,Z.start,Z.end);return X?{type:"PseudoElementSelector",name:J,children:null,loc:w($,Q,Z)}:{type:"PseudoClassSelector",name:J,children:null,loc:w($,Q,Z)}}if(Z.type===2){L($);let J=H8($.source,Z.start,Z.end-1),Y=n();if(!X&&m9.has(J)){let U=j($),q=U,z=1;while(F($)!==0&&z>0){if(F($)===21||F($)===2)z++;else if(F($)===22){if(z--,z===0)break}q=L($)}if(F($)===22)L($);let _=$.source.slice(U.start,q.end).trim();if(_.length>0){let A=RX(_,{positions:!1}),W=q$(A);Y.appendData(W)}}else{while(F($)!==0&&F($)!==22){let U=O0($);if(U)Y.appendData(U)}if(F($)===22)L($)}if(X)return{type:"PseudoElementSelector",name:J,children:Y,loc:w($,Q,j($))};return{type:"PseudoClassSelector",name:J,children:Y,loc:w($,Q,j($))}}return null}function $Z($){let X=L($);Z0($);let Q=j($);if(Q.type!==1)return null;L($);let Z={type:"Identifier",name:q0($,Q),loc:w($,Q,Q)};Z0($);let J=null,Y=null,G=null,H=j($);if(H.type===9){let q=$.source[H.start],z=$.source[H.start+1];if(q==="=")J="=",L($);else if((q==="~"||q==="|"||q==="^"||q==="$"||q==="*")&&z==="="){L($);let W=j($);if(W.type===9&&$.source[W.start]==="=")L($),J=`${q}=`}Z0($);let _=j($);if(_.type===5){L($);let W=_.end-_.start>=2&&$.source.charCodeAt(_.end-1)===$.source.charCodeAt(_.start);Y={type:"String",value:Z$($.source,_.start+1,W?_.end-1:_.end),loc:w($,_,_)}}else if(_.type===1)L($),Y={type:"Identifier",name:q0($,_),loc:w($,_,_)};Z0($);let A=j($);if(A.type===1)L($),G=q0($,A)}Z0($);let U=j($);if(F($)===20)U=L($);return{type:"AttributeSelector",name:Z,matcher:J,value:Y,flags:G,loc:w($,X,U)}}var IX=Symbol("walkSkip"),b=Symbol("walkStop");function XZ($){return{root:$,stylesheet:null,atrule:null,atrulePrelude:null,rule:null,selector:null,block:null,declaration:null,function:null}}function QZ($,X){let Q=XZ($),Z=typeof X==="function"?X:X.enter,J=typeof X==="function"?null:X.leave??null,Y=typeof X==="function"?null:X.visit??null,G=typeof X==="function"?!1:X.reverse??!1;function H(U,q,z){let _=null,A;switch(U.type){case"StyleSheet":_="stylesheet",A=Q.stylesheet,Q.stylesheet=U;break;case"Atrule":_="atrule",A=Q.atrule,Q.atrule=U;break;case"AtrulePrelude":_="atrulePrelude",A=Q.atrulePrelude,Q.atrulePrelude=U;break;case"Rule":_="rule",A=Q.rule,Q.rule=U;break;case"Selector":_="selector",A=Q.selector,Q.selector=U;break;case"Block":_="block",A=Q.block,Q.block=U;break;case"Declaration":_="declaration",A=Q.declaration,Q.declaration=U;break;case"Function":_="function",A=Q.function,Q.function=U;break}let W;if((Y===null||Y===U.type)&&Z){let K=Z.call(Q,U,q,z);if(K===IX){if(_)Q[_]=A;return}if(K===b){if(_)Q[_]=A;return b}}if(W=ZZ(U,G,H),W===b){if(_)Q[_]=A;return b}if((Y===null||Y===U.type)&&J){if(J.call(Q,U,q,z)===b){if(_)Q[_]=A;return b}}if(_)Q[_]=A;return}return H($,null,null)}var W0=Object.assign(QZ,{skip:IX,stop:b});function ZZ($,X,Q){if("children"in $&&$.children instanceof d)return JZ($.children,X,Q);if($.type==="Rule"){if(Q($.prelude,null,null)===b)return b;if(Q($.block,null,null)===b)return b;return}if($.type==="Atrule"){if($.prelude){if(Q($.prelude,null,null)===b)return b}if($.block){if(Q($.block,null,null)===b)return b}return}if($.type==="Declaration")return Q($.value,null,null);if($.type==="AttributeSelector"){if(Q($.name,null,null)===b)return b;if($.value)return Q($.value,null,null);return}return}function JZ($,X,Q){let Z;if(X)$.forEachRight((J,Y,G)=>{if(Z)return;if(Q(J,Y,G)===b)Z=b});else $.forEach((J,Y,G)=>{if(Z)return;if(Q(J,Y,G)===b)Z=b});return Z}var xX={};Z8(xX,{stringify:()=>z8,parse:()=>A0,isTraversal:()=>_$,IgnoreCaseMode:()=>CX});var VX=/(?:\\(?:[\dA-Fa-f]{1,6} ?|[^])|[\w\-\u00B0-\uFFFF])+/y,YZ=/\\([\dA-Fa-f]{1,6} ?|[^])/g;function GZ($){return $.replace(YZ,(X,Q)=>{if(Q.length>1&&/^[\dA-Fa-f]/.test(Q)){let Z=Number.parseInt(Q,16);if(Z>=55296&&Z<=57343)return"\uFFFD";return String.fromCodePoint(Z)}return Q})}function NX($){return $.indexOf("\\")<0?$:GZ($)}var HZ=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 UZ($){switch($){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 q8($){return $===32||$===9||$===10||$===13||$===12}function A0($,X={}){let Q=[],Z=EX(Q,$,X,0);if(Z<$.length)throw Error(`Unmatched selector: ${$.slice(Z)}`);return Q}function J0($,X){VX.lastIndex=X;let Q=VX.exec($);if(!Q)throw Error(`Expected name, found ${$.slice(X)}`);return{value:NX(Q[0]),end:X+Q[0].length}}function N0($,X){while(X<$.length&&q8($.charCodeAt(X)))X++;return X}function EX($,X,Q,Z){let J=[],Y=N0(X,Z),G=X.length,H=Q.xmlMode===!0,U=Q.lowerCaseAttributeNames!==!1&&!H,q=Q.lowerCaseTags!==!1;while(Y<G){let z=X.charCodeAt(Y);if(q8(z)){let _=Y+1;while(_<G&&q8(X.charCodeAt(_)))_++;if(J.length===0)return _;Y=_,x0(J,"descendant");continue}if(z===62||z===60||z===126||z===43||z===124){let _=Y+1;while(_<G&&q8(X.charCodeAt(_)))_++;switch(Y=_,z){case 62:x0(J,"child");break;case 60:x0(J,"parent");break;case 126:x0(J,"sibling");break;case 43:x0(J,"adjacent");break;case 124:if(Y<G&&X.charCodeAt(Y)===124)Y++,Y=N0(X,Y),x0(J,"column-combinator");else J.push({type:"tag",name:"",namespace:""});break}continue}if(z===44){if(J.length===0)throw Error("Empty sub-selector");$.push(J),J=[],Y=N0(X,Y+1);continue}if(z===47&&X.charCodeAt(Y+1)===42){let _=X.indexOf("*/",Y+2);if(_<0)throw Error("Unmatched comment");Y=N0(X,_+2);continue}if(z===42){Y++,J.push({type:"universal",namespace:null});continue}if(z===35){let _=J0(X,Y+1);Y=_.end,J.push({type:"attribute",name:"id",action:"equals",value:_.value,namespace:null,ignoreCase:!1});continue}if(z===46){let _=J0(X,Y+1);Y=_.end,J.push({type:"attribute",name:"class",action:"element",value:_.value,namespace:null,ignoreCase:!1});continue}if(z===91){Y=qZ(X,Y,J,Q,H,U);continue}if(z===58){Y=zZ(X,Y,J,Q);continue}if(z===124){Y++;let _=J0(X,Y);Y=_.end,J.push({type:"tag",name:q?_.value.toLowerCase():_.value,namespace:""});continue}{let _=J0(X,Y);if(Y=_.end,Y<G&&X.charCodeAt(Y)===124&&X.charCodeAt(Y+1)!==61){Y++;let A=J0(X,Y);Y=A.end,J.push({type:"tag",name:q?A.value.toLowerCase():A.value,namespace:_.value})}else J.push({type:"tag",name:q?_.value.toLowerCase():_.value,namespace:null})}}if(J.length>0)$.push(J);return Y}function qZ($,X,Q,Z,J,Y){let G=X+1,H=$.length,U;if($.charCodeAt(G)===124)throw Error("Empty namespace not supported");if($.charCodeAt(G)===42&&$.charCodeAt(G+1)===124){G+=2;let W=J0($,G);G=W.end,U=W.value}else{let W=J0($,G);if(G=W.end,U=W.value,$.charCodeAt(G)===124&&$.charCodeAt(G+1)!==61){G++;let K=J0($,G);G=K.end,U=K.value}}G=N0($,G);let q="exists",z="",_=null,A=$.charCodeAt(G);if(A===61)q="equals",G++;else if(A===33&&$.charCodeAt(G+1)===61)q="not",G+=2;else{let W=UZ(A);if(W!==null&&$.charCodeAt(G+1)===61)q=W,G+=2}if(q!=="exists"){G=N0($,G);let W=$.charCodeAt(G);if(W===34||W===39){let B=SX($,G+1,W);z=NX($.slice(G+1,B)),G=B+1}else{let B=J0($,G);z=B.value,G=B.end}G=N0($,G);let K=$.charCodeAt(G);if(K===105||K===73)_=!0,G++;else if(K===115||K===83)_=!1,G++}if($.charCodeAt(G)!==93)throw Error("Expected ]");if(G++,_===null&&!J&&HZ.has(U.toLowerCase()))_="quirks";return Q.push({type:"attribute",name:Y?U.toLowerCase():U,action:q,value:z,namespace:null,ignoreCase:_}),G}function zZ($,X,Q,Z){if($.charCodeAt(X+1)===58){let H=X+2,U=J0($,H);H=U.end;let q=U.value.toLowerCase(),z=null;if($.charCodeAt(H)===40){let _=OX($,H);z=$.slice(H+1,_).trim(),H=_+1}return Q.push({type:"pseudo-element",name:q,data:z}),H}let J=X+1,Y=J0($,J);J=Y.end;let G=Y.value.toLowerCase();if($.charCodeAt(J)===40){let H=OX($,J),U=$.slice(J+1,H);if(J=H+1,G==="is"||G==="not"||G==="where"||G==="has"||G==="matches"||G==="-moz-any"||G==="-webkit-any"){let q=[];EX(q,U.trim(),Z,0),Q.push({type:"pseudo",name:G,data:q})}else Q.push({type:"pseudo",name:G,data:U.trim()})}else Q.push({type:"pseudo",name:G,data:null});return J}function x0($,X){if($.length>0&&$[$.length-1].type==="descendant"&&X!=="descendant")$.pop();if($.length>0&&$[$.length-1].type===X)return;$.push({type:X})}function SX($,X,Q){let Z=X,J=$.length;while(Z<J){let Y=$.charCodeAt(Z);if(Y===92){Z+=2;continue}if(Y===Q)return Z;Z++}throw Error("Unterminated string")}function OX($,X){let Q=1,Z=X+1,J=$.length;while(Z<J){let Y=$.charCodeAt(Z);if(Y===92){Z+=2;continue}if(Y===34||Y===39){Z=SX($,Z+1,Y)+1;continue}if(Y===40)Q++;else if(Y===41){if(Q--,Q===0)return Z}Z++}throw Error("Unterminated parenthesis")}var _Z={child:" > ",parent:" < ",sibling:" ~ ",adjacent:" + ",descendant:" ","column-combinator":" || "};function z8($){return $.map(WZ).join(", ")}function WZ($){return $.map((X,Q)=>AZ(X,$[Q-1])).join("")}function AZ($,X){switch($.type){case"tag":return`${z$($.namespace)}${r0($.name)}`;case"universal":return`${z$($.namespace)}*`;case"attribute":{if($.name==="id"&&$.action==="equals"&&!$.ignoreCase&&!$.namespace)return`#${r0($.value)}`;if($.name==="class"&&$.action==="element"&&!$.ignoreCase&&!$.namespace)return`.${r0($.value)}`;let Q=`[${z$($.namespace)}${r0($.name)}`;if($.action!=="exists"){let Z=BZ[$.action]??"=";if(Q+=Z,Q+=`"${$.value.replace(/"/g,"\\\"")}"`,$.ignoreCase===!0)Q+=" i";else if($.ignoreCase===!1)Q+=" s"}return Q+="]",Q}case"pseudo":if($.data===null)return`:${$.name}`;if(typeof $.data==="string")return`:${$.name}(${$.data})`;return`:${$.name}(${z8($.data)})`;case"pseudo-element":return $.data===null?`::${$.name}`:`::${$.name}(${$.data})`;case"descendant":case"child":case"parent":case"sibling":case"adjacent":case"column-combinator":return _Z[$.type]??" "}return""}var BZ={equals:"=",element:"~=",start:"^=",end:"$=",any:"*=",not:"!=",hyphen:"|="};function z$($){if($===null)return"";if($==="")return"|";return`${r0($)}|`}var KZ=/[^\w\u00B0-\uFFFF-]/g;function r0($){if($==="")return"";return $.replace(KZ,(X)=>`\\${X}`)}var RZ=new Set(["adjacent","child","descendant","parent","sibling","column-combinator"]);function _$($){return RZ.has($.type)}var CX={Unknown:null,QuirksMode:"quirks",IgnoreCase:!0,CaseSensitive:!1};var pX={};Z8(pX,{selectOne:()=>mX,selectAll:()=>dX,parseAndCompile:()=>L0,is:()=>uX,compile:()=>A8,clearSelectorCache:()=>CZ});function PX($,X,Q,Z){let J=[],Y=[X],G=[0];for(;;){if(G[0]>=Y[0].length){if(Y.length===1)return J;Y.shift(),G.shift();continue}let H=Y[0][G[0]++];if(!Q.isTag(H))continue;if($(H))J.push(H);if(Z||Q.getName(H)!=="template"){let U=Q.getChildren(H);if(U.length>0)Y.unshift(U),G.unshift(0)}}}function bX($,X,Q,Z){let J=[X],Y=[0];for(;;){if(Y[0]>=J[0].length){if(J.length===1)return null;J.shift(),Y.shift();continue}let G=J[0][Y[0]++];if(!Q.isTag(G))continue;if($(G))return G;if(Z||Q.getName(G)!=="template"){let H=Q.getChildren(G);if(H.length>0)J.unshift(H),Y.unshift(0)}}}function W$($,X){if(Array.isArray($))return X.removeSubsets($);return X.getChildren($)}var P0=($)=>{return!0};function TX($){return $===32||$===9||$===10||$===12||$===13}function _8($,X){let Q=X.length,Z=$.length;if(Q===0||Q>Z)return!1;let J=$.indexOf(X);while(J>=0){let Y=J===0||TX($.charCodeAt(J-1)),G=J+Q,H=G===Z||TX($.charCodeAt(G));if(Y&&H)return!0;J=$.indexOf(X,J+1)}return!1}function FZ($,X,Q){if(X.ignoreCase===!0)return!0;if(X.ignoreCase===!1)return!1;if(X.ignoreCase==="quirks")return!Q.xmlMode;return!1}function kX($,X,Q){let Z=X.adapter,J=$.action,Y=$.name,G=$.value,H=FZ(G,$,X);if(H)G=G.toLowerCase();return jZ(J,Y,G,H,Z,Q)}function jZ($,X,Q,Z,J,Y){let G=Y===P0;switch($){case"exists":if(G)return(H)=>J.hasAttrib(H,X);return(H)=>J.hasAttrib(H,X)&&Y(H);case"equals":if(!Z){if(G)return(H)=>J.getAttributeValue(H,X)===Q;return(H)=>J.getAttributeValue(H,X)===Q&&Y(H)}if(G)return(H)=>{let U=J.getAttributeValue(H,X);if(U==null)return!1;return U.toLowerCase()===Q};return(H)=>{let U=J.getAttributeValue(H,X);if(U==null)return!1;return U.toLowerCase()===Q&&Y(H)};case"not":return(H)=>{let U=J.getAttributeValue(H,X);if(U==null)return Y(H);return(Z?U.toLowerCase():U)!==Q&&Y(H)};case"start":if(Q==="")return()=>!1;if(G)return(H)=>{let U=J.getAttributeValue(H,X);if(U==null)return!1;return(Z?U.toLowerCase():U).startsWith(Q)};return(H)=>{let U=J.getAttributeValue(H,X);if(U==null)return!1;return(Z?U.toLowerCase():U).startsWith(Q)&&Y(H)};case"end":if(Q==="")return()=>!1;if(G)return(H)=>{let U=J.getAttributeValue(H,X);if(U==null)return!1;return(Z?U.toLowerCase():U).endsWith(Q)};return(H)=>{let U=J.getAttributeValue(H,X);if(U==null)return!1;return(Z?U.toLowerCase():U).endsWith(Q)&&Y(H)};case"any":{if(Q==="")return()=>!1;if(Z){if(G)return(H)=>{let U=J.getAttributeValue(H,X);if(U==null)return!1;return U.toLowerCase().indexOf(Q)>=0};return(H)=>{let U=J.getAttributeValue(H,X);if(U==null)return!1;return U.toLowerCase().indexOf(Q)>=0&&Y(H)}}if(G)return(H)=>{let U=J.getAttributeValue(H,X);if(U==null)return!1;return U.indexOf(Q)>=0};return(H)=>{let U=J.getAttributeValue(H,X);if(U==null)return!1;return U.indexOf(Q)>=0&&Y(H)}}case"element":{if(Q===""||/\s/.test(Q))return()=>!1;if(Z){if(G)return(H)=>{let U=J.getAttributeValue(H,X);if(U==null)return!1;return _8(U.toLowerCase(),Q)};return(H)=>{let U=J.getAttributeValue(H,X);if(U==null)return!1;return _8(U.toLowerCase(),Q)&&Y(H)}}if(G)return(H)=>{let U=J.getAttributeValue(H,X);if(U==null)return!1;return _8(U,Q)};return(H)=>{let U=J.getAttributeValue(H,X);if(U==null)return!1;return _8(U,Q)&&Y(H)}}case"hyphen":if(G)return(H)=>{let U=J.getAttributeValue(H,X);if(U==null)return!1;let q=Z?U.toLowerCase():U;if(q===Q)return!0;if(q.startsWith(Q)&&q.charAt(Q.length)==="-")return!0;return!1};return(H)=>{let U=J.getAttributeValue(H,X);if(U==null)return!1;let q=Z?U.toLowerCase():U;if(q===Q)return Y(H);if(q.startsWith(Q)&&q.charAt(Q.length)==="-")return Y(H);return!1}}return(H)=>{return!1}}var MZ=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"]),LZ=new Set(["is","where","matches","-moz-any","-webkit-any"]),wZ=new Set(["nth-child","nth-last-child","nth-of-type","nth-last-of-type"]);function yX($,X,Q){let Z=X.adapter,J=$.name,Y=$.data;if($.type==="pseudo"&&LZ.has(J)){if(!Array.isArray(Y))return Q;let G=Y.map((H)=>L0(H,X));if(G.length===1){let H=G[0];return(U)=>H(U)&&Q(U)}return(H)=>{for(let U of G)if(U(H))return Q(H);return!1}}if($.type==="pseudo"&&J==="not"){if(!Array.isArray(Y))return Q;let G=Y.map((H)=>L0(H,X));if(G.length===1){let H=G[0];return(U)=>!H(U)&&Q(U)}return(H)=>{for(let U of G)if(U(H))return!1;return Q(H)}}if($.type==="pseudo"&&J==="has"){if(!Array.isArray(Y))return Q;let G=Y.map((U)=>L0(U,X)),H=G.length===1?G[0]:(U)=>{for(let q of G)if(q(U))return!0;return!1};return(U)=>{let q=Z.getChildren(U).slice();while(q.length>0){let z=q.pop();if(!Z.isTag(z))continue;if(H(z))return Q(U);let _=Z.getChildren(z);for(let A=0;A<_.length;A++)q.push(_[A])}return!1}}if($.type==="pseudo"&&wZ.has(J)){let G=DZ(typeof Y==="string"?Y:"",J,X);return(H)=>G(H)&&Q(H)}if($.type==="pseudo"&&J==="first-child")return(G)=>{let H=Z.getSiblings(G);for(let U of H){if(!Z.isTag(U))continue;return U===G&&Q(G)}return!1};if($.type==="pseudo"&&J==="last-child")return(G)=>{let H=Z.getSiblings(G);for(let U=H.length-1;U>=0;U--){let q=H[U];if(!Z.isTag(q))continue;return q===G&&Q(G)}return!1};if($.type==="pseudo"&&J==="first-of-type")return(G)=>{let H=Z.getName(G),U=Z.getSiblings(G);for(let q of U){if(!Z.isTag(q)||Z.getName(q)!==H)continue;return q===G&&Q(G)}return!1};if($.type==="pseudo"&&J==="last-of-type")return(G)=>{let H=Z.getName(G),U=Z.getSiblings(G);for(let q=U.length-1;q>=0;q--){let z=U[q];if(!Z.isTag(z)||Z.getName(z)!==H)continue;return z===G&&Q(G)}return!1};if($.type==="pseudo"&&J==="only-child")return(G)=>{let H=Z.getSiblings(G),U=0,q=!1;for(let z of H){if(!Z.isTag(z))continue;if(U++,U>1)return!1;if(z===G)q=!0}return U===1&&q&&Q(G)};if($.type==="pseudo"&&J==="only-of-type")return(G)=>{let H=Z.getName(G),U=Z.getSiblings(G),q=0,z=!1;for(let _ of U){if(!Z.isTag(_)||Z.getName(_)!==H)continue;if(q++,q>1)return!1;if(_===G)z=!0}return q===1&&z&&Q(G)};if($.type==="pseudo"&&J==="empty")return(G)=>Z.getChildren(G).length===0&&Q(G);if($.type==="pseudo"&&J==="root")return(G)=>{let H=Z.getParent(G);return(H==null||!Z.isTag(H))&&Q(G)};if($.type==="pseudo"&&J==="scope"){if(X.context&&Array.isArray(X.context)){let G=new Set(X.context);return(H)=>G.has(H)&&Q(H)}if(X.context){let G=X.context;return(H)=>H===G&&Q(H)}return(G)=>{let H=Z.getParent(G);return(H==null||!Z.isTag(H))&&Q(G)}}if($.type==="pseudo"&&MZ.has(J)){if(X.pseudos&&X.pseudos[J]){let G=X.pseudos[J];if(typeof G==="function")return(H)=>G(H,void 0)&&Q(H)}return(G)=>{return!1}}if($.type==="pseudo-element")return Q;if(X.pseudos&&X.pseudos[J]){let G=X.pseudos[J];if(typeof G==="function")return(H)=>G(H,typeof Y==="string"?Y:void 0)&&Q(H);if(typeof G==="string"){let H=A0(G),U=a0(H,X);return(q)=>U(q)&&Q(q)}}return(G)=>{return!1}}function IZ($){let X=$.trim();if(X==="odd")return{a:2,b:1};if(X==="even")return{a:2,b:0};let Q=/^([+-]?\d*)n([+-]\d+)?$/.exec(X.replace(/\s+/g,""));if(Q){let J=Q[1]===""||Q[1]==="+"?1:Q[1]==="-"?-1:Number(Q[1]),Y=Q[2]?Number(Q[2]):0;return{a:J,b:Y}}let Z=Number(X);if(!Number.isNaN(Z))return{a:0,b:Z};return null}function DZ($,X,Q){let Z=IZ($);if(!Z)return()=>!1;let{a:J,b:Y}=Z,G=Q.adapter,H=X==="nth-of-type"||X==="nth-last-of-type",U=X==="nth-last-child"||X==="nth-last-of-type";return(q)=>{let z=G.getSiblings(q),_=H?G.getName(q):"",A=0,W=0;for(let B of z){if(!G.isTag(B))continue;if(H&&G.getName(B)!==_)continue;if(W++,B===q)A=W}if(A===0)return!1;let K=U?W-A+1:A;if(J===0)return K===Y;return(K-Y)/J>=0&&(K-Y)%J===0}}function hX($,X,Q){let Z=X.adapter,J=Q===P0;switch($.type){case"tag":{let Y=X.lowerCaseTags!==!1&&!X.xmlMode?$.name.toLowerCase():$.name;if(J)return(G)=>Z.getName(G)===Y;return(G)=>Z.getName(G)===Y&&Q(G)}case"universal":return Q;case"attribute":return kX($,X,Q);case"pseudo":case"pseudo-element":return yX($,X,Q);case"descendant":case"child":case"parent":case"sibling":case"adjacent":case"column-combinator":return Q}return(Y)=>{return!1}}var VZ={universal:50,tag:30,attribute:1,pseudo:0,"pseudo-element":0},OZ={exists:10,equals:8,not:7,start:6,end:6,hyphen:5,any:4,element:3};function vX($){let X=VZ[$.type]??0;if($.type==="attribute")return X+(OZ[$.action]??0);return X}function a0($,X){if($.length===1)return L0($[0],X);let Q=$.map((Z)=>L0(Z,X));return(Z)=>Q.some((J)=>J(Z))}function L0($,X){let Q=X.adapter,Z=[[]],J=[];for(let G of $)if(G.type==="descendant"||G.type==="child"||G.type==="sibling"||G.type==="adjacent"||G.type==="parent"||G.type==="column-combinator")J.push(G),Z.push([]);else Z[Z.length-1].push(G);let Y=P0;for(let G=0;G<Z.length;G++){let H=Z[G].slice().sort((U,q)=>vX(U)-vX(q));for(let U of H)Y=hX(U,X,Y);if(G<J.length)Y=NZ(J[G],Y,Q)}return Y}function NZ($,X,Q){switch($.type){case"descendant":case"column-combinator":return(Z)=>{let J=Q.getParent(Z);while(J){if(Q.isTag(J)&&X(J))return!0;J=Q.getParent(J)}return!1};case"child":return(Z)=>{let J=Q.getParent(Z);return J!=null&&Q.isTag(J)&&X(J)};case"sibling":return(Z)=>{let J=Q.getSiblings(Z);for(let Y of J){if(Y===Z)return!1;if(Q.isTag(Y)&&X(Y))return!0}return!1};case"adjacent":return(Z)=>{let J=Q.getSiblings(Z),Y=null;for(let G of J){if(G===Z)return Y!=null&&Q.isTag(Y)&&X(Y);Y=G}return!1};case"parent":return(Z)=>Q.existsOne(X,Q.getChildren(Z))}return(Z)=>{return!1}}function gX($){if(!$||!$.adapter)throw Error("css-select: adapter is required");return $.adapter}var W8=new WeakMap;function EZ($){return($.xmlMode?1:0)<<0|($.lowerCaseAttributeNames===!1?1:0)<<1|($.lowerCaseTags===!1?1:0)<<2}function SZ($,X){let Q=W8.get($);if(!Q)Q=[],W8.set($,Q);let Z=Q[X];if(!Z)Z=new Map,Q[X]=Z;return Z}function fX($,X){let Q=A0($,{xmlMode:X.xmlMode,lowerCaseAttributeNames:X.lowerCaseAttributeNames,lowerCaseTags:X.lowerCaseTags});return a0(Q,X)}function A8($,X){if(typeof $!=="string")return a0($,X);if(X.cacheResults===!1||!X.adapter)return fX($,X);let Q=SZ(X.adapter,EZ(X)),Z=Q.get($);if(Z!==void 0)return Z;return Z=fX($,X),Q.set($,Z),Z}function CZ($,X){if(X===void 0){W8.delete($);return}let Q=W8.get($);if(!Q)return;for(let Z of Q)if(Z)Z.delete(X)}function dX($,X,Q){let Z=gX(Q),J=typeof $==="function"?$:A8($,Q),Y=W$(X,Z);return PX(J,Y,Z,Q.xmlMode===!0)}function mX($,X,Q){let Z=gX(Q),J=typeof $==="function"?$:A8($,Q),Y=W$(X,Z);return bX(J,Y,Z,Q.xmlMode===!0)}function uX($,X,Q){return(typeof X==="function"?X:A8(X,Q))($)}var JQ={};Z8(JQ,{syntax:()=>ZQ,specificityToString:()=>QQ,specificity:()=>b0,removeComments:()=>E0,minifyBlock:()=>R$,minify:()=>K$,dedupeDeclarations:()=>s0,compressTree:()=>K8});function E0($,X={}){let Q=X.exclamation??!1,Z=!1;W0($,(J,Y,G)=>{if(J.type!=="Comment")return;let H=J.value.startsWith("!");if(Q===!0&&H)return;if(Q==="first-exclamation"&&H&&!Z){Z=!0;return}if(Y&&G)G.remove(Y)})}function s0($){W0($,(X)=>{if(X.type!=="Block"&&X.type!=="DeclarationList")return;if(!("children"in X)||!X.children)return;let Q=X.children,Z=Q.head;if(Z==null||Z.next==null)return;let J=0;for(let H=Z;H!=null;H=H.next)if(H.data.type==="Declaration"){if(J++,J>=2)break}if(J<2)return;let Y=new Map,G=[];for(let H=Z;H!=null;H=H.next){let U=H.data;if(U.type!=="Declaration")continue;let q=U.property,z=Y.get(q);if(z){let _=!!z.decl.important,A=!!U.important;if(A||_===A)G.push(z.item),Y.set(q,{item:H,decl:U});else G.push(H)}else Y.set(q,{item:H,decl:U})}for(let H of G)Q.remove(H)})}var xZ={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"},PZ={"#f00":"red","#ff0000":"red","#000080":"navy","#008080":"teal"};function B$($){if(!$.startsWith("#"))return $;let X=$.slice(1);if(X.length===6){if(X[0]===X[1]&&X[2]===X[3]&&X[4]===X[5])return`#${X[0]}${X[2]}${X[4]}`}if(X.length===8){if(X[0]===X[1]&&X[2]===X[3]&&X[4]===X[5]&&X[6]===X[7])return`#${X[0]}${X[2]}${X[4]}${X[6]}`}return $}function cX($){let X=$.toLowerCase();return xZ[X]??null}function lX($){let X=$.toLowerCase();return PZ[X]??null}function bZ($,X,Q){let Z=($<<16|X<<8|Q).toString(16).padStart(6,"0");return B$(`#${Z}`)}var TZ=/^rgba?\(\s*([+-]?\d*\.?\d+%?)\s*[,\s]\s*([+-]?\d*\.?\d+%?)\s*[,\s]\s*([+-]?\d*\.?\d+%?)\s*(?:[,/]\s*([+-]?\d*\.?\d+%?)\s*)?\)$/;function nX($){let X=TZ.exec($.trim());if(!X)return $;let Q=A$(X[1]),Z=A$(X[2]),J=A$(X[3]);if(X[4]!==void 0&&!kZ(X[4]))return $;return bZ(Q,Z,J)}function kZ($){if($.endsWith("%"))return Number.parseFloat($)>=100;return Number.parseFloat($)>=1}function A$($){if($.endsWith("%"))return Math.max(0,Math.min(255,Math.round(Number.parseFloat($)*2.55)));return Math.max(0,Math.min(255,Math.round(Number.parseFloat($))))}var yZ=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 B8($){if($.charCodeAt(0)===43)$=$.slice(1);if($.includes(".")){let X=$.replace(/(\.\d*?)0+($|[eE])/,"$1$2");X=X.replace(/\.($|[eE])/,"$1"),$=X}if($.startsWith("0.")&&$.length>2)$=$.slice(1);else if($.startsWith("-0.")&&$.length>3)$=`-${$.slice(2)}`;if($==="-0"||$==="-.0"||$==="-0.0")$="0";return $}function iX($,X){let Q=B8($);if((Q==="0"||Q==="-0")&&yZ.has(X.toLowerCase()))return{value:"0",unit:""};return{value:Q,unit:X}}function oX($){return B8($)}function rX($,X){let Q=Number.parseFloat($);if(!Number.isFinite(Q))return $;let Z=X<0?0:X;return Q.toFixed(Z)}var aX=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 sX($){if(!$||$.type!=="Operator")return!1;let X=$.value;return X===":"||X===","||X==="/"}function hZ($){let X=$.children;if(!X)return;while(X.head&&X.head.data.type==="WhiteSpace")X.remove(X.head);while(X.tail&&X.tail.data.type==="WhiteSpace")X.remove(X.tail);let Q=X.head;while(Q){let Z=Q.next;if(Q.data.type==="WhiteSpace"){let J=Q.prev&&sX(Q.prev.data),Y=Z&&sX(Z.data);if(J||Y)X.remove(Q)}Q=Z}}function K8($,X={}){let Q=X.floatPrecision??null,Z=Q===null?null:(J)=>rX(J,Q);W0($,{enter(J,Y,G){switch(J.type){case"Number":{let H=Z?Z(J.value):J.value;J.value=B8(H);return}case"Percentage":{let H=Z?Z(J.value):J.value;J.value=oX(H);return}case"Dimension":{let H=Z?Z(J.value):J.value,U=iX(H,J.unit);J.value=U.value,J.unit=U.unit;return}case"Hash":{let H=B$(`#${J.name}`).slice(1);if(J.name=H,Y&&G&&this.declaration&&aX.has(this.declaration.property.toLowerCase())){let U=lX(`#${H}`);if(U&&U.length<H.length+1){let q={type:"Identifier",name:U,loc:J.loc};G.replace(Y,G.createItem(q))}}return}case"Identifier":{if(!Y||!G||!this.declaration)return;if(!aX.has(this.declaration.property.toLowerCase()))return;let H=cX(J.name);if(H&&H.length<J.name.length){let U={type:"Hash",name:H.slice(1),loc:J.loc};G.replace(Y,G.createItem(U))}return}case"Url":return;case"Function":{let H=J.name.toLowerCase();if((H==="rgb"||H==="rgba")&&Y&&G)J.__rgbReplaceCandidate=!0}}},leave(J,Y,G){if(J.type==="Parentheses"||J.type==="Function"||J.type==="Value")hZ(J);if(J.type==="Function"&&J.__rgbReplaceCandidate&&Y&&G){let H=f(J),U=nX(H);if(U!==H&&U.startsWith("#")){let q={type:"Hash",name:U.slice(1),loc:J.loc};G.replace(Y,G.createItem(q))}}}})}function K$($,X={}){let Q=C0($,{context:"stylesheet"});return tX(Q,X)}function R$($,X={}){let Q=C0($,{context:"declarationList"});return tX(Q,X)}function tX($,X){if(X.comments===!1)E0($,{exclamation:!1});else if(X.comments==="first-exclamation")E0($,{exclamation:"first-exclamation"});else E0($,{exclamation:!0});return K8($,{floatPrecision:X.floatPrecision??null}),s0($),{css:f($),ast:$}}function b0($){let X=[0,0,0];if(typeof $==="string"){let Q=A0($);return eX(Q,X),X}if(Array.isArray($)){if($.length===0)return X;if(Array.isArray($[0]))eX($,X);else F$($,X);return X}return $Q($,X),X}function $Q($,X){switch($.type){case"IdSelector":X[0]++;return;case"ClassSelector":case"AttributeSelector":X[1]++;return;case"TypeSelector":if($.name!=="*")X[2]++;return;case"PseudoClassSelector":{let Q=$.name.toLowerCase();if(Q==="is"||Q==="matches"||Q==="-moz-any"||Q==="-webkit-any"||Q==="not"||Q==="has"){if($.children){let Z=[];for(let Y of $.children)if(Y.type==="SelectorList"&&"children"in Y&&Y.children)for(let G of Y.children)Z.push(G);else if(Y.type==="Selector")Z.push(Y);let J=[0,0,0];for(let Y of Z){let G=b0(Y);if(XQ(G,J)>0)J=G}X[0]+=J[0],X[1]+=J[1],X[2]+=J[2]}return}if(Q==="where")return;X[1]++;return}case"PseudoElementSelector":X[2]++;return;case"Selector":case"SelectorList":case"AtrulePrelude":if("children"in $&&$.children)for(let Q of $.children)$Q(Q,X);return;case"NestingSelector":return}}function eX($,X){for(let Q of $)F$(Q,X)}function F$($,X){for(let Q of $)switch(Q.type){case"tag":if(Q.name!=="*")X[2]++;break;case"attribute":if(Q.name==="id"&&Q.action==="equals")X[0]++;else X[1]++;break;case"pseudo":{let Z=Q.name.toLowerCase();if(Z==="is"||Z==="matches"||Z==="not"||Z==="has"||Z==="-moz-any"||Z==="-webkit-any"){if(Array.isArray(Q.data)){let J=[0,0,0];for(let Y of Q.data){let G=[0,0,0];if(F$(Y,G),XQ(G,J)>0)J=G}X[0]+=J[0],X[1]+=J[1],X[2]+=J[2]}break}if(Z==="where")break;X[1]++;break}case"pseudo-element":X[2]++;break}}function XQ($,X){for(let Q=0;Q<3;Q++)if($[Q]!==X[Q])return $[Q]-X[Q];return 0}function QQ($){return $.join(",")}var ZQ={specificity:b0};import{existsSync as YQ,statSync as GQ}from"fs";import{existsSync as vZ,mkdirSync as HG,readdirSync as UG,readFileSync as fZ,writeFileSync as qG}from"fs";import{homedir as T0}from"os";import{dirname as WG,resolve as e}from"path";import r8 from"process";import{existsSync as HQ,statSync as UQ}from"fs";import{existsSync as f$,mkdirSync as gZ,readdirSync as dZ,writeFileSync as mZ}from"fs";import{homedir as k0}from"os";import{dirname as qQ,resolve as o}from"path";import S0 from"process";import{join as uZ,relative as pZ,resolve as zQ}from"path";import h8 from"process";import{existsSync as iQ,mkdirSync as IG,readdirSync as DG,writeFileSync as VG}from"fs";import{homedir as j$}from"os";import{dirname as EG,resolve as i}from"path";import e0 from"process";import{join as cZ,relative as lZ,resolve as _Q}from"path";import v8 from"process";import{existsSync as oQ,mkdirSync as bG,readdirSync as TG,writeFileSync as kG}from"fs";import{dirname as hG,resolve as f8}from"path";import g$ from"process";import{Buffer as w0}from"buffer";import{createCipheriv as nZ,createDecipheriv as iZ,randomBytes as M$}from"crypto";import{closeSync as L$,createReadStream as WQ,createWriteStream as oZ,existsSync as w$,fsyncSync as AQ,openSync as BQ,writeFileSync as rZ}from"fs";import{access as aZ,constants as KQ,mkdir as sZ,readdir as R8,rename as RQ,stat as y0,unlink as F8,writeFile as I$}from"fs/promises";import{join as h0}from"path";import m from"process";import{pipeline as tZ}from"stream/promises";import{createGzip as FQ}from"zlib";import v0 from"process";import R0 from"process";import{Buffer as B0}from"buffer";import{createCipheriv as eZ,createDecipheriv as $7,randomBytes as D$}from"crypto";import{closeSync as V$,createReadStream as jQ,createWriteStream as X7,existsSync as j8,fsyncSync as MQ,openSync as LQ,writeFileSync as Q7}from"fs";import{access as Z7,constants as wQ,mkdir as J7,readdir as M8,rename as IQ,stat as f0,unlink as L8,writeFile as O$}from"fs/promises";import{isAbsolute as Y7,join as g0,resolve as G7}from"path";import I from"process";import{pipeline as H7}from"stream/promises";import{createGzip as DQ}from"zlib";import d0 from"process";import F0 from"process";import w8 from"process";import{existsSync as I8}from"fs";import{resolve as N$}from"path";import{existsSync as U7}from"fs";import{existsSync as q7,readdirSync as z7}from"fs";import{extname as E$,resolve as VQ}from"path";import _7 from"process";import{join as W7,relative as A7,resolve as OQ}from"path";import g8 from"process";import{Buffer as K0}from"buffer";import{createCipheriv as B7,createDecipheriv as K7,randomBytes as S$}from"crypto";import{closeSync as C$,createReadStream as NQ,createWriteStream as R7,existsSync as D8,fsyncSync as EQ,openSync as SQ,writeFileSync as F7}from"fs";import{access as j7,constants as CQ,mkdir as M7,readdir as V8,rename as xQ,stat as m0,unlink as O8,writeFile as x$}from"fs/promises";import{isAbsolute as L7,join as u0,resolve as w7}from"path";import D from"process";import{pipeline as I7}from"stream/promises";import{createGzip as PQ}from"zlib";import p0 from"process";import j0 from"process";import E8 from"process";import{existsSync as S8}from"fs";import{resolve as h$}from"path";import{existsSync as uJ}from"fs";class lQ{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,X){let Q=X?`:${X}`:"";return`${this.options.keyPrefix}${$}${Q}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Q],[,Z])=>Q.timestamp.getTime()-Z.timestamp.getTime()),X=$.length-this.options.maxSize+1;for(let Q=0;Q<X;Q++)this.cache.delete($[Q][0])}set($,X,Q,Z){if(!this.options.enabled)return;let J=this.generateKey($,Q),Y=Z??this.options.ttl,G=this.estimateSize(X);this.cache.set(J,{value:X,timestamp:new Date,ttl:Y,hits:0,size:G}),this.evictIfNeeded()}get($,X){if(!this.options.enabled){this.totalMisses++;return}let Q=this.generateKey($,X),Z=this.cache.get(Q);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Q),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified($,X){try{if(!YQ($))return!0;return GQ($).mtime>X}catch{return!0}}getWithFileCheck($,X){let Q=this.get($,X);if(!Q)return;if(this.isFileModified(X,Q.fileTimestamp)){this.delete($,X);return}return Q.value}setWithFileCheck($,X,Q,Z){try{let J=YQ(Q)?GQ(Q):null,Y=J?J.mtime:new Date;this.set($,{value:X,fileTimestamp:Y},Q,Z)}catch{this.set($,X,Q,Z)}}delete($,X){let Q=this.generateKey($,X);return this.cache.delete(Q)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[X,Q]of this.cache.entries())if(this.isExpired(Q))this.cache.delete(X),$++;return $}getStats(){let $=Array.from(this.cache.values()),X=$.reduce((Z,J)=>Z+J.size,0),Q=$.map((Z)=>Z.timestamp).sort();return{size:X,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:Q[0],newestEntry:Q[Q.length-1]}}export(){let $={};for(let[X,Q]of this.cache.entries())$[X]={value:Q.value,timestamp:Q.timestamp.toISOString(),ttl:Q.ttl,hits:Q.hits,size:Q.size};return $}import($){this.cache.clear();for(let[X,Q]of Object.entries($))if(typeof Q==="object"&&Q!==null){let Z=Q;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class nQ{metrics=[];maxMetrics=1000;async track($,X,Q={}){let Z=performance.now(),J=new Date;try{let Y=await X(),G=performance.now()-Z;return this.recordMetric({operation:$,duration:G,timestamp:J,...Q}),Y}catch(Y){let G=performance.now()-Z;throw this.recordMetric({operation:`${$}:error`,duration:G,timestamp:J,...Q}),Y}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let X=$?this.metrics.filter((J)=>J.operation===$):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Q=X.map((J)=>J.duration),Z=Q.reduce((J,Y)=>J+Y,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Q),maxDuration:Math.max(...Q),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((X)=>X.duration>$)}}var y8=new lQ,a$=new nQ;var D7=Object.defineProperty,V7=($)=>$;function O7($,X){this[$]=V7.bind(null,X)}var N7=($,X)=>{for(var Q in X)D7($,Q,{get:X[Q],enumerable:!0,configurable:!0,set:O7.bind(X,Q)})},E7=($,X)=>()=>($&&(X=$($=0)),X),rQ={};N7(rQ,{withErrorRecovery:()=>tQ,tryLoadConfig:()=>a7,loadConfigWithResult:()=>o7,loadConfig:()=>Z9,isRetryableError:()=>u7,isConfigNotFoundError:()=>m7,isBunfigError:()=>eQ,globalPerformanceMonitor:()=>Q8,globalCache:()=>c0,getEnvOrDefault:()=>p7,generateConfigTypes:()=>s7,defaultGeneratedDir:()=>_9,defaultConfigDir:()=>z9,deepMergeWithArrayStrategy:()=>XX,deepMerge:()=>$9,createLibraryConfig:()=>t7,config:()=>r7,bunfigPlugin:()=>e7,applyEnvVarsToConfig:()=>t0,TypeGenerationError:()=>n$,SchemaValidationError:()=>X8,PluginError:()=>o$,PerformanceMonitor:()=>t$,FileSystemError:()=>l$,ErrorFactory:()=>I0,EnvVarError:()=>l8,EnvProcessor:()=>a8,ConfigValidator:()=>QX,ConfigValidationError:()=>p$,ConfigNotFoundError:()=>c8,ConfigMergeError:()=>c$,ConfigLoader:()=>ZX,ConfigLoadError:()=>$8,ConfigFileLoader:()=>s8,ConfigCache:()=>s$,CacheUtils:()=>Y9,BunfigError:()=>t,BrowserConfigError:()=>i$,ArrayMergeStrategies:()=>U9});class s${cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,X){let Q=X?`:${X}`:"";return`${this.options.keyPrefix}${$}${Q}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Q],[,Z])=>Q.timestamp.getTime()-Z.timestamp.getTime()),X=$.length-this.options.maxSize+1;for(let Q=0;Q<X;Q++)this.cache.delete($[Q][0])}set($,X,Q,Z){if(!this.options.enabled)return;let J=this.generateKey($,Q),Y=Z??this.options.ttl,G=this.estimateSize(X);this.cache.set(J,{value:X,timestamp:new Date,ttl:Y,hits:0,size:G}),this.evictIfNeeded()}get($,X){if(!this.options.enabled){this.totalMisses++;return}let Q=this.generateKey($,X),Z=this.cache.get(Q);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Q),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified($,X){try{if(!HQ($))return!0;return UQ($).mtime>X}catch{return!0}}getWithFileCheck($,X){let Q=this.get($,X);if(!Q)return;if(this.isFileModified(X,Q.fileTimestamp)){this.delete($,X);return}return Q.value}setWithFileCheck($,X,Q,Z){try{let J=HQ(Q)?UQ(Q):null,Y=J?J.mtime:new Date;this.set($,{value:X,fileTimestamp:Y},Q,Z)}catch{this.set($,X,Q,Z)}}delete($,X){let Q=this.generateKey($,X);return this.cache.delete(Q)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[X,Q]of this.cache.entries())if(this.isExpired(Q))this.cache.delete(X),$++;return $}getStats(){let $=Array.from(this.cache.values()),X=$.reduce((Z,J)=>Z+J.size,0),Q=$.map((Z)=>Z.timestamp).sort();return{size:X,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:Q[0],newestEntry:Q[Q.length-1]}}export(){let $={};for(let[X,Q]of this.cache.entries())$[X]={value:Q.value,timestamp:Q.timestamp.toISOString(),ttl:Q.ttl,hits:Q.hits,size:Q.size};return $}import($){this.cache.clear();for(let[X,Q]of Object.entries($))if(typeof Q==="object"&&Q!==null){let Z=Q;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class t${metrics=[];maxMetrics=1000;async track($,X,Q={}){let Z=performance.now(),J=new Date;try{let Y=await X(),G=performance.now()-Z;return this.recordMetric({operation:$,duration:G,timestamp:J,...Q}),Y}catch(Y){let G=performance.now()-Z;throw this.recordMetric({operation:`${$}:error`,duration:G,timestamp:J,...Q}),Y}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let X=$?this.metrics.filter((J)=>J.operation===$):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Q=X.map((J)=>J.duration),Z=Q.reduce((J,Y)=>J+Y,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Q),maxDuration:Math.max(...Q),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((X)=>X.duration>$)}}function S7($,X={}){let Z=Object.keys(X).sort().map((J)=>`${J}:${X[J]}`).join("|");return Z?`${$}:${Z}`:$}function C7($,X){try{return JSON.stringify($)===JSON.stringify(X)}catch{return $===X}}function x7($){return $.getStats().size*2}function e$($,X){if(Array.isArray(X)&&Array.isArray($)&&X.length===2&&$.length===2&&C(X[0])&&"id"in X[0]&&X[0].id===3&&C(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(C(X)&&C($)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return $;if(Array.isArray(X)&&!Array.isArray($))return X;if(Array.isArray(X)&&Array.isArray($)){if(C($)&&"arr"in $&&Array.isArray($.arr)&&C(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&$.length>0&&C(X[0])&&C($[0])){let Z=[...X];for(let J of $)if(C(J)&&"name"in J){if(!Z.find((G)=>C(G)&&("name"in G)&&G.name===J.name))Z.push(J)}else if(C(J)&&"path"in J){if(!Z.find((G)=>C(G)&&("path"in G)&&G.path===J.path))Z.push(J)}else if(!Z.some((Y)=>d8(Y,J)))Z.push(J);return Z}if(X.every((Z)=>typeof Z==="string")&&$.every((Z)=>typeof Z==="string")){let Z=[...X];for(let J of $)if(!Z.includes(J))Z.push(J);return Z}return X}if(!C(X)||!C($))return X;let Q={...$};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let J=X[Z];if(J===null||J===void 0)continue;else if(C(J)&&C(Q[Z]))Q[Z]=e$(Q[Z],J);else if(Array.isArray(J)&&Array.isArray(Q[Z]))if(J.length>0&&Q[Z].length>0&&C(J[0])&&C(Q[Z][0])){let Y=[...J];for(let G of Q[Z])if(C(G)&&"name"in G){if(!Y.find((U)=>C(U)&&("name"in U)&&U.name===G.name))Y.push(G)}else if(C(G)&&"path"in G){if(!Y.find((U)=>C(U)&&("path"in U)&&U.path===G.path))Y.push(G)}else if(!Y.some((H)=>d8(H,G)))Y.push(G);Q[Z]=Y}else if(J.every((Y)=>typeof Y==="string")&&Q[Z].every((Y)=>typeof Y==="string")){let Y=[...J];for(let G of Q[Z])if(!Y.includes(G))Y.push(G);Q[Z]=Y}else Q[Z]=J;else Q[Z]=J}return Q}function d8($,X){if($===X)return!0;if(Array.isArray($)&&Array.isArray(X)){if($.length!==X.length)return!1;for(let Q=0;Q<$.length;Q++)if(!d8($[Q],X[Q]))return!1;return!0}if(C($)&&C(X)){let Q=Object.keys($),Z=Object.keys(X);if(Q.length!==Z.length)return!1;for(let J of Q){if(!Object.prototype.hasOwnProperty.call(X,J))return!1;if(!d8($[J],X[J]))return!1}return!0}return!1}function C($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function P7($,X){if(!oQ($))return null;try{let Q=await import($),Z=Q.default||Q;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return e$(X,Z)}catch{return null}}catch{return null}}async function b7({name:$="",cwd:X,defaultConfig:Q}){let Z=X||g$.cwd(),J=[".ts",".js",".mjs",".cjs",".json"],Y=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let G of Y)for(let H of J){let U=f8(Z,`${G}${H}`),q=await P7(U,Q);if(q!==null)return q}try{let G=f8(Z,"package.json");if(oQ(G)){let U=(await import(G))[$];if(U&&typeof U==="object"&&!Array.isArray(U))try{return e$(Q,U)}catch{}}}catch{}return Q}function T7($,X={}){let Q=v8.cwd();while(Q.includes("storage"))Q=_Q(Q,"..");let Z=_Q(Q,$||"");if(X?.relative)return lZ(v8.cwd(),Z);return Z}async function k7(){try{let $=await b7({name:"clarity",defaultConfig:P8,cwd:v8.cwd(),endpoint:"",headers:{}});return{...P8,...$}}catch{return P8}}function P(){if(R0.env.NODE_ENV==="test"||R0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function y7(){if(R0.env.NODE_ENV==="test"||R0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof R0<"u"){let $=R0.type;if($==="renderer"||$==="worker")return!1;return!!(R0.versions&&(R0.versions.node||R0.versions.bun))}return!1}class aQ{async format($){let X=await y7(),Q=await this.getMetadata(X);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Q})}async getMetadata($){if($){let{hostname:X}=await import("os");return{pid:v0.pid,hostname:X(),environment:v0.env.NODE_ENV||"development",platform:v0.platform,version:v0.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:v0.env.NODE_ENV||v0.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class m8{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($,X={}){this.name=$,this.config={...m$},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new aQ,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??m.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Q={...X},Z=X.timestamp!==void 0;if(Z)delete Q.timestamp;if(this.config={...this.config,...Q,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let J=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=J,this.keys.set(J,Y),this.encryptionKeys.set(J,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...b8,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...b8};return{...b8,...$.fingersCrossed}}normalizeOptions($){let X={format:"json",level:"info",logDirectory:m$.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Q={...X,...Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))};if(!Q.level||!["debug","info","success","warning","error"].includes(Q.level))Q.level=X.level;return Q}async writeToFile($){let Q=(async()=>{let J,Y=0,G=3,H=1000;while(Y<G)try{try{try{await aZ(this.config.logDirectory,KQ.F_OK|KQ.W_OK)}catch(q){if(q instanceof Error&&"code"in q)if(q.code==="ENOENT")await sZ(this.config.logDirectory,{recursive:!0,mode:493});else if(q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw q;else throw q}}catch(q){throw console.error("Debug: [writeToFile] Failed to create log directory:",q),q}let U=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:w0.from($);try{if(!w$(this.currentLogFile))await I$(this.currentLogFile,"",{mode:420});if(J=BQ(this.currentLogFile,"a",420),rZ(J,U,{flag:"a"}),AQ(J),J!==void 0)L$(J),J=void 0;if((await y0(this.currentLogFile)).size===0){if(await I$(this.currentLogFile,U,{flag:"w",mode:420}),(await y0(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(q){let z=q;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(Y<G-1){let _=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${G}:`,_);let A=H*2**Y;await new Promise((W)=>setTimeout(W,A)),Y++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(J!==void 0)try{L$(J)}catch(q){console.error("Debug: [writeToFile] Error closing file descriptor:",q)}}}catch(U){if(Y===G-1){let z=U,_=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",_),U}Y++;let q=H*2**(Y-1);await new Promise((z)=>setTimeout(z,q))}})();this.pendingOperations.push(Q);let Z=this.pendingOperations.length-1;try{await Q}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(Z,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 h0(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 h0(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return h0(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(P())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,X;switch($.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Q=typeof X.interval==="number"?X.interval:60,Z=Math.max(Q,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Q=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Q,this.keys.set(Q,Z),this.encryptionKeys.set(Q,{key:Z,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,H],[,U])=>U.createdAt.getTime()-H.createdAt.getTime()),Y=typeof X.maxKeys==="number"?X.maxKeys:1,G=Math.max(1,Y);if(J.length>G)for(let[H]of J.slice(G))this.encryptionKeys.delete(H),this.keys.delete(H)}generateKeyId(){return M$(16).toString("hex")}generateKey(){return M$(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:X}=this.getCurrentKey(),Q=M$(16),Z=nZ("aes-256-gcm",X,Q),J=w0.concat([Z.update($,"utf8"),Z.final()]),Y=Z.getAuthTag();return{encrypted:w0.concat([Q,J,Y]),iv:Q}}async compressData($){return new Promise((X,Q)=>{let Z=FQ(),J=[];Z.on("data",(Y)=>J.push(Y)),Z.on("end",()=>X(w0.from(w0.concat(J)))),Z.on("error",Q),Z.write($),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...$,...X}}return $}async rotateLog(){if(P())return;let $=await y0(this.currentLogFile).catch(()=>null);if(!$)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&$.size>=X.maxSize){let Q=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let J=await R8(this.config.logDirectory),Y=J.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,q)=>{let z=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(q.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),G=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,H=`${Q}.${G}`;if(await y0(Q).catch(()=>null))try{if(await RQ(Q,H),X.compress)try{let U=`${H}.gz`;await this.compressLogFile(H,U),await F8(H)}catch(U){console.error("Error compressing rotated file:",U)}if(Y.length===0&&!J.some((U)=>U.endsWith(".log.1")))try{let U=`${Q}.1`;await I$(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let J=new Date().toISOString().replace(/[:.]/g,"-"),Y=Q.replace(/\.log$/,`-${J}.log`);if(await y0(Q).catch(()=>null))await RQ(Q,Y)}if(this.currentLogFile=Z,X.maxFiles){let Y=(await R8(this.config.logDirectory)).filter((G)=>G.startsWith(this.name)).sort((G,H)=>H.localeCompare(G));for(let G of Y.slice(X.maxFiles))await F8(h0(this.config.logDirectory,G))}}}async compressLogFile($,X){let Q=WQ($),Z=oZ(X),J=FQ();await tZ(Q,J,Z)}async handleFingersCrossedBuffer($,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Q of this.logBuffer){let Z=await this.formatter.format(Q);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(X),console.log(X);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Q={timestamp:new Date,level:$,message:X,name:this.name};this.logBuffer.push(Q)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[$]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),w$(this.currentLogFile))try{let $=BQ(this.currentLogFile,"r+");AQ($),L$($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!P()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await R8(this.config.logDirectory)).filter((Q)=>(Q.includes("temp")||Q.includes(".tmp"))&&Q.includes(this.name));for(let Q of X)try{await F8(h0(this.config.logDirectory,Q))}catch(Z){console.error(`Failed to delete temp file ${Q}:`,Z)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?S.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:X,icon:Q="",tag:Z="",message:J,level:Y,showTimestamp:G=!0}=$,H=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(G)W.push(X);if(Y==="warning")W.push("WARN");else if(Y==="error")W.push("ERROR");else if(Q)W.push(Q.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push(J),W.join(" ")}let U=m.stdout.columns||120,q="";if(Y==="warning"||Y==="error")q=`${Q} ${J}`;else if(Y==="info"||Y==="success")q=`${Q} ${Z} ${J}`;else q=`${Q} ${Z} ${S.cyan(J)}`;if(!G)return q.trim();let z=H(q).trim().length,_=H(X).length,A=Math.max(1,U-2-z-_);return`${q.trim()}${" ".repeat(A)}${X}`}formatMessage($,X){if(X.length===1&&Array.isArray(X[0]))return $.replace(/\{(\d+)\}/g,(Y,G)=>{let H=Number.parseInt(G,10);return H<X[0].length?String(X[0][H]):Y});let Q=/%([sdijfo%])/g,Z=0,J=$.replace(Q,(Y,G)=>{if(G==="%")return"%";if(Z>=X.length)return Y;let H=X[Z++];switch(G){case"s":return String(H);case"d":case"i":return Number(H).toString();case"j":case"o":return JSON.stringify(H,null,2);default:return Y}});if(Z<X.length)J+=` ${X.slice(Z).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return J}async log($,X,...Q){let Z=new Date,J=this.formatConsoleTimestamp(Z),Y=this.formatFileTimestamp(Z),G,H;if(X instanceof Error)G=X.message,H=X.stack;else G=this.formatMessage(X,Q);if(this.fancy&&!P()){let q=G9[$],z=this.options.showTags!==!1&&this.name?S.gray(this.formatTag(this.name)):"",_;switch($){case"debug":_=this.formatConsoleMessage({timestamp:J,icon:q,tag:z,message:S.gray(G),level:$}),console.error(_);break;case"info":_=this.formatConsoleMessage({timestamp:J,icon:q,tag:z,message:G,level:$}),console.error(_);break;case"success":_=this.formatConsoleMessage({timestamp:J,icon:q,tag:z,message:S.green(G),level:$}),console.error(_);break;case"warning":_=this.formatConsoleMessage({timestamp:J,icon:q,tag:z,message:G,level:$}),console.warn(_);break;case"error":if(_=this.formatConsoleMessage({timestamp:J,icon:q,tag:z,message:G,level:$}),console.error(_),H){let A=H.split(`
|
|
3
|
-
`);for(let W of
|
|
4
|
-
`;if(
|
|
5
|
-
`;
|
|
6
|
-
`,
|
|
7
|
-
`),
|
|
8
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(
|
|
9
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(
|
|
10
|
-
`)}finishProgressBar($,X){if(!this.enabled||!this.fancy||P()||!m.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(X)$.message=X;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(P()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let X=await R8(this.config.logDirectory),Q=[];for(let Z of X){if(!($.name?new RegExp($.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let Y=h0(this.config.logDirectory,Z);if($.before)try{if((await y0(Y)).mtime>=$.before)continue}catch(G){console.error(`Failed to get stats for file ${Y}:`,G);continue}Q.push(Y)}if(Q.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Q.length} log file(s)...`);for(let Z of Q)try{await F8(Z),console.warn(`Deleted log file: ${Z}`)}catch(J){console.error(`Failed to delete log file ${Z}:`,J)}console.warn("Log clearing process finished.")}catch(X){console.error("Error during log clearing process:",X)}}}function x8($,X){if(Array.isArray(X)&&Array.isArray($)&&X.length===2&&$.length===2&&N(X[0])&&"id"in X[0]&&X[0].id===3&&N(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(N(X)&&N($)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return $;if(Array.isArray(X)&&!Array.isArray($))return X;if(Array.isArray(X)&&Array.isArray($)){if(N($)&&"arr"in $&&Array.isArray($.arr)&&N(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&$.length>0&&N(X[0])&&N($[0])){let Z=[...X];for(let J of $)if(N(J)&&"name"in J){if(!Z.find((G)=>N(G)&&("name"in G)&&G.name===J.name))Z.push(J)}else if(N(J)&&"path"in J){if(!Z.find((G)=>N(G)&&("path"in G)&&G.path===J.path))Z.push(J)}else if(!Z.some((Y)=>u8(Y,J)))Z.push(J);return Z}if(X.every((Z)=>typeof Z==="string")&&$.every((Z)=>typeof Z==="string")){let Z=[...X];for(let J of $)if(!Z.includes(J))Z.push(J);return Z}return X}if(!N(X)||!N($))return X;let Q={...$};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let J=X[Z];if(J===null||J===void 0)continue;else if(N(J)&&N(Q[Z]))Q[Z]=x8(Q[Z],J);else if(Array.isArray(J)&&Array.isArray(Q[Z]))if(J.length>0&&Q[Z].length>0&&N(J[0])&&N(Q[Z][0])){let Y=[...J];for(let G of Q[Z])if(N(G)&&"name"in G){if(!Y.find((U)=>N(U)&&("name"in U)&&U.name===G.name))Y.push(G)}else if(N(G)&&"path"in G){if(!Y.find((U)=>N(U)&&("path"in U)&&U.path===G.path))Y.push(G)}else if(!Y.some((H)=>u8(H,G)))Y.push(G);Q[Z]=Y}else if(J.every((Y)=>typeof Y==="string")&&Q[Z].every((Y)=>typeof Y==="string")){let Y=[...J];for(let G of Q[Z])if(!Y.includes(G))Y.push(G);Q[Z]=Y}else Q[Z]=J;else Q[Z]=J}return Q}function $X($,X,Q="replace"){if(X===null||X===void 0)return $;if(Array.isArray(X))return Q==="replace"?X:x8($,X);if(Array.isArray($))return Q==="replace"?X:x8($,X);if(!N(X)||!N($))return X;let Z={...$};for(let J of Object.keys(X)){if(!Object.prototype.hasOwnProperty.call(X,J))continue;let Y=X[J],G=Z[J];if(Y===null||Y===void 0)continue;if(Array.isArray(Y)||Array.isArray(G))if(Q==="replace")Z[J]=Y;else Z[J]=x8(G,Y);else if(N(Y)&&N(G))Z[J]=$X(G,Y,Q);else Z[J]=Y}return Z}function u8($,X){if($===X)return!0;if(Array.isArray($)&&Array.isArray(X)){if($.length!==X.length)return!1;for(let Q=0;Q<$.length;Q++)if(!u8($[Q],X[Q]))return!1;return!0}if(N($)&&N(X)){let Q=Object.keys($),Z=Object.keys(X);if(Q.length!==Z.length)return!1;for(let J of Q){if(!Object.prototype.hasOwnProperty.call(X,J))return!1;if(!u8($[J],X[J]))return!1}return!0}return!1}function N($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function N8($,X,Q="replace"){if(!iQ($))return null;try{let Z=await import($),J=Z.default||Z;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return $X(X,J,Q)}catch{return null}}catch{return null}}function h7($,X,Q=!1){if(!$)return X;let Z=$.toUpperCase().replace(/-/g,"_"),J={...X};function Y(G,H=[]){let U={...G};for(let[q,z]of Object.entries(G)){let _=[...H,q],A=(B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase(),W=`${Z}_${_.map(A).join("_")}`,K=`${Z}_${_.map((B)=>B.toUpperCase()).join("_")}`;if(Q)p.info(`Checking environment variable ${W} for config ${$}.${_.join(".")}`);if(typeof z==="object"&&z!==null&&!Array.isArray(z))U[q]=Y(z,_);else{let B=e0.env[W]||e0.env[K];if(B!==void 0){if(Q)p.info(`Using environment variable ${B?W:K} for config ${$}.${_.join(".")}`);if(typeof z==="number")U[q]=Number(B);else if(typeof z==="boolean")U[q]=B.toLowerCase()==="true";else if(Array.isArray(z))try{let M=JSON.parse(B);if(Array.isArray(M))U[q]=M;else U[q]=B.split(",").map((x)=>x.trim())}catch{U[q]=B.split(",").map((M)=>M.trim())}else U[q]=B}}}return U}return Y(J)}async function v7({name:$="",alias:X,cwd:Q,configDir:Z,defaultConfig:J,verbose:Y=!1,checkEnv:G=!0,arrayStrategy:H="replace"}){let U=G&&typeof J==="object"&&J!==null&&!Array.isArray(J)?h7($,J,Y):J,q=Q||e0.cwd(),z=[".ts",".js",".mjs",".cjs",".json"];if(Y)p.info(`Loading configuration for "${$}"${X?` (alias: "${X}")`:""} from ${q}`);let _=[$,`.${$}`].filter(Boolean),A=[`${$}.config`,`.${$}.config`].filter(Boolean),W=X?[X,`.${X}`]:[],K=X?[`${X}.config`,`.${X}.config`]:[],B=Array.from(new Set([q,i(q,"config"),i(q,".config"),Z?i(q,Z):void 0].filter(Boolean)));for(let M of B){if(Y)p.info(`Searching for configuration in: ${M}`);let T=[i(q,"config"),i(q,".config")].concat(Z?[i(q,Z)]:[]).includes(M)?[..._,...A,...W,...K]:[...A,..._,...K,...W];for(let r of T)for(let a of z){let E=i(M,`${r}${a}`),c=await N8(E,U,H);if(c!==null){if(Y)p.success(`Configuration loaded from: ${E}`);return c}}}if($){let M=i(j$(),".config",$),x=["config",`${$}.config`];if(X)x.push(`${X}.config`);if(Y)p.info(`Checking user config directory: ${M}`);for(let T of x)for(let r of z){let a=i(M,`${T}${r}`),E=await N8(a,U,H);if(E!==null){if(Y)p.success(`Configuration loaded from user config directory: ${a}`);return E}}}if($){let M=i(j$(),".config"),x=[`.${$}.config`];if(X)x.push(`.${X}.config`);if(Y)p.info(`Checking user config directory for dotfile configs: ${M}`);for(let T of x)for(let r of z){let a=i(M,`${T}${r}`),E=await N8(a,U,H);if(E!==null){if(Y)p.success(`Configuration loaded from user config directory dotfile: ${a}`);return E}}}if($){let M=j$(),x=[`.${$}.config`,`.${$}`];if(X)x.push(`.${X}.config`),x.push(`.${X}`);if(Y)p.info(`Checking user home directory for dotfile configs: ${M}`);for(let T of x)for(let r of z){let a=i(M,`${T}${r}`),E=await N8(a,U,H);if(E!==null){if(Y)p.success(`Configuration loaded from user home directory: ${a}`);return E}}}try{let M=i(q,"package.json");if(iQ(M)){let x=await import(M),T=x[$];if(!T&&X){if(T=x[X],T&&Y)p.success(`Using alias "${X}" configuration from package.json`)}if(T&&typeof T==="object"&&!Array.isArray(T))try{if(Y)p.success(`Configuration loaded from package.json: ${T===x[$]?$:X}`);return $X(U,T,H)}catch(r){if(Y)p.warn("Failed to merge package.json config:",r)}}}catch(M){if(Y)p.warn("Failed to load package.json:",M)}if(Y)p.info(`No configuration found for "${$}"${X?` or alias "${X}"`:""}, using default configuration with environment variables`);return U}function f7($,X={}){let Q=h8.cwd();while(Q.includes("storage"))Q=zQ(Q,"..");let Z=zQ(Q,$||"");if(X?.relative)return pZ(h8.cwd(),Z);return Z}async function g7(){try{let $=await v7({name:"clarity",alias:"logging",defaultConfig:T8,cwd:h8.cwd()});return{...T8,...$||{}}}catch{return T8}}function k(){if(F0.env.NODE_ENV==="test"||F0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function d7(){if(F0.env.NODE_ENV==="test"||F0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof F0<"u"){let $=F0.type;if($==="renderer"||$==="worker")return!1;return!!(F0.versions&&(F0.versions.node||F0.versions.bun))}return!1}class sQ{async format($){let X=await d7(),Q=await this.getMetadata(X);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Q})}async getMetadata($){if($){let{hostname:X}=await import("os");return{pid:d0.pid,hostname:X(),environment:d0.env.NODE_ENV||"development",platform:d0.platform,version:d0.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:d0.env.NODE_ENV||d0.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class p8{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($,X={}){this.name=$,this.config={...u$},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new sQ,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??I.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Q={...X},Z=X.timestamp!==void 0;if(Z)delete Q.timestamp;if(this.config={...this.config,...Q,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let J=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=J,this.keys.set(J,Y),this.encryptionKeys.set(J,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let X={debug:0,info:1,success:2,warning:3,error:4},Q=this.fingersCrossedConfig.activationLevel??"error";return X[$]>=X[Q]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...k8,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...k8};return{...k8,...$.fingersCrossed}}normalizeOptions($){let X={format:"json",level:"info",logDirectory:u$.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Q={...X,...Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))};if(!Q.level||!["debug","info","success","warning","error"].includes(Q.level))Q.level=X.level;return Q}shouldWriteToFile(){return!k()&&this.config.writeToFile===!0}async writeToFile($){let Q=(async()=>{let J,Y=0,G=3,H=1000;while(Y<G)try{try{try{await Z7(this.config.logDirectory,wQ.F_OK|wQ.W_OK)}catch(q){if(q instanceof Error&&"code"in q)if(q.code==="ENOENT")await J7(this.config.logDirectory,{recursive:!0,mode:493});else if(q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw q;else throw q}}catch(q){throw console.error("Debug: [writeToFile] Failed to create log directory:",q),q}let U=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:B0.from($);try{if(!j8(this.currentLogFile))await O$(this.currentLogFile,"",{mode:420});if(J=LQ(this.currentLogFile,"a",420),Q7(J,U,{flag:"a"}),MQ(J),J!==void 0)V$(J),J=void 0;if((await f0(this.currentLogFile)).size===0){if(await O$(this.currentLogFile,U,{flag:"w",mode:420}),(await f0(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(q){let z=q;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(Y<G-1){let _=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${G}:`,_);let A=H*2**Y;await new Promise((W)=>setTimeout(W,A)),Y++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(J!==void 0)try{V$(J)}catch(q){console.error("Debug: [writeToFile] Error closing file descriptor:",q)}}}catch(U){if(Y===G-1){let z=U,_=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",_),U}Y++;let q=H*2**(Y-1);await new Promise((z)=>setTimeout(z,q))}})();this.pendingOperations.push(Q);let Z=this.pendingOperations.length-1;try{await Q}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(Z,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 g0(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 g0(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return g0(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(k())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,X;switch($.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Q=typeof X.interval==="number"?X.interval:60,Z=Math.max(Q,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Q=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Q,this.keys.set(Q,Z),this.encryptionKeys.set(Q,{key:Z,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,H],[,U])=>U.createdAt.getTime()-H.createdAt.getTime()),Y=typeof X.maxKeys==="number"?X.maxKeys:1,G=Math.max(1,Y);if(J.length>G)for(let[H]of J.slice(G))this.encryptionKeys.delete(H),this.keys.delete(H)}generateKeyId(){return D$(16).toString("hex")}generateKey(){return D$(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:X}=this.getCurrentKey(),Q=D$(16),Z=eZ("aes-256-gcm",X,Q),J=B0.isBuffer($)?$:B0.from($,"utf8"),Y=Z.update(J),G=Z.final(),H=Y.length+G.length,U=Z.getAuthTag(),q=B0.allocUnsafe(16+H+16);return Q.copy(q,0),Y.copy(q,16),G.copy(q,16+Y.length),U.copy(q,16+H),{encrypted:q,iv:Q}}async compressData($){return new Promise((X,Q)=>{let Z=DQ(),J=[];Z.on("data",(Y)=>J.push(Y)),Z.on("end",()=>X(B0.from(B0.concat(J)))),Z.on("error",Q),Z.write($),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...$,...X}}return $}async rotateLog(){if(k())return;if(!this.shouldWriteToFile())return;let $=await f0(this.currentLogFile).catch(()=>null);if(!$)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&$.size>=X.maxSize){let Q=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let J=await M8(this.config.logDirectory),Y=J.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,q)=>{let z=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(q.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),G=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,H=`${Q}.${G}`;if(await f0(Q).catch(()=>null))try{if(await IQ(Q,H),X.compress)try{let U=`${H}.gz`;await this.compressLogFile(H,U),await L8(H)}catch(U){console.error("Error compressing rotated file:",U)}if(Y.length===0&&!J.some((U)=>U.endsWith(".log.1")))try{let U=`${Q}.1`;await O$(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let J=new Date().toISOString().replace(/[:.]/g,"-"),Y=Q.replace(/\.log$/,`-${J}.log`);if(await f0(Q).catch(()=>null))await IQ(Q,Y)}if(this.currentLogFile=Z,X.maxFiles){let Y=(await M8(this.config.logDirectory)).filter((G)=>G.startsWith(this.name)).sort((G,H)=>H.localeCompare(G));for(let G of Y.slice(X.maxFiles))await L8(g0(this.config.logDirectory,G))}}}async compressLogFile($,X){let Q=jQ($),Z=X7(X),J=DQ();await H7(Q,J,Z)}async handleFingersCrossedBuffer($,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Q of this.logBuffer){let Z=await this.formatter.format(Q);if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(X);console.log(X)}}shouldLog($){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[$]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),j8(this.currentLogFile))try{let $=LQ(this.currentLogFile,"r+");MQ($),V$($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!k()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await M8(this.config.logDirectory)).filter((Q)=>(Q.includes("temp")||Q.includes(".tmp"))&&Q.includes(this.name));for(let Q of X)try{await L8(g0(this.config.logDirectory,Q))}catch(Z){console.error(`Failed to delete temp file ${Q}:`,Z)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?V.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||k())return!1;let $=typeof I.env.NO_COLOR<"u",X=I.env.FORCE_COLOR==="0";if($||X)return!1;return!!(typeof I.stderr<"u"&&I.stderr.isTTY||typeof I.stdout<"u"&&I.stdout.isTTY)}formatConsoleMessage($){let{timestamp:X,icon:Q="",tag:Z="",message:J,level:Y,showTimestamp:G=!0}=$,H=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(G)W.push(X);if(Y==="warning")W.push("WARN");else if(Y==="error")W.push("ERROR");else if(Q)W.push(Q.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push(J),W.join(" ")}let U=I.stdout.columns||120,q="";if(Y==="warning"||Y==="error")q=`${Q} ${J}`;else if(Y==="info"||Y==="success")q=`${Q} ${Z} ${J}`;else q=`${Q} ${Z} ${V.cyan(J)}`;if(!G)return q.trim();let z=H(q).trim().length,_=H(X).length,A=Math.max(1,U-2-z-_);return`${q.trim()}${" ".repeat(A)}${X}`}formatMessage($,X){if(X.length===1&&Array.isArray(X[0]))return $.replace(/\{(\d+)\}/g,(Y,G)=>{let H=Number.parseInt(G,10);return H<X[0].length?String(X[0][H]):Y});let Q=/%([sdijfo%])/g,Z=0,J=$.replace(Q,(Y,G)=>{if(G==="%")return"%";if(Z>=X.length)return Y;let H=X[Z++];switch(G){case"s":return String(H);case"d":case"i":return Number(H).toString();case"j":case"o":return JSON.stringify(H,null,2);default:return Y}});if(Z<X.length)J+=` ${X.slice(Z).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return J}formatMarkdown($){if(!$)return $;let X=$;return X=X.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Q,Z,J)=>{let Y=V.underline(V.blue(Z)),G=this.toAbsoluteFilePath(J);if(G&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let H=`file://${encodeURI(G)}`,U="\x1B]8;;",q="\x1B\\";return`\x1B]8;;${H}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${J}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),X=X.replace(/`([^`]+)`/g,(Q,Z)=>V.bgGray(Z)),X=X.replace(/\*\*([^*]+)\*\*/g,(Q,Z)=>V.bold(Z)),X=X.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Q,Z)=>V.italic(Z)),X=X.replace(/(?<!_)_([^_]+)_(?!_)/g,(Q,Z)=>V.italic(Z)),X=X.replace(/~([^~]+)~/g,(Q,Z)=>V.strikethrough(Z)),X}supportsHyperlinks(){if(k())return!1;let $=I.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let X=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(X)&&X>=5000)return!0;return!1}toAbsoluteFilePath($){try{let X=$;if(X.startsWith("file://"))X=X.replace(/^file:\/\//,"");if(X.startsWith("~")){let Q=I.env.HOME||"";if(Q)X=X.replace(/^~(?=$|\/)/,Q)}if(Y7(X)||X.startsWith("./")||X.startsWith("../"))X=G7(X);else return null;return j8(X)?X:null}catch{return null}}buildOutputTexts($){let X=this.shouldStyleConsole()?this.formatMarkdown($):$,Q=$.replace(this.ANSI_PATTERN,"");return{consoleText:X,fileText:Q}}async log($,X,...Q){let Z=new Date,J=this.formatConsoleTimestamp(Z),Y=this.formatFileTimestamp(Z),G,H;if(X instanceof Error)G=X.message,H=X.stack;else G=this.formatMessage(X,Q);let{consoleText:U,fileText:q}=this.buildOutputTexts(G);if(this.shouldStyleConsole()){let _=this.options.showIcons===!1?"":H9[$],A=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",W;switch($){case"debug":W=this.formatConsoleMessage({timestamp:J,icon:_,tag:A,message:V.gray(U),level:$}),console.error(W);break;case"info":W=this.formatConsoleMessage({timestamp:J,icon:_,tag:A,message:U,level:$}),console.warn(W);break;case"success":W=this.formatConsoleMessage({timestamp:J,icon:_,tag:A,message:V.green(U),level:$}),console.error(W);break;case"warning":W=this.formatConsoleMessage({timestamp:J,icon:_,tag:A,message:U,level:$}),console.warn(W);break;case"error":if(W=this.formatConsoleMessage({timestamp:J,icon:_,tag:A,message:U,level:$}),console.error(W),H){let K=H.split(`
|
|
11
|
-
`);for(let B of
|
|
12
|
-
`;if(
|
|
13
|
-
`;if(
|
|
14
|
-
`);if(this[
|
|
15
|
-
`,
|
|
16
|
-
`),
|
|
17
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
18
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
19
|
-
`)}finishProgressBar(
|
|
2
|
+
import{d as y8,e as v8,f as d8,g as h8}from"./chunk-edwg811g.js";import{k as f8,l as p8,m as m8,o as u8,p as g8}from"./chunk-thy3p95k.js";import{q as V8,s as E8,t as T8,x as O8,y as N8,z as C8}from"./chunk-9ep6bwwb.js";import{A as x8,B as k8,C as P8,E as b8}from"./chunk-2wsah70r.js";import{G as l}from"./chunk-1kmkypmr.js";import{existsSync as iX,statSync as sX}from"fs";import{existsSync as LZ,mkdirSync as n8,readdirSync as i8,readFileSync as KZ,writeFileSync as s8}from"fs";import{homedir as YQ}from"os";import{dirname as r8,resolve as d}from"path";import eQ from"process";import{existsSync as oX,statSync as tX}from"fs";import{existsSync as DX,mkdirSync as jZ,readdirSync as IZ,writeFileSync as FZ}from"fs";import{homedir as ZQ}from"os";import{dirname as rX,resolve as y}from"path";import XQ from"process";import{join as MZ,relative as DZ,resolve as aX}from"path";import pQ from"process";import{existsSync as yY,mkdirSync as J9,readdirSync as _9,writeFileSync as G9}from"fs";import{homedir as ZX}from"os";import{dirname as W9,resolve as b}from"path";import wQ from"process";import{join as SZ,relative as VZ,resolve as eX}from"path";import mQ from"process";import{existsSync as vY,mkdirSync as L9,readdirSync as K9,writeFileSync as j9}from"fs";import{dirname as F9,resolve as uQ}from"path";import SX from"process";import{Buffer as e}from"buffer";import{createCipheriv as EZ,createDecipheriv as TZ,randomBytes as $X}from"crypto";import{closeSync as HX,createReadStream as QY,createWriteStream as OZ,existsSync as UX,fsyncSync as XY,openSync as YY,writeFileSync as NZ}from"fs";import{access as CZ,constants as ZY,mkdir as xZ,readdir as IQ,rename as $Y,stat as $Q,unlink as FQ,writeFile as JX}from"fs/promises";import{join as HQ}from"path";import N from"process";import{pipeline as kZ}from"stream/promises";import{createGzip as HY}from"zlib";import UQ from"process";import o from"process";import{Buffer as i}from"buffer";import{createCipheriv as PZ,createDecipheriv as bZ,randomBytes as _X}from"crypto";import{closeSync as GX,createReadStream as UY,createWriteStream as yZ,existsSync as MQ,fsyncSync as JY,openSync as _Y,writeFileSync as vZ}from"fs";import{access as dZ,constants as GY,mkdir as hZ,readdir as DQ,rename as qY,stat as JQ,unlink as SQ,writeFile as qX}from"fs/promises";import{isAbsolute as fZ,join as _Q,resolve as pZ}from"path";import R from"process";import{pipeline as mZ}from"stream/promises";import{createGzip as AY}from"zlib";import GQ from"process";import t from"process";import VQ from"process";import{existsSync as EQ}from"fs";import{resolve as AX}from"path";import{existsSync as uZ}from"fs";import{existsSync as gZ,readdirSync as cZ}from"fs";import{extname as WX,resolve as WY}from"path";import lZ from"process";import{join as nZ,relative as iZ,resolve as zY}from"path";import gQ from"process";import{Buffer as s}from"buffer";import{createCipheriv as sZ,createDecipheriv as oZ,randomBytes as zX}from"crypto";import{closeSync as BX,createReadStream as BY,createWriteStream as tZ,existsSync as TQ,fsyncSync as RY,openSync as wY,writeFileSync as rZ}from"fs";import{access as aZ,constants as LY,mkdir as eZ,readdir as OQ,rename as KY,stat as qQ,unlink as NQ,writeFile as RX}from"fs/promises";import{isAbsolute as Q0,join as AQ,resolve as X0}from"path";import w from"process";import{pipeline as Y0}from"stream/promises";import{createGzip as jY}from"zlib";import WQ from"process";import r from"process";import xQ from"process";import{existsSync as kQ}from"fs";import{resolve as FX}from"path";import{existsSync as M8}from"fs";class PY{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!iX(Q))return!0;return sX(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=iX(Y)?sX(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,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:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class bY{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}var fQ=new PY,yX=new bY;var Z0=Object.defineProperty,$0=(Q)=>Q;function H0(Q,X){this[Q]=$0.bind(null,X)}var U0=(Q,X)=>{for(var Y in X)Z0(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:H0.bind(X,Y)})},J0=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X),dY={};U0(dY,{withErrorRecovery:()=>pY,tryLoadConfig:()=>C0,loadConfigWithResult:()=>O0,loadConfig:()=>lY,isRetryableError:()=>M0,isConfigNotFoundError:()=>F0,isBunfigError:()=>mY,globalPerformanceMonitor:()=>jQ,globalCache:()=>zQ,getEnvOrDefault:()=>D0,generateConfigTypes:()=>x0,defaultGeneratedDir:()=>eY,defaultConfigDir:()=>aY,deepMergeWithArrayStrategy:()=>pX,deepMerge:()=>uY,createLibraryConfig:()=>k0,config:()=>N0,bunfigPlugin:()=>P0,applyEnvVarsToConfig:()=>RQ,TypeGenerationError:()=>xX,SchemaValidationError:()=>KQ,PluginError:()=>PX,PerformanceMonitor:()=>dX,FileSystemError:()=>CX,ErrorFactory:()=>QQ,EnvVarError:()=>oQ,EnvProcessor:()=>QX,ConfigValidator:()=>mX,ConfigValidationError:()=>OX,ConfigNotFoundError:()=>sQ,ConfigMergeError:()=>NX,ConfigLoader:()=>uX,ConfigLoadError:()=>LQ,ConfigFileLoader:()=>XX,ConfigCache:()=>vX,CacheUtils:()=>iY,BunfigError:()=>v,BrowserConfigError:()=>kX,ArrayMergeStrategies:()=>tY});class vX{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!oX(Q))return!0;return tX(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=oX(Y)?tX(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,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:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class dX{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}function _0(Q,X={}){let Z=Object.keys(X).sort().map(($)=>`${$}:${X[$]}`).join("|");return Z?`${Q}:${Z}`:Q}function G0(Q,X){try{return JSON.stringify(Q)===JSON.stringify(X)}catch{return Q===X}}function q0(Q){return Q.getStats().size*2}function hX(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&D(X[0])&&"id"in X[0]&&X[0].id===3&&D(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(D(X)&&D(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(D(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&D(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&D(X[0])&&D(Q[0])){let Z=[...X];for(let $ of Q)if(D($)&&"name"in $){if(!Z.find((U)=>D(U)&&("name"in U)&&U.name===$.name))Z.push($)}else if(D($)&&"path"in $){if(!Z.find((U)=>D(U)&&("path"in U)&&U.path===$.path))Z.push($)}else if(!Z.some((H)=>cQ(H,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!D(X)||!D(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(D($)&&D(Y[Z]))Y[Z]=hX(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&D($[0])&&D(Y[Z][0])){let H=[...$];for(let U of Y[Z])if(D(U)&&"name"in U){if(!H.find((J)=>D(J)&&("name"in J)&&J.name===U.name))H.push(U)}else if(D(U)&&"path"in U){if(!H.find((J)=>D(J)&&("path"in J)&&J.path===U.path))H.push(U)}else if(!H.some((_)=>cQ(_,U)))H.push(U);Y[Z]=H}else if($.every((H)=>typeof H==="string")&&Y[Z].every((H)=>typeof H==="string")){let H=[...$];for(let U of Y[Z])if(!H.includes(U))H.push(U);Y[Z]=H}else Y[Z]=$;else Y[Z]=$}return Y}function cQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!cQ(Q[Y],X[Y]))return!1;return!0}if(D(Q)&&D(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!cQ(Q[$],X[$]))return!1}return!0}return!1}function D(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function A0(Q,X){if(!vY(Q))return null;try{let Y=await import(Q),Z=Y.default||Y;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return hX(X,Z)}catch{return null}}catch{return null}}async function W0({name:Q="",cwd:X,defaultConfig:Y}){let Z=X||SX.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],H=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let U of H)for(let _ of $){let J=uQ(Z,`${U}${_}`),G=await A0(J,Y);if(G!==null)return G}try{let U=uQ(Z,"package.json");if(vY(U)){let J=(await import(U))[Q];if(J&&typeof J==="object"&&!Array.isArray(J))try{return hX(Y,J)}catch{}}}catch{}return Y}function z0(Q,X={}){let Y=mQ.cwd();while(Y.includes("storage"))Y=eX(Y,"..");let Z=eX(Y,Q||"");if(X?.relative)return VZ(mQ.cwd(),Z);return Z}async function B0(){try{let Q=await W0({name:"clarity",defaultConfig:yQ,cwd:mQ.cwd(),endpoint:"",headers:{}});return{...yQ,...Q}}catch{return yQ}}function S(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function R0(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof o<"u"){let Q=o.type;if(Q==="renderer"||Q==="worker")return!1;return!!(o.versions&&(o.versions.node||o.versions.bun))}return!1}class hY{async format(Q){let X=await R0(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:UQ.pid,hostname:X(),environment:UQ.env.NODE_ENV||"development",platform:UQ.platform,version:UQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:UQ.env.NODE_ENV||UQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class lQ{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(Q,X={}){this.name=Q,this.config={...EX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new hY,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??N.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),H=this.generateKey();this.currentKeyId=$,this.keys.set($,H),this.encryptionKeys.set($,{key:H,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...vQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...vQ};return{...vQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:EX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}async writeToFile(Q){let Y=(async()=>{let $,H=0,U=3,_=1000;while(H<U)try{try{try{await CZ(this.config.logDirectory,ZY.F_OK|ZY.W_OK)}catch(G){if(G instanceof Error&&"code"in G)if(G.code==="ENOENT")await xZ(this.config.logDirectory,{recursive:!0,mode:493});else if(G.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw G;else throw G}}catch(G){throw console.error("Debug: [writeToFile] Failed to create log directory:",G),G}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:e.from(Q);try{if(!UX(this.currentLogFile))await JX(this.currentLogFile,"",{mode:420});if($=YY(this.currentLogFile,"a",420),NZ($,J,{flag:"a"}),XY($),$!==void 0)HX($),$=void 0;if((await $Q(this.currentLogFile)).size===0){if(await JX(this.currentLogFile,J,{flag:"w",mode:420}),(await $Q(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(G){let q=G;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if(H<U-1){let A=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${U}:`,A);let z=_*2**H;await new Promise((W)=>setTimeout(W,z)),H++;continue}}if(q?.code&&["ENOSPC","EDQUOT"].includes(q.code))throw Error(`Disk quota exceeded or no space left on device: ${q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",q),q}finally{if($!==void 0)try{HX($)}catch(G){console.error("Debug: [writeToFile] Error closing file descriptor:",G)}}}catch(J){if(H===U-1){let q=J,A=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}H++;let G=_*2**(H-1);await new Promise((q)=>setTimeout(q,G))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,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 HQ(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 HQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return HQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(S())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,_],[,J])=>J.createdAt.getTime()-_.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,U=Math.max(1,H);if($.length>U)for(let[_]of $.slice(U))this.encryptionKeys.delete(_),this.keys.delete(_)}generateKeyId(){return $X(16).toString("hex")}generateKey(){return $X(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=$X(16),Z=EZ("aes-256-gcm",X,Y),$=e.concat([Z.update(Q,"utf8"),Z.final()]),H=Z.getAuthTag();return{encrypted:e.concat([Y,$,H]),iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=HY(),$=[];Z.on("data",(H)=>$.push(H)),Z.on("end",()=>X(e.from(e.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(S())return;let Q=await $Q(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await IQ(this.config.logDirectory),H=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,G)=>{let q=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(G.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),U=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,_=`${Y}.${U}`;if(await $Q(Y).catch(()=>null))try{if(await $Y(Y,_),X.compress)try{let J=`${_}.gz`;await this.compressLogFile(_,J),await FQ(_)}catch(J){console.error("Error compressing rotated file:",J)}if(H.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await JX(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await $Q(Y).catch(()=>null))await $Y(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await IQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,_)=>_.localeCompare(U));for(let U of H.slice(X.maxFiles))await FQ(HQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=QY(Q),Z=OZ(X),$=HY();await kZ(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(X),console.log(X);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:Q,message:X,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),UX(this.currentLogFile))try{let Q=YY(this.currentLogFile,"r+");XY(Q),HX(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!S()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await IQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await FQ(HQ(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?M.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:H,showTimestamp:U=!0}=Q,_=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(U)W.push(X);if(H==="warning")W.push("WARN");else if(H==="error")W.push("ERROR");else if(Y)W.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let J=N.stdout.columns||120,G="";if(H==="warning"||H==="error")G=`${Y} ${$}`;else if(H==="info"||H==="success")G=`${Y} ${Z} ${$}`;else G=`${Y} ${Z} ${M.cyan($)}`;if(!U)return G.trim();let q=_(G).trim().length,A=_(X).length,z=Math.max(1,J-2-q-A);return`${G.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,U)=>{let _=Number.parseInt(U,10);return _<X[0].length?String(X[0][_]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,U)=>{if(U==="%")return"%";if(Z>=X.length)return H;let _=X[Z++];switch(U){case"s":return String(_);case"d":case"i":return Number(_).toString();case"j":case"o":return JSON.stringify(_,null,2);default:return H}});if(Z<X.length)$+=` ${X.slice(Z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return $}async log(Q,X,...Y){let Z=new Date,$=this.formatConsoleTimestamp(Z),H=this.formatFileTimestamp(Z),U,_;if(X instanceof Error)U=X.message,_=X.stack;else U=this.formatMessage(X,Y);if(this.fancy&&!S()){let G=sY[Q],q=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:G,tag:q,message:M.gray(U),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:G,tag:q,message:U,level:Q}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:G,tag:q,message:M.green(U),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:G,tag:q,message:U,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:G,tag:q,message:U,level:Q}),console.error(A),_){let z=_.split(`
|
|
3
|
+
`);for(let W of z)if(W.trim()&&!W.includes(U))console.error(this.formatConsoleMessage({timestamp:$,message:M.gray(` ${W}`),level:Q,showTimestamp:!1}))}break}}else if(!S()){if(console.error(`${H} ${this.environment}.${Q.toUpperCase()}: ${U}`),_)console.error(_)}if(!this.shouldLog(Q))return;let J=`${H} ${this.environment}.${Q.toUpperCase()}: ${U}
|
|
4
|
+
`;if(_)J+=`${_}
|
|
5
|
+
`;J=J.replace(this.ANSI_PATTERN,""),await this.writeToFile(J)}time(Q){let X=performance.now();if(this.fancy&&!S()){let Y=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:M.blue("\u25D0"),tag:Y,message:`${M.cyan(Q)}...`}))}return async(Y)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-X),H=`${Q} completed in ${$}ms`,U=new Date,_=this.formatConsoleTimestamp(U),G=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${H}`;if(Y)G+=` ${JSON.stringify(Y)}`;if(G+=`
|
|
6
|
+
`,G=G.replace(this.ANSI_PATTERN,""),this.fancy&&!S()){let q=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:_,icon:M.green("\u2713"),tag:q,message:`${H}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!S())console.error(G.trim());await this.writeToFile(G)}}async debug(Q,...X){await this.log("debug",Q,...X)}async info(Q,...X){await this.log("info",Q,...X)}async success(Q,...X){await this.log("success",Q,...X)}async warn(Q,...X){await this.log("warning",Q,...X)}async error(Q,...X){await this.log("error",Q,...X)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:X}=Q;return!!X}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let X=`${this.name}:${Q}`,Y=new lQ(X,{...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(Y),Y}createReadStream(){if(S())throw Error("createReadStream is not supported in browser environments");if(!UX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return QY(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let X=this.config.rotation;if(!X.encrypt||typeof X.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let Z=e.isBuffer(Q)?Q:e.from(Q,"base64"),$=Z.slice(0,16),H=Z.slice(-16),U=Z.slice(16,-16),_=TZ("aes-256-gcm",Y,$);return _.setAuthTag(H),e.concat([_.update(U),_.final()]).toString("utf8")}catch(Z){throw Error(`Decryption failed: ${Z instanceof Error?Z.message:String(Z)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return S()}isServerMode(){return!S()}setTestEncryptionKey(Q,X){this.currentKeyId=Q,this.keys.set(Q,X)}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(Q){if(!this.enabled)return;let X=new Date,Y=this.formatConsoleTimestamp(X),Z=this.formatFileTimestamp(X);if(this.fancy&&!S()){let H=Q.split(`
|
|
7
|
+
`),U=Math.max(...H.map((q)=>q.length))+2,_=`\u250C${"\u2500".repeat(U)}\u2510`,J=`\u2514${"\u2500".repeat(U)}\u2518`,G=H.map((q)=>{let A=" ".repeat(U-q.length-2);return`\u2502 ${q}${A} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:M.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:M.cyan(_)})),G.forEach((q)=>console.error(this.formatConsoleMessage({timestamp:Y,message:M.cyan(q),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:M.cyan(J),showTimestamp:!1}))}else if(!S())console.error(`${Z} ${this.environment}.INFO: [BOX] ${Q}`);let $=`${Z} ${this.environment}.INFO: [BOX] ${Q}
|
|
8
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile($)}async prompt(Q){if(S())return Promise.resolve(!0);return new Promise((X)=>{console.error(`${M.cyan("?")} ${Q} (y/n) `);let Y=(Z)=>{let $=Z.toString().trim().toLowerCase();N.stdin.removeListener("data",Y);try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!1)}catch{}N.stdin.pause(),console.error(""),X($==="y"||$==="yes")};try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!0)}catch{}N.stdin.resume(),N.stdin.once("data",Y)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...X){if(!this.enabled)return;let Y=Q;if(X&&X.length>0){let U=/%([sdijfo%])/g,_=0;if(Y=Q.replace(U,(J,G)=>{if(G==="%")return"%";if(_>=X.length)return J;let q=X[_++];switch(G){case"s":return String(q);case"d":case"i":return Number(q).toString();case"j":case"o":return JSON.stringify(q,null,2);default:return J}}),_<X.length)Y+=` ${X.slice(_).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`}if(this.fancy&&!S()){let U=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",_=M.blue("\u25D0");console.error(`${_} ${U} ${M.cyan(Y)}`)}let H=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
9
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(H)}progress(Q,X=""){if(!this.enabled||!this.fancy||S()||Q<=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 Y=20;return this.activeProgressBar={total:Q,current:0,message:X,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,_)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||S())return;if(this.activeProgressBar.current=Math.max(0,Math.min(Q,U)),_!==void 0)this.activeProgressBar.message=_;let J=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,J)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||S())return;if(this.activeProgressBar.current=this.activeProgressBar.total,U!==void 0)this.activeProgressBar.message=U;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(U,_="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||S())return;N.stdout.write(`${"\r".padEnd(N.stdout.columns||80)}\r`),this.log(_,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(Q,X=!1){if(!this.enabled||!this.fancy||S()||!N.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*Y/100),$=Q.barLength-Z,H=M.green("\u2501".repeat(Z)),U=M.gray("\u2501".repeat($)),_=`[${H}${U}]`,J=`${Y}%`.padStart(4),G=Q.message?` ${Q.message}`:"",q=X||Y===100?M.green("\u2713"):M.blue("\u25B6"),A=this.options.showTags!==!1&&this.name?` ${M.gray(this.formatTag(this.name))}`:"",z=`\r${q}${A} ${_} ${J}${G}`,W=N.stdout.columns||80,I=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${I}`,N.stdout.write(Q.lastRenderedLine),X)N.stdout.write(`
|
|
10
|
+
`)}finishProgressBar(Q,X){if(!this.enabled||!this.fancy||S()||!N.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(X)Q.message=X;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(S()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let X=await IQ(this.config.logDirectory),Y=[];for(let Z of X){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let H=HQ(this.config.logDirectory,Z);if(Q.before)try{if((await $Q(H)).mtime>=Q.before)continue}catch(U){console.error(`Failed to get stats for file ${H}:`,U);continue}Y.push(H)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let Z of Y)try{await FQ(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(X){console.error("Error during log clearing process:",X)}}}function bQ(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&F(X[0])&&"id"in X[0]&&X[0].id===3&&F(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(F(X)&&F(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(F(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&F(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&F(X[0])&&F(Q[0])){let Z=[...X];for(let $ of Q)if(F($)&&"name"in $){if(!Z.find((U)=>F(U)&&("name"in U)&&U.name===$.name))Z.push($)}else if(F($)&&"path"in $){if(!Z.find((U)=>F(U)&&("path"in U)&&U.path===$.path))Z.push($)}else if(!Z.some((H)=>nQ(H,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!F(X)||!F(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(F($)&&F(Y[Z]))Y[Z]=bQ(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&F($[0])&&F(Y[Z][0])){let H=[...$];for(let U of Y[Z])if(F(U)&&"name"in U){if(!H.find((J)=>F(J)&&("name"in J)&&J.name===U.name))H.push(U)}else if(F(U)&&"path"in U){if(!H.find((J)=>F(J)&&("path"in J)&&J.path===U.path))H.push(U)}else if(!H.some((_)=>nQ(_,U)))H.push(U);Y[Z]=H}else if($.every((H)=>typeof H==="string")&&Y[Z].every((H)=>typeof H==="string")){let H=[...$];for(let U of Y[Z])if(!H.includes(U))H.push(U);Y[Z]=H}else Y[Z]=$;else Y[Z]=$}return Y}function fX(Q,X,Y="replace"){if(X===null||X===void 0)return Q;if(Array.isArray(X))return Y==="replace"?X:bQ(Q,X);if(Array.isArray(Q))return Y==="replace"?X:bQ(Q,X);if(!F(X)||!F(Q))return X;let Z={...Q};for(let $ of Object.keys(X)){if(!Object.prototype.hasOwnProperty.call(X,$))continue;let H=X[$],U=Z[$];if(H===null||H===void 0)continue;if(Array.isArray(H)||Array.isArray(U))if(Y==="replace")Z[$]=H;else Z[$]=bQ(U,H);else if(F(H)&&F(U))Z[$]=fX(U,H,Y);else Z[$]=H}return Z}function nQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!nQ(Q[Y],X[Y]))return!1;return!0}if(F(Q)&&F(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!nQ(Q[$],X[$]))return!1}return!0}return!1}function F(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function CQ(Q,X,Y="replace"){if(!yY(Q))return null;try{let Z=await import(Q),$=Z.default||Z;if(typeof $!=="object"||$===null||Array.isArray($))return null;try{return fX(X,$,Y)}catch{return null}}catch{return null}}function w0(Q,X,Y=!1){if(!Q)return X;let Z=Q.toUpperCase().replace(/-/g,"_"),$={...X};function H(U,_=[]){let J={...U};for(let[G,q]of Object.entries(U)){let A=[..._,G],z=(B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase(),W=`${Z}_${A.map(z).join("_")}`,I=`${Z}_${A.map((B)=>B.toUpperCase()).join("_")}`;if(Y)x.info(`Checking environment variable ${W} for config ${Q}.${A.join(".")}`);if(typeof q==="object"&&q!==null&&!Array.isArray(q))J[G]=H(q,A);else{let B=wQ.env[W]||wQ.env[I];if(B!==void 0){if(Y)x.info(`Using environment variable ${B?W:I} for config ${Q}.${A.join(".")}`);if(typeof q==="number")J[G]=Number(B);else if(typeof q==="boolean")J[G]=B.toLowerCase()==="true";else if(Array.isArray(q))try{let K=JSON.parse(B);if(Array.isArray(K))J[G]=K;else J[G]=B.split(",").map((k)=>k.trim())}catch{J[G]=B.split(",").map((K)=>K.trim())}else J[G]=B}}}return J}return H($)}async function L0({name:Q="",alias:X,cwd:Y,configDir:Z,defaultConfig:$,verbose:H=!1,checkEnv:U=!0,arrayStrategy:_="replace"}){let J=U&&typeof $==="object"&&$!==null&&!Array.isArray($)?w0(Q,$,H):$,G=Y||wQ.cwd(),q=[".ts",".js",".mjs",".cjs",".json"];if(H)x.info(`Loading configuration for "${Q}"${X?` (alias: "${X}")`:""} from ${G}`);let A=[Q,`.${Q}`].filter(Boolean),z=[`${Q}.config`,`.${Q}.config`].filter(Boolean),W=X?[X,`.${X}`]:[],I=X?[`${X}.config`,`.${X}.config`]:[],B=Array.from(new Set([G,b(G,"config"),b(G,".config"),Z?b(G,Z):void 0].filter(Boolean)));for(let K of B){if(H)x.info(`Searching for configuration in: ${K}`);let P=[b(G,"config"),b(G,".config")].concat(Z?[b(G,Z)]:[]).includes(K)?[...A,...z,...W,...I]:[...z,...A,...I,...W];for(let n of P)for(let g of q){let p=b(K,`${n}${g}`),nX=await CQ(p,J,_);if(nX!==null){if(H)x.success(`Configuration loaded from: ${p}`);return nX}}}if(Q){let K=b(ZX(),".config",Q),k=["config",`${Q}.config`];if(X)k.push(`${X}.config`);if(H)x.info(`Checking user config directory: ${K}`);for(let P of k)for(let n of q){let g=b(K,`${P}${n}`),p=await CQ(g,J,_);if(p!==null){if(H)x.success(`Configuration loaded from user config directory: ${g}`);return p}}}if(Q){let K=b(ZX(),".config"),k=[`.${Q}.config`];if(X)k.push(`.${X}.config`);if(H)x.info(`Checking user config directory for dotfile configs: ${K}`);for(let P of k)for(let n of q){let g=b(K,`${P}${n}`),p=await CQ(g,J,_);if(p!==null){if(H)x.success(`Configuration loaded from user config directory dotfile: ${g}`);return p}}}if(Q){let K=ZX(),k=[`.${Q}.config`,`.${Q}`];if(X)k.push(`.${X}.config`),k.push(`.${X}`);if(H)x.info(`Checking user home directory for dotfile configs: ${K}`);for(let P of k)for(let n of q){let g=b(K,`${P}${n}`),p=await CQ(g,J,_);if(p!==null){if(H)x.success(`Configuration loaded from user home directory: ${g}`);return p}}}try{let K=b(G,"package.json");if(yY(K)){let k=await import(K),P=k[Q];if(!P&&X){if(P=k[X],P&&H)x.success(`Using alias "${X}" configuration from package.json`)}if(P&&typeof P==="object"&&!Array.isArray(P))try{if(H)x.success(`Configuration loaded from package.json: ${P===k[Q]?Q:X}`);return fX(J,P,_)}catch(n){if(H)x.warn("Failed to merge package.json config:",n)}}}catch(K){if(H)x.warn("Failed to load package.json:",K)}if(H)x.info(`No configuration found for "${Q}"${X?` or alias "${X}"`:""}, using default configuration with environment variables`);return J}function K0(Q,X={}){let Y=pQ.cwd();while(Y.includes("storage"))Y=aX(Y,"..");let Z=aX(Y,Q||"");if(X?.relative)return DZ(pQ.cwd(),Z);return Z}async function j0(){try{let Q=await L0({name:"clarity",alias:"logging",defaultConfig:dQ,cwd:pQ.cwd()});return{...dQ,...Q||{}}}catch{return dQ}}function V(){if(t.env.NODE_ENV==="test"||t.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function I0(){if(t.env.NODE_ENV==="test"||t.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof t<"u"){let Q=t.type;if(Q==="renderer"||Q==="worker")return!1;return!!(t.versions&&(t.versions.node||t.versions.bun))}return!1}class fY{async format(Q){let X=await I0(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:GQ.pid,hostname:X(),environment:GQ.env.NODE_ENV||"development",platform:GQ.platform,version:GQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:GQ.env.NODE_ENV||GQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class iQ{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(Q,X={}){this.name=Q,this.config={...TX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new fY,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??R.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),H=this.generateKey();this.currentKeyId=$,this.keys.set($,H),this.encryptionKeys.set($,{key:H,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;let X={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return X[Q]>=X[Y]}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...hQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...hQ};return{...hQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:TX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}shouldWriteToFile(){return!V()&&this.config.writeToFile===!0}async writeToFile(Q){let Y=(async()=>{let $,H=0,U=3,_=1000;while(H<U)try{try{try{await dZ(this.config.logDirectory,GY.F_OK|GY.W_OK)}catch(G){if(G instanceof Error&&"code"in G)if(G.code==="ENOENT")await hZ(this.config.logDirectory,{recursive:!0,mode:493});else if(G.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw G;else throw G}}catch(G){throw console.error("Debug: [writeToFile] Failed to create log directory:",G),G}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:i.from(Q);try{if(!MQ(this.currentLogFile))await qX(this.currentLogFile,"",{mode:420});if($=_Y(this.currentLogFile,"a",420),vZ($,J,{flag:"a"}),JY($),$!==void 0)GX($),$=void 0;if((await JQ(this.currentLogFile)).size===0){if(await qX(this.currentLogFile,J,{flag:"w",mode:420}),(await JQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(G){let q=G;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if(H<U-1){let A=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${U}:`,A);let z=_*2**H;await new Promise((W)=>setTimeout(W,z)),H++;continue}}if(q?.code&&["ENOSPC","EDQUOT"].includes(q.code))throw Error(`Disk quota exceeded or no space left on device: ${q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",q),q}finally{if($!==void 0)try{GX($)}catch(G){console.error("Debug: [writeToFile] Error closing file descriptor:",G)}}}catch(J){if(H===U-1){let q=J,A=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}H++;let G=_*2**(H-1);await new Promise((q)=>setTimeout(q,G))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,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 _Q(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 _Q(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return _Q(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(V())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,_],[,J])=>J.createdAt.getTime()-_.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,U=Math.max(1,H);if($.length>U)for(let[_]of $.slice(U))this.encryptionKeys.delete(_),this.keys.delete(_)}generateKeyId(){return _X(16).toString("hex")}generateKey(){return _X(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=_X(16),Z=PZ("aes-256-gcm",X,Y),$=i.isBuffer(Q)?Q:i.from(Q,"utf8"),H=Z.update($),U=Z.final(),_=H.length+U.length,J=Z.getAuthTag(),G=i.allocUnsafe(16+_+16);return Y.copy(G,0),H.copy(G,16),U.copy(G,16+H.length),J.copy(G,16+_),{encrypted:G,iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=AY(),$=[];Z.on("data",(H)=>$.push(H)),Z.on("end",()=>X(i.from(i.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(V())return;if(!this.shouldWriteToFile())return;let Q=await JQ(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await DQ(this.config.logDirectory),H=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,G)=>{let q=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(G.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),U=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,_=`${Y}.${U}`;if(await JQ(Y).catch(()=>null))try{if(await qY(Y,_),X.compress)try{let J=`${_}.gz`;await this.compressLogFile(_,J),await SQ(_)}catch(J){console.error("Error compressing rotated file:",J)}if(H.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await qX(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await JQ(Y).catch(()=>null))await qY(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await DQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,_)=>_.localeCompare(U));for(let U of H.slice(X.maxFiles))await SQ(_Q(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=UY(Q),Z=yZ(X),$=AY();await mZ(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(X);console.log(X)}}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),MQ(this.currentLogFile))try{let Q=_Y(this.currentLogFile,"r+");JY(Q),GX(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!V()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await DQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await SQ(_Q(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.shouldStyleConsole()?L.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||V())return!1;let Q=typeof R.env.NO_COLOR<"u",X=R.env.FORCE_COLOR==="0";if(Q||X)return!1;return!!(typeof R.stderr<"u"&&R.stderr.isTTY||typeof R.stdout<"u"&&R.stdout.isTTY)}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:H,showTimestamp:U=!0}=Q,_=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(U)W.push(X);if(H==="warning")W.push("WARN");else if(H==="error")W.push("ERROR");else if(Y)W.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let J=R.stdout.columns||120,G="";if(H==="warning"||H==="error")G=`${Y} ${$}`;else if(H==="info"||H==="success")G=`${Y} ${Z} ${$}`;else G=`${Y} ${Z} ${L.cyan($)}`;if(!U)return G.trim();let q=_(G).trim().length,A=_(X).length,z=Math.max(1,J-2-q-A);return`${G.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,U)=>{let _=Number.parseInt(U,10);return _<X[0].length?String(X[0][_]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,U)=>{if(U==="%")return"%";if(Z>=X.length)return H;let _=X[Z++];switch(U){case"s":return String(_);case"d":case"i":return Number(_).toString();case"j":case"o":return JSON.stringify(_,null,2);default:return H}});if(Z<X.length)$+=` ${X.slice(Z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return $}formatMarkdown(Q){if(!Q)return Q;let X=Q;return X=X.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,Z,$)=>{let H=L.underline(L.blue(Z)),U=this.toAbsoluteFilePath($);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let _=`file://${encodeURI(U)}`,J="\x1B]8;;",G="\x1B\\";return`\x1B]8;;${_}\x1B\\${H}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${$}\x1B\\${H}\x1B]8;;\x1B\\`;return H}),X=X.replace(/`([^`]+)`/g,(Y,Z)=>L.bgGray(Z)),X=X.replace(/\*\*([^*]+)\*\*/g,(Y,Z)=>L.bold(Z)),X=X.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,Z)=>L.italic(Z)),X=X.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,Z)=>L.italic(Z)),X=X.replace(/~([^~]+)~/g,(Y,Z)=>L.strikethrough(Z)),X}supportsHyperlinks(){if(V())return!1;let Q=R.env;if(!Q)return!1;if(Q.TERM_PROGRAM==="iTerm.app"||Q.TERM_PROGRAM==="vscode"||Q.TERM_PROGRAM==="WezTerm")return!0;if(Q.WT_SESSION)return!0;if(Q.TERM==="xterm-kitty")return!0;let X=Q.VTE_VERSION?Number.parseInt(Q.VTE_VERSION,10):0;if(!Number.isNaN(X)&&X>=5000)return!0;return!1}toAbsoluteFilePath(Q){try{let X=Q;if(X.startsWith("file://"))X=X.replace(/^file:\/\//,"");if(X.startsWith("~")){let Y=R.env.HOME||"";if(Y)X=X.replace(/^~(?=$|\/)/,Y)}if(fZ(X)||X.startsWith("./")||X.startsWith("../"))X=pZ(X);else return null;return MQ(X)?X:null}catch{return null}}buildOutputTexts(Q){let X=this.shouldStyleConsole()?this.formatMarkdown(Q):Q,Y=Q.replace(this.ANSI_PATTERN,"");return{consoleText:X,fileText:Y}}async log(Q,X,...Y){let Z=new Date,$=this.formatConsoleTimestamp(Z),H=this.formatFileTimestamp(Z),U,_;if(X instanceof Error)U=X.message,_=X.stack;else U=this.formatMessage(X,Y);let{consoleText:J,fileText:G}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let A=this.options.showIcons===!1?"":oY[Q],z=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",W;switch(Q){case"debug":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:L.gray(J),level:Q}),console.error(W);break;case"info":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:J,level:Q}),console.warn(W);break;case"success":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:L.green(J),level:Q}),console.error(W);break;case"warning":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:J,level:Q}),console.warn(W);break;case"error":if(W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:J,level:Q}),console.error(W),_){let I=_.split(`
|
|
11
|
+
`);for(let B of I)if(B.trim()&&!B.includes(U))console.error(this.formatConsoleMessage({timestamp:$,message:L.gray(` ${B}`),level:Q,showTimestamp:!1}))}break}}else if(!V()){if(console.error(`${H} ${this.environment}.${Q.toUpperCase()}: ${U}`),_)console.error(_)}if(!this.shouldLog(Q))return;let q=`${H} ${this.environment}.${Q.toUpperCase()}: ${G}
|
|
12
|
+
`;if(_)q+=`${_}
|
|
13
|
+
`;if(q=q.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(q)}progress(Q,X=""){let Y={update:(_,J)=>{},finish:(_)=>{},interrupt:(_,J)=>{}};if(!this.enabled)return Y;let Z=30;if(this.activeProgressBar={total:Math.max(1,Q||1),current:0,message:X||"",barLength:Z,lastRenderedLine:""},this.shouldStyleConsole()&&!V()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(_,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,_),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!V()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(_)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,_)},interrupt:(_,J="info")=>{if(!V()&&R.stdout.isTTY)R.stdout.write(`
|
|
14
|
+
`);if(this[J==="warning"?"warn":J](_),this.activeProgressBar&&this.shouldStyleConsole()&&!V()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Q){let X=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":L.blue("\u25D0"),tag:Y,message:`${L.cyan(Q)}...`}))}return async(Y)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-X),H=`${Q} completed in ${$}ms`,U=new Date,_=this.formatConsoleTimestamp(U),G=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${H}`;if(Y)G+=` ${JSON.stringify(Y)}`;if(G+=`
|
|
15
|
+
`,G=G.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let q=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:_,icon:this.options.showIcons===!1?"":L.green("\u2713"),tag:q,message:`${H}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!V())console.error(G.trim());if(this.shouldWriteToFile())await this.writeToFile(G)}}async debug(Q,...X){await this.log("debug",Q,...X)}async info(Q,...X){await this.log("info",Q,...X)}async success(Q,...X){await this.log("success",Q,...X)}async warn(Q,...X){await this.log("warning",Q,...X)}async error(Q,...X){await this.log("error",Q,...X)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:X}=Q;return!!X}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let X=`${this.name}:${Q}`,Y=new iQ(X,{...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(Y),Y}createReadStream(){if(V())throw Error("createReadStream is not supported in browser environments");if(!MQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return UY(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let X=this.config.rotation;if(!X.encrypt||typeof X.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let Z=i.isBuffer(Q)?Q:i.from(Q,"base64"),$=Z.subarray(0,16),H=Z.subarray(Z.length-16),U=Z.subarray(16,Z.length-16),_=bZ("aes-256-gcm",Y,$);_.setAuthTag(H);let J=_.update(U),G=_.final(),q=J.length+G.length,A=i.allocUnsafe(q);return J.copy(A,0),G.copy(A,J.length),A.toString("utf8")}catch(Z){throw Error(`Decryption failed: ${Z instanceof Error?Z.message:String(Z)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return V()}isServerMode(){return!V()}setTestEncryptionKey(Q,X){this.currentKeyId=Q,this.keys.set(Q,X)}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(Q){if(!this.enabled)return;let X=new Date,Y=this.formatConsoleTimestamp(X),Z=this.formatFileTimestamp(X),{consoleText:$,fileText:H}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let _=$.split(`
|
|
16
|
+
`),J=Math.max(..._.map((z)=>z.length))+2,G=`\u250C${"\u2500".repeat(J)}\u2510`,q=`\u2514${"\u2500".repeat(J)}\u2518`,A=_.map((z)=>{return this.formatConsoleMessage({timestamp:Y,message:L.cyan(z),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:L.cyan(G),showTimestamp:!1})),A.forEach((z)=>console.error(z)),console.error(this.formatConsoleMessage({timestamp:Y,message:L.cyan(q),showTimestamp:!1}))}else if(!V())console.error(`${Z} ${this.environment}.INFO: [BOX] ${H}`);let U=`${Z} ${this.environment}.INFO: [BOX] ${H}
|
|
17
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(Q){if(V())return Promise.resolve(!0);return new Promise((X)=>{console.error(`${L.cyan("?")} ${Q} (y/n) `);let Y=(Z)=>{let $=Z.toString().trim().toLowerCase();R.stdin.removeListener("data",Y);try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!1)}catch{}R.stdin.pause(),console.error(""),X($==="y"||$==="yes")};try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!0)}catch{}R.stdin.resume(),R.stdin.once("data",Y)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...X){if(!this.enabled)return;let Y=Q;if(X&&X.length>0){let J=/%([sdijfo%])/g,G=0;if(Y=Q.replace(J,(q,A)=>{if(A==="%")return"%";if(G>=X.length)return q;let z=X[G++];switch(A){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return q}}),G<X.length)Y+=` ${X.slice(G).map((q)=>typeof q==="object"?JSON.stringify(q,null,2):String(q)).join(" ")}`}let{consoleText:Z,fileText:$}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let J=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",G=this.options.showIcons===!1?"":`${L.blue("\u25D0")} `;console.error(`${G}${J} ${L.cyan(Z)}`)}let _=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${$}
|
|
18
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(_)}renderProgressBar(Q,X=!1){if(!this.enabled||!this.shouldStyleConsole()||!R.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*Y/100),$=Q.barLength-Z,H=L.green("\u2501".repeat(Z)),U=L.gray("\u2501".repeat($)),_=`[${H}${U}]`,J=`${Y}%`.padStart(4),G=Q.message?` ${Q.message}`:"",q=this.options.showIcons===!1?"":X||Y===100?L.green("\u2713"):L.blue("\u25B6"),A=this.options.showTags!==!1&&this.name?` ${L.gray(this.formatTag(this.name))}`:"",z=`\r${q}${A} ${_} ${J}${G}`,W=R.stdout.columns||80,I=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${I}`,R.stdout.write(Q.lastRenderedLine),X)R.stdout.write(`
|
|
19
|
+
`)}finishProgressBar(Q,X){if(!this.enabled||!this.fancy||V()||!R.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(X)Q.message=X;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(V()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let X=await DQ(this.config.logDirectory),Y=[];for(let Z of X){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let H=_Q(this.config.logDirectory,Z);if(Q.before)try{if((await JQ(H)).mtime>=Q.before)continue}catch(U){console.error(`Failed to get stats for file ${H}:`,U);continue}Y.push(H)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let Z of Y)try{await SQ(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(X){console.error("Error during log clearing process:",X)}}}async function pY(Q,X={}){let{maxRetries:Y=3,retryDelay:Z=1000,isRetryable:$=()=>!0,fallback:H}=X,U=Error("Unknown error occurred");for(let _=0;_<=Y;_++)try{return await Q()}catch(J){if(U=J instanceof Error?J:Error(String(J)),_===Y||!$(U))break;if(Z>0)await new Promise((G)=>setTimeout(G,Z))}if(H!==void 0)return H;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function mY(Q){return Q instanceof v}function F0(Q){return Q instanceof sQ}function M0(Q){if(mY(Q))return Q.code==="FILE_SYSTEM_ERROR"||Q.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>Q.message.toLowerCase().includes(Y.toLowerCase()))}class QX{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(Q,X)=>X==="boolean"||["true","false","1","0","yes","no"].includes(Q.toLowerCase()),parse:(Q)=>{let X=Q.toLowerCase();return["true","1","yes"].includes(X)}},{name:"number",canParse:(Q,X)=>X==="number"||!Number.isNaN(Number(Q))&&!Number.isNaN(Number.parseFloat(Q)),parse:(Q)=>{let X=Number(Q);if(Number.isNaN(X))throw TypeError(`Cannot parse "${Q}" as number`);return X}},{name:"array",canParse:(Q,X)=>X==="array"||Q.startsWith("[")||Q.includes(","),parse:(Q)=>{try{let X=JSON.parse(Q);if(Array.isArray(X))return X}catch{}return Q.split(",").map((X)=>X.trim())}},{name:"json",canParse:(Q,X)=>X==="object"||(Q.startsWith("{")&&Q.endsWith("}")||Q.startsWith("[")&&Q.endsWith("]")),parse:(Q)=>{try{return JSON.parse(Q)}catch(X){throw Error(`Cannot parse "${Q}" as JSON: ${X}`)}}}]}async applyEnvironmentVariables(Q,X,Y={}){let{prefix:Z,useCamelCase:$=!0,useBackwardCompatibility:H=!0,customParsers:U={},verbose:_=!1,trackPerformance:J=!0}=Y,G=async()=>{if(!Q)return{config:X,source:{type:"environment",priority:50,timestamp:new Date}};let q=Z||this.generateEnvPrefix(Q),A={...X};return this.processObject(A,[],q,{useCamelCase:$,useBackwardCompatibility:H,customParsers:U,verbose:_,configName:Q}),{config:A,source:{type:"environment",priority:50,timestamp:new Date}}};if(J)return jQ.track("applyEnvironmentVariables",G,{configName:Q});return G()}generateEnvPrefix(Q){return Q.toUpperCase().replace(/-/g,"_")}formatEnvKey(Q,X){if(!X)return Q.toUpperCase();return Q.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(Q,X,Y,Z){for(let[$,H]of Object.entries(Q)){let U=[...X,$],_=U.map((q)=>this.formatEnvKey(q,Z.useCamelCase)),J=`${Y}_${_.join("_")}`,G=Z.useBackwardCompatibility?`${Y}_${U.map((q)=>q.toUpperCase()).join("_")}`:null;if(Z.verbose);if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.processObject(H,U,Y,Z);else{let q=VQ.env[J]||(G?VQ.env[G]:void 0);if(q!==void 0){if(Z.verbose){let A=VQ.env[J]?J:G}try{Q[$]=this.parseEnvironmentValue(q,typeof H,J,Z.customParsers,Z.configName)}catch(A){if(A instanceof oQ)throw A;throw QQ.envVar(J,q,typeof H,Z.configName)}}}}}parseEnvironmentValue(Q,X,Y,Z,$){for(let[H,U]of Object.entries(Z))try{return U(Q)}catch{continue}for(let H of this.defaultParsers)if(H.canParse(Q,X))try{return H.parse(Q)}catch{throw QQ.envVar(Y,Q,`${X} (via ${H.name} parser)`,$)}return Q}getEnvironmentVariables(Q){let X={},Y=Q.toUpperCase();for(let[Z,$]of Object.entries(VQ.env))if(Z.startsWith(Y)&&$!==void 0)X[Z]=$;return X}validateEnvironmentVariable(Q,X,Y){let Z=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(Q))Z.push(`Environment variable key "${Q}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(Q,X,Y,{})}catch($){Z.push(`Cannot parse value "${X}" as ${Y}: ${$}`)}return{isValid:Z.length===0,errors:Z}}generateEnvVarDocs(Q,X,Y={}){let{prefix:Z,format:$="text"}=Y,H=Z||this.generateEnvPrefix(Q),U=[];switch(this.extractEnvVarInfo(X,[],H,U),$){case"markdown":return this.formatAsMarkdown(U,Q);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,Q)}}extractEnvVarInfo(Q,X,Y,Z){for(let[$,H]of Object.entries(Q)){let U=[...X,$],_=`${Y}_${U.map((J)=>this.formatEnvKey(J,!0)).join("_")}`;if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.extractEnvVarInfo(H,U,Y,Z);else Z.push({key:_,type:Array.isArray(H)?"array":typeof H,description:`Configuration for ${U.join(".")}`,example:this.generateExample(H)})}}generateExample(Q){if(Array.isArray(Q))return JSON.stringify(Q);if(typeof Q==="object"&&Q!==null)return JSON.stringify(Q);return String(Q)}formatAsText(Q,X){let Y=`Environment Variables for ${X}:
|
|
20
20
|
|
|
21
|
-
`;for(let Z of
|
|
22
|
-
`,
|
|
23
|
-
`,
|
|
24
|
-
`,
|
|
21
|
+
`;for(let Z of Q)Y+=`${Z.key}
|
|
22
|
+
`,Y+=` Type: ${Z.type}
|
|
23
|
+
`,Y+=` Description: ${Z.description}
|
|
24
|
+
`,Y+=` Example: ${Z.example}
|
|
25
25
|
|
|
26
|
-
`;return
|
|
26
|
+
`;return Y}formatAsMarkdown(Q,X){let Y=`# Environment Variables for ${X}
|
|
27
27
|
|
|
28
|
-
`;
|
|
29
|
-
`,
|
|
30
|
-
`;for(let Z of
|
|
31
|
-
`;return Q}}function p7($,X){let Q=J9("process");if(typeof Q>"u"||!Q.env)return X;let Z=Q.env[$];return Z!==void 0?Z:X}function $9($,X,Q={}){return X9($,X,Q,new WeakMap)}function X9($,X,Q,Z){let{arrayMergeMode:J="replace",skipNullish:Y=!1,customMerger:G}=Q;if(X===null||X===void 0)return Y?$:X;if(G){let H=G($,X);if(H!==void 0)return H}if(Array.isArray(X)||Array.isArray($))return Q9($,X,J,Z);if(!$0(X)||!$0($))return X;return i7($,X,Q,Z)}function Q9($,X,Q,Z){if(Array.isArray(X)&&!Array.isArray($))return X;if(Array.isArray($)&&!Array.isArray(X))return X;if(Array.isArray(X)&&Array.isArray($))switch(Q){case"replace":return X;case"concat":return c7($,X);case"smart":return l7($,X,Z);default:return X}return X}function c7($,X){let Q=[...X];for(let Z of $)if(!Q.some((J)=>d$(J,Z)))Q.push(Z);return Q}function l7($,X,Q){if(X.length===0)return $;if($.length===0)return X;if($0(X[0])&&$0($[0]))return n7($,X,Q);if(X.every((Z)=>typeof Z==="string")&&$.every((Z)=>typeof Z==="string")){let Z=[...X];for(let J of $)if(!Z.includes(J))Z.push(J);return Z}return X}function n7($,X,Q){let Z=[...X];for(let J of $){if(!$0(J)){Z.push(J);continue}let Y=["id","name","key","path","type"],G=!1;for(let H of Y)if(H in J){if(Z.find((q)=>$0(q)&&(H in q)&&q[H]===J[H])){G=!0;break}}if(!G)Z.push(J)}return Z}function i7($,X,Q,Z){let J=X;if($0(J)&&Z.has(J))return Z.get(J);let Y={...$};if($0(J))Z.set(J,Y);for(let G in J){if(!Object.prototype.hasOwnProperty.call(J,G))continue;let H=J[G],U=Y[G];if(Q.skipNullish&&(H===null||H===void 0))continue;if(H===null||H===void 0){Y[G]=H;continue}if($0(H)&&$0(U))Y[G]=X9(U,H,Q,Z);else if(Array.isArray(H)||Array.isArray(U))Y[G]=Q9(U,H,Q.arrayMergeMode||"smart",Z);else Y[G]=H}return Y}function XX($,X,Q="replace"){return $9($,X,{arrayMergeMode:Q==="replace"?"replace":"smart",skipNullish:!0})}function d$($,X){if($===X)return!0;if(Array.isArray($)&&Array.isArray(X)){if($.length!==X.length)return!1;for(let Q=0;Q<$.length;Q++)if(!d$($[Q],X[Q]))return!1;return!0}if($0($)&&$0(X)){let Q=Object.keys($),Z=Object.keys(X);if(Q.length!==Z.length)return!1;for(let J of Q){if(!Object.prototype.hasOwnProperty.call(X,J))return!1;if(!d$($[J],X[J]))return!1}return!0}return!1}function $0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class s8{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,X,Q={}){let{arrayStrategy:Z="replace",useCache:J=!0,cacheTtl:Y,trackPerformance:G=!0,verbose:H=!1}=Q;if(J){let q=c0.getWithFileCheck("file",$);if(q){if(H)console.log(`Configuration loaded from cache: ${$}`);return q}}let U=async()=>{if(!I8($))return null;try{let q=`?t=${Date.now()}`,z=await import($+q),_=z.default||z,A="default"in z,W=Object.keys(z).length>0;if(!A&&!W)throw new $8($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof _!=="object"||_===null||Array.isArray(_))throw new $8($,Error("Configuration must export a valid object"),"unknown");let M={config:XX(X,_,Z),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(J)c0.setWithFileCheck("file",M,$,Y);return M}catch(q){throw q instanceof Error?I0.configLoad($,q):I0.configLoad($,Error(String(q)))}};if(G)return Q8.track("loadFromPath",U,{path:$});return U()}async tryLoadFromPaths($,X,Q={}){for(let Z of $)try{let J=await this.loadFromPath(Z,X,Q);if(J)return J}catch(J){if(J instanceof Error&&J.name==="ConfigLoadError")throw J;if(Q.verbose)console.warn(`Failed to load config from ${Z}:`,J)}return null}generateConfigPaths($,X,Q){let Z=this.generateNamePatterns($,Q),J=[];for(let Y of Z)for(let G of this.extensions)J.push(N$(X,`${Y}${G}`));return J}generateNamePatterns($,X){let Q=[];if(Q.push("config",".config"),$)Q.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(X){if(Q.push(X,`.${X}.config`,`${X}.config`,`.${X}`),$)Q.push(`${$}.${X}.config`,`.${$}.${X}.config`)}return Q.filter(Boolean)}checkFileAccess($){return tQ(async()=>{return I8($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,X,Q){let Z=[];if(!I8($))return Z;if(X||Q){let J=this.generateNamePatterns(X||"",Q);for(let Y of J)for(let G of this.extensions){let H=N$($,`${Y}${G}`);if(await this.checkFileAccess(H))Z.push(H)}}else try{let{readdirSync:J}=await import("fs"),Y=J($);for(let G of Y)if(this.looksLikeConfigFile(G)){let H=N$($,G);if(await this.checkFileAccess(H))Z.push(H)}}catch{return[]}return Z}looksLikeConfigFile($){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((Q)=>Q.test($))}async validateConfigFile($){let X=[];try{if(!I8($))return X.push("Configuration file does not exist"),X;let Q=await import($),Z=Q.default||Q;if(Z===void 0)X.push("Configuration file must export a default value or named exports");else if(typeof Z!=="object"||Z===null)X.push("Configuration must be an object");else if(Array.isArray(Z))X.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:J}=await import("fs"),Y=J($,"utf8");JSON.parse(Y)}catch(J){X.push(`Invalid JSON syntax: ${J}`)}}catch(Q){X.push(`Failed to load configuration file: ${Q}`)}return X}async getFileModificationTime($){try{let{statSync:X}=await import("fs");return X($).mtime}catch{return null}}async preloadConfigurations($,X={}){let Q=new Map;return await Promise.allSettled($.map(async(Z)=>{try{let J=await this.loadFromPath(Z,{},X);if(J)Q.set(Z,J.config)}catch(J){if(X.verbose)console.warn(`Failed to preload ${Z}:`,J)}})),Q}}class QX{async validateConfiguration($,X,Q={}){let{stopOnFirstError:Z=!1,validateRequired:J=!0,validateTypes:Y=!0,customRules:G=[],trackPerformance:H=!0,verbose:U=!1}=Q,q=async()=>{let z=[],_=[],A={stopOnFirstError:Z,validateRequired:J,validateTypes:Y,customRules:G,trackPerformance:H,verbose:U};try{if(typeof X==="string")return await this.validateWithSchemaFile($,X,A);else if(Array.isArray(X))return this.validateWithRules($,[...X,...G],A);else return this.validateWithJSONSchema($,X,A)}catch(W){return z.push({path:"",message:`Validation failed: ${W}`,rule:"system"}),{isValid:!1,errors:z,warnings:_}}};if(H)return await Q8.track("validateConfiguration",q);return q()}async validateWithSchemaFile($,X,Q){try{if(!U7(X))throw new X8(X,[{path:"",message:"Schema file does not exist"}]);let Z=await import(X),J=Z.default||Z;if(Array.isArray(J))return this.validateWithRules($,J,Q);else return this.validateWithJSONSchema($,J,Q)}catch(Z){throw new X8(X,[{path:"",message:`Failed to load schema: ${Z}`}])}}validateWithJSONSchema($,X,Q){let Z=[],J=[];return this.validateObjectAgainstSchema($,X,"",Z,J,Q),{isValid:Z.length===0,errors:Z,warnings:J}}validateObjectAgainstSchema($,X,Q,Z,J,Y){if(Y.validateTypes&&X.type){let G=Array.isArray($)?"array":typeof $,H=Array.isArray(X.type)?X.type:[X.type];if(!H.includes(G)){if(Z.push({path:Q,message:`Expected type ${H.join(" or ")}, got ${G}`,expected:H.join(" or "),actual:G,rule:"type"}),Y.stopOnFirstError)return}}if(X.enum&&!X.enum.includes($)){if(Z.push({path:Q,message:`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:$,rule:"enum"}),Y.stopOnFirstError)return}if(typeof $==="string"){if(X.minLength!==void 0&&$.length<X.minLength)Z.push({path:Q,message:`String length must be at least ${X.minLength}`,expected:`>= ${X.minLength}`,actual:$.length,rule:"minLength"});if(X.maxLength!==void 0&&$.length>X.maxLength)Z.push({path:Q,message:`String length must not exceed ${X.maxLength}`,expected:`<= ${X.maxLength}`,actual:$.length,rule:"maxLength"});if(X.pattern){if(!new RegExp(X.pattern).test($))Z.push({path:Q,message:`String does not match pattern ${X.pattern}`,expected:X.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(X.minimum!==void 0&&$<X.minimum)Z.push({path:Q,message:`Value must be at least ${X.minimum}`,expected:`>= ${X.minimum}`,actual:$,rule:"minimum"});if(X.maximum!==void 0&&$>X.maximum)Z.push({path:Q,message:`Value must not exceed ${X.maximum}`,expected:`<= ${X.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&X.items)for(let G=0;G<$.length;G++){let H=Q?`${Q}[${G}]`:`[${G}]`;if(this.validateObjectAgainstSchema($[G],X.items,H,Z,J,Y),Y.stopOnFirstError&&Z.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let G=$;if(Y.validateRequired&&X.required){for(let H of X.required)if(!(H in G)){if(Z.push({path:Q?`${Q}.${H}`:H,message:`Missing required property '${H}'`,expected:"required",rule:"required"}),Y.stopOnFirstError)return}}if(X.properties){for(let[H,U]of Object.entries(X.properties))if(H in G){let q=Q?`${Q}.${H}`:H;if(this.validateObjectAgainstSchema(G[H],U,q,Z,J,Y),Y.stopOnFirstError&&Z.length>0)return}}if(X.additionalProperties===!1){let H=new Set(Object.keys(X.properties||{}));for(let U of Object.keys(G))if(!H.has(U))J.push({path:Q?`${Q}.${U}`:U,message:`Additional property '${U}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,X,Q){let Z=[],J=[];for(let Y of X)try{let G=this.getValueByPath($,Y.path),H=this.validateWithRule(G,Y,Y.path);if(Z.push(...H),Q.stopOnFirstError&&Z.length>0)break}catch(G){Z.push({path:Y.path,message:`Rule validation failed: ${G}`,rule:"system"})}return{isValid:Z.length===0,errors:Z,warnings:J}}validateWithRule($,X,Q){let Z=[];if(X.required&&($===void 0||$===null))return Z.push({path:Q,message:X.message||`Property '${Q}' is required`,expected:"required",rule:"required"}),Z;if($===void 0||$===null)return Z;if(X.type){let J=Array.isArray($)?"array":typeof $;if(J!==X.type)Z.push({path:Q,message:X.message||`Expected type ${X.type}, got ${J}`,expected:X.type,actual:J,rule:"type"})}if(X.min!==void 0){let J=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(J<X.min)Z.push({path:Q,message:X.message||`Value must be at least ${X.min}`,expected:`>= ${X.min}`,actual:J,rule:"min"})}if(X.max!==void 0){let J=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(J>X.max)Z.push({path:Q,message:X.message||`Value must not exceed ${X.max}`,expected:`<= ${X.max}`,actual:J,rule:"max"})}if(X.pattern&&typeof $==="string"){if(!X.pattern.test($))Z.push({path:Q,message:X.message||`Value does not match pattern ${X.pattern}`,expected:X.pattern.toString(),actual:$,rule:"pattern"})}if(X.enum&&!X.enum.includes($))Z.push({path:Q,message:X.message||`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:$,rule:"enum"});if(X.validator){let J=X.validator($);if(J)Z.push({path:Q,message:X.message||J,rule:"custom"})}return Z}getValueByPath($,X){if(!X)return $;let Q=X.split("."),Z=$;for(let J of Q)if(Z&&typeof Z==="object"&&J in Z)Z=Z[J];else return;return Z}generateRulesFromInterface($){let X=[],Q=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Z of Q){let[,J,Y,G]=Z;X.push({path:J,required:!Y,type:this.mapTypeScriptType(G)})}return X}mapTypeScriptType($){switch($.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:q9},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class ZX{fileLoader=new s8;envProcessor=new a8;validator=new QX;async loadConfig($){let X=Date.now(),{cache:Q,performance:Z,schema:J,validate:Y,...G}=$;try{if(Q?.enabled){let U=this.checkCache(G.name||"",G);if(U)return U}let H;try{H=await this.loadConfigurationStrategies(G,!0,Q)}catch(U){let q=G.__strictErrorHandling;if(U instanceof Error&&U.name==="ConfigNotFoundError"){if(q)throw U;H={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`No configuration file found for "${G.name||"config"}", using defaults with environment variables`]}}else if(U instanceof Error&&U.name==="ConfigLoadError"){let z=U.message.includes("EACCES")||U.message.includes("EPERM")||U.message.includes("permission denied"),_=!z&&(U.message.includes("syntax")||U.message.includes("Expected")||U.message.includes("Unexpected")||U.message.includes("BuildMessage")||U.message.includes("errors building")),A=U.message.includes("Configuration must export a valid object")||U.message.includes("Configuration file is empty and exports nothing");if(q&&(A||z))throw U;if(_&&(!q||!A))H={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!q)H={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`Configuration loading error, using defaults: ${U.message}`]};else throw U}else H={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${U instanceof Error?U.message:String(U)}`]}}if(J||Y)await this.validateConfiguration(H.config,J,Y,G.name);if(Q?.enabled&&H)this.cacheResult(G.name||"",H,Q,G);if(Z?.enabled){let U={operation:"loadConfig",duration:Date.now()-X,configName:G.name,timestamp:new Date};if(Z.onMetrics)Z.onMetrics(U);if(Z.slowThreshold&&U.duration>Z.slowThreshold)Y0.warn(`Slow configuration loading detected: ${U.duration}ms for ${G.name}`);H.metrics=U}return H}catch(H){let U=Date.now()-X;throw Y0.error(`Configuration loading failed after ${U}ms:`,[H instanceof Error?H:Error(String(H))]),H}}async loadConfigurationStrategies($,X=!1,Q){let{name:Z="",alias:J,cwd:Y,configDir:G,defaultConfig:H,checkEnv:U=!0,arrayStrategy:q="replace",verbose:z=!1}=$,_=Y||S0.cwd(),A=[],W=await this.loadLocalConfiguration(Z,J,_,G,H,q,z,U,Q);if(W)return A.push(...this.getLocalSearchPaths(Z,J,_,G)),this.finalizeResult(W,A,U,Z,z);let K=await this.loadHomeConfiguration(Z,J,H,q,z,U);if(K)return A.push(...this.getHomeSearchPaths(Z,J)),this.finalizeResult(K,A,U,Z,z);let B=await this.loadPackageJsonConfiguration(Z,J,_,H,q,z,U);if(B)return A.push(o(_,"package.json")),this.finalizeResult(B,A,U,Z,z);if(A.push(...this.getAllSearchPaths(Z,J,_,G)),X)throw I0.configNotFound(Z,A,J);return{...await this.applyEnvironmentVariables(Z,H,U,z),warnings:[`No configuration file found for "${Z}"${J?` or alias "${J}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,X,Q,Z,J,Y,G,H,U){let q=H?t0($,J,G):J,z=this.getLocalDirectories(Q,Z);for(let _ of z){if(G)Y0.info(`Searching for configuration in: ${_}`);let A=this.fileLoader.generateConfigPaths($,_,X),W=await this.fileLoader.tryLoadFromPaths(A,q,{arrayStrategy:Y,verbose:G,cacheTtl:U?.ttl,useCache:!U?.ttl||U.ttl>100});if(W){if(G)Y0.success(`Configuration loaded from: ${W.source.path}`);return W}}return null}async loadHomeConfiguration($,X,Q,Z,J,Y){if(!$)return null;let G=Y?t0($,Q,J):Q,H=[o(k0(),".config",$),o(k0(),".config"),k0()];for(let U of H){if(J)Y0.info(`Checking home directory: ${U}`);let q=this.fileLoader.generateConfigPaths($,U,X),z=await this.fileLoader.tryLoadFromPaths(q,G,{arrayStrategy:Z,verbose:J});if(z){if(J)Y0.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration($,X,Q,Z,J,Y,G){let H=G?t0($,Z,Y):Z;try{let U=o(Q,"package.json");if(!f$(U))return null;let q=await import(U),z=q[$],_=$;if(!z&&X)z=q[X],_=X;if(z&&typeof z==="object"&&!Array.isArray(z)){if(Y)Y0.success(`Configuration loaded from package.json: ${_}`);return{config:XX(H,z,J),source:{type:"package.json",path:U,priority:30,timestamp:new Date}}}}catch(U){if(Y)Y0.warn("Failed to load package.json:",[U instanceof Error?U:Error(String(U))])}return null}async applyEnvironmentVariables($,X,Q,Z){if(!Q||!$||typeof X!=="object"||X===null||Array.isArray(X))return{config:X,source:{type:"default",priority:10,timestamp:new Date}};return{config:t0($,X,Z),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,X,Q,Z,J){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,X,Q,Z){let J=[];if(Q){let Y=Q($);if(Y)J.push(...Y)}if(X){let Y=await this.validator.validateConfiguration($,X);if(!Y.isValid)J.push(...Y.errors.map((G)=>G.path?`${G.path}: ${G.message}`:G.message))}if(J.length>0)throw I0.configValidation(Z||"unknown",J,Z)}checkCache($,X){let Q=this.generateCacheKey($,X);return c0.get(Q)||null}cacheResult($,X,Q,Z){let J=this.generateCacheKey($,Z);c0.set(J,X,void 0,Q.ttl)}generateCacheKey($,X){let Q=[$];if(X.alias)Q.push(`alias:${X.alias}`);if(X.cwd)Q.push(`cwd:${X.cwd}`);if(X.configDir)Q.push(`configDir:${X.configDir}`);if("checkEnv"in X)Q.push(`checkEnv:${X.checkEnv}`);return Q.join("|")}getLocalDirectories($,X){return Array.from(new Set([$,o($,"config"),o($,".config"),X?o($,X):void 0].filter(Boolean)))}getAllSearchPaths($,X,Q,Z){let J=[];return J.push(...this.getLocalSearchPaths($,X,Q,Z)),J.push(...this.getHomeSearchPaths($,X)),J.push(o(Q,"package.json")),J}getLocalSearchPaths($,X,Q,Z){let J=this.getLocalDirectories(Q,Z),Y=[];for(let G of J)Y.push(...this.fileLoader.generateConfigPaths($,G,X));return Y}getHomeSearchPaths($,X){if(!$)return[];let Q=[o(k0(),".config",$),o(k0(),".config"),k0()],Z=[];for(let J of Q)Z.push(...this.fileLoader.generateConfigPaths($,J,X));return Z}async loadConfigWithResult($){return this.loadConfig($)}}function bQ($){let Q=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),Z=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return Q||Z}async function o7($){return M0.loadConfig({...$,__strictErrorHandling:!0})}async function Z9($){let X="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Q="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Z;if(Q)Z=await M0.loadConfig($);else Z=await M0.loadConfig({...$,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}});return Z?.config??X}catch(Z){let J=Z instanceof Error?Z.name:"UnknownError",Y=Z instanceof Error?Z.message:String(Z);if(!(J==="ConfigNotFoundError"||J==="ConfigLoadError"||J==="ConfigValidationError"||Y.includes("config"))&&$.verbose)Y0.warn("Unexpected error loading config, using defaults:",[Z instanceof Error?Z:Error(String(Z))]);let H=Q?{...$,defaultConfig:X}:{...$,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await M0.applyEnvironmentVariables(H.name||"",X,!0,H.verbose||!1))?.config??X;return X}}async function r7($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:X}=await import("process");try{return(await M0.loadConfig({name:$,cwd:X(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Q){if(Q instanceof Error&&(Q.name==="ConfigNotFoundError"||Q.name==="ConfigLoadError"&&bQ(Q)))return(await M0.applyEnvironmentVariables($,{},!0,!1)).config;throw Q}}try{return(await M0.loadConfig({...$,cwd:$.cwd||S0.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(X){if(X instanceof Error&&(X.name==="ConfigNotFoundError"||X.name==="ConfigLoadError"&&bQ(X)))return(await M0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw X}}async function a7($,X,Q="replace"){let Z=new s8;try{let J=await Z.loadFromPath($,X,{arrayStrategy:Q,useCache:!1,trackPerformance:!1});return J?J.config:null}catch{return null}}function t0($,X,Q=!1){let Z=new a8,J=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(G,H=[]){let U={...G};for(let[q,z]of Object.entries(G)){let _=[...H,q],A=[`${J}_${_.join("_").toUpperCase()}`,`${J}_${_.map((B)=>B.toUpperCase()).join("")}`,`${J}_${_.map((B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],W,K;for(let B of A)if(W=S0.env[B],W!==void 0){K=B;break}if(W!==void 0&&K)if(typeof z==="boolean")U[q]=["true","1","yes"].includes(W.toLowerCase());else if(typeof z==="number"){let B=Number(W);if(!Number.isNaN(B))U[q]=B}else if(Array.isArray(z))try{U[q]=JSON.parse(W)}catch{U[q]=W.split(",").map((B)=>B.trim())}else U[q]=W;else if(z&&typeof z==="object"&&!Array.isArray(z))U[q]=Y(z,_)}return U}return Y(X)}function s7($){let X=o(S0.cwd(),$.configDir),Q=o(S0.cwd(),$.generatedDir),Z=o(Q,"config-types.ts");if(!f$(qQ(Z)))gZ(qQ(Z),{recursive:!0,mode:511});let J=f$(X)?dZ(X).map((G)=>G.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],Y=`// Generated by bunfig v${NJ}
|
|
32
|
-
export type ConfigNames = ${
|
|
33
|
-
`;
|
|
34
|
-
${
|
|
28
|
+
`;Y+=`| Variable | Type | Description | Example |
|
|
29
|
+
`,Y+=`|----------|------|-------------|----------|
|
|
30
|
+
`;for(let Z of Q)Y+=`| \`${Z.key}\` | ${Z.type} | ${Z.description} | \`${Z.example}\` |
|
|
31
|
+
`;return Y}}function D0(Q,X){let Y=nY("process");if(typeof Y>"u"||!Y.env)return X;let Z=Y.env[Q];return Z!==void 0?Z:X}function uY(Q,X,Y={}){return gY(Q,X,Y,new WeakMap)}function gY(Q,X,Y,Z){let{arrayMergeMode:$="replace",skipNullish:H=!1,customMerger:U}=Y;if(X===null||X===void 0)return H?Q:X;if(U){let _=U(Q,X);if(_!==void 0)return _}if(Array.isArray(X)||Array.isArray(Q))return cY(Q,X,$,Z);if(!h(X)||!h(Q))return X;return T0(Q,X,Y,Z)}function cY(Q,X,Y,Z){if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(Q)&&!Array.isArray(X))return X;if(Array.isArray(X)&&Array.isArray(Q))switch(Y){case"replace":return X;case"concat":return S0(Q,X);case"smart":return V0(Q,X,Z);default:return X}return X}function S0(Q,X){let Y=[...X];for(let Z of Q)if(!Y.some(($)=>VX($,Z)))Y.push(Z);return Y}function V0(Q,X,Y){if(X.length===0)return Q;if(Q.length===0)return X;if(h(X[0])&&h(Q[0]))return E0(Q,X,Y);if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}function E0(Q,X,Y){let Z=[...X];for(let $ of Q){if(!h($)){Z.push($);continue}let H=["id","name","key","path","type"],U=!1;for(let _ of H)if(_ in $){if(Z.find((G)=>h(G)&&(_ in G)&&G[_]===$[_])){U=!0;break}}if(!U)Z.push($)}return Z}function T0(Q,X,Y,Z){let $=X;if(h($)&&Z.has($))return Z.get($);let H={...Q};if(h($))Z.set($,H);for(let U in $){if(!Object.prototype.hasOwnProperty.call($,U))continue;let _=$[U],J=H[U];if(Y.skipNullish&&(_===null||_===void 0))continue;if(_===null||_===void 0){H[U]=_;continue}if(h(_)&&h(J))H[U]=gY(J,_,Y,Z);else if(Array.isArray(_)||Array.isArray(J))H[U]=cY(J,_,Y.arrayMergeMode||"smart",Z);else H[U]=_}return H}function pX(Q,X,Y="replace"){return uY(Q,X,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function VX(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!VX(Q[Y],X[Y]))return!1;return!0}if(h(Q)&&h(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!VX(Q[$],X[$]))return!1}return!0}return!1}function h(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}class XX{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(Q,X,Y={}){let{arrayStrategy:Z="replace",useCache:$=!0,cacheTtl:H,trackPerformance:U=!0,verbose:_=!1}=Y;if($){let G=zQ.getWithFileCheck("file",Q);if(G){if(_)console.log(`Configuration loaded from cache: ${Q}`);return G}}let J=async()=>{if(!EQ(Q))return null;try{let G=`?t=${Date.now()}`,q=await import(Q+G),A=q.default||q,z="default"in q,W=Object.keys(q).length>0;if(!z&&!W)throw new LQ(Q,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof A!=="object"||A===null||Array.isArray(A))throw new LQ(Q,Error("Configuration must export a valid object"),"unknown");let K={config:pX(X,A,Z),source:{type:"file",path:Q,priority:100,timestamp:new Date}};if($)zQ.setWithFileCheck("file",K,Q,H);return K}catch(G){throw G instanceof Error?QQ.configLoad(Q,G):QQ.configLoad(Q,Error(String(G)))}};if(U)return jQ.track("loadFromPath",J,{path:Q});return J()}async tryLoadFromPaths(Q,X,Y={}){for(let Z of Q)try{let $=await this.loadFromPath(Z,X,Y);if($)return $}catch($){if($ instanceof Error&&$.name==="ConfigLoadError")throw $;if(Y.verbose)console.warn(`Failed to load config from ${Z}:`,$)}return null}generateConfigPaths(Q,X,Y){let Z=this.generateNamePatterns(Q,Y),$=[];for(let H of Z)for(let U of this.extensions)$.push(AX(X,`${H}${U}`));return $}generateNamePatterns(Q,X){let Y=[];if(Y.push("config",".config"),Q)Y.push(Q,`.${Q}.config`,`${Q}.config`,`.${Q}`);if(X){if(Y.push(X,`.${X}.config`,`${X}.config`,`.${X}`),Q)Y.push(`${Q}.${X}.config`,`.${Q}.${X}.config`)}return Y.filter(Boolean)}checkFileAccess(Q){return pY(async()=>{return EQ(Q)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Q,X,Y){let Z=[];if(!EQ(Q))return Z;if(X||Y){let $=this.generateNamePatterns(X||"",Y);for(let H of $)for(let U of this.extensions){let _=AX(Q,`${H}${U}`);if(await this.checkFileAccess(_))Z.push(_)}}else try{let{readdirSync:$}=await import("fs"),H=$(Q);for(let U of H)if(this.looksLikeConfigFile(U)){let _=AX(Q,U);if(await this.checkFileAccess(_))Z.push(_)}}catch{return[]}return Z}looksLikeConfigFile(Q){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((Y)=>Y.test(Q))}async validateConfigFile(Q){let X=[];try{if(!EQ(Q))return X.push("Configuration file does not exist"),X;let Y=await import(Q),Z=Y.default||Y;if(Z===void 0)X.push("Configuration file must export a default value or named exports");else if(typeof Z!=="object"||Z===null)X.push("Configuration must be an object");else if(Array.isArray(Z))X.push("Configuration cannot be an array at the root level");if(Q.endsWith(".json"))try{let{readFileSync:$}=await import("fs"),H=$(Q,"utf8");JSON.parse(H)}catch($){X.push(`Invalid JSON syntax: ${$}`)}}catch(Y){X.push(`Failed to load configuration file: ${Y}`)}return X}async getFileModificationTime(Q){try{let{statSync:X}=await import("fs");return X(Q).mtime}catch{return null}}async preloadConfigurations(Q,X={}){let Y=new Map;return await Promise.allSettled(Q.map(async(Z)=>{try{let $=await this.loadFromPath(Z,{},X);if($)Y.set(Z,$.config)}catch($){if(X.verbose)console.warn(`Failed to preload ${Z}:`,$)}})),Y}}class mX{async validateConfiguration(Q,X,Y={}){let{stopOnFirstError:Z=!1,validateRequired:$=!0,validateTypes:H=!0,customRules:U=[],trackPerformance:_=!0,verbose:J=!1}=Y,G=async()=>{let q=[],A=[],z={stopOnFirstError:Z,validateRequired:$,validateTypes:H,customRules:U,trackPerformance:_,verbose:J};try{if(typeof X==="string")return await this.validateWithSchemaFile(Q,X,z);else if(Array.isArray(X))return this.validateWithRules(Q,[...X,...U],z);else return this.validateWithJSONSchema(Q,X,z)}catch(W){return q.push({path:"",message:`Validation failed: ${W}`,rule:"system"}),{isValid:!1,errors:q,warnings:A}}};if(_)return await jQ.track("validateConfiguration",G);return G()}async validateWithSchemaFile(Q,X,Y){try{if(!uZ(X))throw new KQ(X,[{path:"",message:"Schema file does not exist"}]);let Z=await import(X),$=Z.default||Z;if(Array.isArray($))return this.validateWithRules(Q,$,Y);else return this.validateWithJSONSchema(Q,$,Y)}catch(Z){throw new KQ(X,[{path:"",message:`Failed to load schema: ${Z}`}])}}validateWithJSONSchema(Q,X,Y){let Z=[],$=[];return this.validateObjectAgainstSchema(Q,X,"",Z,$,Y),{isValid:Z.length===0,errors:Z,warnings:$}}validateObjectAgainstSchema(Q,X,Y,Z,$,H){if(H.validateTypes&&X.type){let U=Array.isArray(Q)?"array":typeof Q,_=Array.isArray(X.type)?X.type:[X.type];if(!_.includes(U)){if(Z.push({path:Y,message:`Expected type ${_.join(" or ")}, got ${U}`,expected:_.join(" or "),actual:U,rule:"type"}),H.stopOnFirstError)return}}if(X.enum&&!X.enum.includes(Q)){if(Z.push({path:Y,message:`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"}),H.stopOnFirstError)return}if(typeof Q==="string"){if(X.minLength!==void 0&&Q.length<X.minLength)Z.push({path:Y,message:`String length must be at least ${X.minLength}`,expected:`>= ${X.minLength}`,actual:Q.length,rule:"minLength"});if(X.maxLength!==void 0&&Q.length>X.maxLength)Z.push({path:Y,message:`String length must not exceed ${X.maxLength}`,expected:`<= ${X.maxLength}`,actual:Q.length,rule:"maxLength"});if(X.pattern){if(!new RegExp(X.pattern).test(Q))Z.push({path:Y,message:`String does not match pattern ${X.pattern}`,expected:X.pattern,actual:Q,rule:"pattern"})}}if(typeof Q==="number"){if(X.minimum!==void 0&&Q<X.minimum)Z.push({path:Y,message:`Value must be at least ${X.minimum}`,expected:`>= ${X.minimum}`,actual:Q,rule:"minimum"});if(X.maximum!==void 0&&Q>X.maximum)Z.push({path:Y,message:`Value must not exceed ${X.maximum}`,expected:`<= ${X.maximum}`,actual:Q,rule:"maximum"})}if(Array.isArray(Q)&&X.items)for(let U=0;U<Q.length;U++){let _=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(Q[U],X.items,_,Z,$,H),H.stopOnFirstError&&Z.length>0)return}if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let U=Q;if(H.validateRequired&&X.required){for(let _ of X.required)if(!(_ in U)){if(Z.push({path:Y?`${Y}.${_}`:_,message:`Missing required property '${_}'`,expected:"required",rule:"required"}),H.stopOnFirstError)return}}if(X.properties){for(let[_,J]of Object.entries(X.properties))if(_ in U){let G=Y?`${Y}.${_}`:_;if(this.validateObjectAgainstSchema(U[_],J,G,Z,$,H),H.stopOnFirstError&&Z.length>0)return}}if(X.additionalProperties===!1){let _=new Set(Object.keys(X.properties||{}));for(let J of Object.keys(U))if(!_.has(J))$.push({path:Y?`${Y}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Q,X,Y){let Z=[],$=[];for(let H of X)try{let U=this.getValueByPath(Q,H.path),_=this.validateWithRule(U,H,H.path);if(Z.push(..._),Y.stopOnFirstError&&Z.length>0)break}catch(U){Z.push({path:H.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Z.length===0,errors:Z,warnings:$}}validateWithRule(Q,X,Y){let Z=[];if(X.required&&(Q===void 0||Q===null))return Z.push({path:Y,message:X.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),Z;if(Q===void 0||Q===null)return Z;if(X.type){let $=Array.isArray(Q)?"array":typeof Q;if($!==X.type)Z.push({path:Y,message:X.message||`Expected type ${X.type}, got ${$}`,expected:X.type,actual:$,rule:"type"})}if(X.min!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($<X.min)Z.push({path:Y,message:X.message||`Value must be at least ${X.min}`,expected:`>= ${X.min}`,actual:$,rule:"min"})}if(X.max!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($>X.max)Z.push({path:Y,message:X.message||`Value must not exceed ${X.max}`,expected:`<= ${X.max}`,actual:$,rule:"max"})}if(X.pattern&&typeof Q==="string"){if(!X.pattern.test(Q))Z.push({path:Y,message:X.message||`Value does not match pattern ${X.pattern}`,expected:X.pattern.toString(),actual:Q,rule:"pattern"})}if(X.enum&&!X.enum.includes(Q))Z.push({path:Y,message:X.message||`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"});if(X.validator){let $=X.validator(Q);if($)Z.push({path:Y,message:X.message||$,rule:"custom"})}return Z}getValueByPath(Q,X){if(!X)return Q;let Y=X.split("."),Z=Q;for(let $ of Y)if(Z&&typeof Z==="object"&&$ in Z)Z=Z[$];else return;return Z}generateRulesFromInterface(Q){let X=[],Y=Q.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Z of Y){let[,$,H,U]=Z;X.push({path:$,required:!H,type:this.mapTypeScriptType(U)})}return X}mapTypeScriptType(Q){switch(Q.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:rY},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class uX{fileLoader=new XX;envProcessor=new QX;validator=new mX;async loadConfig(Q){let X=Date.now(),{cache:Y,performance:Z,schema:$,validate:H,...U}=Q;try{if(Y?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let _;try{_=await this.loadConfigurationStrategies(U,!0,Y)}catch(J){let G=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(G)throw J;_={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let q=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),A=!q&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),z=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(G&&(z||q))throw J;if(A&&(!G||!z))_={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!G)_={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else _={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if($||H)await this.validateConfiguration(_.config,$,H,U.name);if(Y?.enabled&&_)this.cacheResult(U.name||"",_,Y,U);if(Z?.enabled){let J={operation:"loadConfig",duration:Date.now()-X,configName:U.name,timestamp:new Date};if(Z.onMetrics)Z.onMetrics(J);if(Z.slowThreshold&&J.duration>Z.slowThreshold)m.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);_.metrics=J}return _}catch(_){let J=Date.now()-X;throw m.error(`Configuration loading failed after ${J}ms:`,[_ instanceof Error?_:Error(String(_))]),_}}async loadConfigurationStrategies(Q,X=!1,Y){let{name:Z="",alias:$,cwd:H,configDir:U,defaultConfig:_,checkEnv:J=!0,arrayStrategy:G="replace",verbose:q=!1}=Q,A=H||XQ.cwd(),z=[],W=await this.loadLocalConfiguration(Z,$,A,U,_,G,q,J,Y);if(W)return z.push(...this.getLocalSearchPaths(Z,$,A,U)),this.finalizeResult(W,z,J,Z,q);let I=await this.loadHomeConfiguration(Z,$,_,G,q,J);if(I)return z.push(...this.getHomeSearchPaths(Z,$)),this.finalizeResult(I,z,J,Z,q);let B=await this.loadPackageJsonConfiguration(Z,$,A,_,G,q,J);if(B)return z.push(y(A,"package.json")),this.finalizeResult(B,z,J,Z,q);if(z.push(...this.getAllSearchPaths(Z,$,A,U)),X)throw QQ.configNotFound(Z,z,$);return{...await this.applyEnvironmentVariables(Z,_,J,q),warnings:[`No configuration file found for "${Z}"${$?` or alias "${$}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(Q,X,Y,Z,$,H,U,_,J){let G=_?RQ(Q,$,U):$,q=this.getLocalDirectories(Y,Z);for(let A of q){if(U)m.info(`Searching for configuration in: ${A}`);let z=this.fileLoader.generateConfigPaths(Q,A,X),W=await this.fileLoader.tryLoadFromPaths(z,G,{arrayStrategy:H,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(W){if(U)m.success(`Configuration loaded from: ${W.source.path}`);return W}}return null}async loadHomeConfiguration(Q,X,Y,Z,$,H){if(!Q)return null;let U=H?RQ(Q,Y,$):Y,_=[y(ZQ(),".config",Q),y(ZQ(),".config"),ZQ()];for(let J of _){if($)m.info(`Checking home directory: ${J}`);let G=this.fileLoader.generateConfigPaths(Q,J,X),q=await this.fileLoader.tryLoadFromPaths(G,U,{arrayStrategy:Z,verbose:$});if(q){if($)m.success(`Configuration loaded from home directory: ${q.source.path}`);return q}}return null}async loadPackageJsonConfiguration(Q,X,Y,Z,$,H,U){let _=U?RQ(Q,Z,H):Z;try{let J=y(Y,"package.json");if(!DX(J))return null;let G=await import(J),q=G[Q],A=Q;if(!q&&X)q=G[X],A=X;if(q&&typeof q==="object"&&!Array.isArray(q)){if(H)m.success(`Configuration loaded from package.json: ${A}`);return{config:pX(_,q,$),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(H)m.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables(Q,X,Y,Z){if(!Y||!Q||typeof X!=="object"||X===null||Array.isArray(X))return{config:X,source:{type:"default",priority:10,timestamp:new Date}};return{config:RQ(Q,X,Z),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(Q,X,Y,Z,$){return{config:Q.config,source:Q.source,path:Q.source.path}}async validateConfiguration(Q,X,Y,Z){let $=[];if(Y){let H=Y(Q);if(H)$.push(...H)}if(X){let H=await this.validator.validateConfiguration(Q,X);if(!H.isValid)$.push(...H.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if($.length>0)throw QQ.configValidation(Z||"unknown",$,Z)}checkCache(Q,X){let Y=this.generateCacheKey(Q,X);return zQ.get(Y)||null}cacheResult(Q,X,Y,Z){let $=this.generateCacheKey(Q,Z);zQ.set($,X,void 0,Y.ttl)}generateCacheKey(Q,X){let Y=[Q];if(X.alias)Y.push(`alias:${X.alias}`);if(X.cwd)Y.push(`cwd:${X.cwd}`);if(X.configDir)Y.push(`configDir:${X.configDir}`);if("checkEnv"in X)Y.push(`checkEnv:${X.checkEnv}`);return Y.join("|")}getLocalDirectories(Q,X){return Array.from(new Set([Q,y(Q,"config"),y(Q,".config"),X?y(Q,X):void 0].filter(Boolean)))}getAllSearchPaths(Q,X,Y,Z){let $=[];return $.push(...this.getLocalSearchPaths(Q,X,Y,Z)),$.push(...this.getHomeSearchPaths(Q,X)),$.push(y(Y,"package.json")),$}getLocalSearchPaths(Q,X,Y,Z){let $=this.getLocalDirectories(Y,Z),H=[];for(let U of $)H.push(...this.fileLoader.generateConfigPaths(Q,U,X));return H}getHomeSearchPaths(Q,X){if(!Q)return[];let Y=[y(ZQ(),".config",Q),y(ZQ(),".config"),ZQ()],Z=[];for(let $ of Y)Z.push(...this.fileLoader.generateConfigPaths(Q,$,X));return Z}async loadConfigWithResult(Q){return this.loadConfig(Q)}}function IY(Q){let Y=!(Q.message.includes("EACCES")||Q.message.includes("EPERM")||Q.message.includes("permission denied"))&&(Q.message.includes("syntax")||Q.message.includes("Expected")||Q.message.includes("Unexpected")||Q.message.includes("BuildMessage")),Z=Q.message.includes("Configuration must export a valid object")||Q.message.includes("Configuration file is empty and exports nothing");return Y||Z}async function O0(Q){return a.loadConfig({...Q,__strictErrorHandling:!0})}async function lY(Q){let X="defaultConfig"in Q&&Q.defaultConfig!==void 0?Q.defaultConfig:{},Y="cache"in Q||"performance"in Q||"schema"in Q||"validate"in Q;try{let Z;if(Y)Z=await a.loadConfig(Q);else Z=await a.loadConfig({...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}});return Z?.config??X}catch(Z){let $=Z instanceof Error?Z.name:"UnknownError",H=Z instanceof Error?Z.message:String(Z);if(!($==="ConfigNotFoundError"||$==="ConfigLoadError"||$==="ConfigValidationError"||H.includes("config"))&&Q.verbose)m.warn("Unexpected error loading config, using defaults:",[Z instanceof Error?Z:Error(String(Z))]);let _=Y?{...Q,defaultConfig:X}:{...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Q?Q.checkEnv!==!1:!0)return(await a.applyEnvironmentVariables(_.name||"",X,!0,_.verbose||!1))?.config??X;return X}}async function N0(Q={defaultConfig:{}}){if(typeof Q==="string"){let{cwd:X}=await import("process");try{return(await a.loadConfig({name:Q,cwd:X(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&IY(Y)))return(await a.applyEnvironmentVariables(Q,{},!0,!1)).config;throw Y}}try{return(await a.loadConfig({...Q,cwd:Q.cwd||XQ.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(X){if(X instanceof Error&&(X.name==="ConfigNotFoundError"||X.name==="ConfigLoadError"&&IY(X)))return(await a.applyEnvironmentVariables(Q.name||"",Q.defaultConfig||{},Q.checkEnv!==!1,Q.verbose||!1)).config;throw X}}async function C0(Q,X,Y="replace"){let Z=new XX;try{let $=await Z.loadFromPath(Q,X,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return $?$.config:null}catch{return null}}function RQ(Q,X,Y=!1){let Z=new QX,$=Q.toUpperCase().replace(/[^A-Z0-9]/g,"_");function H(U,_=[]){let J={...U};for(let[G,q]of Object.entries(U)){let A=[..._,G],z=[`${$}_${A.join("_").toUpperCase()}`,`${$}_${A.map((B)=>B.toUpperCase()).join("")}`,`${$}_${A.map((B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],W,I;for(let B of z)if(W=XQ.env[B],W!==void 0){I=B;break}if(W!==void 0&&I)if(typeof q==="boolean")J[G]=["true","1","yes"].includes(W.toLowerCase());else if(typeof q==="number"){let B=Number(W);if(!Number.isNaN(B))J[G]=B}else if(Array.isArray(q))try{J[G]=JSON.parse(W)}catch{J[G]=W.split(",").map((B)=>B.trim())}else J[G]=W;else if(q&&typeof q==="object"&&!Array.isArray(q))J[G]=H(q,A)}return J}return H(X)}function x0(Q){let X=y(XQ.cwd(),Q.configDir),Y=y(XQ.cwd(),Q.generatedDir),Z=y(Y,"config-types.ts");if(!DX(rX(Z)))jZ(rX(Z),{recursive:!0,mode:511});let $=DX(X)?IZ(X).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],H=`// Generated by bunfig v${U8}
|
|
32
|
+
export type ConfigNames = ${$.length?`'${$.join("' | '")}'`:"string"}
|
|
33
|
+
`;FZ(Z,H,{mode:438})}function k0(Q){let X=null,Y=null,Z=()=>{if(!Y)Y=lY(Q).then((H)=>{return X=H,H},(H)=>{let U="defaultConfig"in Q?Q.defaultConfig:{};if(X=U,"verbose"in Q&&Q.verbose)m.warn("Config loading failed, using defaults:",[H instanceof Error?H:Error(String(H))]);return U});return Y},$="defaultConfig"in Q?Q.defaultConfig:{};return X=$,Z(),new Proxy({},{get(H,U){if(X)return X[U];let _=$[U];return Z(),_},has(H,U){return U in(X||$)},ownKeys(){return Object.keys(X||$)},getOwnPropertyDescriptor(H,U){return Object.getOwnPropertyDescriptor(X||$,U)},set(H,U,_){if(!X)X={...$};return X[U]=_,!0}})}function P0(Q){let X=WY(lZ.cwd(),Q?.configDir||"./config");function Y(){if(!gZ(X))return[];let $=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),H=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=cZ(X).filter((J)=>$.has(WX(J))).map((J)=>({base:J.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:J})),_=new Map;for(let{base:J,file:G}of U){let q=WX(G).toLowerCase(),A=_.get(J);if(!A){_.set(J,G);continue}let z=WX(A).toLowerCase();if(H.indexOf(q)<H.indexOf(z))_.set(J,G)}return Array.from(_.entries()).map(([J,G])=>({base:J,file:G})).sort((J,G)=>J.base.localeCompare(G.base))}function Z(){let $=Y(),H=$.map((G)=>G.base),U=H.length?H.map((G)=>`'${G}'`).join(" | "):"string",_=$.length?`{
|
|
34
|
+
${$.map((G)=>{let q=WY(X,G.file).replace(/\\/g,"/");return` '${G.base}': typeof import('${q}').default`}).join(`,
|
|
35
35
|
`)}
|
|
36
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${
|
|
37
|
-
export type ConfigByName = ${
|
|
36
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${U}
|
|
37
|
+
export type ConfigByName = ${_}
|
|
38
38
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
39
39
|
export type ConfigOf = Config
|
|
40
|
-
`}return{name:"bunfig-plugin",setup(J){J.onResolve({filter:/^virtual:bunfig-types$/},(Y)=>{return{path:Y.path,namespace:"bunfig-virtual"}}),J.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Z(),loader:"ts"}})}}}var J9,c0,Q8,Y9,$J,XJ,TQ,P8,m$,u,S,QJ,kQ,ZJ,yQ,JJ,YJ,P$,GJ,hQ,vQ,b$,HJ,UJ,qJ,zJ,b8,G9,_J,p,WJ,AJ,fQ,T8,u$,y,V,BJ,gQ,KJ,dQ,RJ,FJ,T$,jJ,mQ,uQ,MJ,k$,LJ,wJ,IJ,DJ,VJ,k8,H9,OJ,NJ="0.15.6",t,c8,$8,p$,c$,l8,l$,n$,X8,i$,o$,I0,U9,q9,Y0,M0,z9,_9,EJ=E7(async()=>{J9=import.meta.require,c0=new s$,Q8=new t$,Y9={createKey:S7,isEquivalent:C7,estimateMemoryUsage:x7},$J=f8(g$.cwd(),"config"),XJ=f8(g$.cwd(),"src/generated"),TQ=v8.env.CLARITY_LOG_DIR||cZ(T7(),"logs"),P8={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:TQ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},m$=await k7(),u={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},S=u,QJ=u.red,kQ=u.green,ZJ=u.yellow,yQ=u.blue,JJ=u.magenta,YJ=u.cyan,P$=u.white,GJ=u.gray,hQ=u.bgRed,vQ=u.bgYellow,b$=u.bold,HJ=u.dim,UJ=u.italic,qJ=u.underline,zJ=u.reset,b8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},G9={debug:"\uD83D\uDD0D",info:yQ("\u2139"),success:kQ("\u2713"),warning:vQ(P$(b$(" WARN "))),error:hQ(P$(b$(" ERROR ")))},_J=new m8("stacks"),p=new m8("bunfig",{showTags:!0}),WJ=i(e0.cwd(),"config"),AJ=i(e0.cwd(),"src/generated"),fQ=h8.env.CLARITY_LOG_DIR||uZ(f7(),"logs"),T8={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:fQ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},u$=await g7(),y={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},V=y,BJ=y.red,gQ=y.green,KJ=y.yellow,dQ=y.blue,RJ=y.magenta,FJ=y.cyan,T$=y.white,jJ=y.gray,mQ=y.bgRed,uQ=y.bgYellow,MJ=y.bgGray,k$=y.bold,LJ=y.dim,wJ=y.italic,IJ=y.underline,DJ=y.strikethrough,VJ=y.reset,k8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},H9={debug:"\uD83D\uDD0D",info:dQ("\u2139"),success:gQ("\u2713"),warning:uQ(T$(k$(" WARN "))),error:mQ(T$(k$(" ERROR ")))},OJ=new p8("stacks"),t=class extends Error{timestamp;context;constructor(X,Q={}){super(X);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Q,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 X=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Q,Z])=>`${Q}: ${Z}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${X}`}},c8=class extends t{code="CONFIG_NOT_FOUND";constructor(X,Q,Z){let J=Z?` or alias "${Z}"`:"";super(`Configuration "${X}"${J} not found`,{configName:X,alias:Z,searchPaths:Q,searchPathCount:Q.length})}},$8=class extends t{code="CONFIG_LOAD_ERROR";constructor(X,Q,Z){super(`Failed to load configuration from "${X}": ${Q.message}`,{configPath:X,configName:Z,originalError:Q.name,originalMessage:Q.message});this.cause=Q}},p$=class extends t{code="CONFIG_VALIDATION_ERROR";constructor(X,Q,Z){super(`Configuration validation failed for "${X}"`,{configPath:X,configName:Z,validationErrors:Q,errorCount:Q.length})}},c$=class extends t{code="CONFIG_MERGE_ERROR";constructor(X,Q,Z,J){super(`Failed to merge configuration from "${X}" with "${Q}": ${Z.message}`,{sourcePath:X,targetPath:Q,configName:J,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},l8=class extends t{code="ENV_VAR_ERROR";constructor(X,Q,Z,J){super(`Failed to parse environment variable "${X}" with value "${Q}" as ${Z}`,{envKey:X,envValue:Q,expectedType:Z,configName:J})}},l$=class extends t{code="FILE_SYSTEM_ERROR";constructor(X,Q,Z){super(`File system ${X} failed for "${Q}": ${Z.message}`,{operation:X,path:Q,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},n$=class extends t{code="TYPE_GENERATION_ERROR";constructor(X,Q,Z){super(`Failed to generate types from "${X}" to "${Q}": ${Z.message}`,{configDir:X,outputPath:Q,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},X8=class extends t{code="SCHEMA_VALIDATION_ERROR";constructor(X,Q,Z){super(`Schema validation failed${Z?` for config "${Z}"`:""}`,{schemaPath:X,configName:Z,validationErrors:Q,errorCount:Q.length})}},i$=class extends t{code="BROWSER_CONFIG_ERROR";constructor(X,Q,Z,J){super(`Failed to fetch configuration from "${X}": ${Q} ${Z}`,{endpoint:X,status:Q,statusText:Z,configName:J})}},o$=class extends t{code="PLUGIN_ERROR";constructor(X,Q,Z){super(`Plugin "${X}" failed during ${Q}: ${Z.message}`,{pluginName:X,operation:Q,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},I0={configNotFound($,X,Q){return new c8($,X,Q)},configLoad($,X,Q){return new $8($,X,Q)},configValidation($,X,Q){return new p$($,X,Q)},configMerge($,X,Q,Z){return new c$($,X,Q,Z)},envVar($,X,Q,Z){return new l8($,X,Q,Z)},fileSystem($,X,Q){return new l$($,X,Q)},typeGeneration($,X,Q){return new n$($,X,Q)},schemaValidation($,X,Q){return new X8($,X,Q)},browserConfig($,X,Q,Z){return new i$($,X,Q,Z)},plugin($,X,Q){return new o$($,X,Q)}},U9={replace:"replace",concat:"concat",smart:"smart"},q9=/^https?:\/\//,Y0=new p8("bunfig",{showTags:!0}),M0=new ZX,z9=o(S0.cwd(),"config"),_9=o(S0.cwd(),"src/generated")});function SJ($,X={}){let Q=g8.cwd();while(Q.includes("storage"))Q=OQ(Q,"..");let Z=OQ(Q,$||"");if(X?.relative)return A7(g8.cwd(),Z);return Z}var CJ=g8.env.CLARITY_LOG_DIR||W7(SJ(),"logs"),W9={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:CJ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},n8={...W9},DH=(async()=>{try{let{loadConfig:$}=await EJ().then(()=>rQ),X=await $({name:"clarity",alias:"logging",defaultConfig:W9,cwd:g8.cwd()});if(X)Object.assign(n8,X)}catch{}return n8})();function h(){if(j0.env.NODE_ENV==="test"||j0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function xJ(){if(j0.env.NODE_ENV==="test"||j0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof j0<"u"){let $=j0.type;if($==="renderer"||$==="worker")return!1;return!!(j0.versions&&(j0.versions.node||j0.versions.bun))}return!1}class A9{async format($){let X=await xJ(),Q=await this.getMetadata(X);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Q})}async getMetadata($){if($){let{hostname:X}=await import("os");return{pid:p0.pid,hostname:X(),environment:p0.env.NODE_ENV||"development",platform:p0.platform,version:p0.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:p0.env.NODE_ENV||p0.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var g={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},O=g,VH=g.red,PJ=g.green,OH=g.yellow,bJ=g.blue,NH=g.magenta,EH=g.cyan,pQ=g.white,SH=g.gray,TJ=g.bgRed,kJ=g.bgYellow,CH=g.bgGray,cQ=g.bold,xH=g.dim,PH=g.italic,bH=g.underline,TH=g.strikethrough,kH=g.reset,y$={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},yJ={debug:"\uD83D\uDD0D",info:bJ("\u2139"),success:PJ("\u2713"),warning:kJ(pQ(cQ(" WARN "))),error:TJ(pQ(cQ(" ERROR ")))};class t8{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($,X={}){this.name=$,this.config={...n8},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new A9,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??D.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Q={...X},Z=X.timestamp!==void 0;if(Z)delete Q.timestamp;if(this.config={...this.config,...Q,timestamp:Z||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let J=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=J,this.keys.set(J,Y),this.encryptionKeys.set(J,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let X={debug:0,info:1,success:2,warning:3,error:4},Q=this.fingersCrossedConfig.activationLevel??"error";return X[$]>=X[Q]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...y$,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...y$};return{...y$,...$.fingersCrossed}}normalizeOptions($){let X={format:"json",level:"info",logDirectory:n8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Q={...X,...Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))};if(!Q.level||!["debug","info","success","warning","error"].includes(Q.level))Q.level=X.level;return Q}shouldWriteToFile(){return!h()&&this.config.writeToFile===!0}async writeToFile($){let Q=(async()=>{let J,Y=0,G=3,H=1000;while(Y<G)try{try{try{await j7(this.config.logDirectory,CQ.F_OK|CQ.W_OK)}catch(q){if(q instanceof Error&&"code"in q)if(q.code==="ENOENT")await M7(this.config.logDirectory,{recursive:!0,mode:493});else if(q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw q;else throw q}}catch(q){throw console.error("Debug: [writeToFile] Failed to create log directory:",q),q}let U=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:K0.from($);try{if(!D8(this.currentLogFile))await x$(this.currentLogFile,"",{mode:420});if(J=SQ(this.currentLogFile,"a",420),F7(J,U,{flag:"a"}),EQ(J),J!==void 0)C$(J),J=void 0;if((await m0(this.currentLogFile)).size===0){if(await x$(this.currentLogFile,U,{flag:"w",mode:420}),(await m0(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(q){let z=q;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(Y<G-1){let _=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${G}:`,_);let A=H*2**Y;await new Promise((W)=>setTimeout(W,A)),Y++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(J!==void 0)try{C$(J)}catch(q){console.error("Debug: [writeToFile] Error closing file descriptor:",q)}}}catch(U){if(Y===G-1){let z=U,_=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",_),U}Y++;let q=H*2**(Y-1);await new Promise((z)=>setTimeout(z,q))}})();this.pendingOperations.push(Q);let Z=this.pendingOperations.length-1;try{await Q}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(Z,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 u0(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 u0(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return u0(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(h())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,X;switch($.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Q=typeof X.interval==="number"?X.interval:60,Z=Math.max(Q,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Q=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Q,this.keys.set(Q,Z),this.encryptionKeys.set(Q,{key:Z,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,H],[,U])=>U.createdAt.getTime()-H.createdAt.getTime()),Y=typeof X.maxKeys==="number"?X.maxKeys:1,G=Math.max(1,Y);if(J.length>G)for(let[H]of J.slice(G))this.encryptionKeys.delete(H),this.keys.delete(H)}generateKeyId(){return S$(16).toString("hex")}generateKey(){return S$(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:X}=this.getCurrentKey(),Q=S$(16),Z=B7("aes-256-gcm",X,Q),J=K0.isBuffer($)?$:K0.from($,"utf8"),Y=Z.update(J),G=Z.final(),H=Y.length+G.length,U=Z.getAuthTag(),q=K0.allocUnsafe(16+H+16);return Q.copy(q,0),Y.copy(q,16),G.copy(q,16+Y.length),U.copy(q,16+H),{encrypted:q,iv:Q}}async compressData($){return new Promise((X,Q)=>{let Z=PQ(),J=[];Z.on("data",(Y)=>J.push(Y)),Z.on("end",()=>X(K0.from(K0.concat(J)))),Z.on("error",Q),Z.write($),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...$,...X}}return $}async rotateLog(){if(h())return;if(!this.shouldWriteToFile())return;let $=await m0(this.currentLogFile).catch(()=>null);if(!$)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&$.size>=X.maxSize){let Q=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let J=await V8(this.config.logDirectory),Y=J.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,q)=>{let z=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(q.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),G=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,H=`${Q}.${G}`;if(await m0(Q).catch(()=>null))try{if(await xQ(Q,H),X.compress)try{let U=`${H}.gz`;await this.compressLogFile(H,U),await O8(H)}catch(U){console.error("Error compressing rotated file:",U)}if(Y.length===0&&!J.some((U)=>U.endsWith(".log.1")))try{let U=`${Q}.1`;await x$(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let J=new Date().toISOString().replace(/[:.]/g,"-"),Y=Q.replace(/\.log$/,`-${J}.log`);if(await m0(Q).catch(()=>null))await xQ(Q,Y)}if(this.currentLogFile=Z,X.maxFiles){let Y=(await V8(this.config.logDirectory)).filter((G)=>G.startsWith(this.name)).sort((G,H)=>H.localeCompare(G));for(let G of Y.slice(X.maxFiles))await O8(u0(this.config.logDirectory,G))}}}async compressLogFile($,X){let Q=NQ($),Z=R7(X),J=PQ();await I7(Q,J,Z)}async handleFingersCrossedBuffer($,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Q of this.logBuffer){let Z=await this.formatter.format(Q);if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(X);console.log(X)}}shouldLog($){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[$]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),D8(this.currentLogFile))try{let $=SQ(this.currentLogFile,"r+");EQ($),C$($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!h()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await V8(this.config.logDirectory)).filter((Q)=>(Q.includes("temp")||Q.includes(".tmp"))&&Q.includes(this.name));for(let Q of X)try{await O8(u0(this.config.logDirectory,Q))}catch(Z){console.error(`Failed to delete temp file ${Q}:`,Z)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?O.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||h())return!1;let $=typeof D.env.NO_COLOR<"u",X=D.env.FORCE_COLOR==="0";if($||X)return!1;return!!(typeof D.stderr<"u"&&D.stderr.isTTY||typeof D.stdout<"u"&&D.stdout.isTTY)}formatConsoleMessage($){let{timestamp:X,icon:Q="",tag:Z="",message:J,level:Y,showTimestamp:G=!0}=$,H=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(G)W.push(X);if(Y==="warning")W.push("WARN");else if(Y==="error")W.push("ERROR");else if(Q)W.push(Q.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push(J),W.join(" ")}let U=D.stdout.columns||120,q="";if(Y==="warning"||Y==="error")q=`${Q} ${J}`;else if(Y==="info"||Y==="success")q=`${Q} ${Z} ${J}`;else q=`${Q} ${Z} ${O.cyan(J)}`;if(!G)return q.trim();let z=H(q).trim().length,_=H(X).length,A=Math.max(1,U-2-z-_);return`${q.trim()}${" ".repeat(A)}${X}`}formatMessage($,X){if(X.length===1&&Array.isArray(X[0]))return $.replace(/\{(\d+)\}/g,(Y,G)=>{let H=Number.parseInt(G,10);return H<X[0].length?String(X[0][H]):Y});let Q=/%([sdijfo%])/g,Z=0,J=$.replace(Q,(Y,G)=>{if(G==="%")return"%";if(Z>=X.length)return Y;let H=X[Z++];switch(G){case"s":return String(H);case"d":case"i":return Number(H).toString();case"j":case"o":return JSON.stringify(H,null,2);default:return Y}});if(Z<X.length)J+=` ${X.slice(Z).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return J}formatMarkdown($){if(!$)return $;let X=$;return X=X.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Q,Z,J)=>{let Y=O.underline(O.blue(Z)),G=this.toAbsoluteFilePath(J);if(G&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let H=`file://${encodeURI(G)}`,U="\x1B]8;;",q="\x1B\\";return`\x1B]8;;${H}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${J}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),X=X.replace(/`([^`]+)`/g,(Q,Z)=>O.bgGray(Z)),X=X.replace(/\*\*([^*]+)\*\*/g,(Q,Z)=>O.bold(Z)),X=X.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Q,Z)=>O.italic(Z)),X=X.replace(/(?<!_)_([^_]+)_(?!_)/g,(Q,Z)=>O.italic(Z)),X=X.replace(/~([^~]+)~/g,(Q,Z)=>O.strikethrough(Z)),X}supportsHyperlinks(){if(h())return!1;let $=D.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let X=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(X)&&X>=5000)return!0;return!1}toAbsoluteFilePath($){try{let X=$;if(X.startsWith("file://"))X=X.replace(/^file:\/\//,"");if(X.startsWith("~")){let Q=D.env.HOME||"";if(Q)X=X.replace(/^~(?=$|\/)/,Q)}if(L7(X)||X.startsWith("./")||X.startsWith("../"))X=w7(X);else return null;return D8(X)?X:null}catch{return null}}buildOutputTexts($){let X=this.shouldStyleConsole()?this.formatMarkdown($):$,Q=$.replace(this.ANSI_PATTERN,"");return{consoleText:X,fileText:Q}}async log($,X,...Q){if(!this.shouldLog($))return;let Z=new Date,J=this.formatConsoleTimestamp(Z),Y=this.formatFileTimestamp(Z),G,H;if(X instanceof Error)G=X.message,H=X.stack;else G=this.formatMessage(X,Q);let{consoleText:U,fileText:q}=this.buildOutputTexts(G);if(this.shouldStyleConsole()){let _=this.options.showIcons===!1?"":yJ[$],A=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",W;switch($){case"debug":W=this.formatConsoleMessage({timestamp:J,icon:_,tag:A,message:O.gray(U),level:$}),console.error(W);break;case"info":W=this.formatConsoleMessage({timestamp:J,icon:_,tag:A,message:U,level:$}),console.warn(W);break;case"success":W=this.formatConsoleMessage({timestamp:J,icon:_,tag:A,message:O.green(U),level:$}),console.error(W);break;case"warning":W=this.formatConsoleMessage({timestamp:J,icon:_,tag:A,message:U,level:$}),console.warn(W);break;case"error":if(W=this.formatConsoleMessage({timestamp:J,icon:_,tag:A,message:U,level:$}),console.error(W),H){let K=H.split(`
|
|
41
|
-
`);for(let B of
|
|
42
|
-
`;if(
|
|
43
|
-
`;if(
|
|
44
|
-
`);if(this[
|
|
45
|
-
`,
|
|
46
|
-
`),
|
|
47
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
48
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
49
|
-
`)}finishProgressBar(
|
|
40
|
+
`}return{name:"bunfig-plugin",setup($){$.onResolve({filter:/^virtual:bunfig-types$/},(H)=>{return{path:H.path,namespace:"bunfig-virtual"}}),$.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Z(),loader:"ts"}})}}}var nY,zQ,jQ,iY,b0,y0,FY,yQ,EX,C,M,v0,MY,d0,DY,h0,f0,wX,p0,SY,VY,LX,m0,u0,g0,c0,vQ,sY,l0,x,n0,i0,EY,dQ,TX,E,L,s0,TY,o0,OY,t0,r0,KX,a0,NY,CY,e0,jX,Q8,X8,Y8,Z8,$8,hQ,oY,H8,U8="0.15.6",v,sQ,LQ,OX,NX,oQ,CX,xX,KQ,kX,PX,QQ,tY,rY,m,a,aY,eY,J8=J0(async()=>{nY=import.meta.require,zQ=new vX,jQ=new dX,iY={createKey:_0,isEquivalent:G0,estimateMemoryUsage:q0},b0=uQ(SX.cwd(),"config"),y0=uQ(SX.cwd(),"src/generated"),FY=mQ.env.CLARITY_LOG_DIR||SZ(z0(),"logs"),yQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:FY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},EX=await B0(),C={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,reset:"\x1B[0m"},M=C,v0=C.red,MY=C.green,d0=C.yellow,DY=C.blue,h0=C.magenta,f0=C.cyan,wX=C.white,p0=C.gray,SY=C.bgRed,VY=C.bgYellow,LX=C.bold,m0=C.dim,u0=C.italic,g0=C.underline,c0=C.reset,vQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},sY={debug:"\uD83D\uDD0D",info:DY("\u2139"),success:MY("\u2713"),warning:VY(wX(LX(" WARN "))),error:SY(wX(LX(" ERROR ")))},l0=new lQ("stacks"),x=new lQ("bunfig",{showTags:!0}),n0=b(wQ.cwd(),"config"),i0=b(wQ.cwd(),"src/generated"),EY=pQ.env.CLARITY_LOG_DIR||MZ(K0(),"logs"),dQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:EY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},TX=await j0(),E={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bgGray:(Q)=>`\x1B[100m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,strikethrough:(Q)=>`\x1B[9m${Q}\x1B[0m`,reset:"\x1B[0m"},L=E,s0=E.red,TY=E.green,o0=E.yellow,OY=E.blue,t0=E.magenta,r0=E.cyan,KX=E.white,a0=E.gray,NY=E.bgRed,CY=E.bgYellow,e0=E.bgGray,jX=E.bold,Q8=E.dim,X8=E.italic,Y8=E.underline,Z8=E.strikethrough,$8=E.reset,hQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},oY={debug:"\uD83D\uDD0D",info:OY("\u2139"),success:TY("\u2713"),warning:CY(KX(jX(" WARN "))),error:NY(KX(jX(" ERROR ")))},H8=new iQ("stacks"),v=class extends Error{timestamp;context;constructor(X,Y={}){super(X);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,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 X=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,Z])=>`${Y}: ${Z}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${X}`}},sQ=class extends v{code="CONFIG_NOT_FOUND";constructor(X,Y,Z){let $=Z?` or alias "${Z}"`:"";super(`Configuration "${X}"${$} not found`,{configName:X,alias:Z,searchPaths:Y,searchPathCount:Y.length})}},LQ=class extends v{code="CONFIG_LOAD_ERROR";constructor(X,Y,Z){super(`Failed to load configuration from "${X}": ${Y.message}`,{configPath:X,configName:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},OX=class extends v{code="CONFIG_VALIDATION_ERROR";constructor(X,Y,Z){super(`Configuration validation failed for "${X}"`,{configPath:X,configName:Z,validationErrors:Y,errorCount:Y.length})}},NX=class extends v{code="CONFIG_MERGE_ERROR";constructor(X,Y,Z,$){super(`Failed to merge configuration from "${X}" with "${Y}": ${Z.message}`,{sourcePath:X,targetPath:Y,configName:$,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},oQ=class extends v{code="ENV_VAR_ERROR";constructor(X,Y,Z,$){super(`Failed to parse environment variable "${X}" with value "${Y}" as ${Z}`,{envKey:X,envValue:Y,expectedType:Z,configName:$})}},CX=class extends v{code="FILE_SYSTEM_ERROR";constructor(X,Y,Z){super(`File system ${X} failed for "${Y}": ${Z.message}`,{operation:X,path:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},xX=class extends v{code="TYPE_GENERATION_ERROR";constructor(X,Y,Z){super(`Failed to generate types from "${X}" to "${Y}": ${Z.message}`,{configDir:X,outputPath:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},KQ=class extends v{code="SCHEMA_VALIDATION_ERROR";constructor(X,Y,Z){super(`Schema validation failed${Z?` for config "${Z}"`:""}`,{schemaPath:X,configName:Z,validationErrors:Y,errorCount:Y.length})}},kX=class extends v{code="BROWSER_CONFIG_ERROR";constructor(X,Y,Z,$){super(`Failed to fetch configuration from "${X}": ${Y} ${Z}`,{endpoint:X,status:Y,statusText:Z,configName:$})}},PX=class extends v{code="PLUGIN_ERROR";constructor(X,Y,Z){super(`Plugin "${X}" failed during ${Y}: ${Z.message}`,{pluginName:X,operation:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},QQ={configNotFound(Q,X,Y){return new sQ(Q,X,Y)},configLoad(Q,X,Y){return new LQ(Q,X,Y)},configValidation(Q,X,Y){return new OX(Q,X,Y)},configMerge(Q,X,Y,Z){return new NX(Q,X,Y,Z)},envVar(Q,X,Y,Z){return new oQ(Q,X,Y,Z)},fileSystem(Q,X,Y){return new CX(Q,X,Y)},typeGeneration(Q,X,Y){return new xX(Q,X,Y)},schemaValidation(Q,X,Y){return new KQ(Q,X,Y)},browserConfig(Q,X,Y,Z){return new kX(Q,X,Y,Z)},plugin(Q,X,Y){return new PX(Q,X,Y)}},tY={replace:"replace",concat:"concat",smart:"smart"},rY=/^https?:\/\//,m=new iQ("bunfig",{showTags:!0}),a=new uX,aY=y(XQ.cwd(),"config"),eY=y(XQ.cwd(),"src/generated")});function _8(Q,X={}){let Y=gQ.cwd();while(Y.includes("storage"))Y=zY(Y,"..");let Z=zY(Y,Q||"");if(X?.relative)return iZ(gQ.cwd(),Z);return Z}var G8=gQ.env.CLARITY_LOG_DIR||nZ(_8(),"logs"),QZ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:G8,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},tQ={...QZ},_$=(async()=>{try{let{loadConfig:Q}=await J8().then(()=>dY),X=await Q({name:"clarity",alias:"logging",defaultConfig:QZ,cwd:gQ.cwd()});if(X)Object.assign(tQ,X)}catch{}return tQ})();function T(){if(r.env.NODE_ENV==="test"||r.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function q8(){if(r.env.NODE_ENV==="test"||r.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof r<"u"){let Q=r.type;if(Q==="renderer"||Q==="worker")return!1;return!!(r.versions&&(r.versions.node||r.versions.bun))}return!1}class XZ{async format(Q){let X=await q8(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:WQ.pid,hostname:X(),environment:WQ.env.NODE_ENV||"development",platform:WQ.platform,version:WQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:WQ.env.NODE_ENV||WQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var O={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bgGray:(Q)=>`\x1B[100m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,strikethrough:(Q)=>`\x1B[9m${Q}\x1B[0m`,reset:"\x1B[0m"},j=O,G$=O.red,A8=O.green,q$=O.yellow,W8=O.blue,A$=O.magenta,W$=O.cyan,xY=O.white,z$=O.gray,z8=O.bgRed,B8=O.bgYellow,B$=O.bgGray,kY=O.bold,R$=O.dim,w$=O.italic,L$=O.underline,K$=O.strikethrough,j$=O.reset,IX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},R8={debug:"\uD83D\uDD0D",info:W8("\u2139"),success:A8("\u2713"),warning:B8(xY(kY(" WARN "))),error:z8(xY(kY(" ERROR ")))};class YX{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(Q,X={}){this.name=Q,this.config={...tQ},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new XZ,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??w.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),H=this.generateKey();this.currentKeyId=$,this.keys.set($,H),this.encryptionKeys.set($,{key:H,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;let X={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return X[Q]>=X[Y]}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...IX,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...IX};return{...IX,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:tQ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}shouldWriteToFile(){return!T()&&this.config.writeToFile===!0}async writeToFile(Q){let Y=(async()=>{let $,H=0,U=3,_=1000;while(H<U)try{try{try{await aZ(this.config.logDirectory,LY.F_OK|LY.W_OK)}catch(G){if(G instanceof Error&&"code"in G)if(G.code==="ENOENT")await eZ(this.config.logDirectory,{recursive:!0,mode:493});else if(G.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw G;else throw G}}catch(G){throw console.error("Debug: [writeToFile] Failed to create log directory:",G),G}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:s.from(Q);try{if(!TQ(this.currentLogFile))await RX(this.currentLogFile,"",{mode:420});if($=wY(this.currentLogFile,"a",420),rZ($,J,{flag:"a"}),RY($),$!==void 0)BX($),$=void 0;if((await qQ(this.currentLogFile)).size===0){if(await RX(this.currentLogFile,J,{flag:"w",mode:420}),(await qQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(G){let q=G;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if(H<U-1){let A=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${U}:`,A);let z=_*2**H;await new Promise((W)=>setTimeout(W,z)),H++;continue}}if(q?.code&&["ENOSPC","EDQUOT"].includes(q.code))throw Error(`Disk quota exceeded or no space left on device: ${q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",q),q}finally{if($!==void 0)try{BX($)}catch(G){console.error("Debug: [writeToFile] Error closing file descriptor:",G)}}}catch(J){if(H===U-1){let q=J,A=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}H++;let G=_*2**(H-1);await new Promise((q)=>setTimeout(q,G))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,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 AQ(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 AQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return AQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(T())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,_],[,J])=>J.createdAt.getTime()-_.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,U=Math.max(1,H);if($.length>U)for(let[_]of $.slice(U))this.encryptionKeys.delete(_),this.keys.delete(_)}generateKeyId(){return zX(16).toString("hex")}generateKey(){return zX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=zX(16),Z=sZ("aes-256-gcm",X,Y),$=s.isBuffer(Q)?Q:s.from(Q,"utf8"),H=Z.update($),U=Z.final(),_=H.length+U.length,J=Z.getAuthTag(),G=s.allocUnsafe(16+_+16);return Y.copy(G,0),H.copy(G,16),U.copy(G,16+H.length),J.copy(G,16+_),{encrypted:G,iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=jY(),$=[];Z.on("data",(H)=>$.push(H)),Z.on("end",()=>X(s.from(s.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(T())return;if(!this.shouldWriteToFile())return;let Q=await qQ(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await OQ(this.config.logDirectory),H=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,G)=>{let q=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(G.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),U=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,_=`${Y}.${U}`;if(await qQ(Y).catch(()=>null))try{if(await KY(Y,_),X.compress)try{let J=`${_}.gz`;await this.compressLogFile(_,J),await NQ(_)}catch(J){console.error("Error compressing rotated file:",J)}if(H.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await RX(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await qQ(Y).catch(()=>null))await KY(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await OQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,_)=>_.localeCompare(U));for(let U of H.slice(X.maxFiles))await NQ(AQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=BY(Q),Z=tZ(X),$=jY();await Y0(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(X);console.log(X)}}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),TQ(this.currentLogFile))try{let Q=wY(this.currentLogFile,"r+");RY(Q),BX(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!T()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await OQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await NQ(AQ(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.shouldStyleConsole()?j.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||T())return!1;let Q=typeof w.env.NO_COLOR<"u",X=w.env.FORCE_COLOR==="0";if(Q||X)return!1;return!!(typeof w.stderr<"u"&&w.stderr.isTTY||typeof w.stdout<"u"&&w.stdout.isTTY)}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:H,showTimestamp:U=!0}=Q,_=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(U)W.push(X);if(H==="warning")W.push("WARN");else if(H==="error")W.push("ERROR");else if(Y)W.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let J=w.stdout.columns||120,G="";if(H==="warning"||H==="error")G=`${Y} ${$}`;else if(H==="info"||H==="success")G=`${Y} ${Z} ${$}`;else G=`${Y} ${Z} ${j.cyan($)}`;if(!U)return G.trim();let q=_(G).trim().length,A=_(X).length,z=Math.max(1,J-2-q-A);return`${G.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,U)=>{let _=Number.parseInt(U,10);return _<X[0].length?String(X[0][_]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,U)=>{if(U==="%")return"%";if(Z>=X.length)return H;let _=X[Z++];switch(U){case"s":return String(_);case"d":case"i":return Number(_).toString();case"j":case"o":return JSON.stringify(_,null,2);default:return H}});if(Z<X.length)$+=` ${X.slice(Z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return $}formatMarkdown(Q){if(!Q)return Q;let X=Q;return X=X.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,Z,$)=>{let H=j.underline(j.blue(Z)),U=this.toAbsoluteFilePath($);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let _=`file://${encodeURI(U)}`,J="\x1B]8;;",G="\x1B\\";return`\x1B]8;;${_}\x1B\\${H}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${$}\x1B\\${H}\x1B]8;;\x1B\\`;return H}),X=X.replace(/`([^`]+)`/g,(Y,Z)=>j.bgGray(Z)),X=X.replace(/\*\*([^*]+)\*\*/g,(Y,Z)=>j.bold(Z)),X=X.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,Z)=>j.italic(Z)),X=X.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,Z)=>j.italic(Z)),X=X.replace(/~([^~]+)~/g,(Y,Z)=>j.strikethrough(Z)),X}supportsHyperlinks(){if(T())return!1;let Q=w.env;if(!Q)return!1;if(Q.TERM_PROGRAM==="iTerm.app"||Q.TERM_PROGRAM==="vscode"||Q.TERM_PROGRAM==="WezTerm")return!0;if(Q.WT_SESSION)return!0;if(Q.TERM==="xterm-kitty")return!0;let X=Q.VTE_VERSION?Number.parseInt(Q.VTE_VERSION,10):0;if(!Number.isNaN(X)&&X>=5000)return!0;return!1}toAbsoluteFilePath(Q){try{let X=Q;if(X.startsWith("file://"))X=X.replace(/^file:\/\//,"");if(X.startsWith("~")){let Y=w.env.HOME||"";if(Y)X=X.replace(/^~(?=$|\/)/,Y)}if(Q0(X)||X.startsWith("./")||X.startsWith("../"))X=X0(X);else return null;return TQ(X)?X:null}catch{return null}}buildOutputTexts(Q){let X=this.shouldStyleConsole()?this.formatMarkdown(Q):Q,Y=Q.replace(this.ANSI_PATTERN,"");return{consoleText:X,fileText:Y}}async log(Q,X,...Y){if(!this.shouldLog(Q))return;let Z=new Date,$=this.formatConsoleTimestamp(Z),H=this.formatFileTimestamp(Z),U,_;if(X instanceof Error)U=X.message,_=X.stack;else U=this.formatMessage(X,Y);let{consoleText:J,fileText:G}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let A=this.options.showIcons===!1?"":R8[Q],z=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",W;switch(Q){case"debug":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:j.gray(J),level:Q}),console.error(W);break;case"info":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:J,level:Q}),console.warn(W);break;case"success":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:j.green(J),level:Q}),console.error(W);break;case"warning":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:J,level:Q}),console.warn(W);break;case"error":if(W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:J,level:Q}),console.error(W),_){let I=_.split(`
|
|
41
|
+
`);for(let B of I)if(B.trim()&&!B.includes(U))console.error(this.formatConsoleMessage({timestamp:$,message:j.gray(` ${B}`),level:Q,showTimestamp:!1}))}break}}else if(!T()){if(console.error(`${H} ${this.environment}.${Q.toUpperCase()}: ${U}`),_)console.error(_)}let q=`${H} ${this.environment}.${Q.toUpperCase()}: ${G}
|
|
42
|
+
`;if(_)q+=`${_}
|
|
43
|
+
`;if(q=q.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(q)}progress(Q,X=""){let Y={update:(_,J)=>{},finish:(_)=>{},interrupt:(_,J)=>{}};if(!this.enabled)return Y;let Z=30;if(this.activeProgressBar={total:Math.max(1,Q||1),current:0,message:X||"",barLength:Z,lastRenderedLine:""},this.shouldStyleConsole()&&!T()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(_,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,_),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!T()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(_)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,_)},interrupt:(_,J="info")=>{if(!T()&&w.stdout.isTTY)w.stdout.write(`
|
|
44
|
+
`);if(this[J==="warning"?"warn":J](_),this.activeProgressBar&&this.shouldStyleConsole()&&!T()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Q){let X=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":j.blue("\u25D0"),tag:Y,message:`${j.cyan(Q)}...`}))}return async(Y)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-X),H=`${Q} completed in ${$}ms`,U=new Date,_=this.formatConsoleTimestamp(U),G=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${H}`;if(Y)G+=` ${JSON.stringify(Y)}`;if(G+=`
|
|
45
|
+
`,G=G.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let q=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:_,icon:this.options.showIcons===!1?"":j.green("\u2713"),tag:q,message:`${H}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!T())console.error(G.trim());if(this.shouldWriteToFile())await this.writeToFile(G)}}async debug(Q,...X){await this.log("debug",Q,...X)}async info(Q,...X){await this.log("info",Q,...X)}async success(Q,...X){await this.log("success",Q,...X)}async warn(Q,...X){await this.log("warning",Q,...X)}async error(Q,...X){await this.log("error",Q,...X)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:X}=Q;return!!X}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let X=`${this.name}:${Q}`,Y=new YX(X,{...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(Y),Y}createReadStream(){if(T())throw Error("createReadStream is not supported in browser environments");if(!TQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return BY(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let X=this.config.rotation;if(!X.encrypt||typeof X.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let Z=s.isBuffer(Q)?Q:s.from(Q,"base64"),$=Z.subarray(0,16),H=Z.subarray(Z.length-16),U=Z.subarray(16,Z.length-16),_=oZ("aes-256-gcm",Y,$);_.setAuthTag(H);let J=_.update(U),G=_.final(),q=J.length+G.length,A=s.allocUnsafe(q);return J.copy(A,0),G.copy(A,J.length),A.toString("utf8")}catch(Z){throw Error(`Decryption failed: ${Z instanceof Error?Z.message:String(Z)}`)}}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(Q,X){this.currentKeyId=Q,this.keys.set(Q,X)}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(Q){if(!this.enabled)return;let X=new Date,Y=this.formatConsoleTimestamp(X),Z=this.formatFileTimestamp(X),{consoleText:$,fileText:H}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let _=$.split(`
|
|
46
|
+
`),J=Math.max(..._.map((z)=>z.length))+2,G=`\u250C${"\u2500".repeat(J)}\u2510`,q=`\u2514${"\u2500".repeat(J)}\u2518`,A=_.map((z)=>{return this.formatConsoleMessage({timestamp:Y,message:j.cyan(z),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:j.cyan(G),showTimestamp:!1})),A.forEach((z)=>console.error(z)),console.error(this.formatConsoleMessage({timestamp:Y,message:j.cyan(q),showTimestamp:!1}))}else if(!T())console.error(`${Z} ${this.environment}.INFO: [BOX] ${H}`);let U=`${Z} ${this.environment}.INFO: [BOX] ${H}
|
|
47
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(Q){if(T())return Promise.resolve(!0);return new Promise((X)=>{console.error(`${j.cyan("?")} ${Q} (y/n) `);let Y=(Z)=>{let $=Z.toString().trim().toLowerCase();w.stdin.removeListener("data",Y);try{if(typeof w.stdin.setRawMode==="function")w.stdin.setRawMode(!1)}catch{}w.stdin.pause(),console.error(""),X($==="y"||$==="yes")};try{if(typeof w.stdin.setRawMode==="function")w.stdin.setRawMode(!0)}catch{}w.stdin.resume(),w.stdin.once("data",Y)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...X){if(!this.enabled)return;let Y=Q;if(X&&X.length>0){let J=/%([sdijfo%])/g,G=0;if(Y=Q.replace(J,(q,A)=>{if(A==="%")return"%";if(G>=X.length)return q;let z=X[G++];switch(A){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return q}}),G<X.length)Y+=` ${X.slice(G).map((q)=>typeof q==="object"?JSON.stringify(q,null,2):String(q)).join(" ")}`}let{consoleText:Z,fileText:$}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let J=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",G=this.options.showIcons===!1?"":`${j.blue("\u25D0")} `;console.error(`${G}${J} ${j.cyan(Z)}`)}let _=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${$}
|
|
48
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(_)}renderProgressBar(Q,X=!1){if(!this.enabled||!this.shouldStyleConsole()||!w.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*Y/100),$=Q.barLength-Z,H=j.green("\u2501".repeat(Z)),U=j.gray("\u2501".repeat($)),_=`[${H}${U}]`,J=`${Y}%`.padStart(4),G=Q.message?` ${Q.message}`:"",q=this.options.showIcons===!1?"":X||Y===100?j.green("\u2713"):j.blue("\u25B6"),A=this.options.showTags!==!1&&this.name?` ${j.gray(this.formatTag(this.name))}`:"",z=`\r${q}${A} ${_} ${J}${G}`,W=w.stdout.columns||80,I=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${I}`,w.stdout.write(Q.lastRenderedLine),X)w.stdout.write(`
|
|
49
|
+
`)}finishProgressBar(Q,X){if(!this.enabled||!this.fancy||T()||!w.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(X)Q.message=X;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(T()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let X=await OQ(this.config.logDirectory),Y=[];for(let Z of X){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let H=AQ(this.config.logDirectory,Z);if(Q.before)try{if((await qQ(H)).mtime>=Q.before)continue}catch(U){console.error(`Failed to get stats for file ${H}:`,U);continue}Y.push(H)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let Z of Y)try{await NQ(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(X){console.error("Error during log clearing process:",X)}}}var I$=new YX("stacks");class u extends Error{timestamp;context;constructor(Q,X={}){super(Q);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=X,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 Q=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([X,Y])=>`${X}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${Q}`}}class YZ extends u{code="CONFIG_NOT_FOUND";constructor(Q,X,Y){let Z=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],$="";if(Z.length===1)$=` or alias "${Z[0]}"`;else if(Z.length>1)$=` or aliases ${Z.map((H)=>`"${H}"`).join(", ")}`;super(`Configuration "${Q}"${$} not found`,{configName:Q,alias:Y,searchPaths:X,searchPathCount:X.length})}}class rQ extends u{code="CONFIG_LOAD_ERROR";constructor(Q,X,Y){super(`Failed to load configuration from "${Q}": ${X.message}`,{configPath:Q,configName:Y,originalError:X.name,originalMessage:X.message});this.cause=X}}class ZZ extends u{code="CONFIG_VALIDATION_ERROR";constructor(Q,X,Y){super(`Configuration validation failed for "${Q}"`,{configPath:Q,configName:Y,validationErrors:X,errorCount:X.length})}}class $Z extends u{code="CONFIG_MERGE_ERROR";constructor(Q,X,Y,Z){super(`Failed to merge configuration from "${Q}" with "${X}": ${Y.message}`,{sourcePath:Q,targetPath:X,configName:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class gX extends u{code="ENV_VAR_ERROR";constructor(Q,X,Y,Z){super(`Failed to parse environment variable "${Q}" with value "${X}" as ${Y}`,{envKey:Q,envValue:X,expectedType:Y,configName:Z})}}class HZ extends u{code="FILE_SYSTEM_ERROR";constructor(Q,X,Y){super(`File system ${Q} failed for "${X}": ${Y.message}`,{operation:Q,path:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class UZ extends u{code="TYPE_GENERATION_ERROR";constructor(Q,X,Y){super(`Failed to generate types from "${Q}" to "${X}": ${Y.message}`,{configDir:Q,outputPath:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class aQ extends u{code="SCHEMA_VALIDATION_ERROR";constructor(Q,X,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:Q,configName:Y,validationErrors:X,errorCount:X.length})}}class JZ extends u{code="BROWSER_CONFIG_ERROR";constructor(Q,X,Y,Z){super(`Failed to fetch configuration from "${Q}": ${X} ${Y}`,{endpoint:Q,status:X,statusText:Y,configName:Z})}}class _Z extends u{code="PLUGIN_ERROR";constructor(Q,X,Y){super(`Plugin "${Q}" failed during ${X}: ${Y.message}`,{pluginName:Q,operation:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}var BQ={configNotFound(Q,X,Y){return new YZ(Q,X,Y)},configLoad(Q,X,Y){return new rQ(Q,X,Y)},configValidation(Q,X,Y){return new ZZ(Q,X,Y)},configMerge(Q,X,Y,Z){return new $Z(Q,X,Y,Z)},envVar(Q,X,Y,Z){return new gX(Q,X,Y,Z)},fileSystem(Q,X,Y){return new HZ(Q,X,Y)},typeGeneration(Q,X,Y){return new UZ(Q,X,Y)},schemaValidation(Q,X,Y){return new aQ(Q,X,Y)},browserConfig(Q,X,Y,Z){return new JZ(Q,X,Y,Z)},plugin(Q,X,Y){return new _Z(Q,X,Y)}};async function w8(Q,X={}){let{maxRetries:Y=3,retryDelay:Z=1000,isRetryable:$=()=>!0,fallback:H}=X,U=Error("Unknown error occurred");for(let _=0;_<=Y;_++)try{return await Q()}catch(J){if(U=J instanceof Error?J:Error(String(J)),_===Y||!$(U))break;if(Z>0)await new Promise((G)=>setTimeout(G,Z))}if(H!==void 0)return H;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class cX{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(Q,X)=>X==="boolean"||["true","false","1","0","yes","no"].includes(Q.toLowerCase()),parse:(Q)=>{let X=Q.toLowerCase();return["true","1","yes"].includes(X)}},{name:"number",canParse:(Q,X)=>X==="number"||!Number.isNaN(Number(Q))&&!Number.isNaN(Number.parseFloat(Q)),parse:(Q)=>{let X=Number(Q);if(Number.isNaN(X))throw TypeError(`Cannot parse "${Q}" as number`);return X}},{name:"array",canParse:(Q,X)=>X==="array"||Q.startsWith("[")||Q.includes(","),parse:(Q)=>{try{let X=JSON.parse(Q);if(Array.isArray(X))return X}catch{}return Q.split(",").map((X)=>X.trim())}},{name:"json",canParse:(Q,X)=>X==="object"||(Q.startsWith("{")&&Q.endsWith("}")||Q.startsWith("[")&&Q.endsWith("]")),parse:(Q)=>{try{return JSON.parse(Q)}catch(X){throw Error(`Cannot parse "${Q}" as JSON: ${X}`)}}}]}async applyEnvironmentVariables(Q,X,Y={}){let{prefix:Z,useCamelCase:$=!0,useBackwardCompatibility:H=!0,customParsers:U={},verbose:_=!1,trackPerformance:J=!0}=Y,G=async()=>{if(!Q)return{config:X,source:{type:"environment",priority:50,timestamp:new Date}};let q=Z||this.generateEnvPrefix(Q),A={...X};return this.processObject(A,[],q,{useCamelCase:$,useBackwardCompatibility:H,customParsers:U,verbose:_,configName:Q}),{config:A,source:{type:"environment",priority:50,timestamp:new Date}}};if(J)return yX.track("applyEnvironmentVariables",G,{configName:Q});return G()}generateEnvPrefix(Q){return Q.toUpperCase().replace(/-/g,"_")}formatEnvKey(Q,X){if(!X)return Q.toUpperCase();return Q.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(Q,X,Y,Z){for(let[$,H]of Object.entries(Q)){let U=[...X,$],_=U.map((q)=>this.formatEnvKey(q,Z.useCamelCase)),J=`${Y}_${_.join("_")}`,G=Z.useBackwardCompatibility?`${Y}_${U.map((q)=>q.toUpperCase()).join("_")}`:null;if(Z.verbose);if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.processObject(H,U,Y,Z);else{let q=xQ.env[J]||(G?xQ.env[G]:void 0);if(q!==void 0){if(Z.verbose){let A=xQ.env[J]?J:G}try{Q[$]=this.parseEnvironmentValue(q,typeof H,J,Z.customParsers,Z.configName)}catch(A){if(A instanceof gX)throw A;throw BQ.envVar(J,q,typeof H,Z.configName)}}}}}parseEnvironmentValue(Q,X,Y,Z,$){for(let[H,U]of Object.entries(Z))try{return U(Q)}catch{continue}for(let H of this.defaultParsers)if(H.canParse(Q,X))try{return H.parse(Q)}catch{throw BQ.envVar(Y,Q,`${X} (via ${H.name} parser)`,$)}return Q}getEnvironmentVariables(Q){let X={},Y=Q.toUpperCase();for(let[Z,$]of Object.entries(xQ.env))if(Z.startsWith(Y)&&$!==void 0)X[Z]=$;return X}validateEnvironmentVariable(Q,X,Y){let Z=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(Q))Z.push(`Environment variable key "${Q}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(Q,X,Y,{})}catch($){Z.push(`Cannot parse value "${X}" as ${Y}: ${$}`)}return{isValid:Z.length===0,errors:Z}}generateEnvVarDocs(Q,X,Y={}){let{prefix:Z,format:$="text"}=Y,H=Z||this.generateEnvPrefix(Q),U=[];switch(this.extractEnvVarInfo(X,[],H,U),$){case"markdown":return this.formatAsMarkdown(U,Q);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,Q)}}extractEnvVarInfo(Q,X,Y,Z){for(let[$,H]of Object.entries(Q)){let U=[...X,$],_=`${Y}_${U.map((J)=>this.formatEnvKey(J,!0)).join("_")}`;if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.extractEnvVarInfo(H,U,Y,Z);else Z.push({key:_,type:Array.isArray(H)?"array":typeof H,description:`Configuration for ${U.join(".")}`,example:this.generateExample(H)})}}generateExample(Q){if(Array.isArray(Q))return JSON.stringify(Q);if(typeof Q==="object"&&Q!==null)return JSON.stringify(Q);return String(Q)}formatAsText(Q,X){let Y=`Environment Variables for ${X}:
|
|
50
50
|
|
|
51
|
-
`;for(let Z of
|
|
52
|
-
`,
|
|
53
|
-
`,
|
|
54
|
-
`,
|
|
51
|
+
`;for(let Z of Q)Y+=`${Z.key}
|
|
52
|
+
`,Y+=` Type: ${Z.type}
|
|
53
|
+
`,Y+=` Description: ${Z.description}
|
|
54
|
+
`,Y+=` Example: ${Z.example}
|
|
55
55
|
|
|
56
|
-
`;return
|
|
56
|
+
`;return Y}formatAsMarkdown(Q,X){let Y=`# Environment Variables for ${X}
|
|
57
57
|
|
|
58
|
-
`;
|
|
59
|
-
`,
|
|
60
|
-
`;for(let Z of
|
|
61
|
-
`;return Q}}function vJ($,X,Q={}){return w9($,X,Q,new WeakMap)}function w9($,X,Q,Z){let{arrayMergeMode:J="replace",skipNullish:Y=!1,customMerger:G}=Q;if(X===null||X===void 0)return Y?$:X;if(G){let H=G($,X);if(H!==void 0)return H}if(Array.isArray(X)||Array.isArray($))return I9($,X,J,Z);if(!X0(X)||!X0($))return X;return mJ($,X,Q,Z)}function I9($,X,Q,Z){if(Array.isArray(X)&&!Array.isArray($))return X;if(Array.isArray($)&&!Array.isArray(X))return X;if(Array.isArray(X)&&Array.isArray($))switch(Q){case"replace":return X;case"concat":return fJ($,X);case"smart":return gJ($,X,Z);default:return X}return X}function fJ($,X){let Q=[...X];for(let Z of $)if(!Q.some((J)=>r$(J,Z)))Q.push(Z);return Q}function gJ($,X,Q){if(X.length===0)return $;if($.length===0)return X;if(X0(X[0])&&X0($[0]))return dJ($,X,Q);if(X.every((Z)=>typeof Z==="string")&&$.every((Z)=>typeof Z==="string")){let Z=[...X];for(let J of $)if(!Z.includes(J))Z.push(J);return Z}return X}function dJ($,X,Q){let Z=[...X];for(let J of $){if(!X0(J)){Z.push(J);continue}let Y=["id","name","key","path","type"],G=!1;for(let H of Y)if(H in J){if(Z.find((q)=>X0(q)&&(H in q)&&q[H]===J[H])){G=!0;break}}if(!G)Z.push(J)}return Z}function mJ($,X,Q,Z){let J=X;if(X0(J)&&Z.has(J))return Z.get(J);let Y={...$};if(X0(J))Z.set(J,Y);for(let G in J){if(!Object.prototype.hasOwnProperty.call(J,G))continue;let H=J[G],U=Y[G];if(Q.skipNullish&&(H===null||H===void 0))continue;if(H===null||H===void 0){Y[G]=H;continue}if(X0(H)&&X0(U))Y[G]=w9(U,H,Q,Z);else if(Array.isArray(H)||Array.isArray(U))Y[G]=I9(U,H,Q.arrayMergeMode||"smart",Z);else Y[G]=H}return Y}function D9($,X,Q="replace"){return vJ($,X,{arrayMergeMode:Q==="replace"?"replace":"smart",skipNullish:!0})}function r$($,X){if($===X)return!0;if(Array.isArray($)&&Array.isArray(X)){if($.length!==X.length)return!1;for(let Q=0;Q<$.length;Q++)if(!r$($[Q],X[Q]))return!1;return!0}if(X0($)&&X0(X)){let Q=Object.keys($),Z=Object.keys(X);if(Q.length!==Z.length)return!1;for(let J of Q){if(!Object.prototype.hasOwnProperty.call(X,J))return!1;if(!r$($[J],X[J]))return!1}return!0}return!1}function X0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class V9{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,X,Q={}){let{arrayStrategy:Z="replace",useCache:J=!0,cacheTtl:Y,trackPerformance:G=!0,verbose:H=!1}=Q;if(J){let q=y8.getWithFileCheck("file",$);if(q){if(H)console.log(`Configuration loaded from cache: ${$}`);return q}}let U=async()=>{if(!S8($))return null;try{let q=`?t=${Date.now()}`,z=await import($+q),_=z.default||z,A="default"in z,W=Object.keys(z).length>0;if(!A&&!W)throw new i8($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof _!=="object"||_===null||Array.isArray(_))throw new i8($,Error("Configuration must export a valid object"),"unknown");let M={config:D9(X,_,Z),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(J)y8.setWithFileCheck("file",M,$,Y);return M}catch(q){throw q instanceof Error?l0.configLoad($,q):l0.configLoad($,Error(String(q)))}};if(G)return a$.track("loadFromPath",U,{path:$});return U()}async tryLoadFromPaths($,X,Q={}){for(let Z of $)try{let J=await this.loadFromPath(Z,X,Q);if(J)return J}catch(J){if(J instanceof Error&&J.name==="ConfigLoadError")throw J;if(Q.verbose)console.warn(`Failed to load config from ${Z}:`,J)}return null}generateConfigPaths($,X,Q){let Z=this.generateNamePatterns($,Q),J=[];for(let Y of Z)for(let G of this.extensions)J.push(h$(X,`${Y}${G}`));return J}generateNamePatterns($,X){let Q=[];if(Q.push("config",".config"),$)Q.push($,`.${$}.config`,`${$}.config`,`.${$}`);let Z=X===void 0?[]:Array.isArray(X)?X:[X];for(let Y of Z){if(!Y)continue;if(Q.push(Y,`.${Y}.config`,`${Y}.config`,`.${Y}`),$)Q.push(`${$}.${Y}.config`,`.${$}.${Y}.config`)}let J=new Set;return Q.filter((Y)=>{if(!Y||J.has(Y))return!1;return J.add(Y),!0})}checkFileAccess($){return hJ(async()=>{return S8($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,X,Q){let Z=[];if(!S8($))return Z;if(X||Q){let J=this.generateNamePatterns(X||"",Q);for(let Y of J)for(let G of this.extensions){let H=h$($,`${Y}${G}`);if(await this.checkFileAccess(H))Z.push(H)}}else try{let{readdirSync:J}=await import("fs"),Y=J($);for(let G of Y)if(this.looksLikeConfigFile(G)){let H=h$($,G);if(await this.checkFileAccess(H))Z.push(H)}}catch{return[]}return Z}looksLikeConfigFile($){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((Q)=>Q.test($))}async validateConfigFile($){let X=[];try{if(!S8($))return X.push("Configuration file does not exist"),X;let Q=await import($),Z=Q.default||Q;if(Z===void 0)X.push("Configuration file must export a default value or named exports");else if(typeof Z!=="object"||Z===null)X.push("Configuration must be an object");else if(Array.isArray(Z))X.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:J}=await import("fs"),Y=J($,"utf8");JSON.parse(Y)}catch(J){X.push(`Invalid JSON syntax: ${J}`)}}catch(Q){X.push(`Failed to load configuration file: ${Q}`)}return X}async getFileModificationTime($){try{let{statSync:X}=await import("fs");return X($).mtime}catch{return null}}async preloadConfigurations($,X={}){let Q=new Map;return await Promise.allSettled($.map(async(Z)=>{try{let J=await this.loadFromPath(Z,{},X);if(J)Q.set(Z,J.config)}catch(J){if(X.verbose)console.warn(`Failed to preload ${Z}:`,J)}})),Q}}var pJ=/^https?:\/\//;class O9{async validateConfiguration($,X,Q={}){let{stopOnFirstError:Z=!1,validateRequired:J=!0,validateTypes:Y=!0,customRules:G=[],trackPerformance:H=!0,verbose:U=!1}=Q,q=async()=>{let z=[],_=[],A={stopOnFirstError:Z,validateRequired:J,validateTypes:Y,customRules:G,trackPerformance:H,verbose:U};try{if(typeof X==="string")return await this.validateWithSchemaFile($,X,A);else if(Array.isArray(X))return this.validateWithRules($,[...X,...G],A);else return this.validateWithJSONSchema($,X,A)}catch(W){return z.push({path:"",message:`Validation failed: ${W}`,rule:"system"}),{isValid:!1,errors:z,warnings:_}}};if(H)return await a$.track("validateConfiguration",q);return q()}async validateWithSchemaFile($,X,Q){try{if(!uJ(X))throw new o8(X,[{path:"",message:"Schema file does not exist"}]);let Z=await import(X),J=Z.default||Z;if(Array.isArray(J))return this.validateWithRules($,J,Q);else return this.validateWithJSONSchema($,J,Q)}catch(Z){throw new o8(X,[{path:"",message:`Failed to load schema: ${Z}`}])}}validateWithJSONSchema($,X,Q){let Z=[],J=[];return this.validateObjectAgainstSchema($,X,"",Z,J,Q),{isValid:Z.length===0,errors:Z,warnings:J}}validateObjectAgainstSchema($,X,Q,Z,J,Y){if(Y.validateTypes&&X.type){let G=Array.isArray($)?"array":typeof $,H=Array.isArray(X.type)?X.type:[X.type];if(!H.includes(G)){if(Z.push({path:Q,message:`Expected type ${H.join(" or ")}, got ${G}`,expected:H.join(" or "),actual:G,rule:"type"}),Y.stopOnFirstError)return}}if(X.enum&&!X.enum.includes($)){if(Z.push({path:Q,message:`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:$,rule:"enum"}),Y.stopOnFirstError)return}if(typeof $==="string"){if(X.minLength!==void 0&&$.length<X.minLength)Z.push({path:Q,message:`String length must be at least ${X.minLength}`,expected:`>= ${X.minLength}`,actual:$.length,rule:"minLength"});if(X.maxLength!==void 0&&$.length>X.maxLength)Z.push({path:Q,message:`String length must not exceed ${X.maxLength}`,expected:`<= ${X.maxLength}`,actual:$.length,rule:"maxLength"});if(X.pattern){if(!new RegExp(X.pattern).test($))Z.push({path:Q,message:`String does not match pattern ${X.pattern}`,expected:X.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(X.minimum!==void 0&&$<X.minimum)Z.push({path:Q,message:`Value must be at least ${X.minimum}`,expected:`>= ${X.minimum}`,actual:$,rule:"minimum"});if(X.maximum!==void 0&&$>X.maximum)Z.push({path:Q,message:`Value must not exceed ${X.maximum}`,expected:`<= ${X.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&X.items)for(let G=0;G<$.length;G++){let H=Q?`${Q}[${G}]`:`[${G}]`;if(this.validateObjectAgainstSchema($[G],X.items,H,Z,J,Y),Y.stopOnFirstError&&Z.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let G=$;if(Y.validateRequired&&X.required){for(let H of X.required)if(!(H in G)){if(Z.push({path:Q?`${Q}.${H}`:H,message:`Missing required property '${H}'`,expected:"required",rule:"required"}),Y.stopOnFirstError)return}}if(X.properties){for(let[H,U]of Object.entries(X.properties))if(H in G){let q=Q?`${Q}.${H}`:H;if(this.validateObjectAgainstSchema(G[H],U,q,Z,J,Y),Y.stopOnFirstError&&Z.length>0)return}}if(X.additionalProperties===!1){let H=new Set(Object.keys(X.properties||{}));for(let U of Object.keys(G))if(!H.has(U))J.push({path:Q?`${Q}.${U}`:U,message:`Additional property '${U}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,X,Q){let Z=[],J=[];for(let Y of X)try{let G=this.getValueByPath($,Y.path),H=this.validateWithRule(G,Y,Y.path);if(Z.push(...H),Q.stopOnFirstError&&Z.length>0)break}catch(G){Z.push({path:Y.path,message:`Rule validation failed: ${G}`,rule:"system"})}return{isValid:Z.length===0,errors:Z,warnings:J}}validateWithRule($,X,Q){let Z=[];if(X.required&&($===void 0||$===null))return Z.push({path:Q,message:X.message||`Property '${Q}' is required`,expected:"required",rule:"required"}),Z;if($===void 0||$===null)return Z;if(X.type){let J=Array.isArray($)?"array":typeof $;if(J!==X.type)Z.push({path:Q,message:X.message||`Expected type ${X.type}, got ${J}`,expected:X.type,actual:J,rule:"type"})}if(X.min!==void 0){let J=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(J<X.min)Z.push({path:Q,message:X.message||`Value must be at least ${X.min}`,expected:`>= ${X.min}`,actual:J,rule:"min"})}if(X.max!==void 0){let J=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(J>X.max)Z.push({path:Q,message:X.message||`Value must not exceed ${X.max}`,expected:`<= ${X.max}`,actual:J,rule:"max"})}if(X.pattern&&typeof $==="string"){if(!X.pattern.test($))Z.push({path:Q,message:X.message||`Value does not match pattern ${X.pattern}`,expected:X.pattern.toString(),actual:$,rule:"pattern"})}if(X.enum&&!X.enum.includes($))Z.push({path:Q,message:X.message||`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:$,rule:"enum"});if(X.validator){let J=X.validator($);if(J)Z.push({path:Q,message:X.message||J,rule:"custom"})}return Z}getValueByPath($,X){if(!X)return $;let Q=X.split("."),Z=$;for(let J of Q)if(Z&&typeof Z==="object"&&J in Z)Z=Z[J];else return;return Z}generateRulesFromInterface($){let X=[],Q=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Z of Q){let[,J,Y,G]=Z;X.push({path:J,required:!Y,type:this.mapTypeScriptType(G)})}return X}mapTypeScriptType($){switch($.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:pJ},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var z0=new t8("bunfig",{showTags:!0});function cJ($){if(!$)return"";let X=Array.isArray($)?$.filter(Boolean):[$];if(X.length===0)return"";if(X.length===1)return` or alias "${X[0]}"`;return` or aliases ${X.map((Q)=>`"${Q}"`).join(", ")}`}class N9{fileLoader=new V9;envProcessor=new YX;validator=new O9;async loadConfig($){let X=Date.now(),{cache:Q,performance:Z,schema:J,validate:Y,...G}=$;try{if(Q?.enabled){let U=this.checkCache(G.name||"",G);if(U)return U}let H;try{H=await this.loadConfigurationStrategies(G,!0,Q)}catch(U){let q=G.__strictErrorHandling;if(U instanceof Error&&U.name==="ConfigNotFoundError"){if(q)throw U;H={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`No configuration file found for "${G.name||"config"}", using defaults with environment variables`]}}else if(U instanceof Error&&U.name==="ConfigLoadError"){let z=U.message.includes("EACCES")||U.message.includes("EPERM")||U.message.includes("permission denied"),_=!z&&(U.message.includes("syntax")||U.message.includes("Expected")||U.message.includes("Unexpected")||U.message.includes("BuildMessage")||U.message.includes("errors building")),A=U.message.includes("Configuration must export a valid object")||U.message.includes("Configuration file is empty and exports nothing");if(q&&(A||z))throw U;if(_&&(!q||!A))H={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!q)H={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`Configuration loading error, using defaults: ${U.message}`]};else throw U}else H={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${U instanceof Error?U.message:String(U)}`]}}if(J||Y)await this.validateConfiguration(H.config,J,Y,G.name);if(Q?.enabled&&H)this.cacheResult(G.name||"",H,Q,G);if(Z?.enabled){let U={operation:"loadConfig",duration:Date.now()-X,configName:G.name,timestamp:new Date};if(Z.onMetrics)Z.onMetrics(U);if(Z.slowThreshold&&U.duration>Z.slowThreshold)z0.warn(`Slow configuration loading detected: ${U.duration}ms for ${G.name}`);H.metrics=U}return H}catch(H){if(H instanceof Error&&H.name==="ConfigNotFoundError")throw H;let U=Date.now()-X;throw z0.error(`Configuration loading failed after ${U}ms:`,[H instanceof Error?H:Error(String(H))]),H}}async loadConfigurationStrategies($,X=!1,Q){let{name:Z="",alias:J,cwd:Y,configDir:G,defaultConfig:H,checkEnv:U=!0,arrayStrategy:q="replace",verbose:z=!1}=$,_=Y||r8.cwd(),A=[],W=await this.loadLocalConfiguration(Z,J,_,G,H,q,z,U,Q);if(W)return A.push(...this.getLocalSearchPaths(Z,J,_,G)),this.finalizeResult(W,A,U,Z,z);let K=await this.loadHomeConfiguration(Z,J,H,q,z,U);if(K)return A.push(...this.getHomeSearchPaths(Z,J)),this.finalizeResult(K,A,U,Z,z);let B=await this.loadPackageJsonConfiguration(Z,J,_,H,q,z,U);if(B)return A.push(e(_,"package.json")),this.finalizeResult(B,A,U,Z,z);if(A.push(...this.getAllSearchPaths(Z,J,_,G)),X)throw l0.configNotFound(Z,A,J);return{...await this.applyEnvironmentVariables(Z,H,U,z),warnings:[`No configuration file found for "${Z}"${cJ(J)}, using defaults with environment variables`]}}async loadLocalConfiguration($,X,Q,Z,J,Y,G,H,U){let q=H?C8($,J,G):J,z=this.getLocalDirectories(Q,Z);for(let _ of z){if(G)z0.info(`Searching for configuration in: ${_}`);let A=this.fileLoader.generateConfigPaths($,_,X),W=await this.fileLoader.tryLoadFromPaths(A,q,{arrayStrategy:Y,verbose:G,cacheTtl:U?.ttl,useCache:!U?.ttl||U.ttl>100});if(W){if(G)z0.success(`Configuration loaded from: ${W.source.path}`);return W}}return null}async loadHomeConfiguration($,X,Q,Z,J,Y){if(!$)return null;let G=Y?C8($,Q,J):Q,H=[e(T0(),".config",$),e(T0(),".config"),T0()];for(let U of H){if(J)z0.info(`Checking home directory: ${U}`);let q=this.fileLoader.generateConfigPaths($,U,X),z=await this.fileLoader.tryLoadFromPaths(q,G,{arrayStrategy:Z,verbose:J});if(z){if(J)z0.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration($,X,Q,Z,J,Y,G){let H=G?C8($,Z,Y):Z;try{let U=e(Q,"package.json");if(!vZ(U))return null;let q={};try{q=JSON.parse(fZ(U,"utf8"))}catch(A){if(Y)z0.warn("Failed to parse package.json:",[A instanceof Error?A:Error(String(A))]);return null}let z=q[$],_=$;if(!z&&X){let A=Array.isArray(X)?X:[X];for(let W of A){if(!W)continue;if(q[W]){z=q[W],_=W;break}}}if(z&&typeof z==="object"&&!Array.isArray(z)){if(Y)z0.success(`Configuration loaded from package.json: ${_}`);return{config:D9(H,z,J),source:{type:"package.json",path:U,priority:30,timestamp:new Date}}}}catch(U){if(Y)z0.warn("Failed to load package.json:",[U instanceof Error?U:Error(String(U))])}return null}async applyEnvironmentVariables($,X,Q,Z){if(!Q||!$||typeof X!=="object"||X===null||Array.isArray(X))return{config:X,source:{type:"default",priority:10,timestamp:new Date}};return{config:C8($,X,Z),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,X,Q,Z,J){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,X,Q,Z){let J=[];if(Q){let Y=Q($);if(Y)J.push(...Y)}if(X){let Y=await this.validator.validateConfiguration($,X);if(!Y.isValid)J.push(...Y.errors.map((G)=>G.path?`${G.path}: ${G.message}`:G.message))}if(J.length>0)throw l0.configValidation(Z||"unknown",J,Z)}checkCache($,X){let Q=this.generateCacheKey($,X);return y8.get(Q)||null}cacheResult($,X,Q,Z){let J=this.generateCacheKey($,Z);y8.set(J,X,void 0,Q.ttl)}generateCacheKey($,X){let Q=[$];if(X.alias){let Z=Array.isArray(X.alias)?X.alias.join(","):X.alias;Q.push(`alias:${Z}`)}if(X.cwd)Q.push(`cwd:${X.cwd}`);if(X.configDir)Q.push(`configDir:${X.configDir}`);if("checkEnv"in X)Q.push(`checkEnv:${X.checkEnv}`);return Q.join("|")}getLocalDirectories($,X){return Array.from(new Set([$,e($,"config"),e($,".config"),X?e($,X):void 0].filter(Boolean)))}getAllSearchPaths($,X,Q,Z){let J=[];return J.push(...this.getLocalSearchPaths($,X,Q,Z)),J.push(...this.getHomeSearchPaths($,X)),J.push(e(Q,"package.json")),J}getLocalSearchPaths($,X,Q,Z){let J=this.getLocalDirectories(Q,Z),Y=[];for(let G of J)Y.push(...this.fileLoader.generateConfigPaths($,G,X));return Y}getHomeSearchPaths($,X){if(!$)return[];let Q=[e(T0(),".config",$),e(T0(),".config"),T0()],Z=[];for(let J of Q)Z.push(...this.fileLoader.generateConfigPaths($,J,X));return Z}async loadConfigWithResult($){return this.loadConfig($)}}var v$=new N9;async function E9($){let X="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Q="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Z;if(Q)Z=await v$.loadConfig($);else Z=await v$.loadConfig({...$,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}});return Z?.config??X}catch(Z){let J=Z instanceof Error?Z.name:"UnknownError",Y=Z instanceof Error?Z.message:String(Z);if(!(J==="ConfigNotFoundError"||J==="ConfigLoadError"||J==="ConfigValidationError"||Y.includes("config"))&&$.verbose)z0.warn("Unexpected error loading config, using defaults:",[Z instanceof Error?Z:Error(String(Z))]);let H=Q?{...$,defaultConfig:X}:{...$,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await v$.applyEnvironmentVariables(H.name||"",X,!0,H.verbose||!1))?.config??X;return X}}function C8($,X,Q=!1){let Z=new YX,J=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(G,H=[]){let U={...G};for(let[q,z]of Object.entries(G)){let _=[...H,q],A=[`${J}_${_.join("_").toUpperCase()}`,`${J}_${_.map((B)=>B.toUpperCase()).join("")}`,`${J}_${_.map((B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],W,K;for(let B of A)if(W=r8.env[B],W!==void 0){K=B;break}if(W!==void 0&&K)if(typeof z==="boolean")U[q]=["true","1","yes"].includes(W.toLowerCase());else if(typeof z==="number"){let B=Number(W);if(!Number.isNaN(B))U[q]=B}else if(Array.isArray(z))try{U[q]=JSON.parse(W)}catch{U[q]=W.split(",").map((B)=>B.trim())}else U[q]=W;else if(z&&typeof z==="object"&&!Array.isArray(z))U[q]=Y(z,_)}return U}return Y(X)}var dH=e(r8.cwd(),"config"),mH=e(r8.cwd(),"src/generated");var S9={floatPrecision:3,verbose:!1},GX=null;async function cH(){if(!GX)GX=await E9({name:"css",defaultConfig:S9});return GX}var lH=S9;export{W0 as walk,ZQ as syntax,z8 as stringifySelector,b0 as specificity,mX as selectOne,dX as selectAll,A0 as parseSelector,C0 as parse,R$ as minifyBlock,K$ as minify,_$ as isTraversal,uX as is,cH as getConfig,f as generate,S9 as defaultConfig,DX as csstree,JQ as csso,xX as cssWhat,pX as cssSelect,lH as config,e8 as clone,d as List};
|
|
58
|
+
`;Y+=`| Variable | Type | Description | Example |
|
|
59
|
+
`,Y+=`|----------|------|-------------|----------|
|
|
60
|
+
`;for(let Z of Q)Y+=`| \`${Z.key}\` | ${Z.type} | ${Z.description} | \`${Z.example}\` |
|
|
61
|
+
`;return Y}}function L8(Q,X,Y={}){return GZ(Q,X,Y,new WeakMap)}function GZ(Q,X,Y,Z){let{arrayMergeMode:$="replace",skipNullish:H=!1,customMerger:U}=Y;if(X===null||X===void 0)return H?Q:X;if(U){let _=U(Q,X);if(_!==void 0)return _}if(Array.isArray(X)||Array.isArray(Q))return qZ(Q,X,$,Z);if(!f(X)||!f(Q))return X;return F8(Q,X,Y,Z)}function qZ(Q,X,Y,Z){if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(Q)&&!Array.isArray(X))return X;if(Array.isArray(X)&&Array.isArray(Q))switch(Y){case"replace":return X;case"concat":return K8(Q,X);case"smart":return j8(Q,X,Z);default:return X}return X}function K8(Q,X){let Y=[...X];for(let Z of Q)if(!Y.some(($)=>bX($,Z)))Y.push(Z);return Y}function j8(Q,X,Y){if(X.length===0)return Q;if(Q.length===0)return X;if(f(X[0])&&f(Q[0]))return I8(Q,X,Y);if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}function I8(Q,X,Y){let Z=[...X];for(let $ of Q){if(!f($)){Z.push($);continue}let H=["id","name","key","path","type"],U=!1;for(let _ of H)if(_ in $){if(Z.find((G)=>f(G)&&(_ in G)&&G[_]===$[_])){U=!0;break}}if(!U)Z.push($)}return Z}function F8(Q,X,Y,Z){let $=X;if(f($)&&Z.has($))return Z.get($);let H={...Q};if(f($))Z.set($,H);for(let U in $){if(!Object.prototype.hasOwnProperty.call($,U))continue;let _=$[U],J=H[U];if(Y.skipNullish&&(_===null||_===void 0))continue;if(_===null||_===void 0){H[U]=_;continue}if(f(_)&&f(J))H[U]=GZ(J,_,Y,Z);else if(Array.isArray(_)||Array.isArray(J))H[U]=qZ(J,_,Y.arrayMergeMode||"smart",Z);else H[U]=_}return H}function AZ(Q,X,Y="replace"){return L8(Q,X,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function bX(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!bX(Q[Y],X[Y]))return!1;return!0}if(f(Q)&&f(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!bX(Q[$],X[$]))return!1}return!0}return!1}function f(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}class WZ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(Q,X,Y={}){let{arrayStrategy:Z="replace",useCache:$=!0,cacheTtl:H,trackPerformance:U=!0,verbose:_=!1}=Y;if($){let G=fQ.getWithFileCheck("file",Q);if(G){if(_)console.log(`Configuration loaded from cache: ${Q}`);return G}}let J=async()=>{if(!kQ(Q))return null;try{let G=`?t=${Date.now()}`,q=await import(Q+G),A=q.default||q,z="default"in q,W=Object.keys(q).length>0;if(!z&&!W)throw new rQ(Q,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof A!=="object"||A===null||Array.isArray(A))throw new rQ(Q,Error("Configuration must export a valid object"),"unknown");let K={config:AZ(X,A,Z),source:{type:"file",path:Q,priority:100,timestamp:new Date}};if($)fQ.setWithFileCheck("file",K,Q,H);return K}catch(G){throw G instanceof Error?BQ.configLoad(Q,G):BQ.configLoad(Q,Error(String(G)))}};if(U)return yX.track("loadFromPath",J,{path:Q});return J()}async tryLoadFromPaths(Q,X,Y={}){for(let Z of Q)try{let $=await this.loadFromPath(Z,X,Y);if($)return $}catch($){if($ instanceof Error&&$.name==="ConfigLoadError")throw $;if(Y.verbose)console.warn(`Failed to load config from ${Z}:`,$)}return null}generateConfigPaths(Q,X,Y){let Z=this.generateNamePatterns(Q,Y),$=[];for(let H of Z)for(let U of this.extensions)$.push(FX(X,`${H}${U}`));return $}generateNamePatterns(Q,X){let Y=[];if(Y.push("config",".config"),Q)Y.push(Q,`.${Q}.config`,`${Q}.config`,`.${Q}`);let Z=X===void 0?[]:Array.isArray(X)?X:[X];for(let H of Z){if(!H)continue;if(Y.push(H,`.${H}.config`,`${H}.config`,`.${H}`),Q)Y.push(`${Q}.${H}.config`,`.${Q}.${H}.config`)}let $=new Set;return Y.filter((H)=>{if(!H||$.has(H))return!1;return $.add(H),!0})}checkFileAccess(Q){return w8(async()=>{return kQ(Q)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Q,X,Y){let Z=[];if(!kQ(Q))return Z;if(X||Y){let $=this.generateNamePatterns(X||"",Y);for(let H of $)for(let U of this.extensions){let _=FX(Q,`${H}${U}`);if(await this.checkFileAccess(_))Z.push(_)}}else try{let{readdirSync:$}=await import("fs"),H=$(Q);for(let U of H)if(this.looksLikeConfigFile(U)){let _=FX(Q,U);if(await this.checkFileAccess(_))Z.push(_)}}catch{return[]}return Z}looksLikeConfigFile(Q){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((Y)=>Y.test(Q))}async validateConfigFile(Q){let X=[];try{if(!kQ(Q))return X.push("Configuration file does not exist"),X;let Y=await import(Q),Z=Y.default||Y;if(Z===void 0)X.push("Configuration file must export a default value or named exports");else if(typeof Z!=="object"||Z===null)X.push("Configuration must be an object");else if(Array.isArray(Z))X.push("Configuration cannot be an array at the root level");if(Q.endsWith(".json"))try{let{readFileSync:$}=await import("fs"),H=$(Q,"utf8");JSON.parse(H)}catch($){X.push(`Invalid JSON syntax: ${$}`)}}catch(Y){X.push(`Failed to load configuration file: ${Y}`)}return X}async getFileModificationTime(Q){try{let{statSync:X}=await import("fs");return X(Q).mtime}catch{return null}}async preloadConfigurations(Q,X={}){let Y=new Map;return await Promise.allSettled(Q.map(async(Z)=>{try{let $=await this.loadFromPath(Z,{},X);if($)Y.set(Z,$.config)}catch($){if(X.verbose)console.warn(`Failed to preload ${Z}:`,$)}})),Y}}var D8=/^https?:\/\//;class zZ{async validateConfiguration(Q,X,Y={}){let{stopOnFirstError:Z=!1,validateRequired:$=!0,validateTypes:H=!0,customRules:U=[],trackPerformance:_=!0,verbose:J=!1}=Y,G=async()=>{let q=[],A=[],z={stopOnFirstError:Z,validateRequired:$,validateTypes:H,customRules:U,trackPerformance:_,verbose:J};try{if(typeof X==="string")return await this.validateWithSchemaFile(Q,X,z);else if(Array.isArray(X))return this.validateWithRules(Q,[...X,...U],z);else return this.validateWithJSONSchema(Q,X,z)}catch(W){return q.push({path:"",message:`Validation failed: ${W}`,rule:"system"}),{isValid:!1,errors:q,warnings:A}}};if(_)return await yX.track("validateConfiguration",G);return G()}async validateWithSchemaFile(Q,X,Y){try{if(!M8(X))throw new aQ(X,[{path:"",message:"Schema file does not exist"}]);let Z=await import(X),$=Z.default||Z;if(Array.isArray($))return this.validateWithRules(Q,$,Y);else return this.validateWithJSONSchema(Q,$,Y)}catch(Z){throw new aQ(X,[{path:"",message:`Failed to load schema: ${Z}`}])}}validateWithJSONSchema(Q,X,Y){let Z=[],$=[];return this.validateObjectAgainstSchema(Q,X,"",Z,$,Y),{isValid:Z.length===0,errors:Z,warnings:$}}validateObjectAgainstSchema(Q,X,Y,Z,$,H){if(H.validateTypes&&X.type){let U=Array.isArray(Q)?"array":typeof Q,_=Array.isArray(X.type)?X.type:[X.type];if(!_.includes(U)){if(Z.push({path:Y,message:`Expected type ${_.join(" or ")}, got ${U}`,expected:_.join(" or "),actual:U,rule:"type"}),H.stopOnFirstError)return}}if(X.enum&&!X.enum.includes(Q)){if(Z.push({path:Y,message:`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"}),H.stopOnFirstError)return}if(typeof Q==="string"){if(X.minLength!==void 0&&Q.length<X.minLength)Z.push({path:Y,message:`String length must be at least ${X.minLength}`,expected:`>= ${X.minLength}`,actual:Q.length,rule:"minLength"});if(X.maxLength!==void 0&&Q.length>X.maxLength)Z.push({path:Y,message:`String length must not exceed ${X.maxLength}`,expected:`<= ${X.maxLength}`,actual:Q.length,rule:"maxLength"});if(X.pattern){if(!new RegExp(X.pattern).test(Q))Z.push({path:Y,message:`String does not match pattern ${X.pattern}`,expected:X.pattern,actual:Q,rule:"pattern"})}}if(typeof Q==="number"){if(X.minimum!==void 0&&Q<X.minimum)Z.push({path:Y,message:`Value must be at least ${X.minimum}`,expected:`>= ${X.minimum}`,actual:Q,rule:"minimum"});if(X.maximum!==void 0&&Q>X.maximum)Z.push({path:Y,message:`Value must not exceed ${X.maximum}`,expected:`<= ${X.maximum}`,actual:Q,rule:"maximum"})}if(Array.isArray(Q)&&X.items)for(let U=0;U<Q.length;U++){let _=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(Q[U],X.items,_,Z,$,H),H.stopOnFirstError&&Z.length>0)return}if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let U=Q;if(H.validateRequired&&X.required){for(let _ of X.required)if(!(_ in U)){if(Z.push({path:Y?`${Y}.${_}`:_,message:`Missing required property '${_}'`,expected:"required",rule:"required"}),H.stopOnFirstError)return}}if(X.properties){for(let[_,J]of Object.entries(X.properties))if(_ in U){let G=Y?`${Y}.${_}`:_;if(this.validateObjectAgainstSchema(U[_],J,G,Z,$,H),H.stopOnFirstError&&Z.length>0)return}}if(X.additionalProperties===!1){let _=new Set(Object.keys(X.properties||{}));for(let J of Object.keys(U))if(!_.has(J))$.push({path:Y?`${Y}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Q,X,Y){let Z=[],$=[];for(let H of X)try{let U=this.getValueByPath(Q,H.path),_=this.validateWithRule(U,H,H.path);if(Z.push(..._),Y.stopOnFirstError&&Z.length>0)break}catch(U){Z.push({path:H.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Z.length===0,errors:Z,warnings:$}}validateWithRule(Q,X,Y){let Z=[];if(X.required&&(Q===void 0||Q===null))return Z.push({path:Y,message:X.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),Z;if(Q===void 0||Q===null)return Z;if(X.type){let $=Array.isArray(Q)?"array":typeof Q;if($!==X.type)Z.push({path:Y,message:X.message||`Expected type ${X.type}, got ${$}`,expected:X.type,actual:$,rule:"type"})}if(X.min!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($<X.min)Z.push({path:Y,message:X.message||`Value must be at least ${X.min}`,expected:`>= ${X.min}`,actual:$,rule:"min"})}if(X.max!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($>X.max)Z.push({path:Y,message:X.message||`Value must not exceed ${X.max}`,expected:`<= ${X.max}`,actual:$,rule:"max"})}if(X.pattern&&typeof Q==="string"){if(!X.pattern.test(Q))Z.push({path:Y,message:X.message||`Value does not match pattern ${X.pattern}`,expected:X.pattern.toString(),actual:Q,rule:"pattern"})}if(X.enum&&!X.enum.includes(Q))Z.push({path:Y,message:X.message||`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"});if(X.validator){let $=X.validator(Q);if($)Z.push({path:Y,message:X.message||$,rule:"custom"})}return Z}getValueByPath(Q,X){if(!X)return Q;let Y=X.split("."),Z=Q;for(let $ of Y)if(Z&&typeof Z==="object"&&$ in Z)Z=Z[$];else return;return Z}generateRulesFromInterface(Q){let X=[],Y=Q.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Z of Y){let[,$,H,U]=Z;X.push({path:$,required:!H,type:this.mapTypeScriptType(U)})}return X}mapTypeScriptType(Q){switch(Q.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:D8},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var c=new YX("bunfig",{showTags:!0});function S8(Q){if(!Q)return"";let X=Array.isArray(Q)?Q.filter(Boolean):[Q];if(X.length===0)return"";if(X.length===1)return` or alias "${X[0]}"`;return` or aliases ${X.map((Y)=>`"${Y}"`).join(", ")}`}class BZ{fileLoader=new WZ;envProcessor=new cX;validator=new zZ;async loadConfig(Q){let X=Date.now(),{cache:Y,performance:Z,schema:$,validate:H,...U}=Q;try{if(Y?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let _;try{_=await this.loadConfigurationStrategies(U,!0,Y)}catch(J){let G=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(G)throw J;_={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let q=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),A=!q&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),z=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(G&&(z||q))throw J;if(A&&(!G||!z))_={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!G)_={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else _={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if($||H)await this.validateConfiguration(_.config,$,H,U.name);if(Y?.enabled&&_)this.cacheResult(U.name||"",_,Y,U);if(Z?.enabled){let J={operation:"loadConfig",duration:Date.now()-X,configName:U.name,timestamp:new Date};if(Z.onMetrics)Z.onMetrics(J);if(Z.slowThreshold&&J.duration>Z.slowThreshold)c.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);_.metrics=J}return _}catch(_){if(_ instanceof Error&&_.name==="ConfigNotFoundError")throw _;let J=Date.now()-X;throw c.error(`Configuration loading failed after ${J}ms:`,[_ instanceof Error?_:Error(String(_))]),_}}async loadConfigurationStrategies(Q,X=!1,Y){let{name:Z="",alias:$,cwd:H,configDir:U,defaultConfig:_,checkEnv:J=!0,arrayStrategy:G="replace",verbose:q=!1}=Q,A=H||eQ.cwd(),z=[],W=await this.loadLocalConfiguration(Z,$,A,U,_,G,q,J,Y);if(W)return z.push(...this.getLocalSearchPaths(Z,$,A,U)),this.finalizeResult(W,z,J,Z,q);let I=await this.loadHomeConfiguration(Z,$,_,G,q,J);if(I)return z.push(...this.getHomeSearchPaths(Z,$)),this.finalizeResult(I,z,J,Z,q);let B=await this.loadPackageJsonConfiguration(Z,$,A,_,G,q,J);if(B)return z.push(d(A,"package.json")),this.finalizeResult(B,z,J,Z,q);if(z.push(...this.getAllSearchPaths(Z,$,A,U)),X)throw BQ.configNotFound(Z,z,$);return{...await this.applyEnvironmentVariables(Z,_,J,q),warnings:[`No configuration file found for "${Z}"${S8($)}, using defaults with environment variables`]}}async loadLocalConfiguration(Q,X,Y,Z,$,H,U,_,J){let G=_?PQ(Q,$,U):$,q=this.getLocalDirectories(Y,Z);for(let A of q){if(U)c.info(`Searching for configuration in: ${A}`);let z=this.fileLoader.generateConfigPaths(Q,A,X),W=await this.fileLoader.tryLoadFromPaths(z,G,{arrayStrategy:H,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(W){if(U)c.success(`Configuration loaded from: ${W.source.path}`);return W}}return null}async loadHomeConfiguration(Q,X,Y,Z,$,H){if(!Q)return null;let U=H?PQ(Q,Y,$):Y,_=[d(YQ(),".config",Q),d(YQ(),".config"),YQ()];for(let J of _){if($)c.info(`Checking home directory: ${J}`);let G=this.fileLoader.generateConfigPaths(Q,J,X),q=await this.fileLoader.tryLoadFromPaths(G,U,{arrayStrategy:Z,verbose:$});if(q){if($)c.success(`Configuration loaded from home directory: ${q.source.path}`);return q}}return null}async loadPackageJsonConfiguration(Q,X,Y,Z,$,H,U){let _=U?PQ(Q,Z,H):Z;try{let J=d(Y,"package.json");if(!LZ(J))return null;let G={};try{G=JSON.parse(KZ(J,"utf8"))}catch(z){if(H)c.warn("Failed to parse package.json:",[z instanceof Error?z:Error(String(z))]);return null}let q=G[Q],A=Q;if(!q&&X){let z=Array.isArray(X)?X:[X];for(let W of z){if(!W)continue;if(G[W]){q=G[W],A=W;break}}}if(q&&typeof q==="object"&&!Array.isArray(q)){if(H)c.success(`Configuration loaded from package.json: ${A}`);return{config:AZ(_,q,$),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(H)c.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables(Q,X,Y,Z){if(!Y||!Q||typeof X!=="object"||X===null||Array.isArray(X))return{config:X,source:{type:"default",priority:10,timestamp:new Date}};return{config:PQ(Q,X,Z),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(Q,X,Y,Z,$){return{config:Q.config,source:Q.source,path:Q.source.path}}async validateConfiguration(Q,X,Y,Z){let $=[];if(Y){let H=Y(Q);if(H)$.push(...H)}if(X){let H=await this.validator.validateConfiguration(Q,X);if(!H.isValid)$.push(...H.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if($.length>0)throw BQ.configValidation(Z||"unknown",$,Z)}checkCache(Q,X){let Y=this.generateCacheKey(Q,X);return fQ.get(Y)||null}cacheResult(Q,X,Y,Z){let $=this.generateCacheKey(Q,Z);fQ.set($,X,void 0,Y.ttl)}generateCacheKey(Q,X){let Y=[Q];if(X.alias){let Z=Array.isArray(X.alias)?X.alias.join(","):X.alias;Y.push(`alias:${Z}`)}if(X.cwd)Y.push(`cwd:${X.cwd}`);if(X.configDir)Y.push(`configDir:${X.configDir}`);if("checkEnv"in X)Y.push(`checkEnv:${X.checkEnv}`);return Y.join("|")}getLocalDirectories(Q,X){return Array.from(new Set([Q,d(Q,"config"),d(Q,".config"),X?d(Q,X):void 0].filter(Boolean)))}getAllSearchPaths(Q,X,Y,Z){let $=[];return $.push(...this.getLocalSearchPaths(Q,X,Y,Z)),$.push(...this.getHomeSearchPaths(Q,X)),$.push(d(Y,"package.json")),$}getLocalSearchPaths(Q,X,Y,Z){let $=this.getLocalDirectories(Y,Z),H=[];for(let U of $)H.push(...this.fileLoader.generateConfigPaths(Q,U,X));return H}getHomeSearchPaths(Q,X){if(!Q)return[];let Y=[d(YQ(),".config",Q),d(YQ(),".config"),YQ()],Z=[];for(let $ of Y)Z.push(...this.fileLoader.generateConfigPaths(Q,$,X));return Z}async loadConfigWithResult(Q){return this.loadConfig(Q)}}var MX=new BZ;async function RZ(Q){let X="defaultConfig"in Q&&Q.defaultConfig!==void 0?Q.defaultConfig:{},Y="cache"in Q||"performance"in Q||"schema"in Q||"validate"in Q;try{let Z;if(Y)Z=await MX.loadConfig(Q);else Z=await MX.loadConfig({...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}});return Z?.config??X}catch(Z){let $=Z instanceof Error?Z.name:"UnknownError",H=Z instanceof Error?Z.message:String(Z);if(!($==="ConfigNotFoundError"||$==="ConfigLoadError"||$==="ConfigValidationError"||H.includes("config"))&&Q.verbose)c.warn("Unexpected error loading config, using defaults:",[Z instanceof Error?Z:Error(String(Z))]);let _=Y?{...Q,defaultConfig:X}:{...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Q?Q.checkEnv!==!1:!0)return(await MX.applyEnvironmentVariables(_.name||"",X,!0,_.verbose||!1))?.config??X;return X}}function PQ(Q,X,Y=!1){let Z=new cX,$=Q.toUpperCase().replace(/[^A-Z0-9]/g,"_");function H(U,_=[]){let J={...U};for(let[G,q]of Object.entries(U)){let A=[..._,G],z=[`${$}_${A.join("_").toUpperCase()}`,`${$}_${A.map((B)=>B.toUpperCase()).join("")}`,`${$}_${A.map((B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],W,I;for(let B of z)if(W=eQ.env[B],W!==void 0){I=B;break}if(W!==void 0&&I)if(typeof q==="boolean")J[G]=["true","1","yes"].includes(W.toLowerCase());else if(typeof q==="number"){let B=Number(W);if(!Number.isNaN(B))J[G]=B}else if(Array.isArray(q))try{J[G]=JSON.parse(W)}catch{J[G]=W.split(",").map((B)=>B.trim())}else J[G]=W;else if(q&&typeof q==="object"&&!Array.isArray(q))J[G]=H(q,A)}return J}return H(X)}var V$=d(eQ.cwd(),"config"),E$=d(eQ.cwd(),"src/generated");var wZ={floatPrecision:3,verbose:!1},lX=null;async function N$(){if(!lX)lX=await RZ({name:"css",defaultConfig:wZ});return lX}var C$=wZ;export{N8 as walk,u8 as syntax,k8 as stringifySelector,m8 as specificity,v8 as selectOne,y8 as selectAll,x8 as parseSelector,O8 as parse,p8 as minifyBlock,f8 as minify,P8 as isTraversal,d8 as is,N$ as getConfig,T8 as generate,wZ as defaultConfig,C8 as csstree,g8 as csso,b8 as cssWhat,h8 as cssSelect,C$ as config,E8 as clone,V8 as List};
|