@stacksjs/dtsx 0.9.9 → 0.9.10
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/LICENSE.md +21 -0
- package/README.md +243 -15
- package/dist/bin/cli.js +10 -22
- package/dist/branded-types.d.ts +168 -0
- package/dist/bundler.d.ts +55 -0
- package/dist/cache.d.ts +43 -0
- package/dist/checker.d.ts +107 -0
- package/dist/chunk-09zp67d8.js +6 -0
- package/dist/chunk-0kmfaaz6.js +2 -0
- package/dist/chunk-1mm3t0nr.js +3 -0
- package/dist/chunk-2f046tgr.js +2 -0
- package/dist/chunk-3g2v2ns2.js +2 -0
- package/dist/chunk-3j7r0fxz.js +2 -0
- package/dist/chunk-3mxzfgcv.js +75 -0
- package/dist/chunk-4ev1n7r7.js +3 -0
- package/dist/chunk-57agx6g8.js +3 -0
- package/dist/chunk-6ppqaypd.js +2 -0
- package/dist/chunk-6qv7p9sg.js +170 -0
- package/dist/chunk-6s7n1gt0.js +2 -0
- package/dist/chunk-74j5mydx.js +3 -0
- package/dist/chunk-7cpp6v8f.js +2 -0
- package/dist/chunk-9a3jfxnc.js +3 -0
- package/dist/chunk-9mjc7ddv.js +19 -0
- package/dist/chunk-axb2kjeq.js +2 -0
- package/dist/chunk-bn29kee5.js +102 -0
- package/dist/chunk-c18vx9sq.js +2 -0
- package/dist/chunk-d0p3jzwb.js +34 -0
- package/dist/chunk-dk2vv0np.js +15 -0
- package/dist/chunk-e3j9tecw.js +3 -0
- package/dist/chunk-f18nyrrb.js +32 -0
- package/dist/chunk-fbqcsr60.js +22 -0
- package/dist/chunk-ffqpf34b.js +3 -0
- package/dist/chunk-fw6wcdfd.js +4 -0
- package/dist/chunk-h12gdfk9.js +2 -0
- package/dist/chunk-j22v8wfe.js +33 -0
- package/dist/chunk-jm5ywn4e.js +13 -0
- package/dist/chunk-jvz9t6pq.js +2 -0
- package/dist/chunk-k5h5ppp5.js +2 -0
- package/dist/chunk-p1d09y82.js +449 -0
- package/dist/chunk-pyxbb193.js +2 -0
- package/dist/chunk-q75q4w1s.js +3 -0
- package/dist/chunk-r1m3q3dj.js +2 -0
- package/dist/chunk-r1ywapeb.js +6 -0
- package/dist/chunk-rnt0wkrk.js +23 -0
- package/dist/chunk-rrkq4k1n.js +2 -0
- package/dist/chunk-rw6j20e2.js +3 -0
- package/dist/chunk-v96rjx7x.js +134 -0
- package/dist/circular.d.ts +82 -0
- package/dist/compat.d.ts +108 -0
- package/dist/config.d.ts +33 -3
- package/dist/diff.d.ts +82 -0
- package/dist/docs.d.ts +97 -0
- package/dist/errors.d.ts +113 -0
- package/dist/extractor/builders.d.ts +38 -0
- package/dist/extractor/cache.d.ts +47 -0
- package/dist/extractor/declarations.d.ts +50 -0
- package/dist/extractor/directives.d.ts +9 -0
- package/dist/extractor/extract.d.ts +10 -0
- package/dist/extractor/hash.d.ts +1 -0
- package/dist/extractor/helpers.d.ts +39 -0
- package/dist/extractor/index.d.ts +70 -0
- package/dist/extractor/scanner.d.ts +6 -0
- package/dist/extractor.d.ts +3 -4
- package/dist/formats.d.ts +50 -0
- package/dist/formatter.d.ts +61 -0
- package/dist/generator.d.ts +12 -3
- package/dist/import-sorter.d.ts +99 -0
- package/dist/incremental.d.ts +84 -0
- package/dist/index.d.ts +54 -1
- package/dist/logger.d.ts +57 -0
- package/dist/lsp.d.ts +317 -0
- package/dist/memory.d.ts +110 -0
- package/dist/merger.d.ts +38 -0
- package/dist/optimizer.d.ts +52 -0
- package/dist/output-normalizer.d.ts +123 -0
- package/dist/parallel-processor.d.ts +63 -0
- package/dist/parser.d.ts +24 -15
- package/dist/plugins/bun.d.ts +58 -0
- package/dist/plugins/esbuild.d.ts +63 -0
- package/dist/plugins/index.d.ts +14 -0
- package/dist/plugins/tsup.d.ts +53 -0
- package/dist/plugins/vite.d.ts +49 -0
- package/dist/plugins/webpack.d.ts +66 -0
- package/dist/plugins.d.ts +83 -0
- package/dist/process-source.d.ts +11 -0
- package/dist/processor/cache.d.ts +16 -0
- package/dist/processor/comments.d.ts +7 -0
- package/dist/processor/declarations.d.ts +37 -0
- package/dist/processor/imports.d.ts +65 -0
- package/dist/processor/index.d.ts +34 -0
- package/dist/processor/type-inference.d.ts +106 -0
- package/dist/processor.d.ts +3 -43
- package/dist/profiling.d.ts +101 -0
- package/dist/security.d.ts +100 -0
- package/dist/sourcemap.d.ts +125 -0
- package/dist/src/index.js +55 -2
- package/dist/src/plugins/bun.js +2 -0
- package/dist/src/plugins/esbuild.js +2 -0
- package/dist/src/plugins/index.js +2 -0
- package/dist/src/plugins/tsup.js +2 -0
- package/dist/src/plugins/vite.js +2 -0
- package/dist/src/plugins/webpack.js +2 -0
- package/dist/tracking.d.ts +89 -0
- package/dist/transformers.d.ts +173 -0
- package/dist/tree-shaker.d.ts +69 -0
- package/dist/type-mappings.d.ts +148 -0
- package/dist/types.d.ts +137 -7
- package/dist/utils.d.ts +53 -1
- package/dist/watcher.d.ts +64 -0
- package/dist/worker.d.ts +84 -0
- package/dist/workspace.d.ts +62 -0
- package/package.json +49 -11
- package/dist/chunk-qsyn1k3w.js +0 -504
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Vc as xX}from"./chunk-57agx6g8.js";import{cd as r}from"./chunk-rw6j20e2.js";import{existsSync as CY}from"fs";import{resolve as xY}from"path";import kX from"process";import{pathToFileURL as kY}from"url";import{existsSync as gQ,statSync as cQ}from"fs";import{existsSync as PX,mkdirSync as hY,readdirSync as dY,writeFileSync as fY}from"fs";import{homedir as u}from"os";import{dirname as uY,resolve as x}from"path";import KQ from"process";import{join as bX,relative as yX,resolve as lQ}from"path";import AQ from"process";import{existsSync as WX,mkdirSync as iY,readdirSync as sY,writeFileSync as oY}from"fs";import{homedir as IQ}from"os";import{dirname as aY,resolve as C}from"path";import t from"process";import{join as vX,relative as hX,resolve as nQ}from"path";import zQ from"process";import{existsSync as BX,mkdirSync as ZZ,readdirSync as $Z,writeFileSync as UZ}from"fs";import{dirname as JZ,resolve as WQ}from"path";import hQ from"process";import{Buffer as m}from"buffer";import{createCipheriv as dX,createDecipheriv as fX,randomBytes as MQ}from"crypto";import{closeSync as DQ,createReadStream as iQ,createWriteStream as pX,existsSync as TQ,fsyncSync as sQ,openSync as oQ,writeFileSync as mX}from"fs";import{access as uX,constants as rQ,mkdir as gX,readdir as QQ,rename as tQ,stat as g,unlink as XQ,writeFile as VQ}from"fs/promises";import{join as c}from"path";import V from"process";import{pipeline as cX}from"stream/promises";import{createGzip as aQ}from"zlib";import l from"process";import f from"process";import{Buffer as h}from"buffer";import{createCipheriv as lX,createDecipheriv as nX,randomBytes as NQ}from"crypto";import{closeSync as SQ,createReadStream as eQ,createWriteStream as iX,existsSync as YQ,fsyncSync as QX,openSync as XX,writeFileSync as sX}from"fs";import{access as oX,constants as YX,mkdir as rX,readdir as ZQ,rename as ZX,stat as n,unlink as $Q,writeFile as OQ}from"fs/promises";import{isAbsolute as tX,join as i,resolve as aX}from"path";import R from"process";import{pipeline as eX}from"stream/promises";import{createGzip as $X}from"zlib";import s from"process";import p from"process";import HQ from"process";import{existsSync as JQ}from"fs";import{resolve as PQ}from"path";import{existsSync as OY}from"fs";class AX{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),U=Z??this.options.ttl,H=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:U,hits:0,size:H}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!gQ(Q))return!0;return cQ(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=gQ(Y)?cQ(Y):null,U=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:U},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class zX{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let U=await X(),H=performance.now()-Z;return this.recordMetric({operation:Q,duration:H,timestamp:$,...Y}),U}catch(U){let H=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:H,timestamp:$,...Y}),U}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,U)=>$+U,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}var _Q=new AX,vQ=new zX;function dQ(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&F(X[0])&&"id"in X[0]&&X[0].id===3&&F(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(F(X)&&F(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(F(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&F(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&F(X[0])&&F(Q[0])){let Z=[...X];for(let $ of Q)if(F($)&&"name"in $){if(!Z.find((H)=>F(H)&&("name"in H)&&H.name===$.name))Z.push($)}else if(F($)&&"path"in $){if(!Z.find((H)=>F(H)&&("path"in H)&&H.path===$.path))Z.push($)}else if(!Z.some((U)=>BQ(U,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!F(X)||!F(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(F($)&&F(Y[Z]))Y[Z]=dQ(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&F($[0])&&F(Y[Z][0])){let U=[...$];for(let H of Y[Z])if(F(H)&&"name"in H){if(!U.find((J)=>F(J)&&("name"in J)&&J.name===H.name))U.push(H)}else if(F(H)&&"path"in H){if(!U.find((J)=>F(J)&&("path"in J)&&J.path===H.path))U.push(H)}else if(!U.some((q)=>BQ(q,H)))U.push(H);Y[Z]=U}else if($.every((U)=>typeof U==="string")&&Y[Z].every((U)=>typeof U==="string")){let U=[...$];for(let H of Y[Z])if(!U.includes(H))U.push(H);Y[Z]=U}else Y[Z]=$;else Y[Z]=$}return Y}function BQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!BQ(Q[Y],X[Y]))return!1;return!0}if(F(Q)&&F(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!BQ(Q[$],X[$]))return!1}return!0}return!1}function F(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function QY(Q,X){if(!BX(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 dQ(X,Z)}catch{return null}}catch{return null}}async function XY({name:Q="",cwd:X,defaultConfig:Y}){let Z=X||hQ.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],U=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let H of U)for(let q of $){let J=WQ(Z,`${H}${q}`),G=await QY(J,Y);if(G!==null)return G}try{let H=WQ(Z,"package.json");if(BX(H)){let J=(await import(H))[Q];if(J&&typeof J==="object"&&!Array.isArray(J))try{return dQ(Y,J)}catch{}}}catch{}return Y}var EZ=WQ(hQ.cwd(),"config"),CZ=WQ(hQ.cwd(),"src/generated");function YY(Q,X={}){let Y=zQ.cwd();while(Y.includes("storage"))Y=nQ(Y,"..");let Z=nQ(Y,Q||"");if(X?.relative)return hX(zQ.cwd(),Z);return Z}var ZY=zQ.env.CLARITY_LOG_DIR||vX(YY(),"logs"),EQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ZY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1};async function $Y(){try{let Q=await XY({name:"clarity",defaultConfig:EQ,cwd:zQ.cwd(),endpoint:"",headers:{}});return{...EQ,...Q}}catch{return EQ}}var UX=await $Y();function I(){if(f.env.NODE_ENV==="test"||f.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function UY(){if(f.env.NODE_ENV==="test"||f.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof f<"u"){let Q=f.type;if(Q==="renderer"||Q==="worker")return!1;return!!(f.versions&&(f.versions.node||f.versions.bun))}return!1}class RX{async format(Q){let X=await UY(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:l.pid,hostname:X(),environment:l.env.NODE_ENV||"development",platform:l.platform,version:l.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:l.env.NODE_ENV||l.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var E={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,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"},j=E,xZ=E.red,HY=E.green,kZ=E.yellow,JY=E.blue,PZ=E.magenta,bZ=E.cyan,HX=E.white,yZ=E.gray,qY=E.bgRed,GY=E.bgYellow,JX=E.bold,vZ=E.dim,hZ=E.italic,dZ=E.underline,fZ=E.reset,CQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},_Y={debug:"\uD83D\uDD0D",info:JY("\u2139"),success:HY("\u2713"),warning:GY(HX(JX(" WARN "))),error:qY(HX(JX(" ERROR ")))};class jQ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,X={}){this.name=Q,this.config={...UX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new RX,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??V.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),U=this.generateKey();this.currentKeyId=$,this.keys.set($,U),this.encryptionKeys.set($,{key:U,createdAt:new Date}),this.setupKeyRotation()}}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 X={format:"json",level:"info",logDirectory:UX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}async writeToFile(Q){let Y=(async()=>{let $,U=0,H=3,q=1000;while(U<H)try{try{try{await uX(this.config.logDirectory,rQ.F_OK|rQ.W_OK)}catch(G){if(G instanceof Error&&"code"in G)if(G.code==="ENOENT")await gX(this.config.logDirectory,{recursive:!0,mode:493});else if(G.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw G;else throw G}}catch(G){throw console.error("Debug: [writeToFile] Failed to create log directory:",G),G}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:m.from(Q);try{if(!TQ(this.currentLogFile))await VQ(this.currentLogFile,"",{mode:420});if($=oQ(this.currentLogFile,"a",420),mX($,J,{flag:"a"}),sQ($),$!==void 0)DQ($),$=void 0;if((await g(this.currentLogFile)).size===0){if(await VQ(this.currentLogFile,J,{flag:"w",mode:420}),(await g(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(G){let _=G;if(_.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(_.code)){if(U<H-1){let A=typeof _.message==="string"?_.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${H}:`,A);let W=q*2**U;await new Promise((z)=>setTimeout(z,W)),U++;continue}}if(_?.code&&["ENOSPC","EDQUOT"].includes(_.code))throw Error(`Disk quota exceeded or no space left on device: ${_.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",_),_}finally{if($!==void 0)try{DQ($)}catch(G){console.error("Debug: [writeToFile] Error closing file descriptor:",G)}}}catch(J){if(U===H-1){let _=J,A=typeof _.message==="string"?_.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}U++;let G=q*2**(U-1);await new Promise((_)=>setTimeout(_,G))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return c(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 c(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return c(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(I())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,q],[,J])=>J.createdAt.getTime()-q.createdAt.getTime()),U=typeof X.maxKeys==="number"?X.maxKeys:1,H=Math.max(1,U);if($.length>H)for(let[q]of $.slice(H))this.encryptionKeys.delete(q),this.keys.delete(q)}generateKeyId(){return MQ(16).toString("hex")}generateKey(){return MQ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=MQ(16),Z=dX("aes-256-gcm",X,Y),$=m.concat([Z.update(Q,"utf8"),Z.final()]),U=Z.getAuthTag();return{encrypted:m.concat([Y,$,U]),iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=aQ(),$=[];Z.on("data",(U)=>$.push(U)),Z.on("end",()=>X(m.from(m.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(I())return;let Q=await g(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await QQ(this.config.logDirectory),U=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,G)=>{let _=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(G.match(/\.log\.(\d+)$/)?.[1]||"0")-_}),H=U.length>0?Number.parseInt(U[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,q=`${Y}.${H}`;if(await g(Y).catch(()=>null))try{if(await tQ(Y,q),X.compress)try{let J=`${q}.gz`;await this.compressLogFile(q,J),await XQ(q)}catch(J){console.error("Error compressing rotated file:",J)}if(U.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await VQ(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),U=Y.replace(/\.log$/,`-${$}.log`);if(await g(Y).catch(()=>null))await tQ(Y,U)}if(this.currentLogFile=Z,X.maxFiles){let U=(await QQ(this.config.logDirectory)).filter((H)=>H.startsWith(this.name)).sort((H,q)=>q.localeCompare(H));for(let H of U.slice(X.maxFiles))await XQ(c(this.config.logDirectory,H))}}}async compressLogFile(Q,X){let Y=iQ(Q),Z=pX(X),$=aQ();await cX(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(X),console.log(X);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:Q,message:X,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),TQ(this.currentLogFile))try{let Q=oQ(this.currentLogFile,"r+");sQ(Q),DQ(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(!I()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await QQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await XQ(c(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?j.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:U,showTimestamp:H=!0}=Q,q=(z)=>z.replace(this.ANSI_PATTERN,"");if(!this.fancy){let z=[];if(H)z.push(X);if(U==="warning")z.push("WARN");else if(U==="error")z.push("ERROR");else if(Y)z.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)z.push(Z.replace(/[[\]]/g,""));return z.push($),z.join(" ")}let J=V.stdout.columns||120,G="";if(U==="warning"||U==="error")G=`${Y} ${$}`;else if(U==="info"||U==="success")G=`${Y} ${Z} ${$}`;else G=`${Y} ${Z} ${j.cyan($)}`;if(!H)return G.trim();let _=q(G).trim().length,A=q(X).length,W=Math.max(1,J-2-_-A);return`${G.trim()}${" ".repeat(W)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(U,H)=>{let q=Number.parseInt(H,10);return q<X[0].length?String(X[0][q]):U});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(U,H)=>{if(H==="%")return"%";if(Z>=X.length)return U;let q=X[Z++];switch(H){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 U}});if(Z<X.length)$+=` ${X.slice(Z).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`;return $}async log(Q,X,...Y){let Z=new Date,$=this.formatConsoleTimestamp(Z),U=this.formatFileTimestamp(Z),H,q;if(X instanceof Error)H=X.message,q=X.stack;else H=this.formatMessage(X,Y);if(this.fancy&&!I()){let G=_Y[Q],_=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:G,tag:_,message:j.gray(H),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:G,tag:_,message:H,level:Q}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:G,tag:_,message:j.green(H),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:G,tag:_,message:H,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:G,tag:_,message:H,level:Q}),console.error(A),q){let W=q.split(`
|
|
3
|
+
`);for(let z of W)if(z.trim()&&!z.includes(H))console.error(this.formatConsoleMessage({timestamp:$,message:j.gray(` ${z}`),level:Q,showTimestamp:!1}))}break}}else if(!I()){if(console.error(`${U} ${this.environment}.${Q.toUpperCase()}: ${H}`),q)console.error(q)}if(!this.shouldLog(Q))return;let J=`${U} ${this.environment}.${Q.toUpperCase()}: ${H}
|
|
4
|
+
`;if(q)J+=`${q}
|
|
5
|
+
`;J=J.replace(this.ANSI_PATTERN,""),await this.writeToFile(J)}time(Q){let X=performance.now();if(this.fancy&&!I()){let Y=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:j.blue("\u25D0"),tag:Y,message:`${j.cyan(Q)}...`}))}return async(Y)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-X),U=`${Q} completed in ${$}ms`,H=new Date,q=this.formatConsoleTimestamp(H),G=`${this.formatFileTimestamp(H)} ${this.environment}.INFO: ${U}`;if(Y)G+=` ${JSON.stringify(Y)}`;if(G+=`
|
|
6
|
+
`,G=G.replace(this.ANSI_PATTERN,""),this.fancy&&!I()){let _=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:q,icon:j.green("\u2713"),tag:_,message:`${U}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!I())console.error(G.trim());await this.writeToFile(G)}}async debug(Q,...X){await this.log("debug",Q,...X)}async info(Q,...X){await this.log("info",Q,...X)}async success(Q,...X){await this.log("success",Q,...X)}async warn(Q,...X){await this.log("warning",Q,...X)}async error(Q,...X){await this.log("error",Q,...X)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:X}=Q;return!!X}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let X=`${this.name}:${Q}`,Y=new jQ(X,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(I())throw Error("createReadStream is not supported in browser environments");if(!TQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return iQ(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let X=this.config.rotation;if(!X.encrypt||typeof X.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let Z=m.isBuffer(Q)?Q:m.from(Q,"base64"),$=Z.slice(0,16),U=Z.slice(-16),H=Z.slice(16,-16),q=fX("aes-256-gcm",Y,$);return q.setAuthTag(U),m.concat([q.update(H),q.final()]).toString("utf8")}catch(Z){throw Error(`Decryption failed: ${Z instanceof Error?Z.message:String(Z)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return I()}isServerMode(){return!I()}setTestEncryptionKey(Q,X){this.currentKeyId=Q,this.keys.set(Q,X)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(Q){if(!this.enabled)return;let X=new Date,Y=this.formatConsoleTimestamp(X),Z=this.formatFileTimestamp(X);if(this.fancy&&!I()){let U=Q.split(`
|
|
7
|
+
`),H=Math.max(...U.map((_)=>_.length))+2,q=`\u250C${"\u2500".repeat(H)}\u2510`,J=`\u2514${"\u2500".repeat(H)}\u2518`,G=U.map((_)=>{let A=" ".repeat(H-_.length-2);return`\u2502 ${_}${A} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:j.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:j.cyan(q)})),G.forEach((_)=>console.error(this.formatConsoleMessage({timestamp:Y,message:j.cyan(_),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:j.cyan(J),showTimestamp:!1}))}else if(!I())console.error(`${Z} ${this.environment}.INFO: [BOX] ${Q}`);let $=`${Z} ${this.environment}.INFO: [BOX] ${Q}
|
|
8
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile($)}async prompt(Q){if(I())return Promise.resolve(!0);return new Promise((X)=>{console.error(`${j.cyan("?")} ${Q} (y/n) `);let Y=(Z)=>{let $=Z.toString().trim().toLowerCase();V.stdin.removeListener("data",Y);try{if(typeof V.stdin.setRawMode==="function")V.stdin.setRawMode(!1)}catch{}V.stdin.pause(),console.error(""),X($==="y"||$==="yes")};try{if(typeof V.stdin.setRawMode==="function")V.stdin.setRawMode(!0)}catch{}V.stdin.resume(),V.stdin.once("data",Y)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...X){if(!this.enabled)return;let Y=Q;if(X&&X.length>0){let H=/%([sdijfo%])/g,q=0;if(Y=Q.replace(H,(J,G)=>{if(G==="%")return"%";if(q>=X.length)return J;let _=X[q++];switch(G){case"s":return String(_);case"d":case"i":return Number(_).toString();case"j":case"o":return JSON.stringify(_,null,2);default:return J}}),q<X.length)Y+=` ${X.slice(q).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`}if(this.fancy&&!I()){let H=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",q=j.blue("\u25D0");console.error(`${q} ${H} ${j.cyan(Y)}`)}let U=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
9
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}progress(Q,X=""){if(!this.enabled||!this.fancy||I()||Q<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:Q,current:0,message:X,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(H,q)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||I())return;if(this.activeProgressBar.current=Math.max(0,Math.min(Q,H)),q!==void 0)this.activeProgressBar.message=q;let J=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,J)},finish:(H)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||I())return;if(this.activeProgressBar.current=this.activeProgressBar.total,H!==void 0)this.activeProgressBar.message=H;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(H,q="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||I())return;V.stdout.write(`${"\r".padEnd(V.stdout.columns||80)}\r`),this.log(q,H),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(Q,X=!1){if(!this.enabled||!this.fancy||I()||!V.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*Y/100),$=Q.barLength-Z,U=j.green("\u2501".repeat(Z)),H=j.gray("\u2501".repeat($)),q=`[${U}${H}]`,J=`${Y}%`.padStart(4),G=Q.message?` ${Q.message}`:"",_=X||Y===100?j.green("\u2713"):j.blue("\u25B6"),A=this.options.showTags!==!1&&this.name?` ${j.gray(this.formatTag(this.name))}`:"",W=`\r${_}${A} ${q} ${J}${G}`,z=V.stdout.columns||80,D=" ".repeat(Math.max(0,z-W.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${W}${D}`,V.stdout.write(Q.lastRenderedLine),X)V.stdout.write(`
|
|
10
|
+
`)}finishProgressBar(Q,X){if(!this.enabled||!this.fancy||I()||!V.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(X)Q.message=X;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(I()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let X=await QQ(this.config.logDirectory),Y=[];for(let Z of X){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let U=c(this.config.logDirectory,Z);if(Q.before)try{if((await g(U)).mtime>=Q.before)continue}catch(H){console.error(`Failed to get stats for file ${U}:`,H);continue}Y.push(U)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let Z of Y)try{await XQ(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(X){console.error("Error during log clearing process:",X)}}}var pZ=new jQ("stacks");function GQ(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&w(X[0])&&"id"in X[0]&&X[0].id===3&&w(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(w(X)&&w(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(w(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&w(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&w(X[0])&&w(Q[0])){let Z=[...X];for(let $ of Q)if(w($)&&"name"in $){if(!Z.find((H)=>w(H)&&("name"in H)&&H.name===$.name))Z.push($)}else if(w($)&&"path"in $){if(!Z.find((H)=>w(H)&&("path"in H)&&H.path===$.path))Z.push($)}else if(!Z.some((U)=>RQ(U,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!w(X)||!w(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(w($)&&w(Y[Z]))Y[Z]=GQ(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&w($[0])&&w(Y[Z][0])){let U=[...$];for(let H of Y[Z])if(w(H)&&"name"in H){if(!U.find((J)=>w(J)&&("name"in J)&&J.name===H.name))U.push(H)}else if(w(H)&&"path"in H){if(!U.find((J)=>w(J)&&("path"in J)&&J.path===H.path))U.push(H)}else if(!U.some((q)=>RQ(q,H)))U.push(H);Y[Z]=U}else if($.every((U)=>typeof U==="string")&&Y[Z].every((U)=>typeof U==="string")){let U=[...$];for(let H of Y[Z])if(!U.includes(H))U.push(H);Y[Z]=U}else Y[Z]=$;else Y[Z]=$}return Y}function fQ(Q,X,Y="replace"){if(X===null||X===void 0)return Q;if(Array.isArray(X))return Y==="replace"?X:GQ(Q,X);if(Array.isArray(Q))return Y==="replace"?X:GQ(Q,X);if(!w(X)||!w(Q))return X;let Z={...Q};for(let $ of Object.keys(X)){if(!Object.prototype.hasOwnProperty.call(X,$))continue;let U=X[$],H=Z[$];if(U===null||U===void 0)continue;if(Array.isArray(U)||Array.isArray(H))if(Y==="replace")Z[$]=U;else Z[$]=GQ(H,U);else if(w(U)&&w(H))Z[$]=fQ(H,U,Y);else Z[$]=U}return Z}function RQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!RQ(Q[Y],X[Y]))return!1;return!0}if(w(Q)&&w(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!RQ(Q[$],X[$]))return!1}return!0}return!1}function w(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}var O=new jQ("bunfig",{showTags:!0});async function UQ(Q,X,Y="replace"){if(!WX(Q))return null;try{let Z=await import(Q),$=Z.default||Z;if(typeof $!=="object"||$===null||Array.isArray($))return null;try{return fQ(X,$,Y)}catch{return null}}catch{return null}}function AY(Q,X,Y=!1){if(!Q)return X;let Z=Q.toUpperCase().replace(/-/g,"_"),$={...X};function U(H,q=[]){let J={...H};for(let[G,_]of Object.entries(H)){let A=[...q,G],W=(B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase(),z=`${Z}_${A.map(W).join("_")}`,D=`${Z}_${A.map((B)=>B.toUpperCase()).join("_")}`;if(Y)O.info(`Checking environment variable ${z} for config ${Q}.${A.join(".")}`);if(typeof _==="object"&&_!==null&&!Array.isArray(_))J[G]=U(_,A);else{let B=t.env[z]||t.env[D];if(B!==void 0){if(Y)O.info(`Using environment variable ${B?z:D} for config ${Q}.${A.join(".")}`);if(typeof _==="number")J[G]=Number(B);else if(typeof _==="boolean")J[G]=B.toLowerCase()==="true";else if(Array.isArray(_))try{let K=JSON.parse(B);if(Array.isArray(K))J[G]=K;else J[G]=B.split(",").map((N)=>N.trim())}catch{J[G]=B.split(",").map((K)=>K.trim())}else J[G]=B}}}return J}return U($)}async function zY({name:Q="",alias:X,cwd:Y,configDir:Z,defaultConfig:$,verbose:U=!1,checkEnv:H=!0,arrayStrategy:q="replace"}){let J=H&&typeof $==="object"&&$!==null&&!Array.isArray($)?AY(Q,$,U):$,G=Y||t.cwd(),_=[".ts",".js",".mjs",".cjs",".json"];if(U)O.info(`Loading configuration for "${Q}"${X?` (alias: "${X}")`:""} from ${G}`);let A=[Q,`.${Q}`].filter(Boolean),W=[`${Q}.config`,`.${Q}.config`].filter(Boolean),z=X?[X,`.${X}`]:[],D=X?[`${X}.config`,`.${X}.config`]:[],B=Array.from(new Set([G,C(G,"config"),C(G,".config"),Z?C(G,Z):void 0].filter(Boolean)));for(let K of B){if(U)O.info(`Searching for configuration in: ${K}`);let S=[C(G,"config"),C(G,".config")].concat(Z?[C(G,Z)]:[]).includes(K)?[...A,...W,...z,...D]:[...W,...A,...D,...z];for(let v of S)for(let y of _){let P=C(K,`${v}${y}`),uQ=await UQ(P,J,q);if(uQ!==null){if(U)O.success(`Configuration loaded from: ${P}`);return uQ}}}if(Q){let K=C(IQ(),".config",Q),N=["config",`${Q}.config`];if(X)N.push(`${X}.config`);if(U)O.info(`Checking user config directory: ${K}`);for(let S of N)for(let v of _){let y=C(K,`${S}${v}`),P=await UQ(y,J,q);if(P!==null){if(U)O.success(`Configuration loaded from user config directory: ${y}`);return P}}}if(Q){let K=C(IQ(),".config"),N=[`.${Q}.config`];if(X)N.push(`.${X}.config`);if(U)O.info(`Checking user config directory for dotfile configs: ${K}`);for(let S of N)for(let v of _){let y=C(K,`${S}${v}`),P=await UQ(y,J,q);if(P!==null){if(U)O.success(`Configuration loaded from user config directory dotfile: ${y}`);return P}}}if(Q){let K=IQ(),N=[`.${Q}.config`,`.${Q}`];if(X)N.push(`.${X}.config`),N.push(`.${X}`);if(U)O.info(`Checking user home directory for dotfile configs: ${K}`);for(let S of N)for(let v of _){let y=C(K,`${S}${v}`),P=await UQ(y,J,q);if(P!==null){if(U)O.success(`Configuration loaded from user home directory: ${y}`);return P}}}try{let K=C(G,"package.json");if(WX(K)){let N=await import(K),S=N[Q];if(!S&&X){if(S=N[X],S&&U)O.success(`Using alias "${X}" configuration from package.json`)}if(S&&typeof S==="object"&&!Array.isArray(S))try{if(U)O.success(`Configuration loaded from package.json: ${S===N[Q]?Q:X}`);return fQ(J,S,q)}catch(v){if(U)O.warn("Failed to merge package.json config:",v)}}}catch(K){if(U)O.warn("Failed to load package.json:",K)}if(U)O.info(`No configuration found for "${Q}"${X?` or alias "${X}"`:""}, using default configuration with environment variables`);return J}var mZ=C(t.cwd(),"config"),uZ=C(t.cwd(),"src/generated");function WY(Q,X={}){let Y=AQ.cwd();while(Y.includes("storage"))Y=lQ(Y,"..");let Z=lQ(Y,Q||"");if(X?.relative)return yX(AQ.cwd(),Z);return Z}var BY=AQ.env.CLARITY_LOG_DIR||bX(WY(),"logs"),xQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:BY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1};async function RY(){try{let Q=await zY({name:"clarity",alias:"logging",defaultConfig:xQ,cwd:AQ.cwd()});return{...xQ,...Q||{}}}catch{return xQ}}var qX=await RY();function M(){if(p.env.NODE_ENV==="test"||p.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function LY(){if(p.env.NODE_ENV==="test"||p.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof p<"u"){let Q=p.type;if(Q==="renderer"||Q==="worker")return!1;return!!(p.versions&&(p.versions.node||p.versions.bun))}return!1}class LX{async format(Q){let X=await LY(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:s.pid,hostname:X(),environment:s.env.NODE_ENV||"development",platform:s.platform,version:s.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:s.env.NODE_ENV||s.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"},L=T,gZ=T.red,wY=T.green,cZ=T.yellow,KY=T.blue,lZ=T.magenta,nZ=T.cyan,GX=T.white,iZ=T.gray,jY=T.bgRed,FY=T.bgYellow,sZ=T.bgGray,_X=T.bold,oZ=T.dim,rZ=T.italic,tZ=T.underline,aZ=T.strikethrough,eZ=T.reset,kQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},IY={debug:"\uD83D\uDD0D",info:KY("\u2139"),success:wY("\u2713"),warning:FY(GX(_X(" WARN "))),error:jY(GX(_X(" ERROR ")))};class FQ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,X={}){this.name=Q,this.config={...qX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new LX,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??R.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),U=this.generateKey();this.currentKeyId=$,this.keys.set($,U),this.encryptionKeys.set($,{key:U,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;let X={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return X[Q]>=X[Y]}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...kQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...kQ};return{...kQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:qX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}shouldWriteToFile(){return!M()&&this.config.writeToFile===!0}async writeToFile(Q){let Y=(async()=>{let $,U=0,H=3,q=1000;while(U<H)try{try{try{await oX(this.config.logDirectory,YX.F_OK|YX.W_OK)}catch(G){if(G instanceof Error&&"code"in G)if(G.code==="ENOENT")await rX(this.config.logDirectory,{recursive:!0,mode:493});else if(G.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw G;else throw G}}catch(G){throw console.error("Debug: [writeToFile] Failed to create log directory:",G),G}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:h.from(Q);try{if(!YQ(this.currentLogFile))await OQ(this.currentLogFile,"",{mode:420});if($=XX(this.currentLogFile,"a",420),sX($,J,{flag:"a"}),QX($),$!==void 0)SQ($),$=void 0;if((await n(this.currentLogFile)).size===0){if(await OQ(this.currentLogFile,J,{flag:"w",mode:420}),(await n(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(G){let _=G;if(_.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(_.code)){if(U<H-1){let A=typeof _.message==="string"?_.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${H}:`,A);let W=q*2**U;await new Promise((z)=>setTimeout(z,W)),U++;continue}}if(_?.code&&["ENOSPC","EDQUOT"].includes(_.code))throw Error(`Disk quota exceeded or no space left on device: ${_.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",_),_}finally{if($!==void 0)try{SQ($)}catch(G){console.error("Debug: [writeToFile] Error closing file descriptor:",G)}}}catch(J){if(U===H-1){let _=J,A=typeof _.message==="string"?_.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}U++;let G=q*2**(U-1);await new Promise((_)=>setTimeout(_,G))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return i(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 i(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return i(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(M())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,q],[,J])=>J.createdAt.getTime()-q.createdAt.getTime()),U=typeof X.maxKeys==="number"?X.maxKeys:1,H=Math.max(1,U);if($.length>H)for(let[q]of $.slice(H))this.encryptionKeys.delete(q),this.keys.delete(q)}generateKeyId(){return NQ(16).toString("hex")}generateKey(){return NQ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=NQ(16),Z=lX("aes-256-gcm",X,Y),$=h.isBuffer(Q)?Q:h.from(Q,"utf8"),U=Z.update($),H=Z.final(),q=U.length+H.length,J=Z.getAuthTag(),G=h.allocUnsafe(16+q+16);return Y.copy(G,0),U.copy(G,16),H.copy(G,16+U.length),J.copy(G,16+q),{encrypted:G,iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=$X(),$=[];Z.on("data",(U)=>$.push(U)),Z.on("end",()=>X(h.from(h.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(M())return;if(!this.shouldWriteToFile())return;let Q=await n(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await ZQ(this.config.logDirectory),U=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,G)=>{let _=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(G.match(/\.log\.(\d+)$/)?.[1]||"0")-_}),H=U.length>0?Number.parseInt(U[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,q=`${Y}.${H}`;if(await n(Y).catch(()=>null))try{if(await ZX(Y,q),X.compress)try{let J=`${q}.gz`;await this.compressLogFile(q,J),await $Q(q)}catch(J){console.error("Error compressing rotated file:",J)}if(U.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await OQ(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),U=Y.replace(/\.log$/,`-${$}.log`);if(await n(Y).catch(()=>null))await ZX(Y,U)}if(this.currentLogFile=Z,X.maxFiles){let U=(await ZQ(this.config.logDirectory)).filter((H)=>H.startsWith(this.name)).sort((H,q)=>q.localeCompare(H));for(let H of U.slice(X.maxFiles))await $Q(i(this.config.logDirectory,H))}}}async compressLogFile(Q,X){let Y=eQ(Q),Z=iX(X),$=$X();await eX(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(X);console.log(X)}}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),YQ(this.currentLogFile))try{let Q=XX(this.currentLogFile,"r+");QX(Q),SQ(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(!M()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await ZQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await $Q(i(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.shouldStyleConsole()?L.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||M())return!1;let Q=typeof R.env.NO_COLOR<"u",X=R.env.FORCE_COLOR==="0";if(Q||X)return!1;return!!(typeof R.stderr<"u"&&R.stderr.isTTY||typeof R.stdout<"u"&&R.stdout.isTTY)}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:U,showTimestamp:H=!0}=Q,q=(z)=>z.replace(this.ANSI_PATTERN,"");if(!this.fancy){let z=[];if(H)z.push(X);if(U==="warning")z.push("WARN");else if(U==="error")z.push("ERROR");else if(Y)z.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)z.push(Z.replace(/[[\]]/g,""));return z.push($),z.join(" ")}let J=R.stdout.columns||120,G="";if(U==="warning"||U==="error")G=`${Y} ${$}`;else if(U==="info"||U==="success")G=`${Y} ${Z} ${$}`;else G=`${Y} ${Z} ${L.cyan($)}`;if(!H)return G.trim();let _=q(G).trim().length,A=q(X).length,W=Math.max(1,J-2-_-A);return`${G.trim()}${" ".repeat(W)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(U,H)=>{let q=Number.parseInt(H,10);return q<X[0].length?String(X[0][q]):U});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(U,H)=>{if(H==="%")return"%";if(Z>=X.length)return U;let q=X[Z++];switch(H){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 U}});if(Z<X.length)$+=` ${X.slice(Z).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`;return $}formatMarkdown(Q){if(!Q)return Q;let X=Q;return X=X.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,Z,$)=>{let U=L.underline(L.blue(Z)),H=this.toAbsoluteFilePath($);if(H&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let q=`file://${encodeURI(H)}`,J="\x1B]8;;",G="\x1B\\";return`\x1B]8;;${q}\x1B\\${U}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${$}\x1B\\${U}\x1B]8;;\x1B\\`;return U}),X=X.replace(/`([^`]+)`/g,(Y,Z)=>L.bgGray(Z)),X=X.replace(/\*\*([^*]+)\*\*/g,(Y,Z)=>L.bold(Z)),X=X.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,Z)=>L.italic(Z)),X=X.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,Z)=>L.italic(Z)),X=X.replace(/~([^~]+)~/g,(Y,Z)=>L.strikethrough(Z)),X}supportsHyperlinks(){if(M())return!1;let Q=R.env;if(!Q)return!1;if(Q.TERM_PROGRAM==="iTerm.app"||Q.TERM_PROGRAM==="vscode"||Q.TERM_PROGRAM==="WezTerm")return!0;if(Q.WT_SESSION)return!0;if(Q.TERM==="xterm-kitty")return!0;let X=Q.VTE_VERSION?Number.parseInt(Q.VTE_VERSION,10):0;if(!Number.isNaN(X)&&X>=5000)return!0;return!1}toAbsoluteFilePath(Q){try{let X=Q;if(X.startsWith("file://"))X=X.replace(/^file:\/\//,"");if(X.startsWith("~")){let Y=R.env.HOME||"";if(Y)X=X.replace(/^~(?=$|\/)/,Y)}if(tX(X)||X.startsWith("./")||X.startsWith("../"))X=aX(X);else return null;return YQ(X)?X:null}catch{return null}}buildOutputTexts(Q){let X=this.shouldStyleConsole()?this.formatMarkdown(Q):Q,Y=Q.replace(this.ANSI_PATTERN,"");return{consoleText:X,fileText:Y}}async log(Q,X,...Y){let Z=new Date,$=this.formatConsoleTimestamp(Z),U=this.formatFileTimestamp(Z),H,q;if(X instanceof Error)H=X.message,q=X.stack;else H=this.formatMessage(X,Y);let{consoleText:J,fileText:G}=this.buildOutputTexts(H);if(this.shouldStyleConsole()){let A=this.options.showIcons===!1?"":IY[Q],W=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",z;switch(Q){case"debug":z=this.formatConsoleMessage({timestamp:$,icon:A,tag:W,message:L.gray(J),level:Q}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:$,icon:A,tag:W,message:J,level:Q}),console.warn(z);break;case"success":z=this.formatConsoleMessage({timestamp:$,icon:A,tag:W,message:L.green(J),level:Q}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:$,icon:A,tag:W,message:J,level:Q}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:$,icon:A,tag:W,message:J,level:Q}),console.error(z),q){let D=q.split(`
|
|
11
|
+
`);for(let B of D)if(B.trim()&&!B.includes(H))console.error(this.formatConsoleMessage({timestamp:$,message:L.gray(` ${B}`),level:Q,showTimestamp:!1}))}break}}else if(!M()){if(console.error(`${U} ${this.environment}.${Q.toUpperCase()}: ${H}`),q)console.error(q)}if(!this.shouldLog(Q))return;let _=`${U} ${this.environment}.${Q.toUpperCase()}: ${G}
|
|
12
|
+
`;if(q)_+=`${q}
|
|
13
|
+
`;if(_=_.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(_)}progress(Q,X=""){let Y={update:(q,J)=>{},finish:(q)=>{},interrupt:(q,J)=>{}};if(!this.enabled)return Y;let Z=30;if(this.activeProgressBar={total:Math.max(1,Q||1),current:0,message:X||"",barLength:Z,lastRenderedLine:""},this.shouldStyleConsole()&&!M()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(q,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,q),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!M()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(q)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,q)},interrupt:(q,J="info")=>{if(!M()&&R.stdout.isTTY)R.stdout.write(`
|
|
14
|
+
`);if(this[J==="warning"?"warn":J](q),this.activeProgressBar&&this.shouldStyleConsole()&&!M()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Q){let X=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":L.blue("\u25D0"),tag:Y,message:`${L.cyan(Q)}...`}))}return async(Y)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-X),U=`${Q} completed in ${$}ms`,H=new Date,q=this.formatConsoleTimestamp(H),G=`${this.formatFileTimestamp(H)} ${this.environment}.INFO: ${U}`;if(Y)G+=` ${JSON.stringify(Y)}`;if(G+=`
|
|
15
|
+
`,G=G.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let _=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:q,icon:this.options.showIcons===!1?"":L.green("\u2713"),tag:_,message:`${U}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!M())console.error(G.trim());if(this.shouldWriteToFile())await this.writeToFile(G)}}async debug(Q,...X){await this.log("debug",Q,...X)}async info(Q,...X){await this.log("info",Q,...X)}async success(Q,...X){await this.log("success",Q,...X)}async warn(Q,...X){await this.log("warning",Q,...X)}async error(Q,...X){await this.log("error",Q,...X)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:X}=Q;return!!X}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let X=`${this.name}:${Q}`,Y=new FQ(X,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(M())throw Error("createReadStream is not supported in browser environments");if(!YQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return eQ(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let X=this.config.rotation;if(!X.encrypt||typeof X.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let Z=h.isBuffer(Q)?Q:h.from(Q,"base64"),$=Z.subarray(0,16),U=Z.subarray(Z.length-16),H=Z.subarray(16,Z.length-16),q=nX("aes-256-gcm",Y,$);q.setAuthTag(U);let J=q.update(H),G=q.final(),_=J.length+G.length,A=h.allocUnsafe(_);return J.copy(A,0),G.copy(A,J.length),A.toString("utf8")}catch(Z){throw Error(`Decryption failed: ${Z instanceof Error?Z.message:String(Z)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return M()}isServerMode(){return!M()}setTestEncryptionKey(Q,X){this.currentKeyId=Q,this.keys.set(Q,X)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(Q){if(!this.enabled)return;let X=new Date,Y=this.formatConsoleTimestamp(X),Z=this.formatFileTimestamp(X),{consoleText:$,fileText:U}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let q=$.split(`
|
|
16
|
+
`),J=Math.max(...q.map((W)=>W.length))+2,G=`\u250C${"\u2500".repeat(J)}\u2510`,_=`\u2514${"\u2500".repeat(J)}\u2518`,A=q.map((W)=>{return this.formatConsoleMessage({timestamp:Y,message:L.cyan(W),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:L.cyan(G),showTimestamp:!1})),A.forEach((W)=>console.error(W)),console.error(this.formatConsoleMessage({timestamp:Y,message:L.cyan(_),showTimestamp:!1}))}else if(!M())console.error(`${Z} ${this.environment}.INFO: [BOX] ${U}`);let H=`${Z} ${this.environment}.INFO: [BOX] ${U}
|
|
17
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(H)}async prompt(Q){if(M())return Promise.resolve(!0);return new Promise((X)=>{console.error(`${L.cyan("?")} ${Q} (y/n) `);let Y=(Z)=>{let $=Z.toString().trim().toLowerCase();R.stdin.removeListener("data",Y);try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!1)}catch{}R.stdin.pause(),console.error(""),X($==="y"||$==="yes")};try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!0)}catch{}R.stdin.resume(),R.stdin.once("data",Y)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...X){if(!this.enabled)return;let Y=Q;if(X&&X.length>0){let J=/%([sdijfo%])/g,G=0;if(Y=Q.replace(J,(_,A)=>{if(A==="%")return"%";if(G>=X.length)return _;let W=X[G++];switch(A){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return _}}),G<X.length)Y+=` ${X.slice(G).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`}let{consoleText:Z,fileText:$}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let J=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",G=this.options.showIcons===!1?"":`${L.blue("\u25D0")} `;console.error(`${G}${J} ${L.cyan(Z)}`)}let q=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${$}
|
|
18
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(q)}renderProgressBar(Q,X=!1){if(!this.enabled||!this.shouldStyleConsole()||!R.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*Y/100),$=Q.barLength-Z,U=L.green("\u2501".repeat(Z)),H=L.gray("\u2501".repeat($)),q=`[${U}${H}]`,J=`${Y}%`.padStart(4),G=Q.message?` ${Q.message}`:"",_=this.options.showIcons===!1?"":X||Y===100?L.green("\u2713"):L.blue("\u25B6"),A=this.options.showTags!==!1&&this.name?` ${L.gray(this.formatTag(this.name))}`:"",W=`\r${_}${A} ${q} ${J}${G}`,z=R.stdout.columns||80,D=" ".repeat(Math.max(0,z-W.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${W}${D}`,R.stdout.write(Q.lastRenderedLine),X)R.stdout.write(`
|
|
19
|
+
`)}finishProgressBar(Q,X){if(!this.enabled||!this.fancy||M()||!R.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(X)Q.message=X;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(M()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let X=await ZQ(this.config.logDirectory),Y=[];for(let Z of X){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let U=i(this.config.logDirectory,Z);if(Q.before)try{if((await n(U)).mtime>=Q.before)continue}catch(H){console.error(`Failed to get stats for file ${U}:`,H);continue}Y.push(U)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let Z of Y)try{await $Q(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(X){console.error("Error during log clearing process:",X)}}}var Q0=new FQ("stacks");class b extends Error{timestamp;context;constructor(Q,X={}){super(Q);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=X,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let Q=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([X,Y])=>`${X}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${Q}`}}class wX extends b{code="CONFIG_NOT_FOUND";constructor(Q,X,Y){let Z=Y?` or alias "${Y}"`:"";super(`Configuration "${Q}"${Z} not found`,{configName:Q,alias:Y,searchPaths:X,searchPathCount:X.length})}}class LQ extends b{code="CONFIG_LOAD_ERROR";constructor(Q,X,Y){super(`Failed to load configuration from "${Q}": ${X.message}`,{configPath:Q,configName:Y,originalError:X.name,originalMessage:X.message});this.cause=X}}class KX extends b{code="CONFIG_VALIDATION_ERROR";constructor(Q,X,Y){super(`Configuration validation failed for "${Q}"`,{configPath:Q,configName:Y,validationErrors:X,errorCount:X.length})}}class jX extends b{code="CONFIG_MERGE_ERROR";constructor(Q,X,Y,Z){super(`Failed to merge configuration from "${Q}" with "${X}": ${Y.message}`,{sourcePath:Q,targetPath:X,configName:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class pQ extends b{code="ENV_VAR_ERROR";constructor(Q,X,Y,Z){super(`Failed to parse environment variable "${Q}" with value "${X}" as ${Y}`,{envKey:Q,envValue:X,expectedType:Y,configName:Z})}}class FX extends b{code="FILE_SYSTEM_ERROR";constructor(Q,X,Y){super(`File system ${Q} failed for "${X}": ${Y.message}`,{operation:Q,path:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class IX extends b{code="TYPE_GENERATION_ERROR";constructor(Q,X,Y){super(`Failed to generate types from "${Q}" to "${X}": ${Y.message}`,{configDir:Q,outputPath:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class wQ extends b{code="SCHEMA_VALIDATION_ERROR";constructor(Q,X,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:Q,configName:Y,validationErrors:X,errorCount:X.length})}}class MX extends b{code="BROWSER_CONFIG_ERROR";constructor(Q,X,Y,Z){super(`Failed to fetch configuration from "${Q}": ${X} ${Y}`,{endpoint:Q,status:X,statusText:Y,configName:Z})}}class DX extends b{code="PLUGIN_ERROR";constructor(Q,X,Y){super(`Plugin "${Q}" failed during ${X}: ${Y.message}`,{pluginName:Q,operation:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}var o={configNotFound(Q,X,Y){return new wX(Q,X,Y)},configLoad(Q,X,Y){return new LQ(Q,X,Y)},configValidation(Q,X,Y){return new KX(Q,X,Y)},configMerge(Q,X,Y,Z){return new jX(Q,X,Y,Z)},envVar(Q,X,Y,Z){return new pQ(Q,X,Y,Z)},fileSystem(Q,X,Y){return new FX(Q,X,Y)},typeGeneration(Q,X,Y){return new IX(Q,X,Y)},schemaValidation(Q,X,Y){return new wQ(Q,X,Y)},browserConfig(Q,X,Y,Z){return new MX(Q,X,Y,Z)},plugin(Q,X,Y){return new DX(Q,X,Y)}};async function MY(Q,X={}){let{maxRetries:Y=3,retryDelay:Z=1000,isRetryable:$=()=>!0,fallback:U}=X,H=Error("Unknown error occurred");for(let q=0;q<=Y;q++)try{return await Q()}catch(J){if(H=J instanceof Error?J:Error(String(J)),q===Y||!$(H))break;if(Z>0)await new Promise((G)=>setTimeout(G,Z))}if(U!==void 0)return U;throw H instanceof Error?H:Error(`Unknown error: ${String(H)}`)}class mQ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(Q,X)=>X==="boolean"||["true","false","1","0","yes","no"].includes(Q.toLowerCase()),parse:(Q)=>{let X=Q.toLowerCase();return["true","1","yes"].includes(X)}},{name:"number",canParse:(Q,X)=>X==="number"||!Number.isNaN(Number(Q))&&!Number.isNaN(Number.parseFloat(Q)),parse:(Q)=>{let X=Number(Q);if(Number.isNaN(X))throw TypeError(`Cannot parse "${Q}" as number`);return X}},{name:"array",canParse:(Q,X)=>X==="array"||Q.startsWith("[")||Q.includes(","),parse:(Q)=>{try{let X=JSON.parse(Q);if(Array.isArray(X))return X}catch{}return Q.split(",").map((X)=>X.trim())}},{name:"json",canParse:(Q,X)=>X==="object"||(Q.startsWith("{")&&Q.endsWith("}")||Q.startsWith("[")&&Q.endsWith("]")),parse:(Q)=>{try{return JSON.parse(Q)}catch(X){throw Error(`Cannot parse "${Q}" as JSON: ${X}`)}}}]}async applyEnvironmentVariables(Q,X,Y={}){let{prefix:Z,useCamelCase:$=!0,useBackwardCompatibility:U=!0,customParsers:H={},verbose:q=!1,trackPerformance:J=!0}=Y,G=async()=>{if(!Q)return{config:X,source:{type:"environment",priority:50,timestamp:new Date}};let _=Z||this.generateEnvPrefix(Q),A={...X};return this.processObject(A,[],_,{useCamelCase:$,useBackwardCompatibility:U,customParsers:H,verbose:q,configName:Q}),{config:A,source:{type:"environment",priority:50,timestamp:new Date}}};if(J)return vQ.track("applyEnvironmentVariables",G,{configName:Q});return G()}generateEnvPrefix(Q){return Q.toUpperCase().replace(/-/g,"_")}formatEnvKey(Q,X){if(!X)return Q.toUpperCase();return Q.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(Q,X,Y,Z){for(let[$,U]of Object.entries(Q)){let H=[...X,$],q=H.map((_)=>this.formatEnvKey(_,Z.useCamelCase)),J=`${Y}_${q.join("_")}`,G=Z.useBackwardCompatibility?`${Y}_${H.map((_)=>_.toUpperCase()).join("_")}`:null;if(Z.verbose);if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.processObject(U,H,Y,Z);else{let _=HQ.env[J]||(G?HQ.env[G]:void 0);if(_!==void 0){if(Z.verbose){let A=HQ.env[J]?J:G}try{Q[$]=this.parseEnvironmentValue(_,typeof U,J,Z.customParsers,Z.configName)}catch(A){if(A instanceof pQ)throw A;throw o.envVar(J,_,typeof U,Z.configName)}}}}}parseEnvironmentValue(Q,X,Y,Z,$){for(let[U,H]of Object.entries(Z))try{return H(Q)}catch{continue}for(let U of this.defaultParsers)if(U.canParse(Q,X))try{return U.parse(Q)}catch{throw o.envVar(Y,Q,`${X} (via ${U.name} parser)`,$)}return Q}getEnvironmentVariables(Q){let X={},Y=Q.toUpperCase();for(let[Z,$]of Object.entries(HQ.env))if(Z.startsWith(Y)&&$!==void 0)X[Z]=$;return X}validateEnvironmentVariable(Q,X,Y){let Z=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(Q))Z.push(`Environment variable key "${Q}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(Q,X,Y,{})}catch($){Z.push(`Cannot parse value "${X}" as ${Y}: ${$}`)}return{isValid:Z.length===0,errors:Z}}generateEnvVarDocs(Q,X,Y={}){let{prefix:Z,format:$="text"}=Y,U=Z||this.generateEnvPrefix(Q),H=[];switch(this.extractEnvVarInfo(X,[],U,H),$){case"markdown":return this.formatAsMarkdown(H,Q);case"json":return JSON.stringify(H,null,2);default:return this.formatAsText(H,Q)}}extractEnvVarInfo(Q,X,Y,Z){for(let[$,U]of Object.entries(Q)){let H=[...X,$],q=`${Y}_${H.map((J)=>this.formatEnvKey(J,!0)).join("_")}`;if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.extractEnvVarInfo(U,H,Y,Z);else Z.push({key:q,type:Array.isArray(U)?"array":typeof U,description:`Configuration for ${H.join(".")}`,example:this.generateExample(U)})}}generateExample(Q){if(Array.isArray(Q))return JSON.stringify(Q);if(typeof Q==="object"&&Q!==null)return JSON.stringify(Q);return String(Q)}formatAsText(Q,X){let Y=`Environment Variables for ${X}:
|
|
20
|
+
|
|
21
|
+
`;for(let Z of Q)Y+=`${Z.key}
|
|
22
|
+
`,Y+=` Type: ${Z.type}
|
|
23
|
+
`,Y+=` Description: ${Z.description}
|
|
24
|
+
`,Y+=` Example: ${Z.example}
|
|
25
|
+
|
|
26
|
+
`;return Y}formatAsMarkdown(Q,X){let Y=`# Environment Variables for ${X}
|
|
27
|
+
|
|
28
|
+
`;Y+=`| Variable | Type | Description | Example |
|
|
29
|
+
`,Y+=`|----------|------|-------------|----------|
|
|
30
|
+
`;for(let Z of Q)Y+=`| \`${Z.key}\` | ${Z.type} | ${Z.description} | \`${Z.example}\` |
|
|
31
|
+
`;return Y}}function DY(Q,X,Y={}){return TX(Q,X,Y,new WeakMap)}function TX(Q,X,Y,Z){let{arrayMergeMode:$="replace",skipNullish:U=!1,customMerger:H}=Y;if(X===null||X===void 0)return U?Q:X;if(H){let q=H(Q,X);if(q!==void 0)return q}if(Array.isArray(X)||Array.isArray(Q))return VX(Q,X,$,Z);if(!k(X)||!k(Q))return X;return SY(Q,X,Y,Z)}function VX(Q,X,Y,Z){if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(Q)&&!Array.isArray(X))return X;if(Array.isArray(X)&&Array.isArray(Q))switch(Y){case"replace":return X;case"concat":return TY(Q,X);case"smart":return VY(Q,X,Z);default:return X}return X}function TY(Q,X){let Y=[...X];for(let Z of Q)if(!Y.some(($)=>yQ($,Z)))Y.push(Z);return Y}function VY(Q,X,Y){if(X.length===0)return Q;if(Q.length===0)return X;if(k(X[0])&&k(Q[0]))return NY(Q,X,Y);if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}function NY(Q,X,Y){let Z=[...X];for(let $ of Q){if(!k($)){Z.push($);continue}let U=["id","name","key","path","type"],H=!1;for(let q of U)if(q in $){if(Z.find((G)=>k(G)&&(q in G)&&G[q]===$[q])){H=!0;break}}if(!H)Z.push($)}return Z}function SY(Q,X,Y,Z){let $=X;if(k($)&&Z.has($))return Z.get($);let U={...Q};if(k($))Z.set($,U);for(let H in $){if(!Object.prototype.hasOwnProperty.call($,H))continue;let q=$[H],J=U[H];if(Y.skipNullish&&(q===null||q===void 0))continue;if(q===null||q===void 0){U[H]=q;continue}if(k(q)&&k(J))U[H]=TX(J,q,Y,Z);else if(Array.isArray(q)||Array.isArray(J))U[H]=VX(J,q,Y.arrayMergeMode||"smart",Z);else U[H]=q}return U}function NX(Q,X,Y="replace"){return DY(Q,X,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function yQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!yQ(Q[Y],X[Y]))return!1;return!0}if(k(Q)&&k(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!yQ(Q[$],X[$]))return!1}return!0}return!1}function k(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}class SX{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(Q,X,Y={}){let{arrayStrategy:Z="replace",useCache:$=!0,cacheTtl:U,trackPerformance:H=!0,verbose:q=!1}=Y;if($){let G=_Q.getWithFileCheck("file",Q);if(G){if(q)console.log(`Configuration loaded from cache: ${Q}`);return G}}let J=async()=>{if(!JQ(Q))return null;try{let G=`?t=${Date.now()}`,_=await import(Q+G),A=_.default||_,W="default"in _,z=Object.keys(_).length>0;if(!W&&!z)throw new LQ(Q,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof A!=="object"||A===null||Array.isArray(A))throw new LQ(Q,Error("Configuration must export a valid object"),"unknown");let K={config:NX(X,A,Z),source:{type:"file",path:Q,priority:100,timestamp:new Date}};if($)_Q.setWithFileCheck("file",K,Q,U);return K}catch(G){throw G instanceof Error?o.configLoad(Q,G):o.configLoad(Q,Error(String(G)))}};if(H)return vQ.track("loadFromPath",J,{path:Q});return J()}async tryLoadFromPaths(Q,X,Y={}){for(let Z of Q)try{let $=await this.loadFromPath(Z,X,Y);if($)return $}catch($){if($ instanceof Error&&$.name==="ConfigLoadError")throw $;if(Y.verbose)console.warn(`Failed to load config from ${Z}:`,$)}return null}generateConfigPaths(Q,X,Y){let Z=this.generateNamePatterns(Q,Y),$=[];for(let U of Z)for(let H of this.extensions)$.push(PQ(X,`${U}${H}`));return $}generateNamePatterns(Q,X){let Y=[];if(Y.push("config",".config"),Q)Y.push(Q,`.${Q}.config`,`${Q}.config`,`.${Q}`);if(X){if(Y.push(X,`.${X}.config`,`${X}.config`,`.${X}`),Q)Y.push(`${Q}.${X}.config`,`.${Q}.${X}.config`)}return Y.filter(Boolean)}checkFileAccess(Q){return MY(async()=>{return JQ(Q)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Q,X,Y){let Z=[];if(!JQ(Q))return Z;if(X||Y){let $=this.generateNamePatterns(X||"",Y);for(let U of $)for(let H of this.extensions){let q=PQ(Q,`${U}${H}`);if(await this.checkFileAccess(q))Z.push(q)}}else try{let{readdirSync:$}=await import("fs"),U=$(Q);for(let H of U)if(this.looksLikeConfigFile(H)){let q=PQ(Q,H);if(await this.checkFileAccess(q))Z.push(q)}}catch{return[]}return Z}looksLikeConfigFile(Q){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(Q))}async validateConfigFile(Q){let X=[];try{if(!JQ(Q))return X.push("Configuration file does not exist"),X;let Y=await import(Q),Z=Y.default||Y;if(Z===void 0)X.push("Configuration file must export a default value or named exports");else if(typeof Z!=="object"||Z===null)X.push("Configuration must be an object");else if(Array.isArray(Z))X.push("Configuration cannot be an array at the root level");if(Q.endsWith(".json"))try{let{readFileSync:$}=await import("fs"),U=$(Q,"utf8");JSON.parse(U)}catch($){X.push(`Invalid JSON syntax: ${$}`)}}catch(Y){X.push(`Failed to load configuration file: ${Y}`)}return X}async getFileModificationTime(Q){try{let{statSync:X}=await import("fs");return X(Q).mtime}catch{return null}}async preloadConfigurations(Q,X={}){let Y=new Map;return await Promise.allSettled(Q.map(async(Z)=>{try{let $=await this.loadFromPath(Z,{},X);if($)Y.set(Z,$.config)}catch($){if(X.verbose)console.warn(`Failed to preload ${Z}:`,$)}})),Y}}var EY=/^https?:\/\//;class OX{async validateConfiguration(Q,X,Y={}){let{stopOnFirstError:Z=!1,validateRequired:$=!0,validateTypes:U=!0,customRules:H=[],trackPerformance:q=!0,verbose:J=!1}=Y,G=async()=>{let _=[],A=[],W={stopOnFirstError:Z,validateRequired:$,validateTypes:U,customRules:H,trackPerformance:q,verbose:J};try{if(typeof X==="string")return await this.validateWithSchemaFile(Q,X,W);else if(Array.isArray(X))return this.validateWithRules(Q,[...X,...H],W);else return this.validateWithJSONSchema(Q,X,W)}catch(z){return _.push({path:"",message:`Validation failed: ${z}`,rule:"system"}),{isValid:!1,errors:_,warnings:A}}};if(q)return await vQ.track("validateConfiguration",G);return G()}async validateWithSchemaFile(Q,X,Y){try{if(!OY(X))throw new wQ(X,[{path:"",message:"Schema file does not exist"}]);let Z=await import(X),$=Z.default||Z;if(Array.isArray($))return this.validateWithRules(Q,$,Y);else return this.validateWithJSONSchema(Q,$,Y)}catch(Z){throw new wQ(X,[{path:"",message:`Failed to load schema: ${Z}`}])}}validateWithJSONSchema(Q,X,Y){let Z=[],$=[];return this.validateObjectAgainstSchema(Q,X,"",Z,$,Y),{isValid:Z.length===0,errors:Z,warnings:$}}validateObjectAgainstSchema(Q,X,Y,Z,$,U){if(U.validateTypes&&X.type){let H=Array.isArray(Q)?"array":typeof Q,q=Array.isArray(X.type)?X.type:[X.type];if(!q.includes(H)){if(Z.push({path:Y,message:`Expected type ${q.join(" or ")}, got ${H}`,expected:q.join(" or "),actual:H,rule:"type"}),U.stopOnFirstError)return}}if(X.enum&&!X.enum.includes(Q)){if(Z.push({path:Y,message:`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"}),U.stopOnFirstError)return}if(typeof Q==="string"){if(X.minLength!==void 0&&Q.length<X.minLength)Z.push({path:Y,message:`String length must be at least ${X.minLength}`,expected:`>= ${X.minLength}`,actual:Q.length,rule:"minLength"});if(X.maxLength!==void 0&&Q.length>X.maxLength)Z.push({path:Y,message:`String length must not exceed ${X.maxLength}`,expected:`<= ${X.maxLength}`,actual:Q.length,rule:"maxLength"});if(X.pattern){if(!new RegExp(X.pattern).test(Q))Z.push({path:Y,message:`String does not match pattern ${X.pattern}`,expected:X.pattern,actual:Q,rule:"pattern"})}}if(typeof Q==="number"){if(X.minimum!==void 0&&Q<X.minimum)Z.push({path:Y,message:`Value must be at least ${X.minimum}`,expected:`>= ${X.minimum}`,actual:Q,rule:"minimum"});if(X.maximum!==void 0&&Q>X.maximum)Z.push({path:Y,message:`Value must not exceed ${X.maximum}`,expected:`<= ${X.maximum}`,actual:Q,rule:"maximum"})}if(Array.isArray(Q)&&X.items)for(let H=0;H<Q.length;H++){let q=Y?`${Y}[${H}]`:`[${H}]`;if(this.validateObjectAgainstSchema(Q[H],X.items,q,Z,$,U),U.stopOnFirstError&&Z.length>0)return}if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let H=Q;if(U.validateRequired&&X.required){for(let q of X.required)if(!(q in H)){if(Z.push({path:Y?`${Y}.${q}`:q,message:`Missing required property '${q}'`,expected:"required",rule:"required"}),U.stopOnFirstError)return}}if(X.properties){for(let[q,J]of Object.entries(X.properties))if(q in H){let G=Y?`${Y}.${q}`:q;if(this.validateObjectAgainstSchema(H[q],J,G,Z,$,U),U.stopOnFirstError&&Z.length>0)return}}if(X.additionalProperties===!1){let q=new Set(Object.keys(X.properties||{}));for(let J of Object.keys(H))if(!q.has(J))$.push({path:Y?`${Y}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Q,X,Y){let Z=[],$=[];for(let U of X)try{let H=this.getValueByPath(Q,U.path),q=this.validateWithRule(H,U,U.path);if(Z.push(...q),Y.stopOnFirstError&&Z.length>0)break}catch(H){Z.push({path:U.path,message:`Rule validation failed: ${H}`,rule:"system"})}return{isValid:Z.length===0,errors:Z,warnings:$}}validateWithRule(Q,X,Y){let Z=[];if(X.required&&(Q===void 0||Q===null))return Z.push({path:Y,message:X.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),Z;if(Q===void 0||Q===null)return Z;if(X.type){let $=Array.isArray(Q)?"array":typeof Q;if($!==X.type)Z.push({path:Y,message:X.message||`Expected type ${X.type}, got ${$}`,expected:X.type,actual:$,rule:"type"})}if(X.min!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($<X.min)Z.push({path:Y,message:X.message||`Value must be at least ${X.min}`,expected:`>= ${X.min}`,actual:$,rule:"min"})}if(X.max!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($>X.max)Z.push({path:Y,message:X.message||`Value must not exceed ${X.max}`,expected:`<= ${X.max}`,actual:$,rule:"max"})}if(X.pattern&&typeof Q==="string"){if(!X.pattern.test(Q))Z.push({path:Y,message:X.message||`Value does not match pattern ${X.pattern}`,expected:X.pattern.toString(),actual:Q,rule:"pattern"})}if(X.enum&&!X.enum.includes(Q))Z.push({path:Y,message:X.message||`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"});if(X.validator){let $=X.validator(Q);if($)Z.push({path:Y,message:X.message||$,rule:"custom"})}return Z}getValueByPath(Q,X){if(!X)return Q;let Y=X.split("."),Z=Q;for(let $ of Y)if(Z&&typeof Z==="object"&&$ in Z)Z=Z[$];else return;return Z}generateRulesFromInterface(Q){let X=[],Y=Q.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Z of Y){let[,$,U,H]=Z;X.push({path:$,required:!U,type:this.mapTypeScriptType(H)})}return X}mapTypeScriptType(Q){switch(Q.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:EY},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var d=new FQ("bunfig",{showTags:!0});class EX{fileLoader=new SX;envProcessor=new mQ;validator=new OX;async loadConfig(Q){let X=Date.now(),{cache:Y,performance:Z,schema:$,validate:U,...H}=Q;try{if(Y?.enabled){let J=this.checkCache(H.name||"",H);if(J)return J}let q;try{q=await this.loadConfigurationStrategies(H,!0,Y)}catch(J){let G=H.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(G)throw J;q={...await this.applyEnvironmentVariables(H.name||"",H.defaultConfig,H.checkEnv!==!1,H.verbose||!1),warnings:[`No configuration file found for "${H.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let _=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),A=!_&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),W=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(G&&(W||_))throw J;if(A&&(!G||!W))q={...await this.applyEnvironmentVariables(H.name||"",H.defaultConfig,H.checkEnv!==!1,H.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!G)q={...await this.applyEnvironmentVariables(H.name||"",H.defaultConfig,H.checkEnv!==!1,H.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else q={...await this.applyEnvironmentVariables(H.name||"",H.defaultConfig,H.checkEnv!==!1,H.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if($||U)await this.validateConfiguration(q.config,$,U,H.name);if(Y?.enabled&&q)this.cacheResult(H.name||"",q,Y,H);if(Z?.enabled){let J={operation:"loadConfig",duration:Date.now()-X,configName:H.name,timestamp:new Date};if(Z.onMetrics)Z.onMetrics(J);if(Z.slowThreshold&&J.duration>Z.slowThreshold)d.warn(`Slow configuration loading detected: ${J.duration}ms for ${H.name}`);q.metrics=J}return q}catch(q){let J=Date.now()-X;throw d.error(`Configuration loading failed after ${J}ms:`,[q instanceof Error?q:Error(String(q))]),q}}async loadConfigurationStrategies(Q,X=!1,Y){let{name:Z="",alias:$,cwd:U,configDir:H,defaultConfig:q,checkEnv:J=!0,arrayStrategy:G="replace",verbose:_=!1}=Q,A=U||KQ.cwd(),W=[],z=await this.loadLocalConfiguration(Z,$,A,H,q,G,_,J,Y);if(z)return W.push(...this.getLocalSearchPaths(Z,$,A,H)),this.finalizeResult(z,W,J,Z,_);let D=await this.loadHomeConfiguration(Z,$,q,G,_,J);if(D)return W.push(...this.getHomeSearchPaths(Z,$)),this.finalizeResult(D,W,J,Z,_);let B=await this.loadPackageJsonConfiguration(Z,$,A,q,G,_,J);if(B)return W.push(x(A,"package.json")),this.finalizeResult(B,W,J,Z,_);if(W.push(...this.getAllSearchPaths(Z,$,A,H)),X)throw o.configNotFound(Z,W,$);return{...await this.applyEnvironmentVariables(Z,q,J,_),warnings:[`No configuration file found for "${Z}"${$?` or alias "${$}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(Q,X,Y,Z,$,U,H,q,J){let G=q?qQ(Q,$,H):$,_=this.getLocalDirectories(Y,Z);for(let A of _){if(H)d.info(`Searching for configuration in: ${A}`);let W=this.fileLoader.generateConfigPaths(Q,A,X),z=await this.fileLoader.tryLoadFromPaths(W,G,{arrayStrategy:U,verbose:H,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(z){if(H)d.success(`Configuration loaded from: ${z.source.path}`);return z}}return null}async loadHomeConfiguration(Q,X,Y,Z,$,U){if(!Q)return null;let H=U?qQ(Q,Y,$):Y,q=[x(u(),".config",Q),x(u(),".config"),u()];for(let J of q){if($)d.info(`Checking home directory: ${J}`);let G=this.fileLoader.generateConfigPaths(Q,J,X),_=await this.fileLoader.tryLoadFromPaths(G,H,{arrayStrategy:Z,verbose:$});if(_){if($)d.success(`Configuration loaded from home directory: ${_.source.path}`);return _}}return null}async loadPackageJsonConfiguration(Q,X,Y,Z,$,U,H){let q=H?qQ(Q,Z,U):Z;try{let J=x(Y,"package.json");if(!PX(J))return null;let G=await import(J),_=G[Q],A=Q;if(!_&&X)_=G[X],A=X;if(_&&typeof _==="object"&&!Array.isArray(_)){if(U)d.success(`Configuration loaded from package.json: ${A}`);return{config:NX(q,_,$),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(U)d.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables(Q,X,Y,Z){if(!Y||!Q||typeof X!=="object"||X===null||Array.isArray(X))return{config:X,source:{type:"default",priority:10,timestamp:new Date}};return{config:qQ(Q,X,Z),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(Q,X,Y,Z,$){return{config:Q.config,source:Q.source,path:Q.source.path}}async validateConfiguration(Q,X,Y,Z){let $=[];if(Y){let U=Y(Q);if(U)$.push(...U)}if(X){let U=await this.validator.validateConfiguration(Q,X);if(!U.isValid)$.push(...U.errors.map((H)=>H.path?`${H.path}: ${H.message}`:H.message))}if($.length>0)throw o.configValidation(Z||"unknown",$,Z)}checkCache(Q,X){let Y=this.generateCacheKey(Q,X);return _Q.get(Y)||null}cacheResult(Q,X,Y,Z){let $=this.generateCacheKey(Q,Z);_Q.set($,X,void 0,Y.ttl)}generateCacheKey(Q,X){let Y=[Q];if(X.alias)Y.push(`alias:${X.alias}`);if(X.cwd)Y.push(`cwd:${X.cwd}`);if(X.configDir)Y.push(`configDir:${X.configDir}`);if("checkEnv"in X)Y.push(`checkEnv:${X.checkEnv}`);return Y.join("|")}getLocalDirectories(Q,X){return Array.from(new Set([Q,x(Q,"config"),x(Q,".config"),X?x(Q,X):void 0].filter(Boolean)))}getAllSearchPaths(Q,X,Y,Z){let $=[];return $.push(...this.getLocalSearchPaths(Q,X,Y,Z)),$.push(...this.getHomeSearchPaths(Q,X)),$.push(x(Y,"package.json")),$}getLocalSearchPaths(Q,X,Y,Z){let $=this.getLocalDirectories(Y,Z),U=[];for(let H of $)U.push(...this.fileLoader.generateConfigPaths(Q,H,X));return U}getHomeSearchPaths(Q,X){if(!Q)return[];let Y=[x(u(),".config",Q),x(u(),".config"),u()],Z=[];for(let $ of Y)Z.push(...this.fileLoader.generateConfigPaths(Q,$,X));return Z}async loadConfigWithResult(Q){return this.loadConfig(Q)}}var bQ=new EX;async function CX(Q){let X="defaultConfig"in Q&&Q.defaultConfig!==void 0?Q.defaultConfig:{},Y="cache"in Q||"performance"in Q||"schema"in Q||"validate"in Q;try{let Z;if(Y)Z=await bQ.loadConfig(Q);else Z=await bQ.loadConfig({...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}});return Z?.config??X}catch(Z){let $=Z instanceof Error?Z.name:"UnknownError",U=Z instanceof Error?Z.message:String(Z);if(!($==="ConfigNotFoundError"||$==="ConfigLoadError"||$==="ConfigValidationError"||U.includes("config"))&&Q.verbose)d.warn("Unexpected error loading config, using defaults:",[Z instanceof Error?Z:Error(String(Z))]);let q=Y?{...Q,defaultConfig:X}:{...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Q?Q.checkEnv!==!1:!0)return(await bQ.applyEnvironmentVariables(q.name||"",X,!0,q.verbose||!1))?.config??X;return X}}function qQ(Q,X,Y=!1){let Z=new mQ,$=Q.toUpperCase().replace(/[^A-Z0-9]/g,"_");function U(H,q=[]){let J={...H};for(let[G,_]of Object.entries(H)){let A=[...q,G],W=[`${$}_${A.join("_").toUpperCase()}`,`${$}_${A.map((B)=>B.toUpperCase()).join("")}`,`${$}_${A.map((B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],z,D;for(let B of W)if(z=KQ.env[B],z!==void 0){D=B;break}if(z!==void 0&&D)if(typeof _==="boolean")J[G]=["true","1","yes"].includes(z.toLowerCase());else if(typeof _==="number"){let B=Number(z);if(!Number.isNaN(B))J[G]=B}else if(Array.isArray(_))try{J[G]=JSON.parse(z)}catch{J[G]=z.split(",").map((B)=>B.trim())}else J[G]=z;else if(_&&typeof _==="object"&&!Array.isArray(_))J[G]=U(_,A)}return J}return U(X)}var U0=x(KQ.cwd(),"config"),H0=x(KQ.cwd(),"src/generated");var e={cwd:kX.cwd(),root:"./src",entrypoints:["**/*.ts"],outdir:"./dist",keepComments:!0,clean:!0,tsconfigPath:"./tsconfig.json",outputStructure:"mirror",verbose:!1,importOrder:["bun"],declarationMap:!1},PY=["dtsx.config.ts","dtsx.config.js","dtsx.config.mjs","dtsx.config.mts","dts.config.ts","dts.config.js"];async function bY(Q=kX.cwd()){for(let X of PY){let Y=xY(Q,X);if(CY(Y))try{let $=await import(kY(Y).href),U=$.default||$.config||$,H=typeof U==="function"?await U():U;return{...e,...H,cwd:Q}}catch(Z){let $=Z instanceof Error?Z.message:String(Z);xX.warn(`Failed to load config from ${X}: ${$}`)}}return null}var a=null;async function B0(Q){if(!a){let X=await bY(Q);if(X)a=X;else a=await CX({name:"dts",defaultConfig:e})}return a}function R0(){a=null}function L0(Q){return{...e,...Q}}function w0(Q){return async()=>{let X=await Q();return{...e,...X}}}var K0=e;
|
|
32
|
+
export{e as Oc,B0 as Pc,R0 as Qc,L0 as Rc,w0 as Sc,K0 as Tc};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{ec as F}from"./chunk-9mjc7ddv.js";import{Bc as N}from"./chunk-j22v8wfe.js";import{existsSync as H,readFileSync as P,unwatchFile as T}from"fs";var k;((J)=>{J[J.Error=1]="Error";J[J.Warning=2]="Warning";J[J.Information=3]="Information";J[J.Hint=4]="Hint"})(k||={});var L;((O)=>{O[O.File=1]="File";O[O.Module=2]="Module";O[O.Namespace=3]="Namespace";O[O.Package=4]="Package";O[O.Class=5]="Class";O[O.Method=6]="Method";O[O.Property=7]="Property";O[O.Field=8]="Field";O[O.Constructor=9]="Constructor";O[O.Enum=10]="Enum";O[O.Interface=11]="Interface";O[O.Function=12]="Function";O[O.Variable=13]="Variable";O[O.Constant=14]="Constant";O[O.String=15]="String";O[O.Number=16]="Number";O[O.Boolean=17]="Boolean";O[O.Array=18]="Array";O[O.Object=19]="Object";O[O.Key=20]="Key";O[O.Null=21]="Null";O[O.EnumMember=22]="EnumMember";O[O.Struct=23]="Struct";O[O.Event=24]="Event";O[O.Operator=25]="Operator";O[O.TypeParameter=26]="TypeParameter"})(L||={});var M;((Q)=>{Q[Q.Text=1]="Text";Q[Q.Method=2]="Method";Q[Q.Function=3]="Function";Q[Q.Constructor=4]="Constructor";Q[Q.Field=5]="Field";Q[Q.Variable=6]="Variable";Q[Q.Class=7]="Class";Q[Q.Interface=8]="Interface";Q[Q.Module=9]="Module";Q[Q.Property=10]="Property";Q[Q.Unit=11]="Unit";Q[Q.Value=12]="Value";Q[Q.Enum=13]="Enum";Q[Q.Keyword=14]="Keyword";Q[Q.Snippet=15]="Snippet";Q[Q.Color=16]="Color";Q[Q.File=17]="File";Q[Q.Reference=18]="Reference";Q[Q.Folder=19]="Folder";Q[Q.EnumMember=20]="EnumMember";Q[Q.Constant=21]="Constant";Q[Q.Struct=22]="Struct";Q[Q.Event=23]="Event";Q[Q.Operator=24]="Operator";Q[Q.TypeParameter=25]="TypeParameter"})(M||={});var v;((A)=>{A[A.Text=1]="Text";A[A.Read=2]="Read";A[A.Write=3]="Write"})(v||={});class E{documents=new Map;rootUri=null;config={};messageId=0;watchers=new Map;initialize(j){return this.rootUri=j.rootUri,{capabilities:{textDocumentSync:1,hoverProvider:!0,completionProvider:{triggerCharacters:[".",":","<",'"',"'","/"],resolveProvider:!0},definitionProvider:!0,referencesProvider:!0,renameProvider:{prepareProvider:!0},documentSymbolProvider:!0,workspaceSymbolProvider:!0,codeActionProvider:{codeActionKinds:["quickfix","refactor","source"]},signatureHelpProvider:{triggerCharacters:["(",","],retriggerCharacters:[","]},documentHighlightProvider:!0,documentFormattingProvider:!0,diagnosticProvider:{interFileDependencies:!0,workspaceDiagnostics:!0}}}}didOpen(j){let{uri:z,text:G,version:A}=j.textDocument;this.updateDocument(z,G,A)}didChange(j){let{uri:z,version:G}=j.textDocument,A=j.contentChanges[0]?.text||"";this.updateDocument(z,A,G)}didClose(j){let z=j.textDocument.uri;if(this.documents.delete(z),this.watchers.get(z))T(this.uriToPath(z)),this.watchers.delete(z)}updateDocument(j,z,G){let A=this.uriToPath(j),J=F(z,A,!0);this.documents.set(j,{content:z,version:G,declarations:J})}getDiagnostics(j){let z=this.documents.get(j);if(!z)return[];let G=[];for(let A of z.declarations){if(A.isExported&&A.kind==="variable"&&!A.typeAnnotation)G.push({range:this.getDeclarationRange(A,z.content),severity:2,code:"missing-type",source:"dtsx",message:`Exported variable '${A.name}' should have an explicit type annotation for better declaration generation`});if(A.typeAnnotation==="any"||A.returnType==="any")G.push({range:this.getDeclarationRange(A,z.content),severity:3,code:"any-type",source:"dtsx",message:"Consider using a more specific type instead of 'any'"});if(A.kind==="function"&&A.isExported&&!A.returnType)G.push({range:this.getDeclarationRange(A,z.content),severity:3,code:"missing-return-type",source:"dtsx",message:`Function '${A.name}' should have an explicit return type for better declaration generation`})}return G}hover(j){let z=this.documents.get(j.textDocument.uri);if(!z)return null;let{line:G,character:A}=j.position,R=z.content.split(`
|
|
3
|
+
`)[G]||"",U=R.slice(0,A).match(/[\w$]+$/),V=R.slice(A).match(/^[\w$]+/);if(!U&&!V)return null;let X=(U?.[0]||"")+(V?.[0]||""),Y=z.declarations.find((W)=>W.name===X);if(!Y)return null;let B=`\`\`\`typescript
|
|
4
|
+
${this.buildSignature(Y)}
|
|
5
|
+
\`\`\``;if(Y.leadingComments&&Y.leadingComments.length>0){let q=Y.leadingComments.join(`
|
|
6
|
+
`).match(/\*\s*([^@*][^*]*)/);if(q)B+=`
|
|
7
|
+
|
|
8
|
+
${q[1].trim()}`}return{contents:{kind:"markdown",value:B}}}completion(j){let z=this.documents.get(j.textDocument.uri);if(!z)return[];let G=[];for(let A of z.declarations){if(!A.isExported)continue;let J=6;switch(A.kind){case"function":J=3;break;case"class":J=7;break;case"interface":J=8;break;case"type":J=8;break;case"enum":J=13;break}G.push({label:A.name,kind:J,detail:this.buildSignature(A)})}return G}definition(j){let z=this.documents.get(j.textDocument.uri);if(!z)return null;let{line:G,character:A}=j.position,R=z.content.split(`
|
|
9
|
+
`)[G]||"",U=R.slice(0,A).match(/[\w$]+$/),V=R.slice(A).match(/^[\w$]+/);if(!U&&!V)return null;let X=(U?.[0]||"")+(V?.[0]||""),Y=z.declarations.find(($)=>$.name===X);if(!Y)return null;return{uri:j.textDocument.uri,range:this.getDeclarationRange(Y,z.content)}}references(j){let z=[],G=this.getWordAtPosition(j.textDocument.uri,j.position);if(!G)return z;for(let[A,J]of this.documents){let R=J.content.split(`
|
|
10
|
+
`);for(let U=0;U<R.length;U++){let V=R[U],X=0;while(X<V.length){let Y=V.indexOf(G,X);if(Y===-1)break;let $=Y>0?V[Y-1]:" ",B=Y+G.length<V.length?V[Y+G.length]:" ";if(!/[\w$]/.test($)&&!/[\w$]/.test(B))z.push({uri:A,range:{start:{line:U,character:Y},end:{line:U,character:Y+G.length}}});X=Y+1}}}return z}prepareRename(j){let z=this.getWordAtPosition(j.textDocument.uri,j.position);if(!z)return null;let G=this.documents.get(j.textDocument.uri);if(!G)return null;let A=G.declarations.find((R)=>R.name===z);if(!A)return null;return{range:this.getDeclarationRange(A,G.content),placeholder:z}}rename(j){if(!this.getWordAtPosition(j.textDocument.uri,j.position))return null;let G=this.references({textDocument:j.textDocument,position:j.position,context:{includeDeclaration:!0}});if(G.length===0)return null;let A={};for(let J of G){if(!A[J.uri])A[J.uri]=[];A[J.uri].push({range:J.range,newText:j.newName})}return{changes:A}}documentSymbols(j){let z=this.documents.get(j.textDocument.uri);if(!z)return[];let G=[];for(let A of z.declarations){let J=this.getDeclarationRange(A,z.content),R=this.declarationKindToSymbolKind(A.kind),U={name:A.name,detail:this.buildSignature(A),kind:R,range:J,selectionRange:J};if(A.members&&A.members.length>0)U.children=A.members.map((V)=>({name:V.name,kind:this.declarationKindToSymbolKind(V.kind),range:this.getDeclarationRange(V,z.content),selectionRange:this.getDeclarationRange(V,z.content)}));G.push(U)}return G}workspaceSymbols(j){let z=[],G=j.query.toLowerCase();for(let[A,J]of this.documents)for(let R of J.declarations){if(!R.isExported)continue;if(G&&!R.name.toLowerCase().includes(G))continue;z.push({name:R.name,kind:this.declarationKindToSymbolKind(R.kind),location:{uri:A,range:this.getDeclarationRange(R,J.content)}})}return z}codeActions(j){let z=[];if(!this.documents.get(j.textDocument.uri))return z;for(let J of j.context.diagnostics){if(J.code==="missing-type"){let R=this.getWordAtRange(j.textDocument.uri,J.range);if(R)z.push({title:`Add type annotation to '${R}'`,kind:"quickfix",diagnostics:[J],edit:{changes:{[j.textDocument.uri]:[{range:{start:J.range.end,end:J.range.end},newText:": unknown"}]}}})}if(J.code==="any-type")z.push({title:"Replace 'any' with 'unknown'",kind:"quickfix",diagnostics:[J],isPreferred:!0,edit:{changes:{[j.textDocument.uri]:[{range:J.range,newText:"unknown"}]}}});if(J.code==="missing-return-type"){let R=this.getWordAtRange(j.textDocument.uri,J.range);if(R)z.push({title:`Add return type to '${R}'`,kind:"quickfix",diagnostics:[J]})}}let A=this.getDeclarationAtPosition(j.textDocument.uri,j.range.start);if(A){if(A.kind==="function")z.push({title:"Extract function signature to type",kind:"refactor.extract"});if(A.kind==="interface"||A.kind==="type")z.push({title:"Generate runtime validator",kind:"source"})}return z}signatureHelp(j){let z=this.documents.get(j.textDocument.uri);if(!z)return null;let{line:G,character:A}=j.position,R=z.content.split(`
|
|
11
|
+
`)[G]||"",U=0,V=-1,X=0;for(let Z=A-1;Z>=0;Z--){let _=R[Z];if(_===")")U++;else if(_==="("){if(U===0){V=Z;break}U--}else if(_===","&&U===0)X++}if(V===-1)return null;let $=R.slice(0,V).trimEnd().match(/[\w$]+$/);if(!$)return null;let B=$[0],W=z.declarations.find((Z)=>Z.name===B&&Z.kind==="function");if(!W||!W.parameters)return null;let q=W.parameters.map((Z)=>{let _="";if(Z.rest)_+="...";if(_+=Z.name,Z.optional)_+="?";if(Z.type)_+=`: ${Z.type}`;return _});return{signatures:[{label:`${B}(${q.join(", ")}): ${W.returnType||"void"}`,parameters:W.parameters.map((Z)=>({label:Z.name,documentation:Z.type?`Type: ${Z.type}`:void 0}))}],activeSignature:0,activeParameter:Math.min(X,W.parameters.length-1)}}documentHighlight(j){let z=[],G=this.getWordAtPosition(j.textDocument.uri,j.position);if(!G)return z;let A=this.documents.get(j.textDocument.uri);if(!A)return z;let J=A.content.split(`
|
|
12
|
+
`);for(let R=0;R<J.length;R++){let U=J[R],V=0;while(V<U.length){let X=U.indexOf(G,V);if(X===-1)break;let Y=X>0?U[X-1]:" ",$=X+G.length<U.length?U[X+G.length]:" ";if(!/[\w$]/.test(Y)&&!/[\w$]/.test($)){let B=/^\s*[=:]/.test(U.slice(X+G.length))||/^(const|let|var|function|class|interface|type|enum)\s+$/.test(U.slice(0,X));z.push({range:{start:{line:R,character:X},end:{line:R,character:X+G.length}},kind:B?3:2})}V=X+1}}return z}async formatting(j){let z=this.documents.get(j.textDocument.uri);if(!z)return[];let G=this.generateDts(j.textDocument.uri);if(!G)return[];let A=z.content.split(`
|
|
13
|
+
`);return[{range:{start:{line:0,character:0},end:{line:A.length-1,character:A[A.length-1].length}},newText:G}]}getWordAtPosition(j,z){let G=this.documents.get(j);if(!G)return null;let J=G.content.split(`
|
|
14
|
+
`)[z.line]||"",R=J.slice(0,z.character).match(/[\w$]+$/),U=J.slice(z.character).match(/^[\w$]+/);if(!R&&!U)return null;return(R?.[0]||"")+(U?.[0]||"")}getWordAtRange(j,z){let G=this.documents.get(j);if(!G)return null;let A=G.content.split(`
|
|
15
|
+
`);if(z.start.line===z.end.line)return A[z.start.line]?.slice(z.start.character,z.end.character)||null;return null}getDeclarationAtPosition(j,z){let G=this.documents.get(j);if(!G)return null;for(let A of G.declarations){let J=this.getDeclarationRange(A,G.content);if(this.positionInRange(z,J))return A}return null}positionInRange(j,z){if(j.line<z.start.line||j.line>z.end.line)return!1;if(j.line===z.start.line&&j.character<z.start.character)return!1;if(j.line===z.end.line&&j.character>z.end.character)return!1;return!0}declarationKindToSymbolKind(j){switch(j){case"function":return 12;case"class":return 5;case"interface":return 11;case"type":return 11;case"enum":return 10;case"variable":return 13;case"const":return 14;case"property":return 7;case"method":return 6;case"module":return 2;case"namespace":return 3;default:return 13}}generateDts(j){let z=this.documents.get(j);if(!z)return null;let G={filePath:this.uriToPath(j),sourceCode:z.content,declarations:z.declarations};return N(z.declarations,G,!0,this.config.importOrder)}buildSignature(j){switch(j.kind){case"function":{let z=j.parameters?.map((J)=>{let R="";if(J.rest)R+="...";if(R+=J.name,J.optional)R+="?";if(J.type)R+=`: ${J.type}`;return R}).join(", ")||"",G=j.generics||"",A=j.returnType?`: ${j.returnType}`:"";return`function ${j.name}${G}(${z})${A}`}case"variable":return`const ${j.name}: ${j.typeAnnotation||"unknown"}`;case"interface":return`interface ${j.name}${j.generics||""}${j.extends?` extends ${j.extends}`:""}`;case"type":return`type ${j.name}${j.generics||""} = ${j.typeAnnotation||"unknown"}`;case"class":return`class ${j.name}${j.generics||""}${j.extends?` extends ${j.extends}`:""}`;case"enum":return`enum ${j.name}`;default:return j.name}}getDeclarationRange(j,z){if(j.start!==void 0&&j.end!==void 0)return{start:this.offsetToPosition(j.start,z),end:this.offsetToPosition(j.end,z)};let G=z.split(`
|
|
16
|
+
`);for(let A=0;A<G.length;A++){let J=G[A].indexOf(j.name);if(J!==-1)return{start:{line:A,character:J},end:{line:A,character:J+j.name.length}}}return{start:{line:0,character:0},end:{line:0,character:0}}}offsetToPosition(j,z){let G=0,A=0;for(let J=0;J<j&&J<z.length;J++)if(z[J]===`
|
|
17
|
+
`)G++,A=0;else A++;return{line:G,character:A}}uriToPath(j){if(j.startsWith("file://"))return decodeURIComponent(j.slice(7));return j}pathToUri(j){return`file://${encodeURIComponent(j).replace(/%2F/g,"/")}`}handleMessage(j){if(j.method==="initialize")return{jsonrpc:"2.0",id:j.id,result:this.initialize(j.params)};if(j.method==="initialized")return null;if(j.method==="shutdown")return{jsonrpc:"2.0",id:j.id,result:null};if(j.method==="exit")process.exit(0);let z=j.params;if(j.method==="textDocument/didOpen")return this.didOpen(z),null;if(j.method==="textDocument/didChange")return this.didChange(z),null;if(j.method==="textDocument/didClose")return this.didClose(z),null;if(j.method==="textDocument/hover")return{jsonrpc:"2.0",id:j.id,result:this.hover(z)};if(j.method==="textDocument/completion")return{jsonrpc:"2.0",id:j.id,result:this.completion(z)};if(j.method==="textDocument/definition")return{jsonrpc:"2.0",id:j.id,result:this.definition(z)};if(j.method==="textDocument/references")return{jsonrpc:"2.0",id:j.id,result:this.references(z)};if(j.method==="textDocument/prepareRename")return{jsonrpc:"2.0",id:j.id,result:this.prepareRename(z)};if(j.method==="textDocument/rename")return{jsonrpc:"2.0",id:j.id,result:this.rename(z)};if(j.method==="textDocument/documentSymbol")return{jsonrpc:"2.0",id:j.id,result:this.documentSymbols(z)};if(j.method==="workspace/symbol")return{jsonrpc:"2.0",id:j.id,result:this.workspaceSymbols(z)};if(j.method==="textDocument/codeAction")return{jsonrpc:"2.0",id:j.id,result:this.codeActions(z)};if(j.method==="textDocument/signatureHelp")return{jsonrpc:"2.0",id:j.id,result:this.signatureHelp(z)};if(j.method==="textDocument/documentHighlight")return{jsonrpc:"2.0",id:j.id,result:this.documentHighlight(z)};if(j.method==="textDocument/formatting")return{jsonrpc:"2.0",id:j.id,result:this.formatting(z)};if(j.method==="textDocument/diagnostic"){let G=z?.textDocument?.uri;return{jsonrpc:"2.0",id:j.id,result:{kind:"full",items:G?this.getDiagnostics(G):[]}}}if(j.id!==void 0)return{jsonrpc:"2.0",id:j.id,error:{code:-32601,message:`Method not found: ${j.method}`}};return null}}function C(){let j=new E,z="";process.stdin.setEncoding("utf8"),process.stdin.on("data",(G)=>{z+=G;while(!0){let A=z.indexOf(`\r
|
|
18
|
+
\r
|
|
19
|
+
`);if(A===-1)break;let R=z.slice(0,A).match(/Content-Length:\s*(\d+)/i);if(!R){z=z.slice(A+4);continue}let U=Number.parseInt(R[1],10),V=A+4,X=V+U;if(z.length<X)break;let Y=z.slice(V,X);z=z.slice(X);try{let $=JSON.parse(Y),B=j.handleMessage($);if(B){let W=JSON.stringify(B),q=Buffer.byteLength(W,"utf8");process.stdout.write(`Content-Length: ${q}\r
|
|
20
|
+
\r
|
|
21
|
+
${W}`)}}catch($){console.error("Error parsing LSP message:",$)}}})}function f(j,z){return(G)=>{if(!H(G))return;let A=P(G,"utf-8"),J=`file://${G}`;j.didOpen({textDocument:{uri:J,languageId:"typescript",version:1,text:A}});let R=j.getDiagnostics(J);z(J,R)}}
|
|
22
|
+
export{k as s,L as t,M as u,v,E as w,C as x,f as y};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{tb as z}from"./chunk-3mxzfgcv.js";function C(F={}){let{preBuild:H=!1,postBuild:I=!0,onGenerated:J,onError:w,...q}=F,y=async()=>{try{let j=await z(q);J?.(j)}catch(j){let k=j instanceof Error?j:Error(String(j));if(w?.(k),!w)console.error("[dtsx] Generation failed:",k.message)}};return{name:"dtsx",async setup(j){let k=j.config;if(!q.entrypoints&&k.entrypoints)q.entrypoints=k.entrypoints;if(!q.outdir&&k.outdir)q.outdir=k.outdir;if(!q.root&&k.root)q.root=k.root;if(H)j.onStart(async()=>{await y()});if(I){let v=!1;j.onLoad({filter:/.*/},async(K)=>{if(!v)queueMicrotask(async()=>{if(!v)v=!0,await y()});return})}}}}var M=C,P=C;
|
|
3
|
+
export{C as fa,M as ga,P as ha};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{ec as $}from"./chunk-9mjc7ddv.js";import{existsSync as U,readFileSync as O,writeFileSync as q}from"fs";function _(G){let j=[],H=/\b([A-Z][a-zA-Z0-9]*)\b/g,L;while((L=H.exec(G))!==null){let J=L[1];if(!N(J))j.push(J)}return[...new Set(j)]}function N(G){return new Set(["Array","Object","String","Number","Boolean","Symbol","BigInt","Function","Promise","Map","Set","WeakMap","WeakSet","Date","RegExp","Error","TypeError","RangeError","SyntaxError","Partial","Required","Readonly","Pick","Omit","Record","Exclude","Extract","NonNullable","ReturnType","Parameters","ConstructorParameters","InstanceType","ThisType","Uppercase","Lowercase","Capitalize","Uncapitalize","Awaited","NoInfer","Generator","AsyncGenerator","IterableIterator","AsyncIterableIterator","PropertyKey","Iterable","AsyncIterable","ArrayLike","PromiseLike","ArrayBuffer","SharedArrayBuffer","DataView","Int8Array","Uint8Array","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"]).has(G)}function C(G){if(G.kind!=="type")return!1;let j=G.typeAnnotation||"";if(G.generics)return!1;if(j.includes("{")||j.includes("(")||j.includes("<"))return!1;return/^[\w\s|&]+$/.test(j)}function E(G){if(G.kind!=="interface")return!1;if(!G.members||G.members.length===0){if(!G.extends)return!0}return!1}function F(G,j){let H={...G,members:[...G.members||[],...j.members||[]],leadingComments:[...G.leadingComments||[],...j.leadingComments||[]]};if(G.extends&&j.extends){let L=G.extends.split(",").map((K)=>K.trim()),J=j.extends.split(",").map((K)=>K.trim());H.extends=[...new Set([...L,...J])].join(", ")}else H.extends=G.extends||j.extends;return H}function D(G){let j=["import","interface","type","class","enum","function","variable","export"];return[...G].sort((H,L)=>{let J=j.indexOf(H.kind)-j.indexOf(L.kind);if(J!==0)return J;return H.name.localeCompare(L.name)})}function R(G){let j=G.filter((J)=>J.kind==="import"),H=G.filter((J)=>J.kind!=="import");return[...[...j].sort((J,K)=>{let M=J.source||"",Q=K.source||"",V=M.startsWith("node:")||M==="bun",W=Q.startsWith("node:")||Q==="bun";if(V&&!W)return-1;if(!V&&W)return 1;let Y=!M.startsWith("."),X=!Q.startsWith(".");if(Y&&!X)return-1;if(!Y&&X)return 1;return M.localeCompare(Q)}),...H]}function k(G){let j=new Set;for(let J of G){if(J.kind==="import")continue;let K=J.text||"",M=J.typeAnnotation||"",Q=J.returnType||"",V=J.extends||"",W=J.implements?.join(" ")||"",Y=`${K} ${M} ${Q} ${V} ${W}`;for(let X of _(Y))j.add(X);if(J.members)for(let X of J.members){let Z=`${X.typeAnnotation||""} ${X.returnType||""}`;for(let w of _(Z))j.add(w)}if(J.parameters){for(let X of J.parameters)if(X.type)for(let Z of _(X.type))j.add(Z)}}let H=0;return{declarations:G.map((J)=>{if(J.kind!=="import"||!J.specifiers)return J;let K=J.specifiers.filter((M)=>{let Q=M.alias||M.name;return j.has(Q)});if(K.length===0){if(!J.isSideEffect)return H++,null}if(K.length<(J.specifiers?.length||0))return H+=(J.specifiers?.length||0)-K.length,{...J,specifiers:K};return J}).filter((J)=>J!==null),removed:H}}function A(G){let j=new Map,H=0;for(let L of G){if(L.kind==="import"){let K=`import:${L.source}`;if(j.has(K)){let M=j.get(K),Q=[...M.specifiers||[],...L.specifiers||[]],V=Array.from(new Map(Q.map((W)=>[W.alias||W.name,W])).values());j.set(K,{...M,specifiers:V}),H++}else j.set(K,L);continue}let J=`${L.kind}:${L.name}`;if(j.has(J))H++;else j.set(J,L)}return{declarations:Array.from(j.values()),removed:H}}function z(G){let j=new Map,H=[];for(let K of G)if(K.kind==="interface"){let M=K.name;if(!j.has(M))j.set(M,[]);j.get(M).push(K)}else H.push(K);let L=0,J=[];for(let[K,M]of j)if(M.length>1){let Q=M[0];for(let V=1;V<M.length;V++)Q=F(Q,M[V]),L++;J.push(Q)}else J.push(M[0]);return{declarations:[...H,...J],merged:L}}function P(G){let j=new Map,H=new Set;for(let K of G)if(C(K))j.set(K.name,K.typeAnnotation||""),H.add(K.name);if(j.size===0)return{declarations:G,inlined:0};function L(K){let M=K;for(let[Q,V]of j){let W=new RegExp(`\\b${Q}\\b`,"g");M=M.replace(W,V)}return M}return{declarations:G.filter((K)=>K.kind!=="type"||!H.has(K.name)).map((K)=>{if(K.typeAnnotation)K={...K,typeAnnotation:L(K.typeAnnotation)};if(K.returnType)K={...K,returnType:L(K.returnType)};if(K.extends)K={...K,extends:L(K.extends)};return K}),inlined:j.size}}function v(G){let j=G.length,H=G.filter((L)=>!E(L));return{declarations:H,removed:j-H.length}}function B(G,j={}){let H=[...G],L={originalSize:0,optimizedSize:0,savings:0,savingsPercent:0,removedImports:0,removedDeclarations:0,mergedInterfaces:0,inlinedTypes:0};if(j.removeUnusedImports){let{declarations:J,removed:K}=k(H);H=J,L.removedImports=K}if(j.deduplicateDeclarations){let{declarations:J,removed:K}=A(H);H=J,L.removedDeclarations+=K}if(j.mergeInterfaces){let{declarations:J,merged:K}=z(H);H=J,L.mergedInterfaces=K}if(j.removeEmptyInterfaces){let{declarations:J,removed:K}=v(H);H=J,L.removedDeclarations+=K}if(j.inlineSimpleTypes){let{declarations:J,inlined:K}=P(H);H=J,L.inlinedTypes=K}if(j.sortImports)H=R(H);if(j.sortDeclarations)H=D(H);return{declarations:H,result:L}}async function g(G,j={}){if(!U(G))throw Error(`File not found: ${G}`);let H=O(G,"utf-8"),L=Buffer.byteLength(H,"utf-8"),J=$(H,G,!j.removeComments),{declarations:K,result:M}=B(J,j),Q=h(K,j);if(j.minify)Q=x(Q);let V=Buffer.byteLength(Q,"utf-8");return M.originalSize=L,M.optimizedSize=V,M.savings=L-V,M.savingsPercent=Math.round(M.savings/L*100),q(G,Q),M}function h(G,j){let H=[];for(let L of G){if(!j.removeComments&&L.leadingComments)for(let J of L.leadingComments)H.push(J);if(L.text)H.push(L.text);else H.push(I(L));H.push("")}return H.join(`
|
|
3
|
+
`)}function I(G){let j=[];if(G.isExported)j.push("export");if(G.isDefault)j.push("default");switch(G.kind){case"import":if(G.isTypeOnly)j.push("import type");else j.push("import");if(G.specifiers&&G.specifiers.length>0){let H=G.specifiers.map((L)=>{let J=L.isType?"type ":"";return L.alias?`${J}${L.name} as ${L.alias}`:`${J}${L.name}`}).join(", ");j.push(`{ ${H} }`)}j.push("from"),j.push(`'${G.source}'`);break;case"function":if(j.push("declare function"),j.push(G.name),G.generics)j.push(G.generics);if(j.push(`(${S(G.parameters)})`),G.returnType)j.push(`: ${G.returnType}`);break;case"variable":if(j.push("declare const"),j.push(G.name),G.typeAnnotation)j.push(`: ${G.typeAnnotation}`);break;case"interface":if(j.push("interface"),j.push(G.name),G.generics)j.push(G.generics);if(G.extends)j.push(`extends ${G.extends}`);if(j.push("{"),G.members)for(let H of G.members)j.push(` ${H.name}${H.typeAnnotation?`: ${H.typeAnnotation}`:""}`);j.push("}");break;case"type":if(j.push("type"),j.push(G.name),G.generics)j.push(G.generics);j.push("="),j.push(G.typeAnnotation||"unknown");break;case"class":if(j.push("declare class"),j.push(G.name),G.generics)j.push(G.generics);if(G.extends)j.push(`extends ${G.extends}`);if(G.implements?.length)j.push(`implements ${G.implements.join(", ")}`);j.push("{ }");break;case"enum":j.push("declare enum"),j.push(G.name),j.push("{ }");break;default:return G.text||""}return j.join(" ")}function S(G){if(!G)return"";return G.map((j)=>{let H="";if(j.rest)H+="...";if(H+=j.name,j.optional)H+="?";if(j.type)H+=`: ${j.type}`;return H}).join(", ")}function x(G){return G.replace(/(?<!\/\*\*)\/\/[^\n]*/g,"").replace(/^\s*[\r\n]/gm,"").replace(/ {2,}/g," ").replace(/\s*([{}[\]();,:])\s*/g,"$1").replace(/(\w)(\{)/g,"$1 $2").replace(/(\})([a-z])/gi,"$1 $2").replace(/(export|import|type|interface|class|function|const|let|var|extends|implements|declare)\s*/g,"$1 ").trim()}
|
|
4
|
+
export{B as a,g as b,x as c};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import"./chunk-rw6j20e2.js";var e="@stacksjs/dtsx",i="module",n="0.9.10",r=!0,c="A modern, fast .d.ts generation tool, powered by Bun.",o="Chris Breuer <chris@stacksjs.org>",u="MIT",d="https://github.com/stacksjs/dtsx#readme",p={type:"git",url:"git+https://github.com/stacksjs/dtsx.git"},a={url:"https://github.com/stacksjs/dtsx/issues"},b=["dts","generation","isolated declarations","development","bun","stacks","typescript","javascript"],g={".":{import:"./dist/index.js"},"./*":{import:"./dist/*"}},l="./dist/index.js",m="./dist/index.d.ts",k={dtsx:"./dist/cli.js"},x=["dist"],h={benchmark:"bun benchmark/index.ts",build:"bun --filter './packages/dtsx' build",test:"bun test",lint:"bunx --bun pickier run . --mode lint --config .config/pickier.ts","lint:fix":"bunx --bun pickier run . --mode lint --fix --config .config/pickier.ts",changelog:"bunx logsmith --verbose","changelog:generate":"bunx logsmith --output CHANGELOG.md",release:"bun --bun run changelog:generate && bunx --bun bumpx prompt --recursive",typecheck:"bunx tsc --noEmit","dev:docs":"bun --bun vitepress dev docs","build:docs":"bun --bun vitepress build docs","preview:docs":"bun --bun vitepress preview docs"},v={"@stacksjs/bumpx":"^0.2.4","@stacksjs/bunpress":"^0.1.1","@stacksjs/clapp":"^0.2.0",pickier:"^0.1.18","@stacksjs/gitlint":"^0.1.5","@stacksjs/logsmith":"^0.2.1","@types/bun":"^1.3.9","@typescript/native-preview":"^7.0.0-dev.20260216.1","buddy-bot":"^0.9.16","bun-git-hooks":"^0.3.1","bun-plugin-dtsx":"workspace:*",mitata:"^1.0.34","oxc-transform":"^0.112.0",typescript:"^5.9.3"},j=["packages/*"],y={name:e,type:i,version:n,private:r,description:c,author:o,license:u,homepage:d,repository:p,bugs:a,keywords:b,exports:g,module:l,types:m,bin:k,files:x,scripts:h,devDependencies:v,workspaces:j};export{j as workspaces,n as version,m as types,i as type,h as scripts,p as repository,r as private,e as name,l as module,u as license,b as keywords,d as homepage,x as files,g as exports,v as devDependencies,c as description,y as default,a as bugs,k as bin,o as author};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Cc as Kz,Dc as Uz,Ec as P,Lc as u,Mc as p,Nc as jz}from"./chunk-dk2vv0np.js";function _(z,X=!0){if(!X||!z||z.length===0)return"";if(z.length===1)return z[0].trim()+`
|
|
3
|
+
`;let K="";for(let Z=0;Z<z.length;Z++){if(Z>0)K+=`
|
|
4
|
+
`;K+=z[Z].trim()}return`${K}
|
|
5
|
+
`}function Jz(z){if(z.includes(`
|
|
6
|
+
`))return`/**
|
|
7
|
+
* ${z}
|
|
8
|
+
*/
|
|
9
|
+
`;return`/** ${z} */
|
|
10
|
+
`}function Xz(z){let X=z.indexOf("{");if(X===-1)return-1;let K=z.indexOf("<");if(K===-1||K>X)return X;let Z=0,H=!1,j="";for(let Y=0;Y<z.length;Y++){let J=z[Y],G=Y>0?z[Y-1]:"";if(!H&&(J==='"'||J==="'"||J==="`"))H=!0,j=J;else if(H&&J===j&&G!=="\\")H=!1;if(!H){if(J==="<")Z++;else if(J===">")Z--;else if(J==="{"&&Z===0)return Y}}return-1}function n(z,X=!0){return _(z.leadingComments,X)+z.text}function c(z,X=!0){let K=_(z.leadingComments,X);if(z.typeAnnotation&&!z.value)return K+z.text;let Z="";if(z.isExported)Z+="export ";Z+="declare ";let H=z.modifiers?.[0]||"const";Z+=`${H} `,Z+=z.name;let{typeAnnotation:j,value:Y}=z;if(Y&&Y.includes(" satisfies ")){let G=p(Y);if(G)j=G}else if(Y&&Y.trim().endsWith("as const"))j=P(Y,!0);else if(!j&&Y&&H==="const"){let G=Y.trim(),W=G.startsWith("{")||G.startsWith("[");if(W)Kz();j=P(Y,!W)}else if(j&&Y&&H==="const"&&u(j)){let G=P(Y,!0);if(G!=="unknown")j=G}else if(!j&&Y)j=P(Y,H==="const");if(!j)j="unknown";let J="";if(Y&&!z.typeAnnotation&&!Y.trim().endsWith("as const")){let G=Y.trim();if(H!=="const"){if((j==="string"||j==="number"||j==="boolean")&&G.length>0)J=`@defaultValue ${G}`}else if(G.startsWith("{")||G.startsWith("[")){let W=Uz();if(W)if(W.includes(`
|
|
11
|
+
`))J=`@defaultValue
|
|
12
|
+
* \`\`\`ts
|
|
13
|
+
${W.split(`
|
|
14
|
+
`).map((R)=>` * ${R}`).join(`
|
|
15
|
+
`)}
|
|
16
|
+
* \`\`\``;else J=`@defaultValue \`${W}\``}}if(Z+=`: ${j};`,J&&K&&K.includes("@defaultValue"))J="";if(J&&K){let G=K.trimEnd(),W=G.lastIndexOf("*/");if(W!==-1){let R=G.slice(0,W).trimEnd();if(R.startsWith("/** ")&&!R.includes(`
|
|
17
|
+
`))R=`/**
|
|
18
|
+
* ${R.slice(4)}`;return`${R}
|
|
19
|
+
* ${J}
|
|
20
|
+
*/
|
|
21
|
+
`+Z}return`/**
|
|
22
|
+
* ${G.replace(/^\/\/\s*/,"")}
|
|
23
|
+
* ${J}
|
|
24
|
+
*/
|
|
25
|
+
${Z}`}if(J)return`${Jz(J)}${Z}`;return K+Z}function d(z,X=!0){let K=_(z.leadingComments,X),Z=z.text;if(Z.startsWith("export declare interface")||Z.startsWith("declare interface"))return K+Z;let H="";if(z.isExported)H+="export ";if(H+="declare interface ",H+=z.name,z.generics)H+=z.generics;if(z.extends)H+=` extends ${z.extends}`;let j=Xz(z.text);if(j!==-1)H+=` ${z.text.slice(j)}`;else H+=" {}";return K+H}function l(z,X=!0){let K=_(z.leadingComments,X);if(z.text.includes("{")&&z.text.includes("}")&&z.text.includes("from"))return K+z.text;let Z="";if(z.isExported)Z+="export ";if(!z.isExported&&!z.text.includes(" from "))Z+="declare ";let H=z.text.indexOf("type ");if(H!==-1){let Y=z.text.slice(H),J=Y.length;while(J>0&&(Y.charCodeAt(J-1)===59||Y.charCodeAt(J-1)===32||Y.charCodeAt(J-1)===10||Y.charCodeAt(J-1)===13))J--;if(J<Y.length)Y=Y.slice(0,J);Z+=Y}else{if(Z+=`type ${z.name}`,z.generics)Z+=z.generics;Z+=" = any"}let j=Z.trimEnd();if(!j.endsWith(";")&&!j.endsWith("}"))Z+=";";return K+Z}function i(z,X=!0){return _(z.leadingComments,X)+z.text}function o(z,X=!0){let K=_(z.leadingComments,X),Z="";if(z.isExported)Z+="export ";if(Z+="declare ",z.modifiers?.includes("const"))Z+="const ";Z+="enum ",Z+=z.name;let H=z.text.indexOf("{");if(H!==-1)Z+=` ${z.text.slice(H)}`;else Z+=" {}";return K+Z}function Lz(z){let X=z.text.trim(),K=X.length;while(K>0&&X.charCodeAt(K-1)===59)K--;if(K<X.length)X=X.slice(0,K);return X+=";",X}function Gz(z,X=!0){return _(z.leadingComments,X)+z.text.trim()}function s(z,X=!0){let K=_(z.leadingComments,X);if(z.text.startsWith("declare global"))return K+z.text;if(z.source||(z.name.startsWith('"')||z.name.startsWith("'")||z.name.startsWith("`"))){let Y="declare module ";Y+=z.name;let J=z.text.indexOf("{");if(J!==-1)Y+=` ${z.text.slice(J)}`;else Y+=" {}";return K+Y}let H="";if(z.isExported)H+="export ";if(!z.modifiers?.includes("declare"))H+="declare ";H+="namespace ",H+=z.name;let j=z.text.indexOf("{");if(j!==-1)H+=` ${z.text.slice(j)}`;else H+=" {}";return K+H}var Rz=new Map,T=new Map;function Yz(z){return T.get(z)??null}function m(z,X){if(T.set(z,X),T.size>200){let K=0;for(let Z of T.keys()){if(K++>=20)break;T.delete(Z)}}}function Wz(){Rz.clear(),T.clear()}function a(z){let X=z.indexOf(" from ");if(X===-1)return null;let K=z.slice(X+6).trim(),Z=K[0];if(Z!=='"'&&Z!=="'")return null;let H=K.indexOf(Z,1);if(H===-1)return null;let j=K.slice(1,H),Y=z.slice(0,X).trim(),J=Y.startsWith("import type ");if(Y.startsWith("import "))Y=Y.slice(7).trim();if(Y.startsWith("type "))Y=Y.slice(5).trim();let G=null,W=[],Q=Y.indexOf("{"),R=Y.lastIndexOf("}");if(Q!==-1&&R!==-1){let D=Y.slice(0,Q).trim();if(D.endsWith(","))G=D.slice(0,-1).trim()||null;let w=Y.slice(Q+1,R),b=0;for(let S=0;S<=w.length;S++)if(S===w.length||w.charCodeAt(S)===44){let F=b,O=S;while(F<O&&(w.charCodeAt(F)===32||w.charCodeAt(F)===9||w.charCodeAt(F)===10))F++;while(O>F&&(w.charCodeAt(O-1)===32||w.charCodeAt(O-1)===9||w.charCodeAt(O-1)===10))O--;if(F<O)W.push(w.slice(F,O));b=S+1}}else G=Y.trim()||null;return{defaultName:G,namedItems:W,source:j,isTypeOnly:J}}function r(z){let X=Yz(z);if(X)return X;let K=[],Z=z.indexOf(" from ");if(Z===-1)return m(z,K),K;let H=z.slice(0,Z).trim();if(H.startsWith("import "))H=H.slice(7).trim();if(H.startsWith("type "))H=H.slice(5).trim();let j=H.indexOf("{"),Y=H.lastIndexOf("}");if(j!==-1&&Y!==-1){let J=H.slice(0,j).trim();if(J.endsWith(",")){let Q=J.slice(0,-1).trim();if(Q)K.push(Q)}else if(J&&!J.includes(","))K.push(J);let W=H.slice(j+1,Y).split(",");for(let Q=0;Q<W.length;Q++){let R=W[Q].trim();if(!R)continue;if(R.startsWith("type "))R=R.slice(5).trim();let D=R.indexOf(" as ");if(D!==-1)R=R.slice(D+4).trim();if(R)K.push(R)}}else{let J=H.trim();if(J)K.push(J)}return m(z,K),K}function Zz(z,X){throw Error(X||`Unexpected value: ${z}`)}function Vz(z){return z>=65&&z<=90||z>=97&&z<=122||z>=48&&z<=57||z===95||z===36||z>127}function $z(z){let X=new Set,K=0,Z=z.length;while(K<Z){let H=z.charCodeAt(K);if(H>=65&&H<=90||H>=97&&H<=122||H===95||H===36||H>127){let j=K;K++;while(K<Z&&Vz(z.charCodeAt(K)))K++;X.add(z.substring(j,K))}else K++}return X}var Qz=/export\s+(?:type\s+)?\{\s*([^}]+)\s*\}/;function Tz(z,X,K=!0,Z=["bun"]){let H="",j=X.sourceCode;if(j){let U=0;while(U<j.length&&(j.charCodeAt(U)===32||j.charCodeAt(U)===9||j.charCodeAt(U)===10||j.charCodeAt(U)===13))U++;if(U<j.length-2&&j.charCodeAt(U)===47&&j.charCodeAt(U+1)===47&&j.charCodeAt(U+2)===47){let L=jz(j);if(L.length>0)for(let V=0;V<L.length;V++){if(H)H+=`
|
|
26
|
+
`;H+=L[V]}}}let Y=[],J=[],G=[],W=[],Q=[],R=[],D=[],w=[],b=[];for(let U of z){let L=U.kind;switch(L){case"import":Y.push(U);break;case"function":J.push(U);break;case"variable":G.push(U);break;case"interface":W.push(U);break;case"type":Q.push(U);break;case"class":R.push(U);break;case"enum":D.push(U);break;case"module":w.push(U);break;case"export":b.push(U);break;case"namespace":w.push(U);break;case"unknown":break;default:Zz(L,`Unhandled declaration kind: ${L}`)}}let S=new Set,F=[],O=[],x=[],t=new Set;for(let U of b){let L=_(U.leadingComments,K);if(U.text.startsWith("export default")){let V=U.text.endsWith(";")?U.text:`${U.text};`;x.push(L+V)}else{let V=U.text.trim();if(!V.endsWith(";"))V+=";";let M=V.match(Qz);if(M){let q=M[1].split(",").map((B)=>B.trim());for(let B of q)S.add(B)}let $=L+V;if(!t.has($))if(t.add($),$.includes("export type"))F.push($);else O.push($)}}let y=new Map;if(Y.length>0)for(let U of Y){let L=r(U.text);for(let V of L)y.set(V,U)}let e=new Set;if(W.length>0){let U=[];for(let L of J)if(L.isExported)U.push(L.text);for(let L of R)U.push(L.text);for(let L of Q)U.push(L.text);if(U.length>0){let L=$z(U.join(`
|
|
27
|
+
`));for(let V of W)if(L.has(V.name))e.add(V.name)}}let N=[];if(Y.length>0){let U=new Set,L=[];for(let $ of J)if($.isExported)L.push($.text);for(let $ of G)if($.isExported){if(L.push($.text),$.typeAnnotation)L.push($.typeAnnotation)}for(let $ of W)if($.isExported||e.has($.name))L.push($.text);for(let $ of Q)L.push($.text);for(let $ of R)L.push($.text);for(let $ of D)L.push($.text);for(let $ of w)L.push($.text);for(let $ of b)L.push($.text);let V=L.join(`
|
|
28
|
+
`);if(V&&y.size>0){let $=$z(V);for(let q of y.keys())if($.has(q))U.add(q)}for(let $ of S)if(y.has($))U.add($);for(let $ of Y){if($.isSideEffect){let E=$.text.trim(),g=E.endsWith(";")?E:`${E};`;N.push(g);continue}let q=a($.text);if(!q)continue;let{defaultName:B,namedItems:A,source:v,isTypeOnly:k}=q,h=B?U.has(B):!1,I="",C=0;for(let E=0;E<A.length;E++){let g=A[E],f=g.charCodeAt(0)===116&&g.startsWith("type ")?g.slice(5).trim():g.trim(),Hz=f.indexOf(" as ");if(Hz!==-1)f=f.slice(Hz+4).trim();if(U.has(f)){if(C>0)I+=", ";I+=g,C++}}if(h||C>0){let E=k?"import type ":"import ";if(h&&B)E+=C>0?`${B}, { ${I} }`:B;else if(C>0)E+=`{ ${I} }`;E+=` from '${v}';`,N.push(E)}}let M=Z.length;if(N.length>1){let $=Z.map((A)=>`from '${A}`),q=Z.map((A)=>`from "${A}`),B=new Map;for(let A of N){let v=M;for(let k=0;k<Z.length;k++)if(A.includes($[k])||A.includes(q[k])){v=k;break}B.set(A,v)}N.sort((A,v)=>{let k=B.get(A),h=B.get(v);return k!==h?k-h:A.localeCompare(v)})}}for(let U=0;U<N.length;U++){if(H)H+=`
|
|
29
|
+
`;H+=N[U]}for(let U=0;U<F.length;U++){if(H)H+=`
|
|
30
|
+
`;H+=F[U]}let zz=[J,G,W,Q,R,D,w];for(let U=0;U<zz.length;U++){let L=zz[U];for(let V=0;V<L.length;V++){let M=L[V],$="",q=M.kind;switch(q){case"function":$=n(M,K);break;case"variable":$=c(M,K);break;case"interface":$=d(M,K);break;case"type":$=l(M,K);break;case"class":$=i(M,K);break;case"enum":$=o(M,K);break;case"module":case"namespace":$=s(M,K);break;case"import":case"export":case"unknown":break;default:Zz(q,`Unhandled declaration kind in processor: ${q}`)}if($){if(H)H+=`
|
|
31
|
+
`;H+=$}}}for(let U=0;U<O.length;U++){if(H)H+=`
|
|
32
|
+
`;H+=O[U]}for(let U=0;U<x.length;U++){if(H)H+=`
|
|
33
|
+
`;H+=x[U]}return H}export{_ as oc,n as pc,c as qc,d as rc,l as sc,i as tc,o as uc,Lz as vc,Gz as wc,s as xc,Wz as yc,a as zc,r as Ac,Tz as Bc};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{hc as y}from"./chunk-p1d09y82.js";import{ad as k}from"./chunk-rw6j20e2.js";var H=k(y(),1);import{dirname as C,resolve as F}from"path";function v(q,j){let B=H.default.readConfigFile(q,H.default.sys.readFile);if(B.error)throw Error(`Error reading tsconfig.json: ${b(B.error)}`);let J=H.default.parseJsonConfigFileContent(B.config,H.default.sys,C(q));if(J.errors.length>0){let I=J.errors.map(b).join(`
|
|
3
|
+
`);throw Error(`Error parsing tsconfig.json:
|
|
4
|
+
${I}`)}return{...J.options,...j}}function b(q){if(q.file&&q.start!==void 0){let{line:j,character:B}=q.file.getLineAndCharacterOfPosition(q.start),J=H.default.flattenDiagnosticMessageText(q.messageText,`
|
|
5
|
+
`);return`${q.file.fileName}(${j+1},${B+1}): ${J}`}return H.default.flattenDiagnosticMessageText(q.messageText,`
|
|
6
|
+
`)}function x(q){switch(q){case H.default.DiagnosticCategory.Error:return"error";case H.default.DiagnosticCategory.Warning:return"warning";case H.default.DiagnosticCategory.Suggestion:return"hint";case H.default.DiagnosticCategory.Message:default:return"info"}}function S(q){switch(q){case H.default.DiagnosticCategory.Error:return"Error";case H.default.DiagnosticCategory.Warning:return"Warning";case H.default.DiagnosticCategory.Suggestion:return"Suggestion";case H.default.DiagnosticCategory.Message:return"Message";default:return"Unknown"}}function P(q){let j=H.default.flattenDiagnosticMessageText(q.messageText,`
|
|
7
|
+
`);if(q.file&&q.start!==void 0){let{line:B,character:J}=q.file.getLineAndCharacterOfPosition(q.start),I=q.file,R;if(q.length){let K=B,Q=q.start+q.length,{line:X}=I.getLineAndCharacterOfPosition(Q),$=I.text.split(`
|
|
8
|
+
`),V=Math.max(0,K-1),G=Math.min($.length,X+2);R=$.slice(V,G).join(`
|
|
9
|
+
`)}return{file:I.fileName,line:B+1,column:J+1,message:j,code:q.code,severity:x(q.category),source:R,category:S(q.category)}}return{file:"<unknown>",line:0,column:0,message:j,code:q.code,severity:x(q.category),category:S(q.category)}}function L(q,j){let B=H.default.createCompilerHost(j);return H.default.createProgram(q,j,B)}async function E(q,j={}){let B=Date.now(),J;if(j.tsconfigPath)J=v(j.tsconfigPath,j.compilerOptions);else J={target:H.default.ScriptTarget.ESNext,module:H.default.ModuleKind.ESNext,moduleResolution:H.default.ModuleResolutionKind.Bundler,strict:j.strict??!0,skipLibCheck:j.skipLibCheck??!0,noEmit:!0,declaration:!0,...j.compilerOptions};let I=q;if(j.declarationsOnly)I=q.filter((G)=>G.endsWith(".d.ts"));if(j.include?.length){let G=j.include.map((U)=>new RegExp(U.replace(/\*/g,".*")));I=I.filter((U)=>G.some((W)=>W.test(U)))}if(j.exclude?.length){let G=j.exclude.map((U)=>new RegExp(U.replace(/\*/g,".*")));I=I.filter((U)=>!G.some((W)=>W.test(U)))}let R=L(I,J),Q=[...R.getConfigFileParsingDiagnostics(),...R.getSyntacticDiagnostics(),...R.getSemanticDiagnostics(),...R.getDeclarationDiagnostics()].map(P);if(j.maxErrors&&Q.length>j.maxErrors)Q=Q.slice(0,j.maxErrors);let X=Q.filter((G)=>G.severity==="error").length,$=Q.filter((G)=>G.severity==="warning").length,V=Q.filter((G)=>G.severity==="info"||G.severity==="hint").length;if(j.warningsAsErrors)Q=Q.map((G)=>G.severity==="warning"?{...G,severity:"error"}:G),X+=$;return{success:X===0,diagnostics:Q,errorCount:X,warningCount:j.warningsAsErrors?0:$,infoCount:V,filesChecked:I,durationMs:Date.now()-B}}async function u(q,j={}){return E(q,{...j,declarationsOnly:!0,skipLibCheck:!0,compilerOptions:{...j.compilerOptions,noEmit:!0,declaration:!1}})}async function m(q,j){let B=new Map,I={...j?v(j):{target:H.default.ScriptTarget.ESNext,module:H.default.ModuleKind.ESNext,moduleResolution:H.default.ModuleResolutionKind.Bundler},isolatedDeclarations:!0,declaration:!0,noEmit:!0},R=L(q,I);for(let K of q){let Q=R.getSourceFile(K);if(!Q){B.set(K,{compatible:!0,issues:[]});continue}let X=[],V=[...R.getSyntacticDiagnostics(Q),...R.getSemanticDiagnostics(Q)].filter((G)=>G.code>=9006&&G.code<=9099);for(let G of V)if(G.start!==void 0){let{line:U,character:W}=Q.getLineAndCharacterOfPosition(G.start),Y=H.default.flattenDiagnosticMessageText(G.messageText,`
|
|
10
|
+
`),Z;if(Y.includes("return type"))Z="return";else if(Y.includes("parameter"))Z="parameter";else if(Y.includes("variable"))Z="variable";else if(Y.includes("property"))Z="property";X.push({line:U+1,column:W+1,message:Y,missingAnnotation:Z})}B.set(K,{compatible:X.length===0,issues:X})}return B}function f(q,j,B,J){try{let U=function(Z){if(V>=Z.getStart()&&V<Z.getEnd())return H.default.forEachChild(Z,U)||Z;return},I=J?v(J):{target:H.default.ScriptTarget.ESNext,module:H.default.ModuleKind.ESNext,moduleResolution:H.default.ModuleResolutionKind.Bundler},R=L([q],I),K=R.getSourceFile(q);if(!K)return null;let Q=K.getLineStarts().length;if(j<1||j>Q)return null;let X=K.getLineStarts()[j-1],$=j<Q?K.getLineStarts()[j]:K.text.length;if(B<1||B>$-X)return null;let V=K.getPositionOfLineAndCharacter(j-1,B-1),G=R.getTypeChecker(),W=U(K);if(!W)return null;let Y=G.getTypeAtLocation(W);return G.typeToString(Y)}catch{return null}}function d(q,j,B,J){try{let U=function(M){if(V>=M.getStart()&&V<M.getEnd())return H.default.forEachChild(M,U)||M;return},I=J?v(J):{target:H.default.ScriptTarget.ESNext,module:H.default.ModuleKind.ESNext,moduleResolution:H.default.ModuleResolutionKind.Bundler},R=L([q],I),K=R.getSourceFile(q);if(!K)return null;let Q=K.getLineStarts().length;if(j<1||j>Q)return null;let X=K.getLineStarts()[j-1],$=j<Q?K.getLineStarts()[j]:K.text.length;if(B<1||B>$-X)return null;let V=K.getPositionOfLineAndCharacter(j-1,B-1),G=R.getTypeChecker(),W=U(K);if(!W)return null;let Y=G.getSymbolAtLocation(W);if(!Y){let M=G.getTypeAtLocation(W);return{type:G.typeToString(M)}}let Z=G.typeToString(G.getTypeOfSymbolAtLocation(Y,W)),A=H.default.displayPartsToString(Y.getDocumentationComment(G));return{type:Z,documentation:A||void 0}}catch{return null}}function g(q){let j=[];if(q.success)j.push(`\u2713 Type check passed (${q.filesChecked.length} files checked in ${q.durationMs}ms)`);else{j.push("\u2717 Type check failed"),j.push(` ${q.errorCount} error(s), ${q.warningCount} warning(s)`),j.push("");for(let B of q.diagnostics){let J=B.severity==="error"?"\u2717":B.severity==="warning"?"\u26A0":"\u2139";if(j.push(`${J} ${B.file}:${B.line}:${B.column}`),j.push(` ${B.message}`),B.source){let I=B.source.split(`
|
|
11
|
+
`);for(let R of I)j.push(` \u2502 ${R}`)}if(B.suggestion)j.push(` \uD83D\uDCA1 ${B.suggestion}`);j.push("")}}return j.join(`
|
|
12
|
+
`)}async function l(q){let j=q.entrypoints.map((B)=>F(q.cwd,B));return E(j,{tsconfigPath:q.tsconfigPath,rootDir:q.root})}async function a(q,j,B){let J=q,I=j,R=B,K=[],Q=R?v(R):{target:H.default.ScriptTarget.ESNext,module:H.default.ModuleKind.ESNext,moduleResolution:H.default.ModuleResolutionKind.Bundler},X=L(J,Q),$=L(I,{...Q,declaration:!1}),V=X.getTypeChecker(),G=$.getTypeChecker();for(let U=0;U<J.length;U++){let W=X.getSourceFile(J[U]),Y=$.getSourceFile(I[U]);if(!W||!Y)continue;let Z=V.getSymbolAtLocation(W),A=G.getSymbolAtLocation(Y);if(!Z||!A)continue;let M=V.getExportsOfModule(Z),O=G.getExportsOfModule(A),T=new Map(O.map((w)=>[w.getName(),w]));for(let w of M){let N=w.getName(),D=T.get(N);if(!D){K.push({sourceName:N,sourceType:V.typeToString(V.getTypeOfSymbolAtLocation(w,W)),dtsType:"<missing>"});continue}let _=V.typeToString(V.getTypeOfSymbolAtLocation(w,W)),z=G.typeToString(G.getTypeOfSymbolAtLocation(D,Y));if(_!==z&&!h(_,z))K.push({sourceName:N,sourceType:_,dtsType:z})}}return{valid:K.length===0,mismatches:K}}function h(q,j){let B=(R)=>R.replace(/\s+/g," ").replace(/\s*([<>,{}()[\]:;])\s*/g,"$1").trim(),J=B(q),I=B(j);if(J===I)return!0;if(I==="any")return!0;if(J.startsWith("Promise<")&&I.startsWith("PromiseLike<"))return!0;return!1}
|
|
13
|
+
export{v as z,E as A,u as B,m as C,f as D,d as E,g as F,l as G,a as H};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{d as a,e as b,f as c,g as d,h as e,i as f,j as g,k as h}from"./chunk-bn29kee5.js";import"./chunk-9mjc7ddv.js";import"./chunk-p1d09y82.js";import"./chunk-74j5mydx.js";import"./chunk-rnt0wkrk.js";import"./chunk-dk2vv0np.js";import"./chunk-57agx6g8.js";import"./chunk-rw6j20e2.js";export{a as parseJSDoc,f as generateTypeDocJSON,c as generateMarkdown,e as generateJSON,d as generateHTML,g as generateDocs,b as extractDocumentation,h as createDocsGenerator};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{a,b,c}from"./chunk-fw6wcdfd.js";import"./chunk-9mjc7ddv.js";import"./chunk-p1d09y82.js";import"./chunk-74j5mydx.js";import"./chunk-rnt0wkrk.js";import"./chunk-dk2vv0np.js";import"./chunk-rw6j20e2.js";export{b as optimizeFile,a as optimizeDeclarations,c as minifyDts};
|