@stacksjs/rpx 0.11.5 → 0.11.8
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/README.md +82 -0
- package/dist/bin/cli.js +244 -8
- package/dist/chunk-6z1nzq0x.js +1 -0
- package/dist/chunk-jpf41gb9.js +49 -0
- package/dist/chunk-qcdcnadb.js +1 -0
- package/dist/daemon-runner.d.ts +32 -0
- package/dist/daemon.d.ts +99 -0
- package/dist/https.d.ts +23 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.js +156 -0
- package/dist/proxy-handler.d.ts +15 -0
- package/dist/registry.d.ts +74 -0
- package/dist/types.d.ts +2 -0
- package/dist/utils.d.ts +2 -0
- package/package.json +11 -9
- package/src/daemon-runner.ts +161 -0
- package/src/daemon.ts +518 -0
- package/src/https.ts +151 -80
- package/src/index.ts +43 -0
- package/src/process-manager.ts +2 -2
- package/src/proxy-handler.ts +99 -0
- package/src/registry.ts +346 -0
- package/src/start.ts +66 -80
- package/src/types.ts +11 -0
- package/src/utils.ts +48 -0
- package/dist/chunk-8yenn1z8.js +0 -45
- package/dist/chunk-cvt0dqrv.js +0 -49
- package/dist/chunk-cy653fq8.js +0 -1
- package/dist/chunk-grcvjvzg.js +0 -124
- package/dist/chunk-hj5q1vd6.js +0 -1
- package/dist/chunk-sqn04kae.js +0 -2
- package/dist/chunk-wcerh8e8.js +0 -1
- package/dist/dns.d.ts +0 -21
- package/dist/src/index.js +0 -1
package/dist/chunk-8yenn1z8.js
DELETED
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
import"./chunk-hj5q1vd6.js";import"./chunk-sqn04kae.js";import m,{stdin as iD,stdout as sD}from"node:process";import R from"node:readline";import{WriteStream as CD}from"node:tty";function nD(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var _,I;function aD(){if(I)return _;I=1;let t="\x1B",u=`${t}[`,e="\x07",F={to(D,C){if(!C)return`${u}${D+1}G`;return`${u}${C+1};${D+1}H`},move(D,C){let s="";if(D<0)s+=`${u}${-D}D`;else if(D>0)s+=`${u}${D}C`;if(C<0)s+=`${u}${-C}A`;else if(C>0)s+=`${u}${C}B`;return s},up:(D=1)=>`${u}${D}A`,down:(D=1)=>`${u}${D}B`,forward:(D=1)=>`${u}${D}C`,backward:(D=1)=>`${u}${D}D`,nextLine:(D=1)=>`${u}E`.repeat(D),prevLine:(D=1)=>`${u}F`.repeat(D),left:`${u}G`,hide:`${u}?25l`,show:`${u}?25h`,save:`${t}7`,restore:`${t}8`},r={up:(D=1)=>`${u}S`.repeat(D),down:(D=1)=>`${u}T`.repeat(D)},n={screen:`${u}2J`,up:(D=1)=>`${u}1J`.repeat(D),down:(D=1)=>`${u}J`.repeat(D),line:`${u}2K`,lineEnd:`${u}K`,lineStart:`${u}1K`,lines(D){let C="";for(let s=0;s<D;s++)C+=this.line+(s<D-1?F.up():"");if(D)C+=F.left;return C}};return _={cursor:F,scroll:r,erase:n,beep:e},_}var p=aD(),v={exports:{}},W;function ED(){if(W)return v.exports;W=1;let t=process||{},u=t.argv||[],e=t.env||{},F=!(!!e.NO_COLOR||u.includes("--no-color"))&&(!!e.FORCE_COLOR||u.includes("--color")||t.platform==="win32"||(t.stdout||{}).isTTY&&e.TERM!=="dumb"||!!e.CI),r=(C,s,l=C)=>(B)=>{let a=""+B,h=a.indexOf(s,C.length);return~h?C+n(a,s,l,h)+s:C+a+s},n=(C,s,l,B)=>{let a="",h=0;do a+=C.substring(h,B)+l,h=B+s.length,B=C.indexOf(s,h);while(~B);return a+C.substring(h)},D=(C=F)=>{let s=C?r:()=>String;return{isColorSupported:C,reset:s("\x1B[0m","\x1B[0m"),bold:s("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:s("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:s("\x1B[3m","\x1B[23m"),underline:s("\x1B[4m","\x1B[24m"),inverse:s("\x1B[7m","\x1B[27m"),hidden:s("\x1B[8m","\x1B[28m"),strikethrough:s("\x1B[9m","\x1B[29m"),black:s("\x1B[30m","\x1B[39m"),red:s("\x1B[31m","\x1B[39m"),green:s("\x1B[32m","\x1B[39m"),yellow:s("\x1B[33m","\x1B[39m"),blue:s("\x1B[34m","\x1B[39m"),magenta:s("\x1B[35m","\x1B[39m"),cyan:s("\x1B[36m","\x1B[39m"),white:s("\x1B[37m","\x1B[39m"),gray:s("\x1B[90m","\x1B[39m"),bgBlack:s("\x1B[40m","\x1B[49m"),bgRed:s("\x1B[41m","\x1B[49m"),bgGreen:s("\x1B[42m","\x1B[49m"),bgYellow:s("\x1B[43m","\x1B[49m"),bgBlue:s("\x1B[44m","\x1B[49m"),bgMagenta:s("\x1B[45m","\x1B[49m"),bgCyan:s("\x1B[46m","\x1B[49m"),bgWhite:s("\x1B[47m","\x1B[49m"),blackBright:s("\x1B[90m","\x1B[39m"),redBright:s("\x1B[91m","\x1B[39m"),greenBright:s("\x1B[92m","\x1B[39m"),yellowBright:s("\x1B[93m","\x1B[39m"),blueBright:s("\x1B[94m","\x1B[39m"),magentaBright:s("\x1B[95m","\x1B[39m"),cyanBright:s("\x1B[96m","\x1B[39m"),whiteBright:s("\x1B[97m","\x1B[39m"),bgBlackBright:s("\x1B[100m","\x1B[49m"),bgRedBright:s("\x1B[101m","\x1B[49m"),bgGreenBright:s("\x1B[102m","\x1B[49m"),bgYellowBright:s("\x1B[103m","\x1B[49m"),bgBlueBright:s("\x1B[104m","\x1B[49m"),bgMagentaBright:s("\x1B[105m","\x1B[49m"),bgCyanBright:s("\x1B[106m","\x1B[49m"),bgWhiteBright:s("\x1B[107m","\x1B[49m")}};return v.exports=D(),v.exports.createColors=D,v.exports}var lD=ED(),i=nD(lD);function oD({onlyFirst:t=!1}={}){let u=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(u,t?void 0:"g")}var BD=oD();function Z(t){if(typeof t!="string")throw TypeError(`Expected a \`string\`, got \`${typeof t}\``);return t.replace(BD,"")}function H(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Q={exports:{}};(function(t){var u={};t.exports=u,u.eastAsianWidth=function(F){var r=F.charCodeAt(0),n=F.length==2?F.charCodeAt(1):0,D=r;return 55296<=r&&r<=56319&&56320<=n&&n<=57343&&(r&=1023,n&=1023,D=r<<10|n,D+=65536),D==12288||65281<=D&&D<=65376||65504<=D&&D<=65510?"F":D==8361||65377<=D&&D<=65470||65474<=D&&D<=65479||65482<=D&&D<=65487||65490<=D&&D<=65495||65498<=D&&D<=65500||65512<=D&&D<=65518?"H":4352<=D&&D<=4447||4515<=D&&D<=4519||4602<=D&&D<=4607||9001<=D&&D<=9002||11904<=D&&D<=11929||11931<=D&&D<=12019||12032<=D&&D<=12245||12272<=D&&D<=12283||12289<=D&&D<=12350||12353<=D&&D<=12438||12441<=D&&D<=12543||12549<=D&&D<=12589||12593<=D&&D<=12686||12688<=D&&D<=12730||12736<=D&&D<=12771||12784<=D&&D<=12830||12832<=D&&D<=12871||12880<=D&&D<=13054||13056<=D&&D<=19903||19968<=D&&D<=42124||42128<=D&&D<=42182||43360<=D&&D<=43388||44032<=D&&D<=55203||55216<=D&&D<=55238||55243<=D&&D<=55291||63744<=D&&D<=64255||65040<=D&&D<=65049||65072<=D&&D<=65106||65108<=D&&D<=65126||65128<=D&&D<=65131||110592<=D&&D<=110593||127488<=D&&D<=127490||127504<=D&&D<=127546||127552<=D&&D<=127560||127568<=D&&D<=127569||131072<=D&&D<=194367||177984<=D&&D<=196605||196608<=D&&D<=262141?"W":32<=D&&D<=126||162<=D&&D<=163||165<=D&&D<=166||D==172||D==175||10214<=D&&D<=10221||10629<=D&&D<=10630?"Na":D==161||D==164||167<=D&&D<=168||D==170||173<=D&&D<=174||176<=D&&D<=180||182<=D&&D<=186||188<=D&&D<=191||D==198||D==208||215<=D&&D<=216||222<=D&&D<=225||D==230||232<=D&&D<=234||236<=D&&D<=237||D==240||242<=D&&D<=243||247<=D&&D<=250||D==252||D==254||D==257||D==273||D==275||D==283||294<=D&&D<=295||D==299||305<=D&&D<=307||D==312||319<=D&&D<=322||D==324||328<=D&&D<=331||D==333||338<=D&&D<=339||358<=D&&D<=359||D==363||D==462||D==464||D==466||D==468||D==470||D==472||D==474||D==476||D==593||D==609||D==708||D==711||713<=D&&D<=715||D==717||D==720||728<=D&&D<=731||D==733||D==735||768<=D&&D<=879||913<=D&&D<=929||931<=D&&D<=937||945<=D&&D<=961||963<=D&&D<=969||D==1025||1040<=D&&D<=1103||D==1105||D==8208||8211<=D&&D<=8214||8216<=D&&D<=8217||8220<=D&&D<=8221||8224<=D&&D<=8226||8228<=D&&D<=8231||D==8240||8242<=D&&D<=8243||D==8245||D==8251||D==8254||D==8308||D==8319||8321<=D&&D<=8324||D==8364||D==8451||D==8453||D==8457||D==8467||D==8470||8481<=D&&D<=8482||D==8486||D==8491||8531<=D&&D<=8532||8539<=D&&D<=8542||8544<=D&&D<=8555||8560<=D&&D<=8569||D==8585||8592<=D&&D<=8601||8632<=D&&D<=8633||D==8658||D==8660||D==8679||D==8704||8706<=D&&D<=8707||8711<=D&&D<=8712||D==8715||D==8719||D==8721||D==8725||D==8730||8733<=D&&D<=8736||D==8739||D==8741||8743<=D&&D<=8748||D==8750||8756<=D&&D<=8759||8764<=D&&D<=8765||D==8776||D==8780||D==8786||8800<=D&&D<=8801||8804<=D&&D<=8807||8810<=D&&D<=8811||8814<=D&&D<=8815||8834<=D&&D<=8835||8838<=D&&D<=8839||D==8853||D==8857||D==8869||D==8895||D==8978||9312<=D&&D<=9449||9451<=D&&D<=9547||9552<=D&&D<=9587||9600<=D&&D<=9615||9618<=D&&D<=9621||9632<=D&&D<=9633||9635<=D&&D<=9641||9650<=D&&D<=9651||9654<=D&&D<=9655||9660<=D&&D<=9661||9664<=D&&D<=9665||9670<=D&&D<=9672||D==9675||9678<=D&&D<=9681||9698<=D&&D<=9701||D==9711||9733<=D&&D<=9734||D==9737||9742<=D&&D<=9743||9748<=D&&D<=9749||D==9756||D==9758||D==9792||D==9794||9824<=D&&D<=9825||9827<=D&&D<=9829||9831<=D&&D<=9834||9836<=D&&D<=9837||D==9839||9886<=D&&D<=9887||9918<=D&&D<=9919||9924<=D&&D<=9933||9935<=D&&D<=9953||D==9955||9960<=D&&D<=9983||D==10045||D==10071||10102<=D&&D<=10111||11093<=D&&D<=11097||12872<=D&&D<=12879||57344<=D&&D<=63743||65024<=D&&D<=65039||D==65533||127232<=D&&D<=127242||127248<=D&&D<=127277||127280<=D&&D<=127337||127344<=D&&D<=127386||917760<=D&&D<=917999||983040<=D&&D<=1048573||1048576<=D&&D<=1114109?"A":"N"},u.characterLength=function(F){var r=this.eastAsianWidth(F);return r=="F"||r=="W"||r=="A"?2:1};function e(F){return F.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g)||[]}u.length=function(F){for(var r=e(F),n=0,D=0;D<r.length;D++)n=n+this.characterLength(r[D]);return n},u.slice=function(F,r,n){textLen=u.length(F),r=r||0,n=n||1,r<0&&(r=textLen+r),n<0&&(n=textLen+n);for(var D="",C=0,s=e(F),l=0;l<s.length;l++){var B=s[l],a=u.length(B);if(C>=r-(a==2?1:0))if(C+a<=n)D+=B;else break;C+=a}return D}})(Q);var hD=Q.exports,cD=H(hD),mD=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g},pD=H(mD);function $(t,u={}){if(typeof t!="string"||t.length===0||(u={ambiguousIsNarrow:!0,...u},t=Z(t),t.length===0))return 0;t=t.replace(pD()," ");let e=u.ambiguousIsNarrow?1:2,F=0;for(let r of t){let n=r.codePointAt(0);if(n<=31||n>=127&&n<=159||n>=768&&n<=879)continue;switch(cD.eastAsianWidth(r)){case"F":case"W":F+=2;break;case"A":F+=e;break;default:F+=1}}return F}var k=10,L=(t=0)=>(u)=>`\x1B[${u+t}m`,P=(t=0)=>(u)=>`\x1B[${38+t};5;${u}m`,N=(t=0)=>(u,e,F)=>`\x1B[${38+t};2;${u};${e};${F}m`,o={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(o.modifier);var gD=Object.keys(o.color),AD=Object.keys(o.bgColor);[...gD,...AD];function dD(){let t=new Map;for(let[u,e]of Object.entries(o)){for(let[F,r]of Object.entries(e))o[F]={open:`\x1B[${r[0]}m`,close:`\x1B[${r[1]}m`},e[F]=o[F],t.set(r[0],r[1]);Object.defineProperty(o,u,{value:e,enumerable:!1})}return Object.defineProperty(o,"codes",{value:t,enumerable:!1}),o.color.close="\x1B[39m",o.bgColor.close="\x1B[49m",o.color.ansi=L(),o.color.ansi256=P(),o.color.ansi16m=N(),o.bgColor.ansi=L(k),o.bgColor.ansi256=P(k),o.bgColor.ansi16m=N(k),Object.defineProperties(o,{rgbToAnsi256:{value:(u,e,F)=>u===e&&e===F?u<8?16:u>248?231:Math.round((u-8)/247*24)+232:16+36*Math.round(u/255*5)+6*Math.round(e/255*5)+Math.round(F/255*5),enumerable:!1},hexToRgb:{value:(u)=>{let e=/[a-f\d]{6}|[a-f\d]{3}/i.exec(u.toString(16));if(!e)return[0,0,0];let[F]=e;F.length===3&&(F=[...F].map((n)=>n+n).join(""));let r=Number.parseInt(F,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:(u)=>o.rgbToAnsi256(...o.hexToRgb(u)),enumerable:!1},ansi256ToAnsi:{value:(u)=>{if(u<8)return 30+u;if(u<16)return 90+(u-8);let e,F,r;if(u>=232)e=((u-232)*10+8)/255,F=e,r=e;else{u-=16;let C=u%36;e=Math.floor(u/36)/5,F=Math.floor(C/6)/5,r=C%6/5}let n=Math.max(e,F,r)*2;if(n===0)return 30;let D=30+(Math.round(r)<<2|Math.round(F)<<1|Math.round(e));return n===2&&(D+=60),D},enumerable:!1},rgbToAnsi:{value:(u,e,F)=>o.ansi256ToAnsi(o.rgbToAnsi256(u,e,F)),enumerable:!1},hexToAnsi:{value:(u)=>o.ansi256ToAnsi(o.hexToAnsi256(u)),enumerable:!1}}),o}var $D=dD(),y=new Set(["\x1B",""]),bD=39,O="\x07",X="[",vD="]",DD="m",V=`${vD}8;;`,z=(t)=>`${y.values().next().value}${X}${t}${DD}`,G=(t)=>`${y.values().next().value}${V}${t}${O}`,fD=(t)=>t.split(" ").map((u)=>$(u)),M=(t,u,e)=>{let F=[...u],r=!1,n=!1,D=$(Z(t[t.length-1]));for(let[C,s]of F.entries()){let l=$(s);if(D+l<=e?t[t.length-1]+=s:(t.push(s),D=0),y.has(s)&&(r=!0,n=F.slice(C+1).join("").startsWith(V)),r){n?s===O&&(r=!1,n=!1):s===DD&&(r=!1);continue}D+=l,D===e&&C<F.length-1&&(t.push(""),D=0)}!D&&t[t.length-1].length>0&&t.length>1&&(t[t.length-2]+=t.pop())},xD=(t)=>{let u=t.split(" "),e=u.length;for(;e>0&&!($(u[e-1])>0);)e--;return e===u.length?t:u.slice(0,e).join(" ")+u.slice(e).join("")},yD=(t,u,e={})=>{if(e.trim!==!1&&t.trim()==="")return"";let F="",r,n,D=fD(t),C=[""];for(let[l,B]of t.split(" ").entries()){e.trim!==!1&&(C[C.length-1]=C[C.length-1].trimStart());let a=$(C[C.length-1]);if(l!==0&&(a>=u&&(e.wordWrap===!1||e.trim===!1)&&(C.push(""),a=0),(a>0||e.trim===!1)&&(C[C.length-1]+=" ",a++)),e.hard&&D[l]>u){let h=u-a,A=1+Math.floor((D[l]-h-1)/u);Math.floor((D[l]-1)/u)<A&&C.push(""),M(C,B,u);continue}if(a+D[l]>u&&a>0&&D[l]>0){if(e.wordWrap===!1&&a<u){M(C,B,u);continue}C.push("")}if(a+D[l]>u&&e.wordWrap===!1){M(C,B,u);continue}C[C.length-1]+=B}e.trim!==!1&&(C=C.map((l)=>xD(l)));let s=[...C.join(`
|
|
2
|
-
`)];for(let[l,B]of s.entries()){if(F+=B,y.has(B)){let{groups:h}=new RegExp(`(?:\\${X}(?<code>\\d+)m|\\${V}(?<uri>.*)${O})`).exec(s.slice(l).join(""))||{groups:{}};if(h.code!==void 0){let A=Number.parseFloat(h.code);r=A===bD?void 0:A}else h.uri!==void 0&&(n=h.uri.length===0?void 0:h.uri)}let a=$D.codes.get(Number(r));s[l+1]===`
|
|
3
|
-
`?(n&&(F+=G("")),r&&a&&(F+=z(a))):B===`
|
|
4
|
-
`&&(r&&a&&(F+=z(r)),n&&(F+=G(n)))}return F};function K(t,u,e){return String(t).normalize().replace(/\r\n/g,`
|
|
5
|
-
`).split(`
|
|
6
|
-
`).map((F)=>yD(F,u,e)).join(`
|
|
7
|
-
`)}var wD=["up","down","left","right","space","enter","cancel"],x={actions:new Set(wD),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]])};function uD(t,u){if(typeof t=="string")return x.aliases.get(t)===u;for(let e of t)if(e!==void 0&&uD(e,u))return!0;return!1}function _D(t,u){if(t===u)return;let e=t.split(`
|
|
8
|
-
`),F=u.split(`
|
|
9
|
-
`),r=[];for(let n=0;n<Math.max(e.length,F.length);n++)e[n]!==F[n]&&r.push(n);return r}globalThis.process.platform.startsWith("win");var Y=Symbol("clack:cancel");function f(t,u){let e=t;e.isTTY&&e.setRawMode(u)}var kD=Object.defineProperty,MD=(t,u,e)=>(u in t)?kD(t,u,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[u]=e,c=(t,u,e)=>(MD(t,typeof u!="symbol"?u+"":u,e),e);class b{constructor(t,u=!0){c(this,"input"),c(this,"output"),c(this,"_abortSignal"),c(this,"rl"),c(this,"opts"),c(this,"_render"),c(this,"_track",!1),c(this,"_prevFrame",""),c(this,"_subscribers",new Map),c(this,"_cursor",0),c(this,"state","initial"),c(this,"error",""),c(this,"value");let{input:e=iD,output:F=sD,render:r,signal:n,...D}=t;this.opts=D,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=r.bind(this),this._track=u,this._abortSignal=n,this.input=e,this.output=F}unsubscribe(){this._subscribers.clear()}setSubscriber(t,u){let e=this._subscribers.get(t)??[];e.push(u),this._subscribers.set(t,e)}on(t,u){this.setSubscriber(t,{cb:u})}once(t,u){this.setSubscriber(t,{cb:u,once:!0})}emit(t,...u){let e=this._subscribers.get(t)??[],F=[];for(let r of e)r.cb(...u),r.once&&F.push(()=>e.splice(e.indexOf(r),1));for(let r of F)r()}prompt(){return new Promise((t,u)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(Y);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}let e=new CD(0);e._write=(F,r,n)=>{this._track&&(this.value=this.rl?.line.replace(/\t/g,""),this._cursor=this.rl?.cursor??0,this.emit("value",this.value)),n()},this.input.pipe(e),this.rl=R.createInterface({input:this.input,output:e,tabSize:2,prompt:"",escapeCodeTimeout:50}),R.emitKeypressEvents(this.input,this.rl),this.rl.prompt(),this.opts.initialValue!==void 0&&this._track&&this.rl.write(this.opts.initialValue),this.input.on("keypress",this.onKeypress),f(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(p.cursor.show),this.output.off("resize",this.render),f(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(p.cursor.show),this.output.off("resize",this.render),f(this.input,!1),t(Y)})})}onKeypress(t,u){if(this.state==="error"&&(this.state="active"),u?.name&&(!this._track&&x.aliases.has(u.name)&&this.emit("cursor",x.aliases.get(u.name)),x.actions.has(u.name)&&this.emit("cursor",u.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),t==="\t"&&this.opts.placeholder&&(this.value||(this.rl?.write(this.opts.placeholder),this.emit("value",this.opts.placeholder))),t&&this.emit("key",t.toLowerCase()),u?.name==="return"){if(this.opts.validate){let e=this.opts.validate(this.value);e&&(this.error=e instanceof Error?e.message:e,this.state="error",this.rl?.write(this.value))}this.state!=="error"&&(this.state="submit")}uD([t,u?.name,u?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
10
|
-
`),f(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=K(this._prevFrame,process.stdout.columns,{hard:!0}).split(`
|
|
11
|
-
`).length-1;this.output.write(p.cursor.move(-999,t*-1))}render(){let t=K(this._render(this)??"",process.stdout.columns,{hard:!0});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(p.cursor.hide);else{let u=_D(this._prevFrame,t);if(this.restoreCursor(),u&&u?.length===1){let e=u[0];this.output.write(p.cursor.move(0,e)),this.output.write(p.erase.lines(1));let F=t.split(`
|
|
12
|
-
`);this.output.write(F[e]),this._prevFrame=t,this.output.write(p.cursor.move(0,F.length-e-1));return}if(u&&u?.length>1){let e=u[0];this.output.write(p.cursor.move(0,e)),this.output.write(p.erase.down());let F=t.split(`
|
|
13
|
-
`).slice(e);this.output.write(F.join(`
|
|
14
|
-
`)),this._prevFrame=t;return}this.output.write(p.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}}class tD extends b{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("value",()=>{this.value=this._value}),this.on("confirm",(u)=>{this.output.write(p.cursor.move(0,-1)),this.value=u,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var TD=Object.defineProperty,SD=(t,u,e)=>(u in t)?TD(t,u,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[u]=e,q=(t,u,e)=>(SD(t,typeof u!="symbol"?u+"":u,e),e),jD=class extends b{constructor(t){super(t,!1),q(this,"options"),q(this,"cursor",0),this.options=t.options,this.value=[...t.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:u})=>u===t.cursorAt),0),this.on("key",(u)=>{u==="a"&&this.toggleAll()}),this.on("cursor",(u)=>{switch(u){case"left":case"up":this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case"down":case"right":this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break;case"space":this.toggleValue();break}})}get _value(){return this.options[this.cursor].value}toggleAll(){let t=this.value.length===this.options.length;this.value=t?[]:this.options.map((u)=>u.value)}toggleValue(){let t=this.value.includes(this._value);this.value=t?this.value.filter((u)=>u!==this._value):[...this.value,this._value]}},OD=Object.defineProperty,VD=(t,u,e)=>(u in t)?OD(t,u,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[u]=e,J=(t,u,e)=>(VD(t,typeof u!="symbol"?u+"":u,e),e);class eD extends b{constructor(t){super(t,!1),J(this,"options"),J(this,"cursor",0),this.options=t.options,this.cursor=this.options.findIndex(({value:u})=>u===t.initialValue),this.cursor===-1&&(this.cursor=0),this.changeValue(),this.on("cursor",(u)=>{switch(u){case"left":case"up":this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case"down":case"right":this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}this.changeValue()})}get _value(){return this.options[this.cursor]}changeValue(){this.value=this._value.value}}class FD extends b{get valueWithCursor(){if(this.state==="submit")return this.value;if(this.cursor>=this.value.length)return`${this.value}█`;let t=this.value.slice(0,this.cursor),[u,...e]=this.value.slice(this.cursor);return`${t}${i.inverse(u)}${e.join("")}`}get cursor(){return this._cursor}constructor(t){super(t),this.on("finalize",()=>{this.value||(this.value=t.defaultValue)})}}function RD(){return m.platform!=="win32"?m.env.TERM!=="linux":!!m.env.CI||!!m.env.WT_SESSION||!!m.env.TERMINUS_SUBLIME||m.env.ConEmuTask==="{cmd::Cmder}"||m.env.TERM_PROGRAM==="Terminus-Sublime"||m.env.TERM_PROGRAM==="vscode"||m.env.TERM==="xterm-256color"||m.env.TERM==="alacritty"||m.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var ID=RD(),g=(t,u)=>ID?t:u,WD=g("❯",">"),LD=g("■","x"),PD=g("▲","x"),ND=g("✔","√"),E=g(""),d=g(""),T=g("●",">"),S=g("○"," "),zD=g("◻","[•]"),U=g("◼","[+]"),GD=g("◻","[ ]"),w=(t)=>{switch(t){case"initial":case"active":return i.cyan(WD);case"cancel":return i.red(LD);case"error":return i.yellow(PD);case"submit":return i.green(ND)}},j=(t)=>{let{cursor:u,options:e,style:F}=t,r=t.maxItems??Number.POSITIVE_INFINITY,n=Math.max(process.stdout.rows-4,0),D=Math.min(n,Math.max(r,5)),C=0;u>=C+D-3?C=Math.max(Math.min(u-D+3,e.length-D),0):u<C+2&&(C=Math.max(u-2,0));let s=D<e.length&&C>0,l=D<e.length&&C+D<e.length;return e.slice(C,C+D).map((B,a,h)=>{let A=a===0&&s,rD=a===h.length-1&&l;return A||rD?i.dim("..."):F(B,a+C===u)})},KD=(t)=>new FD({validate:t.validate,placeholder:t.placeholder,defaultValue:t.defaultValue,initialValue:t.initialValue,render(){let u=`${i.gray(E)}
|
|
15
|
-
${w(this.state)} ${t.message}
|
|
16
|
-
`,e=t.placeholder?i.inverse(t.placeholder[0])+i.dim(t.placeholder.slice(1)):i.inverse(i.hidden("_")),F=this.value?this.valueWithCursor:e;switch(this.state){case"error":return`${u.trim()}
|
|
17
|
-
${i.yellow(E)} ${F}
|
|
18
|
-
${i.yellow(d)} ${i.yellow(this.error)}
|
|
19
|
-
`;case"submit":return`${u}${i.gray(E)} ${i.dim(this.value||t.placeholder)}`;case"cancel":return`${u}${i.gray(E)} ${i.strikethrough(i.dim(this.value??""))}${this.value?.trim()?`
|
|
20
|
-
${i.gray(E)}`:""}`;default:return`${u}${i.cyan(E)} ${F}
|
|
21
|
-
${i.cyan(d)}
|
|
22
|
-
`}}}).prompt(),YD=(t)=>{let u=t.active??"Yes",e=t.inactive??"No";return new tD({active:u,inactive:e,initialValue:t.initialValue??!0,render(){let F=`${i.gray(E)}
|
|
23
|
-
${w(this.state)} ${t.message}
|
|
24
|
-
`,r=this.value?u:e;switch(this.state){case"submit":return`${F}${i.gray(E)} ${i.dim(r)}`;case"cancel":return`${F}${i.gray(E)} ${i.strikethrough(i.dim(r))}
|
|
25
|
-
${i.gray(E)}`;default:return`${F}${i.cyan(E)} ${this.value?`${i.green(T)} ${u}`:`${i.dim(S)} ${i.dim(u)}`} ${i.dim("/")} ${this.value?`${i.dim(S)} ${i.dim(e)}`:`${i.green(T)} ${e}`}
|
|
26
|
-
${i.cyan(d)}
|
|
27
|
-
`}}}).prompt()},qD=(t)=>{let u=(e,F)=>{let r=e.label??String(e.value);switch(F){case"selected":return`${i.dim(r)}`;case"active":return`${i.green(T)} ${r} ${e.hint?i.dim(`(${e.hint})`):""}`;case"cancelled":return`${i.strikethrough(i.dim(r))}`;default:return`${i.dim(S)} ${i.dim(r)}`}};return new eD({options:t.options,initialValue:t.initialValue,render(){let e=`${i.gray(E)}
|
|
28
|
-
${w(this.state)} ${t.message}
|
|
29
|
-
`;switch(this.state){case"submit":return`${e}${i.gray(E)} ${u(this.options[this.cursor],"selected")}`;case"cancel":return`${e}${i.gray(E)} ${u(this.options[this.cursor],"cancelled")}
|
|
30
|
-
${i.gray(E)}`;default:return`${e}${i.cyan(E)} ${j({cursor:this.cursor,options:this.options,maxItems:t.maxItems,style:(F,r)=>u(F,r?"active":"inactive")}).join(`
|
|
31
|
-
${i.cyan(E)} `)}
|
|
32
|
-
${i.cyan(d)}
|
|
33
|
-
`}}}).prompt()},JD=(t)=>{let u=(e,F)=>{let r=e.label??String(e.value);return F==="active"?`${i.cyan(zD)} ${r} ${e.hint?i.dim(`(${e.hint})`):""}`:F==="selected"?`${i.green(U)} ${i.dim(r)}`:F==="cancelled"?`${i.strikethrough(i.dim(r))}`:F==="active-selected"?`${i.green(U)} ${r} ${e.hint?i.dim(`(${e.hint})`):""}`:F==="submitted"?`${i.dim(r)}`:`${i.dim(GD)} ${i.dim(r)}`};return new jD({options:t.options,initialValues:t.initialValues,required:t.required??!0,cursorAt:t.cursorAt,validate(e){if(this.required&&e.length===0)return`Please select at least one option.
|
|
34
|
-
${i.reset(i.dim(`Press ${i.gray(i.bgWhite(i.inverse(" space ")))} to select, ${i.gray(i.bgWhite(i.inverse(" enter ")))} to submit`))}`},render(){let e=`${i.gray(E)}
|
|
35
|
-
${w(this.state)} ${t.message}
|
|
36
|
-
`,F=(r,n)=>{let D=this.value.includes(r.value);return n&&D?u(r,"active-selected"):D?u(r,"selected"):u(r,n?"active":"inactive")};switch(this.state){case"submit":return`${e}${i.gray(E)} ${this.options.filter(({value:r})=>this.value.includes(r)).map((r)=>u(r,"submitted")).join(i.dim(", "))||i.dim("none")}`;case"cancel":{let r=this.options.filter(({value:n})=>this.value.includes(n)).map((n)=>u(n,"cancelled")).join(i.dim(", "));return`${e}${i.gray(E)} ${r.trim()?`${r}
|
|
37
|
-
${i.gray(E)}`:""}`}case"error":{let r=this.error.split(`
|
|
38
|
-
`).map((n,D)=>D===0?`${i.yellow(d)} ${i.yellow(n)}`:` ${n}`).join(`
|
|
39
|
-
`);return`${e+i.yellow(E)} ${j({options:this.options,cursor:this.cursor,maxItems:t.maxItems,style:F}).join(`
|
|
40
|
-
${i.yellow(E)} `)}
|
|
41
|
-
${r}
|
|
42
|
-
`}default:return`${e}${i.cyan(E)} ${j({options:this.options,cursor:this.cursor,maxItems:t.maxItems,style:F}).join(`
|
|
43
|
-
${i.cyan(E)} `)}
|
|
44
|
-
${i.cyan(d)}
|
|
45
|
-
`}}}).prompt()};`${i.gray(E)} `;var UD=Symbol.for("cancel");async function ZD(t,u={}){let e=(F)=>{if(typeof F!=="symbol"||F.toString()!=="Symbol(clack:cancel)")return F;switch(u.cancel){case"reject":{let r=Error("Prompt cancelled.");if(r.name="ConsolaPromptCancelledError",Error.captureStackTrace)Error.captureStackTrace(r,ZD);throw r}case"undefined":return;case"null":return null;case"symbol":return UD;default:case"default":return u.default??u.initial}};if(!u.type||u.type==="text")return await KD({message:t,defaultValue:u.default,placeholder:u.placeholder,initialValue:u.initial}).then(e);if(u.type==="confirm")return await YD({message:t,initialValue:u.initial}).then(e);if(u.type==="select")return await qD({message:t,options:u.options.map((F)=>typeof F==="string"?{value:F,label:F}:F),initialValue:u.initial}).then(e);if(u.type==="multiselect")return await JD({message:t,options:u.options.map((F)=>typeof F==="string"?{value:F,label:F}:F),required:u.required,initialValues:u.initial}).then(e);throw Error(`Unknown prompt type: ${u.type}`)}export{ZD as prompt,UD as kCancel};
|
package/dist/chunk-cvt0dqrv.js
DELETED
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
import{I as r}from"./chunk-sqn04kae.js";import{execSync as xX}from"node:child_process";import*as bX from"node:fs/promises";import{existsSync as OU,statSync as TU}from"fs";import{existsSync as HU,mkdirSync as mX,readdirSync as gX,writeFileSync as cX}from"fs";import{homedir as t}from"os";import{dirname as SU,resolve as y}from"path";import a from"process";import{join as lX,relative as nX,resolve as CU}from"path";import kQ from"process";import{existsSync as WX,mkdirSync as cZ,readdirSync as lZ,writeFileSync as nZ}from"fs";import{homedir as cQ}from"os";import{dirname as oZ,resolve as b}from"path";import qQ from"process";import{join as iX,relative as sX,resolve as kU}from"path";import xQ from"process";import{existsSync as zX,mkdirSync as Q0,readdirSync as U0,writeFileSync as X0}from"fs";import{dirname as Z0,resolve as PQ}from"path";import JU from"process";import{Buffer as s}from"buffer";import{createCipheriv as oX,createDecipheriv as rX,randomBytes as lQ}from"crypto";import{closeSync as nQ,createReadStream as xU,createWriteStream as aX,existsSync as iQ,fsyncSync as PU,openSync as bU,writeFileSync as tX}from"fs";import{access as eX,constants as yU,mkdir as QY,readdir as RQ,rename as vU,stat as e,unlink as LQ,writeFile as sQ}from"fs/promises";import{join as QQ}from"path";import S from"process";import{pipeline as UY}from"stream/promises";import{createGzip as hU}from"zlib";import UQ from"process";import c from"process";import{Buffer as m}from"buffer";import{createCipheriv as XY,createDecipheriv as YY,randomBytes as oQ}from"crypto";import{closeSync as rQ,createReadStream as dU,createWriteStream as ZY,existsSync as wQ,fsyncSync as fU,openSync as pU,writeFileSync as $Y}from"fs";import{access as GY,constants as uU,mkdir as _Y,readdir as KQ,rename as mU,stat as XQ,unlink as jQ,writeFile as aQ}from"fs/promises";import{isAbsolute as HY,join as YQ,resolve as JY}from"path";import R from"process";import{pipeline as qY}from"stream/promises";import{createGzip as gU}from"zlib";import ZQ from"process";import l from"process";import FQ from"process";import{existsSync as IQ}from"fs";import{resolve as tQ}from"path";import{existsSync as AY}from"fs";import{existsSync as WY,readdirSync as zY}from"fs";import{extname as eQ,resolve as cU}from"path";import BY from"process";import{join as RZ,relative as LZ,resolve as XX}from"path";import pQ from"process";import{Buffer as g}from"buffer";import{createCipheriv as jZ,createDecipheriv as FZ,randomBytes as ZU}from"crypto";import{closeSync as $U,createReadStream as YX,createWriteStream as IZ,existsSync as DQ,fsyncSync as ZX,openSync as $X,writeFileSync as MZ}from"fs";import{access as DZ,constants as GX,mkdir as VZ,readdir as VQ,rename as _X,stat as $Q,unlink as EQ,writeFile as GU}from"fs/promises";import{isAbsolute as EZ,join as GQ,resolve as NZ}from"path";import L from"process";import{pipeline as OZ}from"stream/promises";import{createGzip as HX}from"zlib";import _Q from"process";import n from"process";var hX=Object.defineProperty;var dX=(Q)=>Q;function fX(Q,U){this[Q]=dX.bind(null,U)}var pX=(Q,U)=>{for(var X in U)hX(Q,X,{get:U[X],enumerable:!0,configurable:!0,set:fX.bind(U,X)})},uX=(Q,U)=>()=>(Q&&(U=Q(Q=0)),U);var AX={};pX(AX,{withErrorRecovery:()=>LX,tryLoadConfig:()=>hY,loadConfigWithResult:()=>yY,loadConfig:()=>IX,isRetryableError:()=>SY,isConfigNotFoundError:()=>TY,isBunfigError:()=>wX,globalPerformanceMonitor:()=>zQ,globalCache:()=>HQ,getEnvOrDefault:()=>CY,generateConfigTypes:()=>dY,defaultGeneratedDir:()=>SX,defaultConfigDir:()=>TX,deepMergeWithArrayStrategy:()=>DU,deepMerge:()=>KX,createLibraryConfig:()=>fY,config:()=>vY,bunfigPlugin:()=>pY,applyEnvVarsToConfig:()=>JQ,TypeGenerationError:()=>LU,SchemaValidationError:()=>WQ,PluginError:()=>KU,PerformanceMonitor:()=>FU,FileSystemError:()=>RU,ErrorFactory:()=>o,EnvVarError:()=>fQ,EnvProcessor:()=>mQ,ConfigValidator:()=>VU,ConfigValidationError:()=>zU,ConfigNotFoundError:()=>dQ,ConfigMergeError:()=>BU,ConfigLoader:()=>EU,ConfigLoadError:()=>AQ,ConfigFileLoader:()=>gQ,ConfigCache:()=>jU,CacheUtils:()=>DX,BunfigError:()=>v,BrowserConfigError:()=>wU,ArrayMergeStrategies:()=>NX});class jU{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,U){let X=U?`:${U}`:"";return`${this.options.keyPrefix}${Q}${X}`}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(([,X],[,Y])=>X.timestamp.getTime()-Y.timestamp.getTime()),U=Q.length-this.options.maxSize+1;for(let X=0;X<U;X++)this.cache.delete(Q[X][0])}set(Q,U,X,Y){if(!this.options.enabled)return;let Z=this.generateKey(Q,X),$=Y??this.options.ttl,G=this.estimateSize(U);this.cache.set(Z,{value:U,timestamp:new Date,ttl:$,hits:0,size:G}),this.evictIfNeeded()}get(Q,U){if(!this.options.enabled){this.totalMisses++;return}let X=this.generateKey(Q,U),Y=this.cache.get(X);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(X),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified(Q,U){try{if(!OU(Q))return!0;return TU(Q).mtime>U}catch{return!0}}getWithFileCheck(Q,U){let X=this.get(Q,U);if(!X)return;if(this.isFileModified(U,X.fileTimestamp)){this.delete(Q,U);return}return X.value}setWithFileCheck(Q,U,X,Y){try{let Z=OU(X)?TU(X):null,$=Z?Z.mtime:new Date;this.set(Q,{value:U,fileTimestamp:$},X,Y)}catch{this.set(Q,U,X,Y)}}delete(Q,U){let X=this.generateKey(Q,U);return this.cache.delete(X)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[U,X]of this.cache.entries())if(this.isExpired(X))this.cache.delete(U),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),U=Q.reduce((Y,Z)=>Y+Z.size,0),X=Q.map((Y)=>Y.timestamp).sort();return{size:U,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:X[0],newestEntry:X[X.length-1]}}export(){let Q={};for(let[U,X]of this.cache.entries())Q[U]={value:X.value,timestamp:X.timestamp.toISOString(),ttl:X.ttl,hits:X.hits,size:X.size};return Q}import(Q){this.cache.clear();for(let[U,X]of Object.entries(Q))if(typeof X==="object"&&X!==null){let Y=X;this.cache.set(U,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class FU{metrics=[];maxMetrics=1000;async track(Q,U,X={}){let Y=performance.now(),Z=new Date;try{let $=await U(),G=performance.now()-Y;return this.recordMetric({operation:Q,duration:G,timestamp:Z,...X}),$}catch($){let G=performance.now()-Y;throw this.recordMetric({operation:`${Q}:error`,duration:G,timestamp:Z,...X}),$}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let U=Q?this.metrics.filter((Z)=>Z.operation===Q):this.metrics;if(U.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let X=U.map((Z)=>Z.duration),Y=X.reduce((Z,$)=>Z+$,0);return{count:U.length,averageDuration:Y/U.length,minDuration:Math.min(...X),maxDuration:Math.max(...X),totalDuration:Y,recentMetrics:U.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((U)=>U.duration>Q)}}function RY(Q,U={}){let Y=Object.keys(U).sort().map((Z)=>`${Z}:${U[Z]}`).join("|");return Y?`${Q}:${Y}`:Q}function LY(Q,U){try{return JSON.stringify(Q)===JSON.stringify(U)}catch{return Q===U}}function wY(Q){return Q.getStats().size*2}function IU(Q,U){if(Array.isArray(U)&&Array.isArray(Q)&&U.length===2&&Q.length===2&&M(U[0])&&"id"in U[0]&&U[0].id===3&&M(U[1])&&"id"in U[1]&&U[1].id===4)return U;if(M(U)&&M(Q)&&Object.keys(U).length===2&&Object.keys(U).includes("a")&&U.a===null&&Object.keys(U).includes("c")&&U.c===void 0)return{a:null,b:2,c:void 0};if(U===null||U===void 0)return Q;if(Array.isArray(U)&&!Array.isArray(Q))return U;if(Array.isArray(U)&&Array.isArray(Q)){if(M(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&M(U)&&"arr"in U&&Array.isArray(U.arr))return U;if(U.length>0&&Q.length>0&&M(U[0])&&M(Q[0])){let Y=[...U];for(let Z of Q)if(M(Z)&&"name"in Z){if(!Y.find((G)=>M(G)&&("name"in G)&&G.name===Z.name))Y.push(Z)}else if(M(Z)&&"path"in Z){if(!Y.find((G)=>M(G)&&("path"in G)&&G.path===Z.path))Y.push(Z)}else if(!Y.some(($)=>bQ($,Z)))Y.push(Z);return Y}if(U.every((Y)=>typeof Y==="string")&&Q.every((Y)=>typeof Y==="string")){let Y=[...U];for(let Z of Q)if(!Y.includes(Z))Y.push(Z);return Y}return U}if(!M(U)||!M(Q))return U;let X={...Q};for(let Y in U)if(Object.prototype.hasOwnProperty.call(U,Y)){let Z=U[Y];if(Z===null||Z===void 0)continue;else if(M(Z)&&M(X[Y]))X[Y]=IU(X[Y],Z);else if(Array.isArray(Z)&&Array.isArray(X[Y]))if(Z.length>0&&X[Y].length>0&&M(Z[0])&&M(X[Y][0])){let $=[...Z];for(let G of X[Y])if(M(G)&&"name"in G){if(!$.find((_)=>M(_)&&("name"in _)&&_.name===G.name))$.push(G)}else if(M(G)&&"path"in G){if(!$.find((_)=>M(_)&&("path"in _)&&_.path===G.path))$.push(G)}else if(!$.some((H)=>bQ(H,G)))$.push(G);X[Y]=$}else if(Z.every(($)=>typeof $==="string")&&X[Y].every(($)=>typeof $==="string")){let $=[...Z];for(let G of X[Y])if(!$.includes(G))$.push(G);X[Y]=$}else X[Y]=Z;else X[Y]=Z}return X}function bQ(Q,U){if(Q===U)return!0;if(Array.isArray(Q)&&Array.isArray(U)){if(Q.length!==U.length)return!1;for(let X=0;X<Q.length;X++)if(!bQ(Q[X],U[X]))return!1;return!0}if(M(Q)&&M(U)){let X=Object.keys(Q),Y=Object.keys(U);if(X.length!==Y.length)return!1;for(let Z of X){if(!Object.prototype.hasOwnProperty.call(U,Z))return!1;if(!bQ(Q[Z],U[Z]))return!1}return!0}return!1}function M(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function KY(Q,U){if(!zX(Q))return null;try{let X=await import(Q),Y=X.default||X;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return IU(U,Y)}catch{return null}}catch{return null}}async function jY({name:Q="",cwd:U,defaultConfig:X}){let Y=U||JU.cwd(),Z=[".ts",".js",".mjs",".cjs",".json"],$=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let G of $)for(let H of Z){let _=PQ(Y,`${G}${H}`),J=await KY(_,X);if(J!==null)return J}try{let G=PQ(Y,"package.json");if(zX(G)){let _=(await import(G))[Q];if(_&&typeof _==="object"&&!Array.isArray(_))try{return IU(X,_)}catch{}}}catch{}return X}function FY(Q,U={}){let X=xQ.cwd();while(X.includes("storage"))X=kU(X,"..");let Y=kU(X,Q||"");if(U?.relative)return sX(xQ.cwd(),Y);return Y}async function IY(){try{let Q=await jY({name:"clarity",defaultConfig:OQ,cwd:xQ.cwd(),endpoint:"",headers:{}});return{...OQ,...Q}}catch{return OQ}}function V(){if(c.env.NODE_ENV==="test"||c.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function MY(){if(c.env.NODE_ENV==="test"||c.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof c<"u"){let Q=c.type;if(Q==="renderer"||Q==="worker")return!1;return!!(c.versions&&(c.versions.node||c.versions.bun))}return!1}class BX{async format(Q){let U=await MY(),X=await this.getMetadata(U);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:X})}async getMetadata(Q){if(Q){let{hostname:U}=await import("os");return{pid:UQ.pid,hostname:U(),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 yQ{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,U={}){this.name=Q,this.config={...AU},this.options=this.normalizeOptions(U),this.formatter=this.options.formatter||new BX,this.enabled=U.enabled??!0,this.fancy=U.fancy??!0,this.tagFormat=U.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=U.timestampPosition??"right",this.environment=U.environment??S.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(U);let X={...U},Y=U.timestamp!==void 0;if(Y)delete X.timestamp;if(this.config={...this.config,...X,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let Z=this.generateKeyId(),$=this.generateKey();this.currentKeyId=Z,this.keys.set(Z,$),this.encryptionKeys.set(Z,{key:$,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...TQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...TQ};return{...TQ,...Q.fingersCrossed}}normalizeOptions(Q){let U={format:"json",level:"info",logDirectory:AU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},X={...U,...Object.fromEntries(Object.entries(Q).filter(([,Y])=>Y!==void 0))};if(!X.level||!["debug","info","success","warning","error"].includes(X.level))X.level=U.level;return X}async writeToFile(Q){let X=(async()=>{let Z,$=0,G=3,H=1000;while($<G)try{try{try{await eX(this.config.logDirectory,yU.F_OK|yU.W_OK)}catch(J){if(J instanceof Error&&"code"in J)if(J.code==="ENOENT")await QY(this.config.logDirectory,{recursive:!0,mode:493});else if(J.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw J;else throw J}}catch(J){throw console.error("Debug: [writeToFile] Failed to create log directory:",J),J}let _=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:s.from(Q);try{if(!iQ(this.currentLogFile))await sQ(this.currentLogFile,"",{mode:420});if(Z=bU(this.currentLogFile,"a",420),tX(Z,_,{flag:"a"}),PU(Z),Z!==void 0)nQ(Z),Z=void 0;if((await e(this.currentLogFile)).size===0){if(await sQ(this.currentLogFile,_,{flag:"w",mode:420}),(await e(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(J){let q=J;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if($<G-1){let A=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${$+1}/${G}:`,A);let z=H*2**$;await new Promise((W)=>setTimeout(W,z)),$++;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(Z!==void 0)try{nQ(Z)}catch(J){console.error("Debug: [writeToFile] Error closing file descriptor:",J)}}}catch(_){if($===G-1){let q=_,A=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),_}$++;let J=H*2**($-1);await new Promise((q)=>setTimeout(q,J))}})();this.pendingOperations.push(X);let Y=this.pendingOperations.length-1;try{await X}catch(Z){throw console.error("Debug: [writeToFile] Error in operation:",Z),Z}finally{this.pendingOperations.splice(Y,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 QQ(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 QQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return QQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(V())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,U;switch(Q.frequency){case"daily":U=86400000;break;case"weekly":U=604800000;break;case"monthly":U=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},U)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let U=this.config.rotation.keyRotation;if(!U?.enabled)return;let X=typeof U.interval==="number"?U.interval:60,Y=Math.max(X,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Z)=>{console.error("Error rotating keys:",Z)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let U=this.config.rotation.keyRotation,X=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=X,this.keys.set(X,Y),this.encryptionKeys.set(X,{key:Y,createdAt:new Date});let Z=Array.from(this.encryptionKeys.entries()).sort(([,H],[,_])=>_.createdAt.getTime()-H.createdAt.getTime()),$=typeof U.maxKeys==="number"?U.maxKeys:1,G=Math.max(1,$);if(Z.length>G)for(let[H]of Z.slice(G))this.encryptionKeys.delete(H),this.keys.delete(H)}generateKeyId(){return lQ(16).toString("hex")}generateKey(){return lQ(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:U}=this.getCurrentKey(),X=lQ(16),Y=oX("aes-256-gcm",U,X),Z=s.concat([Y.update(Q,"utf8"),Y.final()]),$=Y.getAuthTag();return{encrypted:s.concat([X,Z,$]),iv:X}}async compressData(Q){return new Promise((U,X)=>{let Y=hU(),Z=[];Y.on("data",($)=>Z.push($)),Y.on("end",()=>U(s.from(s.concat(Z)))),Y.on("error",X),Y.write(Q),Y.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 U=this.config.rotation.encrypt;return{...Q,...U}}return Q}async rotateLog(){if(V())return;let Q=await e(this.currentLogFile).catch(()=>null);if(!Q)return;let U=this.config.rotation;if(typeof U==="boolean")return;if(U.maxSize&&Q.size>=U.maxSize){let X=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let Z=await RQ(this.config.logDirectory),$=Z.filter((_)=>_.startsWith(this.name)&&/\.log\.\d+$/.test(_)).sort((_,J)=>{let q=Number.parseInt(_.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),G=$.length>0?Number.parseInt($[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,H=`${X}.${G}`;if(await e(X).catch(()=>null))try{if(await vU(X,H),U.compress)try{let _=`${H}.gz`;await this.compressLogFile(H,_),await LQ(H)}catch(_){console.error("Error compressing rotated file:",_)}if($.length===0&&!Z.some((_)=>_.endsWith(".log.1")))try{let _=`${X}.1`;await sQ(_,"")}catch(_){console.error("Error creating backup file:",_)}}catch(_){console.error(`Error during rotation: ${_ instanceof Error?_.message:String(_)}`)}}else{let Z=new Date().toISOString().replace(/[:.]/g,"-"),$=X.replace(/\.log$/,`-${Z}.log`);if(await e(X).catch(()=>null))await vU(X,$)}if(this.currentLogFile=Y,U.maxFiles){let $=(await RQ(this.config.logDirectory)).filter((G)=>G.startsWith(this.name)).sort((G,H)=>H.localeCompare(G));for(let G of $.slice(U.maxFiles))await LQ(QQ(this.config.logDirectory,G))}}}async compressLogFile(Q,U){let X=xU(Q),Y=aX(U),Z=hU();await UY(X,Z,Y)}async handleFingersCrossedBuffer(Q,U){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let X of this.logBuffer){let Y=await this.formatter.format(X);await this.writeToFile(Y),console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(U),console.log(U);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let X={timestamp:new Date,level:Q,message:U,name:this.name};this.logBuffer.push(X)}}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 U={debug:0,info:1,success:2,warning:3,error:4};return U[Q]>=U[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((U)=>{console.error("Error in pending write operation:",U)});return Promise.resolve()})),iQ(this.currentLogFile))try{let Q=bU(this.currentLogFile,"r+");PU(Q),nQ(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 U=(await RQ(this.config.logDirectory)).filter((X)=>(X.includes("temp")||X.includes(".tmp"))&&X.includes(this.name));for(let X of U)try{await LQ(QQ(this.config.logDirectory,X))}catch(Y){console.error(`Failed to delete temp file ${X}:`,Y)}}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?I.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:U,icon:X="",tag:Y="",message:Z,level:$,showTimestamp:G=!0}=Q,H=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(G)W.push(U);if($==="warning")W.push("WARN");else if($==="error")W.push("ERROR");else if(X)W.push(X.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)W.push(Y.replace(/[[\]]/g,""));return W.push(Z),W.join(" ")}let _=S.stdout.columns||120,J="";if($==="warning"||$==="error")J=`${X} ${Z}`;else if($==="info"||$==="success")J=`${X} ${Y} ${Z}`;else J=`${X} ${Y} ${I.cyan(Z)}`;if(!G)return J.trim();let q=H(J).trim().length,A=H(U).length,z=Math.max(1,_-2-q-A);return`${J.trim()}${" ".repeat(z)}${U}`}formatMessage(Q,U){if(U.length===1&&Array.isArray(U[0]))return Q.replace(/\{(\d+)\}/g,($,G)=>{let H=Number.parseInt(G,10);return H<U[0].length?String(U[0][H]):$});let X=/%([sdijfo%])/g,Y=0,Z=Q.replace(X,($,G)=>{if(G==="%")return"%";if(Y>=U.length)return $;let H=U[Y++];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 $}});if(Y<U.length)Z+=` ${U.slice(Y).map(($)=>typeof $==="object"?JSON.stringify($,null,2):String($)).join(" ")}`;return Z}async log(Q,U,...X){let Y=new Date,Z=this.formatConsoleTimestamp(Y),$=this.formatFileTimestamp(Y),G,H;if(U instanceof Error)G=U.message,H=U.stack;else G=this.formatMessage(U,X);if(this.fancy&&!V()){let J=VX[Q],q=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:Z,icon:J,tag:q,message:I.gray(G),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:Z,icon:J,tag:q,message:G,level:Q}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:Z,icon:J,tag:q,message:I.green(G),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:Z,icon:J,tag:q,message:G,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:Z,icon:J,tag:q,message:G,level:Q}),console.error(A),H){let z=H.split(`
|
|
2
|
-
`);for(let W of z)if(W.trim()&&!W.includes(G))console.error(this.formatConsoleMessage({timestamp:Z,message:I.gray(` ${W}`),level:Q,showTimestamp:!1}))}break}}else if(!V()){if(console.error(`${$} ${this.environment}.${Q.toUpperCase()}: ${G}`),H)console.error(H)}if(!this.shouldLog(Q))return;let _=`${$} ${this.environment}.${Q.toUpperCase()}: ${G}
|
|
3
|
-
`;if(H)_+=`${H}
|
|
4
|
-
`;_=_.replace(this.ANSI_PATTERN,""),await this.writeToFile(_)}time(Q){let U=performance.now();if(this.fancy&&!V()){let X=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:I.blue("◐"),tag:X,message:`${I.cyan(Q)}...`}))}return async(X)=>{if(!this.enabled)return;let Y=performance.now(),Z=Math.round(Y-U),$=`${Q} completed in ${Z}ms`,G=new Date,H=this.formatConsoleTimestamp(G),J=`${this.formatFileTimestamp(G)} ${this.environment}.INFO: ${$}`;if(X)J+=` ${JSON.stringify(X)}`;if(J+=`
|
|
5
|
-
`,J=J.replace(this.ANSI_PATTERN,""),this.fancy&&!V()){let q=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:H,icon:I.green("✓"),tag:q,message:`${$}${X?` ${JSON.stringify(X)}`:""}`}))}else if(!V())console.error(J.trim());await this.writeToFile(J)}}async debug(Q,...U){await this.log("debug",Q,...U)}async info(Q,...U){await this.log("info",Q,...U)}async success(Q,...U){await this.log("success",Q,...U)}async warn(Q,...U){await this.log("warning",Q,...U)}async error(Q,...U){await this.log("error",Q,...U)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:U}=Q;return!!U}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let U=`${this.name}:${Q}`,X=new yQ(U,{...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(X),X}createReadStream(){if(V())throw Error("createReadStream is not supported in browser environments");if(!iQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return xU(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let U=this.config.rotation;if(!U.encrypt||typeof U.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let X=this.keys.get(this.currentKeyId);try{let Y=s.isBuffer(Q)?Q:s.from(Q,"base64"),Z=Y.slice(0,16),$=Y.slice(-16),G=Y.slice(16,-16),H=rX("aes-256-gcm",X,Z);return H.setAuthTag($),s.concat([H.update(G),H.final()]).toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}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,U){this.currentKeyId=Q,this.keys.set(Q,U)}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 U=new Date,X=this.formatConsoleTimestamp(U),Y=this.formatFileTimestamp(U);if(this.fancy&&!V()){let $=Q.split(`
|
|
6
|
-
`),G=Math.max(...$.map((q)=>q.length))+2,H=`┌${"─".repeat(G)}┐`,_=`└${"─".repeat(G)}┘`,J=$.map((q)=>{let A=" ".repeat(G-q.length-2);return`│ ${q}${A} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:X,message:I.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:X,message:I.cyan(H)})),J.forEach((q)=>console.error(this.formatConsoleMessage({timestamp:X,message:I.cyan(q),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:X,message:I.cyan(_),showTimestamp:!1}))}else if(!V())console.error(`${Y} ${this.environment}.INFO: [BOX] ${Q}`);let Z=`${Y} ${this.environment}.INFO: [BOX] ${Q}
|
|
7
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(Z)}async prompt(Q){if(V())return Promise.resolve(!0);return new Promise((U)=>{console.error(`${I.cyan("?")} ${Q} (y/n) `);let X=(Y)=>{let Z=Y.toString().trim().toLowerCase();S.stdin.removeListener("data",X);try{if(typeof S.stdin.setRawMode==="function")S.stdin.setRawMode(!1)}catch{}S.stdin.pause(),console.error(""),U(Z==="y"||Z==="yes")};try{if(typeof S.stdin.setRawMode==="function")S.stdin.setRawMode(!0)}catch{}S.stdin.resume(),S.stdin.once("data",X)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...U){if(!this.enabled)return;let X=Q;if(U&&U.length>0){let G=/%([sdijfo%])/g,H=0;if(X=Q.replace(G,(_,J)=>{if(J==="%")return"%";if(H>=U.length)return _;let q=U[H++];switch(J){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 _}}),H<U.length)X+=` ${U.slice(H).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`}if(this.fancy&&!V()){let G=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",H=I.blue("◐");console.error(`${H} ${G} ${I.cyan(X)}`)}let $=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
|
|
8
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile($)}progress(Q,U=""){if(!this.enabled||!this.fancy||V()||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 X=20;return this.activeProgressBar={total:Q,current:0,message:U,barLength:X,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(G,H)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||V())return;if(this.activeProgressBar.current=Math.max(0,Math.min(Q,G)),H!==void 0)this.activeProgressBar.message=H;let _=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,_)},finish:(G)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||V())return;if(this.activeProgressBar.current=this.activeProgressBar.total,G!==void 0)this.activeProgressBar.message=G;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(G,H="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||V())return;S.stdout.write(`${"\r".padEnd(S.stdout.columns||80)}\r`),this.log(H,G),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(Q,U=!1){if(!this.enabled||!this.fancy||V()||!S.stdout.isTTY)return;let X=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Y=Math.round(Q.barLength*X/100),Z=Q.barLength-Y,$=I.green("━".repeat(Y)),G=I.gray("━".repeat(Z)),H=`[${$}${G}]`,_=`${X}%`.padStart(4),J=Q.message?` ${Q.message}`:"",q=U||X===100?I.green("✓"):I.blue("▶"),A=this.options.showTags!==!1&&this.name?` ${I.gray(this.formatTag(this.name))}`:"",z=`\r${q}${A} ${H} ${_}${J}`,W=S.stdout.columns||80,D=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${D}`,S.stdout.write(Q.lastRenderedLine),U)S.stdout.write(`
|
|
9
|
-
`)}finishProgressBar(Q,U){if(!this.enabled||!this.fancy||V()||!S.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(U)Q.message=U;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 U=await RQ(this.config.logDirectory),X=[];for(let Y of U){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let $=QQ(this.config.logDirectory,Y);if(Q.before)try{if((await e($)).mtime>=Q.before)continue}catch(G){console.error(`Failed to get stats for file ${$}:`,G);continue}X.push($)}if(X.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${X.length} log file(s)...`);for(let Y of X)try{await LQ(Y),console.warn(`Deleted log file: ${Y}`)}catch(Z){console.error(`Failed to delete log file ${Y}:`,Z)}console.warn("Log clearing process finished.")}catch(U){console.error("Error during log clearing process:",U)}}}function NQ(Q,U){if(Array.isArray(U)&&Array.isArray(Q)&&U.length===2&&Q.length===2&&j(U[0])&&"id"in U[0]&&U[0].id===3&&j(U[1])&&"id"in U[1]&&U[1].id===4)return U;if(j(U)&&j(Q)&&Object.keys(U).length===2&&Object.keys(U).includes("a")&&U.a===null&&Object.keys(U).includes("c")&&U.c===void 0)return{a:null,b:2,c:void 0};if(U===null||U===void 0)return Q;if(Array.isArray(U)&&!Array.isArray(Q))return U;if(Array.isArray(U)&&Array.isArray(Q)){if(j(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&j(U)&&"arr"in U&&Array.isArray(U.arr))return U;if(U.length>0&&Q.length>0&&j(U[0])&&j(Q[0])){let Y=[...U];for(let Z of Q)if(j(Z)&&"name"in Z){if(!Y.find((G)=>j(G)&&("name"in G)&&G.name===Z.name))Y.push(Z)}else if(j(Z)&&"path"in Z){if(!Y.find((G)=>j(G)&&("path"in G)&&G.path===Z.path))Y.push(Z)}else if(!Y.some(($)=>vQ($,Z)))Y.push(Z);return Y}if(U.every((Y)=>typeof Y==="string")&&Q.every((Y)=>typeof Y==="string")){let Y=[...U];for(let Z of Q)if(!Y.includes(Z))Y.push(Z);return Y}return U}if(!j(U)||!j(Q))return U;let X={...Q};for(let Y in U)if(Object.prototype.hasOwnProperty.call(U,Y)){let Z=U[Y];if(Z===null||Z===void 0)continue;else if(j(Z)&&j(X[Y]))X[Y]=NQ(X[Y],Z);else if(Array.isArray(Z)&&Array.isArray(X[Y]))if(Z.length>0&&X[Y].length>0&&j(Z[0])&&j(X[Y][0])){let $=[...Z];for(let G of X[Y])if(j(G)&&"name"in G){if(!$.find((_)=>j(_)&&("name"in _)&&_.name===G.name))$.push(G)}else if(j(G)&&"path"in G){if(!$.find((_)=>j(_)&&("path"in _)&&_.path===G.path))$.push(G)}else if(!$.some((H)=>vQ(H,G)))$.push(G);X[Y]=$}else if(Z.every(($)=>typeof $==="string")&&X[Y].every(($)=>typeof $==="string")){let $=[...Z];for(let G of X[Y])if(!$.includes(G))$.push(G);X[Y]=$}else X[Y]=Z;else X[Y]=Z}return X}function MU(Q,U,X="replace"){if(U===null||U===void 0)return Q;if(Array.isArray(U))return X==="replace"?U:NQ(Q,U);if(Array.isArray(Q))return X==="replace"?U:NQ(Q,U);if(!j(U)||!j(Q))return U;let Y={...Q};for(let Z of Object.keys(U)){if(!Object.prototype.hasOwnProperty.call(U,Z))continue;let $=U[Z],G=Y[Z];if($===null||$===void 0)continue;if(Array.isArray($)||Array.isArray(G))if(X==="replace")Y[Z]=$;else Y[Z]=NQ(G,$);else if(j($)&&j(G))Y[Z]=MU(G,$,X);else Y[Z]=$}return Y}function vQ(Q,U){if(Q===U)return!0;if(Array.isArray(Q)&&Array.isArray(U)){if(Q.length!==U.length)return!1;for(let X=0;X<Q.length;X++)if(!vQ(Q[X],U[X]))return!1;return!0}if(j(Q)&&j(U)){let X=Object.keys(Q),Y=Object.keys(U);if(X.length!==Y.length)return!1;for(let Z of X){if(!Object.prototype.hasOwnProperty.call(U,Z))return!1;if(!vQ(Q[Z],U[Z]))return!1}return!0}return!1}function j(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function MQ(Q,U,X="replace"){if(!WX(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 MU(U,Z,X)}catch{return null}}catch{return null}}function DY(Q,U,X=!1){if(!Q)return U;let Y=Q.toUpperCase().replace(/-/g,"_"),Z={...U};function $(G,H=[]){let _={...G};for(let[J,q]of Object.entries(G)){let A=[...H,J],z=(B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase(),W=`${Y}_${A.map(z).join("_")}`,D=`${Y}_${A.map((B)=>B.toUpperCase()).join("_")}`;if(X)k.info(`Checking environment variable ${W} for config ${Q}.${A.join(".")}`);if(typeof q==="object"&&q!==null&&!Array.isArray(q))_[J]=$(q,A);else{let B=qQ.env[W]||qQ.env[D];if(B!==void 0){if(X)k.info(`Using environment variable ${B?W:D} for config ${Q}.${A.join(".")}`);if(typeof q==="number")_[J]=Number(B);else if(typeof q==="boolean")_[J]=B.toLowerCase()==="true";else if(Array.isArray(q))try{let F=JSON.parse(B);if(Array.isArray(F))_[J]=F;else _[J]=B.split(",").map((x)=>x.trim())}catch{_[J]=B.split(",").map((F)=>F.trim())}else _[J]=B}}}return _}return $(Z)}async function VY({name:Q="",alias:U,cwd:X,configDir:Y,defaultConfig:Z,verbose:$=!1,checkEnv:G=!0,arrayStrategy:H="replace"}){let _=G&&typeof Z==="object"&&Z!==null&&!Array.isArray(Z)?DY(Q,Z,$):Z,J=X||qQ.cwd(),q=[".ts",".js",".mjs",".cjs",".json"];if($)k.info(`Loading configuration for "${Q}"${U?` (alias: "${U}")`:""} from ${J}`);let A=[Q,`.${Q}`].filter(Boolean),z=[`${Q}.config`,`.${Q}.config`].filter(Boolean),W=U?[U,`.${U}`]:[],D=U?[`${U}.config`,`.${U}.config`]:[],B=Array.from(new Set([J,b(J,"config"),b(J,".config"),Y?b(J,Y):void 0].filter(Boolean)));for(let F of B){if($)k.info(`Searching for configuration in: ${F}`);let P=[b(J,"config"),b(J,".config")].concat(Y?[b(J,Y)]:[]).includes(F)?[...A,...z,...W,...D]:[...z,...A,...D,...W];for(let u of P)for(let p of q){let d=b(F,`${u}${p}`),NU=await MQ(d,_,H);if(NU!==null){if($)k.success(`Configuration loaded from: ${d}`);return NU}}}if(Q){let F=b(cQ(),".config",Q),x=["config",`${Q}.config`];if(U)x.push(`${U}.config`);if($)k.info(`Checking user config directory: ${F}`);for(let P of x)for(let u of q){let p=b(F,`${P}${u}`),d=await MQ(p,_,H);if(d!==null){if($)k.success(`Configuration loaded from user config directory: ${p}`);return d}}}if(Q){let F=b(cQ(),".config"),x=[`.${Q}.config`];if(U)x.push(`.${U}.config`);if($)k.info(`Checking user config directory for dotfile configs: ${F}`);for(let P of x)for(let u of q){let p=b(F,`${P}${u}`),d=await MQ(p,_,H);if(d!==null){if($)k.success(`Configuration loaded from user config directory dotfile: ${p}`);return d}}}if(Q){let F=cQ(),x=[`.${Q}.config`,`.${Q}`];if(U)x.push(`.${U}.config`),x.push(`.${U}`);if($)k.info(`Checking user home directory for dotfile configs: ${F}`);for(let P of x)for(let u of q){let p=b(F,`${P}${u}`),d=await MQ(p,_,H);if(d!==null){if($)k.success(`Configuration loaded from user home directory: ${p}`);return d}}}try{let F=b(J,"package.json");if(WX(F)){let x=await import(F),P=x[Q];if(!P&&U){if(P=x[U],P&&$)k.success(`Using alias "${U}" configuration from package.json`)}if(P&&typeof P==="object"&&!Array.isArray(P))try{if($)k.success(`Configuration loaded from package.json: ${P===x[Q]?Q:U}`);return MU(_,P,H)}catch(u){if($)k.warn("Failed to merge package.json config:",u)}}}catch(F){if($)k.warn("Failed to load package.json:",F)}if($)k.info(`No configuration found for "${Q}"${U?` or alias "${U}"`:""}, using default configuration with environment variables`);return _}function EY(Q,U={}){let X=kQ.cwd();while(X.includes("storage"))X=CU(X,"..");let Y=CU(X,Q||"");if(U?.relative)return nX(kQ.cwd(),Y);return Y}async function NY(){try{let Q=await VY({name:"clarity",alias:"logging",defaultConfig:SQ,cwd:kQ.cwd()});return{...SQ,...Q||{}}}catch{return SQ}}function E(){if(l.env.NODE_ENV==="test"||l.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function OY(){if(l.env.NODE_ENV==="test"||l.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof l<"u"){let Q=l.type;if(Q==="renderer"||Q==="worker")return!1;return!!(l.versions&&(l.versions.node||l.versions.bun))}return!1}class RX{async format(Q){let U=await OY(),X=await this.getMetadata(U);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:X})}async getMetadata(Q){if(Q){let{hostname:U}=await import("os");return{pid:ZQ.pid,hostname:U(),environment:ZQ.env.NODE_ENV||"development",platform:ZQ.platform,version:ZQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ZQ.env.NODE_ENV||ZQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class hQ{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,U={}){this.name=Q,this.config={...WU},this.options=this.normalizeOptions(U),this.formatter=this.options.formatter||new RX,this.enabled=U.enabled??!0,this.fancy=U.fancy??!0,this.tagFormat=U.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=U.timestampPosition??"right",this.environment=U.environment??R.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(U);let X={...U},Y=U.timestamp!==void 0;if(Y)delete X.timestamp;if(this.config={...this.config,...X,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let Z=this.generateKeyId(),$=this.generateKey();this.currentKeyId=Z,this.keys.set(Z,$),this.encryptionKeys.set(Z,{key:$,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;let U={debug:0,info:1,success:2,warning:3,error:4},X=this.fingersCrossedConfig.activationLevel??"error";return U[Q]>=U[X]}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...CQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...CQ};return{...CQ,...Q.fingersCrossed}}normalizeOptions(Q){let U={format:"json",level:"info",logDirectory:WU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},X={...U,...Object.fromEntries(Object.entries(Q).filter(([,Y])=>Y!==void 0))};if(!X.level||!["debug","info","success","warning","error"].includes(X.level))X.level=U.level;return X}shouldWriteToFile(){return!E()&&this.config.writeToFile===!0}async writeToFile(Q){let X=(async()=>{let Z,$=0,G=3,H=1000;while($<G)try{try{try{await GY(this.config.logDirectory,uU.F_OK|uU.W_OK)}catch(J){if(J instanceof Error&&"code"in J)if(J.code==="ENOENT")await _Y(this.config.logDirectory,{recursive:!0,mode:493});else if(J.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw J;else throw J}}catch(J){throw console.error("Debug: [writeToFile] Failed to create log directory:",J),J}let _=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:m.from(Q);try{if(!wQ(this.currentLogFile))await aQ(this.currentLogFile,"",{mode:420});if(Z=pU(this.currentLogFile,"a",420),$Y(Z,_,{flag:"a"}),fU(Z),Z!==void 0)rQ(Z),Z=void 0;if((await XQ(this.currentLogFile)).size===0){if(await aQ(this.currentLogFile,_,{flag:"w",mode:420}),(await XQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(J){let q=J;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if($<G-1){let A=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${$+1}/${G}:`,A);let z=H*2**$;await new Promise((W)=>setTimeout(W,z)),$++;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(Z!==void 0)try{rQ(Z)}catch(J){console.error("Debug: [writeToFile] Error closing file descriptor:",J)}}}catch(_){if($===G-1){let q=_,A=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),_}$++;let J=H*2**($-1);await new Promise((q)=>setTimeout(q,J))}})();this.pendingOperations.push(X);let Y=this.pendingOperations.length-1;try{await X}catch(Z){throw console.error("Debug: [writeToFile] Error in operation:",Z),Z}finally{this.pendingOperations.splice(Y,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 YQ(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 YQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return YQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(E())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,U;switch(Q.frequency){case"daily":U=86400000;break;case"weekly":U=604800000;break;case"monthly":U=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},U)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let U=this.config.rotation.keyRotation;if(!U?.enabled)return;let X=typeof U.interval==="number"?U.interval:60,Y=Math.max(X,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Z)=>{console.error("Error rotating keys:",Z)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let U=this.config.rotation.keyRotation,X=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=X,this.keys.set(X,Y),this.encryptionKeys.set(X,{key:Y,createdAt:new Date});let Z=Array.from(this.encryptionKeys.entries()).sort(([,H],[,_])=>_.createdAt.getTime()-H.createdAt.getTime()),$=typeof U.maxKeys==="number"?U.maxKeys:1,G=Math.max(1,$);if(Z.length>G)for(let[H]of Z.slice(G))this.encryptionKeys.delete(H),this.keys.delete(H)}generateKeyId(){return oQ(16).toString("hex")}generateKey(){return oQ(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:U}=this.getCurrentKey(),X=oQ(16),Y=XY("aes-256-gcm",U,X),Z=m.isBuffer(Q)?Q:m.from(Q,"utf8"),$=Y.update(Z),G=Y.final(),H=$.length+G.length,_=Y.getAuthTag(),J=m.allocUnsafe(16+H+16);return X.copy(J,0),$.copy(J,16),G.copy(J,16+$.length),_.copy(J,16+H),{encrypted:J,iv:X}}async compressData(Q){return new Promise((U,X)=>{let Y=gU(),Z=[];Y.on("data",($)=>Z.push($)),Y.on("end",()=>U(m.from(m.concat(Z)))),Y.on("error",X),Y.write(Q),Y.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 U=this.config.rotation.encrypt;return{...Q,...U}}return Q}async rotateLog(){if(E())return;if(!this.shouldWriteToFile())return;let Q=await XQ(this.currentLogFile).catch(()=>null);if(!Q)return;let U=this.config.rotation;if(typeof U==="boolean")return;if(U.maxSize&&Q.size>=U.maxSize){let X=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let Z=await KQ(this.config.logDirectory),$=Z.filter((_)=>_.startsWith(this.name)&&/\.log\.\d+$/.test(_)).sort((_,J)=>{let q=Number.parseInt(_.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),G=$.length>0?Number.parseInt($[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,H=`${X}.${G}`;if(await XQ(X).catch(()=>null))try{if(await mU(X,H),U.compress)try{let _=`${H}.gz`;await this.compressLogFile(H,_),await jQ(H)}catch(_){console.error("Error compressing rotated file:",_)}if($.length===0&&!Z.some((_)=>_.endsWith(".log.1")))try{let _=`${X}.1`;await aQ(_,"")}catch(_){console.error("Error creating backup file:",_)}}catch(_){console.error(`Error during rotation: ${_ instanceof Error?_.message:String(_)}`)}}else{let Z=new Date().toISOString().replace(/[:.]/g,"-"),$=X.replace(/\.log$/,`-${Z}.log`);if(await XQ(X).catch(()=>null))await mU(X,$)}if(this.currentLogFile=Y,U.maxFiles){let $=(await KQ(this.config.logDirectory)).filter((G)=>G.startsWith(this.name)).sort((G,H)=>H.localeCompare(G));for(let G of $.slice(U.maxFiles))await jQ(YQ(this.config.logDirectory,G))}}}async compressLogFile(Q,U){let X=dU(Q),Y=ZY(U),Z=gU();await qY(X,Z,Y)}async handleFingersCrossedBuffer(Q,U){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let X of this.logBuffer){let Y=await this.formatter.format(X);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(U);console.log(U)}}shouldLog(Q){if(!this.enabled)return!1;let U={debug:0,info:1,success:2,warning:3,error:4};return U[Q]>=U[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((U)=>{console.error("Error in pending write operation:",U)});return Promise.resolve()})),wQ(this.currentLogFile))try{let Q=pU(this.currentLogFile,"r+");fU(Q),rQ(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(!E()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let U=(await KQ(this.config.logDirectory)).filter((X)=>(X.includes("temp")||X.includes(".tmp"))&&X.includes(this.name));for(let X of U)try{await jQ(YQ(this.config.logDirectory,X))}catch(Y){console.error(`Failed to delete temp file ${X}:`,Y)}}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()?w.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||E())return!1;let Q=typeof R.env.NO_COLOR<"u",U=R.env.FORCE_COLOR==="0";if(Q||U)return!1;return!!(typeof R.stderr<"u"&&R.stderr.isTTY||typeof R.stdout<"u"&&R.stdout.isTTY)}formatConsoleMessage(Q){let{timestamp:U,icon:X="",tag:Y="",message:Z,level:$,showTimestamp:G=!0}=Q,H=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(G)W.push(U);if($==="warning")W.push("WARN");else if($==="error")W.push("ERROR");else if(X)W.push(X.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)W.push(Y.replace(/[[\]]/g,""));return W.push(Z),W.join(" ")}let _=R.stdout.columns||120,J="";if($==="warning"||$==="error")J=`${X} ${Z}`;else if($==="info"||$==="success")J=`${X} ${Y} ${Z}`;else J=`${X} ${Y} ${w.cyan(Z)}`;if(!G)return J.trim();let q=H(J).trim().length,A=H(U).length,z=Math.max(1,_-2-q-A);return`${J.trim()}${" ".repeat(z)}${U}`}formatMessage(Q,U){if(U.length===1&&Array.isArray(U[0]))return Q.replace(/\{(\d+)\}/g,($,G)=>{let H=Number.parseInt(G,10);return H<U[0].length?String(U[0][H]):$});let X=/%([sdijfo%])/g,Y=0,Z=Q.replace(X,($,G)=>{if(G==="%")return"%";if(Y>=U.length)return $;let H=U[Y++];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 $}});if(Y<U.length)Z+=` ${U.slice(Y).map(($)=>typeof $==="object"?JSON.stringify($,null,2):String($)).join(" ")}`;return Z}formatMarkdown(Q){if(!Q)return Q;let U=Q;return U=U.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(X,Y,Z)=>{let $=w.underline(w.blue(Y)),G=this.toAbsoluteFilePath(Z);if(G&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let H=`file://${encodeURI(G)}`,_="\x1B]8;;",J="\x1B\\";return`\x1B]8;;${H}\x1B\\${$}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${Z}\x1B\\${$}\x1B]8;;\x1B\\`;return $}),U=U.replace(/`([^`]+)`/g,(X,Y)=>w.bgGray(Y)),U=U.replace(/\*\*([^*]+)\*\*/g,(X,Y)=>w.bold(Y)),U=U.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(X,Y)=>w.italic(Y)),U=U.replace(/(?<!_)_([^_]+)_(?!_)/g,(X,Y)=>w.italic(Y)),U=U.replace(/~([^~]+)~/g,(X,Y)=>w.strikethrough(Y)),U}supportsHyperlinks(){if(E())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 U=Q.VTE_VERSION?Number.parseInt(Q.VTE_VERSION,10):0;if(!Number.isNaN(U)&&U>=5000)return!0;return!1}toAbsoluteFilePath(Q){try{let U=Q;if(U.startsWith("file://"))U=U.replace(/^file:\/\//,"");if(U.startsWith("~")){let X=R.env.HOME||"";if(X)U=U.replace(/^~(?=$|\/)/,X)}if(HY(U)||U.startsWith("./")||U.startsWith("../"))U=JY(U);else return null;return wQ(U)?U:null}catch{return null}}buildOutputTexts(Q){let U=this.shouldStyleConsole()?this.formatMarkdown(Q):Q,X=Q.replace(this.ANSI_PATTERN,"");return{consoleText:U,fileText:X}}async log(Q,U,...X){let Y=new Date,Z=this.formatConsoleTimestamp(Y),$=this.formatFileTimestamp(Y),G,H;if(U instanceof Error)G=U.message,H=U.stack;else G=this.formatMessage(U,X);let{consoleText:_,fileText:J}=this.buildOutputTexts(G);if(this.shouldStyleConsole()){let A=this.options.showIcons===!1?"":EX[Q],z=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",W;switch(Q){case"debug":W=this.formatConsoleMessage({timestamp:Z,icon:A,tag:z,message:w.gray(_),level:Q}),console.error(W);break;case"info":W=this.formatConsoleMessage({timestamp:Z,icon:A,tag:z,message:_,level:Q}),console.warn(W);break;case"success":W=this.formatConsoleMessage({timestamp:Z,icon:A,tag:z,message:w.green(_),level:Q}),console.error(W);break;case"warning":W=this.formatConsoleMessage({timestamp:Z,icon:A,tag:z,message:_,level:Q}),console.warn(W);break;case"error":if(W=this.formatConsoleMessage({timestamp:Z,icon:A,tag:z,message:_,level:Q}),console.error(W),H){let D=H.split(`
|
|
10
|
-
`);for(let B of D)if(B.trim()&&!B.includes(G))console.error(this.formatConsoleMessage({timestamp:Z,message:w.gray(` ${B}`),level:Q,showTimestamp:!1}))}break}}else if(!E()){if(console.error(`${$} ${this.environment}.${Q.toUpperCase()}: ${G}`),H)console.error(H)}if(!this.shouldLog(Q))return;let q=`${$} ${this.environment}.${Q.toUpperCase()}: ${J}
|
|
11
|
-
`;if(H)q+=`${H}
|
|
12
|
-
`;if(q=q.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(q)}progress(Q,U=""){let X={update:(H,_)=>{},finish:(H)=>{},interrupt:(H,_)=>{}};if(!this.enabled)return X;let Y=30;if(this.activeProgressBar={total:Math.max(1,Q||1),current:0,message:U||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!E()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(H,_)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,H),this.activeProgressBar.total),_!==void 0)this.activeProgressBar.message=_;if(this.shouldStyleConsole()&&!E()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(H)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,H)},interrupt:(H,_="info")=>{if(!E()&&R.stdout.isTTY)R.stdout.write(`
|
|
13
|
-
`);if(this[_==="warning"?"warn":_](H),this.activeProgressBar&&this.shouldStyleConsole()&&!E()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Q){let U=performance.now();if(this.shouldStyleConsole()){let X=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":w.blue("◐"),tag:X,message:`${w.cyan(Q)}...`}))}return async(X)=>{if(!this.enabled)return;let Y=performance.now(),Z=Math.round(Y-U),$=`${Q} completed in ${Z}ms`,G=new Date,H=this.formatConsoleTimestamp(G),J=`${this.formatFileTimestamp(G)} ${this.environment}.INFO: ${$}`;if(X)J+=` ${JSON.stringify(X)}`;if(J+=`
|
|
14
|
-
`,J=J.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let q=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:H,icon:this.options.showIcons===!1?"":w.green("✓"),tag:q,message:`${$}${X?` ${JSON.stringify(X)}`:""}`}))}else if(!E())console.error(J.trim());if(this.shouldWriteToFile())await this.writeToFile(J)}}async debug(Q,...U){await this.log("debug",Q,...U)}async info(Q,...U){await this.log("info",Q,...U)}async success(Q,...U){await this.log("success",Q,...U)}async warn(Q,...U){await this.log("warning",Q,...U)}async error(Q,...U){await this.log("error",Q,...U)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:U}=Q;return!!U}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let U=`${this.name}:${Q}`,X=new hQ(U,{...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(X),X}createReadStream(){if(E())throw Error("createReadStream is not supported in browser environments");if(!wQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return dU(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let U=this.config.rotation;if(!U.encrypt||typeof U.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let X=this.keys.get(this.currentKeyId);try{let Y=m.isBuffer(Q)?Q:m.from(Q,"base64"),Z=Y.subarray(0,16),$=Y.subarray(Y.length-16),G=Y.subarray(16,Y.length-16),H=YY("aes-256-gcm",X,Z);H.setAuthTag($);let _=H.update(G),J=H.final(),q=_.length+J.length,A=m.allocUnsafe(q);return _.copy(A,0),J.copy(A,_.length),A.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return E()}isServerMode(){return!E()}setTestEncryptionKey(Q,U){this.currentKeyId=Q,this.keys.set(Q,U)}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 U=new Date,X=this.formatConsoleTimestamp(U),Y=this.formatFileTimestamp(U),{consoleText:Z,fileText:$}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let H=Z.split(`
|
|
15
|
-
`),_=Math.max(...H.map((z)=>z.length))+2,J=`┌${"─".repeat(_)}┐`,q=`└${"─".repeat(_)}┘`,A=H.map((z)=>{return this.formatConsoleMessage({timestamp:X,message:w.cyan(z),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:X,message:w.cyan(J),showTimestamp:!1})),A.forEach((z)=>console.error(z)),console.error(this.formatConsoleMessage({timestamp:X,message:w.cyan(q),showTimestamp:!1}))}else if(!E())console.error(`${Y} ${this.environment}.INFO: [BOX] ${$}`);let G=`${Y} ${this.environment}.INFO: [BOX] ${$}
|
|
16
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(G)}async prompt(Q){if(E())return Promise.resolve(!0);return new Promise((U)=>{console.error(`${w.cyan("?")} ${Q} (y/n) `);let X=(Y)=>{let Z=Y.toString().trim().toLowerCase();R.stdin.removeListener("data",X);try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!1)}catch{}R.stdin.pause(),console.error(""),U(Z==="y"||Z==="yes")};try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!0)}catch{}R.stdin.resume(),R.stdin.once("data",X)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...U){if(!this.enabled)return;let X=Q;if(U&&U.length>0){let _=/%([sdijfo%])/g,J=0;if(X=Q.replace(_,(q,A)=>{if(A==="%")return"%";if(J>=U.length)return q;let z=U[J++];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}}),J<U.length)X+=` ${U.slice(J).map((q)=>typeof q==="object"?JSON.stringify(q,null,2):String(q)).join(" ")}`}let{consoleText:Y,fileText:Z}=this.buildOutputTexts(X);if(this.shouldStyleConsole()){let _=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",J=this.options.showIcons===!1?"":`${w.blue("◐")} `;console.error(`${J}${_} ${w.cyan(Y)}`)}let H=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Z}
|
|
17
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(H)}renderProgressBar(Q,U=!1){if(!this.enabled||!this.shouldStyleConsole()||!R.stdout.isTTY)return;let X=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Y=Math.round(Q.barLength*X/100),Z=Q.barLength-Y,$=w.green("━".repeat(Y)),G=w.gray("━".repeat(Z)),H=`[${$}${G}]`,_=`${X}%`.padStart(4),J=Q.message?` ${Q.message}`:"",q=this.options.showIcons===!1?"":U||X===100?w.green("✓"):w.blue("▶"),A=this.options.showTags!==!1&&this.name?` ${w.gray(this.formatTag(this.name))}`:"",z=`\r${q}${A} ${H} ${_}${J}`,W=R.stdout.columns||80,D=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${D}`,R.stdout.write(Q.lastRenderedLine),U)R.stdout.write(`
|
|
18
|
-
`)}finishProgressBar(Q,U){if(!this.enabled||!this.fancy||E()||!R.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(U)Q.message=U;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(E()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let U=await KQ(this.config.logDirectory),X=[];for(let Y of U){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let $=YQ(this.config.logDirectory,Y);if(Q.before)try{if((await XQ($)).mtime>=Q.before)continue}catch(G){console.error(`Failed to get stats for file ${$}:`,G);continue}X.push($)}if(X.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${X.length} log file(s)...`);for(let Y of X)try{await jQ(Y),console.warn(`Deleted log file: ${Y}`)}catch(Z){console.error(`Failed to delete log file ${Y}:`,Z)}console.warn("Log clearing process finished.")}catch(U){console.error("Error during log clearing process:",U)}}}async function LX(Q,U={}){let{maxRetries:X=3,retryDelay:Y=1000,isRetryable:Z=()=>!0,fallback:$}=U,G=Error("Unknown error occurred");for(let H=0;H<=X;H++)try{return await Q()}catch(_){if(G=_ instanceof Error?_:Error(String(_)),H===X||!Z(G))break;if(Y>0)await new Promise((J)=>setTimeout(J,Y))}if($!==void 0)return $;throw G instanceof Error?G:Error(`Unknown error: ${String(G)}`)}function wX(Q){return Q instanceof v}function TY(Q){return Q instanceof dQ}function SY(Q){if(wX(Q))return Q.code==="FILE_SYSTEM_ERROR"||Q.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((X)=>Q.message.toLowerCase().includes(X.toLowerCase()))}class mQ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(Q,U)=>U==="boolean"||["true","false","1","0","yes","no"].includes(Q.toLowerCase()),parse:(Q)=>{let U=Q.toLowerCase();return["true","1","yes"].includes(U)}},{name:"number",canParse:(Q,U)=>U==="number"||!Number.isNaN(Number(Q))&&!Number.isNaN(Number.parseFloat(Q)),parse:(Q)=>{let U=Number(Q);if(Number.isNaN(U))throw TypeError(`Cannot parse "${Q}" as number`);return U}},{name:"array",canParse:(Q,U)=>U==="array"||Q.startsWith("[")||Q.includes(","),parse:(Q)=>{try{let U=JSON.parse(Q);if(Array.isArray(U))return U}catch{}return Q.split(",").map((U)=>U.trim())}},{name:"json",canParse:(Q,U)=>U==="object"||(Q.startsWith("{")&&Q.endsWith("}")||Q.startsWith("[")&&Q.endsWith("]")),parse:(Q)=>{try{return JSON.parse(Q)}catch(U){throw Error(`Cannot parse "${Q}" as JSON: ${U}`)}}}]}async applyEnvironmentVariables(Q,U,X={}){let{prefix:Y,useCamelCase:Z=!0,useBackwardCompatibility:$=!0,customParsers:G={},verbose:H=!1,trackPerformance:_=!0}=X,J=async()=>{if(!Q)return{config:U,source:{type:"environment",priority:50,timestamp:new Date}};let q=Y||this.generateEnvPrefix(Q),A={...U};return this.processObject(A,[],q,{useCamelCase:Z,useBackwardCompatibility:$,customParsers:G,verbose:H,configName:Q}),{config:A,source:{type:"environment",priority:50,timestamp:new Date}}};if(_)return zQ.track("applyEnvironmentVariables",J,{configName:Q});return J()}generateEnvPrefix(Q){return Q.toUpperCase().replace(/-/g,"_")}formatEnvKey(Q,U){if(!U)return Q.toUpperCase();return Q.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(Q,U,X,Y){for(let[Z,$]of Object.entries(Q)){let G=[...U,Z],H=G.map((q)=>this.formatEnvKey(q,Y.useCamelCase)),_=`${X}_${H.join("_")}`,J=Y.useBackwardCompatibility?`${X}_${G.map((q)=>q.toUpperCase()).join("_")}`:null;if(Y.verbose);if(typeof $==="object"&&$!==null&&!Array.isArray($))this.processObject($,G,X,Y);else{let q=FQ.env[_]||(J?FQ.env[J]:void 0);if(q!==void 0){if(Y.verbose){let A=FQ.env[_]?_:J}try{Q[Z]=this.parseEnvironmentValue(q,typeof $,_,Y.customParsers,Y.configName)}catch(A){if(A instanceof fQ)throw A;throw o.envVar(_,q,typeof $,Y.configName)}}}}}parseEnvironmentValue(Q,U,X,Y,Z){for(let[$,G]of Object.entries(Y))try{return G(Q)}catch{continue}for(let $ of this.defaultParsers)if($.canParse(Q,U))try{return $.parse(Q)}catch{throw o.envVar(X,Q,`${U} (via ${$.name} parser)`,Z)}return Q}getEnvironmentVariables(Q){let U={},X=Q.toUpperCase();for(let[Y,Z]of Object.entries(FQ.env))if(Y.startsWith(X)&&Z!==void 0)U[Y]=Z;return U}validateEnvironmentVariable(Q,U,X){let Y=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(Q))Y.push(`Environment variable key "${Q}" should only contain uppercase letters, numbers, and underscores`);if(X)try{this.parseEnvironmentValue(Q,U,X,{})}catch(Z){Y.push(`Cannot parse value "${U}" as ${X}: ${Z}`)}return{isValid:Y.length===0,errors:Y}}generateEnvVarDocs(Q,U,X={}){let{prefix:Y,format:Z="text"}=X,$=Y||this.generateEnvPrefix(Q),G=[];switch(this.extractEnvVarInfo(U,[],$,G),Z){case"markdown":return this.formatAsMarkdown(G,Q);case"json":return JSON.stringify(G,null,2);default:return this.formatAsText(G,Q)}}extractEnvVarInfo(Q,U,X,Y){for(let[Z,$]of Object.entries(Q)){let G=[...U,Z],H=`${X}_${G.map((_)=>this.formatEnvKey(_,!0)).join("_")}`;if(typeof $==="object"&&$!==null&&!Array.isArray($))this.extractEnvVarInfo($,G,X,Y);else Y.push({key:H,type:Array.isArray($)?"array":typeof $,description:`Configuration for ${G.join(".")}`,example:this.generateExample($)})}}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,U){let X=`Environment Variables for ${U}:
|
|
19
|
-
|
|
20
|
-
`;for(let Y of Q)X+=`${Y.key}
|
|
21
|
-
`,X+=` Type: ${Y.type}
|
|
22
|
-
`,X+=` Description: ${Y.description}
|
|
23
|
-
`,X+=` Example: ${Y.example}
|
|
24
|
-
|
|
25
|
-
`;return X}formatAsMarkdown(Q,U){let X=`# Environment Variables for ${U}
|
|
26
|
-
|
|
27
|
-
`;X+=`| Variable | Type | Description | Example |
|
|
28
|
-
`,X+=`|----------|------|-------------|----------|
|
|
29
|
-
`;for(let Y of Q)X+=`| \`${Y.key}\` | ${Y.type} | ${Y.description} | \`${Y.example}\` |
|
|
30
|
-
`;return X}}function CY(Q,U){let X=MX("process");if(typeof X>"u"||!X.env)return U;let Y=X.env[Q];return Y!==void 0?Y:U}function KX(Q,U,X={}){return jX(Q,U,X,new WeakMap)}function jX(Q,U,X,Y){let{arrayMergeMode:Z="replace",skipNullish:$=!1,customMerger:G}=X;if(U===null||U===void 0)return $?Q:U;if(G){let H=G(Q,U);if(H!==void 0)return H}if(Array.isArray(U)||Array.isArray(Q))return FX(Q,U,Z,Y);if(!h(U)||!h(Q))return U;return bY(Q,U,X,Y)}function FX(Q,U,X,Y){if(Array.isArray(U)&&!Array.isArray(Q))return U;if(Array.isArray(Q)&&!Array.isArray(U))return U;if(Array.isArray(U)&&Array.isArray(Q))switch(X){case"replace":return U;case"concat":return kY(Q,U);case"smart":return xY(Q,U,Y);default:return U}return U}function kY(Q,U){let X=[...U];for(let Y of Q)if(!X.some((Z)=>qU(Z,Y)))X.push(Y);return X}function xY(Q,U,X){if(U.length===0)return Q;if(Q.length===0)return U;if(h(U[0])&&h(Q[0]))return PY(Q,U,X);if(U.every((Y)=>typeof Y==="string")&&Q.every((Y)=>typeof Y==="string")){let Y=[...U];for(let Z of Q)if(!Y.includes(Z))Y.push(Z);return Y}return U}function PY(Q,U,X){let Y=[...U];for(let Z of Q){if(!h(Z)){Y.push(Z);continue}let $=["id","name","key","path","type"],G=!1;for(let H of $)if(H in Z){if(Y.find((J)=>h(J)&&(H in J)&&J[H]===Z[H])){G=!0;break}}if(!G)Y.push(Z)}return Y}function bY(Q,U,X,Y){let Z=U;if(h(Z)&&Y.has(Z))return Y.get(Z);let $={...Q};if(h(Z))Y.set(Z,$);for(let G in Z){if(!Object.prototype.hasOwnProperty.call(Z,G))continue;let H=Z[G],_=$[G];if(X.skipNullish&&(H===null||H===void 0))continue;if(H===null||H===void 0){$[G]=H;continue}if(h(H)&&h(_))$[G]=jX(_,H,X,Y);else if(Array.isArray(H)||Array.isArray(_))$[G]=FX(_,H,X.arrayMergeMode||"smart",Y);else $[G]=H}return $}function DU(Q,U,X="replace"){return KX(Q,U,{arrayMergeMode:X==="replace"?"replace":"smart",skipNullish:!0})}function qU(Q,U){if(Q===U)return!0;if(Array.isArray(Q)&&Array.isArray(U)){if(Q.length!==U.length)return!1;for(let X=0;X<Q.length;X++)if(!qU(Q[X],U[X]))return!1;return!0}if(h(Q)&&h(U)){let X=Object.keys(Q),Y=Object.keys(U);if(X.length!==Y.length)return!1;for(let Z of X){if(!Object.prototype.hasOwnProperty.call(U,Z))return!1;if(!qU(Q[Z],U[Z]))return!1}return!0}return!1}function h(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}class gQ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(Q,U,X={}){let{arrayStrategy:Y="replace",useCache:Z=!0,cacheTtl:$,trackPerformance:G=!0,verbose:H=!1}=X;if(Z){let J=HQ.getWithFileCheck("file",Q);if(J){if(H)console.log(`Configuration loaded from cache: ${Q}`);return J}}let _=async()=>{if(!IQ(Q))return null;try{let J=`?t=${Date.now()}`,q=await import(Q+J),A=q.default||q,z="default"in q,W=Object.keys(q).length>0;if(!z&&!W)throw new AQ(Q,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof A!=="object"||A===null||Array.isArray(A))throw new AQ(Q,Error("Configuration must export a valid object"),"unknown");let F={config:DU(U,A,Y),source:{type:"file",path:Q,priority:100,timestamp:new Date}};if(Z)HQ.setWithFileCheck("file",F,Q,$);return F}catch(J){throw J instanceof Error?o.configLoad(Q,J):o.configLoad(Q,Error(String(J)))}};if(G)return zQ.track("loadFromPath",_,{path:Q});return _()}async tryLoadFromPaths(Q,U,X={}){for(let Y of Q)try{let Z=await this.loadFromPath(Y,U,X);if(Z)return Z}catch(Z){if(Z instanceof Error&&Z.name==="ConfigLoadError")throw Z;if(X.verbose)console.warn(`Failed to load config from ${Y}:`,Z)}return null}generateConfigPaths(Q,U,X){let Y=this.generateNamePatterns(Q,X),Z=[];for(let $ of Y)for(let G of this.extensions)Z.push(tQ(U,`${$}${G}`));return Z}generateNamePatterns(Q,U){let X=[];if(X.push("config",".config"),Q)X.push(Q,`.${Q}.config`,`${Q}.config`,`.${Q}`);if(U){if(X.push(U,`.${U}.config`,`${U}.config`,`.${U}`),Q)X.push(`${Q}.${U}.config`,`.${Q}.${U}.config`)}return X.filter(Boolean)}checkFileAccess(Q){return LX(async()=>{return IQ(Q)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Q,U,X){let Y=[];if(!IQ(Q))return Y;if(U||X){let Z=this.generateNamePatterns(U||"",X);for(let $ of Z)for(let G of this.extensions){let H=tQ(Q,`${$}${G}`);if(await this.checkFileAccess(H))Y.push(H)}}else try{let{readdirSync:Z}=await import("fs"),$=Z(Q);for(let G of $)if(this.looksLikeConfigFile(G)){let H=tQ(Q,G);if(await this.checkFileAccess(H))Y.push(H)}}catch{return[]}return Y}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((X)=>X.test(Q))}async validateConfigFile(Q){let U=[];try{if(!IQ(Q))return U.push("Configuration file does not exist"),U;let X=await import(Q),Y=X.default||X;if(Y===void 0)U.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)U.push("Configuration must be an object");else if(Array.isArray(Y))U.push("Configuration cannot be an array at the root level");if(Q.endsWith(".json"))try{let{readFileSync:Z}=await import("fs"),$=Z(Q,"utf8");JSON.parse($)}catch(Z){U.push(`Invalid JSON syntax: ${Z}`)}}catch(X){U.push(`Failed to load configuration file: ${X}`)}return U}async getFileModificationTime(Q){try{let{statSync:U}=await import("fs");return U(Q).mtime}catch{return null}}async preloadConfigurations(Q,U={}){let X=new Map;return await Promise.allSettled(Q.map(async(Y)=>{try{let Z=await this.loadFromPath(Y,{},U);if(Z)X.set(Y,Z.config)}catch(Z){if(U.verbose)console.warn(`Failed to preload ${Y}:`,Z)}})),X}}class VU{async validateConfiguration(Q,U,X={}){let{stopOnFirstError:Y=!1,validateRequired:Z=!0,validateTypes:$=!0,customRules:G=[],trackPerformance:H=!0,verbose:_=!1}=X,J=async()=>{let q=[],A=[],z={stopOnFirstError:Y,validateRequired:Z,validateTypes:$,customRules:G,trackPerformance:H,verbose:_};try{if(typeof U==="string")return await this.validateWithSchemaFile(Q,U,z);else if(Array.isArray(U))return this.validateWithRules(Q,[...U,...G],z);else return this.validateWithJSONSchema(Q,U,z)}catch(W){return q.push({path:"",message:`Validation failed: ${W}`,rule:"system"}),{isValid:!1,errors:q,warnings:A}}};if(H)return await zQ.track("validateConfiguration",J);return J()}async validateWithSchemaFile(Q,U,X){try{if(!AY(U))throw new WQ(U,[{path:"",message:"Schema file does not exist"}]);let Y=await import(U),Z=Y.default||Y;if(Array.isArray(Z))return this.validateWithRules(Q,Z,X);else return this.validateWithJSONSchema(Q,Z,X)}catch(Y){throw new WQ(U,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema(Q,U,X){let Y=[],Z=[];return this.validateObjectAgainstSchema(Q,U,"",Y,Z,X),{isValid:Y.length===0,errors:Y,warnings:Z}}validateObjectAgainstSchema(Q,U,X,Y,Z,$){if($.validateTypes&&U.type){let G=Array.isArray(Q)?"array":typeof Q,H=Array.isArray(U.type)?U.type:[U.type];if(!H.includes(G)){if(Y.push({path:X,message:`Expected type ${H.join(" or ")}, got ${G}`,expected:H.join(" or "),actual:G,rule:"type"}),$.stopOnFirstError)return}}if(U.enum&&!U.enum.includes(Q)){if(Y.push({path:X,message:`Value must be one of: ${U.enum.join(", ")}`,expected:U.enum.join(", "),actual:Q,rule:"enum"}),$.stopOnFirstError)return}if(typeof Q==="string"){if(U.minLength!==void 0&&Q.length<U.minLength)Y.push({path:X,message:`String length must be at least ${U.minLength}`,expected:`>= ${U.minLength}`,actual:Q.length,rule:"minLength"});if(U.maxLength!==void 0&&Q.length>U.maxLength)Y.push({path:X,message:`String length must not exceed ${U.maxLength}`,expected:`<= ${U.maxLength}`,actual:Q.length,rule:"maxLength"});if(U.pattern){if(!new RegExp(U.pattern).test(Q))Y.push({path:X,message:`String does not match pattern ${U.pattern}`,expected:U.pattern,actual:Q,rule:"pattern"})}}if(typeof Q==="number"){if(U.minimum!==void 0&&Q<U.minimum)Y.push({path:X,message:`Value must be at least ${U.minimum}`,expected:`>= ${U.minimum}`,actual:Q,rule:"minimum"});if(U.maximum!==void 0&&Q>U.maximum)Y.push({path:X,message:`Value must not exceed ${U.maximum}`,expected:`<= ${U.maximum}`,actual:Q,rule:"maximum"})}if(Array.isArray(Q)&&U.items)for(let G=0;G<Q.length;G++){let H=X?`${X}[${G}]`:`[${G}]`;if(this.validateObjectAgainstSchema(Q[G],U.items,H,Y,Z,$),$.stopOnFirstError&&Y.length>0)return}if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let G=Q;if($.validateRequired&&U.required){for(let H of U.required)if(!(H in G)){if(Y.push({path:X?`${X}.${H}`:H,message:`Missing required property '${H}'`,expected:"required",rule:"required"}),$.stopOnFirstError)return}}if(U.properties){for(let[H,_]of Object.entries(U.properties))if(H in G){let J=X?`${X}.${H}`:H;if(this.validateObjectAgainstSchema(G[H],_,J,Y,Z,$),$.stopOnFirstError&&Y.length>0)return}}if(U.additionalProperties===!1){let H=new Set(Object.keys(U.properties||{}));for(let _ of Object.keys(G))if(!H.has(_))Z.push({path:X?`${X}.${_}`:_,message:`Additional property '${_}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Q,U,X){let Y=[],Z=[];for(let $ of U)try{let G=this.getValueByPath(Q,$.path),H=this.validateWithRule(G,$,$.path);if(Y.push(...H),X.stopOnFirstError&&Y.length>0)break}catch(G){Y.push({path:$.path,message:`Rule validation failed: ${G}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:Z}}validateWithRule(Q,U,X){let Y=[];if(U.required&&(Q===void 0||Q===null))return Y.push({path:X,message:U.message||`Property '${X}' is required`,expected:"required",rule:"required"}),Y;if(Q===void 0||Q===null)return Y;if(U.type){let Z=Array.isArray(Q)?"array":typeof Q;if(Z!==U.type)Y.push({path:X,message:U.message||`Expected type ${U.type}, got ${Z}`,expected:U.type,actual:Z,rule:"type"})}if(U.min!==void 0){let Z=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if(Z<U.min)Y.push({path:X,message:U.message||`Value must be at least ${U.min}`,expected:`>= ${U.min}`,actual:Z,rule:"min"})}if(U.max!==void 0){let Z=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if(Z>U.max)Y.push({path:X,message:U.message||`Value must not exceed ${U.max}`,expected:`<= ${U.max}`,actual:Z,rule:"max"})}if(U.pattern&&typeof Q==="string"){if(!U.pattern.test(Q))Y.push({path:X,message:U.message||`Value does not match pattern ${U.pattern}`,expected:U.pattern.toString(),actual:Q,rule:"pattern"})}if(U.enum&&!U.enum.includes(Q))Y.push({path:X,message:U.message||`Value must be one of: ${U.enum.join(", ")}`,expected:U.enum.join(", "),actual:Q,rule:"enum"});if(U.validator){let Z=U.validator(Q);if(Z)Y.push({path:X,message:U.message||Z,rule:"custom"})}return Y}getValueByPath(Q,U){if(!U)return Q;let X=U.split("."),Y=Q;for(let Z of X)if(Y&&typeof Y==="object"&&Z in Y)Y=Y[Z];else return;return Y}generateRulesFromInterface(Q){let U=[],X=Q.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of X){let[,Z,$,G]=Y;U.push({path:Z,required:!$,type:this.mapTypeScriptType(G)})}return U}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:OX},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class EU{fileLoader=new gQ;envProcessor=new mQ;validator=new VU;async loadConfig(Q){let U=Date.now(),{cache:X,performance:Y,schema:Z,validate:$,...G}=Q;try{if(X?.enabled){let _=this.checkCache(G.name||"",G);if(_)return _}let H;try{H=await this.loadConfigurationStrategies(G,!0,X)}catch(_){let J=G.__strictErrorHandling;if(_ instanceof Error&&_.name==="ConfigNotFoundError"){if(J)throw _;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(_ instanceof Error&&_.name==="ConfigLoadError"){let q=_.message.includes("EACCES")||_.message.includes("EPERM")||_.message.includes("permission denied"),A=!q&&(_.message.includes("syntax")||_.message.includes("Expected")||_.message.includes("Unexpected")||_.message.includes("BuildMessage")||_.message.includes("errors building")),z=_.message.includes("Configuration must export a valid object")||_.message.includes("Configuration file is empty and exports nothing");if(J&&(z||q))throw _;if(A&&(!J||!z))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(!J)H={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`Configuration loading error, using defaults: ${_.message}`]};else throw _}else H={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${_ instanceof Error?_.message:String(_)}`]}}if(Z||$)await this.validateConfiguration(H.config,Z,$,G.name);if(X?.enabled&&H)this.cacheResult(G.name||"",H,X,G);if(Y?.enabled){let _={operation:"loadConfig",duration:Date.now()-U,configName:G.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(_);if(Y.slowThreshold&&_.duration>Y.slowThreshold)f.warn(`Slow configuration loading detected: ${_.duration}ms for ${G.name}`);H.metrics=_}return H}catch(H){let _=Date.now()-U;throw f.error(`Configuration loading failed after ${_}ms:`,[H instanceof Error?H:Error(String(H))]),H}}async loadConfigurationStrategies(Q,U=!1,X){let{name:Y="",alias:Z,cwd:$,configDir:G,defaultConfig:H,checkEnv:_=!0,arrayStrategy:J="replace",verbose:q=!1}=Q,A=$||a.cwd(),z=[],W=await this.loadLocalConfiguration(Y,Z,A,G,H,J,q,_,X);if(W)return z.push(...this.getLocalSearchPaths(Y,Z,A,G)),this.finalizeResult(W,z,_,Y,q);let D=await this.loadHomeConfiguration(Y,Z,H,J,q,_);if(D)return z.push(...this.getHomeSearchPaths(Y,Z)),this.finalizeResult(D,z,_,Y,q);let B=await this.loadPackageJsonConfiguration(Y,Z,A,H,J,q,_);if(B)return z.push(y(A,"package.json")),this.finalizeResult(B,z,_,Y,q);if(z.push(...this.getAllSearchPaths(Y,Z,A,G)),U)throw o.configNotFound(Y,z,Z);return{...await this.applyEnvironmentVariables(Y,H,_,q),warnings:[`No configuration file found for "${Y}"${Z?` or alias "${Z}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(Q,U,X,Y,Z,$,G,H,_){let J=H?JQ(Q,Z,G):Z,q=this.getLocalDirectories(X,Y);for(let A of q){if(G)f.info(`Searching for configuration in: ${A}`);let z=this.fileLoader.generateConfigPaths(Q,A,U),W=await this.fileLoader.tryLoadFromPaths(z,J,{arrayStrategy:$,verbose:G,cacheTtl:_?.ttl,useCache:!_?.ttl||_.ttl>100});if(W){if(G)f.success(`Configuration loaded from: ${W.source.path}`);return W}}return null}async loadHomeConfiguration(Q,U,X,Y,Z,$){if(!Q)return null;let G=$?JQ(Q,X,Z):X,H=[y(t(),".config",Q),y(t(),".config"),t()];for(let _ of H){if(Z)f.info(`Checking home directory: ${_}`);let J=this.fileLoader.generateConfigPaths(Q,_,U),q=await this.fileLoader.tryLoadFromPaths(J,G,{arrayStrategy:Y,verbose:Z});if(q){if(Z)f.success(`Configuration loaded from home directory: ${q.source.path}`);return q}}return null}async loadPackageJsonConfiguration(Q,U,X,Y,Z,$,G){let H=G?JQ(Q,Y,$):Y;try{let _=y(X,"package.json");if(!HU(_))return null;let J=await import(_),q=J[Q],A=Q;if(!q&&U)q=J[U],A=U;if(q&&typeof q==="object"&&!Array.isArray(q)){if($)f.success(`Configuration loaded from package.json: ${A}`);return{config:DU(H,q,Z),source:{type:"package.json",path:_,priority:30,timestamp:new Date}}}}catch(_){if($)f.warn("Failed to load package.json:",[_ instanceof Error?_:Error(String(_))])}return null}async applyEnvironmentVariables(Q,U,X,Y){if(!X||!Q||typeof U!=="object"||U===null||Array.isArray(U))return{config:U,source:{type:"default",priority:10,timestamp:new Date}};return{config:JQ(Q,U,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(Q,U,X,Y,Z){return{config:Q.config,source:Q.source,path:Q.source.path}}async validateConfiguration(Q,U,X,Y){let Z=[];if(X){let $=X(Q);if($)Z.push(...$)}if(U){let $=await this.validator.validateConfiguration(Q,U);if(!$.isValid)Z.push(...$.errors.map((G)=>G.path?`${G.path}: ${G.message}`:G.message))}if(Z.length>0)throw o.configValidation(Y||"unknown",Z,Y)}checkCache(Q,U){let X=this.generateCacheKey(Q,U);return HQ.get(X)||null}cacheResult(Q,U,X,Y){let Z=this.generateCacheKey(Q,Y);HQ.set(Z,U,void 0,X.ttl)}generateCacheKey(Q,U){let X=[Q];if(U.alias)X.push(`alias:${U.alias}`);if(U.cwd)X.push(`cwd:${U.cwd}`);if(U.configDir)X.push(`configDir:${U.configDir}`);if("checkEnv"in U)X.push(`checkEnv:${U.checkEnv}`);return X.join("|")}getLocalDirectories(Q,U){return Array.from(new Set([Q,y(Q,"config"),y(Q,".config"),U?y(Q,U):void 0].filter(Boolean)))}getAllSearchPaths(Q,U,X,Y){let Z=[];return Z.push(...this.getLocalSearchPaths(Q,U,X,Y)),Z.push(...this.getHomeSearchPaths(Q,U)),Z.push(y(X,"package.json")),Z}getLocalSearchPaths(Q,U,X,Y){let Z=this.getLocalDirectories(X,Y),$=[];for(let G of Z)$.push(...this.fileLoader.generateConfigPaths(Q,G,U));return $}getHomeSearchPaths(Q,U){if(!Q)return[];let X=[y(t(),".config",Q),y(t(),".config"),t()],Y=[];for(let Z of X)Y.push(...this.fileLoader.generateConfigPaths(Q,Z,U));return Y}async loadConfigWithResult(Q){return this.loadConfig(Q)}}function lU(Q){let X=!(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")),Y=Q.message.includes("Configuration must export a valid object")||Q.message.includes("Configuration file is empty and exports nothing");return X||Y}async function yY(Q){return i.loadConfig({...Q,__strictErrorHandling:!0})}async function IX(Q){let U="defaultConfig"in Q&&Q.defaultConfig!==void 0?Q.defaultConfig:{},X="cache"in Q||"performance"in Q||"schema"in Q||"validate"in Q;try{let Y;if(X)Y=await i.loadConfig(Q);else Y=await i.loadConfig({...Q,defaultConfig:U,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??U}catch(Y){let Z=Y instanceof Error?Y.name:"UnknownError",$=Y instanceof Error?Y.message:String(Y);if(!(Z==="ConfigNotFoundError"||Z==="ConfigLoadError"||Z==="ConfigValidationError"||$.includes("config"))&&Q.verbose)f.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let H=X?{...Q,defaultConfig:U}:{...Q,defaultConfig:U,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Q?Q.checkEnv!==!1:!0)return(await i.applyEnvironmentVariables(H.name||"",U,!0,H.verbose||!1))?.config??U;return U}}async function vY(Q={defaultConfig:{}}){if(typeof Q==="string"){let{cwd:U}=await import("process");try{return(await i.loadConfig({name:Q,cwd:U(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(X){if(X instanceof Error&&(X.name==="ConfigNotFoundError"||X.name==="ConfigLoadError"&&lU(X)))return(await i.applyEnvironmentVariables(Q,{},!0,!1)).config;throw X}}try{return(await i.loadConfig({...Q,cwd:Q.cwd||a.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(U){if(U instanceof Error&&(U.name==="ConfigNotFoundError"||U.name==="ConfigLoadError"&&lU(U)))return(await i.applyEnvironmentVariables(Q.name||"",Q.defaultConfig||{},Q.checkEnv!==!1,Q.verbose||!1)).config;throw U}}async function hY(Q,U,X="replace"){let Y=new gQ;try{let Z=await Y.loadFromPath(Q,U,{arrayStrategy:X,useCache:!1,trackPerformance:!1});return Z?Z.config:null}catch{return null}}function JQ(Q,U,X=!1){let Y=new mQ,Z=Q.toUpperCase().replace(/[^A-Z0-9]/g,"_");function $(G,H=[]){let _={...G};for(let[J,q]of Object.entries(G)){let A=[...H,J],z=[`${Z}_${A.join("_").toUpperCase()}`,`${Z}_${A.map((B)=>B.toUpperCase()).join("")}`,`${Z}_${A.map((B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],W,D;for(let B of z)if(W=a.env[B],W!==void 0){D=B;break}if(W!==void 0&&D)if(typeof q==="boolean")_[J]=["true","1","yes"].includes(W.toLowerCase());else if(typeof q==="number"){let B=Number(W);if(!Number.isNaN(B))_[J]=B}else if(Array.isArray(q))try{_[J]=JSON.parse(W)}catch{_[J]=W.split(",").map((B)=>B.trim())}else _[J]=W;else if(q&&typeof q==="object"&&!Array.isArray(q))_[J]=$(q,A)}return _}return $(U)}function dY(Q){let U=y(a.cwd(),Q.configDir),X=y(a.cwd(),Q.generatedDir),Y=y(X,"config-types.ts");if(!HU(SU(Y)))mX(SU(Y),{recursive:!0,mode:511});let Z=HU(U)?gX(U).map((G)=>G.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],$=`// Generated by bunfig v${zZ}
|
|
31
|
-
export type ConfigNames = ${Z.length?`'${Z.join("' | '")}'`:"string"}
|
|
32
|
-
`;cX(Y,$,{mode:438})}function fY(Q){let U=null,X=null,Y=()=>{if(!X)X=IX(Q).then(($)=>{return U=$,$},($)=>{let G="defaultConfig"in Q?Q.defaultConfig:{};if(U=G,"verbose"in Q&&Q.verbose)f.warn("Config loading failed, using defaults:",[$ instanceof Error?$:Error(String($))]);return G});return X},Z="defaultConfig"in Q?Q.defaultConfig:{};return U=Z,Y(),new Proxy({},{get($,G){if(U)return U[G];let H=Z[G];return Y(),H},has($,G){return G in(U||Z)},ownKeys(){return Object.keys(U||Z)},getOwnPropertyDescriptor($,G){return Object.getOwnPropertyDescriptor(U||Z,G)},set($,G,H){if(!U)U={...Z};return U[G]=H,!0}})}function pY(Q){let U=cU(BY.cwd(),Q?.configDir||"./config");function X(){if(!WY(U))return[];let Z=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),$=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],G=zY(U).filter((_)=>Z.has(eQ(_))).map((_)=>({base:_.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:_})),H=new Map;for(let{base:_,file:J}of G){let q=eQ(J).toLowerCase(),A=H.get(_);if(!A){H.set(_,J);continue}let z=eQ(A).toLowerCase();if($.indexOf(q)<$.indexOf(z))H.set(_,J)}return Array.from(H.entries()).map(([_,J])=>({base:_,file:J})).sort((_,J)=>_.base.localeCompare(J.base))}function Y(){let Z=X(),$=Z.map((J)=>J.base),G=$.length?$.map((J)=>`'${J}'`).join(" | "):"string",H=Z.length?`{
|
|
33
|
-
${Z.map((J)=>{let q=cU(U,J.file).replace(/\\/g,"/");return` '${J.base}': typeof import('${q}').default`}).join(`,
|
|
34
|
-
`)}
|
|
35
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${G}
|
|
36
|
-
export type ConfigByName = ${H}
|
|
37
|
-
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
38
|
-
export type ConfigOf = Config
|
|
39
|
-
`}return{name:"bunfig-plugin",setup(Z){Z.onResolve({filter:/^virtual:bunfig-types$/},($)=>{return{path:$.path,namespace:"bunfig-virtual"}}),Z.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Y(),loader:"ts"}})}}}var MX,HQ,zQ,DX,uY,mY,nU,OQ,AU,C,I,gY,iU,cY,sU,lY,nY,QU,iY,oU,rU,UU,sY,oY,rY,aY,TQ,VX,tY,k,eY,QZ,aU,SQ,WU,N,w,UZ,tU,XZ,eU,YZ,ZZ,XU,$Z,QX,UX,GZ,YU,_Z,HZ,JZ,qZ,AZ,CQ,EX,WZ,zZ="0.15.6",v,dQ,AQ,zU,BU,fQ,RU,LU,WQ,wU,KU,o,NX,OX,f,i,TX,SX,BZ=uX(async()=>{MX=import.meta.require,HQ=new jU,zQ=new FU,DX={createKey:RY,isEquivalent:LY,estimateMemoryUsage:wY},uY=PQ(JU.cwd(),"config"),mY=PQ(JU.cwd(),"src/generated"),nU=xQ.env.CLARITY_LOG_DIR||iX(FY(),"logs"),OQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:nU,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},AU=await IY(),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"},I=C,gY=C.red,iU=C.green,cY=C.yellow,sU=C.blue,lY=C.magenta,nY=C.cyan,QU=C.white,iY=C.gray,oU=C.bgRed,rU=C.bgYellow,UU=C.bold,sY=C.dim,oY=C.italic,rY=C.underline,aY=C.reset,TQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},VX={debug:"\uD83D\uDD0D",info:sU("ℹ"),success:iU("✓"),warning:rU(QU(UU(" WARN "))),error:oU(QU(UU(" ERROR ")))},tY=new yQ("stacks"),k=new yQ("bunfig",{showTags:!0}),eY=b(qQ.cwd(),"config"),QZ=b(qQ.cwd(),"src/generated"),aU=kQ.env.CLARITY_LOG_DIR||lX(EY(),"logs"),SQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:aU,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},WU=await NY(),N={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"},w=N,UZ=N.red,tU=N.green,XZ=N.yellow,eU=N.blue,YZ=N.magenta,ZZ=N.cyan,XU=N.white,$Z=N.gray,QX=N.bgRed,UX=N.bgYellow,GZ=N.bgGray,YU=N.bold,_Z=N.dim,HZ=N.italic,JZ=N.underline,qZ=N.strikethrough,AZ=N.reset,CQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},EX={debug:"\uD83D\uDD0D",info:eU("ℹ"),success:tU("✓"),warning:UX(XU(YU(" WARN "))),error:QX(XU(YU(" ERROR ")))},WZ=new hQ("stacks"),v=class extends Error{timestamp;context;constructor(U,X={}){super(U);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 U=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([X,Y])=>`${X}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${U}`}},dQ=class extends v{code="CONFIG_NOT_FOUND";constructor(U,X,Y){let Z=Y?` or alias "${Y}"`:"";super(`Configuration "${U}"${Z} not found`,{configName:U,alias:Y,searchPaths:X,searchPathCount:X.length})}},AQ=class extends v{code="CONFIG_LOAD_ERROR";constructor(U,X,Y){super(`Failed to load configuration from "${U}": ${X.message}`,{configPath:U,configName:Y,originalError:X.name,originalMessage:X.message});this.cause=X}},zU=class extends v{code="CONFIG_VALIDATION_ERROR";constructor(U,X,Y){super(`Configuration validation failed for "${U}"`,{configPath:U,configName:Y,validationErrors:X,errorCount:X.length})}},BU=class extends v{code="CONFIG_MERGE_ERROR";constructor(U,X,Y,Z){super(`Failed to merge configuration from "${U}" with "${X}": ${Y.message}`,{sourcePath:U,targetPath:X,configName:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},fQ=class extends v{code="ENV_VAR_ERROR";constructor(U,X,Y,Z){super(`Failed to parse environment variable "${U}" with value "${X}" as ${Y}`,{envKey:U,envValue:X,expectedType:Y,configName:Z})}},RU=class extends v{code="FILE_SYSTEM_ERROR";constructor(U,X,Y){super(`File system ${U} failed for "${X}": ${Y.message}`,{operation:U,path:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},LU=class extends v{code="TYPE_GENERATION_ERROR";constructor(U,X,Y){super(`Failed to generate types from "${U}" to "${X}": ${Y.message}`,{configDir:U,outputPath:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},WQ=class extends v{code="SCHEMA_VALIDATION_ERROR";constructor(U,X,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:U,configName:Y,validationErrors:X,errorCount:X.length})}},wU=class extends v{code="BROWSER_CONFIG_ERROR";constructor(U,X,Y,Z){super(`Failed to fetch configuration from "${U}": ${X} ${Y}`,{endpoint:U,status:X,statusText:Y,configName:Z})}},KU=class extends v{code="PLUGIN_ERROR";constructor(U,X,Y){super(`Plugin "${U}" failed during ${X}: ${Y.message}`,{pluginName:U,operation:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},o={configNotFound(Q,U,X){return new dQ(Q,U,X)},configLoad(Q,U,X){return new AQ(Q,U,X)},configValidation(Q,U,X){return new zU(Q,U,X)},configMerge(Q,U,X,Y){return new BU(Q,U,X,Y)},envVar(Q,U,X,Y){return new fQ(Q,U,X,Y)},fileSystem(Q,U,X){return new RU(Q,U,X)},typeGeneration(Q,U,X){return new LU(Q,U,X)},schemaValidation(Q,U,X){return new WQ(Q,U,X)},browserConfig(Q,U,X,Y){return new wU(Q,U,X,Y)},plugin(Q,U,X){return new KU(Q,U,X)}},NX={replace:"replace",concat:"concat",smart:"smart"},OX=/^https?:\/\//,f=new hQ("bunfig",{showTags:!0}),i=new EU,TX=y(a.cwd(),"config"),SX=y(a.cwd(),"src/generated")});function wZ(Q,U={}){let X=pQ.cwd();while(X.includes("storage"))X=XX(X,"..");let Y=XX(X,Q||"");if(U?.relative)return LZ(pQ.cwd(),Y);return Y}var KZ=pQ.env.CLARITY_LOG_DIR||RZ(wZ(),"logs"),CX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:KZ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},uQ={...CX},y0=(async()=>{try{let{loadConfig:Q}=await BZ().then(()=>AX),U=await Q({name:"clarity",alias:"logging",defaultConfig:CX,cwd:pQ.cwd()});if(U)Object.assign(uQ,U)}catch{}return uQ})();function O(){if(n.env.NODE_ENV==="test"||n.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function TZ(){if(n.env.NODE_ENV==="test"||n.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof n<"u"){let Q=n.type;if(Q==="renderer"||Q==="worker")return!1;return!!(n.versions&&(n.versions.node||n.versions.bun))}return!1}class kX{async format(Q){let U=await TZ(),X=await this.getMetadata(U);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:X})}async getMetadata(Q){if(Q){let{hostname:U}=await import("os");return{pid:_Q.pid,hostname:U(),environment:_Q.env.NODE_ENV||"development",platform:_Q.platform,version:_Q.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:_Q.env.NODE_ENV||_Q.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var T={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"},K=T,n0=T.red,SZ=T.green,i0=T.yellow,CZ=T.blue,s0=T.magenta,o0=T.cyan,JX=T.white,r0=T.gray,kZ=T.bgRed,xZ=T.bgYellow,a0=T.bgGray,qX=T.bold,t0=T.dim,e0=T.italic,Q7=T.underline,U7=T.strikethrough,X7=T.reset,_U={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},PZ={debug:"\uD83D\uDD0D",info:CZ("ℹ"),success:SZ("✓"),warning:xZ(JX(qX(" WARN "))),error:kZ(JX(qX(" ERROR ")))};class BQ{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,U={}){this.name=Q,this.config={...uQ},this.options=this.normalizeOptions(U),this.formatter=this.options.formatter||new kX,this.enabled=U.enabled??!0,this.fancy=U.fancy??!0,this.tagFormat=U.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=U.timestampPosition??"right",this.environment=U.environment??L.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(U);let X={...U},Y=U.timestamp!==void 0;if(Y)delete X.timestamp;if(this.config={...this.config,...X,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let Z=this.generateKeyId(),$=this.generateKey();this.currentKeyId=Z,this.keys.set(Z,$),this.encryptionKeys.set(Z,{key:$,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;let U={debug:0,info:1,success:2,warning:3,error:4},X=this.fingersCrossedConfig.activationLevel??"error";return U[Q]>=U[X]}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{..._U,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{..._U};return{..._U,...Q.fingersCrossed}}normalizeOptions(Q){let U={format:"json",level:"info",logDirectory:uQ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},X={...U,...Object.fromEntries(Object.entries(Q).filter(([,Y])=>Y!==void 0))};if(!X.level||!["debug","info","success","warning","error"].includes(X.level))X.level=U.level;return X}shouldWriteToFile(){return!O()&&this.config.writeToFile===!0}async writeToFile(Q){let X=(async()=>{let Z,$=0,G=3,H=1000;while($<G)try{try{try{await DZ(this.config.logDirectory,GX.F_OK|GX.W_OK)}catch(J){if(J instanceof Error&&"code"in J)if(J.code==="ENOENT")await VZ(this.config.logDirectory,{recursive:!0,mode:493});else if(J.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw J;else throw J}}catch(J){throw console.error("Debug: [writeToFile] Failed to create log directory:",J),J}let _=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:g.from(Q);try{if(!DQ(this.currentLogFile))await GU(this.currentLogFile,"",{mode:420});if(Z=$X(this.currentLogFile,"a",420),MZ(Z,_,{flag:"a"}),ZX(Z),Z!==void 0)$U(Z),Z=void 0;if((await $Q(this.currentLogFile)).size===0){if(await GU(this.currentLogFile,_,{flag:"w",mode:420}),(await $Q(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(J){let q=J;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if($<G-1){let A=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${$+1}/${G}:`,A);let z=H*2**$;await new Promise((W)=>setTimeout(W,z)),$++;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(Z!==void 0)try{$U(Z)}catch(J){console.error("Debug: [writeToFile] Error closing file descriptor:",J)}}}catch(_){if($===G-1){let q=_,A=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),_}$++;let J=H*2**($-1);await new Promise((q)=>setTimeout(q,J))}})();this.pendingOperations.push(X);let Y=this.pendingOperations.length-1;try{await X}catch(Z){throw console.error("Debug: [writeToFile] Error in operation:",Z),Z}finally{this.pendingOperations.splice(Y,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 GQ(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 GQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return GQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(O())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,U;switch(Q.frequency){case"daily":U=86400000;break;case"weekly":U=604800000;break;case"monthly":U=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},U)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let U=this.config.rotation.keyRotation;if(!U?.enabled)return;let X=typeof U.interval==="number"?U.interval:60,Y=Math.max(X,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Z)=>{console.error("Error rotating keys:",Z)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let U=this.config.rotation.keyRotation,X=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=X,this.keys.set(X,Y),this.encryptionKeys.set(X,{key:Y,createdAt:new Date});let Z=Array.from(this.encryptionKeys.entries()).sort(([,H],[,_])=>_.createdAt.getTime()-H.createdAt.getTime()),$=typeof U.maxKeys==="number"?U.maxKeys:1,G=Math.max(1,$);if(Z.length>G)for(let[H]of Z.slice(G))this.encryptionKeys.delete(H),this.keys.delete(H)}generateKeyId(){return ZU(16).toString("hex")}generateKey(){return ZU(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:U}=this.getCurrentKey(),X=ZU(16),Y=jZ("aes-256-gcm",U,X),Z=g.isBuffer(Q)?Q:g.from(Q,"utf8"),$=Y.update(Z),G=Y.final(),H=$.length+G.length,_=Y.getAuthTag(),J=g.allocUnsafe(16+H+16);return X.copy(J,0),$.copy(J,16),G.copy(J,16+$.length),_.copy(J,16+H),{encrypted:J,iv:X}}async compressData(Q){return new Promise((U,X)=>{let Y=HX(),Z=[];Y.on("data",($)=>Z.push($)),Y.on("end",()=>U(g.from(g.concat(Z)))),Y.on("error",X),Y.write(Q),Y.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 U=this.config.rotation.encrypt;return{...Q,...U}}return Q}async rotateLog(){if(O())return;if(!this.shouldWriteToFile())return;let Q=await $Q(this.currentLogFile).catch(()=>null);if(!Q)return;let U=this.config.rotation;if(typeof U==="boolean")return;if(U.maxSize&&Q.size>=U.maxSize){let X=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let Z=await VQ(this.config.logDirectory),$=Z.filter((_)=>_.startsWith(this.name)&&/\.log\.\d+$/.test(_)).sort((_,J)=>{let q=Number.parseInt(_.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),G=$.length>0?Number.parseInt($[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,H=`${X}.${G}`;if(await $Q(X).catch(()=>null))try{if(await _X(X,H),U.compress)try{let _=`${H}.gz`;await this.compressLogFile(H,_),await EQ(H)}catch(_){console.error("Error compressing rotated file:",_)}if($.length===0&&!Z.some((_)=>_.endsWith(".log.1")))try{let _=`${X}.1`;await GU(_,"")}catch(_){console.error("Error creating backup file:",_)}}catch(_){console.error(`Error during rotation: ${_ instanceof Error?_.message:String(_)}`)}}else{let Z=new Date().toISOString().replace(/[:.]/g,"-"),$=X.replace(/\.log$/,`-${Z}.log`);if(await $Q(X).catch(()=>null))await _X(X,$)}if(this.currentLogFile=Y,U.maxFiles){let $=(await VQ(this.config.logDirectory)).filter((G)=>G.startsWith(this.name)).sort((G,H)=>H.localeCompare(G));for(let G of $.slice(U.maxFiles))await EQ(GQ(this.config.logDirectory,G))}}}async compressLogFile(Q,U){let X=YX(Q),Y=IZ(U),Z=HX();await OZ(X,Z,Y)}async handleFingersCrossedBuffer(Q,U){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let X of this.logBuffer){let Y=await this.formatter.format(X);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(U);console.log(U)}}shouldLog(Q){if(!this.enabled)return!1;let U={debug:0,info:1,success:2,warning:3,error:4};return U[Q]>=U[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((U)=>{console.error("Error in pending write operation:",U)});return Promise.resolve()})),DQ(this.currentLogFile))try{let Q=$X(this.currentLogFile,"r+");ZX(Q),$U(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(!O()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let U=(await VQ(this.config.logDirectory)).filter((X)=>(X.includes("temp")||X.includes(".tmp"))&&X.includes(this.name));for(let X of U)try{await EQ(GQ(this.config.logDirectory,X))}catch(Y){console.error(`Failed to delete temp file ${X}:`,Y)}}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()?K.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||O())return!1;let Q=typeof L.env.NO_COLOR<"u",U=L.env.FORCE_COLOR==="0";if(Q||U)return!1;return!!(typeof L.stderr<"u"&&L.stderr.isTTY||typeof L.stdout<"u"&&L.stdout.isTTY)}formatConsoleMessage(Q){let{timestamp:U,icon:X="",tag:Y="",message:Z,level:$,showTimestamp:G=!0}=Q,H=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(G)W.push(U);if($==="warning")W.push("WARN");else if($==="error")W.push("ERROR");else if(X)W.push(X.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)W.push(Y.replace(/[[\]]/g,""));return W.push(Z),W.join(" ")}let _=L.stdout.columns||120,J="";if($==="warning"||$==="error")J=`${X} ${Z}`;else if($==="info"||$==="success")J=`${X} ${Y} ${Z}`;else J=`${X} ${Y} ${K.cyan(Z)}`;if(!G)return J.trim();let q=H(J).trim().length,A=H(U).length,z=Math.max(1,_-2-q-A);return`${J.trim()}${" ".repeat(z)}${U}`}formatMessage(Q,U){if(U.length===1&&Array.isArray(U[0]))return Q.replace(/\{(\d+)\}/g,($,G)=>{let H=Number.parseInt(G,10);return H<U[0].length?String(U[0][H]):$});let X=/%([sdijfo%])/g,Y=0,Z=Q.replace(X,($,G)=>{if(G==="%")return"%";if(Y>=U.length)return $;let H=U[Y++];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 $}});if(Y<U.length)Z+=` ${U.slice(Y).map(($)=>typeof $==="object"?JSON.stringify($,null,2):String($)).join(" ")}`;return Z}formatMarkdown(Q){if(!Q)return Q;let U=Q;return U=U.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(X,Y,Z)=>{let $=K.underline(K.blue(Y)),G=this.toAbsoluteFilePath(Z);if(G&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let H=`file://${encodeURI(G)}`,_="\x1B]8;;",J="\x1B\\";return`\x1B]8;;${H}\x1B\\${$}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${Z}\x1B\\${$}\x1B]8;;\x1B\\`;return $}),U=U.replace(/`([^`]+)`/g,(X,Y)=>K.bgGray(Y)),U=U.replace(/\*\*([^*]+)\*\*/g,(X,Y)=>K.bold(Y)),U=U.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(X,Y)=>K.italic(Y)),U=U.replace(/(?<!_)_([^_]+)_(?!_)/g,(X,Y)=>K.italic(Y)),U=U.replace(/~([^~]+)~/g,(X,Y)=>K.strikethrough(Y)),U}supportsHyperlinks(){if(O())return!1;let Q=L.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 U=Q.VTE_VERSION?Number.parseInt(Q.VTE_VERSION,10):0;if(!Number.isNaN(U)&&U>=5000)return!0;return!1}toAbsoluteFilePath(Q){try{let U=Q;if(U.startsWith("file://"))U=U.replace(/^file:\/\//,"");if(U.startsWith("~")){let X=L.env.HOME||"";if(X)U=U.replace(/^~(?=$|\/)/,X)}if(EZ(U)||U.startsWith("./")||U.startsWith("../"))U=NZ(U);else return null;return DQ(U)?U:null}catch{return null}}buildOutputTexts(Q){let U=this.shouldStyleConsole()?this.formatMarkdown(Q):Q,X=Q.replace(this.ANSI_PATTERN,"");return{consoleText:U,fileText:X}}async log(Q,U,...X){if(!this.shouldLog(Q))return;let Y=new Date,Z=this.formatConsoleTimestamp(Y),$=this.formatFileTimestamp(Y),G,H;if(U instanceof Error)G=U.message,H=U.stack;else G=this.formatMessage(U,X);let{consoleText:_,fileText:J}=this.buildOutputTexts(G);if(this.shouldStyleConsole()){let A=this.options.showIcons===!1?"":PZ[Q],z=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",W;switch(Q){case"debug":W=this.formatConsoleMessage({timestamp:Z,icon:A,tag:z,message:K.gray(_),level:Q}),console.error(W);break;case"info":W=this.formatConsoleMessage({timestamp:Z,icon:A,tag:z,message:_,level:Q}),console.warn(W);break;case"success":W=this.formatConsoleMessage({timestamp:Z,icon:A,tag:z,message:K.green(_),level:Q}),console.error(W);break;case"warning":W=this.formatConsoleMessage({timestamp:Z,icon:A,tag:z,message:_,level:Q}),console.warn(W);break;case"error":if(W=this.formatConsoleMessage({timestamp:Z,icon:A,tag:z,message:_,level:Q}),console.error(W),H){let D=H.split(`
|
|
40
|
-
`);for(let B of D)if(B.trim()&&!B.includes(G))console.error(this.formatConsoleMessage({timestamp:Z,message:K.gray(` ${B}`),level:Q,showTimestamp:!1}))}break}}else if(!O()){if(console.error(`${$} ${this.environment}.${Q.toUpperCase()}: ${G}`),H)console.error(H)}let q=`${$} ${this.environment}.${Q.toUpperCase()}: ${J}
|
|
41
|
-
`;if(H)q+=`${H}
|
|
42
|
-
`;if(q=q.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(q)}progress(Q,U=""){let X={update:(H,_)=>{},finish:(H)=>{},interrupt:(H,_)=>{}};if(!this.enabled)return X;let Y=30;if(this.activeProgressBar={total:Math.max(1,Q||1),current:0,message:U||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!O()&&L.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(H,_)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,H),this.activeProgressBar.total),_!==void 0)this.activeProgressBar.message=_;if(this.shouldStyleConsole()&&!O()&&L.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(H)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,H)},interrupt:(H,_="info")=>{if(!O()&&L.stdout.isTTY)L.stdout.write(`
|
|
43
|
-
`);if(this[_==="warning"?"warn":_](H),this.activeProgressBar&&this.shouldStyleConsole()&&!O()&&L.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Q){let U=performance.now();if(this.shouldStyleConsole()){let X=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":K.blue("◐"),tag:X,message:`${K.cyan(Q)}...`}))}return async(X)=>{if(!this.enabled)return;let Y=performance.now(),Z=Math.round(Y-U),$=`${Q} completed in ${Z}ms`,G=new Date,H=this.formatConsoleTimestamp(G),J=`${this.formatFileTimestamp(G)} ${this.environment}.INFO: ${$}`;if(X)J+=` ${JSON.stringify(X)}`;if(J+=`
|
|
44
|
-
`,J=J.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let q=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:H,icon:this.options.showIcons===!1?"":K.green("✓"),tag:q,message:`${$}${X?` ${JSON.stringify(X)}`:""}`}))}else if(!O())console.error(J.trim());if(this.shouldWriteToFile())await this.writeToFile(J)}}async debug(Q,...U){await this.log("debug",Q,...U)}async info(Q,...U){await this.log("info",Q,...U)}async success(Q,...U){await this.log("success",Q,...U)}async warn(Q,...U){await this.log("warning",Q,...U)}async error(Q,...U){await this.log("error",Q,...U)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:U}=Q;return!!U}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let U=`${this.name}:${Q}`,X=new BQ(U,{...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(X),X}createReadStream(){if(O())throw Error("createReadStream is not supported in browser environments");if(!DQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return YX(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let U=this.config.rotation;if(!U.encrypt||typeof U.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let X=this.keys.get(this.currentKeyId);try{let Y=g.isBuffer(Q)?Q:g.from(Q,"base64"),Z=Y.subarray(0,16),$=Y.subarray(Y.length-16),G=Y.subarray(16,Y.length-16),H=FZ("aes-256-gcm",X,Z);H.setAuthTag($);let _=H.update(G),J=H.final(),q=_.length+J.length,A=g.allocUnsafe(q);return _.copy(A,0),J.copy(A,_.length),A.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return O()}isServerMode(){return!O()}setTestEncryptionKey(Q,U){this.currentKeyId=Q,this.keys.set(Q,U)}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 U=new Date,X=this.formatConsoleTimestamp(U),Y=this.formatFileTimestamp(U),{consoleText:Z,fileText:$}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let H=Z.split(`
|
|
45
|
-
`),_=Math.max(...H.map((z)=>z.length))+2,J=`┌${"─".repeat(_)}┐`,q=`└${"─".repeat(_)}┘`,A=H.map((z)=>{return this.formatConsoleMessage({timestamp:X,message:K.cyan(z),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:X,message:K.cyan(J),showTimestamp:!1})),A.forEach((z)=>console.error(z)),console.error(this.formatConsoleMessage({timestamp:X,message:K.cyan(q),showTimestamp:!1}))}else if(!O())console.error(`${Y} ${this.environment}.INFO: [BOX] ${$}`);let G=`${Y} ${this.environment}.INFO: [BOX] ${$}
|
|
46
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(G)}async prompt(Q){if(O())return Promise.resolve(!0);return new Promise((U)=>{console.error(`${K.cyan("?")} ${Q} (y/n) `);let X=(Y)=>{let Z=Y.toString().trim().toLowerCase();L.stdin.removeListener("data",X);try{if(typeof L.stdin.setRawMode==="function")L.stdin.setRawMode(!1)}catch{}L.stdin.pause(),console.error(""),U(Z==="y"||Z==="yes")};try{if(typeof L.stdin.setRawMode==="function")L.stdin.setRawMode(!0)}catch{}L.stdin.resume(),L.stdin.once("data",X)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...U){if(!this.enabled)return;let X=Q;if(U&&U.length>0){let _=/%([sdijfo%])/g,J=0;if(X=Q.replace(_,(q,A)=>{if(A==="%")return"%";if(J>=U.length)return q;let z=U[J++];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}}),J<U.length)X+=` ${U.slice(J).map((q)=>typeof q==="object"?JSON.stringify(q,null,2):String(q)).join(" ")}`}let{consoleText:Y,fileText:Z}=this.buildOutputTexts(X);if(this.shouldStyleConsole()){let _=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",J=this.options.showIcons===!1?"":`${K.blue("◐")} `;console.error(`${J}${_} ${K.cyan(Y)}`)}let H=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Z}
|
|
47
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(H)}renderProgressBar(Q,U=!1){if(!this.enabled||!this.shouldStyleConsole()||!L.stdout.isTTY)return;let X=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Y=Math.round(Q.barLength*X/100),Z=Q.barLength-Y,$=K.green("━".repeat(Y)),G=K.gray("━".repeat(Z)),H=`[${$}${G}]`,_=`${X}%`.padStart(4),J=Q.message?` ${Q.message}`:"",q=this.options.showIcons===!1?"":U||X===100?K.green("✓"):K.blue("▶"),A=this.options.showTags!==!1&&this.name?` ${K.gray(this.formatTag(this.name))}`:"",z=`\r${q}${A} ${H} ${_}${J}`,W=L.stdout.columns||80,D=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${D}`,L.stdout.write(Q.lastRenderedLine),U)L.stdout.write(`
|
|
48
|
-
`)}finishProgressBar(Q,U){if(!this.enabled||!this.fancy||O()||!L.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(U)Q.message=U;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(O()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let U=await VQ(this.config.logDirectory),X=[];for(let Y of U){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let $=GQ(this.config.logDirectory,Y);if(Q.before)try{if((await $Q($)).mtime>=Q.before)continue}catch(G){console.error(`Failed to get stats for file ${$}:`,G);continue}X.push($)}if(X.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${X.length} log file(s)...`);for(let Y of X)try{await EQ(Y),console.warn(`Deleted log file: ${Y}`)}catch(Z){console.error(`Failed to delete log file ${Y}:`,Z)}console.warn("Log clearing process finished.")}catch(U){console.error("Error during log clearing process:",U)}}}var Y7=new BQ("stacks");var bZ=new BQ("rpx",{showTags:!1});function yZ(){return process.env.SUDO_PASSWORD}function _7(Q){let U=yZ(),X=Q.replace(/'/g,"'\\''");if(U)return xX(`echo '${U}' | sudo -S sh -c '${X}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return xX(`sudo sh -c '${X}'`,{encoding:"utf-8"})}function PX(Q,U,X){if(X)bZ.debug(`[rpx:${Q}] ${U}`)}function H7(Q){if(yX(Q))return Q.proxies.map((U)=>{let X=U.to||"stacks.localhost";return X.startsWith("http")?new URL(X).hostname:X});if(vX(Q)){let U=Q.to||"stacks.localhost";return[U.startsWith("http")?new URL(U).hostname:U]}return["stacks.localhost"]}function J7(Q){return typeof Q==="object"&&Q!==null&&"certificate"in Q&&"privateKey"in Q&&typeof Q.certificate==="string"&&typeof Q.privateKey==="string"}function q7(Q){if(!Q)return"stacks.localhost";if(yX(Q)&&Q.proxies.length>0)return Q.proxies[0].to||"stacks.localhost";if(vX(Q))return Q.to||"stacks.localhost";return"stacks.localhost"}function A7(Q){return!!(Q&&("proxies"in Q)&&Array.isArray(Q.proxies))}function yX(Q){return"proxies"in Q&&Array.isArray(Q.proxies)}function vX(Q){return"to"in Q&&typeof Q.to==="string"}function W7(Q){return!!(Q&&("to"in Q)&&!("proxies"in Q))}function z7(Q,U){if(!U||U.length===0)return null;for(let X of U)if(Q===X.from||Q.startsWith(`${X.from}/`)){let Y=X.to.startsWith("http")?new URL(X.to).host:X.to,Z=X.stripPrefix===!0?Q.slice(X.from.length)||"/":Q;return{targetHost:Y,targetPath:Z}}return null}async function B7(Q,U){try{await bX.unlink(Q),PX("certificates",`Successfully deleted: ${Q}`,U)}catch(X){if(X.code!=="ENOENT")PX("certificates",`Warning: Could not delete ${Q}: ${X}`,U)}}
|
|
49
|
-
export{yZ as w,_7 as x,PX as y,H7 as z,J7 as A,q7 as B,A7 as C,yX as D,vX as E,W7 as F,z7 as G,B7 as H};
|
package/dist/chunk-cy653fq8.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{y as F}from"./chunk-cvt0dqrv.js";import{I as X}from"./chunk-sqn04kae.js";import Q from"node:dgram";var $=15353;function _(k){return{id:k.readUInt16BE(0),flags:k.readUInt16BE(2),qdcount:k.readUInt16BE(4),ancount:k.readUInt16BE(6),nscount:k.readUInt16BE(8),arcount:k.readUInt16BE(10)}}function C(k,z){let A=[],j=z;while(!0){let B=k[j];if(B===0){j++;break}if((B&192)===192){let G=k.readUInt16BE(j)&16383,{name:E}=C(k,G);A.push(E),j+=2;break}j++,A.push(k.subarray(j,j+B).toString("ascii")),j+=B}return{name:A.join("."),newOffset:j}}function H(k,z){let{name:A,newOffset:j}=C(k,z),B=k.readUInt16BE(j),G=k.readUInt16BE(j+2);return{question:{name:A,type:B,class:G},newOffset:j+4}}function U(k){let z=k.split("."),A=[];for(let j of z)A.push(Buffer.from([j.length])),A.push(Buffer.from(j,"ascii"));return A.push(Buffer.from([0])),Buffer.concat(A)}function T(k,z,A){let j=[],B=Buffer.alloc(12);B.writeUInt16BE(k,0),B.writeUInt16BE(33152,2),B.writeUInt16BE(1,4),B.writeUInt16BE(1,6),B.writeUInt16BE(0,8),B.writeUInt16BE(0,10),j.push(B),j.push(U(z.name));let G=Buffer.alloc(4);G.writeUInt16BE(z.type,0),G.writeUInt16BE(z.class,2),j.push(G),j.push(U(z.name));let E=Buffer.alloc(10);if(E.writeUInt16BE(z.type,0),E.writeUInt16BE(1,2),E.writeUInt32BE(300,4),z.type===1){E.writeUInt16BE(4,8),j.push(E);let K=A.split(".").map((M)=>Number.parseInt(M,10));j.push(Buffer.from(K))}else if(z.type===28)E.writeUInt16BE(16,8),j.push(E),j.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return B.writeUInt16BE(33155,2),B.writeUInt16BE(0,6),Buffer.concat([B,U(z.name),G]);return Buffer.concat(j)}function I(k,z){let A=[],j=Buffer.alloc(12);j.writeUInt16BE(k,0),j.writeUInt16BE(33155,2),j.writeUInt16BE(1,4),j.writeUInt16BE(0,6),j.writeUInt16BE(0,8),j.writeUInt16BE(0,10),A.push(j),A.push(U(z.name));let B=Buffer.alloc(4);return B.writeUInt16BE(z.type,0),B.writeUInt16BE(z.class,2),A.push(B),Buffer.concat(A)}var J=null,Z=new Set;async function R(k,z){if(J)return F("dns","DNS server already running",z),!0;return Z=new Set(k.map((A)=>A.toLowerCase())),new Promise((A)=>{J=Q.createSocket("udp4"),J.on("error",(j)=>{if(F("dns",`DNS server error: ${j.message}`,z),j.message.includes("EACCES")||j.message.includes("permission"))F("dns","DNS server requires root privileges to bind to port 53",z);J?.close(),J=null,A(!1)}),J.on("message",(j,B)=>{try{let G=_(j),{question:E}=H(j,12);F("dns",`Query for ${E.name} type ${E.type} from ${B.address}`,z);let K=E.name.toLowerCase(),M=!1;for(let Y of Z)if(K===Y||K.endsWith(`.${Y}`)){M=!0;break}let W;if(M&&(E.type===1||E.type===28))W=T(G.id,E,"127.0.0.1"),F("dns",`Responding with localhost for ${E.name}`,z);else W=I(G.id,E),F("dns",`NXDOMAIN for ${E.name}`,z);J?.send(W,B.port,B.address)}catch(G){F("dns",`Error processing DNS query: ${G}`,z)}}),J.on("listening",()=>{let j=J?.address();F("dns",`DNS server listening on ${j?.address}:${j?.port}`,z),A(!0)});try{J.bind($,"127.0.0.1")}catch(j){F("dns",`Failed to bind DNS server: ${j}`,z),A(!1)}})}function O(k){if(J)F("dns","Stopping DNS server",k),J.close(),J=null}function w(){return J!==null}function x(k){let z=new Set;for(let A of k){let j=A.split(".");if(j.length>=2)z.add(j[j.length-1])}return Array.from(z)}var V=new Set;async function D(k){if(process.platform!=="darwin")return;let{execSudoSync:z,getSudoPassword:A}=await import("./chunk-wcerh8e8.js");if(!A()){F("dns","Cannot flush DNS cache without SUDO_PASSWORD",k);return}try{z("dscacheutil -flushcache"),z("killall -HUP mDNSResponder 2>/dev/null || true"),F("dns","DNS cache flushed",k)}catch(B){F("dns",`Could not flush DNS cache: ${B}`,k)}}async function y(k,z){if(process.platform!=="darwin")return F("dns","Resolver setup only needed on macOS",k),!0;let{execSudoSync:A,getSudoPassword:j}=await import("./chunk-wcerh8e8.js");if(!j())return F("dns","SUDO_PASSWORD not set, cannot create resolver files",k),!1;let G=z?x(z):["test"];try{for(let E of G){if(V.has(E))continue;let K=`bash -c 'mkdir -p /etc/resolver && echo -e "nameserver 127.0.0.1\\nport ${$}" > /etc/resolver/${E}'`;A(K),V.add(E),F("dns",`Created /etc/resolver/${E} for .${E} TLD`,k)}return await D(k),!0}catch(E){return F("dns",`Failed to create resolver file: ${E}`,k),!1}}async function L(k){if(process.platform!=="darwin")return;let{execSudoSync:z,getSudoPassword:A}=await import("./chunk-wcerh8e8.js");try{if(A()){for(let B of V)z(`rm -f /etc/resolver/${B}`),F("dns",`Removed /etc/resolver/${B}`,k);V.clear()}}catch(j){F("dns",`Failed to remove resolver files: ${j}`,k)}}export{O as stopDnsServer,R as startDnsServer,y as setupResolver,L as removeResolver,w as isDnsServerRunning};
|