@stacksjs/rpx 0.11.45 → 0.11.47
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/dist/bin/cli.js +289 -239
- package/dist/chunk-3tg7caak.js +311 -0
- package/dist/chunk-er1mtkha.js +1 -0
- package/dist/chunk-handw2xw.js +1 -0
- package/dist/chunk-pcyc92vj.js +49 -0
- package/dist/daemon.d.ts +4 -2
- package/dist/gateway.d.ts +65 -0
- package/dist/https.d.ts +8 -0
- package/dist/index.d.ts +26 -2
- package/dist/index.js +2 -2
- package/dist/local-ca.d.ts +77 -0
- package/dist/proxy-handler.d.ts +2 -1
- package/dist/proxy-pool.d.ts +1 -0
- package/dist/sni.d.ts +37 -0
- package/dist/start.d.ts +9 -1
- package/dist/types.d.ts +23 -0
- package/package.json +2 -2
- package/dist/chunk-bvq3wmhm.js +0 -1
- package/dist/chunk-t6pzd7ec.js +0 -252
- package/dist/chunk-vce43wgr.js +0 -1
- package/dist/chunk-w4t1nar9.js +0 -49
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{$b as k,Rb as a,Sb as b,Tb as c,Ub as d,Vb as e,Wb as f,Xb as g,Yb as h,Zb as i,_b as j,ac as l,bc as m,cc as n,dc as o,ec as p,fc as q}from"./chunk-pcyc92vj.js";export{c as authorizeSystemAccess,e as debugLog,d as execSudoSync,i as extractHostname,k as getPrimaryDomain,a as getSudoPassword,l as isMultiProxyConfig,m as isMultiProxyOptions,b as isProcessElevated,o as isSingleProxyConfig,n as isSingleProxyOptions,j as isValidRootCA,g as redactSensitive,p as resolvePathRewrite,q as safeDeleteFile,h as safeStringify,f as shouldReusePort};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ab as l,Bb as m,Cb as n,Db as o,pb as a,qb as b,rb as c,sb as d,tb as e,ub as f,vb as g,wb as h,xb as i,yb as j,zb as k}from"./chunk-3tg7caak.js";import"./chunk-pcyc92vj.js";export{a as DNS_PORT,b as RPX_RESOLVER_MARKER,h as contentLooksLikeRpxResolver,e as isDnsServerRunning,f as isRpxDevelopmentDnsAnswering,o as reconcileStaleDevelopmentDns,j as removeLegacyTldResolvers,n as removeResolver,g as resolverFilePath,k as setupDevelopmentDns,i as setupResolver,c as startDnsServer,d as stopDnsServer,l as syncDevelopmentDnsFromRegistry,m as tearDownDevelopmentDns};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import{createRequire as Ur}from"node:module";var Wr=Object.defineProperty;var Vr=(e)=>e;function zr(e,t){this[e]=Vr.bind(null,t)}var Ji=(e,t)=>{for(var r in t)Wr(e,r,{get:t[r],enumerable:!0,configurable:!0,set:zr.bind(t,r)})};var Z=Ur(import.meta.url);import{execSync as Ue}from"node:child_process";import*as Lr from"node:fs/promises";import{existsSync as Ot,statSync as Pt}from"fs";import{existsSync as ft,mkdirSync as Zr,readdirSync as Xr,writeFileSync as Qr}from"fs";import{homedir as Q}from"os";import{dirname as Rt,resolve as M}from"path";import X from"process";import{join as en,relative as tn,resolve as Nt}from"path";import Re from"process";import{existsSync as dr,mkdirSync as ss,readdirSync as os,writeFileSync as as}from"fs";import{homedir as Ye}from"os";import{dirname as fs,resolve as D}from"path";import ue from"process";import{join as rn,relative as nn,resolve as Bt}from"path";import Ne from"process";import{existsSync as pr,mkdirSync as ds,readdirSync as ps,writeFileSync as ys}from"fs";import{dirname as $s,resolve as Be}from"path";import ut from"process";import{Buffer as H}from"buffer";import{createCipheriv as sn,createDecipheriv as on,randomBytes as Ge}from"crypto";import{closeSync as Je,createReadStream as Dt,createWriteStream as an,existsSync as He,fsyncSync as Mt,openSync as Lt,writeFileSync as cn}from"fs";import{access as ln,constants as It,mkdir as fn,readdir as pe,rename as jt,stat as ee,unlink as ye,writeFile as qe}from"fs/promises";import{join as te}from"path";import O from"process";import{pipeline as un}from"stream/promises";import{createGzip as _t}from"zlib";import re from"process";import U from"process";import{Buffer as V}from"buffer";import{createCipheriv as gn,createDecipheriv as hn,randomBytes as Ze}from"crypto";import{closeSync as Xe,createReadStream as Kt,createWriteStream as mn,existsSync as we,fsyncSync as Wt,openSync as Vt,writeFileSync as dn}from"fs";import{access as pn,constants as zt,mkdir as yn,readdir as $e,rename as Ut,stat as ne,unlink as ve,writeFile as Qe}from"fs/promises";import{isAbsolute as wn,join as ie,resolve as $n}from"path";import d from"process";import{pipeline as vn}from"stream/promises";import{createGzip as Yt}from"zlib";import se from"process";import Y from"process";import Ce from"process";import{existsSync as Ee}from"fs";import{resolve as et}from"path";import{existsSync as Cn}from"fs";import{existsSync as En,readdirSync as bn}from"fs";import{extname as tt,resolve as Gt}from"path";import xn from"process";import{join as Ti,relative as Si,resolve as sr}from"path";import Ke from"process";import{Buffer as z}from"buffer";import{createCipheriv as Fi,createDecipheriv as Oi,randomBytes as ot}from"crypto";import{closeSync as at,createReadStream as or,createWriteStream as Pi,existsSync as xe,fsyncSync as ar,openSync as cr,writeFileSync as Ri}from"fs";import{access as Ni,constants as lr,mkdir as Bi,readdir as Te,rename as fr,stat as oe,unlink as Se,writeFile as ct}from"fs/promises";import{isAbsolute as Di,join as ae,resolve as Mi}from"path";import p from"process";import{pipeline as Li}from"stream/promises";import{createGzip as ur}from"zlib";import ce from"process";import G from"process";var Yr=Object.defineProperty;var Gr=(e)=>e;function Jr(e,t){this[e]=Gr.bind(null,t)}var Hr=(e,t)=>{for(var r in t)Yr(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Jr.bind(t,r)})},qr=(e,t)=>()=>(e&&(t=e(e=0)),t);var mr={};Hr(mr,{withErrorRecovery:()=>$r,tryLoadConfig:()=>Gn,loadConfigWithResult:()=>Un,loadConfig:()=>xr,isRetryableError:()=>jn,isConfigNotFoundError:()=>In,isBunfigError:()=>vr,globalPerformanceMonitor:()=>me,globalCache:()=>le,getEnvOrDefault:()=>_n,generateConfigTypes:()=>Jn,defaultGeneratedDir:()=>Rr,defaultConfigDir:()=>Pr,deepMergeWithArrayStrategy:()=>Tt,deepMerge:()=>Cr,createLibraryConfig:()=>Hn,config:()=>Yn,bunfigPlugin:()=>qn,applyEnvVarsToConfig:()=>fe,TypeGenerationError:()=>wt,SchemaValidationError:()=>he,PluginError:()=>vt,PerformanceMonitor:()=>Et,FileSystemError:()=>yt,ErrorFactory:()=>q,EnvVarError:()=>_e,EnvProcessor:()=>Ve,ConfigValidator:()=>St,ConfigValidationError:()=>dt,ConfigNotFoundError:()=>je,ConfigMergeError:()=>pt,ConfigLoader:()=>kt,ConfigLoadError:()=>ge,ConfigFileLoader:()=>ze,ConfigCache:()=>Ct,CacheUtils:()=>Sr,BunfigError:()=>L,BrowserConfigError:()=>$t,ArrayMergeStrategies:()=>Fr});class Ct{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!Ot(e))return!0;return Pt(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=Ot(r)?Pt(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Et{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),s}catch(s){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Tn(e,t={}){let n=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return n?`${e}:${n}`:e}function Sn(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function kn(e){return e.getStats().size*2}function bt(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&b(t[0])&&"id"in t[0]&&t[0].id===3&&b(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(b(t)&&b(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(b(e)&&"arr"in e&&Array.isArray(e.arr)&&b(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&b(t[0])&&b(e[0])){let n=[...t];for(let i of e)if(b(i)&&"name"in i){if(!n.find((o)=>b(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(b(i)&&"path"in i){if(!n.find((o)=>b(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((s)=>De(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!b(t)||!b(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(b(i)&&b(r[n]))r[n]=bt(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&b(i[0])&&b(r[n][0])){let s=[...i];for(let o of r[n])if(b(o)&&"name"in o){if(!s.find((a)=>b(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(b(o)&&"path"in o){if(!s.find((a)=>b(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>De(c,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function De(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!De(e[r],t[r]))return!1;return!0}if(b(e)&&b(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!De(e[i],t[i]))return!1}return!0}return!1}function b(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function An(e,t){if(!pr(e))return null;try{let r=await import(e),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return bt(t,n)}catch{return null}}catch{return null}}async function Fn({name:e="",cwd:t,defaultConfig:r}){let n=t||ut.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let c of i){let a=Be(n,`${o}${c}`),l=await An(a,r);if(l!==null)return l}try{let o=Be(n,"package.json");if(pr(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return bt(r,a)}catch{}}}catch{}return r}function On(e,t={}){let r=Ne.cwd();while(r.includes("storage"))r=Bt(r,"..");let n=Bt(r,e||"");if(t?.relative)return nn(Ne.cwd(),n);return n}async function Pn(){try{let e=await Fn({name:"clarity",defaultConfig:Ae,cwd:Ne.cwd(),endpoint:"",headers:{}});return{...Ae,...e}}catch{return Ae}}function T(){if(U.env.NODE_ENV==="test"||U.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Rn(){if(U.env.NODE_ENV==="test"||U.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof U<"u"){let e=U.type;if(e==="renderer"||e==="worker")return!1;return!!(U.versions&&(U.versions.node||U.versions.bun))}return!1}class yr{async format(e){let t=await Rn(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:re.pid,hostname:t(),environment:re.env.NODE_ENV||"development",platform:re.platform,version:re.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:re.env.NODE_ENV||re.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Me{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...ht},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new yr,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??O.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Fe,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Fe};return{...Fe,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:ht.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await ln(this.config.logDirectory,It.F_OK|It.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await fn(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:H.from(e);try{if(!He(this.currentLogFile))await qe(this.currentLogFile,"",{mode:420});if(i=Lt(this.currentLogFile,"a",420),cn(i,a,{flag:"a"}),Mt(i),i!==void 0)Je(i),i=void 0;if((await ee(this.currentLogFile)).size===0){if(await qe(this.currentLogFile,a,{flag:"w",mode:420}),(await ee(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(s<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,u);let h=c*2**s;await new Promise((g)=>setTimeout(g,h)),s++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(i!==void 0)try{Je(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}s++;let l=c*2**(s-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return te(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 te(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return te(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(T())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Ge(16).toString("hex")}generateKey(){return Ge(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Ge(16),n=sn("aes-256-gcm",t,r),i=H.concat([n.update(e,"utf8"),n.final()]),s=n.getAuthTag();return{encrypted:H.concat([r,i,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=_t(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(H.from(H.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(T())return;let e=await ee(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await pe(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let f=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await ee(r).catch(()=>null))try{if(await jt(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await ye(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await qe(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await ee(r).catch(()=>null))await jt(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await pe(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await ye(te(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Dt(e),n=an(t),i=_t();await un(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),He(this.currentLogFile))try{let e=Lt(this.currentLogFile,"r+");Mt(e),Je(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!T()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await pe(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await ye(te(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?E.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(g)=>g.replace(this.ANSI_PATTERN,"");if(!this.fancy){let g=[];if(o)g.push(t);if(s==="warning")g.push("WARN");else if(s==="error")g.push("ERROR");else if(r)g.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)g.push(n.replace(/[[\]]/g,""));return g.push(i),g.join(" ")}let a=O.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${E.cyan(i)}`;if(!o)return l.trim();let f=c(l).trim().length,u=c(t).length,h=Math.max(1,a-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!T()){let l=kr[e],f=this.options.showTags!==!1&&this.name?E.gray(this.formatTag(this.name)):"",u;switch(e){case"debug":u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:E.gray(o),level:e}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:o,level:e}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:E.green(o),level:e}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:o,level:e}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:o,level:e}),console.error(u),c){let h=c.split(`
|
|
2
|
+
`);for(let g of h)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:E.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!T()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let a=`${s} ${this.environment}.${e.toUpperCase()}: ${o}
|
|
3
|
+
`;if(c)a+=`${c}
|
|
4
|
+
`;a=a.replace(this.ANSI_PATTERN,""),await this.writeToFile(a)}time(e){let t=performance.now();if(this.fancy&&!T()){let r=this.options.showTags!==!1&&this.name?E.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:E.blue("◐"),tag:r,message:`${E.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
5
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!T()){let f=this.options.showTags!==!1&&this.name?E.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:E.green("✓"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!T())console.error(l.trim());await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Me(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(T())throw Error("createReadStream is not supported in browser environments");if(!He(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Dt(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=H.isBuffer(e)?e:H.from(e,"base64"),i=n.slice(0,16),s=n.slice(-16),o=n.slice(16,-16),c=on("aes-256-gcm",r,i);return c.setAuthTag(s),H.concat([c.update(o),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return T()}isServerMode(){return!T()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!T()){let s=e.split(`
|
|
6
|
+
`),o=Math.max(...s.map((f)=>f.length))+2,c=`┌${"─".repeat(o)}┐`,a=`└${"─".repeat(o)}┘`,l=s.map((f)=>{let u=" ".repeat(o-f.length-2);return`│ ${f}${u} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:E.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:E.cyan(c)})),l.forEach((f)=>console.error(this.formatConsoleMessage({timestamp:r,message:E.cyan(f),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:E.cyan(a),showTimestamp:!1}))}else if(!T())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let i=`${n} ${this.environment}.INFO: [BOX] ${e}
|
|
7
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(T())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${E.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();O.stdin.removeListener("data",r);try{if(typeof O.stdin.setRawMode==="function")O.stdin.setRawMode(!1)}catch{}O.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof O.stdin.setRawMode==="function")O.stdin.setRawMode(!0)}catch{}O.stdin.resume(),O.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,c=0;if(r=e.replace(o,(a,l)=>{if(l==="%")return"%";if(c>=t.length)return a;let f=t[c++];switch(l){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return a}}),c<t.length)r+=` ${t.slice(c).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}if(this.fancy&&!T()){let o=this.options.showTags!==!1&&this.name?E.gray(this.formatTag(this.name)):"",c=E.blue("◐");console.error(`${c} ${o} ${E.cyan(r)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
8
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(s)}progress(e,t=""){if(!this.enabled||!this.fancy||T()||e<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(o,c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||T())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,o)),c!==void 0)this.activeProgressBar.message=c;let a=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,a)},finish:(o)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||T())return;if(this.activeProgressBar.current=this.activeProgressBar.total,o!==void 0)this.activeProgressBar.message=o;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(o,c="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||T())return;O.stdout.write(`${"\r".padEnd(O.stdout.columns||80)}\r`),this.log(c,o),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||T()||!O.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=E.green("━".repeat(n)),o=E.gray("━".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=t||r===100?E.green("✓"):E.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${E.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${c} ${a}${l}`,g=O.stdout.columns||80,x=" ".repeat(Math.max(0,g-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${x}`,O.stdout.write(e.lastRenderedLine),t)O.stdout.write(`
|
|
9
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||T()||!O.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(T()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await pe(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=te(this.config.logDirectory,n);if(e.before)try{if((await ee(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await ye(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function ke(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&v(t[0])&&"id"in t[0]&&t[0].id===3&&v(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(v(t)&&v(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(v(e)&&"arr"in e&&Array.isArray(e.arr)&&v(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&v(t[0])&&v(e[0])){let n=[...t];for(let i of e)if(v(i)&&"name"in i){if(!n.find((o)=>v(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(v(i)&&"path"in i){if(!n.find((o)=>v(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((s)=>Le(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!v(t)||!v(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(v(i)&&v(r[n]))r[n]=ke(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&v(i[0])&&v(r[n][0])){let s=[...i];for(let o of r[n])if(v(o)&&"name"in o){if(!s.find((a)=>v(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(v(o)&&"path"in o){if(!s.find((a)=>v(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>Le(c,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function xt(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:ke(e,t);if(Array.isArray(e))return r==="replace"?t:ke(e,t);if(!v(t)||!v(e))return t;let n={...e};for(let i of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,i))continue;let s=t[i],o=n[i];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")n[i]=s;else n[i]=ke(o,s);else if(v(s)&&v(o))n[i]=xt(o,s,r);else n[i]=s}return n}function Le(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Le(e[r],t[r]))return!1;return!0}if(v(e)&&v(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Le(e[i],t[i]))return!1}return!0}return!1}function v(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function be(e,t,r="replace"){if(!dr(e))return null;try{let n=await import(e),i=n.default||n;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return xt(t,i,r)}catch{return null}}catch{return null}}function Nn(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function s(o,c=[]){let a={...o};for(let[l,f]of Object.entries(o)){let u=[...c,l],h=(m)=>m.replace(/([A-Z])/g,"_$1").toUpperCase(),g=`${n}_${u.map(h).join("_")}`,x=`${n}_${u.map((m)=>m.toUpperCase()).join("_")}`;if(r)R.info(`Checking environment variable ${g} for config ${e}.${u.join(".")}`);if(typeof f==="object"&&f!==null&&!Array.isArray(f))a[l]=s(f,u);else{let m=ue.env[g]||ue.env[x];if(m!==void 0){if(r)R.info(`Using environment variable ${m?g:x} for config ${e}.${u.join(".")}`);if(typeof f==="number")a[l]=Number(m);else if(typeof f==="boolean")a[l]=m.toLowerCase()==="true";else if(Array.isArray(f))try{let C=JSON.parse(m);if(Array.isArray(C))a[l]=C;else a[l]=m.split(",").map((N)=>N.trim())}catch{a[l]=m.split(",").map((C)=>C.trim())}else a[l]=m}}}return a}return s(i)}async function Bn({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:s=!1,checkEnv:o=!0,arrayStrategy:c="replace"}){let a=o&&typeof i==="object"&&i!==null&&!Array.isArray(i)?Nn(e,i,s):i,l=r||ue.cwd(),f=[".ts",".js",".mjs",".cjs",".json"];if(s)R.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${l}`);let u=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),g=t?[t,`.${t}`]:[],x=t?[`${t}.config`,`.${t}.config`]:[],m=Array.from(new Set([l,D(l,"config"),D(l,".config"),n?D(l,n):void 0].filter(Boolean)));for(let C of m){if(s)R.info(`Searching for configuration in: ${C}`);let B=[D(l,"config"),D(l,".config")].concat(n?[D(l,n)]:[]).includes(C)?[...u,...h,...g,...x]:[...h,...u,...x,...g];for(let W of B)for(let K of f){let j=D(C,`${W}${K}`),Ft=await be(j,a,c);if(Ft!==null){if(s)R.success(`Configuration loaded from: ${j}`);return Ft}}}if(e){let C=D(Ye(),".config",e),N=["config",`${e}.config`];if(t)N.push(`${t}.config`);if(s)R.info(`Checking user config directory: ${C}`);for(let B of N)for(let W of f){let K=D(C,`${B}${W}`),j=await be(K,a,c);if(j!==null){if(s)R.success(`Configuration loaded from user config directory: ${K}`);return j}}}if(e){let C=D(Ye(),".config"),N=[`.${e}.config`];if(t)N.push(`.${t}.config`);if(s)R.info(`Checking user config directory for dotfile configs: ${C}`);for(let B of N)for(let W of f){let K=D(C,`${B}${W}`),j=await be(K,a,c);if(j!==null){if(s)R.success(`Configuration loaded from user config directory dotfile: ${K}`);return j}}}if(e){let C=Ye(),N=[`.${e}.config`,`.${e}`];if(t)N.push(`.${t}.config`),N.push(`.${t}`);if(s)R.info(`Checking user home directory for dotfile configs: ${C}`);for(let B of N)for(let W of f){let K=D(C,`${B}${W}`),j=await be(K,a,c);if(j!==null){if(s)R.success(`Configuration loaded from user home directory: ${K}`);return j}}}try{let C=D(l,"package.json");if(dr(C)){let N=await import(C),B=N[e];if(!B&&t){if(B=N[t],B&&s)R.success(`Using alias "${t}" configuration from package.json`)}if(B&&typeof B==="object"&&!Array.isArray(B))try{if(s)R.success(`Configuration loaded from package.json: ${B===N[e]?e:t}`);return xt(a,B,c)}catch(W){if(s)R.warn("Failed to merge package.json config:",W)}}}catch(C){if(s)R.warn("Failed to load package.json:",C)}if(s)R.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return a}function Dn(e,t={}){let r=Re.cwd();while(r.includes("storage"))r=Nt(r,"..");let n=Nt(r,e||"");if(t?.relative)return tn(Re.cwd(),n);return n}async function Mn(){try{let e=await Bn({name:"clarity",alias:"logging",defaultConfig:Oe,cwd:Re.cwd()});return{...Oe,...e||{}}}catch{return Oe}}function S(){if(Y.env.NODE_ENV==="test"||Y.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ln(){if(Y.env.NODE_ENV==="test"||Y.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Y<"u"){let e=Y.type;if(e==="renderer"||e==="worker")return!1;return!!(Y.versions&&(Y.versions.node||Y.versions.bun))}return!1}class wr{async format(e){let t=await Ln(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:se.pid,hostname:t(),environment:se.env.NODE_ENV||"development",platform:se.platform,version:se.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:se.env.NODE_ENV||se.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ie{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...mt},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new wr,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??d.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Pe,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Pe};return{...Pe,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:mt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!S()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await pn(this.config.logDirectory,zt.F_OK|zt.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await yn(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:V.from(e);try{if(!we(this.currentLogFile))await Qe(this.currentLogFile,"",{mode:420});if(i=Vt(this.currentLogFile,"a",420),dn(i,a,{flag:"a"}),Wt(i),i!==void 0)Xe(i),i=void 0;if((await ne(this.currentLogFile)).size===0){if(await Qe(this.currentLogFile,a,{flag:"w",mode:420}),(await ne(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(s<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,u);let h=c*2**s;await new Promise((g)=>setTimeout(g,h)),s++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(i!==void 0)try{Xe(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}s++;let l=c*2**(s-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return ie(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 ie(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ie(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(S())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Ze(16).toString("hex")}generateKey(){return Ze(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Ze(16),n=gn("aes-256-gcm",t,r),i=V.isBuffer(e)?e:V.from(e,"utf8"),s=n.update(i),o=n.final(),c=s.length+o.length,a=n.getAuthTag(),l=V.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Yt(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(V.from(V.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(S())return;if(!this.shouldWriteToFile())return;let e=await ne(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await $e(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let f=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await ne(r).catch(()=>null))try{if(await Ut(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await ve(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await Qe(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await ne(r).catch(()=>null))await Ut(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await $e(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await ve(ie(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Kt(e),n=mn(t),i=Yt();await vn(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),we(this.currentLogFile))try{let e=Vt(this.currentLogFile,"r+");Wt(e),Xe(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!S()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await $e(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await ve(ie(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?y.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||S())return!1;let e=typeof d.env.NO_COLOR<"u",t=d.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof d.stderr<"u"&&d.stderr.isTTY||typeof d.stdout<"u"&&d.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(g)=>g.replace(this.ANSI_PATTERN,"");if(!this.fancy){let g=[];if(o)g.push(t);if(s==="warning")g.push("WARN");else if(s==="error")g.push("ERROR");else if(r)g.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)g.push(n.replace(/[[\]]/g,""));return g.push(i),g.join(" ")}let a=d.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${y.cyan(i)}`;if(!o)return l.trim();let f=c(l).trim().length,u=c(t).length,h=Math.max(1,a-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=y.underline(y.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>y.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>y.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>y.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>y.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>y.strikethrough(n)),t}supportsHyperlinks(){if(S())return!1;let e=d.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=d.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(wn(t)||t.startsWith("./")||t.startsWith("../"))t=$n(t);else return null;return we(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":Ar[e],h=this.options.showTags!==!1&&this.name?y.gray(this.formatTag(this.name)):"",g;switch(e){case"debug":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:y.gray(a),level:e}),console.error(g);break;case"info":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:a,level:e}),console.warn(g);break;case"success":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:y.green(a),level:e}),console.error(g);break;case"warning":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:a,level:e}),console.warn(g);break;case"error":if(g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:a,level:e}),console.error(g),c){let x=c.split(`
|
|
10
|
+
`);for(let m of x)if(m.trim()&&!m.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:y.gray(` ${m}`),level:e,showTimestamp:!1}))}break}}else if(!S()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let f=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
|
|
11
|
+
`;if(c)f+=`${c}
|
|
12
|
+
`;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!S()&&d.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!S()&&d.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!S()&&d.stdout.isTTY)d.stdout.write(`
|
|
13
|
+
`);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!S()&&d.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?y.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":y.blue("◐"),tag:r,message:`${y.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
14
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?y.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":y.green("✓"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!S())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Ie(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(S())throw Error("createReadStream is not supported in browser environments");if(!we(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Kt(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=V.isBuffer(e)?e:V.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),c=hn("aes-256-gcm",r,i);c.setAuthTag(s);let a=c.update(o),l=c.final(),f=a.length+l.length,u=V.allocUnsafe(f);return a.copy(u,0),l.copy(u,a.length),u.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return S()}isServerMode(){return!S()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
|
|
15
|
+
`),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,f=`└${"─".repeat(a)}┘`,u=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:y.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:y.cyan(l),showTimestamp:!1})),u.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:y.cyan(f),showTimestamp:!1}))}else if(!S())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
|
|
16
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(S())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${y.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();d.stdin.removeListener("data",r);try{if(typeof d.stdin.setRawMode==="function")d.stdin.setRawMode(!1)}catch{}d.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof d.stdin.setRawMode==="function")d.stdin.setRawMode(!0)}catch{}d.stdin.resume(),d.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(f,u)=>{if(u==="%")return"%";if(l>=t.length)return f;let h=t[l++];switch(u){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return f}}),l<t.length)r+=` ${t.slice(l).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?y.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${y.blue("◐")} `;console.error(`${l}${a} ${y.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
17
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!d.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=y.green("━".repeat(n)),o=y.gray("━".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=this.options.showIcons===!1?"":t||r===100?y.green("✓"):y.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${y.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${c} ${a}${l}`,g=d.stdout.columns||80,x=" ".repeat(Math.max(0,g-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${x}`,d.stdout.write(e.lastRenderedLine),t)d.stdout.write(`
|
|
18
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||S()||!d.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(S()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await $e(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=ie(this.config.logDirectory,n);if(e.before)try{if((await ne(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await ve(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function $r(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!i(o))break;if(n>0)await new Promise((l)=>setTimeout(l,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function vr(e){return e instanceof L}function In(e){return e instanceof je}function jn(e){if(vr(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>e.message.toLowerCase().includes(r.toLowerCase()))}class Ve{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let f=n||this.generateEnvPrefix(e),u={...t};return this.processObject(u,[],f,{useCamelCase:i,useBackwardCompatibility:s,customParsers:o,verbose:c,configName:e}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return me.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=o.map((f)=>this.formatEnvKey(f,n.useCamelCase)),a=`${r}_${c.join("_")}`,l=n.useBackwardCompatibility?`${r}_${o.map((f)=>f.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,n);else{let f=Ce.env[a]||(l?Ce.env[l]:void 0);if(f!==void 0){if(n.verbose){let u=Ce.env[a]?a:l}try{e[i]=this.parseEnvironmentValue(f,typeof s,a,n.customParsers,n.configName)}catch(u){if(u instanceof _e)throw u;throw q.envVar(a,f,typeof s,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[s,o]of Object.entries(n))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw q.envVar(r,e,`${t} (via ${s.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(Ce.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,s=n||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),i){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,n);else n.push({key:c,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
19
|
+
|
|
20
|
+
`;for(let n of e)r+=`${n.key}
|
|
21
|
+
`,r+=` Type: ${n.type}
|
|
22
|
+
`,r+=` Description: ${n.description}
|
|
23
|
+
`,r+=` Example: ${n.example}
|
|
24
|
+
|
|
25
|
+
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
26
|
+
|
|
27
|
+
`;r+=`| Variable | Type | Description | Example |
|
|
28
|
+
`,r+=`|----------|------|-------------|----------|
|
|
29
|
+
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
30
|
+
`;return r}}function _n(e,t){let r=Tr("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function Cr(e,t,r={}){return Er(e,t,r,new WeakMap)}function Er(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return br(e,t,i,n);if(!I(t)||!I(e))return t;return zn(e,t,r,n)}function br(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return Kn(e,t);case"smart":return Wn(e,t,n);default:return t}return t}function Kn(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>gt(i,n)))r.push(n);return r}function Wn(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(I(t[0])&&I(e[0]))return Vn(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function Vn(e,t,r){let n=[...t];for(let i of e){if(!I(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in i){if(n.find((l)=>I(l)&&(c in l)&&l[c]===i[c])){o=!0;break}}if(!o)n.push(i)}return n}function zn(e,t,r,n){let i=t;if(I(i)&&n.has(i))return n.get(i);let s={...e};if(I(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let c=i[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(I(c)&&I(a))s[o]=Er(a,c,r,n);else if(Array.isArray(c)||Array.isArray(a))s[o]=br(a,c,r.arrayMergeMode||"smart",n);else s[o]=c}return s}function Tt(e,t,r="replace"){return Cr(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function gt(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!gt(e[r],t[r]))return!1;return!0}if(I(e)&&I(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!gt(e[i],t[i]))return!1}return!0}return!1}function I(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class ze{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(i){let l=le.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!Ee(e))return null;try{let l=`?t=${Date.now()}`,f=await import(e+l),u=f.default||f,h="default"in f,g=Object.keys(f).length>0;if(!h&&!g)throw new ge(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new ge(e,Error("Configuration must export a valid object"),"unknown");let C={config:Tt(t,u,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)le.setWithFileCheck("file",C,e,s);return C}catch(l){throw l instanceof Error?q.configLoad(e,l):q.configLoad(e,Error(String(l)))}};if(o)return me.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(et(t,`${s}${o}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return $r(async()=>Ee(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Ee(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let c=et(e,`${s}${o}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=et(e,o);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!Ee(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class St{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let f=[],u=[],h={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(g){return f.push({path:"",message:`Validation failed: ${g}`,rule:"system"}),{isValid:!1,errors:f,warnings:u}}};if(c)return await me.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!Cn(t))throw new he(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new he(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))i.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,o]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Or},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class kt{fileLoader=new ze;envProcessor=new Ve;validator=new St;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let f=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),u=!f&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||f))throw a;if(u&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(i||s)await this.validateConfiguration(c.config,i,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(n?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(a);if(n.slowThreshold&&a.duration>n.slowThreshold)_.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){let a=Date.now()-t;throw _.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:f=!1}=e,u=s||X.cwd(),h=[],g=await this.loadLocalConfiguration(n,i,u,o,c,l,f,a,r);if(g)return h.push(...this.getLocalSearchPaths(n,i,u,o)),this.finalizeResult(g,h,a,n,f);let x=await this.loadHomeConfiguration(n,i,c,l,f,a);if(x)return h.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(x,h,a,n,f);let m=await this.loadPackageJsonConfiguration(n,i,u,c,l,f,a);if(m)return h.push(M(u,"package.json")),this.finalizeResult(m,h,a,n,f);if(h.push(...this.getAllSearchPaths(n,i,u,o)),t)throw q.configNotFound(n,h,i);return{...await this.applyEnvironmentVariables(n,c,a,f),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,c,a){let l=c?fe(e,i,o):i,f=this.getLocalDirectories(r,n);for(let u of f){if(o)_.info(`Searching for configuration in: ${u}`);let h=this.fileLoader.generateConfigPaths(e,u,t),g=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(g){if(o)_.success(`Configuration loaded from: ${g.source.path}`);return g}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?fe(e,r,i):r,c=[M(Q(),".config",e),M(Q(),".config"),Q()];for(let a of c){if(i)_.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),f=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:n,verbose:i});if(f){if(i)_.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let c=o?fe(e,n,s):n;try{let a=M(r,"package.json");if(!ft(a))return null;let l=await import(a),f=l[e],u=e;if(!f&&t)f=l[t],u=t;if(f&&typeof f==="object"&&!Array.isArray(f)){if(s)_.success(`Configuration loaded from package.json: ${u}`);return{config:Tt(c,f,i),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)_.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:fe(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(i.length>0)throw q.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return le.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);le.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,M(e,"config"),M(e,".config"),t?M(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(M(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let o of i)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[M(Q(),".config",e),M(Q(),".config"),Q()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function Jt(e){let r=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),n=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return r||n}async function Un(e){return J.loadConfig({...e,__strictErrorHandling:!0})}async function xr(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await J.loadConfig(e);else n=await J.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",s=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||s.includes("config"))&&e.verbose)_.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await J.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}async function Yn(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await J.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Jt(r)))return(await J.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await J.loadConfig({...e,cwd:e.cwd||X.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Jt(t)))return(await J.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Gn(e,t,r="replace"){let n=new ze;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function fe(e,t,r=!1){let n=new Ve,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,f]of Object.entries(o)){let u=[...c,l],h=[`${i}_${u.join("_").toUpperCase()}`,`${i}_${u.map((m)=>m.toUpperCase()).join("")}`,`${i}_${u.map((m)=>m.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],g,x;for(let m of h)if(g=X.env[m],g!==void 0){x=m;break}if(g!==void 0&&x)if(typeof f==="boolean")a[l]=["true","1","yes"].includes(g.toLowerCase());else if(typeof f==="number"){let m=Number(g);if(!Number.isNaN(m))a[l]=m}else if(Array.isArray(f))try{a[l]=JSON.parse(g)}catch{a[l]=g.split(",").map((m)=>m.trim())}else a[l]=g;else if(f&&typeof f==="object"&&!Array.isArray(f))a[l]=s(f,u)}return a}return s(t)}function Jn(e){let t=M(X.cwd(),e.configDir),r=M(X.cwd(),e.generatedDir),n=M(r,"config-types.ts");if(!ft(Rt(n)))Zr(Rt(n),{recursive:!0,mode:511});let i=ft(t)?Xr(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${bi}
|
|
31
|
+
export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
|
|
32
|
+
`;Qr(n,s,{mode:438})}function Hn(e){let t=null,r=null,n=()=>{if(!r)r=xr(e).then((s)=>(t=s,s),(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)_.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return o});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(s,o){if(t)return t[o];let c=i[o];return n(),c},has(s,o){return o in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(s,o){return Object.getOwnPropertyDescriptor(t||i,o)},set(s,o,c){if(!t)t={...i};return t[o]=c,!0}})}function qn(e){let t=Gt(xn.cwd(),e?.configDir||"./config");function r(){if(!En(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=bn(t).filter((a)=>i.has(tt(a))).map((a)=>({base:a.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:a})),c=new Map;for(let{base:a,file:l}of o){let f=tt(l).toLowerCase(),u=c.get(a);if(!u){c.set(a,l);continue}let h=tt(u).toLowerCase();if(s.indexOf(f)<s.indexOf(h))c.set(a,l)}return Array.from(c.entries()).map(([a,l])=>({base:a,file:l})).sort((a,l)=>a.base.localeCompare(l.base))}function n(){let i=r(),s=i.map((l)=>l.base),o=s.length?s.map((l)=>`'${l}'`).join(" | "):"string",c=i.length?`{
|
|
33
|
+
${i.map((l)=>{let f=Gt(t,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${f}').default`}).join(`,
|
|
34
|
+
`)}
|
|
35
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${o}
|
|
36
|
+
export type ConfigByName = ${c}
|
|
37
|
+
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
38
|
+
export type ConfigOf = Config
|
|
39
|
+
`}return{name:"bunfig-plugin",setup(i){i.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:n(),loader:"ts"}))}}}var Tr,le,me,Sr,Zn,Xn,Ht,Ae,ht,P,E,Qn,qt,ei,Zt,ti,ri,rt,ni,Xt,Qt,nt,ii,si,oi,ai,Fe,kr,ci,R,li,fi,er,Oe,mt,k,y,ui,tr,gi,rr,hi,mi,it,di,nr,ir,pi,st,yi,wi,$i,vi,Ci,Pe,Ar,Ei,bi="0.15.6",L,je,ge,dt,pt,_e,yt,wt,he,$t,vt,q,Fr,Or,_,J,Pr,Rr,xi=qr(async()=>{Tr=import.meta.require,le=new Ct,me=new Et,Sr={createKey:Tn,isEquivalent:Sn,estimateMemoryUsage:kn},Zn=Be(ut.cwd(),"config"),Xn=Be(ut.cwd(),"src/generated"),Ht=Ne.env.CLARITY_LOG_DIR||rn(On(),"logs"),Ae={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ht,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},ht=await Pn(),P={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},E=P,Qn=P.red,qt=P.green,ei=P.yellow,Zt=P.blue,ti=P.magenta,ri=P.cyan,rt=P.white,ni=P.gray,Xt=P.bgRed,Qt=P.bgYellow,nt=P.bold,ii=P.dim,si=P.italic,oi=P.underline,ai=P.reset,Fe={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},kr={debug:"\uD83D\uDD0D",info:Zt("ℹ"),success:qt("✓"),warning:Qt(rt(nt(" WARN "))),error:Xt(rt(nt(" ERROR ")))},ci=new Me("stacks"),R=new Me("bunfig",{showTags:!0}),li=D(ue.cwd(),"config"),fi=D(ue.cwd(),"src/generated"),er=Re.env.CLARITY_LOG_DIR||en(Dn(),"logs"),Oe={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:er,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},mt=await Mn(),k={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},y=k,ui=k.red,tr=k.green,gi=k.yellow,rr=k.blue,hi=k.magenta,mi=k.cyan,it=k.white,di=k.gray,nr=k.bgRed,ir=k.bgYellow,pi=k.bgGray,st=k.bold,yi=k.dim,wi=k.italic,$i=k.underline,vi=k.strikethrough,Ci=k.reset,Pe={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ar={debug:"\uD83D\uDD0D",info:rr("ℹ"),success:tr("✓"),warning:ir(it(st(" WARN "))),error:nr(it(st(" ERROR ")))},Ei=new Ie("stacks"),L=class extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},je=class extends L{code="CONFIG_NOT_FOUND";constructor(t,r,n){let i=n?` or alias "${n}"`:"";super(`Configuration "${t}"${i} not found`,{configName:t,alias:n,searchPaths:r,searchPathCount:r.length})}},ge=class extends L{code="CONFIG_LOAD_ERROR";constructor(t,r,n){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},dt=class extends L{code="CONFIG_VALIDATION_ERROR";constructor(t,r,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:r,errorCount:r.length})}},pt=class extends L{code="CONFIG_MERGE_ERROR";constructor(t,r,n,i){super(`Failed to merge configuration from "${t}" with "${r}": ${n.message}`,{sourcePath:t,targetPath:r,configName:i,originalError:n.name,originalMessage:n.message});this.cause=n}},_e=class extends L{code="ENV_VAR_ERROR";constructor(t,r,n,i){super(`Failed to parse environment variable "${t}" with value "${r}" as ${n}`,{envKey:t,envValue:r,expectedType:n,configName:i})}},yt=class extends L{code="FILE_SYSTEM_ERROR";constructor(t,r,n){super(`File system ${t} failed for "${r}": ${n.message}`,{operation:t,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}},wt=class extends L{code="TYPE_GENERATION_ERROR";constructor(t,r,n){super(`Failed to generate types from "${t}" to "${r}": ${n.message}`,{configDir:t,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}},he=class extends L{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:r,errorCount:r.length})}},$t=class extends L{code="BROWSER_CONFIG_ERROR";constructor(t,r,n,i){super(`Failed to fetch configuration from "${t}": ${r} ${n}`,{endpoint:t,status:r,statusText:n,configName:i})}},vt=class extends L{code="PLUGIN_ERROR";constructor(t,r,n){super(`Plugin "${t}" failed during ${r}: ${n.message}`,{pluginName:t,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}},q={configNotFound(e,t,r){return new je(e,t,r)},configLoad(e,t,r){return new ge(e,t,r)},configValidation(e,t,r){return new dt(e,t,r)},configMerge(e,t,r,n){return new pt(e,t,r,n)},envVar(e,t,r,n){return new _e(e,t,r,n)},fileSystem(e,t,r){return new yt(e,t,r)},typeGeneration(e,t,r){return new wt(e,t,r)},schemaValidation(e,t,r){return new he(e,t,r)},browserConfig(e,t,r,n){return new $t(e,t,r,n)},plugin(e,t,r){return new vt(e,t,r)}},Fr={replace:"replace",concat:"concat",smart:"smart"},Or=/^https?:\/\//,_=new Ie("bunfig",{showTags:!0}),J=new kt,Pr=M(X.cwd(),"config"),Rr=M(X.cwd(),"src/generated")});function ki(e,t={}){let r=Ke.cwd();while(r.includes("storage"))r=sr(r,"..");let n=sr(r,e||"");if(t?.relative)return Si(Ke.cwd(),n);return n}var Ai=Ke.env.CLARITY_LOG_DIR||Ti(ki(),"logs"),Nr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ai,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},We={...Nr},qs=(async()=>{try{let{loadConfig:e}=await xi().then(()=>mr),t=await e({name:"clarity",alias:"logging",defaultConfig:Nr,cwd:Ke.cwd()});if(t)Object.assign(We,t)}catch{}return We})();function A(){if(G.env.NODE_ENV==="test"||G.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ii(){if(G.env.NODE_ENV==="test"||G.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof G<"u"){let e=G.type;if(e==="renderer"||e==="worker")return!1;return!!(G.versions&&(G.versions.node||G.versions.bun))}return!1}class Br{async format(e){let t=await Ii(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:ce.pid,hostname:t(),environment:ce.env.NODE_ENV||"development",platform:ce.platform,version:ce.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ce.env.NODE_ENV||ce.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var F={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},w=F,ao=F.red,ji=F.green,co=F.yellow,_i=F.blue,lo=F.magenta,fo=F.cyan,gr=F.white,uo=F.gray,Ki=F.bgRed,Wi=F.bgYellow,go=F.bgGray,hr=F.bold,ho=F.dim,mo=F.italic,po=F.underline,yo=F.strikethrough,wo=F.reset,lt={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Vi={debug:"\uD83D\uDD0D",info:_i("ℹ"),success:ji("✓"),warning:Wi(gr(hr(" WARN "))),error:Ki(gr(hr(" ERROR ")))};class de{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...We},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Br,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??p.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...lt,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...lt};return{...lt,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:We.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!A()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await Ni(this.config.logDirectory,lr.F_OK|lr.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Bi(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:z.from(e);try{if(!xe(this.currentLogFile))await ct(this.currentLogFile,"",{mode:420});if(i=cr(this.currentLogFile,"a",420),Ri(i,a,{flag:"a"}),ar(i),i!==void 0)at(i),i=void 0;if((await oe(this.currentLogFile)).size===0){if(await ct(this.currentLogFile,a,{flag:"w",mode:420}),(await oe(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(s<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,u);let h=c*2**s;await new Promise((g)=>setTimeout(g,h)),s++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(i!==void 0)try{at(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}s++;let l=c*2**(s-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return ae(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return ae(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ae(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(A())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return ot(16).toString("hex")}generateKey(){return ot(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=ot(16),n=Fi("aes-256-gcm",t,r),i=z.isBuffer(e)?e:z.from(e,"utf8"),s=n.update(i),o=n.final(),c=s.length+o.length,a=n.getAuthTag(),l=z.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=ur(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(z.from(z.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(A())return;if(!this.shouldWriteToFile())return;let e=await oe(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Te(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let f=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await oe(r).catch(()=>null))try{if(await fr(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Se(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await ct(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await oe(r).catch(()=>null))await fr(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await Te(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await Se(ae(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=or(e),n=Pi(t),i=ur();await Li(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),xe(this.currentLogFile))try{let e=cr(this.currentLogFile,"r+");ar(e),at(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!A()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Te(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Se(ae(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?w.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||A())return!1;let e=typeof p.env.NO_COLOR<"u",t=p.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof p.stderr<"u"&&p.stderr.isTTY||typeof p.stdout<"u"&&p.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(g)=>g.replace(this.ANSI_PATTERN,"");if(!this.fancy){let g=[];if(o)g.push(t);if(s==="warning")g.push("WARN");else if(s==="error")g.push("ERROR");else if(r)g.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)g.push(n.replace(/[[\]]/g,""));return g.push(i),g.join(" ")}let a=p.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${w.cyan(i)}`;if(!o)return l.trim();let f=c(l).trim().length,u=c(t).length,h=Math.max(1,a-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=w.underline(w.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>w.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>w.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>w.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>w.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>w.strikethrough(n)),t}supportsHyperlinks(){if(A())return!1;let e=p.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=p.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Di(t)||t.startsWith("./")||t.startsWith("../"))t=Mi(t);else return null;return xe(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":Vi[e],h=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",g;switch(e){case"debug":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:w.gray(a),level:e}),console.error(g);break;case"info":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:a,level:e}),console.warn(g);break;case"success":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:w.green(a),level:e}),console.error(g);break;case"warning":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:a,level:e}),console.warn(g);break;case"error":if(g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:a,level:e}),console.error(g),c){let x=c.split(`
|
|
40
|
+
`);for(let m of x)if(m.trim()&&!m.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:w.gray(` ${m}`),level:e,showTimestamp:!1}))}break}}else if(!A()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}let f=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
|
|
41
|
+
`;if(c)f+=`${c}
|
|
42
|
+
`;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!A()&&p.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!A()&&p.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!A()&&p.stdout.isTTY)p.stdout.write(`
|
|
43
|
+
`);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!A()&&p.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":w.blue("◐"),tag:r,message:`${w.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
44
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":w.green("✓"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!A())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new de(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(A())throw Error("createReadStream is not supported in browser environments");if(!xe(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return or(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=z.isBuffer(e)?e:z.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),c=Oi("aes-256-gcm",r,i);c.setAuthTag(s);let a=c.update(o),l=c.final(),f=a.length+l.length,u=z.allocUnsafe(f);return a.copy(u,0),l.copy(u,a.length),u.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return A()}isServerMode(){return!A()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
|
|
45
|
+
`),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,f=`└${"─".repeat(a)}┘`,u=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:w.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:w.cyan(l),showTimestamp:!1})),u.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:w.cyan(f),showTimestamp:!1}))}else if(!A())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
|
|
46
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(A())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${w.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();p.stdin.removeListener("data",r);try{if(typeof p.stdin.setRawMode==="function")p.stdin.setRawMode(!1)}catch{}p.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof p.stdin.setRawMode==="function")p.stdin.setRawMode(!0)}catch{}p.stdin.resume(),p.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(f,u)=>{if(u==="%")return"%";if(l>=t.length)return f;let h=t[l++];switch(u){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return f}}),l<t.length)r+=` ${t.slice(l).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${w.blue("◐")} `;console.error(`${l}${a} ${w.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
47
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!p.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=w.green("━".repeat(n)),o=w.gray("━".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=this.options.showIcons===!1?"":t||r===100?w.green("✓"):w.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${w.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${c} ${a}${l}`,g=p.stdout.columns||80,x=" ".repeat(Math.max(0,g-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${x}`,p.stdout.write(e.lastRenderedLine),t)p.stdout.write(`
|
|
48
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||A()||!p.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(A()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Te(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=ae(this.config.logDirectory,n);if(e.before)try{if((await oe(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Se(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var $o=new de("stacks");var zi=new de("rpx",{showTags:!1});function Ir(){return process.env.SUDO_PASSWORD}function jr(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function bo(e={}){if(process.platform==="win32")return!0;if(jr()||!!Ir())return!0;let t=e.exec??Ue;try{return t("sudo -n true",{stdio:"ignore"}),!0}catch{if(!e.interactive)return!1}try{return t("sudo -v",{stdio:"inherit"}),!0}catch{return!1}}function xo(e){if(jr())return Ue(e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let t=Ir(),r=e.replace(/'/g,"'\\''");if(t)return Ue(`echo '${t}' | sudo -S sh -c '${r}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return Ue(`sudo -n sh -c '${r}'`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}function Dr(e,t,r){if(r)zi.debug(`[rpx:${e}] ${t}`)}function To(){let e=process.env.RPX_REUSE_PORT;return e==="1"||e==="true"}var Mr="[redacted]",Ui=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),Yi=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function Gi(e){let t=e.toLowerCase();return Ui.has(t)||t.endsWith("password")||t.includes("secret")||t.includes("token")}function At(e){if(Array.isArray(e))return e.map((r)=>At(r));if(typeof e==="string")return Yi.test(e)?Mr:e;if(!e||typeof e!=="object")return e;let t={};for(let[r,n]of Object.entries(e)){if(Gi(r)){t[r]=Mr;continue}t[r]=At(n)}return t}function So(e,t){return JSON.stringify(At(e),null,t)}function ko(e){if(_r(e))return e.proxies.map((t)=>{let r=t.to||"stacks.localhost";return r.startsWith("http")?new URL(r).hostname:r});if(Kr(e)){let t=e.to||"stacks.localhost";return[t.startsWith("http")?new URL(t).hostname:t]}return["stacks.localhost"]}function Ao(e){return typeof e==="object"&&e!==null&&"certificate"in e&&"privateKey"in e&&typeof e.certificate==="string"&&typeof e.privateKey==="string"}function Fo(e){if(!e)return"stacks.localhost";if(_r(e)&&e.proxies.length>0)return e.proxies[0].to||"stacks.localhost";if(Kr(e))return e.to||"stacks.localhost";return"stacks.localhost"}function Oo(e){return!!(e&&("proxies"in e)&&Array.isArray(e.proxies))}function _r(e){return"proxies"in e&&Array.isArray(e.proxies)}function Kr(e){return"to"in e&&typeof e.to==="string"}function Po(e){return!!(e&&("to"in e)&&!("proxies"in e))}function Ro(e,t){if(!t||t.length===0)return null;for(let r of t)if(e===r.from||e.startsWith(`${r.from}/`)){let n=r.to.startsWith("http")?new URL(r.to).host:r.to,i=r.stripPrefix===!0?e.slice(r.from.length)||"/":e;return{targetHost:n,targetPath:i}}return null}async function No(e,t){try{await Lr.unlink(e),Dr("certificates",`Successfully deleted: ${e}`,t)}catch(r){if(r.code!=="ENOENT")Dr("certificates",`Warning: Could not delete ${e}: ${r}`,t)}}
|
|
49
|
+
export{Ji as Pb,Z as Qb,Ir as Rb,jr as Sb,bo as Tb,xo as Ub,Dr as Vb,To as Wb,At as Xb,So as Yb,ko as Zb,Ao as _b,Fo as $b,Oo as ac,_r as bc,Kr as cc,Po as dc,Ro as ec,No as fc};
|
package/dist/daemon.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { OnDemandCertManager } from './on-demand';
|
|
2
|
-
import type { OnDemandSitesConfig, OnDemandTlsConfig, ProductionTlsConfig, TlsOption } from './types';
|
|
2
|
+
import type { LocalCaConfig, OnDemandSitesConfig, OnDemandTlsConfig, ProductionTlsConfig, TlsOption } from './types';
|
|
3
3
|
import type { ProxyRoute } from './proxy-handler';
|
|
4
4
|
import type { RegistryEntry } from './registry';
|
|
5
5
|
import type { SiteSnapshot } from './site-supervisor';
|
|
@@ -89,9 +89,11 @@ export declare interface DaemonOptions {
|
|
|
89
89
|
httpsPort?: number
|
|
90
90
|
httpPort?: number
|
|
91
91
|
hostname?: string
|
|
92
|
-
https?: TlsOption
|
|
92
|
+
https?: boolean | TlsOption
|
|
93
93
|
productionCerts?: ProductionTlsConfig
|
|
94
94
|
onDemandTls?: OnDemandTlsConfig
|
|
95
|
+
localCa?: LocalCaConfig
|
|
96
|
+
maxTlsContexts?: number
|
|
95
97
|
onDemandSites?: OnDemandSitesConfig
|
|
96
98
|
acmeChallengeWebroot?: string
|
|
97
99
|
gcIntervalMs?: number
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { LocalCaConfig, OnDemandTlsConfig, ProductionTlsConfig, ProxyOptions, ResolvedProxyOptions } from './types';
|
|
2
|
+
import type { OriginGuardOptions } from './origin-guard';
|
|
3
|
+
/**
|
|
4
|
+
* Read every `*.json` fragment in `sitesDir`, in filename order. A missing
|
|
5
|
+
* directory yields no fragments (a box with nothing deployed yet). A fragment
|
|
6
|
+
* that fails to read or parse is passed to `onFragmentError` and skipped.
|
|
7
|
+
*/
|
|
8
|
+
export declare function readGatewayFragments(sitesDir: string, onFragmentError?: (file: string, err: Error) => void): Promise<GatewayFragmentFile[]>;
|
|
9
|
+
/**
|
|
10
|
+
* Merge fragments into the options `startProxies` takes, with ts-cloud's
|
|
11
|
+
* assembler semantics (see the module header). Pure: no I/O, no env reads.
|
|
12
|
+
*/
|
|
13
|
+
export declare function mergeGatewayFragments(fragments: GatewayFragmentFile[], options?: MergeGatewayOptions): ProxyOptions;
|
|
14
|
+
/**
|
|
15
|
+
* Resolve the full `startProxies` options for a gateway: read + merge the
|
|
16
|
+
* fragments, then apply the gateway-level switches (`https`, ports, local CA,
|
|
17
|
+
* memory guard, verbosity). Exported so the CLI and tests see exactly what
|
|
18
|
+
* {@link startGateway} starts.
|
|
19
|
+
*/
|
|
20
|
+
export declare function resolveGatewayOptions(options?: GatewayOptions): Promise<ProxyOptions>;
|
|
21
|
+
/**
|
|
22
|
+
* Start the gateway: merge every fragment under `sitesDir` and hand the result
|
|
23
|
+
* to {@link startProxies}. Resolves once the listeners are bound (or a bind was
|
|
24
|
+
* refused and logged); the process then serves until SIGINT / SIGTERM.
|
|
25
|
+
*/
|
|
26
|
+
export declare function startGateway(options?: GatewayOptions): Promise<void>;
|
|
27
|
+
/** Default directory on the box that holds real per-domain TLS certs. */
|
|
28
|
+
export declare const DEFAULT_GATEWAY_CERTS_DIR: '/etc/rpx/certs';
|
|
29
|
+
/** Default per-app fragment registry. */
|
|
30
|
+
export declare const DEFAULT_GATEWAY_SITES_DIR: '/etc/rpx/sites.d';
|
|
31
|
+
/** A per-app fragment: ts-cloud's `RpxGatewayConfig` plus its `slug`. */
|
|
32
|
+
export declare interface GatewayFragment {
|
|
33
|
+
slug?: string
|
|
34
|
+
proxies?: GatewayRoute[]
|
|
35
|
+
productionCerts?: Partial<ProductionTlsConfig>
|
|
36
|
+
onDemandTls?: Partial<OnDemandTlsConfig> & { staging?: boolean }
|
|
37
|
+
acmeChallengeWebroot?: string
|
|
38
|
+
originGuard?: Partial<OriginGuardOptions>
|
|
39
|
+
[key: string]: unknown
|
|
40
|
+
}
|
|
41
|
+
export declare interface GatewayFragmentFile {
|
|
42
|
+
file: string
|
|
43
|
+
fragment: GatewayFragment
|
|
44
|
+
}
|
|
45
|
+
export declare interface GatewayOptions {
|
|
46
|
+
sitesDir?: string
|
|
47
|
+
certsDir?: string
|
|
48
|
+
localCa?: LocalCaConfig
|
|
49
|
+
https?: boolean
|
|
50
|
+
httpPort?: number
|
|
51
|
+
httpsPort?: number
|
|
52
|
+
maxTlsContexts?: number
|
|
53
|
+
verbose?: boolean
|
|
54
|
+
onFragmentError?: (file: string, err: Error) => void
|
|
55
|
+
}
|
|
56
|
+
export declare interface MergeGatewayOptions {
|
|
57
|
+
certsDir?: string
|
|
58
|
+
onWarning?: (message: string) => void
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* One route inside a fragment. Structurally the rpx `BaseProxyConfig` (ts-cloud
|
|
62
|
+
* emits exactly these keys), typed loosely enough that a fragment written by
|
|
63
|
+
* an older or newer ts-cloud still loads.
|
|
64
|
+
*/
|
|
65
|
+
export type GatewayRoute = NonNullable<ResolvedProxyOptions['proxies']>[number];
|
package/dist/https.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { config } from './config';
|
|
2
2
|
import { MACOS_CA_TRUST_FLAGS, MACOS_SYSTEM_KEYCHAIN, getMacosLoginKeychainPath, isRootCaFingerprintInKeychains, isRootCaTrustedForSsl, pruneStaleRootCas, trustRootCaForBrowsers } from './macos-trust';
|
|
3
3
|
import { readCertCommonName, readCertSha256Fingerprint } from './cert-inspect';
|
|
4
|
+
import type { CAOptions } from '@stacksjs/tlsx';
|
|
4
5
|
import type { ProxyConfigs, ProxyOption, ProxyOptions, SSLConfig, TlsConfig } from './types';
|
|
5
6
|
/**
|
|
6
7
|
* Bun needs one `tls[]` entry per SNI name even when a single PEM covers every SAN.
|
|
@@ -20,6 +21,13 @@ export declare function getSharedDaemonCertPaths(sslDir: string): {
|
|
|
20
21
|
caCertPath: string
|
|
21
22
|
rootCA: RootCAPaths
|
|
22
23
|
};
|
|
24
|
+
/**
|
|
25
|
+
* Load the persisted Root CA under `sslDir`, or create and persist a fresh one
|
|
26
|
+
* (cert 0644, private key 0600). The one load-or-create used for the dev cert
|
|
27
|
+
* flow (`~/.stacks/ssl`) and the LAN local-CA flow alike, so a CA is only ever
|
|
28
|
+
* minted once per directory and browsers trust it once.
|
|
29
|
+
*/
|
|
30
|
+
export declare function ensureRootCA(sslDir: string, options?: { caOptions?: CAOptions, verbose?: boolean }): Promise<{ certificate: string, privateKey: string, created: boolean, paths: RootCAPaths }>;
|
|
23
31
|
/**
|
|
24
32
|
* Resolves SSL paths based on configuration
|
|
25
33
|
*/
|
package/dist/index.d.ts
CHANGED
|
@@ -17,7 +17,9 @@ export type { OriginGuard, OriginGuardOptions } from './origin-guard';
|
|
|
17
17
|
export type { ResolvedAuth } from './auth';
|
|
18
18
|
export type { HostRoutes, PathRoute } from './host-routes';
|
|
19
19
|
export type { ResolvedStaticRoute, StaticResolution } from './static-files';
|
|
20
|
-
export type { SniTlsEntry } from './sni';
|
|
20
|
+
export type { DefaultTlsContext, SniTlsEntry } from './sni';
|
|
21
|
+
export type { EnsureLocalCaOptions, LocalCaMaterial, LocalCaPaths, ResolvedLocalCaConfig } from './local-ca';
|
|
22
|
+
export type { GatewayFragment, GatewayFragmentFile, GatewayOptions, GatewayRoute, MergeGatewayOptions } from './gateway';
|
|
21
23
|
export type { CertIssuer, OnDemandCertManagerOptions } from './on-demand';
|
|
22
24
|
export type {
|
|
23
25
|
ResolvedSite,
|
|
@@ -57,6 +59,7 @@ export {
|
|
|
57
59
|
cleanupCertificates,
|
|
58
60
|
clearSslConfigCache,
|
|
59
61
|
devSslToSniEntries,
|
|
62
|
+
ensureRootCA,
|
|
60
63
|
forceTrustCertificate,
|
|
61
64
|
generateCertificate,
|
|
62
65
|
getRootCAPaths,
|
|
@@ -163,7 +166,28 @@ export {
|
|
|
163
166
|
safeRelativePath,
|
|
164
167
|
serveStaticFile,
|
|
165
168
|
} from './static-files';
|
|
166
|
-
export { buildSniTlsConfig, serverNameFromCertFilename } from './sni';
|
|
169
|
+
export { buildListenerTls, buildSniTlsConfig, capTlsContexts, DEFAULT_MAX_TLS_CONTEXTS, serverNameFromCertFilename, withLowMemoryTls } from './sni';
|
|
170
|
+
export {
|
|
171
|
+
DEFAULT_LOCAL_CA_RENEW_BEFORE_DAYS,
|
|
172
|
+
DEFAULT_LOCAL_CA_VALIDITY_DAYS,
|
|
173
|
+
ensureLocalCa,
|
|
174
|
+
installLocalCaTrust,
|
|
175
|
+
leafRenewalReason,
|
|
176
|
+
LOCAL_CA_COMMON_NAME,
|
|
177
|
+
LOCAL_CA_LEAF_CERT_FILENAME,
|
|
178
|
+
LOCAL_CA_LEAF_KEY_FILENAME,
|
|
179
|
+
localCaPaths,
|
|
180
|
+
parseSanNames,
|
|
181
|
+
resolveLocalCaConfig,
|
|
182
|
+
} from './local-ca';
|
|
183
|
+
export {
|
|
184
|
+
DEFAULT_GATEWAY_CERTS_DIR,
|
|
185
|
+
DEFAULT_GATEWAY_SITES_DIR,
|
|
186
|
+
mergeGatewayFragments,
|
|
187
|
+
readGatewayFragments,
|
|
188
|
+
resolveGatewayOptions,
|
|
189
|
+
startGateway,
|
|
190
|
+
} from './gateway';
|
|
167
191
|
export { isLikelyHostname, matchesAllowedSuffix, OnDemandCertManager } from './on-demand';
|
|
168
192
|
export {
|
|
169
193
|
createSiteResolver,
|