@stacksjs/build 0.72.56 → 0.72.60
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/index.js +151 -151
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
2
|
+
var pc=Object.defineProperty;var gc=(e)=>e;function yc(e,t){this[e]=gc.bind(null,t)}var Cc=(e,t)=>{for(var r in t)pc(e,r,{get:t[r],enumerable:!0,configurable:!0,set:yc.bind(t,r)})};var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var Xe=import.meta.require;class Mr{plugins=[];config=null;register(e){if(this.plugins.some((t)=>t.name===e.name))throw Error(`Plugin "${e.name}" is already registered`);this.plugins.push(e)}unregister(e){let t=this.plugins.findIndex((r)=>r.name===e);if(t>=0)return this.plugins.splice(t,1),!0;return!1}getPlugins(){return this.plugins}createLogger(e){return{debug:(t)=>console.debug(`[${e}] ${t}`),info:(t)=>console.info(`[${e}] ${t}`),warn:(t)=>console.warn(`[${e}] ${t}`),error:(t)=>console.error(`[${e}] ${t}`)}}async runOnStart(e){let t=e;for(let r of this.plugins)if(r.onStart){let n=await r.onStart(t);if(n)t=n}return this.config=t,t}async runOnBeforeFile(e,t){let r=t;for(let n of this.plugins)if(n.onBeforeFile){let i={filePath:e,sourceCode:t,content:r,config:this.config,log:this.createLogger(n.name)},s=await n.onBeforeFile(i);if(typeof s==="string")r=s}return r}async runOnDeclarations(e,t,r){let n=r;for(let i of this.plugins)if(i.onDeclarations){let s={filePath:e,sourceCode:t,declarations:n,config:this.config,log:this.createLogger(i.name)},o=await i.onDeclarations(s);if(o)n=o}return n}async runOnAfterFile(e,t,r){let n=r;for(let i of this.plugins)if(i.onAfterFile){let s={filePath:e,sourceCode:t,content:n,config:this.config,log:this.createLogger(i.name)},o=await i.onAfterFile(s);if(typeof o==="string")n=o}return n}async runOnEnd(e){for(let t of this.plugins)if(t.onEnd)await t.onEnd(e)}async runOnError(e,t,r){for(let n of this.plugins)if(n.onError){let i={filePath:t,sourceCode:r,config:this.config,log:this.createLogger(n.name)};await n.onError(e,i)}}}function wc(e){return e}var Gm,Bm;var Ds=ce(()=>{Gm=new Mr;Bm=wc({name:"strip-internal",version:"1.0.0",description:"Removes declarations marked with @internal",onDeclarations:(e)=>e.declarations.filter((t)=>{if(t.leadingComments){if(t.leadingComments.some((r)=>r.includes("@internal")))return e.log.debug(`Stripping internal declaration: ${t.name}`),!1}return!0})})});function fr(e){if($c)return Bun.hash(e);let t=0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);t=(t<<5)-t+n,t=t&t}return t}var $c;var qi=ce(()=>{$c=typeof globalThis.Bun?.hash==="function"});import{existsSync as ur,mkdirSync as Ec,readFileSync as zi,renameSync as vc,rmSync as Is,statSync as Fs,writeFileSync as Ns}from"fs";import{join as Ws,relative as Dr,resolve as Sc}from"path";class Qi{cacheDir;manifestPath;manifest=null;configHash;constructor(e){this.cacheDir=Sc(e.cwd,Ir),this.manifestPath=Ws(this.cacheDir,bc),this.configHash=this.hashConfig(e)}hashConfig(e){let t={keepComments:e.keepComments,importOrder:e.importOrder,outputStructure:e.outputStructure,isolatedDeclarations:e.isolatedDeclarations,declarationMap:e.declarationMap,indentStyle:e.indentStyle,indentSize:e.indentSize,prettier:e.prettier,typeMappings:e.typeMappings?{includeDefaults:e.typeMappings.includeDefaults,presets:e.typeMappings.presets,cacheKey:e.typeMappings.cacheKey,rules:e.typeMappings.rules.map((r)=>({pattern:typeof r.pattern==="string"?{kind:"string",value:r.pattern}:{kind:"regex",source:r.pattern.source,flags:r.pattern.flags},replacement:r.replacement,global:r.global,priority:r.priority,hasCondition:Boolean(r.condition)}))}:void 0,lineEnding:e.lineEnding,normalizeOutput:e.normalizeOutput,declarationOrder:e.declarationOrder,plugins:e.plugins?.map((r)=>({name:r.name,version:r.version,cacheKey:r.cacheKey}))};return String(fr(JSON.stringify(t)))}hashString(e){return String(fr(e))}load(){try{if(!ur(this.manifestPath))return!1;let e=zi(this.manifestPath,"utf-8"),t=JSON.parse(e);if(t.version!==Xi)return!1;if(t.configHash!==this.configHash)return!1;if(!t.entries||typeof t.entries!=="object"||Array.isArray(t.entries))return!1;return this.manifest=t,!0}catch{return!1}}save(){if(!this.manifest)this.manifest={version:Xi,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};if(this.manifest.updatedAt=Date.now(),!ur(this.cacheDir))Ec(this.cacheDir,{recursive:!0});let e=`${this.manifestPath}.${process.pid}.tmp`;try{Ns(e,JSON.stringify(this.manifest,null,2)),vc(e,this.manifestPath)}finally{if(ur(e))Is(e,{force:!0})}}needsRegeneration(e,t){return this.getCachedIfValid(e,t)===null}getCached(e,t){return this.getCachedIfValid(e,t)}getCachedIfValid(e,t){if(!this.manifest)return null;let r=Dr(t,e),n=this.manifest.entries[r];if(!n)return null;if(typeof n.dtsContent!=="string"||typeof n.dtsHash!=="string"||n.configHash!==this.configHash||this.hashString(n.dtsContent)!==n.dtsHash)return null;try{let i=Fs(e),s=i.mtimeMs,o=i.ctimeMs;if(i.size!==n.sourceSize)return null;if(s!==n.sourceMtime||o!==n.sourceCtime){let a=zi(e,"utf-8");if(this.hashString(a)!==n.sourceHash)return null;n.sourceMtime=s,n.sourceCtime=o}return n.dtsContent}catch{return null}}update(e,t,r,n){if(!this.manifest)this.manifest={version:Xi,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};let i=Dr(n,e),s,o,a;try{let c=Fs(e);s=c.mtimeMs,o=c.ctimeMs,a=c.size}catch{s=Date.now(),o=s,a=Buffer.byteLength(t)}this.manifest.entries[i]={sourcePath:i,sourceHash:this.hashString(t),sourceMtime:s,sourceCtime:o,sourceSize:a,dtsContent:r,dtsHash:this.hashString(r),generatedAt:Date.now(),configHash:this.configHash}}remove(e,t){if(!this.manifest)return;let r=Dr(t,e);delete this.manifest.entries[r]}clear(){this.manifest=null;try{if(ur(this.manifestPath))Is(this.cacheDir,{recursive:!0,force:!0})}catch{}}getStats(){if(!this.manifest)return{entries:0,size:0};let e=Object.keys(this.manifest.entries).length,t=0;for(let r of Object.values(this.manifest.entries))t+=r.dtsContent.length;return{entries:e,size:t}}prune(e,t){if(!this.manifest)return 0;let r=0,n=new Set(Array.from(e).map((i)=>Dr(t,i)));for(let i of Object.keys(this.manifest.entries))if(!n.has(i))delete this.manifest.entries[i],r++;return r}}function Ls(e){let t=Ws(e,".gitignore");try{let r="";if(ur(t))r=zi(t,"utf-8");if(!r.split(/\r?\n/).some((n)=>n.trim()===Ir||n.trim()===`${Ir}/`)){let n=r.trimEnd(),i=`${n}${n?`
|
|
3
3
|
|
|
4
4
|
`:""}# dtsx cache
|
|
5
5
|
${Ir}/
|
|
6
|
-
`;Fs(t,i)}}catch{}}var qi=3,Ir=".dtsx-cache",Sc="manifest.json";var Ls=le(()=>{Zi()});function Bt(e){return Gs[e]>=Gs[Dr]}function xc(){if(!Ac)return"";return`[${new Date().toISOString().slice(11,23)}] `}function Tc(e,t){let r=xc();if(e||r)return[`${r}${e}`,...t];return t}function Vt(e,t,r){let n=Tc(t,r);if(Bs){Bs(e,...n);return}switch(e){case"debug":console.debug(...n);break;case"info":console.log(...n);break;case"warn":console.warn(...n);break;case"error":console.error(...n);break}}function Vs(e){return{debug:(...t)=>{if(Bt("debug"))Vt("debug",e,t)},info:(...t)=>{if(Bt("info"))Vt("info",e,t)},warn:(...t)=>{if(Bt("warn"))Vt("warn",e,t)},error:(...t)=>{if(Bt("error"))Vt("error",e,t)},setLevel:(t)=>{Dr=t},getLevel:()=>Dr,child:(t)=>{let r=e?`${e}:${t}`:`[${t}]`;return Vs(r)},time:(t)=>{let r=performance.now();return()=>{let n=performance.now()-r;if(Bt("debug"))Vt("debug",e,[`${t}: ${n.toFixed(2)}ms`])}},progress:(t)=>{if(Bt("info"))if(typeof process<"u"&&process.stdout?.isTTY)process.stdout.write(`\r${e} ${t}`);else Vt("info",e,[t])}}}function Qi(e){Dr=e}var Gs,Dr="info",bc="[dtsx]",Ac=!1,Bs=null,j;var _s=le(()=>{Gs={debug:0,info:1,warn:2,error:3,silent:4};j=Vs(bc)});import Rc from"process";import{existsSync as Hs,statSync as js}from"fs";import{existsSync as Oc,mkdirSync as qm,readdirSync as Xm,readFileSync as Pc,writeFileSync as zm}from"fs";import{homedir as _t}from"os";import{dirname as tp,resolve as Xe}from"path";import mi from"process";import{existsSync as Ks,statSync as Js}from"fs";import{existsSync as $n,mkdirSync as kc,readdirSync as Mc,writeFileSync as Ic}from"fs";import{homedir as Ht}from"os";import{dirname as Us,resolve as He}from"path";import Rt from"process";import{join as Dc,relative as Fc,resolve as Ys}from"path";import ei from"process";import{existsSync as Oa,mkdirSync as up,readdirSync as hp,writeFileSync as dp}from"fs";import{homedir as en}from"os";import{dirname as gp,resolve as _e}from"path";import hr from"process";import{join as Nc,relative as Wc,resolve as Zs}from"path";import ti from"process";import{existsSync as Pa,mkdirSync as Ep,readdirSync as vp,writeFileSync as Sp}from"fs";import{dirname as Ap,resolve as ri}from"path";import En from"process";import{Buffer as At}from"buffer";import{createCipheriv as Lc,createDecipheriv as Gc,randomBytes as tn}from"crypto";import{closeSync as rn,createReadStream as qs,createWriteStream as Bc,existsSync as nn,fsyncSync as Xs,openSync as zs,writeFileSync as Vc}from"fs";import{access as _c,constants as Qs,mkdir as Hc,readdir as Fr,rename as ea,stat as jt,unlink as Nr,writeFile as sn}from"fs/promises";import{join as Kt}from"path";import Ge from"process";import{pipeline as jc}from"stream/promises";import{createGzip as ta}from"zlib";import Jt from"process";import pt from"process";import{Buffer as ht}from"buffer";import{createCipheriv as Kc,createDecipheriv as Jc,randomBytes as an}from"crypto";import{closeSync as on,createReadStream as ra,createWriteStream as Uc,existsSync as Wr,fsyncSync as ia,openSync as na,writeFileSync as Yc}from"fs";import{access as Zc,constants as sa,mkdir as qc,readdir as Lr,rename as aa,stat as Ut,unlink as Gr,writeFile as ln}from"fs/promises";import{isAbsolute as Xc,join as Yt,resolve as zc}from"path";import ce from"process";import{pipeline as Qc}from"stream/promises";import{createGzip as oa}from"zlib";import Zt from"process";import gt from"process";import Br from"process";import{existsSync as Vr}from"fs";import{resolve as cn}from"path";import{existsSync as ef}from"fs";import{existsSync as tf,readdirSync as rf}from"fs";import{extname as fn,resolve as la}from"path";import nf from"process";import{join as sf,relative as af,resolve as ca}from"path";import ii from"process";import{Buffer as dt}from"buffer";import{createCipheriv as of,createDecipheriv as lf,randomBytes as un}from"crypto";import{closeSync as hn,createReadStream as fa,createWriteStream as cf,existsSync as _r,fsyncSync as ua,openSync as ha,writeFileSync as ff}from"fs";import{access as uf,constants as da,mkdir as hf,readdir as Hr,rename as ma,stat as qt,unlink as jr,writeFile as dn}from"fs/promises";import{isAbsolute as df,join as Xt,resolve as mf}from"path";import fe from"process";import{pipeline as pf}from"stream/promises";import{createGzip as pa}from"zlib";import zt from"process";import yt from"process";import Kr from"process";import{existsSync as Jr}from"fs";import{resolve as mn}from"path";import{existsSync as gf}from"fs";class ka{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,a=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:s,hits:0,size:a}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!Hs(e))return!0;return js(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=Hs(r)?js(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 Ma{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),a=performance.now()-n;return this.recordMetric({operation:e,duration:a,timestamp:i,...r}),s}catch(s){let a=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:a,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 wf(e,t){this[e]=Cf.bind(null,t)}class In{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,a=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:s,hits:0,size:a}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!Ks(e))return!0;return Js(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=Ks(r)?Js(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 Dn{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),a=performance.now()-n;return this.recordMetric({operation:e,duration:a,timestamp:i,...r}),s}catch(s){let a=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:a,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 vf(e,t={}){let r=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return r?`${e}:${r}`:e}function Sf(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function bf(e){return e.getStats().size*2}function Fn(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&ye(t[0])&&"id"in t[0]&&t[0].id===3&&ye(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(ye(t)&&ye(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(ye(e)&&"arr"in e&&Array.isArray(e.arr)&&ye(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&ye(t[0])&&ye(e[0])){let n=[...t];for(let i of e)if(ye(i)&&"name"in i){if(!n.find((s)=>ye(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(ye(i)&&"path"in i){if(!n.find((s)=>ye(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((s)=>si(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(!ye(t)||!ye(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(ye(i)&&ye(r[n]))r[n]=Fn(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&ye(i[0])&&ye(r[n][0])){let s=[...i];for(let a of r[n])if(ye(a)&&"name"in a){if(!s.find((o)=>ye(o)&&("name"in o)&&o.name===a.name))s.push(a)}else if(ye(a)&&"path"in a){if(!s.find((o)=>ye(o)&&("path"in o)&&o.path===a.path))s.push(a)}else if(!s.some((o)=>si(o,a)))s.push(a);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let a of r[n])if(!s.includes(a))s.push(a);r[n]=s}else r[n]=i;else r[n]=i}return r}function si(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(!si(e[r],t[r]))return!1;return!0}if(ye(e)&&ye(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(!si(e[i],t[i]))return!1}return!0}return!1}function ye(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Af(e,t){if(!Pa(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 Fn(t,n)}catch{return null}}catch{return null}}async function xf({name:e="",cwd:t,defaultConfig:r}){let n=t||En.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let a of s)for(let o of i){let c=ri(n,`${a}${o}`),f=await Af(c,r);if(f!==null)return f}try{let a=ri(n,"package.json");if(Pa(a)){let o=(await import(a))[e];if(o&&typeof o==="object"&&!Array.isArray(o))try{return Fn(r,o)}catch{}}}catch{}return r}function Tf(e,t={}){let r=ti.cwd();while(r.includes("storage"))r=Zs(r,"..");let n=Zs(r,e||"");if(t?.relative)return Wc(ti.cwd(),n);return n}async function Rf(){try{let e=await xf({name:"clarity",defaultConfig:qr,cwd:ti.cwd(),endpoint:"",headers:{}});return{...qr,...e}}catch{return qr}}function Se(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Of(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof pt<"u"){let e=pt.type;if(e==="renderer"||e==="worker")return!1;return!!(pt.versions&&(pt.versions.node||pt.versions.bun))}return!1}class Da{async format(e){let t=await Of(),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:Jt.pid,hostname:t(),environment:Jt.env.NODE_ENV||"development",platform:Jt.platform,version:Jt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Jt.env.NODE_ENV||Jt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class ai{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={...Sn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Da,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??Ge.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{...Xr,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Xr};return{...Xr,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Sn.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 t=(async()=>{let n,i=0,s=3,a=1000;while(i<s)try{try{try{await _c(this.config.logDirectory,Qs.F_OK|Qs.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Hc(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let o=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:At.from(e);try{if(!nn(this.currentLogFile))await sn(this.currentLogFile,"",{mode:420});if(n=zs(this.currentLogFile,"a",420),Vc(n,o,{flag:"a"}),Xs(n),n!==void 0)rn(n),n=void 0;if((await jt(this.currentLogFile)).size===0){if(await sn(this.currentLogFile,o,{flag:"w",mode:420}),(await jt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(i<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let l=a*2**i;await new Promise((g)=>setTimeout(g,l)),i++;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(n!==void 0)try{rn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(o){if(i===s-1){let f=o,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),o}i++;let c=a*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,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 Kt(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 Kt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Kt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Se())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 e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,a],[,o])=>o.createdAt.getTime()-a.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,i);if(n.length>s)for(let[a]of n.slice(s))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return tn(16).toString("hex")}generateKey(){return tn(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=tn(16),n=Lc("aes-256-gcm",t,r),i=At.concat([n.update(e,"utf8"),n.final()]),s=n.getAuthTag();return{encrypted:At.concat([r,i,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=ta(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(At.from(At.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(Se())return;let e=await jt(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 Fr(this.config.logDirectory),s=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,o=`${r}.${a}`;if(await jt(r).catch(()=>null))try{if(await ea(r,o),t.compress)try{let c=`${o}.gz`;await this.compressLogFile(o,c),await Nr(o)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await sn(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await jt(r).catch(()=>null))await ea(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await Fr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of i.slice(t.maxFiles))await Nr(Kt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=qs(e),n=Bc(t),i=ta();await jc(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()})),nn(this.currentLogFile))try{let e=zs(this.currentLogFile,"r+");Xs(e),rn(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(!Se()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Fr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Nr(Kt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}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?ge.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:a=!0}=e,o=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(a)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let c=Ge.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${i}`;else if(s==="info"||s==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${ge.cyan(i)}`;if(!a)return f.trim();let u=o(f).trim().length,l=o(t).length,g=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(g)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,a)=>{let o=Number.parseInt(a,10);return o<t[0].length?String(t[0][o]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,a)=>{if(a==="%")return"%";if(n>=t.length)return s;let o=t[n++];switch(a){case"s":return String(o);case"d":case"i":return Number(o).toString();case"j":case"o":return JSON.stringify(o,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),a,o;if(t instanceof Error)a=t.message,o=t.stack;else a=this.formatMessage(t,r);if(this.fancy&&!Se()){let f=ja[e],u=this.options.showTags!==!1&&this.name?ge.gray(this.formatTag(this.name)):"",l;switch(e){case"debug":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:ge.gray(a),level:e}),console.error(l);break;case"info":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:a,level:e}),console.error(l);break;case"success":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:ge.green(a),level:e}),console.error(l);break;case"warning":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:a,level:e}),console.warn(l);break;case"error":if(l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:a,level:e}),console.error(l),o){let g=o.split(`
|
|
7
|
-
`);for(let d of g)if(d.trim()&&!d.includes(
|
|
8
|
-
`;if(
|
|
9
|
-
`;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(e){let t=performance.now();if(this.fancy&&!
|
|
10
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.fancy&&!
|
|
11
|
-
`),
|
|
12
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(
|
|
13
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(e,t=""){if(!this.enabled||!this.fancy||
|
|
14
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Se()||!Ge.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(Se()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Fr(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 i=Kt(this.config.logDirectory,n);if(e.before)try{if((await jt(i)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${i}:`,s);continue}r.push(i)}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 Nr(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 Zr(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&ue(t[0])&&"id"in t[0]&&t[0].id===3&&ue(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(ue(t)&&ue(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(ue(e)&&"arr"in e&&Array.isArray(e.arr)&&ue(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&ue(t[0])&&ue(e[0])){let n=[...t];for(let i of e)if(ue(i)&&"name"in i){if(!n.find((s)=>ue(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(ue(i)&&"path"in i){if(!n.find((s)=>ue(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((s)=>oi(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(!ue(t)||!ue(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(ue(i)&&ue(r[n]))r[n]=Zr(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&ue(i[0])&&ue(r[n][0])){let s=[...i];for(let a of r[n])if(ue(a)&&"name"in a){if(!s.find((o)=>ue(o)&&("name"in o)&&o.name===a.name))s.push(a)}else if(ue(a)&&"path"in a){if(!s.find((o)=>ue(o)&&("path"in o)&&o.path===a.path))s.push(a)}else if(!s.some((o)=>oi(o,a)))s.push(a);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let a of r[n])if(!s.includes(a))s.push(a);r[n]=s}else r[n]=i;else r[n]=i}return r}function Nn(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:Zr(e,t);if(Array.isArray(e))return r==="replace"?t:Zr(e,t);if(!ue(t)||!ue(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],a=n[i];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(a))if(r==="replace")n[i]=s;else n[i]=Zr(a,s);else if(ue(s)&&ue(a))n[i]=Nn(a,s,r);else n[i]=s}return n}function oi(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(!oi(e[r],t[r]))return!1;return!0}if(ue(e)&&ue(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(!oi(e[i],t[i]))return!1}return!0}return!1}function ue(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Ur(e,t,r="replace"){if(!Oa(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 Nn(t,i,r)}catch{return null}}catch{return null}}function Pf(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function s(a,o=[]){let c={...a};for(let[f,u]of Object.entries(a)){let l=[...o,f],g=(v)=>v.replace(/([A-Z])/g,"_$1").toUpperCase(),d=`${n}_${l.map(g).join("_")}`,$=`${n}_${l.map((v)=>v.toUpperCase()).join("_")}`;if(r)Ve.info(`Checking environment variable ${d} for config ${e}.${l.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))c[f]=s(u,l);else{let v=hr.env[d]||hr.env[$];if(v!==void 0){if(r)Ve.info(`Using environment variable ${v?d:$} for config ${e}.${l.join(".")}`);if(typeof u==="number")c[f]=Number(v);else if(typeof u==="boolean")c[f]=v.toLowerCase()==="true";else if(Array.isArray(u))try{let C=JSON.parse(v);if(Array.isArray(C))c[f]=C;else c[f]=v.split(",").map((x)=>x.trim())}catch{c[f]=v.split(",").map((C)=>C.trim())}else c[f]=v}}}return c}return s(i)}async function kf({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:s=!1,checkEnv:a=!0,arrayStrategy:o="replace"}){let c=a&&typeof i==="object"&&i!==null&&!Array.isArray(i)?Pf(e,i,s):i,f=r||hr.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)Ve.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${f}`);let l=[e,`.${e}`].filter(Boolean),g=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],$=t?[`${t}.config`,`.${t}.config`]:[],v=Array.from(new Set([f,_e(f,"config"),_e(f,".config"),n?_e(f,n):void 0].filter(Boolean)));for(let C of v){if(s)Ve.info(`Searching for configuration in: ${C}`);let x=[_e(f,"config"),_e(f,".config")].concat(n?[_e(f,n)]:[]).includes(C)?[...l,...g,...d,...$]:[...g,...l,...$,...d];for(let P of x)for(let R of u){let I=_e(C,`${P}${R}`),B=await Ur(I,c,o);if(B!==null){if(s)Ve.success(`Configuration loaded from: ${I}`);return B}}}if(e){let C=_e(en(),".config",e),x=["config",`${e}.config`];if(t)x.push(`${t}.config`);if(s)Ve.info(`Checking user config directory: ${C}`);for(let P of x)for(let R of u){let I=_e(C,`${P}${R}`),B=await Ur(I,c,o);if(B!==null){if(s)Ve.success(`Configuration loaded from user config directory: ${I}`);return B}}}if(e){let C=_e(en(),".config"),x=[`.${e}.config`];if(t)x.push(`.${t}.config`);if(s)Ve.info(`Checking user config directory for dotfile configs: ${C}`);for(let P of x)for(let R of u){let I=_e(C,`${P}${R}`),B=await Ur(I,c,o);if(B!==null){if(s)Ve.success(`Configuration loaded from user config directory dotfile: ${I}`);return B}}}if(e){let C=en(),x=[`.${e}.config`,`.${e}`];if(t)x.push(`.${t}.config`),x.push(`.${t}`);if(s)Ve.info(`Checking user home directory for dotfile configs: ${C}`);for(let P of x)for(let R of u){let I=_e(C,`${P}${R}`),B=await Ur(I,c,o);if(B!==null){if(s)Ve.success(`Configuration loaded from user home directory: ${I}`);return B}}}try{let C=_e(f,"package.json");if(Oa(C)){let x=await import(C),P=x[e];if(!P&&t){if(P=x[t],P&&s)Ve.success(`Using alias "${t}" configuration from package.json`)}if(P&&typeof P==="object"&&!Array.isArray(P))try{if(s)Ve.success(`Configuration loaded from package.json: ${P===x[e]?e:t}`);return Nn(c,P,o)}catch(R){if(s)Ve.warn("Failed to merge package.json config:",R)}}}catch(C){if(s)Ve.warn("Failed to load package.json:",C)}if(s)Ve.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function Mf(e,t={}){let r=ei.cwd();while(r.includes("storage"))r=Ys(r,"..");let n=Ys(r,e||"");if(t?.relative)return Fc(ei.cwd(),n);return n}async function If(){try{let e=await kf({name:"clarity",alias:"logging",defaultConfig:zr,cwd:ei.cwd()});return{...zr,...e||{}}}catch{return zr}}function Me(){if(gt.env.NODE_ENV==="test"||gt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Df(){if(gt.env.NODE_ENV==="test"||gt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof gt<"u"){let e=gt.type;if(e==="renderer"||e==="worker")return!1;return!!(gt.versions&&(gt.versions.node||gt.versions.bun))}return!1}class Fa{async format(e){let t=await Df(),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:Zt.pid,hostname:t(),environment:Zt.env.NODE_ENV||"development",platform:Zt.platform,version:Zt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Zt.env.NODE_ENV||Zt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class li{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={...bn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Fa,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??ce.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{...Qr,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Qr};return{...Qr,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:bn.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!Me()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,i=0,s=3,a=1000;while(i<s)try{try{try{await Zc(this.config.logDirectory,sa.F_OK|sa.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await qc(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let o=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ht.from(e);try{if(!Wr(this.currentLogFile))await ln(this.currentLogFile,"",{mode:420});if(n=na(this.currentLogFile,"a",420),Yc(n,o,{flag:"a"}),ia(n),n!==void 0)on(n),n=void 0;if((await Ut(this.currentLogFile)).size===0){if(await ln(this.currentLogFile,o,{flag:"w",mode:420}),(await Ut(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(i<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let l=a*2**i;await new Promise((g)=>setTimeout(g,l)),i++;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(n!==void 0)try{on(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(o){if(i===s-1){let f=o,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),o}i++;let c=a*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,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 Yt(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 Yt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Yt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Me())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 e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,a],[,o])=>o.createdAt.getTime()-a.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,i);if(n.length>s)for(let[a]of n.slice(s))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return an(16).toString("hex")}generateKey(){return an(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=an(16),n=Kc("aes-256-gcm",t,r),i=ht.isBuffer(e)?e:ht.from(e,"utf8"),s=n.update(i),a=n.final(),o=s.length+a.length,c=n.getAuthTag(),f=ht.allocUnsafe(16+o+16);return r.copy(f,0),s.copy(f,16),a.copy(f,16+s.length),c.copy(f,16+o),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=oa(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(ht.from(ht.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(Me())return;if(!this.shouldWriteToFile())return;let e=await Ut(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 Lr(this.config.logDirectory),s=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,o=`${r}.${a}`;if(await Ut(r).catch(()=>null))try{if(await aa(r,o),t.compress)try{let c=`${o}.gz`;await this.compressLogFile(o,c),await Gr(o)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await ln(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await Ut(r).catch(()=>null))await aa(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await Lr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of i.slice(t.maxFiles))await Gr(Yt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=ra(e),n=Uc(t),i=oa();await Qc(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()})),Wr(this.currentLogFile))try{let e=na(this.currentLogFile,"r+");ia(e),on(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(!Me()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Lr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Gr(Yt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}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()?ee.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Me())return!1;let e=typeof ce.env.NO_COLOR<"u",t=ce.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof ce.stderr<"u"&&ce.stderr.isTTY||typeof ce.stdout<"u"&&ce.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:a=!0}=e,o=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(a)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let c=ce.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${i}`;else if(s==="info"||s==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${ee.cyan(i)}`;if(!a)return f.trim();let u=o(f).trim().length,l=o(t).length,g=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(g)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,a)=>{let o=Number.parseInt(a,10);return o<t[0].length?String(t[0][o]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,a)=>{if(a==="%")return"%";if(n>=t.length)return s;let o=t[n++];switch(a){case"s":return String(o);case"d":case"i":return Number(o).toString();case"j":case"o":return JSON.stringify(o,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=ee.underline(ee.blue(n)),a=this.toAbsoluteFilePath(i);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let o=`file://${encodeURI(a)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${o}\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)=>ee.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>ee.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>ee.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>ee.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>ee.strikethrough(n)),t}supportsHyperlinks(){if(Me())return!1;let e=ce.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=ce.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Xc(t)||t.startsWith("./")||t.startsWith("../"))t=zc(t);else return null;return Wr(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),a,o;if(t instanceof Error)a=t.message,o=t.stack;else a=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let l=this.options.showIcons===!1?"":Ka[e],g=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:ee.gray(c),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:ee.green(c),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.error(d),o){let $=o.split(`
|
|
15
|
-
`);for(let
|
|
16
|
-
`;if(
|
|
17
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(i,s)=>{},finish:(i)=>{},interrupt:(i,s)=>{}};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()&&!
|
|
18
|
-
`);if(this[s==="warning"?"warn":s](i),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
19
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?
|
|
20
|
-
`),c=Math.max(...
|
|
21
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
22
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
23
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||
|
|
6
|
+
`;Ns(t,i)}}catch{}}var Xi=3,Ir=".dtsx-cache",bc="manifest.json";var Gs=ce(()=>{qi()});function Vt(e){return Bs[e]>=Bs[Fr]}function Tc(){if(!xc)return"";return`[${new Date().toISOString().slice(11,23)}] `}function Rc(e,t){let r=Tc();if(e||r)return[`${r}${e}`,...t];return t}function _t(e,t,r){let n=Rc(t,r);if(Vs){Vs(e,...n);return}switch(e){case"debug":console.debug(...n);break;case"info":console.log(...n);break;case"warn":console.warn(...n);break;case"error":console.error(...n);break}}function _s(e){return{debug:(...t)=>{if(Vt("debug"))_t("debug",e,t)},info:(...t)=>{if(Vt("info"))_t("info",e,t)},warn:(...t)=>{if(Vt("warn"))_t("warn",e,t)},error:(...t)=>{if(Vt("error"))_t("error",e,t)},setLevel:(t)=>{Fr=t},getLevel:()=>Fr,child:(t)=>{let r=e?`${e}:${t}`:`[${t}]`;return _s(r)},time:(t)=>{let r=performance.now();return()=>{let n=performance.now()-r;if(Vt("debug"))_t("debug",e,[`${t}: ${n.toFixed(2)}ms`])}},progress:(t)=>{if(Vt("info"))if(typeof process<"u"&&process.stdout?.isTTY)process.stdout.write(`\r${e} ${t}`);else _t("info",e,[t])}}}function en(e){Fr=e}var Bs,Fr="info",Ac="[dtsx]",xc=!1,Vs=null,K;var Hs=ce(()=>{Bs={debug:0,info:1,warn:2,error:3,silent:4};K=_s(Ac)});import Oc from"process";import{existsSync as js,statSync as Ks}from"fs";import{existsSync as Pc,mkdirSync as Xm,readdirSync as zm,readFileSync as kc,writeFileSync as Qm}from"fs";import{homedir as Ht}from"os";import{dirname as rp,resolve as ze}from"path";import pi from"process";import{existsSync as Js,statSync as Us}from"fs";import{existsSync as En,mkdirSync as Mc,readdirSync as Dc,writeFileSync as Ic}from"fs";import{homedir as jt}from"os";import{dirname as Ys,resolve as je}from"path";import Ot from"process";import{join as Fc,relative as Nc,resolve as Zs}from"path";import ti from"process";import{existsSync as ko,mkdirSync as hp,readdirSync as dp,writeFileSync as mp}from"fs";import{homedir as tn}from"os";import{dirname as yp,resolve as He}from"path";import dr from"process";import{join as Wc,relative as Lc,resolve as qs}from"path";import ri from"process";import{existsSync as Mo,mkdirSync as vp,readdirSync as Sp,writeFileSync as bp}from"fs";import{dirname as xp,resolve as ii}from"path";import vn from"process";import{Buffer as xt}from"buffer";import{createCipheriv as Gc,createDecipheriv as Bc,randomBytes as rn}from"crypto";import{closeSync as nn,createReadStream as Xs,createWriteStream as Vc,existsSync as sn,fsyncSync as zs,openSync as Qs,writeFileSync as _c}from"fs";import{access as Hc,constants as eo,mkdir as jc,readdir as Nr,rename as to,stat as Kt,unlink as Wr,writeFile as on}from"fs/promises";import{join as Jt}from"path";import Be from"process";import{pipeline as Kc}from"stream/promises";import{createGzip as ro}from"zlib";import Ut from"process";import gt from"process";import{Buffer as dt}from"buffer";import{createCipheriv as Jc,createDecipheriv as Uc,randomBytes as an}from"crypto";import{closeSync as ln,createReadStream as io,createWriteStream as Yc,existsSync as Lr,fsyncSync as no,openSync as so,writeFileSync as Zc}from"fs";import{access as qc,constants as oo,mkdir as Xc,readdir as Gr,rename as ao,stat as Yt,unlink as Br,writeFile as cn}from"fs/promises";import{isAbsolute as zc,join as Zt,resolve as Qc}from"path";import fe from"process";import{pipeline as ef}from"stream/promises";import{createGzip as lo}from"zlib";import qt from"process";import yt from"process";import Vr from"process";import{existsSync as _r}from"fs";import{resolve as fn}from"path";import{existsSync as tf}from"fs";import{existsSync as rf,readdirSync as nf}from"fs";import{extname as un,resolve as co}from"path";import sf from"process";import{join as of,relative as af,resolve as fo}from"path";import ni from"process";import{Buffer as mt}from"buffer";import{createCipheriv as lf,createDecipheriv as cf,randomBytes as hn}from"crypto";import{closeSync as dn,createReadStream as uo,createWriteStream as ff,existsSync as Hr,fsyncSync as ho,openSync as mo,writeFileSync as uf}from"fs";import{access as hf,constants as po,mkdir as df,readdir as jr,rename as go,stat as Xt,unlink as Kr,writeFile as mn}from"fs/promises";import{isAbsolute as mf,join as zt,resolve as pf}from"path";import ue from"process";import{pipeline as gf}from"stream/promises";import{createGzip as yo}from"zlib";import Qt from"process";import Ct from"process";import Jr from"process";import{existsSync as Ur}from"fs";import{resolve as pn}from"path";import{existsSync as yf}from"fs";class Do{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(!js(e))return!0;return Ks(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=js(r)?Ks(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 Io{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 $f(e,t){this[e]=wf.bind(null,t)}class In{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(!Js(e))return!0;return Us(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=Js(r)?Us(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 Fn{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 Sf(e,t={}){let r=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return r?`${e}:${r}`:e}function bf(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Af(e){return e.getStats().size*2}function Nn(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Ce(t[0])&&"id"in t[0]&&t[0].id===3&&Ce(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Ce(t)&&Ce(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(Ce(e)&&"arr"in e&&Array.isArray(e.arr)&&Ce(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Ce(t[0])&&Ce(e[0])){let n=[...t];for(let i of e)if(Ce(i)&&"name"in i){if(!n.find((s)=>Ce(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(Ce(i)&&"path"in i){if(!n.find((s)=>Ce(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((s)=>oi(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(!Ce(t)||!Ce(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(Ce(i)&&Ce(r[n]))r[n]=Nn(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&Ce(i[0])&&Ce(r[n][0])){let s=[...i];for(let o of r[n])if(Ce(o)&&"name"in o){if(!s.find((a)=>Ce(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(Ce(o)&&"path"in o){if(!s.find((a)=>Ce(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((a)=>oi(a,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 oi(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(!oi(e[r],t[r]))return!1;return!0}if(Ce(e)&&Ce(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(!oi(e[i],t[i]))return!1}return!0}return!1}function Ce(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function xf(e,t){if(!Mo(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 Nn(t,n)}catch{return null}}catch{return null}}async function Tf({name:e="",cwd:t,defaultConfig:r}){let n=t||vn.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let a of i){let c=ii(n,`${o}${a}`),f=await xf(c,r);if(f!==null)return f}try{let o=ii(n,"package.json");if(Mo(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return Nn(r,a)}catch{}}}catch{}return r}function Rf(e,t={}){let r=ri.cwd();while(r.includes("storage"))r=qs(r,"..");let n=qs(r,e||"");if(t?.relative)return Lc(ri.cwd(),n);return n}async function Of(){try{let e=await Tf({name:"clarity",defaultConfig:Xr,cwd:ri.cwd(),endpoint:"",headers:{}});return{...Xr,...e}}catch{return Xr}}function be(){if(gt.env.NODE_ENV==="test"||gt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Pf(){if(gt.env.NODE_ENV==="test"||gt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof gt<"u"){let e=gt.type;if(e==="renderer"||e==="worker")return!1;return!!(gt.versions&&(gt.versions.node||gt.versions.bun))}return!1}class No{async format(e){let t=await Pf(),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:Ut.pid,hostname:t(),environment:Ut.env.NODE_ENV||"development",platform:Ut.platform,version:Ut.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ut.env.NODE_ENV||Ut.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class ai{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={...bn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new No,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??Be.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{...zr,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...zr};return{...zr,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:bn.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 t=(async()=>{let n,i=0,s=3,o=1000;while(i<s)try{try{try{await Hc(this.config.logDirectory,eo.F_OK|eo.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await jc(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:xt.from(e);try{if(!sn(this.currentLogFile))await on(this.currentLogFile,"",{mode:420});if(n=Qs(this.currentLogFile,"a",420),_c(n,a,{flag:"a"}),zs(n),n!==void 0)nn(n),n=void 0;if((await Kt(this.currentLogFile)).size===0){if(await on(this.currentLogFile,a,{flag:"w",mode:420}),(await Kt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(i<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let l=o*2**i;await new Promise((g)=>setTimeout(g,l)),i++;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(n!==void 0)try{nn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===s-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}i++;let c=o*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,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 Jt(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 Jt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Jt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(be())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 e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,o],[,a])=>a.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,i);if(n.length>s)for(let[o]of n.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return rn(16).toString("hex")}generateKey(){return rn(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=rn(16),n=Gc("aes-256-gcm",t,r),i=xt.concat([n.update(e,"utf8"),n.final()]),s=n.getAuthTag();return{encrypted:xt.concat([r,i,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=ro(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(xt.from(xt.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(be())return;let e=await Kt(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 Nr(this.config.logDirectory),s=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${o}`;if(await Kt(r).catch(()=>null))try{if(await to(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await Wr(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await on(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await Kt(r).catch(()=>null))await to(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await Nr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await Wr(Jt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Xs(e),n=Vc(t),i=ro();await Kc(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()})),sn(this.currentLogFile))try{let e=Qs(this.currentLogFile,"r+");zs(e),nn(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(!be()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Nr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Wr(Jt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}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?ye.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,a=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let c=Be.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${i}`;else if(s==="info"||s==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${ye.cyan(i)}`;if(!o)return f.trim();let u=a(f).trim().length,l=a(t).length,g=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(g)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let a=Number.parseInt(o,10);return a<t[0].length?String(t[0][a]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let a=t[n++];switch(o){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,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,a;if(t instanceof Error)o=t.message,a=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!be()){let f=Jo[e],u=this.options.showTags!==!1&&this.name?ye.gray(this.formatTag(this.name)):"",l;switch(e){case"debug":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:ye.gray(o),level:e}),console.error(l);break;case"info":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:o,level:e}),console.error(l);break;case"success":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:ye.green(o),level:e}),console.error(l);break;case"warning":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:o,level:e}),console.warn(l);break;case"error":if(l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:o,level:e}),console.error(l),a){let g=a.split(`
|
|
7
|
+
`);for(let d of g)if(d.trim()&&!d.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:ye.gray(` ${d}`),level:e,showTimestamp:!1}))}break}}else if(!be()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),a)console.error(a)}if(!this.shouldLog(e))return;let c=`${s} ${this.environment}.${e.toUpperCase()}: ${o}
|
|
8
|
+
`;if(a)c+=`${a}
|
|
9
|
+
`;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(e){let t=performance.now();if(this.fancy&&!be()){let r=this.options.showTags!==!1&&this.name?ye.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:ye.blue("\u25D0"),tag:r,message:`${ye.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,a=this.formatConsoleTimestamp(o),c=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
|
|
10
|
+
`,c=c.replace(this.ANSI_PATTERN,""),this.fancy&&!be()){let f=this.options.showTags!==!1&&this.name?ye.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:ye.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!be())console.error(c.trim());await this.writeToFile(c)}}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 ai(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(be())throw Error("createReadStream is not supported in browser environments");if(!sn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Xs(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=xt.isBuffer(e)?e:xt.from(e,"base64"),i=n.slice(0,16),s=n.slice(-16),o=n.slice(16,-16),a=Bc("aes-256-gcm",r,i);return a.setAuthTag(s),xt.concat([a.update(o),a.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 be()}isServerMode(){return!be()}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&&!be()){let s=e.split(`
|
|
11
|
+
`),o=Math.max(...s.map((u)=>u.length))+2,a=`\u250C${"\u2500".repeat(o)}\u2510`,c=`\u2514${"\u2500".repeat(o)}\u2518`,f=s.map((u)=>{let l=" ".repeat(o-u.length-2);return`\u2502 ${u}${l} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:ye.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:ye.cyan(a)})),f.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:ye.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:ye.cyan(c),showTimestamp:!1}))}else if(!be())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let i=`${n} ${this.environment}.INFO: [BOX] ${e}
|
|
12
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(be())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${ye.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();Be.stdin.removeListener("data",r);try{if(typeof Be.stdin.setRawMode==="function")Be.stdin.setRawMode(!1)}catch{}Be.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof Be.stdin.setRawMode==="function")Be.stdin.setRawMode(!0)}catch{}Be.stdin.resume(),Be.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 i=/%([sdijfo%])/g,s=0;if(r=e.replace(i,(o,a)=>{if(a==="%")return"%";if(s>=t.length)return o;let c=t[s++];switch(a){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 o}}),s<t.length)r+=` ${t.slice(s).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`}if(this.fancy&&!be()){let i=this.options.showTags!==!1&&this.name?ye.gray(this.formatTag(this.name)):"",s=ye.blue("\u25D0");console.error(`${s} ${i} ${ye.cyan(r)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
13
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(e,t=""){if(!this.enabled||!this.fancy||be()||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:(n,i)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||be())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,n)),i!==void 0)this.activeProgressBar.message=i;let s=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,s)},finish:(n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||be())return;if(this.activeProgressBar.current=this.activeProgressBar.total,n!==void 0)this.activeProgressBar.message=n;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(n,i="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||be())return;Be.stdout.write(`${"\r".padEnd(Be.stdout.columns||80)}\r`),this.log(i,n),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||be()||!Be.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=ye.green("\u2501".repeat(n)),o=ye.gray("\u2501".repeat(i)),a=`[${s}${o}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=t||r===100?ye.green("\u2713"):ye.blue("\u25B6"),l=this.options.showTags!==!1&&this.name?` ${ye.gray(this.formatTag(this.name))}`:"",g=`\r${u}${l} ${a} ${c}${f}`,d=Be.stdout.columns||80,E=" ".repeat(Math.max(0,d-g.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${g}${E}`,Be.stdout.write(e.lastRenderedLine),t)Be.stdout.write(`
|
|
14
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||be()||!Be.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(be()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Nr(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 i=Jt(this.config.logDirectory,n);if(e.before)try{if((await Kt(i)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${i}:`,s);continue}r.push(i)}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 Wr(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 qr(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&he(t[0])&&"id"in t[0]&&t[0].id===3&&he(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(he(t)&&he(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(he(e)&&"arr"in e&&Array.isArray(e.arr)&&he(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&he(t[0])&&he(e[0])){let n=[...t];for(let i of e)if(he(i)&&"name"in i){if(!n.find((s)=>he(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(he(i)&&"path"in i){if(!n.find((s)=>he(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((s)=>li(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(!he(t)||!he(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(he(i)&&he(r[n]))r[n]=qr(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&he(i[0])&&he(r[n][0])){let s=[...i];for(let o of r[n])if(he(o)&&"name"in o){if(!s.find((a)=>he(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(he(o)&&"path"in o){if(!s.find((a)=>he(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((a)=>li(a,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 Wn(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:qr(e,t);if(Array.isArray(e))return r==="replace"?t:qr(e,t);if(!he(t)||!he(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]=qr(o,s);else if(he(s)&&he(o))n[i]=Wn(o,s,r);else n[i]=s}return n}function li(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(!li(e[r],t[r]))return!1;return!0}if(he(e)&&he(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(!li(e[i],t[i]))return!1}return!0}return!1}function he(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Yr(e,t,r="replace"){if(!ko(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 Wn(t,i,r)}catch{return null}}catch{return null}}function kf(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function s(o,a=[]){let c={...o};for(let[f,u]of Object.entries(o)){let l=[...a,f],g=(S)=>S.replace(/([A-Z])/g,"_$1").toUpperCase(),d=`${n}_${l.map(g).join("_")}`,E=`${n}_${l.map((S)=>S.toUpperCase()).join("_")}`;if(r)_e.info(`Checking environment variable ${d} for config ${e}.${l.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))c[f]=s(u,l);else{let S=dr.env[d]||dr.env[E];if(S!==void 0){if(r)_e.info(`Using environment variable ${S?d:E} for config ${e}.${l.join(".")}`);if(typeof u==="number")c[f]=Number(S);else if(typeof u==="boolean")c[f]=S.toLowerCase()==="true";else if(Array.isArray(u))try{let C=JSON.parse(S);if(Array.isArray(C))c[f]=C;else c[f]=S.split(",").map((T)=>T.trim())}catch{c[f]=S.split(",").map((C)=>C.trim())}else c[f]=S}}}return c}return s(i)}async function Mf({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:s=!1,checkEnv:o=!0,arrayStrategy:a="replace"}){let c=o&&typeof i==="object"&&i!==null&&!Array.isArray(i)?kf(e,i,s):i,f=r||dr.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)_e.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${f}`);let l=[e,`.${e}`].filter(Boolean),g=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],E=t?[`${t}.config`,`.${t}.config`]:[],S=Array.from(new Set([f,He(f,"config"),He(f,".config"),n?He(f,n):void 0].filter(Boolean)));for(let C of S){if(s)_e.info(`Searching for configuration in: ${C}`);let T=[He(f,"config"),He(f,".config")].concat(n?[He(f,n)]:[]).includes(C)?[...l,...g,...d,...E]:[...g,...l,...E,...d];for(let k of T)for(let O of u){let I=He(C,`${k}${O}`),V=await Yr(I,c,a);if(V!==null){if(s)_e.success(`Configuration loaded from: ${I}`);return V}}}if(e){let C=He(tn(),".config",e),T=["config",`${e}.config`];if(t)T.push(`${t}.config`);if(s)_e.info(`Checking user config directory: ${C}`);for(let k of T)for(let O of u){let I=He(C,`${k}${O}`),V=await Yr(I,c,a);if(V!==null){if(s)_e.success(`Configuration loaded from user config directory: ${I}`);return V}}}if(e){let C=He(tn(),".config"),T=[`.${e}.config`];if(t)T.push(`.${t}.config`);if(s)_e.info(`Checking user config directory for dotfile configs: ${C}`);for(let k of T)for(let O of u){let I=He(C,`${k}${O}`),V=await Yr(I,c,a);if(V!==null){if(s)_e.success(`Configuration loaded from user config directory dotfile: ${I}`);return V}}}if(e){let C=tn(),T=[`.${e}.config`,`.${e}`];if(t)T.push(`.${t}.config`),T.push(`.${t}`);if(s)_e.info(`Checking user home directory for dotfile configs: ${C}`);for(let k of T)for(let O of u){let I=He(C,`${k}${O}`),V=await Yr(I,c,a);if(V!==null){if(s)_e.success(`Configuration loaded from user home directory: ${I}`);return V}}}try{let C=He(f,"package.json");if(ko(C)){let T=await import(C),k=T[e];if(!k&&t){if(k=T[t],k&&s)_e.success(`Using alias "${t}" configuration from package.json`)}if(k&&typeof k==="object"&&!Array.isArray(k))try{if(s)_e.success(`Configuration loaded from package.json: ${k===T[e]?e:t}`);return Wn(c,k,a)}catch(O){if(s)_e.warn("Failed to merge package.json config:",O)}}}catch(C){if(s)_e.warn("Failed to load package.json:",C)}if(s)_e.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function Df(e,t={}){let r=ti.cwd();while(r.includes("storage"))r=Zs(r,"..");let n=Zs(r,e||"");if(t?.relative)return Nc(ti.cwd(),n);return n}async function If(){try{let e=await Mf({name:"clarity",alias:"logging",defaultConfig:Qr,cwd:ti.cwd()});return{...Qr,...e||{}}}catch{return Qr}}function De(){if(yt.env.NODE_ENV==="test"||yt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ff(){if(yt.env.NODE_ENV==="test"||yt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof yt<"u"){let e=yt.type;if(e==="renderer"||e==="worker")return!1;return!!(yt.versions&&(yt.versions.node||yt.versions.bun))}return!1}class Wo{async format(e){let t=await Ff(),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:qt.pid,hostname:t(),environment:qt.env.NODE_ENV||"development",platform:qt.platform,version:qt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:qt.env.NODE_ENV||qt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class ci{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={...An},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Wo,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??fe.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{...ei,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ei};return{...ei,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:An.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!De()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,i=0,s=3,o=1000;while(i<s)try{try{try{await qc(this.config.logDirectory,oo.F_OK|oo.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Xc(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:dt.from(e);try{if(!Lr(this.currentLogFile))await cn(this.currentLogFile,"",{mode:420});if(n=so(this.currentLogFile,"a",420),Zc(n,a,{flag:"a"}),no(n),n!==void 0)ln(n),n=void 0;if((await Yt(this.currentLogFile)).size===0){if(await cn(this.currentLogFile,a,{flag:"w",mode:420}),(await Yt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(i<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let l=o*2**i;await new Promise((g)=>setTimeout(g,l)),i++;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(n!==void 0)try{ln(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===s-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}i++;let c=o*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,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 Zt(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 Zt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Zt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(De())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 e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,o],[,a])=>a.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,i);if(n.length>s)for(let[o]of n.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return an(16).toString("hex")}generateKey(){return an(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=an(16),n=Jc("aes-256-gcm",t,r),i=dt.isBuffer(e)?e:dt.from(e,"utf8"),s=n.update(i),o=n.final(),a=s.length+o.length,c=n.getAuthTag(),f=dt.allocUnsafe(16+a+16);return r.copy(f,0),s.copy(f,16),o.copy(f,16+s.length),c.copy(f,16+a),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=lo(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(dt.from(dt.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(De())return;if(!this.shouldWriteToFile())return;let e=await Yt(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 Gr(this.config.logDirectory),s=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${o}`;if(await Yt(r).catch(()=>null))try{if(await ao(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await Br(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await cn(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await Yt(r).catch(()=>null))await ao(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await Gr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await Br(Zt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=io(e),n=Yc(t),i=lo();await ef(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()})),Lr(this.currentLogFile))try{let e=so(this.currentLogFile,"r+");no(e),ln(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(!De()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Gr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Br(Zt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}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()?te.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||De())return!1;let e=typeof fe.env.NO_COLOR<"u",t=fe.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof fe.stderr<"u"&&fe.stderr.isTTY||typeof fe.stdout<"u"&&fe.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,a=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let c=fe.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${i}`;else if(s==="info"||s==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${te.cyan(i)}`;if(!o)return f.trim();let u=a(f).trim().length,l=a(t).length,g=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(g)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let a=Number.parseInt(o,10);return a<t[0].length?String(t[0][a]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let a=t[n++];switch(o){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,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=te.underline(te.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(o)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${a}\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)=>te.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>te.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>te.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>te.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>te.strikethrough(n)),t}supportsHyperlinks(){if(De())return!1;let e=fe.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=fe.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(zc(t)||t.startsWith("./")||t.startsWith("../"))t=Qc(t);else return null;return Lr(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,a;if(t instanceof Error)o=t.message,a=t.stack;else o=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let l=this.options.showIcons===!1?"":Uo[e],g=this.options.showTags!==!1&&this.name?te.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:te.gray(c),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:te.green(c),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.error(d),a){let E=a.split(`
|
|
15
|
+
`);for(let S of E)if(S.trim()&&!S.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:te.gray(` ${S}`),level:e,showTimestamp:!1}))}break}}else if(!De()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),a)console.error(a)}if(!this.shouldLog(e))return;let u=`${s} ${this.environment}.${e.toUpperCase()}: ${f}
|
|
16
|
+
`;if(a)u+=`${a}
|
|
17
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(i,s)=>{},finish:(i)=>{},interrupt:(i,s)=>{}};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()&&!De()&&fe.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(i,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,i),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!De()&&fe.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,s="info")=>{if(!De()&&fe.stdout.isTTY)fe.stdout.write(`
|
|
18
|
+
`);if(this[s==="warning"?"warn":s](i),this.activeProgressBar&&this.shouldStyleConsole()&&!De()&&fe.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?te.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":te.blue("\u25D0"),tag:r,message:`${te.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,a=this.formatConsoleTimestamp(o),c=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
|
|
19
|
+
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?te.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":te.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!De())console.error(c.trim());if(this.shouldWriteToFile())await this.writeToFile(c)}}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 ci(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(De())throw Error("createReadStream is not supported in browser environments");if(!Lr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return io(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=dt.isBuffer(e)?e:dt.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),a=Uc("aes-256-gcm",r,i);a.setAuthTag(s);let c=a.update(o),f=a.final(),u=c.length+f.length,l=dt.allocUnsafe(u);return c.copy(l,0),f.copy(l,c.length),l.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 De()}isServerMode(){return!De()}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 a=i.split(`
|
|
20
|
+
`),c=Math.max(...a.map((g)=>g.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,l=a.map((g)=>this.formatConsoleMessage({timestamp:r,message:te.cyan(g),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:te.cyan(f),showTimestamp:!1})),l.forEach((g)=>console.error(g)),console.error(this.formatConsoleMessage({timestamp:r,message:te.cyan(u),showTimestamp:!1}))}else if(!De())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
|
|
21
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(De())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${te.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();fe.stdin.removeListener("data",r);try{if(typeof fe.stdin.setRawMode==="function")fe.stdin.setRawMode(!1)}catch{}fe.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof fe.stdin.setRawMode==="function")fe.stdin.setRawMode(!0)}catch{}fe.stdin.resume(),fe.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,a=0;if(r=e.replace(o,(c,f)=>{if(f==="%")return"%";if(a>=t.length)return c;let u=t[a++];switch(f){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return c}}),a<t.length)r+=` ${t.slice(a).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?te.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${te.blue("\u25D0")} `;console.error(`${a}${o} ${te.cyan(n)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
22
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!fe.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=te.green("\u2501".repeat(n)),o=te.gray("\u2501".repeat(i)),a=`[${s}${o}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?te.green("\u2713"):te.blue("\u25B6"),l=this.options.showTags!==!1&&this.name?` ${te.gray(this.formatTag(this.name))}`:"",g=`\r${u}${l} ${a} ${c}${f}`,d=fe.stdout.columns||80,E=" ".repeat(Math.max(0,d-g.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${g}${E}`,fe.stdout.write(e.lastRenderedLine),t)fe.stdout.write(`
|
|
23
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||De()||!fe.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(De()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Gr(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 i=Zt(this.config.logDirectory,n);if(e.before)try{if((await Yt(i)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${i}:`,s);continue}r.push(i)}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 Br(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 Lo(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let a=0;a<=r;a++)try{return await e()}catch(c){if(o=c instanceof Error?c:Error(String(c)),a===r||!i(o))break;if(n>0)await new Promise((f)=>setTimeout(f,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function Go(e){return e instanceof Ze}function Nf(e){return e instanceof fi}function Wf(e){if(Go(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((t)=>e.message.toLowerCase().includes(t.toLowerCase()))}class gi{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:a=!1,trackPerformance:c=!0}=r,f=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),l={...t};return this.processObject(l,[],u,{useCamelCase:i,useBackwardCompatibility:s,customParsers:o,verbose:a,configName:e}),{config:l,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return gr.track("applyEnvironmentVariables",f,{configName:e});return f()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],a=o.map((u)=>this.formatEnvKey(u,n.useCamelCase)),c=`${r}_${a.join("_")}`,f=n.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,n);else{let u=Vr.env[c]||(f?Vr.env[f]:void 0);if(u!==void 0){if(n.verbose){let l=Vr.env[c]?c:f}try{e[i]=this.parseEnvironmentValue(u,typeof s,c,n.customParsers,n.configName)}catch(l){if(l instanceof ui)throw l;throw Tt.envVar(c,u,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 Tt.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(Vr.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],a=`${r}_${o.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,n);else n.push({key:a,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}:
|
|
24
24
|
|
|
25
25
|
`;for(let n of e)r+=`${n.key}
|
|
26
26
|
`,r+=` Type: ${n.type}
|
|
@@ -32,25 +32,25 @@ ${Ir}/
|
|
|
32
32
|
`;r+=`| Variable | Type | Description | Example |
|
|
33
33
|
`,r+=`|----------|------|-------------|----------|
|
|
34
34
|
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
35
|
-
`;return r}}function Wf(e,t){let r=_a("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function La(e,t,r={}){return Ga(e,t,r,new WeakMap)}function Ga(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:a}=r;if(t===null||t===void 0)return s?e:t;if(a){let o=a(e,t);if(o!==void 0)return o}if(Array.isArray(t)||Array.isArray(e))return Ba(e,t,i,n);if(!ze(t)||!ze(e))return t;return Vf(e,t,r,n)}function Ba(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 Lf(e,t);case"smart":return Gf(e,t,n);default:return t}return t}function Lf(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>vn(i,n)))r.push(n);return r}function Gf(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(ze(t[0])&&ze(e[0]))return Bf(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 Bf(e,t,r){let n=[...t];for(let i of e){if(!ze(i)){n.push(i);continue}let s=["id","name","key","path","type"],a=!1;for(let o of s)if(o in i){if(n.find((c)=>ze(c)&&(o in c)&&c[o]===i[o])){a=!0;break}}if(!a)n.push(i)}return n}function Vf(e,t,r,n){let i=t;if(ze(i)&&n.has(i))return n.get(i);let s={...e};if(ze(i))n.set(i,s);for(let a in i){if(!Object.prototype.hasOwnProperty.call(i,a))continue;let o=i[a],c=s[a];if(r.skipNullish&&(o===null||o===void 0))continue;if(o===null||o===void 0){s[a]=o;continue}if(ze(o)&&ze(c))s[a]=Ga(c,o,r,n);else if(Array.isArray(o)||Array.isArray(c))s[a]=Ba(c,o,r.arrayMergeMode||"smart",n);else s[a]=o}return s}function Wn(e,t,r="replace"){return La(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function vn(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(!vn(e[r],t[r]))return!1;return!0}if(ze(e)&&ze(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(!vn(e[i],t[i]))return!1}return!0}return!1}function ze(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class gi{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:a=!0,verbose:o=!1}=r;if(i){let f=Qt.getWithFileCheck("file",e);if(f){if(o)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!Vr(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,g="default"in u,d=Object.keys(u).length>0;if(!g&&!d)throw new dr(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new dr(e,Error("Configuration must export a valid object"),"unknown");let $={config:Wn(t,l,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)Qt.setWithFileCheck("file",$,e,s);return $}catch(f){throw f instanceof Error?xt.configLoad(e,f):xt.configLoad(e,Error(String(f)))}};if(a)return pr.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let a of this.extensions)i.push(cn(t,`${s}${a}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return Na(async()=>{return Vr(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Vr(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let a of this.extensions){let o=cn(e,`${s}${a}`);if(await this.checkFileAccess(o))n.push(o)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let a of s)if(this.looksLikeConfigFile(a)){let o=cn(e,a);if(await this.checkFileAccess(o))n.push(o)}}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((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!Vr(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 Ln{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:a=[],trackPerformance:o=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],g={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:a,trackPerformance:o,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,g);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...a],g);else return this.validateWithJSONSchema(e,t,g)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(o)return await pr.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!ef(t))throw new mr(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 mr(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 a=Array.isArray(e)?"array":typeof e,o=Array.isArray(t.type)?t.type:[t.type];if(!o.includes(a)){if(n.push({path:r,message:`Expected type ${o.join(" or ")}, got ${a}`,expected:o.join(" or "),actual:a,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 a=0;a<e.length;a++){let o=r?`${r}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(e[a],t.items,o,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let a=e;if(s.validateRequired&&t.required){for(let o of t.required)if(!(o in a)){if(n.push({path:r?`${r}.${o}`:o,message:`Missing required property '${o}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[o,c]of Object.entries(t.properties))if(o in a){let f=r?`${r}.${o}`:o;if(this.validateObjectAgainstSchema(a[o],c,f,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let o=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(a))if(!o.has(c))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let a=this.getValueByPath(e,s.path),o=this.validateWithRule(a,s,s.path);if(n.push(...o),r.stopOnFirstError&&n.length>0)break}catch(a){n.push({path:s.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,a]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(a)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Ua},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Gn{fileLoader=new gi;envProcessor=new pi;validator=new Ln;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...a}=e;try{if(r?.enabled){let c=this.checkCache(a.name||"",a);if(c)return c}let o;try{o=await this.loadConfigurationStrategies(a,!0,r)}catch(c){let f=a.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`No configuration file found for "${a.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),l=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),g=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(g||u))throw c;if(l&&(!f||!g))o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(i||s)await this.validateConfiguration(o.config,i,s,a.name);if(r?.enabled&&o)this.cacheResult(a.name||"",o,r,a);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:a.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)at.warn(`Slow configuration loading detected: ${c.duration}ms for ${a.name}`);o.metrics=c}return o}catch(o){let c=Date.now()-t;throw at.error(`Configuration loading failed after ${c}ms:`,[o instanceof Error?o:Error(String(o))]),o}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:a,defaultConfig:o,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=s||Rt.cwd(),g=[],d=await this.loadLocalConfiguration(n,i,l,a,o,f,u,c,r);if(d)return g.push(...this.getLocalSearchPaths(n,i,l,a)),this.finalizeResult(d,g,c,n,u);let $=await this.loadHomeConfiguration(n,i,o,f,u,c);if($)return g.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult($,g,c,n,u);let v=await this.loadPackageJsonConfiguration(n,i,l,o,f,u,c);if(v)return g.push(He(l,"package.json")),this.finalizeResult(v,g,c,n,u);if(g.push(...this.getAllSearchPaths(n,i,l,a)),t)throw xt.configNotFound(n,g,i);return{...await this.applyEnvironmentVariables(n,o,c,u),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,a,o,c){let f=o?ur(e,i,a):i,u=this.getLocalDirectories(r,n);for(let l of u){if(a)at.info(`Searching for configuration in: ${l}`);let g=this.fileLoader.generateConfigPaths(e,l,t),d=await this.fileLoader.tryLoadFromPaths(g,f,{arrayStrategy:s,verbose:a,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(d){if(a)at.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let a=s?ur(e,r,i):r,o=[He(Ht(),".config",e),He(Ht(),".config"),Ht()];for(let c of o){if(i)at.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,a,{arrayStrategy:n,verbose:i});if(u){if(i)at.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,a){let o=a?ur(e,n,s):n;try{let c=He(r,"package.json");if(!$n(c))return null;let f=await import(c),u=f[e],l=e;if(!u&&t)u=f[t],l=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)at.success(`Configuration loaded from package.json: ${l}`);return{config:Wn(o,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)at.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:ur(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((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(i.length>0)throw xt.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Qt.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);Qt.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,He(e,"config"),He(e,".config"),t?He(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(He(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let a of i)s.push(...this.fileLoader.generateConfigPaths(e,a,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[He(Ht(),".config",e),He(Ht(),".config"),Ht()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function ga(e){let t=!(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")),r=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return t||r}async function _f(e){return Ct.loadConfig({...e,__strictErrorHandling:!0})}async function Va(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 Ct.loadConfig(e);else n=await Ct.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)at.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let a=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await Ct.applyEnvironmentVariables(a.name||"",t,!0,a.verbose||!1))?.config??t;return t}}async function Hf(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await Ct.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"&&ga(r)))return(await Ct.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await Ct.loadConfig({...e,cwd:e.cwd||Rt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&ga(t)))return(await Ct.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function jf(e,t,r="replace"){let n=new gi;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function ur(e,t,r=!1){let n=new pi,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(a,o=[]){let c={...a};for(let[f,u]of Object.entries(a)){let l=[...o,f],g=[`${i}_${l.join("_").toUpperCase()}`,`${i}_${l.map((v)=>v.toUpperCase()).join("")}`,`${i}_${l.map((v)=>v.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,$;for(let v of g)if(d=Rt.env[v],d!==void 0){$=v;break}if(d!==void 0&&$)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let v=Number(d);if(!Number.isNaN(v))c[f]=v}else if(Array.isArray(u))try{c[f]=JSON.parse(d)}catch{c[f]=d.split(",").map((v)=>v.trim())}else c[f]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,l)}return c}return s(t)}function Kf(e){let t=He(Rt.cwd(),e.configDir),r=He(Rt.cwd(),e.generatedDir),n=He(r,"config-types.ts");if(!$n(Us(n)))kc(Us(n),{recursive:!0,mode:511});let i=$n(t)?Mc(t).map((a)=>a.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${$u}
|
|
35
|
+
`;return r}}function Lf(e,t){let r=jo("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function Bo(e,t,r={}){return Vo(e,t,r,new WeakMap)}function Vo(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 a=o(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return _o(e,t,i,n);if(!Qe(t)||!Qe(e))return t;return _f(e,t,r,n)}function _o(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 Gf(e,t);case"smart":return Bf(e,t,n);default:return t}return t}function Gf(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Sn(i,n)))r.push(n);return r}function Bf(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(Qe(t[0])&&Qe(e[0]))return Vf(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 Vf(e,t,r){let n=[...t];for(let i of e){if(!Qe(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let a of s)if(a in i){if(n.find((c)=>Qe(c)&&(a in c)&&c[a]===i[a])){o=!0;break}}if(!o)n.push(i)}return n}function _f(e,t,r,n){let i=t;if(Qe(i)&&n.has(i))return n.get(i);let s={...e};if(Qe(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let a=i[o],c=s[o];if(r.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){s[o]=a;continue}if(Qe(a)&&Qe(c))s[o]=Vo(c,a,r,n);else if(Array.isArray(a)||Array.isArray(c))s[o]=_o(c,a,r.arrayMergeMode||"smart",n);else s[o]=a}return s}function Ln(e,t,r="replace"){return Bo(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Sn(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(!Sn(e[r],t[r]))return!1;return!0}if(Qe(e)&&Qe(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(!Sn(e[i],t[i]))return!1}return!0}return!1}function Qe(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class yi{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:a=!1}=r;if(i){let f=er.getWithFileCheck("file",e);if(f){if(a)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!_r(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,g="default"in u,d=Object.keys(u).length>0;if(!g&&!d)throw new mr(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new mr(e,Error("Configuration must export a valid object"),"unknown");let E={config:Ln(t,l,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)er.setWithFileCheck("file",E,e,s);return E}catch(f){throw f instanceof Error?Tt.configLoad(e,f):Tt.configLoad(e,Error(String(f)))}};if(o)return gr.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(fn(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 Lo(async()=>_r(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!_r(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let a=fn(e,`${s}${o}`);if(await this.checkFileAccess(a))n.push(a)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let a=fn(e,o);if(await this.checkFileAccess(a))n.push(a)}}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((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!_r(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 Gn{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:a=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],g={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,g);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],g);else return this.validateWithJSONSchema(e,t,g)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(a)return await gr.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!tf(t))throw new pr(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 pr(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,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(o)){if(n.push({path:r,message:`Expected type ${a.join(" or ")}, got ${o}`,expected:a.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 a=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,a,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 a of t.required)if(!(a in o)){if(n.push({path:r?`${r}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[a,c]of Object.entries(t.properties))if(a in o){let f=r?`${r}.${a}`:a;if(this.validateObjectAgainstSchema(o[a],c,f,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(o))if(!a.has(c))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),a=this.validateWithRule(o,s,s.path);if(n.push(...a),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:Zo},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Bn{fileLoader=new yi;envProcessor=new gi;validator=new Gn;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let c=this.checkCache(o.name||"",o);if(c)return c}let a;try{a=await this.loadConfigurationStrategies(o,!0,r)}catch(c){let f=o.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;a={...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(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),l=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),g=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(g||u))throw c;if(l&&(!f||!g))a={...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(!f)a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(i||s)await this.validateConfiguration(a.config,i,s,o.name);if(r?.enabled&&a)this.cacheResult(o.name||"",a,r,o);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)at.warn(`Slow configuration loading detected: ${c.duration}ms for ${o.name}`);a.metrics=c}return a}catch(a){let c=Date.now()-t;throw at.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:a,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=s||Ot.cwd(),g=[],d=await this.loadLocalConfiguration(n,i,l,o,a,f,u,c,r);if(d)return g.push(...this.getLocalSearchPaths(n,i,l,o)),this.finalizeResult(d,g,c,n,u);let E=await this.loadHomeConfiguration(n,i,a,f,u,c);if(E)return g.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(E,g,c,n,u);let S=await this.loadPackageJsonConfiguration(n,i,l,a,f,u,c);if(S)return g.push(je(l,"package.json")),this.finalizeResult(S,g,c,n,u);if(g.push(...this.getAllSearchPaths(n,i,l,o)),t)throw Tt.configNotFound(n,g,i);return{...await this.applyEnvironmentVariables(n,a,c,u),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,a,c){let f=a?hr(e,i,o):i,u=this.getLocalDirectories(r,n);for(let l of u){if(o)at.info(`Searching for configuration in: ${l}`);let g=this.fileLoader.generateConfigPaths(e,l,t),d=await this.fileLoader.tryLoadFromPaths(g,f,{arrayStrategy:s,verbose:o,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(d){if(o)at.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?hr(e,r,i):r,a=[je(jt(),".config",e),je(jt(),".config"),jt()];for(let c of a){if(i)at.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,o,{arrayStrategy:n,verbose:i});if(u){if(i)at.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let a=o?hr(e,n,s):n;try{let c=je(r,"package.json");if(!En(c))return null;let f=await import(c),u=f[e],l=e;if(!u&&t)u=f[t],l=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)at.success(`Configuration loaded from package.json: ${l}`);return{config:Ln(a,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)at.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:hr(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 Tt.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return er.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);er.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,je(e,"config"),je(e,".config"),t?je(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(je(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=[je(jt(),".config",e),je(jt(),".config"),jt()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function Co(e){let t=!(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")),r=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return t||r}async function Hf(e){return wt.loadConfig({...e,__strictErrorHandling:!0})}async function Ho(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 wt.loadConfig(e);else n=await wt.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)at.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let o=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await wt.applyEnvironmentVariables(o.name||"",t,!0,o.verbose||!1))?.config??t;return t}}async function jf(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await wt.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"&&Co(r)))return(await wt.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await wt.loadConfig({...e,cwd:e.cwd||Ot.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Co(t)))return(await wt.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Kf(e,t,r="replace"){let n=new yi;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function hr(e,t,r=!1){let n=new gi,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,a=[]){let c={...o};for(let[f,u]of Object.entries(o)){let l=[...a,f],g=[`${i}_${l.join("_").toUpperCase()}`,`${i}_${l.map((S)=>S.toUpperCase()).join("")}`,`${i}_${l.map((S)=>S.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,E;for(let S of g)if(d=Ot.env[S],d!==void 0){E=S;break}if(d!==void 0&&E)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let S=Number(d);if(!Number.isNaN(S))c[f]=S}else if(Array.isArray(u))try{c[f]=JSON.parse(d)}catch{c[f]=d.split(",").map((S)=>S.trim())}else c[f]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,l)}return c}return s(t)}function Jf(e){let t=je(Ot.cwd(),e.configDir),r=je(Ot.cwd(),e.generatedDir),n=je(r,"config-types.ts");if(!En(Ys(n)))Mc(Ys(n),{recursive:!0,mode:511});let i=En(t)?Dc(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${Eu}
|
|
36
36
|
export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
|
|
37
|
-
`;Ic(n,s,{mode:438})}function
|
|
38
|
-
${i.map((c)=>{let f=
|
|
37
|
+
`;Ic(n,s,{mode:438})}function Uf(e){let t=null,r=null,n=()=>{if(!r)r=Ho(e).then((s)=>(t=s,s),(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)at.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 a=i[o];return n(),a},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,a){if(!t)t={...i};return t[o]=a,!0}})}function Yf(e){let t=co(sf.cwd(),e?.configDir||"./config");function r(){if(!rf(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=nf(t).filter((c)=>i.has(un(c))).map((c)=>({base:c.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:c})),a=new Map;for(let{base:c,file:f}of o){let u=un(f).toLowerCase(),l=a.get(c);if(!l){a.set(c,f);continue}let g=un(l).toLowerCase();if(s.indexOf(u)<s.indexOf(g))a.set(c,f)}return Array.from(a.entries()).map(([c,f])=>({base:c,file:f})).sort((c,f)=>c.base.localeCompare(f.base))}function n(){let i=r(),s=i.map((c)=>c.base),o=s.length?s.map((c)=>`'${c}'`).join(" | "):"string",a=i.length?`{
|
|
38
|
+
${i.map((c)=>{let f=co(t,c.file).replace(/\\/g,"/");return` '${c.base}': typeof import('${f}').default`}).join(`,
|
|
39
39
|
`)}
|
|
40
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${
|
|
41
|
-
export type ConfigByName = ${
|
|
40
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${o}
|
|
41
|
+
export type ConfigByName = ${a}
|
|
42
42
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
43
43
|
export type ConfigOf = Config
|
|
44
|
-
`}return{name:"bunfig-plugin",setup(i){i.onResolve({filter:/^virtual:bunfig-types$/},(s)=>{return{path:s.path,namespace:"bunfig-virtual"}}),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:n(),loader:"ts"}})}}}function vu(e,t={}){let r=ii.cwd();while(r.includes("storage"))r=ca(r,"..");let n=ca(r,e||"");if(t?.relative)return af(ii.cwd(),n);return n}function De(){if(yt.env.NODE_ENV==="test"||yt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function bu(){if(yt.env.NODE_ENV==="test"||yt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof yt<"u"){let e=yt.type;if(e==="renderer"||e==="worker")return!1;return!!(yt.versions&&(yt.versions.node||yt.versions.bun))}return!1}class Xa{async format(e){let t=await bu(),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:zt.pid,hostname:t(),environment:zt.env.NODE_ENV||"development",platform:zt.platform,version:zt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:zt.env.NODE_ENV||zt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class yi{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={...ui},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Xa,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??fe.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{...wn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...wn};return{...wn,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:ui.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!De()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,i=0,s=3,a=1000;while(i<s)try{try{try{await uf(this.config.logDirectory,da.F_OK|da.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await hf(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let o=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:dt.from(e);try{if(!_r(this.currentLogFile))await dn(this.currentLogFile,"",{mode:420});if(n=ha(this.currentLogFile,"a",420),ff(n,o,{flag:"a"}),ua(n),n!==void 0)hn(n),n=void 0;if((await qt(this.currentLogFile)).size===0){if(await dn(this.currentLogFile,o,{flag:"w",mode:420}),(await qt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(i<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let l=a*2**i;await new Promise((g)=>setTimeout(g,l)),i++;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(n!==void 0)try{hn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(o){if(i===s-1){let f=o,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),o}i++;let c=a*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,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 Xt(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 Xt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Xt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(De())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 e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,a],[,o])=>o.createdAt.getTime()-a.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,i);if(n.length>s)for(let[a]of n.slice(s))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return un(16).toString("hex")}generateKey(){return un(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=un(16),n=of("aes-256-gcm",t,r),i=dt.isBuffer(e)?e:dt.from(e,"utf8"),s=n.update(i),a=n.final(),o=s.length+a.length,c=n.getAuthTag(),f=dt.allocUnsafe(16+o+16);return r.copy(f,0),s.copy(f,16),a.copy(f,16+s.length),c.copy(f,16+o),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=pa(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(dt.from(dt.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(De())return;if(!this.shouldWriteToFile())return;let e=await qt(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 Hr(this.config.logDirectory),s=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,o=`${r}.${a}`;if(await qt(r).catch(()=>null))try{if(await ma(r,o),t.compress)try{let c=`${o}.gz`;await this.compressLogFile(o,c),await jr(o)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await dn(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await qt(r).catch(()=>null))await ma(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await Hr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of i.slice(t.maxFiles))await jr(Xt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=fa(e),n=cf(t),i=pa();await pf(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()})),_r(this.currentLogFile))try{let e=ha(this.currentLogFile,"r+");ua(e),hn(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(!De()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Hr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await jr(Xt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}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()?re.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||De())return!1;let e=typeof fe.env.NO_COLOR<"u",t=fe.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof fe.stderr<"u"&&fe.stderr.isTTY||typeof fe.stdout<"u"&&fe.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:a=!0}=e,o=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(a)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let c=fe.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${i}`;else if(s==="info"||s==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${re.cyan(i)}`;if(!a)return f.trim();let u=o(f).trim().length,l=o(t).length,g=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(g)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,a)=>{let o=Number.parseInt(a,10);return o<t[0].length?String(t[0][o]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,a)=>{if(a==="%")return"%";if(n>=t.length)return s;let o=t[n++];switch(a){case"s":return String(o);case"d":case"i":return Number(o).toString();case"j":case"o":return JSON.stringify(o,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=re.underline(re.blue(n)),a=this.toAbsoluteFilePath(i);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let o=`file://${encodeURI(a)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${o}\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)=>re.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>re.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>re.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>re.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>re.strikethrough(n)),t}supportsHyperlinks(){if(De())return!1;let e=fe.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=fe.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(df(t)||t.startsWith("./")||t.startsWith("../"))t=mf(t);else return null;return _r(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),a,o;if(t instanceof Error)a=t.message,o=t.stack;else a=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let l=this.options.showIcons===!1?"":Ou[e],g=this.options.showTags!==!1&&this.name?re.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:re.gray(c),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:re.green(c),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.error(d),o){let $=o.split(`
|
|
45
|
-
`);for(let
|
|
46
|
-
`;if(
|
|
47
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(i,s)=>{},finish:(i)=>{},interrupt:(i,s)=>{}};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()&&!
|
|
48
|
-
`);if(this[s==="warning"?"warn":s](i),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
49
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?
|
|
50
|
-
`),c=Math.max(...
|
|
51
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
52
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
53
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||
|
|
44
|
+
`}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"}))}}}function Su(e,t={}){let r=ni.cwd();while(r.includes("storage"))r=fo(r,"..");let n=fo(r,e||"");if(t?.relative)return af(ni.cwd(),n);return n}function Fe(){if(Ct.env.NODE_ENV==="test"||Ct.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Au(){if(Ct.env.NODE_ENV==="test"||Ct.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Ct<"u"){let e=Ct.type;if(e==="renderer"||e==="worker")return!1;return!!(Ct.versions&&(Ct.versions.node||Ct.versions.bun))}return!1}class Qo{async format(e){let t=await Au(),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:Qt.pid,hostname:t(),environment:Qt.env.NODE_ENV||"development",platform:Qt.platform,version:Qt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Qt.env.NODE_ENV||Qt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ci{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={...hi},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Qo,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??ue.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{...$n,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...$n};return{...$n,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:hi.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!Fe()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,i=0,s=3,o=1000;while(i<s)try{try{try{await hf(this.config.logDirectory,po.F_OK|po.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await df(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:mt.from(e);try{if(!Hr(this.currentLogFile))await mn(this.currentLogFile,"",{mode:420});if(n=mo(this.currentLogFile,"a",420),uf(n,a,{flag:"a"}),ho(n),n!==void 0)dn(n),n=void 0;if((await Xt(this.currentLogFile)).size===0){if(await mn(this.currentLogFile,a,{flag:"w",mode:420}),(await Xt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(i<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let l=o*2**i;await new Promise((g)=>setTimeout(g,l)),i++;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(n!==void 0)try{dn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===s-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}i++;let c=o*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,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 zt(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 zt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return zt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Fe())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 e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,o],[,a])=>a.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,i);if(n.length>s)for(let[o]of n.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return hn(16).toString("hex")}generateKey(){return hn(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=hn(16),n=lf("aes-256-gcm",t,r),i=mt.isBuffer(e)?e:mt.from(e,"utf8"),s=n.update(i),o=n.final(),a=s.length+o.length,c=n.getAuthTag(),f=mt.allocUnsafe(16+a+16);return r.copy(f,0),s.copy(f,16),o.copy(f,16+s.length),c.copy(f,16+a),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=yo(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(mt.from(mt.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(Fe())return;if(!this.shouldWriteToFile())return;let e=await Xt(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 jr(this.config.logDirectory),s=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${o}`;if(await Xt(r).catch(()=>null))try{if(await go(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await Kr(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await mn(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await Xt(r).catch(()=>null))await go(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await jr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await Kr(zt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=uo(e),n=ff(t),i=yo();await gf(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()})),Hr(this.currentLogFile))try{let e=mo(this.currentLogFile,"r+");ho(e),dn(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(!Fe()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await jr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Kr(zt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}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()?ie.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Fe())return!1;let e=typeof ue.env.NO_COLOR<"u",t=ue.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof ue.stderr<"u"&&ue.stderr.isTTY||typeof ue.stdout<"u"&&ue.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,a=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let c=ue.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${i}`;else if(s==="info"||s==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${ie.cyan(i)}`;if(!o)return f.trim();let u=a(f).trim().length,l=a(t).length,g=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(g)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let a=Number.parseInt(o,10);return a<t[0].length?String(t[0][a]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let a=t[n++];switch(o){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,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=ie.underline(ie.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(o)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${a}\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)=>ie.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>ie.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>ie.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>ie.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>ie.strikethrough(n)),t}supportsHyperlinks(){if(Fe())return!1;let e=ue.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=ue.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(mf(t)||t.startsWith("./")||t.startsWith("../"))t=pf(t);else return null;return Hr(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,a;if(t instanceof Error)o=t.message,a=t.stack;else o=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let l=this.options.showIcons===!1?"":Pu[e],g=this.options.showTags!==!1&&this.name?ie.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:ie.gray(c),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:ie.green(c),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.error(d),a){let E=a.split(`
|
|
45
|
+
`);for(let S of E)if(S.trim()&&!S.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:ie.gray(` ${S}`),level:e,showTimestamp:!1}))}break}}else if(!Fe()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),a)console.error(a)}let u=`${s} ${this.environment}.${e.toUpperCase()}: ${f}
|
|
46
|
+
`;if(a)u+=`${a}
|
|
47
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(i,s)=>{},finish:(i)=>{},interrupt:(i,s)=>{}};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()&&!Fe()&&ue.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(i,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,i),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!Fe()&&ue.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,s="info")=>{if(!Fe()&&ue.stdout.isTTY)ue.stdout.write(`
|
|
48
|
+
`);if(this[s==="warning"?"warn":s](i),this.activeProgressBar&&this.shouldStyleConsole()&&!Fe()&&ue.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?ie.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":ie.blue("\u25D0"),tag:r,message:`${ie.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,a=this.formatConsoleTimestamp(o),c=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
|
|
49
|
+
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?ie.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":ie.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Fe())console.error(c.trim());if(this.shouldWriteToFile())await this.writeToFile(c)}}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 Ci(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(Fe())throw Error("createReadStream is not supported in browser environments");if(!Hr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return uo(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=mt.isBuffer(e)?e:mt.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),a=cf("aes-256-gcm",r,i);a.setAuthTag(s);let c=a.update(o),f=a.final(),u=c.length+f.length,l=mt.allocUnsafe(u);return c.copy(l,0),f.copy(l,c.length),l.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 Fe()}isServerMode(){return!Fe()}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 a=i.split(`
|
|
50
|
+
`),c=Math.max(...a.map((g)=>g.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,l=a.map((g)=>this.formatConsoleMessage({timestamp:r,message:ie.cyan(g),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:ie.cyan(f),showTimestamp:!1})),l.forEach((g)=>console.error(g)),console.error(this.formatConsoleMessage({timestamp:r,message:ie.cyan(u),showTimestamp:!1}))}else if(!Fe())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
|
|
51
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(Fe())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${ie.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();ue.stdin.removeListener("data",r);try{if(typeof ue.stdin.setRawMode==="function")ue.stdin.setRawMode(!1)}catch{}ue.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof ue.stdin.setRawMode==="function")ue.stdin.setRawMode(!0)}catch{}ue.stdin.resume(),ue.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,a=0;if(r=e.replace(o,(c,f)=>{if(f==="%")return"%";if(a>=t.length)return c;let u=t[a++];switch(f){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return c}}),a<t.length)r+=` ${t.slice(a).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?ie.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${ie.blue("\u25D0")} `;console.error(`${a}${o} ${ie.cyan(n)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
52
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!ue.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=ie.green("\u2501".repeat(n)),o=ie.gray("\u2501".repeat(i)),a=`[${s}${o}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?ie.green("\u2713"):ie.blue("\u25B6"),l=this.options.showTags!==!1&&this.name?` ${ie.gray(this.formatTag(this.name))}`:"",g=`\r${u}${l} ${a} ${c}${f}`,d=ue.stdout.columns||80,E=" ".repeat(Math.max(0,d-g.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${g}${E}`,ue.stdout.write(e.lastRenderedLine),t)ue.stdout.write(`
|
|
53
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Fe()||!ue.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(Fe()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await jr(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 i=zt(this.config.logDirectory,n);if(e.before)try{if((await Xt(i)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${i}:`,s);continue}r.push(i)}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 Kr(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 ku(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let a=0;a<=r;a++)try{return await e()}catch(c){if(o=c instanceof Error?c:Error(String(c)),a===r||!i(o))break;if(n>0)await new Promise((f)=>setTimeout(f,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}class _n{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:a=!1,trackPerformance:c=!0}=r,f=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),l={...t};return this.processObject(l,[],u,{useCamelCase:i,useBackwardCompatibility:s,customParsers:o,verbose:a,configName:e}),{config:l,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return Dn.track("applyEnvironmentVariables",f,{configName:e});return f()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],a=o.map((u)=>this.formatEnvKey(u,n.useCamelCase)),c=`${r}_${a.join("_")}`,f=n.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,n);else{let u=Jr.env[c]||(f?Jr.env[f]:void 0);if(u!==void 0){if(n.verbose){let l=Jr.env[c]?c:f}try{e[i]=this.parseEnvironmentValue(u,typeof s,c,n.customParsers,n.configName)}catch(l){if(l instanceof Vn)throw l;throw tr.envVar(c,u,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 tr.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(Jr.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],a=`${r}_${o.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,n);else n.push({key:a,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}:
|
|
54
54
|
|
|
55
55
|
`;for(let n of e)r+=`${n.key}
|
|
56
56
|
`,r+=` Type: ${n.type}
|
|
@@ -62,171 +62,171 @@ export type ConfigOf = Config
|
|
|
62
62
|
`;r+=`| Variable | Type | Description | Example |
|
|
63
63
|
`,r+=`|----------|------|-------------|----------|
|
|
64
64
|
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
65
|
-
`;return r}}function ku(e,t,r={}){return so(e,t,r,new WeakMap)}function so(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:a}=r;if(t===null||t===void 0)return s?e:t;if(a){let o=a(e,t);if(o!==void 0)return o}if(Array.isArray(t)||Array.isArray(e))return ao(e,t,i,n);if(!Qe(t)||!Qe(e))return t;return Fu(e,t,r,n)}function ao(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 Mu(e,t);case"smart":return Iu(e,t,n);default:return t}return t}function Mu(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>kn(i,n)))r.push(n);return r}function Iu(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(Qe(t[0])&&Qe(e[0]))return Du(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 Du(e,t,r){let n=[...t];for(let i of e){if(!Qe(i)){n.push(i);continue}let s=["id","name","key","path","type"],a=!1;for(let o of s)if(o in i){if(n.find((c)=>Qe(c)&&(o in c)&&c[o]===i[o])){a=!0;break}}if(!a)n.push(i)}return n}function Fu(e,t,r,n){let i=t;if(Qe(i)&&n.has(i))return n.get(i);let s={...e};if(Qe(i))n.set(i,s);for(let a in i){if(!Object.prototype.hasOwnProperty.call(i,a))continue;let o=i[a],c=s[a];if(r.skipNullish&&(o===null||o===void 0))continue;if(o===null||o===void 0){s[a]=o;continue}if(Qe(o)&&Qe(c))s[a]=so(c,o,r,n);else if(Array.isArray(o)||Array.isArray(c))s[a]=ao(c,o,r.arrayMergeMode||"smart",n);else s[a]=o}return s}function oo(e,t,r="replace"){return ku(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function kn(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(!kn(e[r],t[r]))return!1;return!0}if(Qe(e)&&Qe(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(!kn(e[i],t[i]))return!1}return!0}return!1}function Qe(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class lo{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:a=!0,verbose:o=!1}=r;if(i){let f=ni.getWithFileCheck("file",e);if(f){if(o)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!Jr(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,g="default"in u,d=Object.keys(u).length>0;if(!g&&!d)throw new hi(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new hi(e,Error("Configuration must export a valid object"),"unknown");let $={config:oo(t,l,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)ni.setWithFileCheck("file",$,e,s);return $}catch(f){throw f instanceof Error?er.configLoad(e,f):er.configLoad(e,Error(String(f)))}};if(a)return Mn.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let a of this.extensions)i.push(mn(t,`${s}${a}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let s of n){if(!s)continue;if(r.push(s,`.${s}.config`,`${s}.config`,`.${s}`),e)r.push(`${e}.${s}.config`,`.${e}.${s}.config`)}let i=new Set;return r.filter((s)=>{if(!s||i.has(s))return!1;return i.add(s),!0})}checkFileAccess(e){return Pu(async()=>{return Jr(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Jr(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let a of this.extensions){let o=mn(e,`${s}${a}`);if(await this.checkFileAccess(o))n.push(o)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let a of s)if(this.looksLikeConfigFile(a)){let o=mn(e,a);if(await this.checkFileAccess(o))n.push(o)}}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((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!Jr(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 co{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:a=[],trackPerformance:o=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],g={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:a,trackPerformance:o,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,g);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...a],g);else return this.validateWithJSONSchema(e,t,g)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(o)return await Mn.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!gf(t))throw new di(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 di(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 a=Array.isArray(e)?"array":typeof e,o=Array.isArray(t.type)?t.type:[t.type];if(!o.includes(a)){if(n.push({path:r,message:`Expected type ${o.join(" or ")}, got ${a}`,expected:o.join(" or "),actual:a,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 a=0;a<e.length;a++){let o=r?`${r}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(e[a],t.items,o,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let a=e;if(s.validateRequired&&t.required){for(let o of t.required)if(!(o in a)){if(n.push({path:r?`${r}.${o}`:o,message:`Missing required property '${o}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[o,c]of Object.entries(t.properties))if(o in a){let f=r?`${r}.${o}`:o;if(this.validateObjectAgainstSchema(a[o],c,f,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let o=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(a))if(!o.has(c))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let a=this.getValueByPath(e,s.path),o=this.validateWithRule(a,s,s.path);if(n.push(...o),r.stopOnFirstError&&n.length>0)break}catch(a){n.push({path:s.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,a]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(a)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Nu},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function Wu(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class fo{fileLoader=new lo;envProcessor=new Vn;validator=new co;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...a}=e;try{if(r?.enabled){let c=this.checkCache(a.name||"",a);if(c)return c}let o;try{o=await this.loadConfigurationStrategies(a,!0,r)}catch(c){let f=a.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`No configuration file found for "${a.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),l=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),g=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(g||u))throw c;if(l&&(!f||!g))o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(i||s)await this.validateConfiguration(o.config,i,s,a.name);if(r?.enabled&&o)this.cacheResult(a.name||"",o,r,a);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:a.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)mt.warn(`Slow configuration loading detected: ${c.duration}ms for ${a.name}`);o.metrics=c}return o}catch(o){if(o instanceof Error&&o.name==="ConfigNotFoundError")throw o;let c=Date.now()-t;throw mt.error(`Configuration loading failed after ${c}ms:`,[o instanceof Error?o:Error(String(o))]),o}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:a,defaultConfig:o,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=s||mi.cwd(),g=[],d=await this.loadLocalConfiguration(n,i,l,a,o,f,u,c,r);if(d)return g.push(...this.getLocalSearchPaths(n,i,l,a)),this.finalizeResult(d,g,c,n,u);let $=await this.loadHomeConfiguration(n,i,o,f,u,c);if($)return g.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult($,g,c,n,u);let v=await this.loadPackageJsonConfiguration(n,i,l,o,f,u,c);if(v)return g.push(Xe(l,"package.json")),this.finalizeResult(v,g,c,n,u);if(g.push(...this.getAllSearchPaths(n,i,l,a)),t)throw er.configNotFound(n,g,i);return{...await this.applyEnvironmentVariables(n,o,c,u),warnings:[`No configuration file found for "${n}"${Wu(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,a,o,c){let f=o?Yr(e,i,a):i,u=this.getLocalDirectories(r,n);for(let l of u){if(a)mt.info(`Searching for configuration in: ${l}`);let g=this.fileLoader.generateConfigPaths(e,l,t),d=await this.fileLoader.tryLoadFromPaths(g,f,{arrayStrategy:s,verbose:a,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(d){if(a)mt.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let a=s?Yr(e,r,i):r,o=[Xe(_t(),".config",e),Xe(_t(),".config"),_t()];for(let c of o){if(i)mt.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,a,{arrayStrategy:n,verbose:i});if(u){if(i)mt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,a){let o=a?Yr(e,n,s):n;try{let c=Xe(r,"package.json");if(!Oc(c))return null;let f={};try{f=JSON.parse(Pc(c,"utf8"))}catch(g){if(s)mt.warn("Failed to parse package.json:",[g instanceof Error?g:Error(String(g))]);return null}let u=f[e],l=e;if(!u&&t){let g=Array.isArray(t)?t:[t];for(let d of g){if(!d)continue;if(f[d]){u=f[d],l=d;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)mt.success(`Configuration loaded from package.json: ${l}`);return{config:oo(o,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)mt.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Yr(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((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(i.length>0)throw er.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return ni.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);ni.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.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,Xe(e,"config"),Xe(e,".config"),t?Xe(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(Xe(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let a of i)s.push(...this.fileLoader.generateConfigPaths(e,a,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[Xe(_t(),".config",e),Xe(_t(),".config"),_t()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function Yr(e,t,r=!1){let n=new Vn,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(a,o=[]){let c={...a};for(let[f,u]of Object.entries(a)){let l=[...o,f],g=[`${i}_${l.join("_").toUpperCase()}`,`${i}_${l.map((v)=>v.toUpperCase()).join("")}`,`${i}_${l.map((v)=>v.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,$;for(let v of g)if(d=mi.env[v],d!==void 0){$=v;break}if(d!==void 0&&$)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let v=Number(d);if(!Number.isNaN(v))c[f]=v}else if(Array.isArray(u))try{c[f]=JSON.parse(d)}catch{c[f]=d.split(",").map((v)=>v.trim())}else c[f]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,l)}return c}return s(t)}var ni,Mn,yf,Cf=(e)=>e,$f=(e,t)=>{for(var r in t)yf(e,r,{get:t[r],enumerable:!0,configurable:!0,set:wf.bind(t,r)})},Ef=(e,t)=>()=>(e&&(t=e(e=0)),t),Ia,_a,Qt,pr,Ha,Yf,Zf,ya,qr,Sn,Be,ge,qf,Ca,Xf,wa,zf,Qf,pn,eu,$a,Ea,gn,tu,ru,iu,nu,Xr,ja,su,Ve,au,ou,va,zr,bn,Ie,ee,lu,Sa,cu,ba,fu,uu,yn,hu,Aa,xa,du,Cn,mu,pu,gu,yu,Cu,Qr,Ka,wu,$u="0.15.6",Ye,ci,dr,An,xn,fi,Tn,Rn,mr,On,Pn,xt,Ja,Ua,at,Ct,Ya,Za,Eu,Su,qa,ui,gg,We,re,yg,Au,Cg,xu,wg,$g,Ta,Eg,Tu,Ru,vg,Ra,Sg,bg,Ag,xg,Tg,wn,Ou,Rg,ot,za,hi,Qa,eo,Bn,to,ro,di,io,no,er,Nu,mt,Og,Pg,kg,Lu,uo;var ho=le(()=>{ni=new ka,Mn=new Ma,yf=Object.defineProperty;Ia={};$f(Ia,{withErrorRecovery:()=>Na,tryLoadConfig:()=>jf,loadConfigWithResult:()=>_f,loadConfig:()=>Va,isRetryableError:()=>Nf,isConfigNotFoundError:()=>Ff,isBunfigError:()=>Wa,globalPerformanceMonitor:()=>pr,globalCache:()=>Qt,getEnvOrDefault:()=>Wf,generateConfigTypes:()=>Kf,defaultGeneratedDir:()=>Za,defaultConfigDir:()=>Ya,deepMergeWithArrayStrategy:()=>Wn,deepMerge:()=>La,createLibraryConfig:()=>Jf,config:()=>Hf,bunfigPlugin:()=>Uf,applyEnvVarsToConfig:()=>ur,TypeGenerationError:()=>Rn,SchemaValidationError:()=>mr,PluginError:()=>Pn,PerformanceMonitor:()=>Dn,FileSystemError:()=>Tn,ErrorFactory:()=>xt,EnvVarError:()=>fi,EnvProcessor:()=>pi,ConfigValidator:()=>Ln,ConfigValidationError:()=>An,ConfigNotFoundError:()=>ci,ConfigMergeError:()=>xn,ConfigLoader:()=>Gn,ConfigLoadError:()=>dr,ConfigFileLoader:()=>gi,ConfigCache:()=>In,CacheUtils:()=>Ha,BunfigError:()=>Ye,BrowserConfigError:()=>On,ArrayMergeStrategies:()=>Ja});Eu=Ef(async()=>{_a=import.meta.require,Qt=new In,pr=new Dn,Ha={createKey:vf,isEquivalent:Sf,estimateMemoryUsage:bf},Yf=ri(En.cwd(),"config"),Zf=ri(En.cwd(),"src/generated"),ya=ti.env.CLARITY_LOG_DIR||Nc(Tf(),"logs"),qr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ya,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Sn=await Rf(),Be={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"},ge=Be,qf=Be.red,Ca=Be.green,Xf=Be.yellow,wa=Be.blue,zf=Be.magenta,Qf=Be.cyan,pn=Be.white,eu=Be.gray,$a=Be.bgRed,Ea=Be.bgYellow,gn=Be.bold,tu=Be.dim,ru=Be.italic,iu=Be.underline,nu=Be.reset,Xr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ja={debug:"\uD83D\uDD0D",info:wa("\u2139"),success:Ca("\u2713"),warning:Ea(pn(gn(" WARN "))),error:$a(pn(gn(" ERROR ")))},su=new ai("stacks"),Ve=new ai("bunfig",{showTags:!0}),au=_e(hr.cwd(),"config"),ou=_e(hr.cwd(),"src/generated"),va=ei.env.CLARITY_LOG_DIR||Dc(Mf(),"logs"),zr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:va,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},bn=await If(),Ie={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"},ee=Ie,lu=Ie.red,Sa=Ie.green,cu=Ie.yellow,ba=Ie.blue,fu=Ie.magenta,uu=Ie.cyan,yn=Ie.white,hu=Ie.gray,Aa=Ie.bgRed,xa=Ie.bgYellow,du=Ie.bgGray,Cn=Ie.bold,mu=Ie.dim,pu=Ie.italic,gu=Ie.underline,yu=Ie.strikethrough,Cu=Ie.reset,Qr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ka={debug:"\uD83D\uDD0D",info:ba("\u2139"),success:Sa("\u2713"),warning:xa(yn(Cn(" WARN "))),error:Aa(yn(Cn(" ERROR ")))},wu=new li("stacks"),Ye=class extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},ci=class extends Ye{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r?` or alias "${r}"`:"";super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},dr=class extends Ye{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},An=class extends Ye{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},xn=class extends Ye{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},fi=class extends Ye{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}},Tn=class extends Ye{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Rn=class extends Ye{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},mr=class extends Ye{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}},On=class extends Ye{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}},Pn=class extends Ye{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},xt={configNotFound(e,t,r){return new ci(e,t,r)},configLoad(e,t,r){return new dr(e,t,r)},configValidation(e,t,r){return new An(e,t,r)},configMerge(e,t,r,n){return new xn(e,t,r,n)},envVar(e,t,r,n){return new fi(e,t,r,n)},fileSystem(e,t,r){return new Tn(e,t,r)},typeGeneration(e,t,r){return new Rn(e,t,r)},schemaValidation(e,t,r){return new mr(e,t,r)},browserConfig(e,t,r,n){return new On(e,t,r,n)},plugin(e,t,r){return new Pn(e,t,r)}},Ja={replace:"replace",concat:"concat",smart:"smart"},Ua=/^https?:\/\//,at=new li("bunfig",{showTags:!0}),Ct=new Gn,Ya=He(Rt.cwd(),"config"),Za=He(Rt.cwd(),"src/generated")});Su=ii.env.CLARITY_LOG_DIR||sf(vu(),"logs"),qa={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Su,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},ui={...qa},gg=(async()=>{try{let{loadConfig:e}=await Eu().then(()=>Ia),t=await e({name:"clarity",alias:"logging",defaultConfig:qa,cwd:ii.cwd()});if(t)Object.assign(ui,t)}catch{}return ui})();We={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"},re=We,yg=We.red,Au=We.green,Cg=We.yellow,xu=We.blue,wg=We.magenta,$g=We.cyan,Ta=We.white,Eg=We.gray,Tu=We.bgRed,Ru=We.bgYellow,vg=We.bgGray,Ra=We.bold,Sg=We.dim,bg=We.italic,Ag=We.underline,xg=We.strikethrough,Tg=We.reset,wn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ou={debug:"\uD83D\uDD0D",info:xu("\u2139"),success:Au("\u2713"),warning:Ru(Ta(Ra(" WARN "))),error:Tu(Ta(Ra(" ERROR ")))};Rg=new yi("stacks");ot=class ot extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}};za=class za extends ot{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],i="";if(n.length===1)i=` or alias "${n[0]}"`;else if(n.length>1)i=` or aliases ${n.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}};hi=class hi extends ot{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}};Qa=class Qa extends ot{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};eo=class eo extends ot{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}};Bn=class Bn extends ot{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}};to=class to extends ot{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}};ro=class ro extends ot{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}};di=class di extends ot{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}};io=class io extends ot{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}};no=class no extends ot{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}};er={configNotFound(e,t,r){return new za(e,t,r)},configLoad(e,t,r){return new hi(e,t,r)},configValidation(e,t,r){return new Qa(e,t,r)},configMerge(e,t,r,n){return new eo(e,t,r,n)},envVar(e,t,r,n){return new Bn(e,t,r,n)},fileSystem(e,t,r){return new to(e,t,r)},typeGeneration(e,t,r){return new ro(e,t,r)},schemaValidation(e,t,r){return new di(e,t,r)},browserConfig(e,t,r,n){return new io(e,t,r,n)},plugin(e,t,r){return new no(e,t,r)}};Nu=/^https?:\/\//;mt=new yi("bunfig",{showTags:!0});Og=new fo;Pg=Xe(mi.cwd(),"config"),kg=Xe(mi.cwd(),"src/generated"),Lu={cwd:Rc.cwd(),root:"./src",entrypoints:["**/*.{ts,tsx,mts,cts,vue,stx}"],outdir:"./dist",keepComments:!0,clean:!0,tsconfigPath:"./tsconfig.json",outputStructure:"mirror",verbose:!1,importOrder:["bun"],declarationMap:!1},uo=Lu});var mo;var po=le(()=>{mo=new Set(["ANGLE_instanced_arrays","ARIAMixin","AacBitstreamFormat","AacEncoderConfig","AbortController","AbortSignal","AbortSignalEventMap","AbstractRange","AbstractWorker","AbstractWorkerEventMap","ActiveXObject","AddEventListenerOptions","AddressErrors","AddressType","AddressValue","AesCbcParams","AesCtrParams","AesDerivedKeyParams","AesGcmParams","AesKeyAlgorithm","AesKeyGenParams","AggregateError","AggregateErrorConstructor","Algorithm","AlgorithmIdentifier","AlignSetting","AllAcceptedCredentialsOptions","AllowSharedBufferSource","AlphaOption","AnalyserNode","AnalyserOptions","Animatable","Animation","AnimationEffect","AnimationEvent","AnimationEventInit","AnimationEventMap","AnimationFrameProvider","AnimationPlayState","AnimationPlaybackEvent","AnimationPlaybackEventInit","AnimationReplaceState","AnimationTimeline","AppendMode","Array","ArrayBuffer","ArrayBufferConstructor","ArrayBufferLike","ArrayBufferTypes","ArrayBufferView","ArrayConstructor","ArrayIterator","ArrayLike","AssignedNodesOptions","AsyncDisposable","AsyncDisposableStack","AsyncDisposableStackConstructor","AsyncGenerator","AsyncGeneratorFunction","AsyncGeneratorFunctionConstructor","AsyncIterable","AsyncIterableIterator","AsyncIterator","AsyncIteratorObject","Atomics","AttestationConveyancePreference","Attr","Audio","AudioBuffer","AudioBufferOptions","AudioBufferSourceNode","AudioBufferSourceOptions","AudioConfiguration","AudioContext","AudioContextLatencyCategory","AudioContextOptions","AudioContextState","AudioData","AudioDataCopyToOptions","AudioDataInit","AudioDataOutputCallback","AudioDecoder","AudioDecoderConfig","AudioDecoderEventMap","AudioDecoderInit","AudioDecoderSupport","AudioDestinationNode","AudioEncoder","AudioEncoderConfig","AudioEncoderEventMap","AudioEncoderInit","AudioEncoderSupport","AudioListener","AudioNode","AudioNodeOptions","AudioParam","AudioParamMap","AudioProcessingEvent","AudioProcessingEventInit","AudioSampleFormat","AudioScheduledSourceNode","AudioScheduledSourceNodeEventMap","AudioTimestamp","AudioWorklet","AudioWorkletNode","AudioWorkletNodeEventMap","AudioWorkletNodeOptions","AuthenticationExtensionsClientInputs","AuthenticationExtensionsClientInputsJSON","AuthenticationExtensionsClientOutputs","AuthenticationExtensionsClientOutputsJSON","AuthenticationExtensionsLargeBlobInputs","AuthenticationExtensionsLargeBlobInputsJSON","AuthenticationExtensionsLargeBlobOutputs","AuthenticationExtensionsLargeBlobOutputsJSON","AuthenticationExtensionsPRFInputs","AuthenticationExtensionsPRFInputsJSON","AuthenticationExtensionsPRFOutputs","AuthenticationExtensionsPRFOutputsJSON","AuthenticationExtensionsPRFValues","AuthenticationExtensionsPRFValuesJSON","AuthenticationResponseJSON","AuthenticatorAssertionResponse","AuthenticatorAssertionResponseJSON","AuthenticatorAttachment","AuthenticatorAttestationResponse","AuthenticatorAttestationResponseJSON","AuthenticatorResponse","AuthenticatorSelectionCriteria","AuthenticatorTransport","AutoFill","AutoFillAddressKind","AutoFillBase","AutoFillContactField","AutoFillContactKind","AutoFillCredentialField","AutoFillField","AutoFillNormalField","AutoFillSection","AutoKeyword","AutomationRate","AvcBitstreamFormat","AvcEncoderConfig","Awaited","BarProp","Base64URLString","BaseAudioContext","BaseAudioContextEventMap","BeforeUnloadEvent","BigInt","BigInt64Array","BigInt64ArrayConstructor","BigIntConstructor","BigIntToLocaleStringOptions","BigInteger","BigUint64Array","BigUint64ArrayConstructor","BinaryType","BiquadFilterNode","BiquadFilterOptions","BiquadFilterType","BitrateMode","Blob","BlobCallback","BlobEvent","BlobEventInit","BlobPart","BlobPropertyBag","Body","BodyInit","Boolean","BooleanConstructor","BroadcastChannel","BroadcastChannelEventMap","Buffer","BufferEncoding","BufferSource","BuiltinIteratorReturn","Bun","BunFile","ByteLengthQueuingStrategy","CDATASection","COSEAlgorithmIdentifier","CSS","CSSAnimation","CSSConditionRule","CSSContainerRule","CSSCounterStyleRule","CSSFontFaceRule","CSSFontFeatureValuesRule","CSSFontPaletteValuesRule","CSSGroupingRule","CSSImageValue","CSSImportRule","CSSKeyframeRule","CSSKeyframesRule","CSSKeywordValue","CSSKeywordish","CSSLayerBlockRule","CSSLayerStatementRule","CSSMathClamp","CSSMathInvert","CSSMathMax","CSSMathMin","CSSMathNegate","CSSMathOperator","CSSMathProduct","CSSMathSum","CSSMathValue","CSSMatrixComponent","CSSMatrixComponentOptions","CSSMediaRule","CSSNamespaceRule","CSSNestedDeclarations","CSSNumberish","CSSNumericArray","CSSNumericBaseType","CSSNumericType","CSSNumericValue","CSSPageDescriptors","CSSPageRule","CSSPerspective","CSSPerspectiveValue","CSSPositionTryDescriptors","CSSPositionTryRule","CSSPropertyRule","CSSRotate","CSSRule","CSSRuleList","CSSScale","CSSScopeRule","CSSSkew","CSSSkewX","CSSSkewY","CSSStartingStyleRule","CSSStyleDeclaration","CSSStyleDeclarationBase","CSSStyleProperties","CSSStyleRule","CSSStyleSheet","CSSStyleSheetInit","CSSStyleValue","CSSSupportsRule","CSSTransformComponent","CSSTransformValue","CSSTransition","CSSTranslate","CSSUnitValue","CSSUnparsedSegment","CSSUnparsedValue","CSSVariableReferenceValue","CSSViewTransitionRule","Cache","CacheQueryOptions","CacheStorage","CalendarLike","CallableFunction","CanPlayTypeResult","CanvasCaptureMediaStreamTrack","CanvasCompositing","CanvasDirection","CanvasDrawImage","CanvasDrawPath","CanvasFillRule","CanvasFillStrokeStyles","CanvasFilters","CanvasFontKerning","CanvasFontStretch","CanvasFontVariantCaps","CanvasGradient","CanvasImageData","CanvasImageSmoothing","CanvasImageSource","CanvasLineCap","CanvasLineJoin","CanvasPath","CanvasPathDrawingStyles","CanvasPattern","CanvasRect","CanvasRenderingContext2D","CanvasRenderingContext2DSettings","CanvasSettings","CanvasShadowStyles","CanvasState","CanvasText","CanvasTextAlign","CanvasTextBaseline","CanvasTextDrawingStyles","CanvasTextRendering","CanvasTransform","CanvasUserInterface","Capitalize","CaretPosition","CaretPositionFromPointOptions","ChannelCountMode","ChannelInterpretation","ChannelMergerNode","ChannelMergerOptions","ChannelSplitterNode","ChannelSplitterOptions","CharacterData","CheckVisibilityOptions","ChildNode","ClassAccessorDecoratorContext","ClassAccessorDecoratorResult","ClassAccessorDecoratorTarget","ClassDecorator","ClassDecoratorContext","ClassFieldDecoratorContext","ClassGetterDecoratorContext","ClassMemberDecoratorContext","ClassMethodDecoratorContext","ClassSetterDecoratorContext","Client","ClientQueryOptions","ClientRect","ClientTypes","Clients","Clipboard","ClipboardEvent","ClipboardEventInit","ClipboardItem","ClipboardItemData","ClipboardItemOptions","ClipboardItems","CloseEvent","CloseEventInit","CodecState","Collator","CollatorConstructor","CollatorOptions","ColorGamut","ColorSpaceConversion","CommandEvent","CommandEventInit","Comment","CompileError","CompositeOperation","CompositeOperationOrAuto","CompositionEvent","CompositionEventInit","CompressionFormat","CompressionStream","ComputedEffectTiming","ComputedKeyframe","ConcatArray","Console","ConstantSourceNode","ConstantSourceOptions","ConstrainBoolean","ConstrainBooleanOrDOMString","ConstrainBooleanOrDOMStringParameters","ConstrainBooleanParameters","ConstrainDOMString","ConstrainDOMStringParameters","ConstrainDouble","ConstrainDoubleRange","ConstrainULong","ConstrainULongRange","ConstructorParameters","ContentVisibilityAutoStateChangeEvent","ContentVisibilityAutoStateChangeEventInit","ConvolverNode","ConvolverOptions","CookieChangeEvent","CookieChangeEventInit","CookieInit","CookieList","CookieListItem","CookieSameSite","CookieStore","CookieStoreDeleteOptions","CookieStoreEventMap","CookieStoreGetOptions","CookieStoreManager","CountQueuingStrategy","Credential","CredentialCreationOptions","CredentialMediationRequirement","CredentialPropertiesOutput","CredentialRequestOptions","CredentialsContainer","Crypto","CryptoKey","CryptoKeyPair","CurrentUserDetailsOptions","CustomElementConstructor","CustomElementRegistry","CustomEvent","CustomEventInit","CustomStateSet","DOMException","DOMHighResTimeStamp","DOMImplementation","DOMMatrix","DOMMatrix2DInit","DOMMatrixInit","DOMMatrixReadOnly","DOMParser","DOMParserSupportedType","DOMPoint","DOMPointInit","DOMPointReadOnly","DOMQuad","DOMQuadInit","DOMRect","DOMRectInit","DOMRectList","DOMRectReadOnly","DOMStringList","DOMStringMap","DOMTokenList","DataTransfer","DataTransferItem","DataTransferItemList","DataView","DataViewConstructor","Date","DateConstructor","DateLikeObject","DateTimeFormat","DateTimeFormatConstructor","DateTimeFormatOptions","DateTimeFormatPart","DateTimeFormatPartTypes","DateTimeFormatPartTypesRegistry","DateTimeLikeObject","DateTimeRangeFormatPart","DateUnit","DecodeErrorCallback","DecodeSuccessCallback","DecompressionStream","DecoratorContext","DecoratorMetadata","DecoratorMetadataObject","DedicatedWorkerGlobalScope","DedicatedWorkerGlobalScopeEventMap","DelayNode","DelayOptions","DeviceMotionEvent","DeviceMotionEventAcceleration","DeviceMotionEventAccelerationInit","DeviceMotionEventInit","DeviceMotionEventRotationRate","DeviceMotionEventRotationRateInit","DeviceOrientationEvent","DeviceOrientationEventInit","DigitalCredential","DirectionSetting","Dirent","DisambiguationOptions","DisplayCaptureSurfaceType","DisplayMediaStreamOptions","DisplayNames","DisplayNamesFallback","DisplayNamesLanguageDisplay","DisplayNamesOptions","DisplayNamesType","Disposable","DisposableStack","DisposableStackConstructor","DistanceModelType","Document","DocumentEventMap","DocumentFragment","DocumentOrShadowRoot","DocumentReadyState","DocumentTimeline","DocumentTimelineOptions","DocumentType","DocumentVisibilityState","DoubleRange","DragEvent","DragEventInit","Duration","DurationConstructor","DurationFormat","DurationFormatDisplayOption","DurationFormatLocaleMatcher","DurationFormatOptions","DurationFormatPart","DurationFormatStyle","DurationFormatUnit","DurationFormatUnitSingular","DurationLike","DurationLikeObject","DurationRelativeToOptions","DurationRoundingOptions","DurationToStringOptions","DurationTotalOptions","DynamicsCompressorNode","DynamicsCompressorOptions","EXT_blend_minmax","EXT_color_buffer_float","EXT_color_buffer_half_float","EXT_float_blend","EXT_frag_depth","EXT_sRGB","EXT_shader_texture_lod","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","EXT_texture_norm16","EcKeyAlgorithm","EcKeyGenParams","EcKeyImportParams","EcdhKeyDeriveParams","EcdsaParams","EffectTiming","Element","ElementCSSInlineStyle","ElementContentEditable","ElementCreationOptions","ElementDefinitionOptions","ElementEventMap","ElementInternals","ElementTagNameMap","EncodedAudioChunk","EncodedAudioChunkInit","EncodedAudioChunkMetadata","EncodedAudioChunkOutputCallback","EncodedAudioChunkType","EncodedVideoChunk","EncodedVideoChunkInit","EncodedVideoChunkMetadata","EncodedVideoChunkOutputCallback","EncodedVideoChunkType","EndOfStreamError","EndingType","Enumerator","EnumeratorConstructor","EpochTimeStamp","Error","ErrorCallback","ErrorConstructor","ErrorEvent","ErrorEventInit","ErrorOptions","EvalError","EvalErrorConstructor","Event","EventCounts","EventInit","EventListener","EventListenerObject","EventListenerOptions","EventListenerOrEventListenerObject","EventModifierInit","EventSource","EventSourceEventMap","EventSourceInit","EventTarget","Exception","ExceptionOptions","Exclude","ExportValue","Exports","ExtendableCookieChangeEvent","ExtendableCookieChangeEventInit","ExtendableEvent","ExtendableEventInit","ExtendableMessageEvent","ExtendableMessageEventInit","External","Extract","FetchEvent","FetchEventInit","File","FileCallback","FileList","FilePropertyBag","FileReader","FileReaderEventMap","FileReaderSync","FileSink","FileSystem","FileSystemCreateWritableOptions","FileSystemDirectoryEntry","FileSystemDirectoryHandle","FileSystemDirectoryHandleAsyncIterator","FileSystemDirectoryReader","FileSystemEntriesCallback","FileSystemEntry","FileSystemEntryCallback","FileSystemFileEntry","FileSystemFileHandle","FileSystemFlags","FileSystemGetDirectoryOptions","FileSystemGetFileOptions","FileSystemHandle","FileSystemHandleKind","FileSystemReadWriteOptions","FileSystemRemoveOptions","FileSystemSyncAccessHandle","FileSystemWritableFileStream","FileSystemWriteChunkType","FillLightMode","FillMode","FinalizationRegistry","FinalizationRegistryConstructor","FlatArray","Float16Array","Float16ArrayConstructor","Float32Array","Float32ArrayConstructor","Float32List","Float64Array","Float64ArrayConstructor","FocusEvent","FocusEventInit","FocusOptions","FontDisplay","FontFace","FontFaceDescriptors","FontFaceLoadStatus","FontFaceSet","FontFaceSetEventMap","FontFaceSetLoadEvent","FontFaceSetLoadEventInit","FontFaceSetLoadStatus","FontFaceSource","FormData","FormDataEntryValue","FormDataEvent","FormDataEventInit","FormDataIterator","FormattableTemporalObject","FragmentDirective","FrameRequestCallback","FrameType","FullscreenNavigationUI","FullscreenOptions","Function","FunctionConstructor","FunctionStringCallback","GLbitfield","GLboolean","GLclampf","GLenum","GLfloat","GLint","GLint64","GLintptr","GLsizei","GLsizeiptr","GLuint","GLuint64","GPU","GPUAdapter","GPUAdapterInfo","GPUAddressMode","GPUAutoLayoutMode","GPUBindGroup","GPUBindGroupDescriptor","GPUBindGroupEntry","GPUBindGroupLayout","GPUBindGroupLayoutDescriptor","GPUBindGroupLayoutEntry","GPUBindingCommandsMixin","GPUBindingResource","GPUBlendComponent","GPUBlendFactor","GPUBlendOperation","GPUBlendState","GPUBuffer","GPUBufferBinding","GPUBufferBindingLayout","GPUBufferBindingType","GPUBufferDescriptor","GPUBufferDynamicOffset","GPUBufferMapState","GPUBufferUsageFlags","GPUCanvasAlphaMode","GPUCanvasConfiguration","GPUCanvasContext","GPUCanvasToneMapping","GPUCanvasToneMappingMode","GPUColor","GPUColorDict","GPUColorTargetState","GPUColorWriteFlags","GPUCommandBuffer","GPUCommandBufferDescriptor","GPUCommandEncoder","GPUCommandEncoderDescriptor","GPUCompareFunction","GPUCompilationInfo","GPUCompilationMessage","GPUCompilationMessageType","GPUComputePassDescriptor","GPUComputePassEncoder","GPUComputePassTimestampWrites","GPUComputePipeline","GPUComputePipelineDescriptor","GPUCopyExternalImageDestInfo","GPUCopyExternalImageSource","GPUCopyExternalImageSourceInfo","GPUCullMode","GPUDebugCommandsMixin","GPUDepthBias","GPUDepthStencilState","GPUDevice","GPUDeviceDescriptor","GPUDeviceEventMap","GPUDeviceLostInfo","GPUDeviceLostReason","GPUError","GPUErrorFilter","GPUExtent3D","GPUExtent3DDict","GPUExternalTexture","GPUExternalTextureBindingLayout","GPUExternalTextureDescriptor","GPUFeatureName","GPUFilterMode","GPUFlagsConstant","GPUFragmentState","GPUFrontFace","GPUIndex32","GPUIndexFormat","GPUIntegerCoordinate","GPUIntegerCoordinateOut","GPUInternalError","GPULoadOp","GPUMapModeFlags","GPUMipmapFilterMode","GPUMultisampleState","GPUObjectBase","GPUObjectDescriptorBase","GPUOrigin2D","GPUOrigin2DDict","GPUOrigin3D","GPUOrigin3DDict","GPUOutOfMemoryError","GPUPipelineBase","GPUPipelineConstantValue","GPUPipelineDescriptorBase","GPUPipelineError","GPUPipelineErrorInit","GPUPipelineErrorReason","GPUPipelineLayout","GPUPipelineLayoutDescriptor","GPUPowerPreference","GPUPrimitiveState","GPUPrimitiveTopology","GPUProgrammableStage","GPUQuerySet","GPUQuerySetDescriptor","GPUQueryType","GPUQueue","GPUQueueDescriptor","GPURenderBundle","GPURenderBundleDescriptor","GPURenderBundleEncoder","GPURenderBundleEncoderDescriptor","GPURenderCommandsMixin","GPURenderPassColorAttachment","GPURenderPassDepthStencilAttachment","GPURenderPassDescriptor","GPURenderPassEncoder","GPURenderPassLayout","GPURenderPassTimestampWrites","GPURenderPipeline","GPURenderPipelineDescriptor","GPURequestAdapterOptions","GPUSampleMask","GPUSampler","GPUSamplerBindingLayout","GPUSamplerBindingType","GPUSamplerDescriptor","GPUShaderModule","GPUShaderModuleDescriptor","GPUShaderStageFlags","GPUSignedOffset32","GPUSize32","GPUSize32Out","GPUSize64","GPUSize64Out","GPUStencilFaceState","GPUStencilOperation","GPUStencilValue","GPUStorageTextureAccess","GPUStorageTextureBindingLayout","GPUStoreOp","GPUSupportedFeatures","GPUSupportedLimits","GPUTexelCopyBufferInfo","GPUTexelCopyBufferLayout","GPUTexelCopyTextureInfo","GPUTexture","GPUTextureAspect","GPUTextureBindingLayout","GPUTextureDescriptor","GPUTextureDimension","GPUTextureFormat","GPUTextureSampleType","GPUTextureUsageFlags","GPUTextureView","GPUTextureViewDescriptor","GPUTextureViewDimension","GPUUncapturedErrorEvent","GPUUncapturedErrorEventInit","GPUValidationError","GPUVertexAttribute","GPUVertexBufferLayout","GPUVertexFormat","GPUVertexState","GPUVertexStepMode","GainNode","GainOptions","Gamepad","GamepadButton","GamepadEffectParameters","GamepadEvent","GamepadEventInit","GamepadHapticActuator","GamepadHapticEffectType","GamepadHapticsResult","GamepadMappingType","Generator","GeneratorFunction","GeneratorFunctionConstructor","GenericTransformStream","Geolocation","GeolocationCoordinates","GeolocationPosition","GeolocationPositionError","GetAnimationsOptions","GetComposedRangesOptions","GetHTMLOptions","GetNotificationOptions","GetRootNodeOptions","Global","GlobalCompositeOperation","GlobalDescriptor","GlobalEventHandlers","GlobalEventHandlersEventMap","HTMLAllCollection","HTMLAnchorElement","HTMLAreaElement","HTMLAudioElement","HTMLBRElement","HTMLBaseElement","HTMLBodyElement","HTMLBodyElementEventMap","HTMLButtonElement","HTMLCanvasElement","HTMLCollection","HTMLCollectionBase","HTMLCollectionOf","HTMLDListElement","HTMLDataElement","HTMLDataListElement","HTMLDetailsElement","HTMLDialogElement","HTMLDirectoryElement","HTMLDivElement","HTMLDocument","HTMLElement","HTMLElementDeprecatedTagNameMap","HTMLElementEventMap","HTMLElementTagNameMap","HTMLEmbedElement","HTMLFieldSetElement","HTMLFontElement","HTMLFormControlsCollection","HTMLFormElement","HTMLFrameElement","HTMLFrameSetElement","HTMLFrameSetElementEventMap","HTMLHRElement","HTMLHeadElement","HTMLHeadingElement","HTMLHtmlElement","HTMLHyperlinkElementUtils","HTMLIFrameElement","HTMLImageElement","HTMLInputElement","HTMLLIElement","HTMLLabelElement","HTMLLegendElement","HTMLLinkElement","HTMLMapElement","HTMLMarqueeElement","HTMLMediaElement","HTMLMediaElementEventMap","HTMLMenuElement","HTMLMetaElement","HTMLMeterElement","HTMLModElement","HTMLOListElement","HTMLObjectElement","HTMLOptGroupElement","HTMLOptionElement","HTMLOptionsCollection","HTMLOrSVGElement","HTMLOrSVGImageElement","HTMLOrSVGScriptElement","HTMLOutputElement","HTMLParagraphElement","HTMLParamElement","HTMLPictureElement","HTMLPreElement","HTMLProgressElement","HTMLQuoteElement","HTMLScriptElement","HTMLSelectElement","HTMLSlotElement","HTMLSourceElement","HTMLSpanElement","HTMLStyleElement","HTMLTableCaptionElement","HTMLTableCellElement","HTMLTableColElement","HTMLTableDataCellElement","HTMLTableElement","HTMLTableHeaderCellElement","HTMLTableRowElement","HTMLTableSectionElement","HTMLTemplateElement","HTMLTextAreaElement","HTMLTimeElement","HTMLTitleElement","HTMLTrackElement","HTMLUListElement","HTMLUnknownElement","HTMLVideoElement","HTMLVideoElementEventMap","HardwareAcceleration","HashAlgorithmIdentifier","HashChangeEvent","HashChangeEventInit","HdrMetadataType","Headers","HeadersInit","HeadersIterator","Highlight","HighlightRegistry","HighlightType","History","HkdfParams","HmacImportParams","HmacKeyAlgorithm","HmacKeyGenParams","IArguments","IDBCursor","IDBCursorDirection","IDBCursorWithValue","IDBDatabase","IDBDatabaseEventMap","IDBDatabaseInfo","IDBFactory","IDBIndex","IDBIndexParameters","IDBKeyRange","IDBObjectStore","IDBObjectStoreParameters","IDBOpenDBRequest","IDBOpenDBRequestEventMap","IDBRequest","IDBRequestEventMap","IDBRequestReadyState","IDBTransaction","IDBTransactionDurability","IDBTransactionEventMap","IDBTransactionMode","IDBTransactionOptions","IDBValidKey","IDBVersionChangeEvent","IDBVersionChangeEventInit","IIRFilterNode","IIRFilterOptions","ITextWriter","IdleDeadline","IdleRequestCallback","IdleRequestOptions","Image","ImageBitmap","ImageBitmapOptions","ImageBitmapRenderingContext","ImageBitmapRenderingContextSettings","ImageBitmapSource","ImageBufferSource","ImageCapture","ImageData","ImageDataArray","ImageDataPixelFormat","ImageDataSettings","ImageDecodeOptions","ImageDecodeResult","ImageDecoder","ImageDecoderInit","ImageEncodeOptions","ImageOrientation","ImageSmoothingQuality","ImageTrack","ImageTrackList","Immediate","ImportAssertions","ImportAttributes","ImportCallOptions","ImportExportKind","ImportMeta","ImportNodeOptions","ImportValue","Imports","Infinity","InputDeviceInfo","InputEvent","InputEventInit","InsertPosition","Instance","InstanceType","Instant","InstantConstructor","InstantLike","InstantToStringOptions","Int16Array","Int16ArrayConstructor","Int32Array","Int32ArrayConstructor","Int32List","Int8Array","Int8ArrayConstructor","IntersectionObserver","IntersectionObserverCallback","IntersectionObserverEntry","IntersectionObserverInit","Intl","Iterable","IterableIterator","IterationCompositeOperation","Iterator","IteratorConstructor","IteratorObject","IteratorObjectConstructor","IteratorResult","IteratorReturnResult","IteratorYieldResult","JSON","JsonWebKey","KHR_parallel_shader_compile","KeyAlgorithm","KeyFormat","KeySystemTrackConfiguration","KeyType","KeyUsage","KeyboardEvent","KeyboardEventInit","Keyframe","KeyframeAnimationOptions","KeyframeEffect","KeyframeEffectOptions","LDMLPluralRule","LargestContentfulPaint","LatencyMode","LineAlignSetting","LineAndPositionSetting","LinkError","LinkStyle","ListFormat","ListFormatLocaleMatcher","ListFormatOptions","ListFormatStyle","ListFormatType","Locale","LocaleCollationCaseFirst","LocaleHourCycleKey","LocaleOptions","LocalesArgument","Location","Lock","LockGrantedCallback","LockInfo","LockManager","LockManagerSnapshot","LockMode","LockOptions","LoginStatus","Lowercase","MIDIAccess","MIDIAccessEventMap","MIDIConnectionEvent","MIDIConnectionEventInit","MIDIInput","MIDIInputEventMap","MIDIInputMap","MIDIMessageEvent","MIDIMessageEventInit","MIDIOptions","MIDIOutput","MIDIOutputMap","MIDIPort","MIDIPortConnectionState","MIDIPortDeviceState","MIDIPortEventMap","MIDIPortType","Map","MapConstructor","MapIterator","Math","MathMLElement","MathMLElementEventMap","MathMLElementTagNameMap","MediaCapabilities","MediaCapabilitiesDecodingInfo","MediaCapabilitiesEncodingInfo","MediaCapabilitiesInfo","MediaCapabilitiesKeySystemConfiguration","MediaConfiguration","MediaDecodingConfiguration","MediaDecodingType","MediaDeviceInfo","MediaDeviceKind","MediaDevices","MediaDevicesEventMap","MediaElementAudioSourceNode","MediaElementAudioSourceOptions","MediaEncodingConfiguration","MediaEncodingType","MediaEncryptedEvent","MediaEncryptedEventInit","MediaError","MediaImage","MediaKeyMessageEvent","MediaKeyMessageEventInit","MediaKeyMessageType","MediaKeySession","MediaKeySessionClosedReason","MediaKeySessionEventMap","MediaKeySessionType","MediaKeyStatus","MediaKeyStatusMap","MediaKeyStatusMapIterator","MediaKeySystemAccess","MediaKeySystemConfiguration","MediaKeySystemMediaCapability","MediaKeys","MediaKeysPolicy","MediaKeysRequirement","MediaList","MediaMetadata","MediaMetadataInit","MediaPositionState","MediaProvider","MediaQueryList","MediaQueryListEvent","MediaQueryListEventInit","MediaQueryListEventMap","MediaRecorder","MediaRecorderEventMap","MediaRecorderOptions","MediaSession","MediaSessionAction","MediaSessionActionDetails","MediaSessionActionHandler","MediaSessionPlaybackState","MediaSettingsRange","MediaSource","MediaSourceEventMap","MediaSourceHandle","MediaStream","MediaStreamAudioDestinationNode","MediaStreamAudioSourceNode","MediaStreamAudioSourceOptions","MediaStreamConstraints","MediaStreamEventMap","MediaStreamTrack","MediaStreamTrackEvent","MediaStreamTrackEventInit","MediaStreamTrackEventMap","MediaStreamTrackProcessor","MediaStreamTrackProcessorInit","MediaStreamTrackState","MediaTrackCapabilities","MediaTrackConstraintSet","MediaTrackConstraints","MediaTrackSettings","MediaTrackSupportedConstraints","Memory","MemoryDescriptor","MessageChannel","MessageEvent","MessageEventInit","MessageEventSource","MessageEventTarget","MessageEventTargetEventMap","MessagePort","MessagePortEventMap","MethodDecorator","MimeType","MimeTypeArray","Module","ModuleExportDescriptor","ModuleImportDescriptor","ModuleImports","MouseEvent","MouseEventInit","MultiCacheQueryOptions","MutationCallback","MutationObserver","MutationObserverInit","MutationRecord","MutationRecordType","NaN","NamedCurve","NamedNodeMap","NavigateEvent","NavigateEventInit","Navigation","NavigationActivation","NavigationCurrentEntryChangeEvent","NavigationCurrentEntryChangeEventInit","NavigationDestination","NavigationEventMap","NavigationFocusReset","NavigationHistoryBehavior","NavigationHistoryEntry","NavigationHistoryEntryEventMap","NavigationInterceptHandler","NavigationInterceptOptions","NavigationNavigateOptions","NavigationOptions","NavigationPrecommitController","NavigationPrecommitHandler","NavigationPreloadManager","NavigationPreloadState","NavigationReloadOptions","NavigationResult","NavigationScrollBehavior","NavigationTimingType","NavigationTransition","NavigationType","NavigationUpdateCurrentEntryOptions","Navigator","NavigatorAutomationInformation","NavigatorBadge","NavigatorConcurrentHardware","NavigatorContentUtils","NavigatorCookies","NavigatorGPU","NavigatorID","NavigatorLanguage","NavigatorLocks","NavigatorLogin","NavigatorOnLine","NavigatorPlugins","NavigatorStorage","NewableFunction","NoInfer","Node","NodeFilter","NodeIterator","NodeJS","NodeList","NodeListOf","NodeModule","NodeRequire","NonDocumentTypeChildNode","NonElementParentNode","NonNullable","Notification","NotificationDirection","NotificationEvent","NotificationEventInit","NotificationEventMap","NotificationOptions","NotificationPermission","NotificationPermissionCallback","Now","Number","NumberConstructor","NumberFormat","NumberFormatConstructor","NumberFormatOptions","NumberFormatOptionsCurrencyDisplay","NumberFormatOptionsCurrencyDisplayRegistry","NumberFormatOptionsSignDisplay","NumberFormatOptionsSignDisplayRegistry","NumberFormatOptionsStyle","NumberFormatOptionsStyleRegistry","NumberFormatOptionsUseGrouping","NumberFormatOptionsUseGroupingRegistry","NumberFormatPart","NumberFormatPartTypeRegistry","NumberFormatPartTypes","NumberFormatRangePartTypeRegistry","NumberFormatRangePartTypes","NumberRangeFormatPart","OES_draw_buffers_indexed","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_float_linear","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","OVR_multiview2","Object","ObjectConstructor","OfflineAudioCompletionEvent","OfflineAudioCompletionEventInit","OfflineAudioContext","OfflineAudioContextEventMap","OfflineAudioContextOptions","OffscreenCanvas","OffscreenCanvasEventMap","OffscreenCanvasRenderingContext2D","OffscreenRenderingContext","OffscreenRenderingContextId","Omit","OmitThisParameter","OnBeforeUnloadEventHandler","OnBeforeUnloadEventHandlerNonNull","OnErrorEventHandler","OnErrorEventHandlerNonNull","Option","OptionalEffectTiming","OptionalPostfixToken","OptionalPrefixToken","OpusBitstreamFormat","OpusEncoderConfig","OrientationLockType","OrientationType","OscillatorNode","OscillatorOptions","OscillatorType","OverSampleType","OverconstrainedError","OverflowOptions","PageRevealEvent","PageRevealEventInit","PageSwapEvent","PageSwapEventInit","PageTransitionEvent","PageTransitionEventInit","PaintTimingMixin","PannerNode","PannerOptions","PanningModelType","ParameterDecorator","Parameters","ParentNode","Partial","PartialTemporalLike","Path2D","PayerErrors","PaymentAddress","PaymentComplete","PaymentCurrencyAmount","PaymentDetailsBase","PaymentDetailsInit","PaymentDetailsModifier","PaymentDetailsUpdate","PaymentItem","PaymentMethodChangeEvent","PaymentMethodChangeEventInit","PaymentMethodData","PaymentOptions","PaymentRequest","PaymentRequestEventMap","PaymentRequestUpdateEvent","PaymentRequestUpdateEventInit","PaymentResponse","PaymentResponseEventMap","PaymentShippingOption","PaymentShippingType","PaymentValidationErrors","Pbkdf2Params","Performance","PerformanceEntry","PerformanceEntryList","PerformanceEventMap","PerformanceEventTiming","PerformanceMark","PerformanceMarkOptions","PerformanceMeasure","PerformanceMeasureOptions","PerformanceNavigation","PerformanceNavigationTiming","PerformanceObserver","PerformanceObserverCallback","PerformanceObserverEntryList","PerformanceObserverInit","PerformancePaintTiming","PerformanceResourceTiming","PerformanceServerTiming","PerformanceTiming","PeriodicWave","PeriodicWaveConstraints","PeriodicWaveOptions","PermissionDescriptor","PermissionName","PermissionState","PermissionStatus","PermissionStatusEventMap","Permissions","PhotoCapabilities","PhotoSettings","Pick","PictureInPictureEvent","PictureInPictureEventInit","PictureInPictureWindow","PictureInPictureWindowEventMap","PlainDate","PlainDateConstructor","PlainDateLike","PlainDateTime","PlainDateTimeConstructor","PlainDateTimeLike","PlainDateTimeToStringOptions","PlainDateToStringOptions","PlainDateToZonedDateTimeOptions","PlainMonthDay","PlainMonthDayConstructor","PlainMonthDayLike","PlainMonthDayToPlainDateOptions","PlainTime","PlainTimeConstructor","PlainTimeLike","PlainTimeToStringOptions","PlainYearMonth","PlainYearMonthConstructor","PlainYearMonthLike","PlainYearMonthToPlainDateOptions","PlaneLayout","PlaybackDirection","Plugin","PluginArray","PluralRuleType","PluralRules","PluralRulesConstructor","PluralRulesOptions","PluralizeUnit","PointerEvent","PointerEventInit","PointerLockOptions","PopStateEvent","PopStateEventInit","PopoverTargetAttributes","PositionAlignSetting","PositionCallback","PositionErrorCallback","PositionOptions","PredefinedColorSpace","PremultiplyAlpha","PresentationStyle","ProcessingInstruction","ProgressEvent","ProgressEventInit","Promise","PromiseConstructor","PromiseConstructorLike","PromiseFulfilledResult","PromiseLike","PromiseRejectedResult","PromiseRejectionEvent","PromiseRejectionEventInit","PromiseSettledResult","PromiseWithResolvers","PropertyDecorator","PropertyDefinition","PropertyDescriptor","PropertyDescriptorMap","PropertyIndexedKeyframes","PropertyKey","Proxy","ProxyConstructor","ProxyHandler","PublicKeyCredential","PublicKeyCredentialClientCapabilities","PublicKeyCredentialCreationOptions","PublicKeyCredentialCreationOptionsJSON","PublicKeyCredentialDescriptor","PublicKeyCredentialDescriptorJSON","PublicKeyCredentialEntity","PublicKeyCredentialParameters","PublicKeyCredentialRequestOptions","PublicKeyCredentialRequestOptionsJSON","PublicKeyCredentialRpEntity","PublicKeyCredentialType","PublicKeyCredentialUserEntity","PublicKeyCredentialUserEntityJSON","PushEncryptionKeyName","PushEvent","PushEventInit","PushManager","PushManagerAttribute","PushMessageData","PushMessageDataInit","PushSubscription","PushSubscriptionChangeEvent","PushSubscriptionChangeEventInit","PushSubscriptionJSON","PushSubscriptionOptions","PushSubscriptionOptionsInit","QueuingStrategy","QueuingStrategyInit","QueuingStrategySize","RTCAnswerOptions","RTCBundlePolicy","RTCCertificate","RTCCertificateExpiration","RTCConfiguration","RTCDTMFSender","RTCDTMFSenderEventMap","RTCDTMFToneChangeEvent","RTCDTMFToneChangeEventInit","RTCDataChannel","RTCDataChannelEvent","RTCDataChannelEventInit","RTCDataChannelEventMap","RTCDataChannelInit","RTCDataChannelState","RTCDegradationPreference","RTCDtlsFingerprint","RTCDtlsRole","RTCDtlsTransport","RTCDtlsTransportEventMap","RTCDtlsTransportState","RTCEncodedAudioFrame","RTCEncodedAudioFrameMetadata","RTCEncodedFrameMetadata","RTCEncodedVideoFrame","RTCEncodedVideoFrameMetadata","RTCError","RTCErrorDetailType","RTCErrorEvent","RTCErrorEventInit","RTCErrorInit","RTCIceCandidate","RTCIceCandidateInit","RTCIceCandidatePair","RTCIceCandidatePairStats","RTCIceCandidateType","RTCIceComponent","RTCIceConnectionState","RTCIceGathererState","RTCIceGatheringState","RTCIceProtocol","RTCIceRole","RTCIceServer","RTCIceTcpCandidateType","RTCIceTransport","RTCIceTransportEventMap","RTCIceTransportPolicy","RTCIceTransportState","RTCInboundRtpStreamStats","RTCLocalIceCandidateInit","RTCLocalSessionDescriptionInit","RTCOfferAnswerOptions","RTCOfferOptions","RTCOutboundRtpStreamStats","RTCPeerConnection","RTCPeerConnectionErrorCallback","RTCPeerConnectionEventMap","RTCPeerConnectionIceErrorEvent","RTCPeerConnectionIceErrorEventInit","RTCPeerConnectionIceEvent","RTCPeerConnectionIceEventInit","RTCPeerConnectionState","RTCPriorityType","RTCQualityLimitationReason","RTCReceivedRtpStreamStats","RTCRtcpMuxPolicy","RTCRtcpParameters","RTCRtpCapabilities","RTCRtpCodec","RTCRtpCodecParameters","RTCRtpCodingParameters","RTCRtpContributingSource","RTCRtpEncodingParameters","RTCRtpHeaderExtensionCapability","RTCRtpHeaderExtensionParameters","RTCRtpParameters","RTCRtpReceiveParameters","RTCRtpReceiver","RTCRtpReceiverTransform","RTCRtpScriptTransform","RTCRtpScriptTransformer","RTCRtpSendParameters","RTCRtpSender","RTCRtpSenderTransform","RTCRtpStreamStats","RTCRtpSynchronizationSource","RTCRtpTransceiver","RTCRtpTransceiverDirection","RTCRtpTransceiverInit","RTCSctpTransport","RTCSctpTransportEventMap","RTCSctpTransportState","RTCSdpType","RTCSentRtpStreamStats","RTCSessionDescription","RTCSessionDescriptionCallback","RTCSessionDescriptionInit","RTCSetParameterOptions","RTCSignalingState","RTCStats","RTCStatsIceCandidatePairState","RTCStatsReport","RTCStatsType","RTCTrackEvent","RTCTrackEventInit","RTCTransformEvent","RTCTransportStats","RadioNodeList","Range","RangeError","RangeErrorConstructor","ReadableByteStreamController","ReadableStream","ReadableStreamAsyncIterator","ReadableStreamBYOBReader","ReadableStreamBYOBReaderReadOptions","ReadableStreamBYOBRequest","ReadableStreamController","ReadableStreamDefaultController","ReadableStreamDefaultReader","ReadableStreamGenericReader","ReadableStreamGetReaderOptions","ReadableStreamIteratorOptions","ReadableStreamReadDoneResult","ReadableStreamReadResult","ReadableStreamReadValueResult","ReadableStreamReader","ReadableStreamReaderMode","ReadableStreamType","ReadableWritablePair","Readonly","ReadonlyArray","ReadonlyMap","ReadonlySet","ReadonlySetLike","ReadyState","Record","RecordingState","RedEyeReduction","ReferenceError","ReferenceErrorConstructor","ReferrerPolicy","Reflect","RegExp","RegExpConstructor","RegExpExecArray","RegExpIndicesArray","RegExpMatchArray","RegExpStringIterator","RegistrationOptions","RegistrationResponseJSON","RelativeTimeFormat","RelativeTimeFormatLocaleMatcher","RelativeTimeFormatNumeric","RelativeTimeFormatOptions","RelativeTimeFormatPart","RelativeTimeFormatStyle","RelativeTimeFormatUnit","RelativeTimeFormatUnitSingular","RemotePlayback","RemotePlaybackAvailabilityCallback","RemotePlaybackEventMap","RemotePlaybackState","RenderingContext","Report","ReportBody","ReportList","ReportingObserver","ReportingObserverCallback","ReportingObserverOptions","Request","RequestCache","RequestCredentials","RequestDestination","RequestInfo","RequestInit","RequestMode","RequestPriority","RequestRedirect","Required","ResidentKeyRequirement","ResizeObserver","ResizeObserverBoxOptions","ResizeObserverCallback","ResizeObserverEntry","ResizeObserverOptions","ResizeObserverSize","ResizeQuality","ResolvedCollatorOptions","ResolvedDateTimeFormatOptions","ResolvedDisplayNamesOptions","ResolvedDurationFormatOptions","ResolvedListFormatOptions","ResolvedNumberFormatOptions","ResolvedNumberFormatOptionsUseGrouping","ResolvedPluralRulesOptions","ResolvedRelativeTimeFormatOptions","ResolvedSegmenterOptions","Response","ResponseInit","ResponseType","ReturnType","RoundingOptions","RoundingOptionsWithLargestUnit","RsaHashedImportParams","RsaHashedKeyAlgorithm","RsaHashedKeyGenParams","RsaKeyAlgorithm","RsaKeyGenParams","RsaOaepParams","RsaOtherPrimesInfo","RsaPssParams","RuntimeError","SVGAElement","SVGAngle","SVGAnimateElement","SVGAnimateMotionElement","SVGAnimateTransformElement","SVGAnimatedAngle","SVGAnimatedBoolean","SVGAnimatedEnumeration","SVGAnimatedInteger","SVGAnimatedLength","SVGAnimatedLengthList","SVGAnimatedNumber","SVGAnimatedNumberList","SVGAnimatedPoints","SVGAnimatedPreserveAspectRatio","SVGAnimatedRect","SVGAnimatedString","SVGAnimatedTransformList","SVGAnimationElement","SVGBoundingBoxOptions","SVGCircleElement","SVGClipPathElement","SVGComponentTransferFunctionElement","SVGDefsElement","SVGDescElement","SVGElement","SVGElementEventMap","SVGElementTagNameMap","SVGEllipseElement","SVGFEBlendElement","SVGFEColorMatrixElement","SVGFEComponentTransferElement","SVGFECompositeElement","SVGFEConvolveMatrixElement","SVGFEDiffuseLightingElement","SVGFEDisplacementMapElement","SVGFEDistantLightElement","SVGFEDropShadowElement","SVGFEFloodElement","SVGFEFuncAElement","SVGFEFuncBElement","SVGFEFuncGElement","SVGFEFuncRElement","SVGFEGaussianBlurElement","SVGFEImageElement","SVGFEMergeElement","SVGFEMergeNodeElement","SVGFEMorphologyElement","SVGFEOffsetElement","SVGFEPointLightElement","SVGFESpecularLightingElement","SVGFESpotLightElement","SVGFETileElement","SVGFETurbulenceElement","SVGFilterElement","SVGFilterPrimitiveStandardAttributes","SVGFitToViewBox","SVGForeignObjectElement","SVGGElement","SVGGeometryElement","SVGGradientElement","SVGGraphicsElement","SVGImageElement","SVGLength","SVGLengthList","SVGLineElement","SVGLinearGradientElement","SVGMPathElement","SVGMarkerElement","SVGMaskElement","SVGMatrix","SVGMetadataElement","SVGNumber","SVGNumberList","SVGPathElement","SVGPatternElement","SVGPoint","SVGPointList","SVGPolygonElement","SVGPolylineElement","SVGPreserveAspectRatio","SVGRadialGradientElement","SVGRect","SVGRectElement","SVGSVGElement","SVGSVGElementEventMap","SVGScriptElement","SVGSetElement","SVGStopElement","SVGStringList","SVGStyleElement","SVGSwitchElement","SVGSymbolElement","SVGTSpanElement","SVGTests","SVGTextContentElement","SVGTextElement","SVGTextPathElement","SVGTextPositioningElement","SVGTitleElement","SVGTransform","SVGTransformList","SVGURIReference","SVGUnitTypes","SVGUseElement","SVGViewElement","Sanitizer","SanitizerAttribute","SanitizerAttributeNamespace","SanitizerConfig","SanitizerElement","SanitizerElementNamespace","SanitizerElementNamespaceWithAttributes","SanitizerElementWithAttributes","SanitizerPresets","Scheduler","SchedulerPostTaskCallback","SchedulerPostTaskOptions","Screen","ScreenOrientation","ScreenOrientationEventMap","ScriptProcessorNode","ScriptProcessorNodeEventMap","ScrollAxis","ScrollBehavior","ScrollIntoViewOptions","ScrollLogicalPosition","ScrollOptions","ScrollRestoration","ScrollSetting","ScrollTimeline","ScrollTimelineOptions","ScrollToOptions","SecurityPolicyViolationEvent","SecurityPolicyViolationEventDisposition","SecurityPolicyViolationEventInit","SegmentData","SegmentIterator","Segmenter","SegmenterOptions","Segments","Selection","SelectionDirection","SelectionMode","Server","ServerWebSocket","ServiceWorker","ServiceWorkerContainer","ServiceWorkerContainerEventMap","ServiceWorkerEventMap","ServiceWorkerGlobalScope","ServiceWorkerGlobalScopeEventMap","ServiceWorkerRegistration","ServiceWorkerRegistrationEventMap","ServiceWorkerState","ServiceWorkerUpdateViaCache","Set","SetConstructor","SetIterator","ShadowRoot","ShadowRootEventMap","ShadowRootInit","ShadowRootMode","ShareData","SharedArrayBuffer","SharedArrayBufferConstructor","SharedWorker","SharedWorkerGlobalScope","SharedWorkerGlobalScopeEventMap","ShellPromise","ShowPopoverOptions","SlotAssignmentMode","Slottable","Socket","SocketHandler","SourceBuffer","SourceBufferEventMap","SourceBufferList","SourceBufferListEventMap","SpeechRecognitionAlternative","SpeechRecognitionErrorCode","SpeechRecognitionErrorEvent","SpeechRecognitionErrorEventInit","SpeechRecognitionEvent","SpeechRecognitionEventInit","SpeechRecognitionResult","SpeechRecognitionResultList","SpeechSynthesis","SpeechSynthesisErrorCode","SpeechSynthesisErrorEvent","SpeechSynthesisErrorEventInit","SpeechSynthesisEvent","SpeechSynthesisEventInit","SpeechSynthesisEventMap","SpeechSynthesisUtterance","SpeechSynthesisUtteranceEventMap","SpeechSynthesisVoice","StartViewTransitionOptions","StaticRange","StaticRangeInit","Stats","StereoPannerNode","StereoPannerOptions","Storage","StorageEstimate","StorageEvent","StorageEventInit","StorageManager","StreamPipeOptions","String","StringConstructor","StringIterator","StringNumericLiteral","StructuredSerializeOptions","StylePropertyMap","StylePropertyMapReadOnly","StylePropertyMapReadOnlyIterator","StyleSheet","StyleSheetList","SubmitEvent","SubmitEventInit","Subprocess","SubtleCrypto","SuppressedError","SuppressedErrorConstructor","SvcOutputMetadata","Symbol","SymbolConstructor","SyntaxError","SyntaxErrorConstructor","TCPSocket","Table","TableDescriptor","TableKind","Tag","TagType","TaskController","TaskControllerInit","TaskPriority","TaskPriorityChangeEvent","TaskPriorityChangeEventInit","TaskSignal","TaskSignalAnyInit","TaskSignalEventMap","TemplateStringsArray","Temporal","TexImageSource","Text","TextDecodeOptions","TextDecoder","TextDecoderCommon","TextDecoderOptions","TextDecoderStream","TextEncoder","TextEncoderCommon","TextEncoderEncodeIntoResult","TextEncoderStream","TextEvent","TextInfo","TextMetrics","TextStreamBase","TextStreamReader","TextStreamWriter","TextTrack","TextTrackCue","TextTrackCueEventMap","TextTrackCueList","TextTrackEventMap","TextTrackKind","TextTrackList","TextTrackListEventMap","TextTrackMode","ThisParameterType","ThisType","TimeLikeObject","TimeRanges","TimeUnit","TimeZoneLike","TimelineRangeOffset","Timeout","Timer","TimerHandler","ToStringRoundingOptions","ToStringRoundingOptionsWithFractionalSeconds","ToggleEvent","ToggleEventInit","TogglePopoverOptions","Touch","TouchEvent","TouchEventInit","TouchInit","TouchList","TouchType","TrackEvent","TrackEventInit","TransferFunction","Transferable","TransformStream","TransformStreamDefaultController","Transformer","TransformerFlushCallback","TransformerStartCallback","TransformerTransformCallback","TransitionEvent","TransitionEventInit","TransitionOptions","TreeWalker","TypeError","TypeErrorConstructor","TypedArray","TypedPropertyDescriptor","UIEvent","UIEventInit","ULongRange","URIError","URIErrorConstructor","URL","URLPattern","URLPatternComponentResult","URLPatternInit","URLPatternInput","URLPatternOptions","URLPatternResult","URLSearchParams","URLSearchParamsIterator","Uint16Array","Uint16ArrayConstructor","Uint32Array","Uint32ArrayConstructor","Uint32List","Uint8Array","Uint8ArrayConstructor","Uint8ClampedArray","Uint8ClampedArrayConstructor","Uncapitalize","UnderlyingByteSource","UnderlyingDefaultSource","UnderlyingSink","UnderlyingSinkAbortCallback","UnderlyingSinkCloseCallback","UnderlyingSinkStartCallback","UnderlyingSinkWriteCallback","UnderlyingSource","UnderlyingSourceCancelCallback","UnderlyingSourcePullCallback","UnderlyingSourceStartCallback","UnicodeBCP47LocaleIdentifier","UnknownCredentialOptions","Uppercase","UserActivation","UserVerificationRequirement","VBArray","VBArrayConstructor","VTTCue","VTTRegion","ValidityState","ValidityStateFlags","ValueType","ValueTypeMap","VibratePattern","VideoColorPrimaries","VideoColorSpace","VideoColorSpaceInit","VideoConfiguration","VideoDecoder","VideoDecoderConfig","VideoDecoderEventMap","VideoDecoderInit","VideoDecoderSupport","VideoEncoder","VideoEncoderBitrateMode","VideoEncoderConfig","VideoEncoderEncodeOptions","VideoEncoderEncodeOptionsForAvc","VideoEncoderEventMap","VideoEncoderInit","VideoEncoderSupport","VideoFacingModeEnum","VideoFrame","VideoFrameBufferInit","VideoFrameCallbackMetadata","VideoFrameCopyToOptions","VideoFrameInit","VideoFrameOutputCallback","VideoFrameRequestCallback","VideoMatrixCoefficients","VideoPixelFormat","VideoPlaybackQuality","VideoTransferCharacteristics","ViewTimeline","ViewTimelineOptions","ViewTransition","ViewTransitionTypeSet","ViewTransitionUpdateCallback","VisualViewport","VisualViewportEventMap","VoidFunction","WEBGL_color_buffer_float","WEBGL_compressed_texture_astc","WEBGL_compressed_texture_etc","WEBGL_compressed_texture_etc1","WEBGL_compressed_texture_pvrtc","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_depth_texture","WEBGL_draw_buffers","WEBGL_lose_context","WEBGL_multi_draw","WGSLLanguageFeatures","WSH","WScript","WakeLock","WakeLockSentinel","WakeLockSentinelEventMap","WakeLockType","WaveShaperNode","WaveShaperOptions","WeakKey","WeakKeyTypes","WeakMap","WeakMapConstructor","WeakRef","WeakRefConstructor","WeakSet","WeakSetConstructor","WebAssembly","WebAssemblyCompileOptions","WebAssemblyInstantiatedSource","WebCodecsErrorCallback","WebGL2RenderingContext","WebGL2RenderingContextBase","WebGL2RenderingContextOverloads","WebGLActiveInfo","WebGLBuffer","WebGLContextAttributes","WebGLContextEvent","WebGLContextEventInit","WebGLFramebuffer","WebGLPowerPreference","WebGLProgram","WebGLQuery","WebGLRenderbuffer","WebGLRenderingContext","WebGLRenderingContextBase","WebGLRenderingContextOverloads","WebGLSampler","WebGLShader","WebGLShaderPrecisionFormat","WebGLSync","WebGLTexture","WebGLTransformFeedback","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES","WebKitCSSMatrix","WebSocket","WebSocketEventMap","WebSocketHandler","WebTransport","WebTransportBidirectionalStream","WebTransportCloseInfo","WebTransportCongestionControl","WebTransportDatagramDuplexStream","WebTransportError","WebTransportErrorOptions","WebTransportErrorSource","WebTransportHash","WebTransportOptions","WebTransportSendOptions","WebTransportSendStreamOptions","WeekInfo","WheelEvent","WheelEventInit","Window","WindowClient","WindowEventHandlers","WindowEventHandlersEventMap","WindowEventMap","WindowLocalStorage","WindowOrWorkerGlobalScope","WindowPostMessageOptions","WindowProxy","WindowSessionStorage","WithImplicitCoercion","Worker","WorkerEventMap","WorkerGlobalScope","WorkerGlobalScopeEventMap","WorkerLocation","WorkerNavigator","WorkerOptions","WorkerType","Worklet","WorkletOptions","WritableStream","WritableStreamDefaultController","WritableStreamDefaultWriter","WriteCommandType","WriteParams","XMLDocument","XMLHttpRequest","XMLHttpRequestBodyInit","XMLHttpRequestEventMap","XMLHttpRequestEventTarget","XMLHttpRequestEventTargetEventMap","XMLHttpRequestResponseType","XMLHttpRequestUpload","XMLSerializer","XPathEvaluator","XPathEvaluatorBase","XPathExpression","XPathNSResolver","XPathResult","XSLTProcessor","YearMonthLikeObject","ZonedDateTime","ZonedDateTimeConstructor","ZonedDateTimeFromOptions","ZonedDateTimeLike","ZonedDateTimeLikeObject","ZonedDateTimeToStringOptions","global","globalThis","process","structuredClone"])});function go(e,t={strings:!0}){let r="",n=0;while(n<e.length){let i=e.slice(n,n+2);if(i==="//"){let a=e.indexOf(`
|
|
66
|
-
`,n),o
|
|
65
|
+
`;return r}}function Mu(e,t,r={}){return aa(e,t,r,new WeakMap)}function aa(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 a=o(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return la(e,t,i,n);if(!et(t)||!et(e))return t;return Nu(e,t,r,n)}function la(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 Du(e,t);case"smart":return Iu(e,t,n);default:return t}return t}function Du(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Mn(i,n)))r.push(n);return r}function Iu(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(et(t[0])&&et(e[0]))return Fu(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 Fu(e,t,r){let n=[...t];for(let i of e){if(!et(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let a of s)if(a in i){if(n.find((c)=>et(c)&&(a in c)&&c[a]===i[a])){o=!0;break}}if(!o)n.push(i)}return n}function Nu(e,t,r,n){let i=t;if(et(i)&&n.has(i))return n.get(i);let s={...e};if(et(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let a=i[o],c=s[o];if(r.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){s[o]=a;continue}if(et(a)&&et(c))s[o]=aa(c,a,r,n);else if(Array.isArray(a)||Array.isArray(c))s[o]=la(c,a,r.arrayMergeMode||"smart",n);else s[o]=a}return s}function ca(e,t,r="replace"){return Mu(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Mn(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(!Mn(e[r],t[r]))return!1;return!0}if(et(e)&&et(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(!Mn(e[i],t[i]))return!1}return!0}return!1}function et(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class fa{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:a=!1}=r;if(i){let f=si.getWithFileCheck("file",e);if(f){if(a)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!Ur(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,g="default"in u,d=Object.keys(u).length>0;if(!g&&!d)throw new di(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new di(e,Error("Configuration must export a valid object"),"unknown");let E={config:ca(t,l,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)si.setWithFileCheck("file",E,e,s);return E}catch(f){throw f instanceof Error?tr.configLoad(e,f):tr.configLoad(e,Error(String(f)))}};if(o)return Dn.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(pn(t,`${s}${o}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let s of n){if(!s)continue;if(r.push(s,`.${s}.config`,`${s}.config`,`.${s}`),e)r.push(`${e}.${s}.config`,`.${e}.${s}.config`)}let i=new Set;return r.filter((s)=>{if(!s||i.has(s))return!1;return i.add(s),!0})}checkFileAccess(e){return ku(async()=>Ur(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Ur(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let a=pn(e,`${s}${o}`);if(await this.checkFileAccess(a))n.push(a)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let a=pn(e,o);if(await this.checkFileAccess(a))n.push(a)}}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((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!Ur(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 ua{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:a=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],g={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,g);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],g);else return this.validateWithJSONSchema(e,t,g)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(a)return await Dn.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!yf(t))throw new mi(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 mi(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,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(o)){if(n.push({path:r,message:`Expected type ${a.join(" or ")}, got ${o}`,expected:a.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 a=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,a,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 a of t.required)if(!(a in o)){if(n.push({path:r?`${r}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[a,c]of Object.entries(t.properties))if(a in o){let f=r?`${r}.${a}`:a;if(this.validateObjectAgainstSchema(o[a],c,f,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(o))if(!a.has(c))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),a=this.validateWithRule(o,s,s.path);if(n.push(...a),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:Wu},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function Lu(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class ha{fileLoader=new fa;envProcessor=new _n;validator=new ua;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let c=this.checkCache(o.name||"",o);if(c)return c}let a;try{a=await this.loadConfigurationStrategies(o,!0,r)}catch(c){let f=o.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;a={...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(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),l=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),g=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(g||u))throw c;if(l&&(!f||!g))a={...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(!f)a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(i||s)await this.validateConfiguration(a.config,i,s,o.name);if(r?.enabled&&a)this.cacheResult(o.name||"",a,r,o);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)pt.warn(`Slow configuration loading detected: ${c.duration}ms for ${o.name}`);a.metrics=c}return a}catch(a){if(a instanceof Error&&a.name==="ConfigNotFoundError")throw a;let c=Date.now()-t;throw pt.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:a,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=s||pi.cwd(),g=[],d=await this.loadLocalConfiguration(n,i,l,o,a,f,u,c,r);if(d)return g.push(...this.getLocalSearchPaths(n,i,l,o)),this.finalizeResult(d,g,c,n,u);let E=await this.loadHomeConfiguration(n,i,a,f,u,c);if(E)return g.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(E,g,c,n,u);let S=await this.loadPackageJsonConfiguration(n,i,l,a,f,u,c);if(S)return g.push(ze(l,"package.json")),this.finalizeResult(S,g,c,n,u);if(g.push(...this.getAllSearchPaths(n,i,l,o)),t)throw tr.configNotFound(n,g,i);return{...await this.applyEnvironmentVariables(n,a,c,u),warnings:[`No configuration file found for "${n}"${Lu(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,a,c){let f=a?Zr(e,i,o):i,u=this.getLocalDirectories(r,n);for(let l of u){if(o)pt.info(`Searching for configuration in: ${l}`);let g=this.fileLoader.generateConfigPaths(e,l,t),d=await this.fileLoader.tryLoadFromPaths(g,f,{arrayStrategy:s,verbose:o,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(d){if(o)pt.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?Zr(e,r,i):r,a=[ze(Ht(),".config",e),ze(Ht(),".config"),Ht()];for(let c of a){if(i)pt.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,o,{arrayStrategy:n,verbose:i});if(u){if(i)pt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let a=o?Zr(e,n,s):n;try{let c=ze(r,"package.json");if(!Pc(c))return null;let f={};try{f=JSON.parse(kc(c,"utf8"))}catch(g){if(s)pt.warn("Failed to parse package.json:",[g instanceof Error?g:Error(String(g))]);return null}let u=f[e],l=e;if(!u&&t){let g=Array.isArray(t)?t:[t];for(let d of g){if(!d)continue;if(f[d]){u=f[d],l=d;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)pt.success(`Configuration loaded from package.json: ${l}`);return{config:ca(a,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)pt.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Zr(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 tr.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return si.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);si.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.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,ze(e,"config"),ze(e,".config"),t?ze(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(ze(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=[ze(Ht(),".config",e),ze(Ht(),".config"),Ht()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function Zr(e,t,r=!1){let n=new _n,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,a=[]){let c={...o};for(let[f,u]of Object.entries(o)){let l=[...a,f],g=[`${i}_${l.join("_").toUpperCase()}`,`${i}_${l.map((S)=>S.toUpperCase()).join("")}`,`${i}_${l.map((S)=>S.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,E;for(let S of g)if(d=pi.env[S],d!==void 0){E=S;break}if(d!==void 0&&E)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let S=Number(d);if(!Number.isNaN(S))c[f]=S}else if(Array.isArray(u))try{c[f]=JSON.parse(d)}catch{c[f]=d.split(",").map((S)=>S.trim())}else c[f]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,l)}return c}return s(t)}var si,Dn,Cf,wf=(e)=>e,Ef=(e,t)=>{for(var r in t)Cf(e,r,{get:t[r],enumerable:!0,configurable:!0,set:$f.bind(t,r)})},vf=(e,t)=>()=>(e&&(t=e(e=0)),t),Fo,jo,er,gr,Ko,Zf,qf,wo,Xr,bn,Ve,ye,Xf,$o,zf,Eo,Qf,eu,gn,tu,vo,So,yn,ru,iu,nu,su,zr,Jo,ou,_e,au,lu,bo,Qr,An,Ie,te,cu,Ao,fu,xo,uu,hu,Cn,du,To,Ro,mu,wn,pu,gu,yu,Cu,wu,ei,Uo,$u,Eu="0.15.6",Ze,fi,mr,xn,Tn,ui,Rn,On,pr,Pn,kn,Tt,Yo,Zo,at,wt,qo,Xo,vu,bu,zo,hi,yg,Le,ie,Cg,xu,wg,Tu,$g,Eg,Oo,vg,Ru,Ou,Sg,Po,bg,Ag,xg,Tg,Rg,$n,Pu,Og,lt,ea,di,ta,ra,Vn,ia,na,mi,sa,oa,tr,Wu,pt,Pg,kg,Mg,Gu,da;var ma=ce(()=>{si=new Do,Dn=new Io,Cf=Object.defineProperty;Fo={};Ef(Fo,{withErrorRecovery:()=>Lo,tryLoadConfig:()=>Kf,loadConfigWithResult:()=>Hf,loadConfig:()=>Ho,isRetryableError:()=>Wf,isConfigNotFoundError:()=>Nf,isBunfigError:()=>Go,globalPerformanceMonitor:()=>gr,globalCache:()=>er,getEnvOrDefault:()=>Lf,generateConfigTypes:()=>Jf,defaultGeneratedDir:()=>Xo,defaultConfigDir:()=>qo,deepMergeWithArrayStrategy:()=>Ln,deepMerge:()=>Bo,createLibraryConfig:()=>Uf,config:()=>jf,bunfigPlugin:()=>Yf,applyEnvVarsToConfig:()=>hr,TypeGenerationError:()=>On,SchemaValidationError:()=>pr,PluginError:()=>kn,PerformanceMonitor:()=>Fn,FileSystemError:()=>Rn,ErrorFactory:()=>Tt,EnvVarError:()=>ui,EnvProcessor:()=>gi,ConfigValidator:()=>Gn,ConfigValidationError:()=>xn,ConfigNotFoundError:()=>fi,ConfigMergeError:()=>Tn,ConfigLoader:()=>Bn,ConfigLoadError:()=>mr,ConfigFileLoader:()=>yi,ConfigCache:()=>In,CacheUtils:()=>Ko,BunfigError:()=>Ze,BrowserConfigError:()=>Pn,ArrayMergeStrategies:()=>Yo});vu=vf(async()=>{jo=import.meta.require,er=new In,gr=new Fn,Ko={createKey:Sf,isEquivalent:bf,estimateMemoryUsage:Af},Zf=ii(vn.cwd(),"config"),qf=ii(vn.cwd(),"src/generated"),wo=ri.env.CLARITY_LOG_DIR||Wc(Rf(),"logs"),Xr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:wo,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},bn=await Of(),Ve={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"},ye=Ve,Xf=Ve.red,$o=Ve.green,zf=Ve.yellow,Eo=Ve.blue,Qf=Ve.magenta,eu=Ve.cyan,gn=Ve.white,tu=Ve.gray,vo=Ve.bgRed,So=Ve.bgYellow,yn=Ve.bold,ru=Ve.dim,iu=Ve.italic,nu=Ve.underline,su=Ve.reset,zr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Jo={debug:"\uD83D\uDD0D",info:Eo("\u2139"),success:$o("\u2713"),warning:So(gn(yn(" WARN "))),error:vo(gn(yn(" ERROR ")))},ou=new ai("stacks"),_e=new ai("bunfig",{showTags:!0}),au=He(dr.cwd(),"config"),lu=He(dr.cwd(),"src/generated"),bo=ti.env.CLARITY_LOG_DIR||Fc(Df(),"logs"),Qr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:bo,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},An=await If(),Ie={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"},te=Ie,cu=Ie.red,Ao=Ie.green,fu=Ie.yellow,xo=Ie.blue,uu=Ie.magenta,hu=Ie.cyan,Cn=Ie.white,du=Ie.gray,To=Ie.bgRed,Ro=Ie.bgYellow,mu=Ie.bgGray,wn=Ie.bold,pu=Ie.dim,gu=Ie.italic,yu=Ie.underline,Cu=Ie.strikethrough,wu=Ie.reset,ei={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Uo={debug:"\uD83D\uDD0D",info:xo("\u2139"),success:Ao("\u2713"),warning:Ro(Cn(wn(" WARN "))),error:To(Cn(wn(" ERROR ")))},$u=new ci("stacks"),Ze=class extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},fi=class extends Ze{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r?` or alias "${r}"`:"";super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},mr=class extends Ze{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},xn=class extends Ze{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Tn=class extends Ze{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},ui=class extends Ze{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}},Rn=class extends Ze{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},On=class extends Ze{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},pr=class extends Ze{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Pn=class extends Ze{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}},kn=class extends Ze{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Tt={configNotFound(e,t,r){return new fi(e,t,r)},configLoad(e,t,r){return new mr(e,t,r)},configValidation(e,t,r){return new xn(e,t,r)},configMerge(e,t,r,n){return new Tn(e,t,r,n)},envVar(e,t,r,n){return new ui(e,t,r,n)},fileSystem(e,t,r){return new Rn(e,t,r)},typeGeneration(e,t,r){return new On(e,t,r)},schemaValidation(e,t,r){return new pr(e,t,r)},browserConfig(e,t,r,n){return new Pn(e,t,r,n)},plugin(e,t,r){return new kn(e,t,r)}},Yo={replace:"replace",concat:"concat",smart:"smart"},Zo=/^https?:\/\//,at=new ci("bunfig",{showTags:!0}),wt=new Bn,qo=je(Ot.cwd(),"config"),Xo=je(Ot.cwd(),"src/generated")});bu=ni.env.CLARITY_LOG_DIR||of(Su(),"logs"),zo={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:bu,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},hi={...zo},yg=(async()=>{try{let{loadConfig:e}=await vu().then(()=>Fo),t=await e({name:"clarity",alias:"logging",defaultConfig:zo,cwd:ni.cwd()});if(t)Object.assign(hi,t)}catch{}return hi})();Le={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"},ie=Le,Cg=Le.red,xu=Le.green,wg=Le.yellow,Tu=Le.blue,$g=Le.magenta,Eg=Le.cyan,Oo=Le.white,vg=Le.gray,Ru=Le.bgRed,Ou=Le.bgYellow,Sg=Le.bgGray,Po=Le.bold,bg=Le.dim,Ag=Le.italic,xg=Le.underline,Tg=Le.strikethrough,Rg=Le.reset,$n={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Pu={debug:"\uD83D\uDD0D",info:Tu("\u2139"),success:xu("\u2713"),warning:Ou(Oo(Po(" WARN "))),error:Ru(Oo(Po(" ERROR ")))};Og=new Ci("stacks");lt=class lt extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}};ea=class ea extends lt{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],i="";if(n.length===1)i=` or alias "${n[0]}"`;else if(n.length>1)i=` or aliases ${n.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}};di=class di extends lt{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}};ta=class ta extends lt{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};ra=class ra extends lt{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}};Vn=class Vn extends lt{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}};ia=class ia extends lt{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}};na=class na extends lt{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}};mi=class mi extends lt{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}};sa=class sa extends lt{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}};oa=class oa extends lt{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}};tr={configNotFound(e,t,r){return new ea(e,t,r)},configLoad(e,t,r){return new di(e,t,r)},configValidation(e,t,r){return new ta(e,t,r)},configMerge(e,t,r,n){return new ra(e,t,r,n)},envVar(e,t,r,n){return new Vn(e,t,r,n)},fileSystem(e,t,r){return new ia(e,t,r)},typeGeneration(e,t,r){return new na(e,t,r)},schemaValidation(e,t,r){return new mi(e,t,r)},browserConfig(e,t,r,n){return new sa(e,t,r,n)},plugin(e,t,r){return new oa(e,t,r)}};Wu=/^https?:\/\//;pt=new Ci("bunfig",{showTags:!0});Pg=new ha;kg=ze(pi.cwd(),"config"),Mg=ze(pi.cwd(),"src/generated"),Gu={cwd:Oc.cwd(),root:"./src",entrypoints:["**/*.{ts,tsx,mts,cts,vue,stx}"],outdir:"./dist",keepComments:!0,clean:!0,tsconfigPath:"./tsconfig.json",outputStructure:"mirror",verbose:!1,importOrder:["bun"],declarationMap:!1},da=Gu});var pa;var ga=ce(()=>{pa=new Set(["ANGLE_instanced_arrays","ARIAMixin","AacBitstreamFormat","AacEncoderConfig","AbortController","AbortSignal","AbortSignalEventMap","AbstractRange","AbstractWorker","AbstractWorkerEventMap","ActiveXObject","AddEventListenerOptions","AddressErrors","AddressType","AddressValue","AesCbcParams","AesCtrParams","AesDerivedKeyParams","AesGcmParams","AesKeyAlgorithm","AesKeyGenParams","AggregateError","AggregateErrorConstructor","Algorithm","AlgorithmIdentifier","AlignSetting","AllAcceptedCredentialsOptions","AllowSharedBufferSource","AlphaOption","AnalyserNode","AnalyserOptions","Animatable","Animation","AnimationEffect","AnimationEvent","AnimationEventInit","AnimationEventMap","AnimationFrameProvider","AnimationPlayState","AnimationPlaybackEvent","AnimationPlaybackEventInit","AnimationReplaceState","AnimationTimeline","AppendMode","Array","ArrayBuffer","ArrayBufferConstructor","ArrayBufferLike","ArrayBufferTypes","ArrayBufferView","ArrayConstructor","ArrayIterator","ArrayLike","AssignedNodesOptions","AsyncDisposable","AsyncDisposableStack","AsyncDisposableStackConstructor","AsyncGenerator","AsyncGeneratorFunction","AsyncGeneratorFunctionConstructor","AsyncIterable","AsyncIterableIterator","AsyncIterator","AsyncIteratorObject","Atomics","AttestationConveyancePreference","Attr","Audio","AudioBuffer","AudioBufferOptions","AudioBufferSourceNode","AudioBufferSourceOptions","AudioConfiguration","AudioContext","AudioContextLatencyCategory","AudioContextOptions","AudioContextState","AudioData","AudioDataCopyToOptions","AudioDataInit","AudioDataOutputCallback","AudioDecoder","AudioDecoderConfig","AudioDecoderEventMap","AudioDecoderInit","AudioDecoderSupport","AudioDestinationNode","AudioEncoder","AudioEncoderConfig","AudioEncoderEventMap","AudioEncoderInit","AudioEncoderSupport","AudioListener","AudioNode","AudioNodeOptions","AudioParam","AudioParamMap","AudioProcessingEvent","AudioProcessingEventInit","AudioSampleFormat","AudioScheduledSourceNode","AudioScheduledSourceNodeEventMap","AudioTimestamp","AudioWorklet","AudioWorkletNode","AudioWorkletNodeEventMap","AudioWorkletNodeOptions","AuthenticationExtensionsClientInputs","AuthenticationExtensionsClientInputsJSON","AuthenticationExtensionsClientOutputs","AuthenticationExtensionsClientOutputsJSON","AuthenticationExtensionsLargeBlobInputs","AuthenticationExtensionsLargeBlobInputsJSON","AuthenticationExtensionsLargeBlobOutputs","AuthenticationExtensionsLargeBlobOutputsJSON","AuthenticationExtensionsPRFInputs","AuthenticationExtensionsPRFInputsJSON","AuthenticationExtensionsPRFOutputs","AuthenticationExtensionsPRFOutputsJSON","AuthenticationExtensionsPRFValues","AuthenticationExtensionsPRFValuesJSON","AuthenticationResponseJSON","AuthenticatorAssertionResponse","AuthenticatorAssertionResponseJSON","AuthenticatorAttachment","AuthenticatorAttestationResponse","AuthenticatorAttestationResponseJSON","AuthenticatorResponse","AuthenticatorSelectionCriteria","AuthenticatorTransport","AutoFill","AutoFillAddressKind","AutoFillBase","AutoFillContactField","AutoFillContactKind","AutoFillCredentialField","AutoFillField","AutoFillNormalField","AutoFillSection","AutoKeyword","AutomationRate","AvcBitstreamFormat","AvcEncoderConfig","Awaited","BarProp","Base64URLString","BaseAudioContext","BaseAudioContextEventMap","BeforeUnloadEvent","BigInt","BigInt64Array","BigInt64ArrayConstructor","BigIntConstructor","BigIntToLocaleStringOptions","BigInteger","BigUint64Array","BigUint64ArrayConstructor","BinaryType","BiquadFilterNode","BiquadFilterOptions","BiquadFilterType","BitrateMode","Blob","BlobCallback","BlobEvent","BlobEventInit","BlobPart","BlobPropertyBag","Body","BodyInit","Boolean","BooleanConstructor","BroadcastChannel","BroadcastChannelEventMap","Buffer","BufferEncoding","BufferSource","BuiltinIteratorReturn","Bun","BunFile","ByteLengthQueuingStrategy","CDATASection","COSEAlgorithmIdentifier","CSS","CSSAnimation","CSSConditionRule","CSSContainerRule","CSSCounterStyleRule","CSSFontFaceRule","CSSFontFeatureValuesRule","CSSFontPaletteValuesRule","CSSGroupingRule","CSSImageValue","CSSImportRule","CSSKeyframeRule","CSSKeyframesRule","CSSKeywordValue","CSSKeywordish","CSSLayerBlockRule","CSSLayerStatementRule","CSSMathClamp","CSSMathInvert","CSSMathMax","CSSMathMin","CSSMathNegate","CSSMathOperator","CSSMathProduct","CSSMathSum","CSSMathValue","CSSMatrixComponent","CSSMatrixComponentOptions","CSSMediaRule","CSSNamespaceRule","CSSNestedDeclarations","CSSNumberish","CSSNumericArray","CSSNumericBaseType","CSSNumericType","CSSNumericValue","CSSPageDescriptors","CSSPageRule","CSSPerspective","CSSPerspectiveValue","CSSPositionTryDescriptors","CSSPositionTryRule","CSSPropertyRule","CSSRotate","CSSRule","CSSRuleList","CSSScale","CSSScopeRule","CSSSkew","CSSSkewX","CSSSkewY","CSSStartingStyleRule","CSSStyleDeclaration","CSSStyleDeclarationBase","CSSStyleProperties","CSSStyleRule","CSSStyleSheet","CSSStyleSheetInit","CSSStyleValue","CSSSupportsRule","CSSTransformComponent","CSSTransformValue","CSSTransition","CSSTranslate","CSSUnitValue","CSSUnparsedSegment","CSSUnparsedValue","CSSVariableReferenceValue","CSSViewTransitionRule","Cache","CacheQueryOptions","CacheStorage","CalendarLike","CallableFunction","CanPlayTypeResult","CanvasCaptureMediaStreamTrack","CanvasCompositing","CanvasDirection","CanvasDrawImage","CanvasDrawPath","CanvasFillRule","CanvasFillStrokeStyles","CanvasFilters","CanvasFontKerning","CanvasFontStretch","CanvasFontVariantCaps","CanvasGradient","CanvasImageData","CanvasImageSmoothing","CanvasImageSource","CanvasLineCap","CanvasLineJoin","CanvasPath","CanvasPathDrawingStyles","CanvasPattern","CanvasRect","CanvasRenderingContext2D","CanvasRenderingContext2DSettings","CanvasSettings","CanvasShadowStyles","CanvasState","CanvasText","CanvasTextAlign","CanvasTextBaseline","CanvasTextDrawingStyles","CanvasTextRendering","CanvasTransform","CanvasUserInterface","Capitalize","CaretPosition","CaretPositionFromPointOptions","ChannelCountMode","ChannelInterpretation","ChannelMergerNode","ChannelMergerOptions","ChannelSplitterNode","ChannelSplitterOptions","CharacterData","CheckVisibilityOptions","ChildNode","ClassAccessorDecoratorContext","ClassAccessorDecoratorResult","ClassAccessorDecoratorTarget","ClassDecorator","ClassDecoratorContext","ClassFieldDecoratorContext","ClassGetterDecoratorContext","ClassMemberDecoratorContext","ClassMethodDecoratorContext","ClassSetterDecoratorContext","Client","ClientQueryOptions","ClientRect","ClientTypes","Clients","Clipboard","ClipboardEvent","ClipboardEventInit","ClipboardItem","ClipboardItemData","ClipboardItemOptions","ClipboardItems","CloseEvent","CloseEventInit","CodecState","Collator","CollatorConstructor","CollatorOptions","ColorGamut","ColorSpaceConversion","CommandEvent","CommandEventInit","Comment","CompileError","CompositeOperation","CompositeOperationOrAuto","CompositionEvent","CompositionEventInit","CompressionFormat","CompressionStream","ComputedEffectTiming","ComputedKeyframe","ConcatArray","Console","ConstantSourceNode","ConstantSourceOptions","ConstrainBoolean","ConstrainBooleanOrDOMString","ConstrainBooleanOrDOMStringParameters","ConstrainBooleanParameters","ConstrainDOMString","ConstrainDOMStringParameters","ConstrainDouble","ConstrainDoubleRange","ConstrainULong","ConstrainULongRange","ConstructorParameters","ContentVisibilityAutoStateChangeEvent","ContentVisibilityAutoStateChangeEventInit","ConvolverNode","ConvolverOptions","CookieChangeEvent","CookieChangeEventInit","CookieInit","CookieList","CookieListItem","CookieSameSite","CookieStore","CookieStoreDeleteOptions","CookieStoreEventMap","CookieStoreGetOptions","CookieStoreManager","CountQueuingStrategy","Credential","CredentialCreationOptions","CredentialMediationRequirement","CredentialPropertiesOutput","CredentialRequestOptions","CredentialsContainer","Crypto","CryptoKey","CryptoKeyPair","CurrentUserDetailsOptions","CustomElementConstructor","CustomElementRegistry","CustomEvent","CustomEventInit","CustomStateSet","DOMException","DOMHighResTimeStamp","DOMImplementation","DOMMatrix","DOMMatrix2DInit","DOMMatrixInit","DOMMatrixReadOnly","DOMParser","DOMParserSupportedType","DOMPoint","DOMPointInit","DOMPointReadOnly","DOMQuad","DOMQuadInit","DOMRect","DOMRectInit","DOMRectList","DOMRectReadOnly","DOMStringList","DOMStringMap","DOMTokenList","DataTransfer","DataTransferItem","DataTransferItemList","DataView","DataViewConstructor","Date","DateConstructor","DateLikeObject","DateTimeFormat","DateTimeFormatConstructor","DateTimeFormatOptions","DateTimeFormatPart","DateTimeFormatPartTypes","DateTimeFormatPartTypesRegistry","DateTimeLikeObject","DateTimeRangeFormatPart","DateUnit","DecodeErrorCallback","DecodeSuccessCallback","DecompressionStream","DecoratorContext","DecoratorMetadata","DecoratorMetadataObject","DedicatedWorkerGlobalScope","DedicatedWorkerGlobalScopeEventMap","DelayNode","DelayOptions","DeviceMotionEvent","DeviceMotionEventAcceleration","DeviceMotionEventAccelerationInit","DeviceMotionEventInit","DeviceMotionEventRotationRate","DeviceMotionEventRotationRateInit","DeviceOrientationEvent","DeviceOrientationEventInit","DigitalCredential","DirectionSetting","Dirent","DisambiguationOptions","DisplayCaptureSurfaceType","DisplayMediaStreamOptions","DisplayNames","DisplayNamesFallback","DisplayNamesLanguageDisplay","DisplayNamesOptions","DisplayNamesType","Disposable","DisposableStack","DisposableStackConstructor","DistanceModelType","Document","DocumentEventMap","DocumentFragment","DocumentOrShadowRoot","DocumentReadyState","DocumentTimeline","DocumentTimelineOptions","DocumentType","DocumentVisibilityState","DoubleRange","DragEvent","DragEventInit","Duration","DurationConstructor","DurationFormat","DurationFormatDisplayOption","DurationFormatLocaleMatcher","DurationFormatOptions","DurationFormatPart","DurationFormatStyle","DurationFormatUnit","DurationFormatUnitSingular","DurationLike","DurationLikeObject","DurationRelativeToOptions","DurationRoundingOptions","DurationToStringOptions","DurationTotalOptions","DynamicsCompressorNode","DynamicsCompressorOptions","EXT_blend_minmax","EXT_color_buffer_float","EXT_color_buffer_half_float","EXT_float_blend","EXT_frag_depth","EXT_sRGB","EXT_shader_texture_lod","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","EXT_texture_norm16","EcKeyAlgorithm","EcKeyGenParams","EcKeyImportParams","EcdhKeyDeriveParams","EcdsaParams","EffectTiming","Element","ElementCSSInlineStyle","ElementContentEditable","ElementCreationOptions","ElementDefinitionOptions","ElementEventMap","ElementInternals","ElementTagNameMap","EncodedAudioChunk","EncodedAudioChunkInit","EncodedAudioChunkMetadata","EncodedAudioChunkOutputCallback","EncodedAudioChunkType","EncodedVideoChunk","EncodedVideoChunkInit","EncodedVideoChunkMetadata","EncodedVideoChunkOutputCallback","EncodedVideoChunkType","EndOfStreamError","EndingType","Enumerator","EnumeratorConstructor","EpochTimeStamp","Error","ErrorCallback","ErrorConstructor","ErrorEvent","ErrorEventInit","ErrorOptions","EvalError","EvalErrorConstructor","Event","EventCounts","EventInit","EventListener","EventListenerObject","EventListenerOptions","EventListenerOrEventListenerObject","EventModifierInit","EventSource","EventSourceEventMap","EventSourceInit","EventTarget","Exception","ExceptionOptions","Exclude","ExportValue","Exports","ExtendableCookieChangeEvent","ExtendableCookieChangeEventInit","ExtendableEvent","ExtendableEventInit","ExtendableMessageEvent","ExtendableMessageEventInit","External","Extract","FetchEvent","FetchEventInit","File","FileCallback","FileList","FilePropertyBag","FileReader","FileReaderEventMap","FileReaderSync","FileSink","FileSystem","FileSystemCreateWritableOptions","FileSystemDirectoryEntry","FileSystemDirectoryHandle","FileSystemDirectoryHandleAsyncIterator","FileSystemDirectoryReader","FileSystemEntriesCallback","FileSystemEntry","FileSystemEntryCallback","FileSystemFileEntry","FileSystemFileHandle","FileSystemFlags","FileSystemGetDirectoryOptions","FileSystemGetFileOptions","FileSystemHandle","FileSystemHandleKind","FileSystemReadWriteOptions","FileSystemRemoveOptions","FileSystemSyncAccessHandle","FileSystemWritableFileStream","FileSystemWriteChunkType","FillLightMode","FillMode","FinalizationRegistry","FinalizationRegistryConstructor","FlatArray","Float16Array","Float16ArrayConstructor","Float32Array","Float32ArrayConstructor","Float32List","Float64Array","Float64ArrayConstructor","FocusEvent","FocusEventInit","FocusOptions","FontDisplay","FontFace","FontFaceDescriptors","FontFaceLoadStatus","FontFaceSet","FontFaceSetEventMap","FontFaceSetLoadEvent","FontFaceSetLoadEventInit","FontFaceSetLoadStatus","FontFaceSource","FormData","FormDataEntryValue","FormDataEvent","FormDataEventInit","FormDataIterator","FormattableTemporalObject","FragmentDirective","FrameRequestCallback","FrameType","FullscreenNavigationUI","FullscreenOptions","Function","FunctionConstructor","FunctionStringCallback","GLbitfield","GLboolean","GLclampf","GLenum","GLfloat","GLint","GLint64","GLintptr","GLsizei","GLsizeiptr","GLuint","GLuint64","GPU","GPUAdapter","GPUAdapterInfo","GPUAddressMode","GPUAutoLayoutMode","GPUBindGroup","GPUBindGroupDescriptor","GPUBindGroupEntry","GPUBindGroupLayout","GPUBindGroupLayoutDescriptor","GPUBindGroupLayoutEntry","GPUBindingCommandsMixin","GPUBindingResource","GPUBlendComponent","GPUBlendFactor","GPUBlendOperation","GPUBlendState","GPUBuffer","GPUBufferBinding","GPUBufferBindingLayout","GPUBufferBindingType","GPUBufferDescriptor","GPUBufferDynamicOffset","GPUBufferMapState","GPUBufferUsageFlags","GPUCanvasAlphaMode","GPUCanvasConfiguration","GPUCanvasContext","GPUCanvasToneMapping","GPUCanvasToneMappingMode","GPUColor","GPUColorDict","GPUColorTargetState","GPUColorWriteFlags","GPUCommandBuffer","GPUCommandBufferDescriptor","GPUCommandEncoder","GPUCommandEncoderDescriptor","GPUCompareFunction","GPUCompilationInfo","GPUCompilationMessage","GPUCompilationMessageType","GPUComputePassDescriptor","GPUComputePassEncoder","GPUComputePassTimestampWrites","GPUComputePipeline","GPUComputePipelineDescriptor","GPUCopyExternalImageDestInfo","GPUCopyExternalImageSource","GPUCopyExternalImageSourceInfo","GPUCullMode","GPUDebugCommandsMixin","GPUDepthBias","GPUDepthStencilState","GPUDevice","GPUDeviceDescriptor","GPUDeviceEventMap","GPUDeviceLostInfo","GPUDeviceLostReason","GPUError","GPUErrorFilter","GPUExtent3D","GPUExtent3DDict","GPUExternalTexture","GPUExternalTextureBindingLayout","GPUExternalTextureDescriptor","GPUFeatureName","GPUFilterMode","GPUFlagsConstant","GPUFragmentState","GPUFrontFace","GPUIndex32","GPUIndexFormat","GPUIntegerCoordinate","GPUIntegerCoordinateOut","GPUInternalError","GPULoadOp","GPUMapModeFlags","GPUMipmapFilterMode","GPUMultisampleState","GPUObjectBase","GPUObjectDescriptorBase","GPUOrigin2D","GPUOrigin2DDict","GPUOrigin3D","GPUOrigin3DDict","GPUOutOfMemoryError","GPUPipelineBase","GPUPipelineConstantValue","GPUPipelineDescriptorBase","GPUPipelineError","GPUPipelineErrorInit","GPUPipelineErrorReason","GPUPipelineLayout","GPUPipelineLayoutDescriptor","GPUPowerPreference","GPUPrimitiveState","GPUPrimitiveTopology","GPUProgrammableStage","GPUQuerySet","GPUQuerySetDescriptor","GPUQueryType","GPUQueue","GPUQueueDescriptor","GPURenderBundle","GPURenderBundleDescriptor","GPURenderBundleEncoder","GPURenderBundleEncoderDescriptor","GPURenderCommandsMixin","GPURenderPassColorAttachment","GPURenderPassDepthStencilAttachment","GPURenderPassDescriptor","GPURenderPassEncoder","GPURenderPassLayout","GPURenderPassTimestampWrites","GPURenderPipeline","GPURenderPipelineDescriptor","GPURequestAdapterOptions","GPUSampleMask","GPUSampler","GPUSamplerBindingLayout","GPUSamplerBindingType","GPUSamplerDescriptor","GPUShaderModule","GPUShaderModuleDescriptor","GPUShaderStageFlags","GPUSignedOffset32","GPUSize32","GPUSize32Out","GPUSize64","GPUSize64Out","GPUStencilFaceState","GPUStencilOperation","GPUStencilValue","GPUStorageTextureAccess","GPUStorageTextureBindingLayout","GPUStoreOp","GPUSupportedFeatures","GPUSupportedLimits","GPUTexelCopyBufferInfo","GPUTexelCopyBufferLayout","GPUTexelCopyTextureInfo","GPUTexture","GPUTextureAspect","GPUTextureBindingLayout","GPUTextureDescriptor","GPUTextureDimension","GPUTextureFormat","GPUTextureSampleType","GPUTextureUsageFlags","GPUTextureView","GPUTextureViewDescriptor","GPUTextureViewDimension","GPUUncapturedErrorEvent","GPUUncapturedErrorEventInit","GPUValidationError","GPUVertexAttribute","GPUVertexBufferLayout","GPUVertexFormat","GPUVertexState","GPUVertexStepMode","GainNode","GainOptions","Gamepad","GamepadButton","GamepadEffectParameters","GamepadEvent","GamepadEventInit","GamepadHapticActuator","GamepadHapticEffectType","GamepadHapticsResult","GamepadMappingType","Generator","GeneratorFunction","GeneratorFunctionConstructor","GenericTransformStream","Geolocation","GeolocationCoordinates","GeolocationPosition","GeolocationPositionError","GetAnimationsOptions","GetComposedRangesOptions","GetHTMLOptions","GetNotificationOptions","GetRootNodeOptions","Global","GlobalCompositeOperation","GlobalDescriptor","GlobalEventHandlers","GlobalEventHandlersEventMap","HTMLAllCollection","HTMLAnchorElement","HTMLAreaElement","HTMLAudioElement","HTMLBRElement","HTMLBaseElement","HTMLBodyElement","HTMLBodyElementEventMap","HTMLButtonElement","HTMLCanvasElement","HTMLCollection","HTMLCollectionBase","HTMLCollectionOf","HTMLDListElement","HTMLDataElement","HTMLDataListElement","HTMLDetailsElement","HTMLDialogElement","HTMLDirectoryElement","HTMLDivElement","HTMLDocument","HTMLElement","HTMLElementDeprecatedTagNameMap","HTMLElementEventMap","HTMLElementTagNameMap","HTMLEmbedElement","HTMLFieldSetElement","HTMLFontElement","HTMLFormControlsCollection","HTMLFormElement","HTMLFrameElement","HTMLFrameSetElement","HTMLFrameSetElementEventMap","HTMLHRElement","HTMLHeadElement","HTMLHeadingElement","HTMLHtmlElement","HTMLHyperlinkElementUtils","HTMLIFrameElement","HTMLImageElement","HTMLInputElement","HTMLLIElement","HTMLLabelElement","HTMLLegendElement","HTMLLinkElement","HTMLMapElement","HTMLMarqueeElement","HTMLMediaElement","HTMLMediaElementEventMap","HTMLMenuElement","HTMLMetaElement","HTMLMeterElement","HTMLModElement","HTMLOListElement","HTMLObjectElement","HTMLOptGroupElement","HTMLOptionElement","HTMLOptionsCollection","HTMLOrSVGElement","HTMLOrSVGImageElement","HTMLOrSVGScriptElement","HTMLOutputElement","HTMLParagraphElement","HTMLParamElement","HTMLPictureElement","HTMLPreElement","HTMLProgressElement","HTMLQuoteElement","HTMLScriptElement","HTMLSelectElement","HTMLSlotElement","HTMLSourceElement","HTMLSpanElement","HTMLStyleElement","HTMLTableCaptionElement","HTMLTableCellElement","HTMLTableColElement","HTMLTableDataCellElement","HTMLTableElement","HTMLTableHeaderCellElement","HTMLTableRowElement","HTMLTableSectionElement","HTMLTemplateElement","HTMLTextAreaElement","HTMLTimeElement","HTMLTitleElement","HTMLTrackElement","HTMLUListElement","HTMLUnknownElement","HTMLVideoElement","HTMLVideoElementEventMap","HardwareAcceleration","HashAlgorithmIdentifier","HashChangeEvent","HashChangeEventInit","HdrMetadataType","Headers","HeadersInit","HeadersIterator","Highlight","HighlightRegistry","HighlightType","History","HkdfParams","HmacImportParams","HmacKeyAlgorithm","HmacKeyGenParams","IArguments","IDBCursor","IDBCursorDirection","IDBCursorWithValue","IDBDatabase","IDBDatabaseEventMap","IDBDatabaseInfo","IDBFactory","IDBIndex","IDBIndexParameters","IDBKeyRange","IDBObjectStore","IDBObjectStoreParameters","IDBOpenDBRequest","IDBOpenDBRequestEventMap","IDBRequest","IDBRequestEventMap","IDBRequestReadyState","IDBTransaction","IDBTransactionDurability","IDBTransactionEventMap","IDBTransactionMode","IDBTransactionOptions","IDBValidKey","IDBVersionChangeEvent","IDBVersionChangeEventInit","IIRFilterNode","IIRFilterOptions","ITextWriter","IdleDeadline","IdleRequestCallback","IdleRequestOptions","Image","ImageBitmap","ImageBitmapOptions","ImageBitmapRenderingContext","ImageBitmapRenderingContextSettings","ImageBitmapSource","ImageBufferSource","ImageCapture","ImageData","ImageDataArray","ImageDataPixelFormat","ImageDataSettings","ImageDecodeOptions","ImageDecodeResult","ImageDecoder","ImageDecoderInit","ImageEncodeOptions","ImageOrientation","ImageSmoothingQuality","ImageTrack","ImageTrackList","Immediate","ImportAssertions","ImportAttributes","ImportCallOptions","ImportExportKind","ImportMeta","ImportNodeOptions","ImportValue","Imports","Infinity","InputDeviceInfo","InputEvent","InputEventInit","InsertPosition","Instance","InstanceType","Instant","InstantConstructor","InstantLike","InstantToStringOptions","Int16Array","Int16ArrayConstructor","Int32Array","Int32ArrayConstructor","Int32List","Int8Array","Int8ArrayConstructor","IntersectionObserver","IntersectionObserverCallback","IntersectionObserverEntry","IntersectionObserverInit","Intl","Iterable","IterableIterator","IterationCompositeOperation","Iterator","IteratorConstructor","IteratorObject","IteratorObjectConstructor","IteratorResult","IteratorReturnResult","IteratorYieldResult","JSON","JsonWebKey","KHR_parallel_shader_compile","KeyAlgorithm","KeyFormat","KeySystemTrackConfiguration","KeyType","KeyUsage","KeyboardEvent","KeyboardEventInit","Keyframe","KeyframeAnimationOptions","KeyframeEffect","KeyframeEffectOptions","LDMLPluralRule","LargestContentfulPaint","LatencyMode","LineAlignSetting","LineAndPositionSetting","LinkError","LinkStyle","ListFormat","ListFormatLocaleMatcher","ListFormatOptions","ListFormatStyle","ListFormatType","Locale","LocaleCollationCaseFirst","LocaleHourCycleKey","LocaleOptions","LocalesArgument","Location","Lock","LockGrantedCallback","LockInfo","LockManager","LockManagerSnapshot","LockMode","LockOptions","LoginStatus","Lowercase","MIDIAccess","MIDIAccessEventMap","MIDIConnectionEvent","MIDIConnectionEventInit","MIDIInput","MIDIInputEventMap","MIDIInputMap","MIDIMessageEvent","MIDIMessageEventInit","MIDIOptions","MIDIOutput","MIDIOutputMap","MIDIPort","MIDIPortConnectionState","MIDIPortDeviceState","MIDIPortEventMap","MIDIPortType","Map","MapConstructor","MapIterator","Math","MathMLElement","MathMLElementEventMap","MathMLElementTagNameMap","MediaCapabilities","MediaCapabilitiesDecodingInfo","MediaCapabilitiesEncodingInfo","MediaCapabilitiesInfo","MediaCapabilitiesKeySystemConfiguration","MediaConfiguration","MediaDecodingConfiguration","MediaDecodingType","MediaDeviceInfo","MediaDeviceKind","MediaDevices","MediaDevicesEventMap","MediaElementAudioSourceNode","MediaElementAudioSourceOptions","MediaEncodingConfiguration","MediaEncodingType","MediaEncryptedEvent","MediaEncryptedEventInit","MediaError","MediaImage","MediaKeyMessageEvent","MediaKeyMessageEventInit","MediaKeyMessageType","MediaKeySession","MediaKeySessionClosedReason","MediaKeySessionEventMap","MediaKeySessionType","MediaKeyStatus","MediaKeyStatusMap","MediaKeyStatusMapIterator","MediaKeySystemAccess","MediaKeySystemConfiguration","MediaKeySystemMediaCapability","MediaKeys","MediaKeysPolicy","MediaKeysRequirement","MediaList","MediaMetadata","MediaMetadataInit","MediaPositionState","MediaProvider","MediaQueryList","MediaQueryListEvent","MediaQueryListEventInit","MediaQueryListEventMap","MediaRecorder","MediaRecorderEventMap","MediaRecorderOptions","MediaSession","MediaSessionAction","MediaSessionActionDetails","MediaSessionActionHandler","MediaSessionPlaybackState","MediaSettingsRange","MediaSource","MediaSourceEventMap","MediaSourceHandle","MediaStream","MediaStreamAudioDestinationNode","MediaStreamAudioSourceNode","MediaStreamAudioSourceOptions","MediaStreamConstraints","MediaStreamEventMap","MediaStreamTrack","MediaStreamTrackEvent","MediaStreamTrackEventInit","MediaStreamTrackEventMap","MediaStreamTrackProcessor","MediaStreamTrackProcessorInit","MediaStreamTrackState","MediaTrackCapabilities","MediaTrackConstraintSet","MediaTrackConstraints","MediaTrackSettings","MediaTrackSupportedConstraints","Memory","MemoryDescriptor","MessageChannel","MessageEvent","MessageEventInit","MessageEventSource","MessageEventTarget","MessageEventTargetEventMap","MessagePort","MessagePortEventMap","MethodDecorator","MimeType","MimeTypeArray","Module","ModuleExportDescriptor","ModuleImportDescriptor","ModuleImports","MouseEvent","MouseEventInit","MultiCacheQueryOptions","MutationCallback","MutationObserver","MutationObserverInit","MutationRecord","MutationRecordType","NaN","NamedCurve","NamedNodeMap","NavigateEvent","NavigateEventInit","Navigation","NavigationActivation","NavigationCurrentEntryChangeEvent","NavigationCurrentEntryChangeEventInit","NavigationDestination","NavigationEventMap","NavigationFocusReset","NavigationHistoryBehavior","NavigationHistoryEntry","NavigationHistoryEntryEventMap","NavigationInterceptHandler","NavigationInterceptOptions","NavigationNavigateOptions","NavigationOptions","NavigationPrecommitController","NavigationPrecommitHandler","NavigationPreloadManager","NavigationPreloadState","NavigationReloadOptions","NavigationResult","NavigationScrollBehavior","NavigationTimingType","NavigationTransition","NavigationType","NavigationUpdateCurrentEntryOptions","Navigator","NavigatorAutomationInformation","NavigatorBadge","NavigatorConcurrentHardware","NavigatorContentUtils","NavigatorCookies","NavigatorGPU","NavigatorID","NavigatorLanguage","NavigatorLocks","NavigatorLogin","NavigatorOnLine","NavigatorPlugins","NavigatorStorage","NewableFunction","NoInfer","Node","NodeFilter","NodeIterator","NodeJS","NodeList","NodeListOf","NodeModule","NodeRequire","NonDocumentTypeChildNode","NonElementParentNode","NonNullable","Notification","NotificationDirection","NotificationEvent","NotificationEventInit","NotificationEventMap","NotificationOptions","NotificationPermission","NotificationPermissionCallback","Now","Number","NumberConstructor","NumberFormat","NumberFormatConstructor","NumberFormatOptions","NumberFormatOptionsCurrencyDisplay","NumberFormatOptionsCurrencyDisplayRegistry","NumberFormatOptionsSignDisplay","NumberFormatOptionsSignDisplayRegistry","NumberFormatOptionsStyle","NumberFormatOptionsStyleRegistry","NumberFormatOptionsUseGrouping","NumberFormatOptionsUseGroupingRegistry","NumberFormatPart","NumberFormatPartTypeRegistry","NumberFormatPartTypes","NumberFormatRangePartTypeRegistry","NumberFormatRangePartTypes","NumberRangeFormatPart","OES_draw_buffers_indexed","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_float_linear","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","OVR_multiview2","Object","ObjectConstructor","OfflineAudioCompletionEvent","OfflineAudioCompletionEventInit","OfflineAudioContext","OfflineAudioContextEventMap","OfflineAudioContextOptions","OffscreenCanvas","OffscreenCanvasEventMap","OffscreenCanvasRenderingContext2D","OffscreenRenderingContext","OffscreenRenderingContextId","Omit","OmitThisParameter","OnBeforeUnloadEventHandler","OnBeforeUnloadEventHandlerNonNull","OnErrorEventHandler","OnErrorEventHandlerNonNull","Option","OptionalEffectTiming","OptionalPostfixToken","OptionalPrefixToken","OpusBitstreamFormat","OpusEncoderConfig","OrientationLockType","OrientationType","OscillatorNode","OscillatorOptions","OscillatorType","OverSampleType","OverconstrainedError","OverflowOptions","PageRevealEvent","PageRevealEventInit","PageSwapEvent","PageSwapEventInit","PageTransitionEvent","PageTransitionEventInit","PaintTimingMixin","PannerNode","PannerOptions","PanningModelType","ParameterDecorator","Parameters","ParentNode","Partial","PartialTemporalLike","Path2D","PayerErrors","PaymentAddress","PaymentComplete","PaymentCurrencyAmount","PaymentDetailsBase","PaymentDetailsInit","PaymentDetailsModifier","PaymentDetailsUpdate","PaymentItem","PaymentMethodChangeEvent","PaymentMethodChangeEventInit","PaymentMethodData","PaymentOptions","PaymentRequest","PaymentRequestEventMap","PaymentRequestUpdateEvent","PaymentRequestUpdateEventInit","PaymentResponse","PaymentResponseEventMap","PaymentShippingOption","PaymentShippingType","PaymentValidationErrors","Pbkdf2Params","Performance","PerformanceEntry","PerformanceEntryList","PerformanceEventMap","PerformanceEventTiming","PerformanceMark","PerformanceMarkOptions","PerformanceMeasure","PerformanceMeasureOptions","PerformanceNavigation","PerformanceNavigationTiming","PerformanceObserver","PerformanceObserverCallback","PerformanceObserverEntryList","PerformanceObserverInit","PerformancePaintTiming","PerformanceResourceTiming","PerformanceServerTiming","PerformanceTiming","PeriodicWave","PeriodicWaveConstraints","PeriodicWaveOptions","PermissionDescriptor","PermissionName","PermissionState","PermissionStatus","PermissionStatusEventMap","Permissions","PhotoCapabilities","PhotoSettings","Pick","PictureInPictureEvent","PictureInPictureEventInit","PictureInPictureWindow","PictureInPictureWindowEventMap","PlainDate","PlainDateConstructor","PlainDateLike","PlainDateTime","PlainDateTimeConstructor","PlainDateTimeLike","PlainDateTimeToStringOptions","PlainDateToStringOptions","PlainDateToZonedDateTimeOptions","PlainMonthDay","PlainMonthDayConstructor","PlainMonthDayLike","PlainMonthDayToPlainDateOptions","PlainTime","PlainTimeConstructor","PlainTimeLike","PlainTimeToStringOptions","PlainYearMonth","PlainYearMonthConstructor","PlainYearMonthLike","PlainYearMonthToPlainDateOptions","PlaneLayout","PlaybackDirection","Plugin","PluginArray","PluralRuleType","PluralRules","PluralRulesConstructor","PluralRulesOptions","PluralizeUnit","PointerEvent","PointerEventInit","PointerLockOptions","PopStateEvent","PopStateEventInit","PopoverTargetAttributes","PositionAlignSetting","PositionCallback","PositionErrorCallback","PositionOptions","PredefinedColorSpace","PremultiplyAlpha","PresentationStyle","ProcessingInstruction","ProgressEvent","ProgressEventInit","Promise","PromiseConstructor","PromiseConstructorLike","PromiseFulfilledResult","PromiseLike","PromiseRejectedResult","PromiseRejectionEvent","PromiseRejectionEventInit","PromiseSettledResult","PromiseWithResolvers","PropertyDecorator","PropertyDefinition","PropertyDescriptor","PropertyDescriptorMap","PropertyIndexedKeyframes","PropertyKey","Proxy","ProxyConstructor","ProxyHandler","PublicKeyCredential","PublicKeyCredentialClientCapabilities","PublicKeyCredentialCreationOptions","PublicKeyCredentialCreationOptionsJSON","PublicKeyCredentialDescriptor","PublicKeyCredentialDescriptorJSON","PublicKeyCredentialEntity","PublicKeyCredentialParameters","PublicKeyCredentialRequestOptions","PublicKeyCredentialRequestOptionsJSON","PublicKeyCredentialRpEntity","PublicKeyCredentialType","PublicKeyCredentialUserEntity","PublicKeyCredentialUserEntityJSON","PushEncryptionKeyName","PushEvent","PushEventInit","PushManager","PushManagerAttribute","PushMessageData","PushMessageDataInit","PushSubscription","PushSubscriptionChangeEvent","PushSubscriptionChangeEventInit","PushSubscriptionJSON","PushSubscriptionOptions","PushSubscriptionOptionsInit","QueuingStrategy","QueuingStrategyInit","QueuingStrategySize","RTCAnswerOptions","RTCBundlePolicy","RTCCertificate","RTCCertificateExpiration","RTCConfiguration","RTCDTMFSender","RTCDTMFSenderEventMap","RTCDTMFToneChangeEvent","RTCDTMFToneChangeEventInit","RTCDataChannel","RTCDataChannelEvent","RTCDataChannelEventInit","RTCDataChannelEventMap","RTCDataChannelInit","RTCDataChannelState","RTCDegradationPreference","RTCDtlsFingerprint","RTCDtlsRole","RTCDtlsTransport","RTCDtlsTransportEventMap","RTCDtlsTransportState","RTCEncodedAudioFrame","RTCEncodedAudioFrameMetadata","RTCEncodedFrameMetadata","RTCEncodedVideoFrame","RTCEncodedVideoFrameMetadata","RTCError","RTCErrorDetailType","RTCErrorEvent","RTCErrorEventInit","RTCErrorInit","RTCIceCandidate","RTCIceCandidateInit","RTCIceCandidatePair","RTCIceCandidatePairStats","RTCIceCandidateType","RTCIceComponent","RTCIceConnectionState","RTCIceGathererState","RTCIceGatheringState","RTCIceProtocol","RTCIceRole","RTCIceServer","RTCIceTcpCandidateType","RTCIceTransport","RTCIceTransportEventMap","RTCIceTransportPolicy","RTCIceTransportState","RTCInboundRtpStreamStats","RTCLocalIceCandidateInit","RTCLocalSessionDescriptionInit","RTCOfferAnswerOptions","RTCOfferOptions","RTCOutboundRtpStreamStats","RTCPeerConnection","RTCPeerConnectionErrorCallback","RTCPeerConnectionEventMap","RTCPeerConnectionIceErrorEvent","RTCPeerConnectionIceErrorEventInit","RTCPeerConnectionIceEvent","RTCPeerConnectionIceEventInit","RTCPeerConnectionState","RTCPriorityType","RTCQualityLimitationReason","RTCReceivedRtpStreamStats","RTCRtcpMuxPolicy","RTCRtcpParameters","RTCRtpCapabilities","RTCRtpCodec","RTCRtpCodecParameters","RTCRtpCodingParameters","RTCRtpContributingSource","RTCRtpEncodingParameters","RTCRtpHeaderExtensionCapability","RTCRtpHeaderExtensionParameters","RTCRtpParameters","RTCRtpReceiveParameters","RTCRtpReceiver","RTCRtpReceiverTransform","RTCRtpScriptTransform","RTCRtpScriptTransformer","RTCRtpSendParameters","RTCRtpSender","RTCRtpSenderTransform","RTCRtpStreamStats","RTCRtpSynchronizationSource","RTCRtpTransceiver","RTCRtpTransceiverDirection","RTCRtpTransceiverInit","RTCSctpTransport","RTCSctpTransportEventMap","RTCSctpTransportState","RTCSdpType","RTCSentRtpStreamStats","RTCSessionDescription","RTCSessionDescriptionCallback","RTCSessionDescriptionInit","RTCSetParameterOptions","RTCSignalingState","RTCStats","RTCStatsIceCandidatePairState","RTCStatsReport","RTCStatsType","RTCTrackEvent","RTCTrackEventInit","RTCTransformEvent","RTCTransportStats","RadioNodeList","Range","RangeError","RangeErrorConstructor","ReadableByteStreamController","ReadableStream","ReadableStreamAsyncIterator","ReadableStreamBYOBReader","ReadableStreamBYOBReaderReadOptions","ReadableStreamBYOBRequest","ReadableStreamController","ReadableStreamDefaultController","ReadableStreamDefaultReader","ReadableStreamGenericReader","ReadableStreamGetReaderOptions","ReadableStreamIteratorOptions","ReadableStreamReadDoneResult","ReadableStreamReadResult","ReadableStreamReadValueResult","ReadableStreamReader","ReadableStreamReaderMode","ReadableStreamType","ReadableWritablePair","Readonly","ReadonlyArray","ReadonlyMap","ReadonlySet","ReadonlySetLike","ReadyState","Record","RecordingState","RedEyeReduction","ReferenceError","ReferenceErrorConstructor","ReferrerPolicy","Reflect","RegExp","RegExpConstructor","RegExpExecArray","RegExpIndicesArray","RegExpMatchArray","RegExpStringIterator","RegistrationOptions","RegistrationResponseJSON","RelativeTimeFormat","RelativeTimeFormatLocaleMatcher","RelativeTimeFormatNumeric","RelativeTimeFormatOptions","RelativeTimeFormatPart","RelativeTimeFormatStyle","RelativeTimeFormatUnit","RelativeTimeFormatUnitSingular","RemotePlayback","RemotePlaybackAvailabilityCallback","RemotePlaybackEventMap","RemotePlaybackState","RenderingContext","Report","ReportBody","ReportList","ReportingObserver","ReportingObserverCallback","ReportingObserverOptions","Request","RequestCache","RequestCredentials","RequestDestination","RequestInfo","RequestInit","RequestMode","RequestPriority","RequestRedirect","Required","ResidentKeyRequirement","ResizeObserver","ResizeObserverBoxOptions","ResizeObserverCallback","ResizeObserverEntry","ResizeObserverOptions","ResizeObserverSize","ResizeQuality","ResolvedCollatorOptions","ResolvedDateTimeFormatOptions","ResolvedDisplayNamesOptions","ResolvedDurationFormatOptions","ResolvedListFormatOptions","ResolvedNumberFormatOptions","ResolvedNumberFormatOptionsUseGrouping","ResolvedPluralRulesOptions","ResolvedRelativeTimeFormatOptions","ResolvedSegmenterOptions","Response","ResponseInit","ResponseType","ReturnType","RoundingOptions","RoundingOptionsWithLargestUnit","RsaHashedImportParams","RsaHashedKeyAlgorithm","RsaHashedKeyGenParams","RsaKeyAlgorithm","RsaKeyGenParams","RsaOaepParams","RsaOtherPrimesInfo","RsaPssParams","RuntimeError","SVGAElement","SVGAngle","SVGAnimateElement","SVGAnimateMotionElement","SVGAnimateTransformElement","SVGAnimatedAngle","SVGAnimatedBoolean","SVGAnimatedEnumeration","SVGAnimatedInteger","SVGAnimatedLength","SVGAnimatedLengthList","SVGAnimatedNumber","SVGAnimatedNumberList","SVGAnimatedPoints","SVGAnimatedPreserveAspectRatio","SVGAnimatedRect","SVGAnimatedString","SVGAnimatedTransformList","SVGAnimationElement","SVGBoundingBoxOptions","SVGCircleElement","SVGClipPathElement","SVGComponentTransferFunctionElement","SVGDefsElement","SVGDescElement","SVGElement","SVGElementEventMap","SVGElementTagNameMap","SVGEllipseElement","SVGFEBlendElement","SVGFEColorMatrixElement","SVGFEComponentTransferElement","SVGFECompositeElement","SVGFEConvolveMatrixElement","SVGFEDiffuseLightingElement","SVGFEDisplacementMapElement","SVGFEDistantLightElement","SVGFEDropShadowElement","SVGFEFloodElement","SVGFEFuncAElement","SVGFEFuncBElement","SVGFEFuncGElement","SVGFEFuncRElement","SVGFEGaussianBlurElement","SVGFEImageElement","SVGFEMergeElement","SVGFEMergeNodeElement","SVGFEMorphologyElement","SVGFEOffsetElement","SVGFEPointLightElement","SVGFESpecularLightingElement","SVGFESpotLightElement","SVGFETileElement","SVGFETurbulenceElement","SVGFilterElement","SVGFilterPrimitiveStandardAttributes","SVGFitToViewBox","SVGForeignObjectElement","SVGGElement","SVGGeometryElement","SVGGradientElement","SVGGraphicsElement","SVGImageElement","SVGLength","SVGLengthList","SVGLineElement","SVGLinearGradientElement","SVGMPathElement","SVGMarkerElement","SVGMaskElement","SVGMatrix","SVGMetadataElement","SVGNumber","SVGNumberList","SVGPathElement","SVGPatternElement","SVGPoint","SVGPointList","SVGPolygonElement","SVGPolylineElement","SVGPreserveAspectRatio","SVGRadialGradientElement","SVGRect","SVGRectElement","SVGSVGElement","SVGSVGElementEventMap","SVGScriptElement","SVGSetElement","SVGStopElement","SVGStringList","SVGStyleElement","SVGSwitchElement","SVGSymbolElement","SVGTSpanElement","SVGTests","SVGTextContentElement","SVGTextElement","SVGTextPathElement","SVGTextPositioningElement","SVGTitleElement","SVGTransform","SVGTransformList","SVGURIReference","SVGUnitTypes","SVGUseElement","SVGViewElement","Sanitizer","SanitizerAttribute","SanitizerAttributeNamespace","SanitizerConfig","SanitizerElement","SanitizerElementNamespace","SanitizerElementNamespaceWithAttributes","SanitizerElementWithAttributes","SanitizerPresets","Scheduler","SchedulerPostTaskCallback","SchedulerPostTaskOptions","Screen","ScreenOrientation","ScreenOrientationEventMap","ScriptProcessorNode","ScriptProcessorNodeEventMap","ScrollAxis","ScrollBehavior","ScrollIntoViewOptions","ScrollLogicalPosition","ScrollOptions","ScrollRestoration","ScrollSetting","ScrollTimeline","ScrollTimelineOptions","ScrollToOptions","SecurityPolicyViolationEvent","SecurityPolicyViolationEventDisposition","SecurityPolicyViolationEventInit","SegmentData","SegmentIterator","Segmenter","SegmenterOptions","Segments","Selection","SelectionDirection","SelectionMode","Server","ServerWebSocket","ServiceWorker","ServiceWorkerContainer","ServiceWorkerContainerEventMap","ServiceWorkerEventMap","ServiceWorkerGlobalScope","ServiceWorkerGlobalScopeEventMap","ServiceWorkerRegistration","ServiceWorkerRegistrationEventMap","ServiceWorkerState","ServiceWorkerUpdateViaCache","Set","SetConstructor","SetIterator","ShadowRoot","ShadowRootEventMap","ShadowRootInit","ShadowRootMode","ShareData","SharedArrayBuffer","SharedArrayBufferConstructor","SharedWorker","SharedWorkerGlobalScope","SharedWorkerGlobalScopeEventMap","ShellPromise","ShowPopoverOptions","SlotAssignmentMode","Slottable","Socket","SocketHandler","SourceBuffer","SourceBufferEventMap","SourceBufferList","SourceBufferListEventMap","SpeechRecognitionAlternative","SpeechRecognitionErrorCode","SpeechRecognitionErrorEvent","SpeechRecognitionErrorEventInit","SpeechRecognitionEvent","SpeechRecognitionEventInit","SpeechRecognitionResult","SpeechRecognitionResultList","SpeechSynthesis","SpeechSynthesisErrorCode","SpeechSynthesisErrorEvent","SpeechSynthesisErrorEventInit","SpeechSynthesisEvent","SpeechSynthesisEventInit","SpeechSynthesisEventMap","SpeechSynthesisUtterance","SpeechSynthesisUtteranceEventMap","SpeechSynthesisVoice","StartViewTransitionOptions","StaticRange","StaticRangeInit","Stats","StereoPannerNode","StereoPannerOptions","Storage","StorageEstimate","StorageEvent","StorageEventInit","StorageManager","StreamPipeOptions","String","StringConstructor","StringIterator","StringNumericLiteral","StructuredSerializeOptions","StylePropertyMap","StylePropertyMapReadOnly","StylePropertyMapReadOnlyIterator","StyleSheet","StyleSheetList","SubmitEvent","SubmitEventInit","Subprocess","SubtleCrypto","SuppressedError","SuppressedErrorConstructor","SvcOutputMetadata","Symbol","SymbolConstructor","SyntaxError","SyntaxErrorConstructor","TCPSocket","Table","TableDescriptor","TableKind","Tag","TagType","TaskController","TaskControllerInit","TaskPriority","TaskPriorityChangeEvent","TaskPriorityChangeEventInit","TaskSignal","TaskSignalAnyInit","TaskSignalEventMap","TemplateStringsArray","Temporal","TexImageSource","Text","TextDecodeOptions","TextDecoder","TextDecoderCommon","TextDecoderOptions","TextDecoderStream","TextEncoder","TextEncoderCommon","TextEncoderEncodeIntoResult","TextEncoderStream","TextEvent","TextInfo","TextMetrics","TextStreamBase","TextStreamReader","TextStreamWriter","TextTrack","TextTrackCue","TextTrackCueEventMap","TextTrackCueList","TextTrackEventMap","TextTrackKind","TextTrackList","TextTrackListEventMap","TextTrackMode","ThisParameterType","ThisType","TimeLikeObject","TimeRanges","TimeUnit","TimeZoneLike","TimelineRangeOffset","Timeout","Timer","TimerHandler","ToStringRoundingOptions","ToStringRoundingOptionsWithFractionalSeconds","ToggleEvent","ToggleEventInit","TogglePopoverOptions","Touch","TouchEvent","TouchEventInit","TouchInit","TouchList","TouchType","TrackEvent","TrackEventInit","TransferFunction","Transferable","TransformStream","TransformStreamDefaultController","Transformer","TransformerFlushCallback","TransformerStartCallback","TransformerTransformCallback","TransitionEvent","TransitionEventInit","TransitionOptions","TreeWalker","TypeError","TypeErrorConstructor","TypedArray","TypedPropertyDescriptor","UIEvent","UIEventInit","ULongRange","URIError","URIErrorConstructor","URL","URLPattern","URLPatternComponentResult","URLPatternInit","URLPatternInput","URLPatternOptions","URLPatternResult","URLSearchParams","URLSearchParamsIterator","Uint16Array","Uint16ArrayConstructor","Uint32Array","Uint32ArrayConstructor","Uint32List","Uint8Array","Uint8ArrayConstructor","Uint8ClampedArray","Uint8ClampedArrayConstructor","Uncapitalize","UnderlyingByteSource","UnderlyingDefaultSource","UnderlyingSink","UnderlyingSinkAbortCallback","UnderlyingSinkCloseCallback","UnderlyingSinkStartCallback","UnderlyingSinkWriteCallback","UnderlyingSource","UnderlyingSourceCancelCallback","UnderlyingSourcePullCallback","UnderlyingSourceStartCallback","UnicodeBCP47LocaleIdentifier","UnknownCredentialOptions","Uppercase","UserActivation","UserVerificationRequirement","VBArray","VBArrayConstructor","VTTCue","VTTRegion","ValidityState","ValidityStateFlags","ValueType","ValueTypeMap","VibratePattern","VideoColorPrimaries","VideoColorSpace","VideoColorSpaceInit","VideoConfiguration","VideoDecoder","VideoDecoderConfig","VideoDecoderEventMap","VideoDecoderInit","VideoDecoderSupport","VideoEncoder","VideoEncoderBitrateMode","VideoEncoderConfig","VideoEncoderEncodeOptions","VideoEncoderEncodeOptionsForAvc","VideoEncoderEventMap","VideoEncoderInit","VideoEncoderSupport","VideoFacingModeEnum","VideoFrame","VideoFrameBufferInit","VideoFrameCallbackMetadata","VideoFrameCopyToOptions","VideoFrameInit","VideoFrameOutputCallback","VideoFrameRequestCallback","VideoMatrixCoefficients","VideoPixelFormat","VideoPlaybackQuality","VideoTransferCharacteristics","ViewTimeline","ViewTimelineOptions","ViewTransition","ViewTransitionTypeSet","ViewTransitionUpdateCallback","VisualViewport","VisualViewportEventMap","VoidFunction","WEBGL_color_buffer_float","WEBGL_compressed_texture_astc","WEBGL_compressed_texture_etc","WEBGL_compressed_texture_etc1","WEBGL_compressed_texture_pvrtc","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_depth_texture","WEBGL_draw_buffers","WEBGL_lose_context","WEBGL_multi_draw","WGSLLanguageFeatures","WSH","WScript","WakeLock","WakeLockSentinel","WakeLockSentinelEventMap","WakeLockType","WaveShaperNode","WaveShaperOptions","WeakKey","WeakKeyTypes","WeakMap","WeakMapConstructor","WeakRef","WeakRefConstructor","WeakSet","WeakSetConstructor","WebAssembly","WebAssemblyCompileOptions","WebAssemblyInstantiatedSource","WebCodecsErrorCallback","WebGL2RenderingContext","WebGL2RenderingContextBase","WebGL2RenderingContextOverloads","WebGLActiveInfo","WebGLBuffer","WebGLContextAttributes","WebGLContextEvent","WebGLContextEventInit","WebGLFramebuffer","WebGLPowerPreference","WebGLProgram","WebGLQuery","WebGLRenderbuffer","WebGLRenderingContext","WebGLRenderingContextBase","WebGLRenderingContextOverloads","WebGLSampler","WebGLShader","WebGLShaderPrecisionFormat","WebGLSync","WebGLTexture","WebGLTransformFeedback","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES","WebKitCSSMatrix","WebSocket","WebSocketEventMap","WebSocketHandler","WebTransport","WebTransportBidirectionalStream","WebTransportCloseInfo","WebTransportCongestionControl","WebTransportDatagramDuplexStream","WebTransportError","WebTransportErrorOptions","WebTransportErrorSource","WebTransportHash","WebTransportOptions","WebTransportSendOptions","WebTransportSendStreamOptions","WeekInfo","WheelEvent","WheelEventInit","Window","WindowClient","WindowEventHandlers","WindowEventHandlersEventMap","WindowEventMap","WindowLocalStorage","WindowOrWorkerGlobalScope","WindowPostMessageOptions","WindowProxy","WindowSessionStorage","WithImplicitCoercion","Worker","WorkerEventMap","WorkerGlobalScope","WorkerGlobalScopeEventMap","WorkerLocation","WorkerNavigator","WorkerOptions","WorkerType","Worklet","WorkletOptions","WritableStream","WritableStreamDefaultController","WritableStreamDefaultWriter","WriteCommandType","WriteParams","XMLDocument","XMLHttpRequest","XMLHttpRequestBodyInit","XMLHttpRequestEventMap","XMLHttpRequestEventTarget","XMLHttpRequestEventTargetEventMap","XMLHttpRequestResponseType","XMLHttpRequestUpload","XMLSerializer","XPathEvaluator","XPathEvaluatorBase","XPathExpression","XPathNSResolver","XPathResult","XSLTProcessor","YearMonthLikeObject","ZonedDateTime","ZonedDateTimeConstructor","ZonedDateTimeFromOptions","ZonedDateTimeLike","ZonedDateTimeLikeObject","ZonedDateTimeToStringOptions","global","globalThis","process","structuredClone"])});function ya(e,t={strings:!0}){let r="",n=0;while(n<e.length){let i=e.slice(n,n+2);if(i==="//"){let o=e.indexOf(`
|
|
66
|
+
`,n),a=o===-1?e.length:o;r+=" ".repeat(a-n),n=a;continue}if(i==="/*"){let o=e.indexOf("*/",n+2),a=o===-1?e.length:o+2;for(let c=n;c<a;c++)r+=e[c]===`
|
|
67
67
|
`?`
|
|
68
|
-
`:" ";n=
|
|
68
|
+
`:" ";n=a;continue}let s=e[n];if(t.strings&&(s==='"'||s==="'"||s==="`")){let o=s;r+=" ",n++;while(n<e.length){if(e[n]==="\\"){r+=" ",n+=2;continue}if(e[n]===o){r+=" ",n++;break}r+=e[n]===`
|
|
69
69
|
`?`
|
|
70
|
-
`:" ",n++}continue}r+=s,n++}return r}function
|
|
70
|
+
`:" ",n++}continue}r+=s,n++}return r}function Vu(e){let t=new Set,r=[/\b(?:export\s+)?(?:declare\s+)?(?:abstract\s+)?(?:type|interface|class|enum|namespace|module)\s+([A-Za-z_$][\w$]*)/g,/\b(?:export\s+)?(?:declare\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/g,/\b(?:export\s+)?declare\s+(?:const|let|var)\s+([A-Za-z_$][\w$]*)/g];for(let n of r)for(let i of e.matchAll(n))t.add(i[1]);return t}function _u(e){let t=new Set;for(let r of e.matchAll(/\bimport\s+(?:type\s+)?([\s\S]*?)\s+from\s*['"`]/g)){let n=r[1],i=/\*\s*as\s+([A-Za-z_$][\w$]*)/.exec(n);if(i)t.add(i[1]);let s=n.split("{")[0].replace(/\*\s*as\s+[A-Za-z_$][\w$]*/,"");for(let a of s.split(",")){let c=a.trim();if(/^[A-Za-z_$][\w$]*$/.test(c))t.add(c)}let o=/\{([\s\S]*?)\}/.exec(n);if(o)for(let a of o[1].split(",")){let c=a.trim().replace(/^type\s+/,"");if(!c)continue;let f=/\bas\s+([A-Za-z_$][\w$]*)$/.exec(c);t.add(f?f[1]:c.split(/\s+/)[0])}}for(let r of e.matchAll(/\bimport\s*\(\s*['"`][^'"`]*['"`]\s*\)\s*\.\s*([A-Za-z_$][\w$]*)/g))t.add(r[1]);return t}function Hu(e){let t=new Set,r=(i)=>{for(let s of i.split(",")){let o=s.trim().split(/\s+|=/)[0]?.trim();if(o&&/^[A-Za-z_$][\w$]*$/.test(o))t.add(o)}},n=/\b(?:type|interface|class|function)\s+[A-Za-z_$][\w$]*\s*<([^<>]*(?:<[^<>]*>[^<>]*)*)>/g;for(let i of e.matchAll(n))r(i[1]);for(let i of e.matchAll(/(?:\b[A-Za-z_$][\w$]*)?\s*<([^<>()]*)>\s*\(/g))r(i[1]);for(let i of e.matchAll(/\binfer\s+([A-Za-z_$][\w$]*)/g))t.add(i[1]);for(let i of e.matchAll(/\[\s*([A-Za-z_$][\w$]*)\s+in\b/g))t.add(i[1]);return t}function ju(e){let t=new Map,r=(i)=>{let s=1;for(let o=0;o<i&&o<e.length;o++)if(e.charCodeAt(o)===10)s++;return s},n=(i,s,o)=>{for(let a of i.matchAll(/\b([A-Z][\w$]*)\b/g)){let c=a[1];if(t.has(c))continue;let f=i.slice(a.index+c.length);if(/^\s*\??:/.test(f))continue;t.set(c,{line:r(s),context:o.trim().slice(0,120)})}};for(let i of e.matchAll(/\btype\s+[A-Za-z_$][\w$]*\s*(?:<[^=]*?>)?\s*=([^;]*)/g))n(i[1],i.index+i[0].indexOf("="),i[0]);for(let i of e.matchAll(/\b(?:extends|implements)\s+([^{;]*)/g))n(i[1],i.index,i[0]);for(let i of e.matchAll(/:\s*([^;,){}\n=]+)/g))n(i[1],i.index,i[0]);for(let i of e.matchAll(/<([^<>()]*)>/g))n(i[1],i.index,i[0]);return t}function Ca(e){let t=ya(e),r=ya(e,{strings:!1}),n=new Set([...Vu(t),..._u(r),...Hu(t),...pa,...Bu]),i=[];for(let[s,o]of ju(t)){if(n.has(s))continue;if(new RegExp(`[\\w$]\\s*\\.\\s*${s}\\b`).test(t))continue;i.push({name:s,line:o.line,context:o.context})}return i.sort((s,o)=>s.line-o.line||s.name.localeCompare(o.name))}var Bu;var wa=ce(()=>{ga();Bu=new Set(["This","True","False","Null","Undefined","Void","Never","Any","Unknown","Object","Infinity","NaN"])});function rr(e,t){let r=1,n=1;for(let i=0;i<t;i++)if(e.charCodeAt(i)===10)r++,n=1;else n++;return{line:r,column:n}}function $a(e){let t=[],r=[],n=[],i={")":"(","]":"[","}":"{"},s=0,o=0,a=-1;for(let f=0;f<e.length;f++){let u=e.charCodeAt(f),l=e.charCodeAt(f+1);if(a!==-1){if(u===42&&l===47)r.push({start:a,end:f+2}),a=-1,f++;continue}if(s){if(u===92)f++;else if(u===s)r.push({start:o,end:f+1}),s=0;continue}if(u===47&&l===42){a=f,f++;continue}if(u===47&&l===47){let d=f;while(f<e.length&&e.charCodeAt(f)!==10)f++;r.push({start:d,end:f});continue}if(u===39||u===34||u===96){s=u,o=f;continue}let g=e[f];if(g==="("||g==="["||g==="{")n.push({char:g,offset:f});else if(i[g]){let d=n.pop();if(!d||d.char!==i[g])t.push({...rr(e,f),message:`Unexpected closing delimiter ${g}`,code:"DTSX1004"})}}if(s)t.push({...rr(e,o),message:"Unterminated string literal",code:"DTSX1002"});if(a!==-1)t.push({...rr(e,a),message:"Unterminated block comment",code:"DTSX1003"});for(let f of n)t.push({...rr(e,f.offset),message:`Unclosed delimiter ${f.char}`,code:"DTSX1001"});let c=[[/\b(?:interface|class|enum)\s*(?=[{=])/g,"Declaration name expected"],[/\bfunction\s*(?=\()/g,"Function name expected"],[/\(\s*:/g,"Parameter name expected"]];for(let[f,u]of c)for(let l of e.matchAll(f)){if(r.some((g)=>l.index>=g.start&&l.index<g.end))continue;t.push({...rr(e,l.index),message:u,code:"DTSX1005"})}for(let f of e.matchAll(/\btype\s*(?=[{=])/g)){if(r.some((l)=>f.index>=l.start&&f.index<l.end))continue;let u=e.slice(0,f.index).trimEnd();if(u.endsWith("import")||u.endsWith("export"))continue;t.push({...rr(e,f.index),message:"Declaration name expected",code:"DTSX1005"})}return t.sort((f,u)=>f.line-u.line||f.column-u.column)}var Ea=()=>{};import{readFile as Ku,stat as qg,writeFile as Ju}from"fs/promises";async function va(e,t){if(wi)return globalThis.Bun.write(e,t);let r=typeof t==="string"?t:t instanceof ArrayBuffer?Buffer.from(t):t;return await Ju(e,r),typeof t==="string"?Buffer.byteLength(t):t.byteLength}async function $t(e){if(wi)return globalThis.Bun.file(e).text();return Ku(e,"utf-8")}var wi,Xg;var $i=ce(()=>{wi=typeof globalThis.Bun<"u",Xg=!wi&&typeof process<"u"&&!!process.versions?.node});import{statSync as Uu}from"fs";import{readFile as Yu,readdir as ny}from"fs/promises";import{createRequire as Zu}from"module";import{dirname as qu,isAbsolute as Sa,join as Xu,resolve as ba}from"path";import zu from"process";function jn(){return`${String.fromCharCode(47,47,35)} sourceMappingURL=`}async function yr(e,t,r="lf"){let n=t.replace(/\r\n/g,`
|
|
71
71
|
`);if(!n.endsWith(`
|
|
72
72
|
`))n+=`
|
|
73
73
|
`;if(r==="crlf")n=n.replace(/\n/g,`\r
|
|
74
|
-
`);await
|
|
75
|
-
`;r++}r=Math.min(r+2,e.length);continue}if(i===44){let s=r+1;while(s<e.length){while(s<e.length&&e.charCodeAt(s)<=32)s++;if(e.charCodeAt(s)===47&&e.charCodeAt(s+1)===47){s+=2;while(s<e.length&&e.charCodeAt(s)!==10)s++;continue}if(e.charCodeAt(s)===47&&e.charCodeAt(s+1)===42){s+=2;while(s+1<e.length&&!(e.charCodeAt(s)===42&&e.charCodeAt(s+1)===47))s++;s=Math.min(s+2,e.length);continue}break}let
|
|
74
|
+
`);await va(e,n)}function Qu(e){let t="",r=0,n=0;while(r<e.length){let i=e.charCodeAt(r);if(n){if(t+=e[r],i===92&&r+1<e.length){t+=e[r+1],r+=2;continue}if(i===n)n=0;r++;continue}if(i===34){n=i,t+=e[r++];continue}if(i===47&&e.charCodeAt(r+1)===47){r+=2;while(r<e.length&&e.charCodeAt(r)!==10)r++;continue}if(i===47&&e.charCodeAt(r+1)===42){r+=2;while(r+1<e.length&&!(e.charCodeAt(r)===42&&e.charCodeAt(r+1)===47)){if(e.charCodeAt(r)===10)t+=`
|
|
75
|
+
`;r++}r=Math.min(r+2,e.length);continue}if(i===44){let s=r+1;while(s<e.length){while(s<e.length&&e.charCodeAt(s)<=32)s++;if(e.charCodeAt(s)===47&&e.charCodeAt(s+1)===47){s+=2;while(s<e.length&&e.charCodeAt(s)!==10)s++;continue}if(e.charCodeAt(s)===47&&e.charCodeAt(s+1)===42){s+=2;while(s+1<e.length&&!(e.charCodeAt(s)===42&&e.charCodeAt(s+1)===47))s++;s=Math.min(s+2,e.length);continue}break}let o=e.charCodeAt(s);if(o===93||o===125){r++;continue}}t+=e[r++]}return t}function Hn(e){let t=[e];if(!e.endsWith(".json"))t.push(`${e}.json`);t.push(Xu(e,"tsconfig.json"));for(let r of t)try{if(Uu(r).isFile())return r}catch{}return null}function eh(e,t){if(Sa(e)||e.startsWith("."))return Hn(ba(qu(t),e));let r=Zu(t);for(let n of[e,`${e}/tsconfig.json`])try{let i=Hn(r.resolve(n));if(i)return i}catch{}return null}async function Aa(e,t){let r=Hn(e);if(!r||t.has(r))return;t.add(r);let n=await Yu(r,"utf8"),i=JSON.parse(Qu(n)),s=typeof i.extends==="string"?[i.extends]:i.extends??[],o;for(let a of s){let c=eh(a,r);if(!c)continue;let f=await Aa(c,t);if(f!==void 0)o=f}return i.compilerOptions?.isolatedDeclarations??o}async function xa(e){try{let t=e?.cwd||zu.cwd(),r=e?.tsconfigPath||"tsconfig.json",n=Sa(r)?r:ba(t,r);return await Aa(n,new Set)??!1}catch{return!1}}function Ta(e,t){let r={isValid:!0,errors:[]};for(let n of $a(e))r.errors.push({line:n.line,column:n.column,message:n.message,code:n.code});for(let n of Ca(e))r.errors.push({line:n.line,column:1,message:`'${n.name}' is used but never declared or imported here, so it resolves to an error type for anything consuming this file. It is most likely an ambient global in the source project \u2014 import it explicitly. Referenced by: ${n.context}`,code:"dangling-type-reference"});return r.isValid=r.errors.length===0,r}function Ra(e,t,r){if(e===t)return"";let n=e.split(`
|
|
76
76
|
`),i=t.split(`
|
|
77
|
-
`),s=new Map,
|
|
78
|
-
`)}function
|
|
79
|
-
`),s=[];function
|
|
80
|
-
`).length;for(let l=0;l<i.length;l++){if(i[l].trim()===""){s.push("");continue}
|
|
81
|
-
${
|
|
82
|
-
`}var
|
|
83
|
-
`)||i.includes("\r"))return"string";return i}if(i.charCodeAt(0)===39||i.charCodeAt(0)===34){let
|
|
84
|
-
`;if(r==="t")return"\t";if(r==="r")return"\r";if(r==="0")return"\x00";return r})}function
|
|
85
|
-
`)||e.includes("\r"))return"string";return e}function
|
|
77
|
+
`),s=new Map,o=new Map;for(let u=0;u<n.length;u++)s.set(n[u],(s.get(n[u])??0)+1);for(let u=0;u<i.length;u++)o.set(i[u],(o.get(i[u])??0)+1);let a=[],c=[];for(let[u,l]of s){let g=l-(o.get(u)??0);for(let d=0;d<g;d++)a.push(u)}for(let[u,l]of o){let g=l-(s.get(u)??0);for(let d=0;d<g;d++)c.push(u)}if(a.length===0&&c.length===0)return"";let f=[`--- ${r}`,`+++ ${r}`];for(let u=0;u<a.length;u++)f.push(`- ${a[u]}`);for(let u=0;u<c.length;u++)f.push(`+ ${c[u]}`);return f.join(`
|
|
78
|
+
`)}function Oa(e,t,r,n){let i=e.split(`
|
|
79
|
+
`),s=[];function o(l){let g="",d=l<0?-l<<1|1:l<<1;do{let E=d&31;if(d>>>=5,d>0)E|=32;g+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[E]}while(d>0);return g}let a=0,c=0,f=0,u=n.split(`
|
|
80
|
+
`).length;for(let l=0;l<i.length;l++){if(i[l].trim()===""){s.push("");continue}a=0;let g=Math.min(l,u-1),d=[],E=0-a,S=0,C=g-c,T=0-f;d.push(o(E)+o(S)+o(C)+o(T)),a=0,c=g,f=0,s.push(d.join(","))}return{version:3,file:t,sourceRoot:"",sources:[r],sourcesContent:[n],mappings:s.join(";")}}function Pa(e,t){return`${e}
|
|
81
|
+
${jn()}${t}
|
|
82
|
+
`}var ka=ce(()=>{wa();Ea();$i()});function Ma(e,t){let r=Number.isFinite(t)?Math.max(1,Math.floor(t)):1;if(e===void 0||!Number.isFinite(e))return r;return Math.max(1,Math.floor(e))}var Da=()=>{};function th(e){if(e.indexOf("/*")===-1)return e.trim();let t=[],r=0,n=0,i=e.length;while(n<i)if(e.charCodeAt(n)===47&&n+1<i&&e.charCodeAt(n+1)===42){if(n>r)t.push(e.substring(r,n));n+=2;while(n<i-1){if(e.charCodeAt(n)===42&&e.charCodeAt(n+1)===47){n+=2;break}n++}r=n}else n++;if(r<i)t.push(e.substring(r));return t.join("").trim()}function Zn(){bi=!0,Ke=null}function qn(){bi=!1;let e=Ke;return Ke=null,e}function Xn(e){let t=e.length;if(t===0)return!1;let r=0;if(e.charCodeAt(r)===45)r++;if(r>=t)return!1;let n=r;while(r<t&&e.charCodeAt(r)>=48&&e.charCodeAt(r)<=57)r++;if(r===n)return!1;if(r<t&&e.charCodeAt(r)===46){r++;let i=r;while(r<t&&e.charCodeAt(r)>=48&&e.charCodeAt(r)<=57)r++;if(r===i)return!1}return r===t}function rh(e){for(let t=0,r=e.length-1;t<r;t++){let n=e.charCodeAt(t);if(n<48||n>57)return!1}return!0}function Kn(e,t){let r=0,n=0;while((n=e.indexOf(t,n))!==-1)r++,n+=t.length;return r}function Ia(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===36||e===95||e===46||e===58||e===45}function Ei(e){let t=e.trim();if(t.length<3||t.charCodeAt(0)!==60)return!1;if(t.startsWith("<>"))return t.endsWith("</>");let r=t.charCodeAt(1);if(!(r>=65&&r<=90||r>=97&&r<=122||r===36||r===95))return!1;let n=2;while(n<t.length&&Ia(t.charCodeAt(n)))n++;let i=t.slice(1,n),s=t.charCodeAt(n);if(s>32&&s!==62&&s!==47)return!1;if(t.endsWith("/>"))return!0;let o=t.lastIndexOf("</");if(o===-1)return!1;let a=o+2;while(a<t.length&&Ia(t.charCodeAt(a)))a++;return t.slice(o+2,a)===i&&t.charCodeAt(a)===62&&a===t.length-1}function Cr(e){let t=e.length,r=!1;for(let o=1;o<t;o++)if(e.charCodeAt(o)<=32&&e.charCodeAt(o-1)<=32){r=!0;break}if(!r)for(let o=0;o<t;o++){let a=e.charCodeAt(o);if(a===10||a===13||a===9){r=!0;break}}if(!r)return e;let n=[],i=-1,s=!1;for(let o=0;o<t;o++)if(e.charCodeAt(o)<=32){if(!s){if(i>=0)n.push(e.substring(i,o));n.push(" "),s=!0,i=-1}}else{if(s||i<0)i=o;s=!1}if(i>=0)n.push(e.substring(i));return n.join("")}function Te(e,t=!1,r=!1,n=0){if(!e||typeof e!=="string")return"unknown";if(n>=20)return"unknown";let i=e.trim();if(Ei(i))return"JSX.Element";if(i.startsWith("BigInt("))return"bigint";if(i.startsWith("Symbol.for("))return"symbol";if(i.includes(".raw`")||i.includes("String.raw`"))return"string";if(i.startsWith("`")&&i.endsWith("`")){if(!t||i.includes("${")||i.includes(`
|
|
83
|
+
`)||i.includes("\r"))return"string";return i}if(i.charCodeAt(0)===39||i.charCodeAt(0)===34){let o=ih(i);if(o!==null){if(o==="string"||!t)return"string";return o}}if(Xn(i)){if(!t)return"number";return i}if(i==="true"||i==="false"){if(!t)return"boolean";return i}if(i==="null")return"null";if(i==="undefined")return"undefined";if(i.startsWith("[")&&i.endsWith("]"))return Jn(i,t,n+1);if(i.startsWith("{")&&i.endsWith("}"))return gh(i,t,n+1);if(i.startsWith("class ")||i.startsWith("class{"))return mh(i);if(i.startsWith("new "))return dh(i);if(i.endsWith("as const")){let o=i.slice(0,-8).trim();if(o.startsWith("[")&&o.endsWith("]")){let a=o.slice(1,-1).trim();if(!a)return"readonly []";let c=vi(a),f=[];for(let u=0;u<c.length;u++)f.push(Te(c[u].trim(),!0,!1,n+1));return`readonly [${f.join(", ")}]`}return Te(o,!0,r,n+1)}if(Si(i)!==-1||i.startsWith("function")||i.startsWith("async"))return Ja(i,r,n,t);if(i.startsWith("`")&&i.endsWith("`"))return hh(i,t);if(i.startsWith("Promise."))return _a(i,t,n);if(i.startsWith("await "))return"unknown";if(i.charCodeAt(i.length-1)===110&&i.length>1&&rh(i)){if(t)return i;return"bigint"}if(i.startsWith("Symbol(")||i==="Symbol.for")return"symbol";let s=Ha(i);if(s!==null)return s;if(lh(i))return"boolean";if(ah(i))return"number";return"unknown"}function Fa(e){let t=e.charCodeAt(0);if(t!==39&&t!==34)return!1;return kt(e,0,t)===e.length}function ih(e){if(Fa(e))return e;let t=nh(e);if(t.length<2)return null;let r=!1,n=!0,i="";for(let s of t){let o=s.trim();if(Fa(o))r=!0,i+=sh(o);else n=!1}if(n)return oh(i);if(r)return"string";return null}function nh(e){let t=[],r=0,n=0,i=0;while(i<e.length){let s=e.charCodeAt(i);if(s===39||s===34||s===96){i=kt(e,i,s);continue}if(s===40||s===91||s===123)r++;else if(s===41||s===93||s===125)r--;else if(s===43&&r===0)t.push(e.slice(n,i)),n=i+1;i++}return t.push(e.slice(n)),t}function sh(e){return e.slice(1,-1).replace(/\\(.)/g,(t,r)=>{if(r==="n")return`
|
|
84
|
+
`;if(r==="t")return"\t";if(r==="r")return"\r";if(r==="0")return"\x00";return r})}function oh(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function ah(e){if(e==="")return!1;let t=!1,r=!1;for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);if(i>=48&&i<=57){t=!0;continue}if(i===43||i===45||i===42||i===47||i===37){r=!0;continue}if(i===46||i===40||i===41||i<=32)continue;return!1}return t&&r}function lh(e){let t=0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n===34||n===39||n===96){r=kt(e,r,n)-1;continue}if(n===40||n===91||n===123){t++;continue}if(n===41||n===93||n===125){t--;continue}if(t!==0)continue;if(e.startsWith("===",r)||e.startsWith("!==",r)||e.startsWith("==",r)||e.startsWith("!=",r)||e.startsWith(">=",r)||e.startsWith("<=",r))return!0;if((n===62||n===60)&&e.charCodeAt(r-1)!==61&&e.charCodeAt(r+1)!==61)return!0}return!1}function ch(e,t=!1,r=0){return Te(e,t,!0,r)}function wr(e,t=!1,r=""){let n=Ba(r),i=[],s=!1,o=0;while(o<e.length){let c=e.charCodeAt(o);if(c===34||c===39||c===96){o=kt(e,o,c);continue}if(c===47&&e.charCodeAt(o+1)===47){o+=2;while(o<e.length&&e.charCodeAt(o)!==10&&e.charCodeAt(o)!==13)o++;continue}if(c===47&&e.charCodeAt(o+1)===42){let f=e.indexOf("*/",o+2);o=f===-1?e.length:f+2;continue}if(e.startsWith("function",o)&&Na(e,o,8)||e.startsWith("class",o)&&Na(e,o,5)){let f=uh(e,o);if(f!==-1){o=Wa(e,f);continue}}if(c===61&&e.charCodeAt(o+1)===62){let f=o+2;while(f<e.length&&e.charCodeAt(f)<=32)f++;if(e.charCodeAt(f)===123){o=Wa(e,f);continue}}if(e.startsWith("return",o)&&(o===0||!Et(e.charCodeAt(o-1)))&&!Et(e.charCodeAt(o+6))){o+=6;let f=!1;while(o<e.length&&e.charCodeAt(o)<=32){let C=e.charCodeAt(o);if(C===10||C===13)f=!0;o++}if(f||o>=e.length||e.charCodeAt(o)===59||e.charCodeAt(o)===125){s=!0;continue}let u=o,l=0,g=0,d=0;while(o<e.length){let C=e.charCodeAt(o);if(C===34||C===39||C===96){o=kt(e,o,C);continue}if(C===47&&e.charCodeAt(o+1)===47)break;if(C===47&&e.charCodeAt(o+1)===42){let T=e.indexOf("*/",o+2);o=T===-1?e.length:T+2;continue}if(C===40)l++;else if(C===41)l--;else if(C===91)g++;else if(C===93)g--;else if(C===123)d++;else if(C===125){if(d===0&&l===0&&g===0)break;d--}else if(C===59&&l===0&&g===0&&d===0)break;else if((C===10||C===13)&&l===0&&g===0&&d===0){let T=o+1;while(T<e.length&&e.charCodeAt(T)<=32)T++;if(e.startsWith("return",T)&&!Et(e.charCodeAt(T+6)))break}o++}let E=e.slice(u,o).trim(),S=Pt(E,n);if(!i.includes(S))i.push(S);continue}o++}if(s&&!i.includes("undefined"))i.push("undefined");let a=i.includes("unknown")?"unknown":i.length===0?"void":i.join(" | ");return t&&!a.startsWith("Promise<")?`Promise<${a}>`:a}function Ba(e){let t=new Map,r=e.startsWith("(")&&e.endsWith(")")?e.slice(1,-1):e,n=0,i=0,s=0;for(let o=0;o<=r.length;o++){let a=r.charCodeAt(o);if(a===40||a===91||a===123)i++;else if(a===41||a===93||a===125)i--;else if(a===60)s++;else if(a===62&&r.charCodeAt(o-1)!==61&&s>0)s--;if(o!==r.length&&(a!==44||i!==0||s!==0))continue;let c=r.slice(n,o).trim(),f=c.indexOf(":");if(f!==-1){let u=c.slice(0,f).trim().replace(/^\.\.\./,"").replace(/\?$/,""),l=c.slice(f+1).trim(),g=l.indexOf("=");if(g!==-1)l=l.slice(0,g).trim();if($r(u)&&l)t.set(u,l)}n=o+1}return t}function Pt(e,t){let r=e.trim();while(Va(r))r=r.slice(1,-1).trim();if(Ei(r))return"JSX.Element";if(r.startsWith("await ")){let s=Pt(r.slice(6),t);return s.startsWith("Promise<")&&s.endsWith(">")?s.slice(8,-1):s}if(t.has(r))return t.get(r);if(r.startsWith("!"))return"boolean";if(r.startsWith("fetch("))return"Promise<Response>";let n=fh(r);if(n){let s=Pt(n.whenTrue,t),o=Pt(n.whenFalse,t);return s===o?s:`${s} | ${o}`}if(["===","!==","==","!=",">=","<="].some((s)=>r.includes(s))||r.includes(" > ")||r.includes(" < "))return"boolean";let i=0;for(let s=r.length-1;s>=0;s--){let o=r.charCodeAt(s);if(o===41||o===93||o===125)i++;else if(o===40||o===91||o===123)i--;else if(i===0&&(o===43||o===45||o===42||o===47||o===37)){let a=Pt(r.slice(0,s),t),c=Pt(r.slice(s+1),t);if(o===43&&(a==="string"||c==="string"))return"string";if(a==="number"&&c==="number")return"number";break}}return Te(r,!1).replace(/\btypeof\s+[$A-Z_a-z][$\w]*/g,(s)=>{let o=s.slice(7);return t.get(o)??"unknown"})}function Va(e){if(!e.startsWith("(")||!e.endsWith(")"))return!1;let t=0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n===40)t++;else if(n===41&&--t===0)return r===e.length-1}return!1}function fh(e){let t=0,r=-1;for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);if(i===40||i===91||i===123)t++;else if(i===41||i===93||i===125)t--;else if(i===63&&t===0&&e.charCodeAt(n+1)!==63)r=n;else if(i===58&&t===0&&r!==-1)return{whenTrue:e.slice(r+1,n),whenFalse:e.slice(n+1)}}return null}function Na(e,t,r){return(t===0||!Et(e.charCodeAt(t-1)))&&!Et(e.charCodeAt(t+r))}function uh(e,t){for(let r=t;r<e.length;r++){let n=e.charCodeAt(r);if(n===34||n===39||n===96){r=kt(e,r,n)-1;continue}if(n===123)return r;if(n===59)return-1}return-1}function Wa(e,t){let r=1,n=t+1;while(n<e.length&&r>0){let i=e.charCodeAt(n);if(i===34||i===39||i===96){n=kt(e,n,i);continue}if(i===47&&e.charCodeAt(n+1)===47){n+=2;while(n<e.length&&e.charCodeAt(n)!==10&&e.charCodeAt(n)!==13)n++;continue}if(i===47&&e.charCodeAt(n+1)===42){let s=e.indexOf("*/",n+2);n=s===-1?e.length:s+2;continue}if(i===123)r++;else if(i===125)r--;n++}return n}function kt(e,t,r){let n=t+1;while(n<e.length){let i=e.charCodeAt(n);if(i===92){n+=2;continue}if(n++,i===r)break}return n}function hh(e,t){if(e.includes(".raw`")||e.includes("String.raw`"))return"string";if(!t||e.includes("${")||e.includes(`
|
|
85
|
+
`)||e.includes("\r"))return"string";return e}function dh(e){let t=4;while(t<e.length&&e.charCodeAt(t)<=32)t++;let r=t,n=e.charCodeAt(t);if(n<65||n>90)return"unknown";while(t<e.length&&(Et(e.charCodeAt(t))||e.charCodeAt(t)===46))t++;if(t===r)return"unknown";let i=e.slice(r,t);{let s=e.slice(t),o=s;if(s.startsWith("<")){let c=0,f=-1;for(let u=0;u<s.length;u++)if(s[u]==="<")c++;else if(s[u]===">"){if(c--,c===0){f=u;break}}if(f!==-1){let u=s.slice(0,f+1);o=s.slice(f+1);let l=o.indexOf("(");if(l!==-1){let g=0,d=-1;for(let E=l;E<o.length;E++)if(o[E]==="(")g++;else if(o[E]===")"){if(g--,g===0){d=E;break}}if(d!==-1){if(o.slice(d+1).trimStart().startsWith("."))return"unknown"}}return`${i}${u}`}}let a=o.indexOf("(");if(a!==-1){let c=0,f=-1;for(let u=a;u<o.length;u++)if(o[u]==="(")c++;else if(o[u]===")"){if(c--,c===0){f=u;break}}if(f!==-1){if(o.slice(f+1).trimStart().startsWith("."))return"unknown"}}switch(i){case"Date":return"Date";case"Map":return"Map<any, any>";case"Set":return"Set<any>";case"WeakMap":return"WeakMap<any, any>";case"WeakSet":return"WeakSet<any>";case"RegExp":return"RegExp";case"Error":return"Error";case"Array":return"any[]";case"Object":return"object";case"Function":return"Function";case"Promise":return"Promise<any>";default:return i}}return"unknown"}function mh(e){return"{ new (...args: any[]): any }"}function _a(e,t,r=0){if(e.startsWith("Promise.resolve(")){let n=e.indexOf(")",16);if(n!==-1){let i=e.slice(16,n).trim();if(i)return`Promise<${Te(i,t,!1,r+1)}>`}return"Promise<unknown>"}if(e.startsWith("Promise.reject("))return"Promise<never>";if(e.startsWith("Promise.all(")){let n=e.indexOf("[",12),i=e.lastIndexOf("]");if(n!==-1&&i>n){let s=e.slice(n+1,i).trim(),o=vi(s),a=[];for(let c=0;c<o.length;c++){let f=o[c].trim();if(f.startsWith("Promise.resolve(")){let u=_a(f,t,r+1),l=u.indexOf("<"),g=u.lastIndexOf(">");a.push(l!==-1&&g>l?u.slice(l+1,g):"unknown")}else a.push(Te(f,t,!1,r+1))}return`Promise<[${a.join(", ")}]>`}return"Promise<unknown[]>"}return"Promise<unknown>"}function Jn(e,t,r=0){let n=e.slice(1,-1).trim();if(!n)return"never[]";if(r>=20)return"unknown[]";let i=vi(n),s=!1;for(let g=0;g<i.length;g++){let d=i[g],E=d.length;while(E>0&&d.charCodeAt(E-1)<=32)E--;if(E>=8&&d.slice(E-8,E)==="as const"){s=!0;break}}if(s){let g=[];for(let d=0;d<i.length;d++){let E=i[d].trim();if(E.endsWith("as const")){let S=E.slice(0,-8).trim();if(S.startsWith("[")&&S.endsWith("]")){let C=S.slice(1,-1).trim(),T=vi(C),k=[];for(let O=0;O<T.length;O++)k.push(Te(T[O].trim(),!0,!1,r+1));g.push(`readonly [${k.join(", ")}]`)}else g.push(Te(S,!0,!1,r+1))}else if(E.startsWith("[")&&E.endsWith("]"))g.push(Jn(E,!0,r+1));else g.push(Te(E,!0,!1,r+1))}return`readonly [
|
|
86
86
|
${g.join(` |
|
|
87
87
|
`)}
|
|
88
|
-
]`}let
|
|
89
|
-
`:"",C
|
|
90
|
-
${C}: ${
|
|
88
|
+
]`}let o=bi&&!t,a=[],c=[];for(let g of i){let d=g.trim(),E=Ke;if(Ke=null,d.startsWith("...")){let S=d.slice(3).trim(),C=Te(S,!1,!1,r+1);if(C.endsWith("[]"))a.push(C.slice(0,-2));else if(C.startsWith("readonly [")&&C.endsWith("]"))a.push(C.slice(10,-1));else if(Er(S))a.push(`(typeof ${S})[number]`);else a.push("unknown")}else if(d.startsWith("[")&&d.endsWith("]"))a.push(Jn(d,t,r+1));else a.push(ch(d,t,r+1));if(o)c.push(Ke);Ke=E}if(o)if(Yn(e))Ke=Cr(e);else{let g=[];for(let d=0;d<i.length;d++){let E=i[d].trim();if(E.endsWith("as const"))continue;if(Un(E)||E==="null"||E==="undefined")g.push(E);else if(E.startsWith("[")&&Yn(E))g.push(Cr(E));else if(E.startsWith("{")){if(c[d])g.push(c[d])}else{let S=Te(E,!1,!1,0);if(S!=="unknown")g.push(S)}}if(g.length>0)Ke=`[${g.join(", ")}]`}if(t)return`readonly [${a.join(", ")}]`;let f=new Set,u=[],l=!0;for(let g of a){if(!f.has(g))f.add(g),u.push(g);if(l){if(!(Xn(g)||g==="true"||g==="false"||g.charCodeAt(0)===34&&g.charCodeAt(g.length-1)===34||g.charCodeAt(0)===39&&g.charCodeAt(g.length-1)===39))l=!1}}if(l&&a.length<=10)return`readonly [${a.join(", ")}]`;if(u.length===1)return`${u[0]}[]`;return`(${u.join(" | ")})[]`}function vi(e){let t=[],r=0,n=0,i=!1,s=0;for(let a=0;a<e.length;a++){let c=e.charCodeAt(a);if(!i&&(c===34||c===39||c===96))i=!0,s=c;else if(i&&c===s&&(a===0||e.charCodeAt(a-1)!==92))i=!1;if(!i){if(c===91||c===123||c===40)n++;else if(c===93||c===125||c===41)n--;else if(c===44&&n===0){let f=e.substring(r,a).trim();if(f)t.push(f);r=a+1;continue}}}let o=e.substring(r).trim();if(o)t.push(o);return t}function Un(e){if(Xn(e))return!0;if(e==="true"||e==="false")return!0;if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return!0;return!1}function ph(e){return e==="number"||e==="string"||e==="boolean"}function Yn(e){let t=!1,r=0,n=e.length;for(let i=0;i<n;i++){let s=e.charCodeAt(i);if(t){if(s===92){i++;continue}if(s===r)t=!1;continue}if(s===34||s===39||s===96){t=!0,r=s;continue}if(s===61&&i+1<n&&e.charCodeAt(i+1)===62)return!1;if(s>=97&&s<=122){let o=i;while(i<n&&(e.charCodeAt(i)>=97&&e.charCodeAt(i)<=122||e.charCodeAt(i)>=65&&e.charCodeAt(i)<=90||e.charCodeAt(i)>=48&&e.charCodeAt(i)<=57||e.charCodeAt(i)===95||e.charCodeAt(i)===36))i++;let a=e.slice(o,i);if(a==="new"||a==="async"||a==="await"||a==="function"||a==="yield"||a==="console"||a==="process")return!1;let c=i;while(c<n&&e.charCodeAt(c)<=32)c++;if(c<n&&e.charCodeAt(c)===40)return!1;i--}}return!0}function gh(e,t,r=0){let n=e.slice(1,-1).trim();if(!n)return"{}";if(r>=20)return"Record<string, unknown>";let i=vh(n),s=[],o=[],a=bi&&!t,c=[];for(let[l,g]of i){let{comments:d,key:E}=Eh(l),S=d?`${d}
|
|
89
|
+
`:"",C=E,T=!1;if(E==="..."){let F=g.trim(),j=Er(F)?`typeof ${F}`:Te(F,t,!1,r+1);if(j!=="unknown")o.push(j);if(a&&(Er(F)||F.startsWith("{")))c.push(`...${Cr(F)}`);continue}let k=Ke;Ke=null;let O,I=g.trim();if(I===E&&$r(I))O=`typeof ${I}`;else if(Ah(I)){T=!0;let F=xh(E);if(F){C=F.name;let j="";if(I.startsWith("async "))j="async ";if(I.charCodeAt(j.length)===42)j+="*";O=La(F.name,j+F.typeParams+I.slice(j.length))}else O=La(E,I)}else if(O=Te(g,t,!1,r+1),O.includes("=>")||O.includes("function")||O.includes("async"))O=Ch(O);let V=Ke;Ke=k;let L=g.trim(),R=Sh(E);if(R){let F=bh(R.kind,R.name,O);if(F){s.push(`${S}${F}`);continue}}if(!t&&ph(O)&&Un(L))s.push(`${S}/** @defaultValue ${L} */
|
|
90
|
+
${C}: ${O}`);else s.push(`${S}${C}: ${O}`);if(a){let F=th(C);if(L.endsWith("as const"));else if(Un(L))c.push(`${F}: ${L}`);else if(L.startsWith("[")&&Yn(L))c.push(`${F}: ${Cr(L)}`);else if(L.startsWith("{")){if(V)c.push(`${F}: ${V}`)}else if(T)c.push(`${F}: ${Cr(O)}`);else if(!L.startsWith("[")&&(L.includes("=>")||L.startsWith("function")||L.startsWith("async"))){let j=Ja(L,!1,0,!0);c.push(`${F}: ${j}`)}}}if(a&&c.length>0){let l=r>0?(r-1)/2:0,g=`{ ${c.join(", ")} }`;if(g.length<=80)Ke=g;else{let d=" ".repeat((l+1)*2),E=" ".repeat(l*2);Ke=`{
|
|
91
91
|
${d}${c.join(`,
|
|
92
92
|
${d}`)}
|
|
93
|
-
${
|
|
93
|
+
${E}}`}}let f=s.length>0?`{
|
|
94
94
|
${s.join(`;
|
|
95
95
|
`)}
|
|
96
|
-
}`:"{}";if(
|
|
97
|
-
`).map((f)=>
|
|
98
|
-
`),r=t.indexOf("async");if(r!==-1){let f=r>0?t.charCodeAt(r-1):32,u=r+5<t.length?t.charCodeAt(r+5):32;if(
|
|
99
|
-
`),key:e.slice(r).trim()}}function
|
|
100
|
-
`))
|
|
101
|
-
`,l+2);l=y===-1?
|
|
102
|
-
`,l+2);l=y===-1?
|
|
103
|
-
`,l+2);return l=m===-1?
|
|
104
|
-
`,h)+1,y=
|
|
105
|
-
`,l+2);l=
|
|
106
|
-
`,l+2);l=
|
|
107
|
-
`,l+2);l=
|
|
108
|
-
`,l+2);l=w===-1?
|
|
109
|
-
`,l),h=p===-1?
|
|
110
|
-
`));continue}break}if(m.length===0)return;return m.reverse(),m}function
|
|
111
|
-
`),y=[],w=[],
|
|
112
|
-
`);let
|
|
113
|
-
`)}function
|
|
114
|
-
`)){let m="",y=!1;for(let w=0;w<h.length;w++){let
|
|
115
|
-
`)===-1&&h.indexOf(":")!==-1&&h.indexOf("{")===-1&&h.indexOf("[")===-1&&h.indexOf("=")===-1&&h.indexOf("@")===-1&&h.indexOf("...")===-1){let
|
|
116
|
-
`,
|
|
117
|
-
`))h=h.slice(0,-1);m++;let
|
|
118
|
-
`)){let
|
|
119
|
-
`).map((
|
|
120
|
-
`)}let
|
|
121
|
-
`,
|
|
122
|
-
`;if(m==="t")return"\t";if(m==="r")return"\r";if(m==="0")return"\x00";return m})}function
|
|
96
|
+
}`:"{}";if(o.length===0)return f;let u=o[0];for(let l=1;l<o.length;l++)u=`Omit<${u}, keyof ${o[l]}> & ${o[l]}`;return s.length>0?`Omit<${u}, keyof ${f}> & ${f}`:u}function $r(e){if(!e)return!1;let t=e.charCodeAt(0);if(!(t>=65&&t<=90||t>=97&&t<=122||t===95||t===36||t>127))return!1;for(let r=1;r<e.length;r++)if(!Et(e.charCodeAt(r)))return!1;return!0}function Er(e){let t=e.split(".");return t.length>0&&t.every($r)}function yh(e){let t=!1,r="";for(let n=0;n<e.length;n++){let i=e[n];if(t){if(i==="\\")n++;else if(i===r)t=!1;continue}if(i==='"'||i==="'"||i==="`"){t=!0,r=i;continue}if(i==="(")return n;if(i==="<"){let s=tt(e,n,"<",">");if(s!==-1)n=s}}return-1}function Ha(e){if(e.length<3||!e.endsWith(")"))return null;let t=yh(e);if(t===-1||tt(e,t,"(",")")!==e.length-1)return null;let r=e.slice(0,t).trim(),n=!1;if(r.endsWith("?."))n=!0,r=r.slice(0,-2).trim();let i=r,s=!1,o=r.indexOf("<");if(o!==-1){if(tt(r,o,"<",">")!==r.length-1)return null;i=r.slice(0,o).trim(),s=!0}if(!Er(i))return null;let a=e.slice(t+1,-1).trim(),c=Si(a)!==-1||a.startsWith("function")||a.startsWith("async function"),f=Er(a),u=!c&&a.endsWith(")")&&Ha(a)!==null;if(!s&&!n&&!c&&!f&&!u)return null;let l=`ReturnType<typeof ${r}>`;return n?`${l} | undefined`:l}function Ch(e){let t=e.split(`
|
|
97
|
+
`).map((f)=>ja(f)).join(`
|
|
98
|
+
`),r=t.indexOf("async");if(r!==-1){let f=r>0?t.charCodeAt(r-1):32,u=r+5<t.length?t.charCodeAt(r+5):32;if(!Et(f)&&!Et(u))t=(t.slice(0,r)+t.slice(r+5)).trim()}let n=t.indexOf("(");if(n!==-1){let f=tt(t,n,"(",")");if(f!==-1){let u=t.slice(n,f+1),l=ir(u);t=t.slice(0,n)+l+t.slice(f+1)}}let i=t.length,s="",o=[],a=!1,c=!1;for(let f=0;f<i;f++){let u=t.charCodeAt(f);if(u===123||u===40)o.push(u);else if(u===125||u===41)o.pop();if(u<=32){if(a=!0,u===10||u===13)c=!0;continue}if(a&&s.length>0){let l=(o.length>0?o[o.length-1]:0)===123;if(c&&l){let g=s.charCodeAt(s.length-1),d=g===59||g===44||g===123||u===125,E=s.length>=2&&s.charCodeAt(s.length-1)===47&&s.charCodeAt(s.length-2)===42;if(!d&&!E)s+="; ";else s+=" "}else s+=" "}a=!1,c=!1,s+=t[f]}return s.trim()}function Et(e){return e>=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57||e===95||e===36}function ir(e){let t=e.trim(),r,n=!1;if(t.startsWith("(")&&t.endsWith(")"))r=t.slice(1,-1),n=!0;else r=t;let i=r.trim();if(!i)return n?"()":"";let s=!1;{let E=0;for(let S=0;S<i.length;S++){let C=i.charCodeAt(S);if(C===40||C===60||C===91||C===123)E++;else if(C===41||C===62||C===93||C===125)E--;else if(E===0&&C===61){let T=S>0?i.charCodeAt(S-1):0,k=S+1<i.length?i.charCodeAt(S+1):0;if(T!==61&&T!==33&&T!==60&&T!==62&&k!==61&&k!==62){s=!0;break}}}}if(!s)return t;let o=[],a=[],c=0,f=0,u=!1,l=0;for(let E=0;E<=i.length;E++){if(E===i.length){o.push(i.slice(c));break}let S=i.charCodeAt(E);if(u){if(S===92){E++;continue}if(S===l)u=!1;continue}if(S===47&&E+1<i.length){let C=i.charCodeAt(E+1);if(C===42){E+=2;while(E+1<i.length&&!(i.charCodeAt(E)===42&&i.charCodeAt(E+1)===47))E++;E++;continue}if(C===47){while(E<i.length&&i.charCodeAt(E)!==10)E++;continue}}if(S===39||S===34||S===96){u=!0,l=S;continue}if(S===40||S===60||S===91||S===123)f++;else if(S===41||S===62||S===93||S===125)f--;else if(S===44&&f===0){o.push(i.slice(c,E));let C=",",T=E+1;while(T<i.length&&i.charCodeAt(T)<=32)C+=i[T],T++;a.push(C),c=T}}let g=[];for(let E of o){let S=E.trim();if(!S){g.push(E);continue}if(S.startsWith("//"))continue;let C=ja(S),T=E.slice(0,E.length-E.trimStart().length);g.push(T+wh(C))}let d=g[0]||"";for(let E=1;E<g.length;E++)d+=(a[E-1]||", ")+g[E];return n?`(${d})`:d}function ja(e){let t=!1,r=0;for(let n=0;n<e.length-1;n++){let i=e.charCodeAt(n);if(t){if(i===92){n++;continue}if(i===r)t=!1;continue}if(i===39||i===34||i===96){t=!0,r=i;continue}if(i===47&&e.charCodeAt(n+1)===47)return e.slice(0,n).trimEnd()}return e}function wh(e){if(e.startsWith("..."))return e;let t=-1,r=-1,n=0,i=!1,s=0;for(let a=0;a<e.length;a++){let c=e.charCodeAt(a);if(i){if(c===92){a++;continue}if(c===s)i=!1;continue}if(c===47&&a+1<e.length){let f=e.charCodeAt(a+1);if(f===42){a+=2;while(a+1<e.length&&!(e.charCodeAt(a)===42&&e.charCodeAt(a+1)===47))a++;a++;continue}if(f===47){while(a<e.length&&e.charCodeAt(a)!==10)a++;continue}}if(c===39||c===34||c===96){i=!0,s=c;continue}if(c===40||c===60||c===91||c===123)n++;else if(c===41||c===62||c===93||c===125)n--;else if(n===0){if(c===58&&t===-1)t=a;else if(c===61&&r===-1&&(a===0||e.charCodeAt(a-1)!==61)&&(a+1>=e.length||e.charCodeAt(a+1)!==61&&e.charCodeAt(a+1)!==62))r=a}}let o=r!==-1;if(t!==-1&&(r===-1||t<r)){let a=e.slice(0,t).trim(),c=r!==-1?e.slice(t+1,r).trim():e.slice(t+1).trim(),f=o&&!a.endsWith("?")?"?":"";return`${a}${f}: ${c}`}else if(r!==-1){let a=e.slice(0,r).trim(),c=!a.endsWith("?")?"?":"",f=e.slice(r+1).trim(),u="unknown";if(f==="true"||f==="false")u="boolean";else if(/^-?\d+(\.\d+)?$/.test(f))u="number";else if(f.startsWith("'")&&f.endsWith("'")||f.startsWith('"')&&f.endsWith('"'))u="string";else if(f.startsWith("["))u="unknown[]";else if(f.startsWith("{"))u="Record<string, unknown>";return`${a}${c}: ${u}`}return e}function $h(e){let t=0,r=e.length;while(t<r){while(t<r&&(e.charCodeAt(t)===32||e.charCodeAt(t)===9||e.charCodeAt(t)===10||e.charCodeAt(t)===13))t++;if(t+1<r&&e.charCodeAt(t)===47&&e.charCodeAt(t+1)===42){t+=2;while(t+1<r&&!(e.charCodeAt(t)===42&&e.charCodeAt(t+1)===47))t++;t+=2;continue}break}return t}function Eh(e){let t=[],r=0,n=e.length;while(r<n){while(r<n&&e.charCodeAt(r)<=32)r++;if(r+1>=n||e.charCodeAt(r)!==47||e.charCodeAt(r+1)!==42)break;let i=r;r+=2;while(r+1<n&&!(e.charCodeAt(r)===42&&e.charCodeAt(r+1)===47))r++;r=Math.min(r+2,n),t.push(e.slice(i,r).trim())}return{comments:t.join(`
|
|
99
|
+
`),key:e.slice(r).trim()}}function vh(e){let t=[],r="",n="",i=0,s=!1,o="",a=!0,c=!1,f=0,u=!1,l=!1,g=0,d=!1,E=!1;for(let S=0;S<e.length;S++){let C=e.charCodeAt(S),T=S>0?e.charCodeAt(S-1):0,k=S<e.length-1?e.charCodeAt(S+1):0;if(!s&&!c&&C===47&&k===47){S+=2;while(S<e.length&&e.charCodeAt(S)!==10)S++;continue}if(!s&&!c&&C===47&&k===42){c=!0,f=1,r+="/*",S++;continue}else if(c&&C===42&&k===47){if(f--,r+="*/",S++,f===0)c=!1;continue}else if(c&&C===47&&k===42){f++,r+="/*",S++;continue}let O=e[S];if(!s&&(C===34||C===39||C===96))s=!0,o=O,r+=O;else if(s&&O===o&&T!==92)s=!1,r+=O;else if(!s&&!c)if(C===40&&i===0&&a&&g===0){n=r.trim();let I=$h(n),V=I>0?n.slice(0,I):"",L=n.slice(I),R="";if(L.startsWith("async ")||L.startsWith("async\t")||L.startsWith(`async
|
|
100
|
+
`))L=L.slice(6).trimStart(),R="async ";if(L.startsWith("*"))L=L.slice(1).trimStart(),R+="*";n=V+L,r=R+O,a=!1,d=!0,E=!1,i=1}else if(C===123||C===91||C===40){if(i++,r+=O,E&&C===123)E=!1}else if(C===125||C===93||C===41){if(i--,r+=O,C===41&&i===0&&!a&&!d)u=!0;if(d){if(C===41&&i===0&&!E)E=!0;else if(C===125&&i===0)d=!1,E=!1}}else if(C===58&&i===0&&a&&g===0)n=r.trim(),r="",a=!1;else if(C===58&&i===0&&u)l=!0,r+=O;else if(C===60&&l)g++,r+=O;else if(C===60&&a&&i===0)g++,r+=O;else if(C===62&&g>0&&T!==61)g--,r+=O;else if(C===61&&k===62&&l&&g===0)l=!1,u=!1,r+=O;else if(C===44&&i===0&&g===0&&!E){if(n&&r.trim()){let I=r.trim();t.push([n,I])}else if(a&&r.trim()){let I=r.trim();if($r(I))t.push([I,I]);else if(I.startsWith("...")&&I.length>3)t.push(["...",I.slice(3).trim()])}r="",n="",a=!0,u=!1,l=!1,g=0}else r+=O;else r+=O}if(n&&r.trim()){let S=r.trim();t.push([n,S])}else if(a&&r.trim()){let S=r.trim();if($r(S))t.push([S,S]);else if(S.startsWith("...")&&S.length>3)t.push(["...",S.slice(3).trim()])}return t}function Sh(e){let t=e.trim();if(t.startsWith("get ")&&t.length>4){let r=t.slice(4).trim();if(r)return{kind:"get",name:r}}if(t.startsWith("set ")&&t.length>4){let r=t.slice(4).trim();if(r)return{kind:"set",name:r}}return null}function bh(e,t,r){let n=r.trim();if(n.charCodeAt(0)!==40)return null;let i=tt(n,0,"(",")");if(i===-1)return null;let s=n.slice(1,i).trim(),o=n.slice(i+1).trimStart();if(!o.startsWith("=>"))return null;let a=o.slice(2).trim();if(e==="get")return`get ${t}(): ${a||"unknown"}`;return`set ${t}(${s})`}function Ah(e){let t=e;if(t.startsWith("async ")||t.startsWith("async\t"))t=t.slice(5).trimStart();if(t.startsWith("*"))t=t.slice(1).trimStart();if(!t.startsWith("("))return!1;let r=0;for(let n=0;n<t.length;n++){let i=t.charCodeAt(n);if(i===40)r++;else if(i===41){if(r--,r===0){let s=t.slice(n+1).trimStart();if(s.startsWith("{"))return!0;if(s.startsWith(":")){let o=Ka(s,1);if(o?.kind==="arrow")return!1;if(o?.kind==="body")return!0}return!1}}}return!1}function xh(e){let t=e.trimEnd();if(!t.endsWith(">"))return null;let r=0,n=-1;for(let s=t.length-1;s>=0;s--){let o=t.charCodeAt(s);if(o===62){if(s>0&&t.charCodeAt(s-1)===61)continue;r++}else if(o===60){if(r--,r===0){n=s;break}}}if(n===-1)return null;let i=t.slice(0,n).trimEnd();if(!i)return null;return{name:i,typeParams:t.slice(n)}}function La(e,t){let r=t.trimStart(),n=!1,i=!1;if(r.startsWith("async ")||r.startsWith("async\t"))n=!0,r=r.slice(5).trimStart();if(r.startsWith("*"))i=!0,r=r.slice(1).trimStart();let s="";if(r.charCodeAt(0)===60){let g=0,d=-1;for(let E=0;E<r.length;E++)if(r.charCodeAt(E)===60)g++;else if(r.charCodeAt(E)===62&&!(E>0&&r.charCodeAt(E-1)===61)){if(g--,g===0){d=E;break}}if(d!==-1)s=r.slice(0,d+1),r=r.slice(d+1).trimStart()}let o=r.indexOf("("),a=tt(r,o,"(",")");if(o===-1||a===-1)return"() => unknown";let c=r.slice(o,a+1),f="unknown",u=r.slice(a+1).trimStart();if(u.charCodeAt(0)===58){let g=u.slice(1),d=Ka(g,0);if(d)f=g.slice(0,d.index).trim();else f=g.trim()}if(f==="unknown"){if(n&&i)f="AsyncGenerator<unknown, void, unknown>";else if(i)f="Generator<unknown, void, unknown>";else if(n)f="Promise<void>"}else if(n&&!f.startsWith("Promise<")&&!f.startsWith("AsyncGenerator<"))f=`Promise<${f}>`;let l=ir(c);return`${s}${l} => ${f}`}function Ka(e,t){let r=0,n=0,i=0,s=0,o=!1,a=0;for(let c=t;c<e.length;c++){let f=e.charCodeAt(c);if(o){if(f===92)c++;else if(f===a)o=!1;continue}if(f===34||f===39||f===96){o=!0,a=f;continue}if(f===40)r++;else if(f===41&&r>0)r--;else if(f===91)n++;else if(f===93&&n>0)n--;else if(f===60)i++;else if(f===62&&i>0&&e.charCodeAt(c-1)!==61)i--;else if(f===125&&s>0)s--;else if(f===123){let u=r>0||n>0||i>0||s>0,l=e.slice(t,c).trimEnd(),g=l.charCodeAt(l.length-1),d=l.length===0||g===38||g===124||g===40||g===44||g===58||g===61||g===91;if(u||d)s++;else return{index:c,kind:"body"}}else if(f===61&&c+1<e.length&&e.charCodeAt(c+1)===62&&r===0&&n===0&&i===0&&s===0)return{index:c,kind:"arrow"}}return null}function tt(e,t,r,n){let i=0;for(let s=t;s<e.length;s++)if(e[s]===r)i++;else if(e[s]===n){if(n===">"&&s>0&&e[s-1]==="=")continue;if(i--,i===0)return s}return-1}function Si(e){let t=0,r=0,n=!1,i="";for(let s=0;s<e.length-1;s++){let o=e[s],a=e[s+1],c=s>0?e[s-1]:"";if(!n&&(o==='"'||o==="'"||o==="`"))n=!0,i=o;else if(n&&o===i&&c!=="\\")n=!1;if(!n){if(o==="<"){let f=tt(e,s,"<",">");if(f!==-1){s=f;continue}}if(o==="(")t++;else if(o===")")t--;else if(o==="[")r++;else if(o==="]")r--;if(o==="="&&a===">"&&t===0&&r===0)return s}}return-1}function Ja(e,t=!1,r=0,n=!0){let i=e.trim();if(i.length>200&&Kn(i,"=>")>2&&Kn(i,"<")>5&&!i.startsWith("function"))return t?"((...args: any[]) => any)":"(...args: any[]) => any";if(i.startsWith("async ")&&i.includes("=>")){let o=i.slice(5).trim(),a=Si(o);if(a===-1)return t?"(() => Promise<unknown>)":"() => Promise<unknown>";let c=o.substring(0,a).trim(),f=o.substring(a+2).trim(),u=Ga(c),l=u.params,g=u.returnType;if(l=ir(l),l==="()"||l==="")l="()";else if(!l.startsWith("("))l=`(${l})`;let d=g;if(d);else if(f.startsWith("{"))d=wr(f.slice(1,f.endsWith("}")?-1:void 0),!0,l);else d=Te(f,n,!1,r+1);let E=`${l} => ${g||d.startsWith("Promise<")?d:`Promise<${d}>`}`;return t?`(${E})`:E}if(i.includes("=>")){let o="",a=i;if(i.startsWith("<")){let C=tt(i,0,"<",">");if(C!==-1)o=i.substring(0,C+1),a=i.substring(C+1).trim()}let c=Si(a);if(c===-1)return t?"(() => unknown)":"() => unknown";let f=a.substring(0,c).trim(),u=a.substring(c+2).trim(),l=Ga(f),g=l.params,d=l.returnType;if(g=ir(g),g==="()"||g==="")g="()";else if(!g.startsWith("("))g=`(${g})`;let E="unknown";if(d)E=d;else if(u.startsWith("{"))E=wr(u.slice(1,u.endsWith("}")?-1:void 0),!1,g);else if(Ei(u)||Va(u)&&Ei(u.slice(1,-1).trim()))E="JSX.Element";else if(u.includes("=>")){let C=u.trimStart(),T=C.indexOf("("),k=T!==-1?tt(C,T,"(",")"):-1,O=k!==-1?C.indexOf("=>",k):-1;if(T===0&&k!==-1&&O!==-1){let I=C.substring(T+1,k).trim(),V=ir(I);if(o.includes("T")&&V.includes("T"))E=`(${V}) => T`;else E=`(${V}) => any`}else E="any"}else if(t)E="unknown";else E=Pt(u,Ba(g));let S=`${o}${g} => ${E}`;return t?`(${S})`:S}if(i.startsWith("function")){let o=8,a=i.length;while(o<a&&i.charCodeAt(o)<=32)o++;let c=!1;if(o<a&&i.charCodeAt(o)===42){c=!0,o++;while(o<a&&i.charCodeAt(o)<=32)o++}let f="";if(o<a&&i.charCodeAt(o)===60){let g=o,d=1;o++;while(o<a&&d>0){let E=i.charCodeAt(o);if(E===60)d++;else if(E===62&&i.charCodeAt(o-1)!==61)d--;o++}f=i.substring(g,o);while(o<a&&i.charCodeAt(o)<=32)o++}let u=i.indexOf("(",o);if(u!==-1){let g=1,d=u+1;while(d<a&&g>0){let T=i.charCodeAt(d);if(T===40)g++;else if(T===41)g--;d++}let E=i.substring(u+1,d-1).trim(),S=E?`(${E})`:"()";if(c){let T=i.substring(d).trim(),k=T.indexOf("Generator<");if(k!==-1){let I=k+10,V=T.indexOf(">",I);if(V!==-1){let L=T.substring(I,V),R=`${f}${S} => Generator<${L}>`;return t?`(${R})`:R}}let O=`${f}${S} => Generator<any, any, any>`;return t?`(${O})`:O}let C=`${f}${S} => unknown`;return t?`(${C})`:C}let l="(...args: any[]) => unknown";return t?`(${l})`:l}if(i.includes("=>")&&i.includes("(")&&i.includes(")")){if(i.length>100||Kn(i,"=>")>2){let o="";if(i.charCodeAt(0)===60){let l=tt(i,0,"<",">");if(l!==-1)o=i.substring(0,l+1)}let a=i.indexOf("("),c=a!==-1?tt(i,a,"(",")"):-1,f=a!==-1&&c!==-1?i.substring(a,c+1):"(...args: any[])";f=ir(f);let u=`${o}${f} => any`;return t?`(${u})`:u}return t?`(${i})`:i}let s="() => unknown";return t?`(${s})`:s}function Ga(e){let t=e.trim();if(!t.startsWith("("))return{params:t,returnType:""};let r=tt(t,0,"(",")");if(r===-1)return{params:t,returnType:""};let n=t.slice(r+1).trim();return{params:t.slice(0,r+1),returnType:n.startsWith(":")?n.slice(1).trim():""}}function Ua(e){let t=e.trim();if(t==="any"||t==="object"||t==="unknown")return!0;if(t.startsWith("Record<")&&t.endsWith(">"))return!0;if(t.startsWith("Array<")&&t.endsWith(">"))return!0;if(/^\{\s*\[[^\]]*\]:\s*(any|string|number|unknown)\s*\}$/.test(t))return!0;return!1}function Ya(e){let t=e.lastIndexOf(" satisfies ");if(t===-1)return null;let r=e.slice(t+11).trim();if(r.endsWith(";"))r=r.slice(0,-1).trim();return r||null}var bi=!1,Ke=null;var zn=()=>{};function Ne(e){return e===ve||e===Se||e===se||e===ge}function Mt(e){return e>=65&&e<=90||e>=97&&e<=122||e===Rh||e===Xa||e>127}function Je(e){return Mt(e)||e>=48&&e<=57}function Oh(e){let t=!0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n===ft){if(t)return!1;t=!0}else if(t){if(!Mt(n))return!1;t=!1}else if(!Je(n))return!1}return e.length>0&&!t}function Ti(e,t,r){let n=t+1;while(n<e.length){let i=e.charCodeAt(n);if(i===Ue){n+=2;continue}if(n++,i===r)break}return n}function Ph(e){if(e==="any"||e==="object"||e==="unknown")return!0;if(e.startsWith("Record<")||e.startsWith("Array<"))return!0;return e.charCodeAt(0)===H&&e.includes("[")&&e.includes("]:")}function za(e,t,r=!0){return el(e,t,r,!0)}function Qa(e,t,r=!0){return el(e,t,r,!1)}function el(e,t,r,n){let i=e,s=r,o=n,a=i.length,c=[],f=new Map,u=new Set,l=0;if(l<a&&i.charCodeAt(l)===65279)l++;function g(p,h){if(p<h){let m=i.charCodeAt(p),y=i.charCodeAt(h-1);if(m!==ve&&m!==Se&&m!==se&&m!==ge&&y!==ve&&y!==Se&&y!==se&&y!==ge)return i.slice(p,h)}while(p<h&&Ne(i.charCodeAt(p)))p++;while(h>p&&Ne(i.charCodeAt(h-1)))h--;return i.slice(p,h)}function d(){if(l>=a)return;let p=i.charCodeAt(l);if(p!==ve&&p!==Se&&p!==se&&p!==ge&&p!==U)return;while(l<a){let h=i.charCodeAt(l);if(h===ve||h===Se||h===se||h===ge){l++;continue}if(h===U&&l+1<a){let m=i.charCodeAt(l+1);if(m===U){let y=i.indexOf(`
|
|
101
|
+
`,l+2);l=y===-1?a:y+1;continue}if(m===$e){let y=i.indexOf("*/",l+2);l=y===-1?a:y+2;continue}}break}}function E(p){let h=p.length,m=0,y=h;for(let w=0;w<h;w++){let v=p.charCodeAt(w);if(m){if(v===Ue){w++;continue}if(v===m)m=0;continue}if(v===ne||v===le||v===Re){m=v;continue}if(v===U&&w+1<h){let x=p.charCodeAt(w+1);if(x===U){y=w;while(y>0&&(p.charCodeAt(y-1)===ve||p.charCodeAt(y-1)===Se))y--;return p.slice(0,y)}if(x===$e){let P=p.indexOf("*/",w+2);if(P!==-1){p=`${p.slice(0,w)} ${p.slice(P+2)}`,w--;continue}}}}y=h;while(y>0&&(p.charCodeAt(y-1)===ve||p.charCodeAt(y-1)===Se||p.charCodeAt(y-1)===ge))y--;return y<h?p.slice(0,y):p}function S(p){l++;let h=p===ne?"'":'"';while(l<a){let m=i.indexOf(h,l);if(m===-1){l=a;return}let y=0,w=m-1;while(w>=0&&i.charCodeAt(w)===Ue)y++,w--;if(y%2===0){l=m+1;return}l=m+1}}function C(){l++;let p=[];while(l<a){let h=i.charCodeAt(l);if(p.length===0){if(h===Ue){l+=2;continue}if(h===Re){l++;return}if(h===Xa&&l+1<a&&i.charCodeAt(l+1)===H){l+=2,p.push(0);continue}l++;continue}if(h===ne||h===le){S(h);continue}if(h===Re){C();continue}if(h===U&&l+1<a){let m=i.charCodeAt(l+1);if(m===U){let y=i.indexOf(`
|
|
102
|
+
`,l+2);l=y===-1?a:y+1;continue}if(m===$e){let y=i.indexOf("*/",l+2);l=y===-1?a:y+2;continue}if(I()){V();continue}l++;continue}if(h===H){p[p.length-1]++,l++;continue}if(h===Y){let m=p[p.length-1];if(m===0){p.pop(),l++;continue}p[p.length-1]=m-1,l++;continue}l++}}function T(){let p=i.charCodeAt(l);if(p===ne||p===le)return S(p),!0;if(p===Re)return C(),!0;if(p===U&&l+1<a){let h=i.charCodeAt(l+1);if(h===U){let m=i.indexOf(`
|
|
103
|
+
`,l+2);return l=m===-1?a:m+1,!0}if(h===$e){let m=i.indexOf("*/",l+2);return l=m===-1?a:m+2,!0}if(I())return V(),!0}return!1}function k(p){let h=p;for(;;){while(h>=0&&(i.charCodeAt(h)===ve||i.charCodeAt(h)===Se||i.charCodeAt(h)===se||i.charCodeAt(h)===ge))h--;if(h<0)return-1;if(i.charCodeAt(h)===U&&h>0&&i.charCodeAt(h-1)===$e){let w=i.lastIndexOf("/*",h-2);if(w===-1)return-1;h=w-1;continue}let m=i.lastIndexOf(`
|
|
104
|
+
`,h)+1,y=O(m,h);if(y!==-1){h=y-1;continue}return h}}function O(p,h){let m=0;for(let y=p;y<=h;y++){let w=i.charCodeAt(y);if(m){if(w===Ue){y++;continue}if(w===m)m=0;continue}if(w===ne||w===le||w===Re){m=w;continue}if(w===U&&y+1<=h&&i.charCodeAt(y+1)===U)return y}return-1}function I(){let p=k(l-1);if(p<0)return!0;let h=i.charCodeAt(p);if(h===Ee||h===ee||h===me||h===33||h===38||h===124||h===Ai||h===rt||h===it||h===q||h===H||h===Y||h===94||h===126||h===43||h===45||h===$e||h===37||h===pe||h===de)return!0;if(Je(h)){let m=p;while(m>=0&&Je(i.charCodeAt(m)))m--;let y=i.slice(m+1,p+1);if(y==="return"||y==="typeof"||y==="void"||y==="delete"||y==="throw"||y==="new"||y==="in"||y==="of"||y==="case"||y==="instanceof"||y==="yield"||y==="await")return!0}return!1}function V(){l++;let p=!1;while(l<a){let h=i.charCodeAt(l);if(h===Ue){l+=2;continue}if(p){if(h===Ae)p=!1;l++;continue}if(h===me){p=!0,l++;continue}if(h===U){l++;break}if(h===se||h===ge)break;l++}while(l<a&&Je(i.charCodeAt(l)))l++}function L(){let p=l;while(l<a&&Je(i.charCodeAt(l)))l++;return i.slice(p,l)}function R(p){if(l+p.length>a)return!1;for(let h=0;h<p.length;h++)if(i.charCodeAt(l+h)!==p.charCodeAt(h))return!1;if(l+p.length<a&&Je(i.charCodeAt(l+p.length)))return!1;return!0}function F(p){let h=l+p;while(h<a){let m=i.charCodeAt(h);if(m===ve||m===Se||m===se||m===ge){h++;continue}return m!==ft&&m!==Ee}return!1}function j(){if(l>=a)return!1;switch(i.charCodeAt(l)){case 101:return R("export")||R("enum");case 105:return R("import")||R("interface");case 102:return R("function");case 99:return R("class")||R("const");case 116:return R("type");case 108:return R("let");case 118:return R("var");case 100:return R("declare")||R("default");case 109:return R("module");case 110:return R("namespace");case 97:return R("abstract")||R("async");default:return!1}}function Z(){let p=i.charCodeAt(l);if(p!==se&&p!==ge)return!1;let h=l;if(l++,p===ge&&l<a&&i.charCodeAt(l)===se)l++;while(l<a){let y=i.charCodeAt(l);if(y===ve||y===Se||y===ge||y===se){l++;continue}if(y===U&&l+1<a){let w=i.charCodeAt(l+1);if(w===U){let v=i.indexOf(`
|
|
105
|
+
`,l+2);l=v===-1?a:v+1;continue}if(w===$e){let v=i.indexOf("*/",l+2);l=v===-1?a:v+2;continue}}break}let m=l>=a||j()||i.charCodeAt(l)===Y;return l=h,m}function oe(p){let h=p-1;while(h>=0){let b=i.charCodeAt(h);if(b===ve||b===Se||b===ge||b===se){h--;continue}break}if(h<0)return!0;let m=i[h];if("+-*/%=<>&|^!~?:,.([{".includes(m))return!0;let y=h;while(y>0&&i.charCodeAt(y-1)!==se)y--;let w=i.slice(y,h+1),v=w.lastIndexOf("<");if(v!==-1&&/^<[A-Za-z]/.test(w.slice(v))&&!w.slice(v).includes(">"))return!0;let x=h;while(x>=0&&/[a-z]/i.test(i[x]))x--;let P=i.slice(x+1,h+1);return["as","in","of","new","typeof","keyof","extends","instanceof","satisfies","await","return","yield","void"].includes(P)}function J(){let p=i.charCodeAt(l);if(p!==se&&p!==ge)return!1;if(oe(l))return!1;let h=l;l++;while(l<a){let v=i.charCodeAt(l);if(v===ve||v===Se||v===ge||v===se){l++;continue}if(v===U&&l+1<a){let x=i.charCodeAt(l+1);if(x===U){let P=i.indexOf(`
|
|
106
|
+
`,l+2);l=P===-1?a:P+1;continue}if(x===$e){let P=i.indexOf("*/",l+2);l=P===-1?a:P+2;continue}}break}let m=l<a?i[l]:"",y=i.slice(l,l+2),w=m==="."||m==="?"||m===":"||m===")"||m==="]"||m==="}"||m===","||m==="+"||m==="-"||m==="*"||m==="/"||m==="%"||m==="<"||m===">"||m==="="||m==="&"||m==="|"||m==="^"||m==="`"||y==="=>"||R("as")||R("satisfies")||R("instanceof")||R("in");return l=h,!w}function X(){let p=i.charCodeAt(l);if(p!==se&&p!==ge)return!1;if(oe(l))return!1;let h=l;l++;while(l<a){let w=i.charCodeAt(l);if(w===ve||w===Se||w===ge||w===se){l++;continue}if(w===U&&l+1<a){let v=i.charCodeAt(l+1);if(v===U){let x=i.indexOf(`
|
|
107
|
+
`,l+2);l=x===-1?a:x+1;continue}if(v===$e){let x=i.indexOf("*/",l+2);l=x===-1?a:x+2;continue}}break}let m=l<a?i[l]:"",y=m==="|"||m==="&"||m==="["||m==="."||m==="?"||m===":"||m===">"||m===")"||m===","||R("extends");return l=h,!y}function re(){let p=i.charCodeAt(l);if(p!==se&&p!==ge)return!1;let h=l;if(l++,p===ge&&l<a&&i.charCodeAt(l)===se)l++;while(l<a){let y=i.charCodeAt(l);if(y===ve||y===Se||y===ge||y===se){l++;continue}if(y===U&&l+1<a&&i.charCodeAt(l+1)===U){let w=i.indexOf(`
|
|
108
|
+
`,l+2);l=w===-1?a:w+1;continue}break}if(l>=a)return l=h,!0;let m=i.charCodeAt(l);if(m===124||m===38||m===ft||m===Ai||m===rt)return l=h,!1;if(R("extends")||R("keyof")||R("typeof")||R("infer")||R("is")||R("as")||R("in"))return l=h,!1;return l=h,!0}let z=/[{}'"`\/]/g,Oe=/[()'"`\/]/g,Pe=/[[\]'"`\/]/g,It=/[<>'"`\/]/g;function ke(p,h){let m=1;l++;let y=p===H?z:p===ee?Oe:p===me?Pe:It;y.lastIndex=l;let w;while((w=y.exec(i))!==null){let v=w.index,x=i.charCodeAt(v);if(x===ne||x===le){l=v,S(x),y.lastIndex=l;continue}if(x===Re){l=v,C(),y.lastIndex=l;continue}if(x===U){if(l=v,T()){y.lastIndex=l;continue}y.lastIndex=v+1;continue}if(x===p)m++;else if(x===h){if(h===de&&v>0&&i.charCodeAt(v-1)===Ee){y.lastIndex=v+1;continue}if(m--,m===0)return l=v+1,l}y.lastIndex=v+1}return l=a,l}function Me(){return l>0&&i.charCodeAt(l-1)===Ee}function ht(){return l+1<a&&i.charCodeAt(l+1)===de}let ae=/[<{};'"`\/\n\r()[\]]/g;function Q(){let p=0,h=0,m=0,y=0,w=i.charCodeAt(l)===H;ae.lastIndex=l;let v;while((v=ae.exec(i))!==null){let x=v.index,P=i.charCodeAt(x);if(P===ne||P===le){l=x,S(P),ae.lastIndex=l;continue}if(P===Re){l=x,C(),ae.lastIndex=l;continue}if(P===U){if(x>0&&i.charCodeAt(x-1)===pe){ae.lastIndex=x+1;continue}if(l=x,T()){ae.lastIndex=l;continue}ae.lastIndex=x+1;continue}if(P===pe){let b=Ts(x);if(b!==null)y=Math.max(0,y+b);ae.lastIndex=x+1;continue}if(P===ee){h++,ae.lastIndex=x+1;continue}if(P===we){h--,ae.lastIndex=x+1;continue}if(P===me){m++,ae.lastIndex=x+1;continue}if(P===Ae){m--,ae.lastIndex=x+1;continue}if(P===H){p++,ae.lastIndex=x+1;continue}if(P===Y){let b=p>0;if(b)p--;if((!b||w)&&p===0&&h===0&&m===0&&y===0){l=x+1;return}ae.lastIndex=x+1;continue}if(P===q&&p===0&&h===0&&m===0&&y===0){l=x+1;return}if((P===se||P===ge)&&p===0&&h===0&&m===0&&y===0){if(l=x,Z())return}ae.lastIndex=x+1}l=a}function Ft(){l++;while(l<a&&(i.charCodeAt(l)===ve||i.charCodeAt(l)===Se))l++;let p=i.indexOf(`
|
|
109
|
+
`,l),h=p===-1?a:p,m=i.indexOf(";",l);if(m!==-1&&m<h){let y=m-1;while(y>=l&&(i.charCodeAt(y)===ve||i.charCodeAt(y)===Se))y--;let w=i.charCodeAt(l),v=i.charCodeAt(y);if(w===H&&v===Y||w===me&&v===Ae||w===ne&&v===ne||w===le&&v===le||w===Re&&v===Re){l=m+1;return}}Q()}function lr(){ke(H,Y);while(l<a&&Ne(i.charCodeAt(l)))l++;if(R("from")){l+=4;while(l<a&&Ne(i.charCodeAt(l)))l++;if(l<a){let p=i.charCodeAt(l);if(p===ne||p===le)S(p)}}while(l<a&&(i.charCodeAt(l)===ve||i.charCodeAt(l)===Se))l++;if(l<a&&i.charCodeAt(l)===q)l++}function vs(){l++;while(l<a&&Ne(i.charCodeAt(l)))l++;if(R("as")){l+=2;while(l<a&&Ne(i.charCodeAt(l)))l++;L();while(l<a&&Ne(i.charCodeAt(l)))l++}if(R("from")){l+=4;while(l<a&&Ne(i.charCodeAt(l)))l++;if(l<a){let p=i.charCodeAt(l);if(p===ne||p===le)S(p)}}while(l<a&&(i.charCodeAt(l)===ve||i.charCodeAt(l)===Se))l++;if(l<a&&i.charCodeAt(l)===q)l++}function Pr(p){let h=p.indexOf("from ");if(h===-1)return;let m=h+5;while(m<p.length&&(p.charCodeAt(m)===32||p.charCodeAt(m)===9))m++;if(m>=p.length)return;let y=p.charCodeAt(m);if(y!==39&&y!==34)return;let w=p.indexOf(p[m],m+1);if(w===-1)return;return p.slice(m+1,w)}function Ye(p){if(!s)return;let h=p-1;while(h>=0&&Ne(i.charCodeAt(h)))h--;if(h<0)return;let m=[],y=!1;while(h>=0){if(h>=1&&i.charCodeAt(h)===U&&i.charCodeAt(h-1)===$e){let x=i.lastIndexOf("/*",h-2);if(x>=0){m.push(i.slice(x,h+1)),y=!0,h=x-1;while(h>=0&&Ne(i.charCodeAt(h)))h--;continue}break}let w=h;while(w>0&&i.charCodeAt(w-1)!==se)w--;let v=g(w,h+1);if(v.startsWith("//")){if(y)break;let x=[v];h=w-1;while(h>=0&&(i.charCodeAt(h)===se||i.charCodeAt(h)===ge))h--;while(h>=0){let P=h;while(P>0&&i.charCodeAt(P-1)!==se)P--;let b=g(P,h+1);if(b.startsWith("//")){x.push(b),h=P-1;while(h>=0&&(i.charCodeAt(h)===se||i.charCodeAt(h)===ge))h--}else if(b===""){h=P-1;while(h>=0&&(i.charCodeAt(h)===se||i.charCodeAt(h)===ge))h--}else break}x.reverse(),m.push(x.join(`
|
|
110
|
+
`));continue}break}if(m.length===0)return;return m.reverse(),m}function oc(p){let h=p,m=!1;while(l<a){let b=i.charCodeAt(l);if(b===q){l++;break}if(b===ne||b===le){S(b),m=!0;while(l<a&&(i.charCodeAt(l)===ve||i.charCodeAt(l)===Se))l++;if(l<a&&i.charCodeAt(l)===q)l++;break}if(b===se&&m)break;l++}let y=g(h,l),w=y.charCodeAt(7)===116&&(y.startsWith("import type ")||y.startsWith("import type{")),v=!1;{let b=6;while(b<y.length&&(y.charCodeAt(b)===ve||y.charCodeAt(b)===Se))b++;if(b<y.length&&y.charCodeAt(b)===116&&y.startsWith("type",b)){b+=4;while(b<y.length&&(y.charCodeAt(b)===ve||y.charCodeAt(b)===Se))b++}if(b<y.length){let A=y.charCodeAt(b);v=A===ne||A===le}}let x="";{let b=y.indexOf("from ");if(b!==-1){let A=b+5;while(A<y.length&&(y.charCodeAt(A)===ve||y.charCodeAt(A)===Se))A++;if(A<y.length){let M=y.charCodeAt(A);if(M===ne||M===le){let W=y.indexOf(String.fromCharCode(M),A+1);if(W!==-1)x=y.slice(A+1,W)}}}else if(v){let A=6;while(A<y.length&&y.charCodeAt(A)!==ne&&y.charCodeAt(A)!==le)A++;if(A<y.length){let M=y.charCodeAt(A),W=y.indexOf(String.fromCharCode(M),A+1);if(W!==-1)x=y.slice(A+1,W)}}}let P=Ye(h);return{kind:"import",name:"",text:y,isExported:!1,isTypeOnly:w,isSideEffect:v,source:x,leadingComments:P,start:h,end:l}}function Vi(){let p=l;return ke(H,Y),i.slice(p,l)}function Ss(p){let h=p.indexOf("(");if(h===-1)return p;let m=p.slice(h);if(m.indexOf("=")===-1)return p;let y=!1;for(let b=0;b<m.length;b++)if(m.charCodeAt(b)===61){let A=b>0?m.charCodeAt(b-1):0,M=b+1<m.length?m.charCodeAt(b+1):0;if(A!==61&&A!==33&&A!==60&&A!==62&&M!==61&&M!==62){y=!0;break}}if(!y)return p;let w=0,v=-1;for(let b=h;b<p.length;b++){let A=p.charCodeAt(b);if(A===40)w++;else if(A===41){if(w--,w===0){v=b;break}}}if(v===-1)return p;let x=p.slice(h,v+1),P=Nt(x);return p.slice(0,h)+P+p.slice(v+1)}function bs(p){let h=p.indexOf("//")!==-1||p.indexOf("/*")!==-1,m=p.split(`
|
|
111
|
+
`),y=[],w=[],v=[],x=!1,P=1/0;for(let M=0;M<m.length;M++){let W=m[M];if(h){if(x){if(W.includes("*/"))x=!1;continue}let B=W.trim();if(B.length===0)continue;let G=B.charCodeAt(0);if(G===U){let xe=B.charCodeAt(1);if(xe===U)continue;if(xe===$e){if(!B.includes("*/"))x=!0;continue}}if(G===$e)continue;let D=E(W);if(D.charCodeAt(D.length-1)===q)D=D.slice(0,-1);D=Ss(D);let N=D.trim();if(!N)continue;y.push(D),w.push(N);let _=0;while(_<D.length&&Ne(D.charCodeAt(_)))_++;if(N!=="{"&&N!=="}"){if(_<P)P=_}v.push(_)}else{let B=W.length;while(B>0&&(W.charCodeAt(B-1)===ve||W.charCodeAt(B-1)===Se||W.charCodeAt(B-1)===ge))B--;if(B===0)continue;let G=B<W.length?W.slice(0,B):W;if(G.charCodeAt(G.length-1)===q)G=G.slice(0,-1);G=Ss(G);let D=G.trim();if(!D)continue;y.push(G),w.push(D);let N=0;while(N<G.length&&Ne(G.charCodeAt(N)))N++;if(D!=="{"&&D!=="}"){if(N<P)P=N}v.push(N)}}if(y.length===0)return"{}";if(P===1/0||P<=2)return y.join(`
|
|
112
|
+
`);let b=P-2,A=Array(y.length);for(let M=0;M<y.length;M++){let W=w[M];if(W==="{"){A[M]=W;continue}let B=v[M];if(B>P)A[M]=y[M];else if(B===P&&(W.charCodeAt(0)===Y||W.charCodeAt(0)===Ae||W.charCodeAt(0)===we))A[M]=y[M];else{let G=Math.max(0,B-b);A[M]=" ".repeat(G)+W}}return A.join(`
|
|
113
|
+
`)}function ct(){if(l>=a||i.charCodeAt(l)!==pe)return"";let p=l;ke(pe,de);let h=i.slice(p,l);if(h.includes(`
|
|
114
|
+
`)){let m="",y=!1;for(let w=0;w<h.length;w++){let v=h.charCodeAt(w);if(v===32||v===9||v===10||v===13){if(!y&&m.length>0)m+=" ",y=!0}else m+=h[w],y=!1}if(m.charCodeAt(1)===32)m=`<${m.slice(2)}`;if(m.charCodeAt(m.length-2)===32)m=`${m.slice(0,-2)}>`;return m}return h}function St(){if(l>=a||i.charCodeAt(l)!==ee)return"()";let p=l;return ke(ee,we),i.slice(p,l)}function Nt(p){let h=p.slice(1,-1).trim();if(!h)return"()";if(p.indexOf(`
|
|
115
|
+
`)===-1&&h.indexOf(":")!==-1&&h.indexOf("{")===-1&&h.indexOf("[")===-1&&h.indexOf("=")===-1&&h.indexOf("@")===-1&&h.indexOf("...")===-1){let b=0,A=0,M=0;for(let W=0;W<h.length;W++){let B=h.charCodeAt(W);if(B===ee||B===pe||B===H)M++;else if(B===we||B===de||B===Y)M--;else if(M===0){if(B===rt)b++;else if(B===it)A++}}if(b>=A+1){let W=!1;for(let B=0;B<Qn.length;B++){let G=Qn[B],D=h.indexOf(G);if(D!==-1){let N=D+G.length;if((D===0||!Je(h.charCodeAt(D-1)))&&(N>=h.length||!Je(h.charCodeAt(N)))){W=!0;break}}}if(!W)return p}}let m=[],y=0,w=0,v=!1,x=0;for(let b=0;b<=h.length;b++){if(b===h.length){m.push(h.slice(y).trim());break}let A=h.charCodeAt(b);if(v){if(A===Ue){b++;continue}if(A===x)v=!1;continue}if(A===U&&b+1<h.length){let M=h.charCodeAt(b+1);if(M===$e){b+=2;while(b+1<h.length&&!(h.charCodeAt(b)===$e&&h.charCodeAt(b+1)===U))b++;b++;continue}if(M===U){while(b<h.length&&h.charCodeAt(b)!==10)b++;continue}}if(A===ne||A===le||A===Re){v=!0,x=A;continue}if(A===ee||A===H||A===me||A===pe)w++;else if(A===we||A===Y||A===Ae||A===de&&!(b>0&&h.charCodeAt(b-1)===Ee))w--;else if(A===it&&w===0)m.push(h.slice(y,b).trim()),y=b+1}let P=[];for(let b of m){if(!b)continue;let A=b.trim();if(A.startsWith("//")||A.startsWith("/*"))continue;let M=b;{let W=!1,B=0,G=0,D=0;for(let N=0;N<M.length-1;N++){let _=M.charCodeAt(N);if(_===se){D=N+1;continue}if(W){if(_===Ue){N++;continue}if(_===B)W=!1;continue}if(_===ne||_===le||_===Re){W=!0,B=_;continue}if(_===H||_===me||_===ee||_===pe){G++;continue}if(_===Y||_===Ae||_===we||_===de){if(G>0)G--;continue}if(_===U&&M.charCodeAt(N+1)===U){if(G===0){M=M.slice(0,N).trimEnd();break}let xe=M.indexOf(`
|
|
116
|
+
`,N);if(xe===-1){M=M.slice(0,D).trimEnd();break}let Bt=M.slice(0,D),mc=M.slice(xe+1);M=`${Bt}${mc}`,N=D-1}}}if(!M.trim())continue;P.push(As(M))}return`(${P.join(", ")})`}function ac(p){if(!p.startsWith("{")&&!p.startsWith("["))return p;let h="",m=0,y=0,w=!1,v=0;while(m<p.length){let x=p.charCodeAt(m);if(w){if(x===Ue&&m+1<p.length){h+=p[m]+p[m+1],m+=2;continue}if(x===v)w=!1;h+=p[m],m++;continue}if(x===U&&m+1<p.length){let P=p.charCodeAt(m+1);if(P===$e){let b=m;m+=2;while(m+1<p.length&&!(p.charCodeAt(m)===$e&&p.charCodeAt(m+1)===U))m++;m=Math.min(m+2,p.length),h+=p.slice(b,m);continue}if(P===U){let b=m;while(m<p.length&&p.charCodeAt(m)!==10)m++;h+=p.slice(b,m);continue}}if(x===ne||x===le||x===Re){w=!0,v=x,h+=p[m],m++;continue}if(x===H||x===me||x===ee)y++;else if(x===Y||x===Ae||x===we)y--;if(y>=1&&x===Ee&&(m+1>=p.length||p.charCodeAt(m+1)!==Ee&&p.charCodeAt(m+1)!==de)){while(h.length>0&&(h[h.length-1]===" "||h[h.length-1]==="\t"||h[h.length-1]===`
|
|
117
|
+
`))h=h.slice(0,-1);m++;let P=0;while(m<p.length){let b=p.charCodeAt(m);if(b===ne||b===le||b===Re){let A=b;m++;while(m<p.length){if(p.charCodeAt(m)===Ue){m+=2;continue}if(p.charCodeAt(m)===A){m++;break}m++}continue}if(b===H||b===me||b===ee)P++;else if(b===Y||b===Ae||b===we){if(P===0)break;P--}else if(b===it&&P===0)break;m++}continue}if(y===1&&x===ft&&m+2<p.length&&p.charCodeAt(m+1)===ft&&p.charCodeAt(m+2)===ft){m+=3;continue}h+=p[m],m++}return h}function As(p){let h=p.trim(),m=h.startsWith("...");if(m)h=h.slice(3).trim();while(h.startsWith("@")){let D=1;while(D<h.length&&Je(h.charCodeAt(D)))D++;if(D<h.length&&h.charCodeAt(D)===ee){let N=1;D++;while(D<h.length&&N>0){if(h.charCodeAt(D)===ee)N++;else if(h.charCodeAt(D)===we)N--;D++}}h=h.slice(D).trim()}let y=!0;while(y){y=!1;for(let D of Qn)if(h.startsWith(D)&&h.length>D.length&&!Je(h.charCodeAt(D.length))){let N=h.slice(D.length).trim();if(N.charCodeAt(0)===rt||N.charCodeAt(0)===Ai&&N.length>1&&N.charCodeAt(1)===rt)break;h=N,y=!0;break}}let w=-1,v=-1,x=0,P=!1,b=0;for(let D=0;D<h.length;D++){let N=h.charCodeAt(D);if(P){if(N===Ue){D++;continue}if(N===b)P=!1;continue}if(N===U&&D+1<h.length){let _=h.charCodeAt(D+1);if(_===$e){D+=2;while(D+1<h.length&&!(h.charCodeAt(D)===$e&&h.charCodeAt(D+1)===U))D++;D++;continue}if(_===U){while(D<h.length&&h.charCodeAt(D)!==10)D++;continue}}if(N===ne||N===le||N===Re){P=!0,b=N;continue}if(N===ee||N===H||N===me||N===pe)x++;else if(N===we||N===Y||N===Ae||N===de&&!(D>0&&h.charCodeAt(D-1)===Ee))x--;else if(x===0){if(N===rt&&w===-1)w=D;else if(N===Ee&&v===-1&&(D===0||h.charCodeAt(D-1)!==Ee)&&(D+1>=h.length||h.charCodeAt(D+1)!==Ee&&h.charCodeAt(D+1)!==de))v=D}}let A,M,W=v!==-1;if(w!==-1&&(v===-1||w<v))if(A=h.slice(0,w).trim(),v!==-1)M=h.slice(w+1,v).trim();else M=h.slice(w+1).trim();else if(v!==-1)A=h.slice(0,v).trim(),M=_i(h.slice(v+1).trim());else A=h,M="unknown";if(A=ac(A),(A.startsWith("{")||A.startsWith("["))&&A.includes(`
|
|
118
|
+
`)){let D=A.replace(/\s*\n\s*/g," ").replace(/\s+/g," ");if(D.length<=40)A=D;else A=A.split(`
|
|
119
|
+
`).map((N)=>{let _=N.trim();if(!_)return"";if(_==="{"||_==="}"||_==="["||_==="]"||_.startsWith("}")||_.startsWith("]"))return _;return` ${_}`}).join(`
|
|
120
|
+
`)}let B=A.endsWith("?")||W;if(A.endsWith("?"))A=A.slice(0,-1).trim();let G=B&&!m?"?":"";if(m)return`...${A}: ${M}`;return`${A}${G}: ${M}`}function xs(p){let h=0;if(h<p.length&&p.charCodeAt(h)===45)h++;if(h>=p.length)return!1;let m=p.charCodeAt(h);if(m<48||m>57)return!1;while(h<p.length&&p.charCodeAt(h)>=48&&p.charCodeAt(h)<=57)h++;if(h<p.length&&p.charCodeAt(h)===46){if(h++,h>=p.length||p.charCodeAt(h)<48||p.charCodeAt(h)>57)return!1;while(h<p.length&&p.charCodeAt(h)>=48&&p.charCodeAt(h)<=57)h++}return h===p.length}function _i(p){let h=p.trim();if(h==="true"||h==="false")return"boolean";if(xs(h))return"number";if(h.startsWith("'")&&h.endsWith("'")||h.startsWith('"')&&h.endsWith('"'))return"string";if(h.startsWith("["))return"unknown[]";if(h.startsWith("{"))return"Record<string, unknown>";return"unknown"}function Hi(p){let h=p.trim();if(h.endsWith("as const"))h=h.slice(0,-8).trim();if(h==="true"||h==="false")return h;if(xs(h))return h;let m=lc(h);if(m!==null)return m;return"unknown"}function lc(p){if(p==="")return null;if(p.charCodeAt(0)===ne||p.charCodeAt(0)===le){if(Ti(p,0,p.charCodeAt(0))===p.length)return p}let h=cc(p,"+");if(h.length>1){let m=!1,y=!0,w=[];for(let v of h){let x=v.trim(),P=x.charCodeAt(0);if((P===ne||P===le)&&Ti(x,0,P)===x.length)m=!0,w.push(fc(x));else y=!1}if(y)return uc(w.join(""));if(m)return"string";return null}if(/^[\d\s()+*/%.\-]+$/.test(p)&&/\d/.test(p)&&/[+*/%\-\s]/.test(p))return"number";return null}function cc(p,h){let m=[],y=0,w="",v=0;while(v<p.length){let x=p.charCodeAt(v);if(x===ne||x===le||x===Re){let P=Ti(p,v,x);w+=p.slice(v,P),v=P;continue}if(x===U&&(p.charCodeAt(v+1)===U||p.charCodeAt(v+1)===42)){if(p.charCodeAt(v+1)===U){let A=p.indexOf(`
|
|
121
|
+
`,v+2),M=A===-1?p.length:A;w+=p.slice(v,M),v=M;continue}let P=p.indexOf("*/",v+2),b=P===-1?p.length:P+2;w+=p.slice(v,b),v=b;continue}if(x===ee||x===me||x===H)y++;else if(x===we||x===Ae||x===Y)y--;if(p[v]===h&&y===0){m.push(w),w="",v++;continue}w+=p[v],v++}return m.push(w),m}function fc(p){return p.slice(1,-1).replace(/\\(.)/g,(h,m)=>{if(m==="n")return`
|
|
122
|
+
`;if(m==="t")return"\t";if(m==="r")return"\r";if(m==="0")return"\x00";return m})}function uc(p){return`'${p.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function kr(p){if(p.endsWith("as const"))return null;let h=0,m=-1;for(let y=0;y<p.length;y++){let w=p.charCodeAt(y);if(w===ne||w===le||w===Re)y=Ti(p,y,w)-1;else if(w===123||w===91||w===40)h++;else if(w===125||w===93||w===41)h--;else if(h===0&&w===32&&y+4<=p.length&&p.substring(y,y+4)===" as ")m=y}if(m===-1)return null;return p.slice(m+4).trim()||null}function cr(){if(d(),l<a&&i.charCodeAt(l)===rt){l++,d();let p=l,h=0;while(l<a){if(T())continue;let m=i.charCodeAt(l);if(m===ee||m===me||m===pe)h++;else if(m===we||m===Ae||m===de&&!Me())h--;else if(m===H)if(h>0)h++;else{let y=g(p,l),w=(v)=>{let x=y.length-v.length;return x>=0&&y.endsWith(v)&&(x===0||!Je(y.charCodeAt(x-1)))};if(y.length===0||y.endsWith("|")||y.endsWith("&")||w("is")||w("extends"))h++;else break}else if(m===Y){if(h===0)break;h--}else if(h===0&&m===q)break;if(h===0&&re())break;l++}return g(p,l)}return""}function bt(p,h,m,y){l+=8,d();let w=l<a&&i.charCodeAt(l)===$e;if(w)l++,d();let v=L();if(!v&&!y)return null;d();let x=ct();d();let P=St();d();let b=cr(),A=b.length>0;if(!b)if(m&&w)b="AsyncGenerator<unknown, void, unknown>";else if(w)b="Generator<unknown, void, unknown>";else if(m)b="Promise<void>";else b="void";d();let M=!1;if(l<a&&i.charCodeAt(l)===H){M=!0;let D=l+1;if(ke(H,Y),!o&&!A&&!w)b=wr(i.slice(D,l-1),m,P)}else if(l<a&&i.charCodeAt(l)===q)l++;let W=Nt(P),B=`${h?y?"export default function ":"export declare function ":"declare function "}${v||(y?"":"default")}${x}${W}: ${b};`,G=Ye(p);if(M)u.add(c.length);return{kind:"function",name:v||"default",text:B,isExported:h,isDefault:y,isAsync:m,isGenerator:w,returnType:b,generics:x||void 0,leadingComments:G,start:p,end:l}}function Wt(p,h,m){l+=h.length,d();let y=[];do{if(d(),l>=a)break;let w=i.charCodeAt(l);if(w===H||w===me)return Q(),y;let v=L();if(!v)return Q(),y;d();let x,P,b=!1;if(l<a&&i.charCodeAt(l)===rt){l++,d();let W=l,B=0;while(l<a){if(T())continue;let G=i.charCodeAt(l);if(G===ee||G===H||G===me||G===pe)B++;else if(G===we||G===Y||G===Ae||G===de&&!Me())B--;else if(B===0&&(G===q||G===it))break;else if(B===0&&G===Ee&&!ht())break;if(B===0&&(Z()||X()))break;l++}x=g(W,l)}if(l<a&&i.charCodeAt(l)===Ee)if(o&&x&&(!s||!Ph(x)))Ft();else{l++,d();let W=l,B=0,G=0,D=0;while(l<a){if(T())continue;let N=i.charCodeAt(l);if(N===ee||N===H||N===me)B++;else if(N===we||N===Y||N===Ae)B--;else if(N===pe&&B===0){let _=Ts(l);if(_!==null)D=Math.max(0,D+_);else if(l+1>=a||i.charCodeAt(l+1)!==Ee)G++}else if(N===de&&B===0&&D===0&&!Me()){if(G>0&&(l+1>=a||i.charCodeAt(l+1)!==Ee))G--}else if(B===0&&G===0&&D===0&&(N===q||N===it))break;if(B===0&&G===0&&D===0&&(Z()||J()))break;l++}if(P=g(W,l),P.endsWith(" as const")||P==="const"){if(b=!0,!x){let N=P.endsWith(" as const")?P.slice(0,-9).trim():P,_=Hi(N);x=_!=="unknown"?_:void 0}}else if(!x){let N=kr(P);if(N)x=N}}if(l<a){let W=i.charCodeAt(l);if(W===it){l++;continue}if(W===q)l++}let A=Ye(p),M=`${m?"export ":""}declare ${h} ${v}: ${x||"unknown"};`;y.push({kind:"variable",name:v,text:M,isExported:m,typeAnnotation:x,value:P,modifiers:b?[h,"const assertion"]:[h],leadingComments:A,start:p,end:l});break}while(l<a);return y}function Ts(p){if(i.charCodeAt(p)!==pe||p+1>=a)return null;let h=i.charCodeAt(p+1);if(h===de)return 1;if(h===U)return-1;if(!Mt(h))return null;let m=p+2;while(m<a){let A=i.charCodeAt(m);if(!Je(A)&&A!==ft&&A!==58&&A!==45)break;m++}let y=i.slice(p+1,m),w=i.charCodeAt(m);if(w>32&&w!==de&&w!==U)return null;let v=0,x=0,P=m;for(;P<a;P++){let A=i.charCodeAt(P);if(x!==0){if(A===Ue)P++;else if(A===x)x=0;continue}if(A===ne||A===le||A===Re)x=A;else if(A===H)v++;else if(A===Y&&v>0)v--;else if(A===de&&v===0)break}if(P>=a)return null;let b=P-1;while(b>p&&i.charCodeAt(b)<=32)b--;if(i.charCodeAt(b)===U)return 0;return i.indexOf(`</${y}`,P+1)===-1?null:1}function ji(p,h){l+=9,d();let m=L();d();let y=ct();d();let w="";if(R("extends")){l+=7,d();let A=l,M=0;while(l<a){if(T())continue;let W=i.charCodeAt(l);if(W===pe)M++;else if(W===de&&!Me())M--;else if(W===H&&M===0)break;l++}w=g(A,l)}d();let v=l<a&&i.charCodeAt(l)===H?Vi():"{}",x=bs(v),P=`${h?"export ":""}declare interface ${m}${y}${w?` extends ${w}`:""} ${x}`,b=Ye(p);return{kind:"interface",name:m,text:P,isExported:h,extends:w||void 0,generics:y||void 0,leadingComments:b,start:p,end:l}}function Ki(p,h){l+=4,d();let m=L();d();let y=ct();if(d(),l<a&&i.charCodeAt(l)===Ee)l++;d();let w=l,v=0;while(l<a){if(T())continue;let A=i.charCodeAt(l);if(A===ee||A===H||A===me||A===pe)v++;else if(A===we||A===Y||A===Ae||A===de&&!Me())v--;else if(v===0&&A===q)break;if(v===0&&(Z()||X()))break;l++}let x=g(w,l);if(l<a&&i.charCodeAt(l)===q)l++;let P=`${h?"export ":""}type ${m}${y} = ${x}`,b=Ye(p);return{kind:"type",name:m,text:P,isExported:h,generics:y||void 0,leadingComments:b,start:p,end:l}}function Lt(p,h,m){l+=4,d();let y=L();d();let w=l;if(l<a&&i.charCodeAt(l)===H)ke(H,Y);let v=g(p,l),x=Ye(p);return{kind:"enum",name:y,text:v,isExported:h,modifiers:m?["const"]:void 0,leadingComments:x,start:p,end:l}}function At(p,h,m,y=!1){l+=5,d();let w=L()||"AnonymousClass";d();let v=ct();d();let x="";if(R("extends")){l+=7,d();let W=l,B=0;while(l<a){if(T())continue;let G=i.charCodeAt(l);if(G===pe)B++;else if(G===de&&!Me())B--;else if(B===0&&(G===H||R("implements")))break;l++}x=g(W,l)}let P;if(R("implements")){l+=10,d();let W=l,B=0;while(l<a){if(T())continue;let D=i.charCodeAt(l);if(D===pe)B++;else if(D===de&&!Me())B--;else if(B===0&&D===H)break;l++}let G=g(W,l);if(G)P=G.split(",").map((D)=>D.trim())}d();let b=Ji(),A=`${h?y?"export default ":"export declare ":"declare "}${m?"abstract ":""}class ${w}${v}${x?` extends ${x}`:""}${P&&P.length>0?` implements ${P.join(", ")}`:""} ${b}`,M=Ye(p);return{kind:"class",name:w,text:A,isExported:h,isDefault:y,extends:x||void 0,implements:P,generics:v||void 0,modifiers:m?["abstract"]:void 0,leadingComments:M,start:p,end:l}}function Ji(){if(l>=a||i.charCodeAt(l)!==H)return"{}";l++;let p=[];while(l<a){if(d(),l>=a)break;if(i.charCodeAt(l)===Y){l++;break}if(i.charCodeAt(l)===q){l++;continue}if(R("static")&&Rs("static")===H){l+=6,d(),ke(H,Y);continue}let h=!1,m=!1,y=!1,w=!1,v=!1,x=!1,P=!1,b=!1,A=!0;while(A){if(d(),R("private")){h=!0,l+=7;continue}if(R("protected")){m=!0,l+=9;continue}if(R("public")){l+=6;continue}if(R("static")){y=!0,l+=6;continue}if(R("abstract")){w=!0,l+=8;continue}if(R("readonly")){v=!0,l+=8;continue}if(R("override")){x=!0,l+=8;continue}if(R("accessor")){P=!0,l+=8;continue}if(R("async")){b=!0,l+=5;continue}if(R("declare")){l+=7;continue}break}if(d(),l>=a||i.charCodeAt(l)===Y)break;if(i.charCodeAt(l)===xi)h=!0;if(h){Yi();continue}let M=" ";if(m)M+="protected ";if(y)M+="static ";if(w)M+="abstract ";if(v)M+="readonly ";if(R("constructor")){l+=11,d();let W=St();if(d(),hc(W,p),l<a&&i.charCodeAt(l)===H)ke(H,Y);else if(l<a&&i.charCodeAt(l)===q)l++;let B=Nt(W);p.push(` constructor${B};`)}else if(R("get"))if(l+=3,d(),l<a&&(Mt(i.charCodeAt(l))||i.charCodeAt(l)===me||i.charCodeAt(l)===xi)){let W=Ui();if(W.startsWith("#")){if(d(),l<a&&i.charCodeAt(l)===ee)St();if(d(),cr(),d(),l<a&&i.charCodeAt(l)===H)ke(H,Y);else if(l<a&&i.charCodeAt(l)===q)l++;continue}d(),St(),d();let B=cr()||"unknown";if(d(),l<a&&i.charCodeAt(l)===H)ke(H,Y);else if(l<a&&i.charCodeAt(l)===q)l++;p.push(`${M}get ${W}(): ${B};`)}else Os("get",M,y,v,b,p);else if(R("set"))if(l+=3,d(),l<a&&(Mt(i.charCodeAt(l))||i.charCodeAt(l)===me||i.charCodeAt(l)===xi)){let W=Ui();if(W.startsWith("#")){if(d(),l<a&&i.charCodeAt(l)===ee)St();if(d(),l<a&&i.charCodeAt(l)===H)ke(H,Y);else if(l<a&&i.charCodeAt(l)===q)l++;continue}d();let B=St();if(d(),l<a&&i.charCodeAt(l)===H)ke(H,Y);else if(l<a&&i.charCodeAt(l)===q)l++;let G=Nt(B);p.push(`${M}set ${W}${G};`)}else Os("set",M,y,v,b,p);else{let W=i.charCodeAt(l)===$e;if(W)l++,d();let B=Ui();if(!B){Yi();continue}Ps(B,M,y,v,W,w,b,p)}}return`{
|
|
123
123
|
${p.join(`
|
|
124
124
|
`)}
|
|
125
|
-
}`}function
|
|
125
|
+
}`}function Ui(){if(l>=a)return"";let p=i.charCodeAt(l);if(p===me){let h=l;return ke(me,Ae),i.slice(h,l)}if(p===xi)return l++,`#${L()}`;return L()}function Rs(p){let h=l+p.length;while(h<a&&Ne(i.charCodeAt(h)))h++;return h<a?i.charCodeAt(h):0}function Yi(){let p=0;while(l<a){if(T())continue;let h=i.charCodeAt(l);if(h===H||h===ee)p++;else if(h===Y||h===we){if(p===0)return;p--}else if(h===q&&p===0){l++;return}if(p===0&&re())return;l++}}function Os(p,h,m,y,w,v){Ps(p,h,m,y,!1,!1,w,v)}function Ps(p,h,m,y,w,v,x,P){if(d(),l>=a)return;let b=i.charCodeAt(l),A=!1;if(b===Ai)A=!0,l++,d();if(l<a&&i.charCodeAt(l)===33)l++,d();let M=l<a?i.charCodeAt(l):0;if(M===ee||M===pe){let W=M===pe?ct():"";d();let B=St();d();let G=cr(),D=G.length>0;if(!G)if(x&&w)G="AsyncGenerator<unknown, void, unknown>";else if(w)G="Generator<unknown, void, unknown>";else if(x)G="Promise<void>";else G="void";if(d(),l<a&&i.charCodeAt(l)===H){let xe=l+1;if(ke(H,Y),!o&&!D&&!w)G=wr(i.slice(xe,l-1),x,B)}else if(l<a&&i.charCodeAt(l)===q)l++;let N=Nt(B),_=A?"?":"";P.push(`${h}${p}${_}${W}${N}: ${G};`)}else if(M===rt||M===Ee||M===q||M===Y||M===se||M===ge){let W="";if(M===rt){l++,d();let D=l,N=0;while(l<a){if(T())continue;let _=i.charCodeAt(l);if(_===ee||_===H||_===me||_===pe)N++;else if(_===we||_===Y||_===Ae||_===de&&!Me()){if(N===0)break;N--}else if(N===0&&(_===q||_===it))break;else if(N===0&&_===Ee&&!ht())break;if(N===0&&re())break;l++}W=g(D,l)}let B="";if(l<a&&i.charCodeAt(l)===Ee)if(o&&W){l++;let D=0;while(l<a){if(T())continue;let N=i.charCodeAt(l);if(N===ee||N===H||N===me)D++;else if(N===we||N===Y||N===Ae){if(D===0&&N===Y)break;D--}else if(D===0&&N===q)break;if(D===0&&re())break;l++}}else{l++,d();let D=l,N=0;while(l<a){if(T())continue;let _=i.charCodeAt(l);if(_===ee||_===H||_===me)N++;else if(_===we||_===Y||_===Ae){if(N===0&&_===Y)break;N--}else if(N===0&&_===q)break;if(N===0&&re())break;l++}B=g(D,l)}if(l<a&&i.charCodeAt(l)===q)l++;if(!W)if(B){let D=kr(B);if(D)W=D;else W=B.endsWith("as const")||m&&y?Hi(B):_i(B)}else W="unknown";let G=A?"?":"";P.push(`${h}${p}${G}: ${W};`)}else Yi()}function hc(p,h){let m=p.slice(1,-1).trim();if(!m)return;let y=[],w=0,v=0,x=!1,P=0;for(let b=0;b<=m.length;b++){if(b===m.length){y.push(m.slice(w).trim());break}let A=m.charCodeAt(b);if(x){if(A===Ue){b++;continue}if(A===P)x=!1;continue}if(A===ne||A===le||A===Re){x=!0,P=A;continue}if(A===ee||A===H||A===me||A===pe)v++;else if(A===we||A===Y||A===Ae||A===de&&!(b>0&&m.charCodeAt(b-1)===Ee))v--;else if(A===it&&v===0)y.push(m.slice(w,b).trim()),w=b+1}for(let b of y){let A=b.startsWith("public ")||b.startsWith("public\t"),M=b.startsWith("protected ")||b.startsWith("protected\t"),W=b.startsWith("private ")||b.startsWith("private\t"),B=b.includes("readonly ");if(!A&&!M&&!W&&!B)continue;if(W)continue;let G=b,D=[];if(A){let xe=6;while(xe<G.length&&Ne(G.charCodeAt(xe)))xe++;G=G.slice(xe),D.push("public")}if(M){let xe=9;while(xe<G.length&&Ne(G.charCodeAt(xe)))xe++;G=G.slice(xe),D.push("protected")}if(B){let xe=G.indexOf("readonly ");if(xe!==-1){let Bt=xe+8;while(Bt<G.length&&Ne(G.charCodeAt(Bt)))Bt++;G=G.slice(0,xe)+G.slice(Bt)}D.push("readonly")}let N=D.length>0?`${D.join(" ")} `:"",_=As(G);h.push(` ${N}${_};`)}}function Zi(p=" "){if(l>=a||i.charCodeAt(l)!==H)return"{}";l++;let h=[];while(l<a){if(d(),l>=a)break;if(i.charCodeAt(l)===Y){l++;break}if(i.charCodeAt(l)===q){l++;continue}let m=!1;if(R("export"))m=!0,l+=6,d();if(R("declare"))l+=7,d();let y=m?"export ":"";if(R("function")||R("async")&&dc("async","function")){let w=!1;if(R("async"))w=!0,l+=5,d();if(l+=8,d(),l<a&&i.charCodeAt(l)===$e)l++,d();let v=L();d();let x=ct();d();let P=St();d();let b=cr();if(!b)b=w?"Promise<void>":"void";if(d(),l<a&&i.charCodeAt(l)===H)ke(H,Y);else if(l<a&&i.charCodeAt(l)===q)l++;let A=Nt(P);h.push(`${p}${y}function ${v}${x}${A}: ${b};`)}else if(R("const")||R("let")||R("var")){let w=R("const")?"const":R("let")?"let":"var";l+=w.length,d();let v=L();if(!v){Q();continue}d();let x="";if(l<a&&i.charCodeAt(l)===rt){l++,d();let b=l,A=0;while(l<a){if(T())continue;let M=i.charCodeAt(l);if(M===ee||M===H||M===me||M===pe)A++;else if(M===we||M===Y||M===Ae||M===de&&!Me())A--;else if(A===0&&(M===q||M===it))break;else if(A===0&&M===Ee&&!ht())break;if(A===0&&Z())break;l++}x=g(b,l)}let P="";if(l<a&&i.charCodeAt(l)===Ee){l++,d();let b=l,A=0;while(l<a){if(T())continue;let M=i.charCodeAt(l);if(M===ee||M===H||M===me||M===pe)A++;else if(M===we||M===Y||M===Ae||M===de&&!Me())A--;else if(A===0&&(M===q||M===it))break;if(A===0&&Z())break;l++}P=g(b,l)}if(l<a&&i.charCodeAt(l)===q)l++;if(!x&&P){let b=kr(P);if(b)x=b;else if(w==="const")x=Hi(P);else x=_i(P)}if(!x)x="unknown";h.push(`${p}${y}${w} ${v}: ${x};`)}else if(R("interface")){l+=9,d();let w=L();d();let v=ct();d();let x="";if(R("extends")){l+=7,d();let b=l,A=0;while(l<a){if(T())continue;let M=i.charCodeAt(l);if(M===pe)A++;else if(M===de&&!Me())A--;else if(M===H&&A===0)break;l++}x=g(b,l)}let P=bs(Vi());h.push(`${p}${y}interface ${w}${v}${x?` extends ${x}`:""} ${P}`)}else if(R("type")){l+=4,d();let w=L();d();let v=ct();if(d(),l<a&&i.charCodeAt(l)===Ee){l++,d();let x=l,P=0;while(l<a){if(T())continue;let A=i.charCodeAt(l);if(A===ee||A===H||A===me||A===pe)P++;else if(A===we||A===Y||A===Ae||A===de&&!Me())P--;else if(P===0&&A===q)break;if(P===0&&Z())break;l++}let b=g(x,l);if(l<a&&i.charCodeAt(l)===q)l++;h.push(`${p}${y}type ${w}${v} = ${b}`)}}else if(R("class")){l+=5,d();let w=L();d();let v=ct();d();let x=l,P=0;while(l<a){if(T())continue;let W=i.charCodeAt(l);if(W===pe)P++;else if(W===de&&!Me())P--;else if(W===H&&P===0)break;l++}let b=g(x,l),A=b?` ${b}`:"",M=Ji();h.push(`${p}${y}class ${w}${v}${A} ${M}`)}else if(R("enum")){l+=4,d();let w=L();d();let v=Vi();h.push(`${p}${y}enum ${w} ${v}`)}else if(R("namespace")||R("module")){let w=R("namespace")?"namespace":"module";l+=w.length,d();let v=L();d();let x=Zi(p);h.push(`${p}${y}${w} ${v} ${x}`)}else if(R("abstract"))if(l+=8,d(),R("class")){l+=5,d();let w=L();d();let v=ct();d();let x=l,P=0;while(l<a){if(T())continue;let W=i.charCodeAt(l);if(W===pe)P++;else if(W===de&&!Me())P--;else if(W===H&&P===0)break;l++}let b=g(x,l),A=b?` ${b}`:"",M=Ji();h.push(`${p}${y}abstract class ${w}${v}${A} ${M}`)}else Q();else if(m&&R("default")){l+=7,d();let w=l;Q();let v=g(w,l);if(v.charCodeAt(v.length-1)===q)v=v.slice(0,-1);if(v)h.push(`${p}export default ${v};`)}else if(!m&&(i.charCodeAt(l)===ne||i.charCodeAt(l)===le||i.charCodeAt(l)===Re))Q();else Q()}if(h.length===0)return"{}";return`{
|
|
126
126
|
${h.join(`
|
|
127
127
|
`)}
|
|
128
|
-
}`}function
|
|
129
|
-
`,t+2);return r===-1?e.length:r+1}if(e[t+1]==="*"){let r=e.indexOf("*/",t+2);return r===-1?e.length:r+2}return t+1}function
|
|
130
|
-
`&&t[i]!=="\r")t[i]=" ";r=n;continue}r++}return t.join("")}function
|
|
131
|
-
`)&&s===0)break;i++}return{kind:"type",start:n.index,end:i,bodyStart:
|
|
132
|
-
`)&&r===0){if(n.trim()!=="")t.push(n.trim());n="",i++;continue}n+=s,i++}if(n.trim()!=="")t.push(n.trim());return t}function
|
|
133
|
-
`,s.index)+1,
|
|
128
|
+
}`}function dc(p,h){let m=l+p.length;while(m<a&&Ne(i.charCodeAt(m)))m++;for(let y=0;y<h.length;y++)if(m+y>=a||i.charCodeAt(m+y)!==h.charCodeAt(y))return!1;return m+h.length>=a||!Je(i.charCodeAt(m+h.length))}function Gt(p,h,m){l+=m.length,d();let y="",w=i.charCodeAt(l);if(w===ne||w===le){let A=l;S(w),y=i.slice(A,l)}else{y=L();while(l<a&&i.charCodeAt(l)===ft)l++,y+=`.${L()}`}d();let v=l<a&&i.charCodeAt(l)===H?Zi():"{}",x=`${h?"export ":""}declare ${m} ${y} ${v}`,P=Ye(p),b=y.startsWith("'")||y.startsWith('"');return{kind:"module",name:y,text:x,isExported:h,source:b?y.slice(1,-1):void 0,leadingComments:P,start:p,end:l}}function ks(p,h){Q();let m=g(h,l);if(m.charCodeAt(m.length-1)===q)m=m.slice(0,-1).trimEnd();if(!m)return;let y=Mt(m.charCodeAt(0));for(let A=1;y&&A<m.length;A++)y=Je(m.charCodeAt(A));let w=Ye(p);if(y){c.push({kind:"export",name:"default",text:`export default ${m};`,isExported:!0,isTypeOnly:!1,leadingComments:w,start:p,end:l});return}let v="__dtsx_default_export__",x=1;while(i.includes(v))v=`__dtsx_default_export_${x++}__`;let P=kr(m)||Te(m,!1),b=P==="unknown"&&Oh(m)?`typeof ${m}`:P;c.push({kind:"variable",name:v,text:`declare const ${v}: ${b};`,isExported:!1,typeAnnotation:b,modifiers:["const"],start:p,end:l}),c.push({kind:"export",name:"default",text:`export default ${v};`,isExported:!0,isTypeOnly:!1,leadingComments:w,start:p,end:l})}while(l<a){if(d(),l>=a)break;let p=l,h=i.charCodeAt(l);if(h===105&&R("import"))c.push(oc(p));else if(h===101&&R("export")){l+=6,d();let m=i.charCodeAt(l);if(m===100&&R("default")){l+=7,d();let y=l,w=i.charCodeAt(l);if(w===102&&R("function")){let v=bt(p,!0,!1,!0);if(v)c.push(v)}else if(w===97&&R("async")&&Rs("async")!==q)if(l+=5,d(),R("function")){let v=bt(p,!0,!0,!0);if(v)c.push(v)}else ks(p,y);else if(w===99&&R("class")){let v=At(p,!0,!1,!0);c.push(v)}else if(w===97&&R("abstract")){if(l+=8,d(),R("class")){let v=At(p,!0,!0,!0);c.push(v)}}else ks(p,y)}else if(m===116&&R("type")){let y=l;if(l+=4,d(),l<a&&i.charCodeAt(l)===H){lr();let w=g(p,l),v=Ye(p);c.push({kind:"export",name:"",text:w,isExported:!0,isTypeOnly:!0,source:Pr(w),leadingComments:v,start:p,end:l})}else if(l<a&&i.charCodeAt(l)===$e){vs();let w=g(p,l);c.push({kind:"export",name:"",text:w,isExported:!0,isTypeOnly:!0,source:Pr(w),start:p,end:l})}else{l=y;let w=Ki(p,!0);c.push(w)}}else if(m===105&&R("interface")){let y=ji(p,!0);c.push(y)}else if(m===102&&R("function")){let y=bt(p,!0,!1,!1);if(y)c.push(y)}else if(m===97&&R("async"))if(l+=5,d(),R("function")){let y=bt(p,!0,!0,!1);if(y)c.push(y)}else Q();else if(m===99)if(R("class")){let y=At(p,!0,!1);c.push(y)}else if(R("const")){let y=l;if(l+=5,d(),R("enum")){l=y+5,d();let w=Lt(p,!0,!0);c.push(w)}else{l=y;let w=Wt(p,"const",!0);for(let v=0;v<w.length;v++)c.push(w[v])}}else Q();else if(m===97&&R("abstract")){if(l+=8,d(),R("class")){let y=At(p,!0,!0);c.push(y)}}else if(m===108&&R("let")){let y=Wt(p,"let",!0);for(let w=0;w<y.length;w++)c.push(y[w])}else if(m===118&&R("var")){let y=Wt(p,"var",!0);for(let w=0;w<y.length;w++)c.push(y[w])}else if(m===101&&R("enum")){let y=Lt(p,!0,!1);c.push(y)}else if(m===100&&R("declare"))l+=7,d(),Ms(p,!0);else if(m===110&&R("namespace")&&F(9)){let y=Gt(p,!0,"namespace");c.push(y)}else if(m===109&&R("module")&&F(6)){let y=Gt(p,!0,"module");c.push(y)}else if(m===H){lr();let y=g(p,l),w=y.includes("export type"),v=Ye(p);c.push({kind:"export",name:"",text:y,isExported:!0,isTypeOnly:w,source:Pr(y),leadingComments:v,start:p,end:l})}else if(m===$e){vs();let y=g(p,l),w=Ye(p);c.push({kind:"export",name:"",text:y,isExported:!0,isTypeOnly:!1,source:Pr(y),leadingComments:w,start:p,end:l})}else{Q();let y=g(p,l);if(y)c.push({kind:"export",name:"",text:y,isExported:!0,start:p,end:l})}}else if(h===100&&R("declare"))l+=7,d(),Ms(p,!1);else if(h===105&&R("interface")){let m=ji(p,!1);f.set(m.name,m)}else if(h===116&&R("type")){let m=Ki(p,!1);f.set(m.name,m),c.push(m)}else if(h===102&&R("function")){let m=bt(p,!1,!1,!1);if(m)f.set(m.name,m);else Q()}else if(h===97)if(R("async")){let m=l;if(l+=5,d(),R("function")){let y=bt(p,!1,!0,!1);if(y)f.set(y.name,y);else l=m,Q()}else l=m,Q()}else if(R("abstract"))if(l+=8,d(),R("class")){let m=At(p,!1,!1);f.set(m.name,m),c.push(m)}else Q();else l++,Q();else if(h===99)if(R("class")){let m=At(p,!1,!1);f.set(m.name,m),c.push(m)}else if(R("const")){let m=l;if(l+=5,d(),R("enum")){l=m+5,d();let y=Lt(p,!1,!0);f.set(y.name,y),c.push(y)}else{l=m;let y=Wt(p,"const",!1);for(let w=0;w<y.length;w++)f.set(y[w].name,y[w])}}else l++,Q();else if(h===101&&R("enum")){let m=Lt(p,!1,!1);f.set(m.name,m),c.push(m)}else if(h===108&&R("let"))Q();else if(h===118&&R("var"))Q();else if(h===109&&R("module")&&F(6)){let m=Gt(p,!1,"module");c.push(m)}else if(h===110&&R("namespace")&&F(9)){let m=Gt(p,!1,"namespace");c.push(m)}else{let m=i.charCodeAt(l);if(m===q)l++;else if(m===ne||m===le){if(S(m),l<a&&i.charCodeAt(l)===q)l++}else if(m===Re){if(C(),l<a&&i.charCodeAt(l)===q)l++}else if(m===Th){if(l++,L(),d(),l<a&&i.charCodeAt(l)===ft)l++,L(),d();if(l<a&&i.charCodeAt(l)===ee)ke(ee,we)}else l++,Q()}}if(f.size>0)kh(c,f);if(u.size>0){let p=new Map;for(let m of c)if(m.kind==="function")p.set(m.name,(p.get(m.name)||0)+1);let h=new Set;for(let[m,y]of p)if(y>1)h.add(m);if(h.size>0){let m=new Set;for(let y of h)for(let w=c.length-1;w>=0;w--)if(c[w].kind==="function"&&c[w].name===y&&u.has(w)){m.add(w);break}if(m.size>0){let y=[...m].sort((w,v)=>v-w);for(let w of y)c.splice(w,1)}}}return c;function Ms(p,h){if(R("function")){let m=bt(p,h,!1,!1);if(m)c.push(m)}else if(R("async")){if(l+=5,d(),R("function")){let m=bt(p,h,!0,!1);if(m)c.push(m)}}else if(R("class")){let m=At(p,h,!1);c.push(m)}else if(R("abstract")){if(l+=8,d(),R("class")){let m=At(p,h,!0);c.push(m)}}else if(R("interface")){let m=ji(p,h);c.push(m)}else if(R("type")){let m=Ki(p,h);c.push(m)}else if(R("enum")){let m=Lt(p,h,!1);c.push(m)}else if(R("const")){let m=l;if(l+=5,d(),R("enum")){l=m+5,d();let y=Lt(p,h,!0);c.push(y)}else if(h){l=m;let y=Wt(p,"const",!0);for(let w=0;w<y.length;w++)c.push(y[w])}else Q()}else if(R("let")||R("var"))if(h){let m=R("let")?"let":"var",y=Wt(p,m,!0);for(let w=0;w<y.length;w++)c.push(y[w])}else Q();else if(R("module")){let m=Gt(p,h,"module");c.push(m)}else if(R("namespace")){let m=Gt(p,h,"namespace");c.push(m)}else if(R("global")){l+=6,d();let m=`declare global ${l<a&&i.charCodeAt(l)===H?Zi():"{}"}`,y=Ye(p);c.push({kind:"module",name:"global",text:m,isExported:!1,leadingComments:y,start:p,end:l})}else Q()}}function Za(e,t){let r=0,n=e.length;while(r<n){let i=e.charCodeAt(r);if(i>=65&&i<=90||i>=97&&i<=122||i===95||i===36||i>127){let s=r;r++;while(r<n){let o=e.charCodeAt(r);if(o>=65&&o<=90||o>=97&&o<=122||o>=48&&o<=57||o===95||o===36||o>127)r++;else break}t.add(e.substring(s,r))}else r++}}function qa(e,t){let r=0;while(r<e.length){let n=e.charCodeAt(r);if(n===ne||n===le||n===Re){let u=n;r++;while(r<e.length)if(e.charCodeAt(r)===Ue)r+=2;else if(e.charCodeAt(r++)===u)break;continue}if(n===U&&e.charCodeAt(r+1)===U){r+=2;while(r<e.length&&e.charCodeAt(r)!==se&&e.charCodeAt(r)!==ge)r++;continue}if(n===U&&e.charCodeAt(r+1)===$e){let u=e.indexOf("*/",r+2);r=u===-1?e.length:u+2;continue}if(!Mt(n)){r++;continue}let i=r++;while(r<e.length&&Je(e.charCodeAt(r)))r++;let s=i-1,o=r;while(s>=0&&Ne(e.charCodeAt(s)))s--;while(o<e.length&&Ne(e.charCodeAt(o)))o++;let a=s>=0?e.charCodeAt(s):0,c=o<e.length?e.charCodeAt(o):0,f=i>=3&&e.slice(i-3,i)==="...";if(c===rt||a===ft&&!f)continue;if(c===ee&&(a===H||a===it))continue;t.add(e.slice(i,r))}}function kh(e,t){let r=new Set,n=new Set;for(let o of e)n.add(o.name);let i=new Set,s=[];for(let o=0;o<e.length;o++){let a=e[o];if(a.kind!=="import"){if(s.push(a.text),Za(a.text,i),typeof a.value==="string")qa(a.value,i)}}for(;;){let o=[];for(let[f,u]of t){if(r.has(f))continue;if(i.has(f)){if(!n.has(f))o.push(u),n.add(f);r.add(f)}}if(o.length===0)break;o.sort((f,u)=>(f.start??1/0)-(u.start??1/0));let a=[],c=0;for(let f=0;f<e.length;f++){let u=e[f].start??1/0;while(c<o.length&&(o[c].start??1/0)<=u)a.push(o[c++]);a.push(e[f])}while(c<o.length)a.push(o[c++]);e.length=0;for(let f=0;f<a.length;f++)e.push(a[f]);for(let f of o)if(f.kind!=="import"){if(s.push(f.text),Za(f.text,i),typeof f.value==="string")qa(f.value,i)}}}var ve=32,Se=9,se=10,ge=13,U=47,$e=42,ne=39,le=34,Re=96,Ue=92,H=123,Y=125,ee=40,we=41,me=91,Ae=93,pe=60,de=62,q=59,rt=58,Ee=61,it=44,ft=46,Ai=63,xi=35,Th=64,Xa=36,Rh=95,Qn;var tl=ce(()=>{zn();Qn=["public","protected","private","readonly","override"]});function il(e){return e.endsWith(".vue")}function Mh(e){let t={script:null,scriptSetup:null},r=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,n;while((n=r.exec(e))!==null){let i=n[1]||"",s=/lang\s*=\s*["']([^"']+)["']/i.exec(i)?.[1]?.toLowerCase()??"js",o={content:n[2]??"",attrs:i,setup:/\bsetup\b/.test(i),lang:s};if(o.setup)t.scriptSetup=o;else t.script=o}return t}function qe(e,t){let r=e[t];t++;while(t<e.length){let n=e[t];if(n==="\\"){t+=2;continue}if(n===r)return t+1;t++}return t}function nt(e,t){t++;let r=0;while(t<e.length){let n=e[t];if(n==="\\"){t+=2;continue}if(n==="`"&&r===0)return t+1;if(n==="$"&&e[t+1]==="{"){r++,t+=2;continue}if(n==="}"){if(r>0)r--;t++;continue}t++}return t}function ut(e,t){if(e[t+1]==="/"){let r=e.indexOf(`
|
|
129
|
+
`,t+2);return r===-1?e.length:r+1}if(e[t+1]==="*"){let r=e.indexOf("*/",t+2);return r===-1?e.length:r+2}return t+1}function ts(e,t){let r=e[t];if(r==='"'||r==="'")return qe(e,t);if(r==="`")return nt(e,t);if(r==="/"&&(e[t+1]==="/"||e[t+1]==="*"))return ut(e,t);return t}function rs(e){let t=e.split(""),r=0;while(r<e.length){let n=ts(e,r);if(n>r){for(let i=r;i<n;i++)if(t[i]!==`
|
|
130
|
+
`&&t[i]!=="\r")t[i]=" ";r=n;continue}r++}return t.join("")}function Ge(e,t,r,n){let i=0,s=t;while(s<e.length){let o=e[s];if(o==='"'||o==="'"){s=qe(e,s);continue}if(o==="`"){s=nt(e,s);continue}if(o==="/"&&(e[s+1]==="/"||e[s+1]==="*")){s=ut(e,s);continue}if(o===r)i++;else if(o===n){if(i--,i===0)return s}s++}return-1}function is(e,t){let r=0,n=t;while(n<e.length){let i=e[n];if(i==='"'||i==="'"){n=qe(e,n);continue}if(i==="`"){n=nt(e,n);continue}if(i==="/"&&(e[n+1]==="/"||e[n+1]==="*")){n=ut(e,n);continue}if(i==="="&&e[n+1]===">"){n+=2;continue}if(i==="<")r++;else if(i===">"){if(r--,r===0)return n}n++}return-1}function nr(e,t=","){let r=[],n=0,i="",s=0;while(s<e.length){let o=e[s];if(o==='"'||o==="'"){let a=qe(e,s);i+=e.slice(s,a),s=a;continue}if(o==="`"){let a=nt(e,s);i+=e.slice(s,a),s=a;continue}if(o==="/"&&(e[s+1]==="/"||e[s+1]==="*")){s=ut(e,s);continue}if(o==="{"||o==="["||o==="("||o==="<")n++;else if(o==="}"||o==="]"||o===")"||o===">")n--;if(o===t&&n===0){r.push(i),i="",s++;continue}i+=o,s++}if(i.trim()!=="")r.push(i);return r}function br(e){let t=e.trim();if(!t.startsWith("{"))return[];let r=Ge(t,0,"{","}");if(r===-1)return[];let n=t.slice(1,r),i=[];for(let s of nr(n)){let o=-1,a=0;for(let u=0;u<s.length;u++){let l=s[u];if(l==='"'||l==="'"){u=qe(s,u)-1;continue}if(l==="`"){u=nt(s,u)-1;continue}if(l==="{"||l==="["||l==="("||l==="<")a++;else if(l==="}"||l==="]"||l===")"||l===">")a--;else if(l===":"&&a===0){o=u;break}}if(o!==-1){i.push({key:vr(s.slice(0,o).trim()),value:s.slice(o+1).trim(),isMethod:!1});continue}let c=/^([A-Za-z_$][\w$]*|['"][^'"]+['"])\s*\(/.exec(s.trim());if(c){i.push({key:vr(c[1]),value:s.trim(),isMethod:!0});continue}let f=s.trim();if(f)i.push({key:vr(f),value:"",isMethod:!1})}return i}function vr(e){if(e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);return e}function Sr(e){return/^[A-Za-z_$][\w$]*$/.test(e)?e:JSON.stringify(e)}function Ar(e,t){let r=new RegExp(`\\b${t}\\b`,"g"),n;while((n=r.exec(e))!==null){let i=n.index+n[0].length;while(i<e.length&&/\s/.test(e[i]))i++;let s=null;if(e[i]==="<"){let c=is(e,i);if(c===-1)return null;s=e.slice(i+1,c).trim(),i=c+1;while(i<e.length&&/\s/.test(e[i]))i++}if(e[i]!=="(")continue;let o=Ge(e,i,"(",")");if(o===-1)return null;let a=nr(e.slice(i+1,o));return{generic:s,arg:a.length>0?a[0].trim():null}}return null}function Dh(e,t){let r=nl(e,t);if(!r)return null;return r.kind==="interface"?e.slice(r.bodyStart,r.end):e.slice(r.bodyStart,r.end).trim()}function nl(e,t){let r=new RegExp(`\\binterface\\s+${t}\\b[^{]*\\{`,"m").exec(e);if(r){let i=r.index+r[0].length-1,s=Ge(e,i,"{","}");if(s!==-1)return{kind:"interface",start:r.index,end:s+1,bodyStart:i}}let n=new RegExp(`\\btype\\s+${t}\\b[^=]*=`,"m").exec(e);if(n){let i=n.index+n[0].length,s=0,o=i;while(i<e.length){let a=e[i];if(a==='"'||a==="'"){i=qe(e,i);continue}if(a==="`"){i=nt(e,i);continue}if(a==="{"||a==="["||a==="("||a==="<")s++;else if(a==="}"||a==="]"||a===")"||a===">")s--;else if((a===";"||a===`
|
|
131
|
+
`)&&s===0)break;i++}return{kind:"type",start:n.index,end:i,bodyStart:o}}return null}function Ih(e){let t=e.search(/\bas\s+PropType\s*</);if(t===-1)return null;let r=e.indexOf("<",t),n=is(e,r);if(n===-1)return null;if(e.slice(n+1).trim()!=="")return null;return e.slice(r+1,n).trim()}function es(e){let t=e.trim(),r=Ih(t);if(r!==null)return{type:r,optional:!0};if(t==="null")return{type:"unknown",optional:!0};if(t.startsWith("[")){let n=Ge(t,0,"[","]");if(n!==-1){let i=nr(t.slice(1,n)).map((s)=>es(s).type).filter((s)=>s!=="unknown");return{type:i.length>0?[...new Set(i)].join(" | "):"unknown",optional:!0}}}if(t.startsWith("{")){let n=br(t),i=n.find((c)=>c.key==="type"),s=n.find((c)=>c.key==="required"),o=i?es(i.value).type:"unknown",a=!(s&&s.value.trim()==="true");return{type:o,optional:a}}if(rl[t])return{type:rl[t],optional:!0};if(/^[A-Za-z_$][\w$.]*$/.test(t))return{type:t,optional:!0};return{type:"unknown",optional:!0}}function ki(e){let t=e.trim();if(t.startsWith("{")){let r=br(t);if(r.length===0)return"{}";return`{ ${r.map((n)=>{if(n.isMethod||n.value==="")return`${Sr(n.key)}?: unknown`;let i=es(n.value);return`${Sr(n.key)}${i.optional?"?":""}: ${i.type}`}).join(", ")} }`}if(t.startsWith("[")){let r=Ge(t,0,"[","]");if(r===-1)return null;let n=nr(t.slice(1,r)).map((i)=>vr(i.trim())).filter((i)=>i!=="");if(n.length===0)return"{}";return`{ ${n.map((i)=>`${Sr(i)}?: unknown`).join(", ")} }`}return null}function Fh(e){let t=e.trim();if(!t.startsWith("["))return null;let r=Ge(t,0,"[","]");if(r===-1)return null;let n=nr(t.slice(1,r)).map((i)=>i.trim());if(n.length===0)return"{}";if(!n.every((i)=>i.startsWith("'")&&i.endsWith("'")||i.startsWith('"')&&i.endsWith('"')))return"string[]";return`[${n.map((i)=>JSON.stringify(vr(i))).join(", ")}]`}function Nh(e){let t=e.trim();if(!t.startsWith("{"))return null;let r=br(t);if(r.length===0)return"{}";return`{ ${r.map((n)=>`${JSON.stringify(n.key)}: (...args: any[]) => void`).join(", ")} }`}function sl(e){return Fh(e)??Nh(e)}function Wh(e){let t=[],r=0,n="",i=0;while(i<e.length){let s=e[i];if(s==='"'||s==="'"){let o=qe(e,i);n+=e.slice(i,o),i=o;continue}if(s==="`"){let o=nt(e,i);n+=e.slice(i,o),i=o;continue}if(s==="/"&&(e[i+1]==="/"||e[i+1]==="*")){let o=ut(e,i);n+=e.slice(i,o),i=o;continue}if(s==="="&&e[i+1]===">"){n+="=>",i+=2;continue}if(s==="{"||s==="["||s==="("||s==="<")r++;else if(s==="}"||s==="]"||s===")"||s===">")r--;if((s===";"||s===","||s===`
|
|
132
|
+
`)&&r===0){if(n.trim()!=="")t.push(n.trim());n="",i++;continue}n+=s,i++}if(n.trim()!=="")t.push(n.trim());return t}function Lh(e){let t=e.trim();if(!t.startsWith("{"))return null;let r=Ge(t,0,"{","}");if(r===-1||t.slice(r+1).trim()!=="")return null;let n=Wh(t.slice(1,r));if(n.length===0)return"{}";let i=[];for(let s of n){let o=/^\(\s*\w+\s*:\s*/.exec(s);if(!o)return null;let a=o[0].length,c=s[a];if(c!=="'"&&c!=='"'&&c!=="`")return null;let f=qe(s,a),u=s.slice(a+1,f-1),l=Ge(s,s.indexOf("(",0),"(",")");if(l===-1)return null;let g=s.slice(a,l),d=nr(g).slice(1),E=s.slice(l+1).trim();if(E.startsWith(":"))E=E.slice(1).trim();if(E==="")E="void";i.push(`${JSON.stringify(u)}: (${d.map((S)=>S.trim()).join(", ")}) => ${E}`)}return`{ ${i.join(", ")} }`}function ns(e){let t=e;for(let r of["defineProps","defineEmits","defineExpose","defineSlots","defineOptions"])t=Gh(t,r);return t}function Gh(e,t){let r=new RegExp(`\\b${t}\\b`,"g"),n=[],i=e,s;while((s=r.exec(e))!==null){let o=e.lastIndexOf(`
|
|
133
|
+
`,s.index)+1,a=e.slice(o,s.index),c=/^\s*(?:(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*(?::[^=]+)?=\s*)?(withDefaults\s*\(\s*)?$/.exec(a);if(!c)continue;let f=s.index+s[0].length;while(f<e.length&&/\s/.test(e[f]))f++;if(e[f]==="<"){let g=is(e,f);if(g===-1)continue;f=g+1;while(f<e.length&&/\s/.test(e[f]))f++}if(e[f]!=="(")continue;let u=Ge(e,f,"(",")");if(u===-1)continue;if(c[1]){let g=o+a.length-c[1].length,d=e.indexOf("(",g);if(d!==-1){let E=Ge(e,d,"(",")");if(E!==-1)u=E}}let l=u+1;while(l<e.length&&e[l]!==`
|
|
134
134
|
`&&/\s|;/.test(e[l]))l++;if(e[l]===`
|
|
135
|
-
`)l++;n.push([
|
|
136
|
-
`,i.index)+1;if(!r.has(s))continue;if(/\bexport\b/.test(e.slice(s,i.index)))continue;let
|
|
135
|
+
`)l++;n.push([o,l])}for(let o=n.length-1;o>=0;o--)i=i.slice(0,n[o][0])+i.slice(n[o][1]);return i}function ss(e){let t=Bh(e);if(t!==-1){let r=/^export\s+default\b/.exec(e.slice(t))?.[0];if(!r)return{options:null,script:e,passthrough:!1};let n=t+r.length;while(n<e.length&&/\s/.test(e[n]))n++;let i=-1,s=-1,o=-1;if(e[n]==="{")i=n,s=Ge(e,n,"{","}"),o=s;else if(e.startsWith("defineComponent",n)){let f=e.indexOf("(",n);if(f!==-1){let u=f+1;while(u<e.length&&/\s/.test(e[u]))u++;if(e[u]==="{")i=u,s=Ge(e,u,"{","}"),o=Ge(e,f,"(",")")}}if(i===-1||s===-1||o===-1)return{options:null,script:e,passthrough:!0};let a=o+1;if(e[a]===";")a++;let c=(e.slice(0,t)+e.slice(a)).trim();return{options:e.slice(i,s+1),script:c,passthrough:!1}}return{options:null,script:e,passthrough:!1}}function Bh(e){let t=0,r=0;while(r<e.length){let n=e[r];if(n==='"'||n==="'"){r=qe(e,r);continue}if(n==="`"){r=nt(e,r);continue}if(n==="/"&&(e[r+1]==="/"||e[r+1]==="*")){r=ut(e,r);continue}if(n==="{"||n==="["||n==="(")t++;else if(n==="}"||n==="]"||n===")")t=Math.max(0,t-1);else if(t===0&&e.startsWith("export",r)){let i=r===0?"":e[r-1],s=e[r+6]??"";if(!/[\w$]/.test(i)&&!/[\w$]/.test(s)){if(/^export\s+default\b/.exec(e.slice(r)))return r}}r++}return-1}function Ri(e,t){let r=br(e).find((n)=>n.key===t);return r&&r.value!==""?r.value:null}function Oi(e,t){let r=_h(e),n=e;for(let i=r.length-1;i>=0;i--){let s=r[i],o=n.slice(0,s.start)+n.slice(s.end);if(Vh(o,s.name))continue;if(new RegExp(`\\btypeof\\s+${s.name}\\b`).test(t))continue;n=o}return n}function Vh(e,t){let r=0;while(r<e.length){let n=e[r];if(n==='"'||n==="'"){r=qe(e,r);continue}if(n==="`"){r=nt(e,r);continue}if(n==="/"&&(e[r+1]==="/"||e[r+1]==="*")){r=ut(e,r);continue}if(/[A-Za-z_$]/.test(n)){let i=r+1;while(i<e.length&&/[\w$]/.test(e[i]))i++;if(e.slice(r,i)===t)return!0;r=i;continue}r++}return!1}function _h(e){let t=[],r=Hh(e),n=/^[ \t]*(const|let|var|(?:async[ \t]+)?function)[ \t]+([A-Za-z_$][\w$]*)[ \t]*(?::[^=\n]+)?=?/gm,i;while((i=n.exec(e))!==null){let s=e.lastIndexOf(`
|
|
136
|
+
`,i.index)+1;if(!r.has(s))continue;if(/\bexport\b/.test(e.slice(s,i.index)))continue;let o=i[1],a=i[2],c=i.index+i[0].length,f=-1;if(o.endsWith("function")){let u=e.indexOf("(",c);if(u===-1)continue;let l=Ge(e,u,"(",")");if(l===-1)continue;c=l+1;while(c<e.length&&/\s/.test(e[c]))c++;if(e[c]===":")while(c<e.length&&e[c]!=="{"&&e[c]!==`
|
|
137
137
|
`)c++;while(c<e.length&&/\s/.test(e[c])&&e[c]!==`
|
|
138
|
-
`)c++;if(e[c]!=="{")continue;let g=
|
|
138
|
+
`)c++;if(e[c]!=="{")continue;let g=Ge(e,c,"{","}");if(g===-1)continue;f=g+1}else{let u=0;while(c<e.length){let l=e[c];if(l==='"'||l==="'"){c=qe(e,c);continue}if(l==="`"){c=nt(e,c);continue}if(l==="/"&&(e[c+1]==="/"||e[c+1]==="*")){c=ut(e,c);continue}if(l==="{"||l==="["||l==="(")u++;else if(l==="}"||l==="]"||l===")")u--;else if(l===";"&&u===0){f=c+1;break}else if(l===`
|
|
139
139
|
`&&u===0){f=c;break}c++}if(f===-1)f=e.length}if(e[f]===`
|
|
140
|
-
`)f++;t.push({name:
|
|
141
|
-
`&&r===0)t.add(n+1);n++}return t}function
|
|
142
|
-
`,n)+1;if(/\bexport\b/.test(e.slice(i,n)))return e;let s=e.slice(0,n)+e.slice(n+r.length);if(new RegExp(`\\b${t}\\b`).test(s))return e;return s}function
|
|
143
|
-
`)
|
|
144
|
-
`){let
|
|
145
|
-
${t.scriptSetup.content}`:t.script.content;if(r=C.script,C.options){let
|
|
146
|
-
`)}var
|
|
147
|
-
defineProps<${r}>()`,null)}function
|
|
148
|
-
`)&&n===0){let c=i+1;if(!al(e.slice(r,c)))t.push([r,c]);r=c}i++}if(r<e.length&&!al(e.slice(r)))t.push([r,e.length]);let s=e;for(let
|
|
149
|
-
`),r=null,n=
|
|
150
|
-
`)}var
|
|
151
|
-
`);return{content:
|
|
152
|
-
`)}`)}t.push("}");break;default:return e.text||""}return t.join(" ")}function
|
|
140
|
+
`)f++;t.push({name:a,start:i.index,end:f})}return t}function Hh(e){let t=new Set([0]),r=0,n=0;while(n<e.length){let i=e[n];if(i==='"'||i==="'"){n=qe(e,n);continue}if(i==="`"){n=nt(e,n);continue}if(i==="/"&&(e[n+1]==="/"||e[n+1]==="*")){n=ut(e,n);continue}if(i==="{"||i==="["||i==="(")r++;else if(i==="}"||i==="]"||i===")")r=Math.max(0,r-1);if(i===`
|
|
141
|
+
`&&r===0)t.add(n+1);n++}return t}function Pi(e,t,r){let n=e.indexOf(r);if(n===-1)return e;let i=e.lastIndexOf(`
|
|
142
|
+
`,n)+1;if(/\bexport\b/.test(e.slice(i,n)))return e;let s=e.slice(0,n)+e.slice(n+r.length);if(new RegExp(`\\b${t}\\b`).test(s))return e;return s}function os(e){let t="",r=0,n=()=>{for(let s=t.length-1;s>=0;s--)if(!/\s/.test(t[s]))return t[s];return""},i=(s)=>{for(let o=s;o<e.length;o++)if(!/\s/.test(e[o]))return e[o];return""};while(r<e.length){let s=e[r];if(s==='"'||s==="'"){let o=qe(e,r);t+=e.slice(r,o),r=o;continue}if(s==="`"){let o=nt(e,r);t+=e.slice(r,o),r=o;continue}if(s==="/"&&e[r+1]==="*"){let o=ut(e,r);t+=e.slice(r,o).replace(/\s*\n\s*/g," "),r=o;continue}if(s==="/"&&e[r+1]==="/"){let o=r+2;while(o<e.length&&e[o]!==`
|
|
143
|
+
`)o++;let a=e.slice(r+2,o).trim();if(a!==""&&!a.includes("*/"))t+=`/* ${a} */`;r=o;continue}if(s===`
|
|
144
|
+
`){let o=n(),a=i(r+1);if(o===""||a===""){r++;continue}let c=jh(t);if(!c&&("{;,(<:=[".includes(o)||"}),]>;|&".includes(a))){if(!t.endsWith(" ")&&!t.endsWith(";"))t+=" "}else if(c){if(!t.endsWith(" "))t+=" "}else{if(t.endsWith(" "))t=t.slice(0,-1);t+="; "}r++;while(r<e.length&&(e[r]===" "||e[r]==="\t"))r++;continue}t+=s,r++}return t}function jh(e){let t=e.length-1;while(t>=0&&/\s/.test(e[t]))t--;if(t<1||e[t]!=="/"||e[t-1]!=="*")return!1;let r=e.lastIndexOf("/*",t);if(r===-1)return!1;for(let n=r-1;n>=0;n--){let i=e[n];if(/\s/.test(i))continue;return"{;,(<:".includes(i)}return!0}function Mi(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=Ar(n,"defineProps");if(!i)continue;if(i.generic){let s=i.generic;if(s.startsWith("{"))return{type:s};if(/^[A-Za-z_$][\w$]*$/.test(s)){for(let o of r){let a=nl(o,s);if(!a)continue;let c=Dh(o,s);if(c===null)continue;return{type:c,inlinedLocal:{name:s,declText:o.slice(a.start,a.end)}}}return{type:s}}return{type:s}}if(i.arg){let s=ki(i.arg);if(s!==null)return{type:s}}}return null}function as(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=Ar(n,"defineEmits");if(!i)continue;if(i.generic)return Lh(i.generic)??i.generic;if(i.arg){let s=sl(i.arg);if(s!==null)return s}}return null}function ls(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=Ar(n,"defineExpose");if(!i||!i.arg||!i.arg.startsWith("{"))continue;let s=br(i.arg);if(s.length===0)return null;return`{ ${s.map((o)=>{if(o.value===""&&/^[A-Za-z_$][\w$]*$/.test(o.key))return`${Sr(o.key)}: typeof ${o.key}`;let a=o.isMethod||/=>|^\s*function\b/.test(o.value);return`${Sr(o.key)}: ${a?"(...args: any[]) => any":"unknown"}`}).join(", ")} }`}return null}function ol(e){let t=Mh(e),r="",n=null,i=null;if(t.script){let C=ss(t.script.content);if(C.passthrough)return t.scriptSetup?`${t.script.content}
|
|
145
|
+
${t.scriptSetup.content}`:t.script.content;if(r=C.script,C.options){let T=Ri(C.options,"props");if(T)n=ki(T);let k=Ri(C.options,"emits");if(k)i=sl(k)}}let s=t.scriptSetup?.content??null,o=s!==null?ns(s):null,a=Mi(s,s!==null?null:r),c=a?.type??n??"{}",f=as(s,null)??i,u=ls(s,null),l=a?.inlinedLocal;if(l){if(r=Pi(r,l.name,l.declText),o!==null)o=Pi(o,l.name,l.declText)}let g=[c,u??"{}"];if(f)g.push("{}","{}","{}","{}","{}",f);let d=os(`DefineComponent<${g.join(", ")}>`),E=[],S=Oi(r,d);if(S.trim()!=="")E.push(S);if(o&&o.trim()!==""){let C=Oi(o,d);if(C.trim()!=="")E.push(C)}return E.push("import type { DefineComponent } from 'vue'"),E.push(`type __DtsxComponentType = ${d}`),E.push("const __dtsx_component__: __DtsxComponentType = null as unknown as __DtsxComponentType"),E.push("export default __dtsx_component__"),E.join(`
|
|
146
|
+
`)}var rl;var cs=ce(()=>{rl={String:"string",Number:"number",Boolean:"boolean",Array:"unknown[]",Object:"Record<string, unknown>",Function:"(...args: any[]) => any",Symbol:"symbol",Promise:"Promise<unknown>",Date:"Date",BigInt:"bigint"}});function ll(e){return e.endsWith(".stx")}function Kh(e){let t=[],r=/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi,n;while((n=r.exec(e))!==null){let i=n[1]??"",s=/\blang\s*=\s*["']([^"']+)["']/i.exec(i)?.[1]?.toLowerCase()??(/\b(?:type\s*=\s*["'](?:text\/)?typescript["']|typescript)\b/i.test(i)?"ts":"js"),o=/\bserver\b/i.test(i)?"server":/\bclient\b/i.test(i)?"client":"universal";t.push({content:n[2]??"",kind:"script",attrs:i,context:o,lang:s,start:n.index})}return t}function Jh(e){let t=[],r=/^[ \t]*@ts[ \t]*(?:\r?\n|$)/gm,n;while((n=r.exec(e))!==null){let i=r.lastIndex,s=/^[ \t]*@endts[ \t]*(?:\r?\n|$)/gm;s.lastIndex=i;let o=s.exec(e),a=o?.index??e.length;if(t.push({content:e.slice(i,a),kind:"ts",attrs:"",context:"universal",lang:"ts",start:n.index}),!o)break;r.lastIndex=s.lastIndex}return t}function Uh(e){return[...Kh(e),...Jh(e)].sort((t,r)=>t.start-r.start)}function Yh(e){if(e.kind==="ts"||e.context!=="universal"||e.lang==="ts")return!0;return/\b(?:defineProps|defineEmits|defineExpose|defineSlots)\b|\bexport\s|\b(?:interface|type)\s+[A-Za-z_$]/.test(e.content)}function Zh(e){let t=/(?:\$?props)\s+as\s+/g,r;while((r=t.exec(e))!==null){let n=t.lastIndex;while(n<e.length&&/\s/.test(e[n]))n++;if(e[n]==="{"){let o=Ge(e,n,"{","}");if(o!==-1)return e.slice(n,o+1).trim();continue}let i=/^[A-Za-z_$][\w$]*/.exec(e.slice(n))?.[0];if(!i)continue;let s=n+i.length;while(s<e.length&&/\s/.test(e[s]))s++;if(e[s]==="<"){let o=Ge(e,s,"<",">");if(o!==-1)s=o+1}return e.slice(n,s).trim()}return null}function qh(e){return/\b(?:const|let|var)\s+\$?props\s*:\s*([^=;\n]+)/.exec(e)?.[1]?.trim()??null}function Xh(e){let t=/^\s*(?:\|\||\?\?)\s*([^;\n]+)/.exec(e)?.[1]?.trim();if(/^['"`]/.test(t??""))return"string";if(/^(?:true|false)\b/.test(t??""))return"boolean";if(/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)\b/.test(t??""))return"number";if(/^\[/.test(t??""))return"unknown[]";if(/^\{/.test(t??""))return"Record<string, unknown>";if(/^\s*(?:===?|!==?)\s*(?:true|false)\b/.test(e))return"boolean";return"unknown"}function zh(e,t){if(!e||e==="unknown")return t;if(t==="unknown"||e===t)return e;return[...new Set([...e.split(" | "),...t.split(" | ")])].join(" | ")}function Qh(e){let t=rs(e),r=new Map,n=/\$props(?:\.([A-Za-z_$][\w$]*)|\[\s*(['"])([^'"\n]+)\2\s*\])/g,i;while((i=n.exec(e))!==null){if(t.slice(i.index,i.index+6)!=="$props")continue;let s=i[1]??i[3],o=Xh(e.slice(n.lastIndex));r.set(s,zh(r.get(s),o))}if(r.size===0)return null;return{type:`{ ${[...r].map(([s,o])=>`${/^[A-Za-z_$][\w$]*$/.test(s)?s:JSON.stringify(s)}?: ${o}`).join(", ")} }`}}function ed(e){let t=Mi(e,null);if(t)return t;let r=Zh(e)??qh(e);if(!r)return Qh(e);if(/^[A-Za-z_$][\w$]*$/.test(r)){let n=r.replace(/[$]/g,"\\$&");if(new RegExp(`\\bexport\\s+(?:declare\\s+)?(?:interface|type)\\s+${n}\\b`).test(e))return{type:r}}return Mi(`${e}
|
|
147
|
+
defineProps<${r}>()`,null)}function td(e){return ns(e)}function al(e){let t=rs(e).trimStart();if(t==="")return!0;return/^(?:import\b|export\b|declare\b|interface\b|type\b|(?:export\s+)?namespace\b|(?:export\s+)?module\b|(?:abstract\s+)?class\b|const\b|let\b|var\b|(?:async\s+)?function\b)/.test(t)}function rd(e){let t=[],r=0,n=0,i=0;while(i<e.length){let o=e[i],a=ts(e,i);if(a>i){i=a;continue}if(o==="{"||o==="["||o==="(")n++;else if(o==="}"||o==="]"||o===")")n=Math.max(0,n-1);if((o===";"||o===`
|
|
148
|
+
`)&&n===0){let c=i+1;if(!al(e.slice(r,c)))t.push([r,c]);r=c}i++}if(r<e.length&&!al(e.slice(r)))t.push([r,e.length]);let s=e;for(let o=t.length-1;o>=0;o--)s=s.slice(0,t[o][0])+s.slice(t[o][1]);return s}function cl(e){let t=Uh(e).filter(Yh).map((S)=>S.content).join(`
|
|
149
|
+
`),r=null,n=ss(t);if(n.passthrough)return t;if(t=n.script,n.options){let S=Ri(n.options,"props");if(S)r=ki(S)}let i=t,s=td(t),o=ed(i),a=o?.type??r??"{}",c=as(i,null),f=ls(i,null),u=Ar(i,"defineSlots")?.generic??null,l=o?.inlinedLocal;if(l)s=Pi(s,l.name,l.declText);let g=`DefineComponent<${a}>`,d=[];if(c)d.push(`readonly __stxEmits?: ${c}`);if(u)d.push(`readonly __stxSlots?: ${u}`);if(f)d.push(`readonly __stxExposed?: ${f}`);if(d.length>0)g+=` & { ${d.join(", ")} }`;g=os(g),s=rd(Oi(s,g));let E=["import type { DefineComponent } from '@stacksjs/stx'",`type __DtsxStxComponentType = ${g}`,"const __dtsx_component__: __DtsxStxComponentType = null as unknown as __DtsxStxComponentType","export default __dtsx_component__"];if(s.trim()!=="")E.push(s);return E.join(`
|
|
150
|
+
`)}var fl=ce(()=>{cs()});function hl(e,t,r=!0,n=!1){if(il(t))e=ol(e);else if(ll(t))e=cl(e);let i=fr(e),s=`${t}:${r?1:0}:${n?1:0}`,o=sr.get(s);if(o&&o.contentHash===i)return o.lastAccess=++ul,o.declarations;let a=n?za(e,t,r):Qa(e,t,r);if(sr.set(s,{declarations:a,contentHash:i,lastAccess:++ul}),sr.size>id){let c=Math.max(1,Math.ceil(sr.size*0.1)),f=[];for(let[u,l]of sr)f.push([u,l.lastAccess]);f.sort((u,l)=>u[1]-l[1]);for(let u=0;u<c&&u<f.length;u++)sr.delete(f[u][0])}return a}var id=100,ul=0,sr;var dl=ce(()=>{tl();qi();fl();cs();sr=new Map});function Di(e,t,r=!0,n=!1){return hl(e,t,r,n)}var fs=ce(()=>{dl()});import{dirname as xy,relative as nd,resolve as Ty}from"path";async function ml(e,t,r){let n=new Map,i=[],s=new Set,o=0,a=0,c=0,f=[];for(let k of e){let O=t.get(k);if(!O)continue;f.push({file:k,decls:Di(O,k,r.keepComments)})}for(let{file:k,decls:O}of f){o+=O.length;for(let I of O)if(I.kind==="import"){a++;let V=I.source||"";if(V.startsWith("."))continue;if(!n.has(V))n.set(V,{source:V,specifiers:new Map,isTypeOnly:I.isTypeOnly||!1,isSideEffect:I.isSideEffect||!1});let L=n.get(V);if(I.specifiers)for(let R of I.specifiers){let F=R.alias||R.name;if(!L.specifiers.has(F))L.specifiers.set(F,{name:R.name,alias:R.alias,isType:R.isType||!1})}if(!I.isTypeOnly)L.isTypeOnly=!1}else if(I.isExported||I.kind==="export"){if(c++,I.kind==="export"&&I.source&&(I.source.startsWith(".")||I.source.startsWith("/")))continue;if(I.name&&s.has(I.name))continue;if(I.name)s.add(I.name);i.push({declaration:I,file:k})}}let u=[];u.push("/**"),u.push(" * Bundled TypeScript declarations"),u.push(` * Generated from ${e.length} source files`),u.push(" */"),u.push("");let l=r.importOrder||["bun"],g=Array.from(n.values()),d=Array(g.length);for(let k=0;k<g.length;k++){let O=g[k].source,I=l.length;for(let V=0;V<l.length;V++)if(O.startsWith(l[V])){I=V;break}d[k]=I}let E=g.map((k,O)=>O);E.sort((k,O)=>{let I=d[k],V=d[O];if(I!==V)return I-V;return g[k].source.localeCompare(g[O].source)});let S=E.map((k)=>g[k]);for(let k of S)if(k.isSideEffect)u.push(`import '${k.source}';`);else if(k.specifiers.size>0){let O=Array.from(k.specifiers.values()).map((V)=>{let L=V.isType?"type ":"";return V.alias?`${L}${V.name} as ${V.alias}`:`${L}${V.name}`}),I=k.isTypeOnly?"type ":"";u.push(`import ${I}{ ${O.join(", ")} } from '${k.source}';`)}if(S.length>0)u.push("");let C=new Map;for(let{declaration:k,file:O}of i){if(!C.has(O))C.set(O,[]);C.get(O).push(k)}for(let[k,O]of C){let I=nd(r.cwd,k);u.push(`// From: ${I}`);for(let V of O){if(r.keepComments&&V.leadingComments)for(let L of V.leadingComments)u.push(L);u.push(pl(V))}u.push("")}let T=u.join(`
|
|
151
|
+
`);return{content:T,files:e,declarationCount:o,importCount:a,exportCount:c,size:Buffer.byteLength(T,"utf8"),warnings:[]}}function pl(e){if(e.text){let r=e.text.trim();if(e.isExported&&!r.startsWith("export"))r=`export ${r}`;if(!r.endsWith(";")&&!r.endsWith("}"))r+=";";return r}let t=[];if(e.isExported)t.push("export");if(e.isDefault)t.push("default");switch(e.kind){case"function":if(t.push("declare function"),t.push(e.name),e.generics)t.push(e.generics);if(t.push(`(${sd(e.parameters)})`),e.returnType)t.push(`: ${e.returnType}`);break;case"variable":if(t.push("declare const"),t.push(e.name),e.typeAnnotation)t.push(`: ${e.typeAnnotation}`);break;case"interface":if(t.push("interface"),t.push(e.name),e.generics)t.push(e.generics);if(e.extends)t.push(`extends ${e.extends}`);if(t.push("{"),e.members)for(let r of e.members)t.push(` ${r.name}${r.typeAnnotation?`: ${r.typeAnnotation}`:""};`);t.push("}");break;case"type":if(t.push("type"),t.push(e.name),e.generics)t.push(e.generics);t.push("="),t.push(e.typeAnnotation||"unknown");break;case"class":if(t.push("declare class"),t.push(e.name),e.generics)t.push(e.generics);if(e.extends)t.push(`extends ${e.extends}`);if(e.implements&&e.implements.length>0)t.push(`implements ${e.implements.join(", ")}`);if(t.push("{"),e.members)for(let r of e.members)t.push(` ${pl(r)}`);t.push("}");break;case"enum":if(t.push("declare enum"),t.push(e.name),t.push("{"),e.members){let r=e.members.map((n)=>n.value!==void 0?`${n.name} = ${n.value}`:n.name);t.push(` ${r.join(`,
|
|
152
|
+
`)}`)}t.push("}");break;default:return e.text||""}return t.join(" ")}function sd(e){if(!e||e.length===0)return"";return e.map((t)=>{let r="";if(t.rest)r+="...";if(r+=t.name,t.optional)r+="?";if(t.type)r+=`: ${t.type}`;if(t.defaultValue)r+=` = ${t.defaultValue}`;return r}).join(", ")}var gl=ce(()=>{fs()});async function od(){if(Ii!==null)return Ii;try{return Rt=await import("prettier"),Ii=!0,!0}catch{return Ii=!1,!1}}async function ad(e,t){if(!Rt)return null;try{if(t&&Rt.resolveConfig){let r=await Rt.resolveConfig(t);if(r)return r}if(e&&Rt.resolveConfig){let r=await Rt.resolveConfig(e);if(r)return r}return null}catch{return null}}async function ld(e,t){if(!Rt)throw Error("Prettier is not available");let r={...t,parser:t.parser||"typescript"};return Rt.format(e,r)}function cd(e,t={}){let{indentSize:r=2,useTabs:n=!1,maxLineWidth:i=100,trailingNewline:s=!0,normalizeWhitespace:o=!0,sortImports:a=!0,groupImports:c=!0}=t,f=e,u=n?"\t":" ".repeat(r);if(f.indexOf(`\r
|
|
153
153
|
`)!==-1)f=f.replace(/\r\n/g,`
|
|
154
|
-
`);if(
|
|
154
|
+
`);if(o){if(/[ \t]\n/.test(f)||/[ \t]$/.test(f))f=f.replace(/[ \t]+$/gm,"");if(f.indexOf(`
|
|
155
155
|
|
|
156
156
|
|
|
157
157
|
`)!==-1)f=f.replace(/\n{3,}/g,`
|
|
158
158
|
|
|
159
|
-
`);f=
|
|
159
|
+
`);f=fd(f,u)}if(a||c)f=ud(f,{sort:a,group:c});if(i>0)f=dd(f,i,u);if(s&&!f.endsWith(`
|
|
160
160
|
`))f+=`
|
|
161
|
-
`;return f}function
|
|
162
|
-
`),n=[];for(let i of r){let s=i.match(/^(\s*)(.*)$/);if(!s){n.push(i);continue}let[,a
|
|
163
|
-
`)}function
|
|
164
|
-
`),n=[],i=[],s=!1,
|
|
165
|
-
`)}function
|
|
166
|
-
`),i=[];for(let s of n){if(s.length<=t){i.push(s);continue}if(s.trimStart().startsWith("import ")){i.push(s);continue}let
|
|
167
|
-
`)}function
|
|
168
|
-
`),s=e.location.line-1;if(s>=0&&s<i.length){let
|
|
169
|
-
`)}var
|
|
161
|
+
`;return f}function fd(e,t){let r=e.split(`
|
|
162
|
+
`),n=[];for(let i of r){let s=i.match(/^(\s*)(.*)$/);if(!s){n.push(i);continue}let[,o,a]=s;if(!a){n.push("");continue}let c=o.replace(/\t/g," ").length,f=Math.floor(c/2);n.push(t.repeat(f)+a)}return n.join(`
|
|
163
|
+
`)}function ud(e,t){let r=e.split(`
|
|
164
|
+
`),n=[],i=[],s=!1,o=0;for(let c=0;c<r.length;c++){let f=r[c],u=f.match(/^(import\s+(?:type\s+)?.*from\s+['"])([^'"]+)(['"].*)$/);if(u){s=!0,o=c;let l=u[1];n.push({line:f,source:u[2],isType:l.startsWith("import type ")||l.startsWith("import type\t")})}else if(s&&f.trim()==="")continue;else{if(s)s=!1;i.push(f)}}if(n.length===0)return e;if(t.sort)n.sort((c,f)=>{if(c.isType!==f.isType)return c.isType?1:-1;return hd(c.source,f.source)});let a;if(t.group){let c=[],f=[],u=[],l=[],g=[];for(let d=0;d<n.length;d++){let E=n[d],S=E.source;if(S.charCodeAt(0)===46)g.push(E);else if(S.startsWith("node:"))c.push(E);else if(S.charCodeAt(0)===64)l.push(E);else if(S.includes("/"))u.push(E);else f.push(E)}a=[...c.map((d)=>d.line),...c.length>0&&f.length>0?[""]:[],...f.map((d)=>d.line),...(c.length>0||f.length>0)&&u.length>0?[""]:[],...u.map((d)=>d.line),...l.length>0&&(c.length>0||f.length>0||u.length>0)?[""]:[],...l.map((d)=>d.line),...g.length>0?[""]:[],...g.map((d)=>d.line)]}else a=n.map((c)=>c.line);return[...a,"",...i].join(`
|
|
165
|
+
`)}function hd(e,t){let r=e.startsWith("node:"),n=t.startsWith("node:");if(r!==n)return r?-1:1;let i=e.startsWith("."),s=t.startsWith(".");if(i!==s)return i?1:-1;return e.localeCompare(t)}function dd(e,t,r){let n=e.split(`
|
|
166
|
+
`),i=[];for(let s of n){if(s.length<=t){i.push(s);continue}if(s.trimStart().startsWith("import ")){i.push(s);continue}let o=s.match(/^(\s*)/)?.[1]||"",a=o+r;if(s.includes("{")&&s.includes("}")){let c=md(s,t,o,a);i.push(...c);continue}if(s.includes(" | ")){let c=pd(s,t,o,a);i.push(...c);continue}i.push(s)}return i.join(`
|
|
167
|
+
`)}function md(e,t,r,n){let i=e.match(/^(\s*)(.*?)(\{)(.+)(\}.*)$/);if(!i)return[e];let[,,s,o,a,c]=i,f=a.split(/;\s*|,\s*/).filter((u)=>u.trim());if(f.length<=1)return[e];return[`${r}${s}${o}`,...f.map((u)=>`${n}${u.trim()};`),`${r}${c.trim()}`]}function pd(e,t,r,n){let i=e.match(/^(\s*)(.*?=\s*)(.+)$/);if(!i)return[e];let[,,s,o]=i,a=o.split(/\s*\|\s*/).filter((c)=>c.trim());if(a.length<=2)return[e];return[`${r}${s}`,...a.map((c,f)=>`${n}${f>0?"| ":" "}${c.trim()}`)]}async function yl(e,t={},r){let n=[];if(t.usePrettier!==!1){if(await od())try{let i={...await ad(t.prettierConfigPath,r),...t.prettierOptions,parser:"typescript"};return{content:await ld(e,i),usedPrettier:!0}}catch(i){n.push(`Prettier formatting failed: ${i}. Using built-in formatter.`)}else if(t.usePrettier===!0)n.push("Prettier requested but not available. Using built-in formatter.")}return{content:cd(e,t.builtIn),usedPrettier:!1,warnings:n.length>0?n:void 0}}var Ii=null,Rt=null;var Cl=()=>{};function wl(e,t,r){let n={file:t,message:"Unknown error",code:xr.UNKNOWN_ERROR};if(e instanceof Error){n.message=e.message,n.stack=e.stack;let i=e.message.match(/\((\d+),(\d+)\)/);if(i)n.location={line:Number.parseInt(i[1],10),column:Number.parseInt(i[2],10)};if(e.message.includes("Cannot find")||e.message.includes("not found"))n.code=xr.FILE_NOT_FOUND,n.suggestion="Check that the file path is correct and the file exists.";else if(e.message.includes("syntax")||e.message.includes("Unexpected token"))n.code=xr.SYNTAX_ERROR,n.suggestion="Check for syntax errors in your TypeScript code.";else if(e.message.includes("type")&&e.message.includes("cannot"))n.code=xr.TYPE_INFERENCE_ERROR,n.suggestion="Add explicit type annotations to help with type inference.";else if(e.message.includes("parse")||e.message.includes("Parse"))n.code=xr.PARSE_ERROR,n.suggestion="The file contains invalid TypeScript syntax."}else if(typeof e==="string")n.message=e;return n}function $l(e,t){let r=[],n=e.file;if(e.location)n+=`:${e.location.line}:${e.location.column}`;if(e.code)n+=` [${e.code}]`;if(r.push(n),r.push(` Error: ${e.message}`),t&&e.location){r.push("");let i=t.split(`
|
|
168
|
+
`),s=e.location.line-1;if(s>=0&&s<i.length){let o=Math.max(0,s-1),a=Math.min(i.length-1,s+1);for(let c=o;c<=a;c++){let f=(c+1).toString().padStart(4," "),u=c===s?">":" ";if(r.push(` ${u} ${f} | ${i[c]}`),c===s&&e.location.column>0){let l=" ".repeat(10+e.location.column-1);r.push(` ${l}^`)}}}}if(e.suggestion)r.push(""),r.push(` Suggestion: ${e.suggestion}`);return r.join(`
|
|
169
|
+
`)}var xr;var El=ce(()=>{xr={PARSE_ERROR:"PARSE_ERROR",SYNTAX_ERROR:"SYNTAX_ERROR",FILE_NOT_FOUND:"FILE_NOT_FOUND",FILE_READ_ERROR:"FILE_READ_ERROR",FILE_WRITE_ERROR:"FILE_WRITE_ERROR",TYPE_INFERENCE_ERROR:"TYPE_INFERENCE_ERROR",UNRESOLVED_TYPE:"UNRESOLVED_TYPE",EXTRACTION_ERROR:"EXTRACTION_ERROR",PROCESSING_ERROR:"PROCESSING_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",INVALID_DECLARATION:"INVALID_DECLARATION",CONFIG_ERROR:"CONFIG_ERROR",INVALID_ENTRYPOINT:"INVALID_ENTRYPOINT",CIRCULAR_DEPENDENCY:"CIRCULAR_DEPENDENCY",TIMEOUT_ERROR:"TIMEOUT_ERROR",NOT_SUPPORTED:"NOT_SUPPORTED",UNKNOWN_ERROR:"UNKNOWN_ERROR"}});function bl(e,t={}){let{lineEnding:r="lf",trailingNewline:n=!0,maxBlankLines:i=1,trimTrailingWhitespace:s=!0,normalizeIndentation:o=!0,indent:a={style:"spaces",size:2},declarationOrder:c,importGrouping:f,preserveComments:u=!0,insertFinalNewline:l=!0}=t,g=e;if(g=Cd(g,r),f?.enabled!==!1)g=Sd(g,f||{});if(c)g=bd(g,c);if(s)g=wd(g);if(g=$d(g,i),o)g=vd(g,a);if(n||l)g=Ed(g);return g}function Cd(e,t){let r=e;if(e.indexOf("\r")!==-1){if(e.indexOf(`\r
|
|
170
170
|
`)!==-1)r=r.replace(/\r\n/g,`
|
|
171
171
|
`);if(r.indexOf("\r")!==-1)r=r.replace(/\r/g,`
|
|
172
172
|
`)}if(t==="crlf")r=r.replace(/\n/g,`\r
|
|
173
|
-
`);return r}function
|
|
173
|
+
`);return r}function wd(e){return e.split(`
|
|
174
174
|
`).map((t)=>t.replace(/[\t ]+$/,"")).join(`
|
|
175
|
-
`)}function
|
|
176
|
-
`.repeat(t+1))}function
|
|
177
|
-
`}function
|
|
178
|
-
`),
|
|
179
|
-
`)}function
|
|
180
|
-
`),
|
|
181
|
-
`)}function
|
|
182
|
-
`),
|
|
183
|
-
`)}function
|
|
175
|
+
`)}function $d(e,t){let r=new RegExp(`\\n{${t+2},}`,"g");return e.replace(r,`
|
|
176
|
+
`.repeat(t+1))}function Ed(e){return`${e.replace(/\s+$/,"")}
|
|
177
|
+
`}function vd(e,t){let{style:r="spaces",size:n=2}=t,i=r==="tabs"?"\t":" ".repeat(n),s=e.split(`
|
|
178
|
+
`),o=[];for(let a of s){let c=a.match(/^([\t ]*)(.*)$/);if(!c){o.push(a);continue}let[,f,u]=c;if(!u){o.push("");continue}let l=f.replace(/\t/g," "),g=Math.floor(l.length/2);o.push(i.repeat(g)+u)}return o.join(`
|
|
179
|
+
`)}function Sd(e,t){let{groups:r=yd,separateGroups:n=!0,alphabetize:i=!0}=t,s=e.split(`
|
|
180
|
+
`),o=[],a=[],c=-1;for(let E=0;E<s.length;E++){let S=s[E],C=vl(S);if(C)o.push({line:S,source:C.source,group:C.group,isType:C.isType}),c=E;else if(o.length>0&&S.trim()==="")continue;else if(o.length>0||S.trim()!==""){if(o.length===0||E>c+1)a.push(S)}}if(o.length===0)return e;let f=new Map;for(let E of r)f.set(E,[]);for(let E of o)(f.get(E.group)||f.get("external")||[]).push(E);if(i)for(let[,E]of f)E.sort((S,C)=>{if(S.isType!==C.isType)return S.isType?1:-1;return S.source.localeCompare(C.source)});let u=[],l=null;for(let E of r){let S=f.get(E)||[];if(S.length===0)continue;if(n&&l!==null)u.push("");for(let C of S)u.push(C.line);l=E}let g=s.slice(0,s.findIndex((E)=>vl(E)!==null)),d=a;while(d.length>0&&d[0].trim()==="")d.shift();return[...g,...u,"",...d].join(`
|
|
181
|
+
`)}function vl(e){let t=e.trim(),r=t.match(/^import\s+(type\s+)?.*from\s+['"]([^'"]+)['"]/);if(!r){let s=t.match(/^import\s+['"]([^'"]+)['"]/);if(s)return{source:s[1],group:Sl(s[1]),isType:!1};return null}let n=!!r[1],i=r[2];return{source:i,group:n?"type":Sl(i),isType:n}}function Sl(e){if(e.startsWith("node:"))return"builtin";let t=["assert","buffer","child_process","cluster","crypto","dgram","dns","events","fs","http","https","net","os","path","querystring","readline","stream","url","util","zlib"];if(t.includes(e)||t.includes(e.split("/")[0]))return"builtin";if(e==="."||e==="./index"||e==="./index.js"||e==="./index.ts")return"index";if(e.startsWith("./"))return"sibling";if(e.startsWith("../"))return"parent";if(e.startsWith("@/")||e.startsWith("~/")||e.startsWith("#"))return"internal";if(e.startsWith("@"))return"scoped";return"external"}function bd(e,t){let{kinds:r=gd,alphabetize:n=!1,groupExports:i=!0}=t,s=e.split(`
|
|
182
|
+
`),o=[],a=[],c=[],f=null,u=0,l=!0,g=!1,d=[];for(let C=0;C<s.length;C++){let T=s[C],k=T.trim(),O=u,I=k.startsWith("///"),V=O===0&&!I&&(k.startsWith("//")||k.startsWith("/*"));if(g||V){if(d.push(T),!g&&k.startsWith("/*")&&!k.includes("*/"))g=!0;else if(g&&k.includes("*/"))g=!1;continue}if(O===0&&d.length>0&&k===""){d.push(T);continue}u+=(T.match(/\{/g)||[]).length,u-=(T.match(/\}/g)||[]).length;let L=Ad(k);if(l&&L&&L.kind!=="import"&&!k.startsWith("//")&&!k.startsWith("/*"))l=!1;if(l){if(d.length>0){if(L?.kind==="import"||!L)a.push(...d),d.length=0}a.push(T);continue}if(L&&u<=1){if(f)o.push(f);f={lines:d.length>0?[...d,T]:[T],kind:L.kind,name:L.name,isExport:L.isExport},d.length=0}else if(f)f.lines.push(T);else{if(k==="")continue;c.push(T)}}if(f)o.push(f);if(d.length>0)c.push(...d);o.sort((C,T)=>{if(i&&C.isExport!==T.isExport)return C.isExport?-1:1;let k=r.indexOf(C.kind),O=r.indexOf(T.kind),I=k>=0?k:r.length,V=O>=0?O:r.length;if(I!==V)return I-V;if(n)return C.name.localeCompare(T.name);return 0});let E=[...a],S=null;for(let C of o){if(S!==null&&C.kind!==S)E.push("");E.push(...C.lines),S=C.kind}if(c.length>0)E.push(""),E.push(...c);return E.join(`
|
|
183
|
+
`)}function Ad(e){let t=e.startsWith("export "),r=t?e.slice(7):e;if(e.startsWith("import "))return{kind:"import",name:e.match(/from\s+['"]([^'"]+)['"]/)?.[1]||"",isExport:!1};if(r.startsWith("type ")||r.startsWith("declare type "))return{kind:"type",name:r.match(/type\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("interface ")||r.startsWith("declare interface "))return{kind:"interface",name:r.match(/interface\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("class ")||r.startsWith("abstract class ")||r.startsWith("declare class ")||r.startsWith("declare abstract class "))return{kind:"class",name:r.match(/class\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("enum ")||r.startsWith("const enum ")||r.startsWith("declare enum ")||r.startsWith("declare const enum "))return{kind:"enum",name:r.match(/enum\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("function ")||r.startsWith("async function ")||r.startsWith("declare function ")||r.startsWith("declare async function "))return{kind:"function",name:r.match(/function\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("const ")||r.startsWith("let ")||r.startsWith("var ")||r.startsWith("declare const ")||r.startsWith("declare let ")||r.startsWith("declare var "))return{kind:"variable",name:r.match(/(?:const|let|var)\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("namespace ")||r.startsWith("declare namespace "))return{kind:"namespace",name:r.match(/namespace\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("module ")||r.startsWith("declare module "))return{kind:"module",name:r.match(/module\s+['"]?(\w+)['"]?/)?.[1]||"",isExport:t};if(e.startsWith("export {")||e.startsWith("export *")||e.startsWith("export type {"))return{kind:"export",name:"",isExport:!0};return null}var gd,yd;var Al=ce(()=>{gd=["import","type","interface","enum","class","function","variable","export","module","namespace","unknown"],yd=["builtin","external","scoped","internal","parent","sibling","index","type"]});function Pd(e){switch(e){case"strict":return Td;case"readonly":return Rd;case"simplified":return Od;case"nullable":return[{pattern:/^(.+)\s*\|\s*undefined$/,replacement:"$1 | undefined",priority:5}];case"branded":return[{pattern:/^string$/,replacement:"string",condition:(t)=>t.declarationKind==="variable"&&(t.declarationName?.includes("path")??!1),priority:5}];default:return[]}}class Tl{rules;compiled=[];cache=new Map;constructor(e={rules:[]}){if(this.rules=[],e.includeDefaults!==!1)this.rules.push(...xd);if(e.presets)for(let t of e.presets)this.rules.push(...Pd(t));this.rules.push(...e.rules),this.rules.sort((t,r)=>(r.priority||0)-(t.priority||0)),this.recompile()}recompile(){let e=Array(this.rules.length);for(let t=0;t<this.rules.length;t++){let r=this.rules[t],n=typeof r.pattern==="string"?new RegExp(r.pattern.replace(kd,"\\$&"),r.global?"g":""):r.pattern;e[t]={rule:r,regex:n}}this.compiled=e}map(e,t={}){let r=!t.declarationName&&!t.declarationKind&&!t.filePath&&!t.isReturnType&&!t.isParameterType&&!t.isPropertyType?e:`${e}\x00${t.declarationName??""}\x00${t.declarationKind??""}\x00${t.filePath??""}\x00${t.isReturnType?"r":""}${t.isParameterType?"p":""}${t.isPropertyType?"P":""}`,n=this.cache.get(r);if(n!==void 0)return n;let i=e,s=null;for(let o=0;o<this.compiled.length;o++){let{rule:a,regex:c}=this.compiled[o];if(a.condition){if(!s)s={type:e,...t};if(!a.condition(s))continue}if(c.lastIndex=0,c.test(i)){if(c.lastIndex=0,i=i.replace(c,a.replacement),c.lastIndex=0,!a.global)break}}if(this.cache.size>=xl){let o=Math.ceil(xl*0.1),a=0;for(let c of this.cache.keys()){if(a++>=o)break;this.cache.delete(c)}}return this.cache.set(r,i),i}mapAll(e,t={}){return e.map((r)=>this.map(r,{...t,type:r}))}addRule(e){this.rules.push(e),this.rules.sort((t,r)=>(r.priority||0)-(t.priority||0)),this.recompile(),this.cache.clear()}removeRules(e){let t=this.rules.length;return this.rules=this.rules.filter((r)=>{let n=typeof r.pattern==="string"?r.pattern:r.pattern.source;if(e instanceof RegExp)e.lastIndex=0;return typeof e==="string"?n!==e:!e.test(n)}),this.recompile(),this.cache.clear(),t-this.rules.length}clearCache(){this.cache.clear()}getRules(){return this.rules}}function Fi(e={rules:[]}){return new Tl(e)}function Rl(e,t,r={}){return e.replace(/:\s*([^;,)\]}]+)/g,(n,i)=>`: ${t.map(i.trim(),r)}`)}var xd,Td,Rd,Od,kd,xl=2048,My,Dy;var Ol=ce(()=>{xd=[{pattern:/^Promise<void>$/,replacement:"Promise<void>",priority:-1},{pattern:/^Record<string,\s*any>$/,replacement:"Record<string, unknown>",priority:0},{pattern:/^Array<([^<>]+)>$/,replacement:"$1[]",priority:0}],Td=[{pattern:/\bany\b/,replacement:"unknown",global:!0,priority:10},{pattern:/^object$/,replacement:"Record<string, unknown>",priority:10},{pattern:/^Function$/,replacement:"(...args: unknown[]) => unknown",priority:10}],Rd=[{pattern:/^(\w+)\[\]$/,replacement:"readonly $1[]",priority:5},{pattern:/^Array<(.+)>$/,replacement:"ReadonlyArray<$1>",priority:5},{pattern:/^Map<(.+),\s*(.+)>$/,replacement:"ReadonlyMap<$1, $2>",priority:5},{pattern:/^Set<(.+)>$/,replacement:"ReadonlySet<$1>",priority:5}],Od=[{pattern:/^Partial<Partial<(.+)>>$/,replacement:"Partial<$1>",priority:5},{pattern:/^Required<Required<(.+)>>$/,replacement:"Required<$1>",priority:5},{pattern:/^Pick<Omit<(.+),\s*(.+)>,\s*(.+)>$/,replacement:"Pick<$1, $3>",priority:5}];kd=/[.*+?^${}()|[\]\\]/g;My=Fi({rules:[]}),Dy=Fi({rules:[],presets:["strict"]})});function vt(e,t=!0){if(!t||!e||e.length===0)return"";if(e.length===1){let n=e[0];if(n.length>0&&n.charCodeAt(0)>32&&n.charCodeAt(n.length-1)>32)return`${n}
|
|
184
184
|
`;return`${n.trim()}
|
|
185
185
|
`}let r="";for(let n=0;n<e.length;n++){if(n>0)r+=`
|
|
186
186
|
`;r+=e[n].trim()}return`${r}
|
|
187
|
-
`}var
|
|
188
|
-
`){let i=r,s=n;while(i<s&&(e[i]===" "||e[i]==="\t"||e[i]==="\r"))i++;while(s>i&&(e[s-1]===" "||e[s-1]==="\t"||e[s-1]==="\r"))s--;let
|
|
187
|
+
`}var Pl=()=>{};function Fd(e){let t=[],r=0;for(let n=0;n<=e.length;n++)if(n===e.length||e[n]===`
|
|
188
|
+
`){let i=r,s=n;while(i<s&&(e[i]===" "||e[i]==="\t"||e[i]==="\r"))i++;while(s>i&&(e[s-1]===" "||e[s-1]==="\t"||e[s-1]==="\r"))s--;let o=e.slice(i,s);if(r=n+1,o.startsWith("///")){if(o.indexOf("<")===-1)continue;if(Md.test(o)||Dd.test(o)||Id.test(o))t.push(o)}else if(o===""||o.startsWith("//"))continue;else break}return t}function Nd(e){if(e.includes(`
|
|
189
189
|
`))return`/**
|
|
190
190
|
* ${e}
|
|
191
191
|
*/
|
|
192
192
|
`;return`/** ${e} */
|
|
193
|
-
`}function
|
|
194
|
-
`))
|
|
193
|
+
`}function Wd(e){let t=e.indexOf("{");if(t===-1)return-1;let r=e.indexOf("<");if(r===-1||r>t)return t;let n=0,i=!1,s="";for(let o=0;o<e.length;o++){let a=e[o],c=o>0?e[o-1]:"";if(!i&&(a==='"'||a==="'"||a==="`"))i=!0,s=a;else if(i&&a===s&&c!=="\\")i=!1;if(!i){if(a==="<")n++;else if(a===">")n--;else if(a==="{"&&n===0)return o}}return-1}function Ld(e,t=!0){return vt(e.leadingComments,t)+e.text}function kl(e,t=!0){let r=vt(e.leadingComments,t);if(e.typeAnnotation&&!e.value)return r+e.text;let n="";if(e.isExported)n+="export ";n+="declare ";let i=e.modifiers?.[0]||"const";n+=`${i} `,n+=e.name;let{typeAnnotation:s,value:o}=e;if(o&&o.includes(" satisfies ")){let c=Ya(o);if(c)s=c}else if(!s&&o&&o.trim().endsWith("as const"))s=Te(o,!0);else if(!s&&o&&i==="const"){let c=o.trim(),f=c.startsWith("{")||c.startsWith("[");if(f)Zn();s=Te(o,!f)}else if(!s&&o)s=Te(o,i==="const");if(!s)s="unknown";let a="";if(t&&o&&!e.typeAnnotation&&!o.trim().endsWith("as const")){let c=o.trim();if(i!=="const"){if((s==="string"||s==="number"||s==="boolean")&&c.length>0)a=`@defaultValue ${c}`}else if(c.startsWith("{")||c.startsWith("[")){let f=qn();if(f)if(f.includes(`
|
|
194
|
+
`))a=`@defaultValue
|
|
195
195
|
* \`\`\`ts
|
|
196
196
|
${f.split(`
|
|
197
197
|
`).map((u)=>` * ${u}`).join(`
|
|
198
198
|
`)}
|
|
199
|
-
* \`\`\``;else
|
|
200
|
-
`))
|
|
199
|
+
* \`\`\``;else a=`@defaultValue \`${f}\``}}else if(t&&o&&e.typeAnnotation&&Ua(e.typeAnnotation)){Zn();let c=o.trim(),f=c.endsWith("as const")?c.slice(0,-8).trim():c;Te(f,!1);let u=qn();if(u)if(u.includes(`
|
|
200
|
+
`))a=`@defaultValue
|
|
201
201
|
* \`\`\`ts
|
|
202
202
|
${u.split(`
|
|
203
203
|
`).map((l)=>` * ${l}`).join(`
|
|
204
204
|
`)}
|
|
205
|
-
* \`\`\``;else
|
|
205
|
+
* \`\`\``;else a=`@defaultValue \`${u}\``}if(n+=`: ${s};`,a&&r&&r.includes("@defaultValue"))a="";if(a&&r){let c=r.trimEnd(),f=c.lastIndexOf("*/");if(f!==-1){let u=c.slice(0,f).trimEnd();if(u.startsWith("/** ")&&!u.includes(`
|
|
206
206
|
`))u=`/**
|
|
207
207
|
* ${u.slice(4)}`;return`${u}
|
|
208
|
-
* ${
|
|
208
|
+
* ${a}
|
|
209
209
|
*/
|
|
210
210
|
`+n}return`/**
|
|
211
211
|
* ${c.replace(/^\/\/\s*/,"")}
|
|
212
|
-
* ${
|
|
212
|
+
* ${a}
|
|
213
213
|
*/
|
|
214
|
-
${n}`}if(
|
|
215
|
-
`;i+=
|
|
216
|
-
`));for(let
|
|
217
|
-
`);if(
|
|
218
|
-
`;i+=
|
|
219
|
-
`;i+=C[
|
|
220
|
-
`;i+=
|
|
221
|
-
`;i+=
|
|
222
|
-
`;i+=
|
|
223
|
-
`||c==="\r"?c:" ":c;continue}if(
|
|
224
|
-
${
|
|
225
|
-
${
|
|
226
|
-
...`:"")),
|
|
227
|
-
`);if(r.failOnUnresolvedReExport)throw Error(
|
|
228
|
-
--- Generation Statistics ---`),
|
|
229
|
-
Errors:`);for(let C of
|
|
230
|
-
`)}if(r.plugins&&r.plugins.length>0)await n.runOnEnd(a);return j.debug("DTS generation complete!"),a}async function jl(e){try{return await rm(e)}catch{return nt(e)}}async function lm(e){let t=nt(e.cwd,e.outdir);if(e.bundle&&e.bundleOutput){if(gs(e.bundleOutput))throw Error("bundleOutput must be relative to outdir");let i=nt(t,e.bundleOutput);if(!Wi(i,t))throw Error("bundleOutput must stay within outdir")}if(!e.clean||e.dryRun)return;if(t===am(t).root)throw Error("Refusing to clean declarations from the filesystem root");let[r,n]=await Promise.all([jl(t),jl(nt(e.cwd,e.root))]);if(Wi(n,r))throw Error("Refusing to clean an outdir that contains the source root")}function cm(e){let t=xr.get(e);if(!t){if(t=new Kl(e),xr.set(e,t),xr.size>om){let r=xr.keys().next().value;if(r!==void 0)xr.delete(r)}}return t}async function fm(e){let t=nt(e.cwd,e.outdir);async function r(n){let i;try{i=await tm(n,{withFileTypes:!0})}catch{return}await Promise.all(i.map(async(s)=>{let a=nt(n,s.name);if(s.isDirectory()){await r(a);return}if(s.name.endsWith(".d.ts")||s.name.endsWith(".d.mts")||s.name.endsWith(".d.cts")||s.name.endsWith(".d.ts.map")||s.name.endsWith(".d.mts.map")||s.name.endsWith(".d.cts.map"))await im(a,{force:!0})}))}await r(t)}function ms(e,t,r){if(!t||t.length===0)return!1;let n=Ne(r,e);for(let i of t){let s=cm(i);if(s.match(n)||s.match(e))return!0}return!1}async function um(e){let t=[],r=nt(e.cwd,e.root),n=e.exclude||[],i=[...e.entrypoints,...e.include??[]];for(let s of i)if(gs(s)&&ps(s)){if(!s.includes("node_modules")){if(!Wi(s,r)&&e.outputStructure!=="flat")j.warn(`Skipping entrypoint outside root: ${Ne(e.cwd,s)}`);else if(!ms(s,n,r))t.push(s)}}else{let a=new Kl(s);for await(let o of a.scan({cwd:r,absolute:!0,onlyFiles:!0}))if(ps(o)&&!o.includes("node_modules")){if(!ms(o,n,r))t.push(o)}}return[...new Set(t)].sort()}function Wi(e,t){let r=Ne(t,e);return r!==".."&&!r.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!gs(r)}function hm(e,t){let r=new Map;for(let n of e){let i=Rr(n,t),s=r.get(i);if(s&&s!==n)throw Error(`Output path collision: ${Ne(t.cwd,s)} and ${Ne(t.cwd,n)} both emit ${Ne(t.cwd,i)}`);r.set(i,n)}}function ps(e){return/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/.test(e)&&!/\.d\.(?:ts|mts|cts)$/.test(e)}function Rr(e,t){let r=nt(t.cwd,t.root),n=Ne(r,e).replace(/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/,(i)=>{if(i===".mts"||i===".mjs")return".d.mts";if(i===".cts"||i===".cjs")return".d.cts";return".d.ts"});if(t.outputStructure==="mirror")return nt(t.cwd,t.outdir,n);else{let i=n.split("/").pop();return nt(t.cwd,t.outdir,i)}}function dm(e,t,r=""){let n=Ne(Tr(e),t).replace(/\\/g,"/");if(n=n.replace(/\.d\.mts$/,"").replace(/\.d\.cts$/,"").replace(/\.d\.ts$/,""),r)n+=r;if(!n.startsWith("."))n=`./${n}`;return n}function mm(e,t,r){let n=Rr(t,r),i=(s)=>{let a=Ni(s,t);if(!a.isRelative||!a.resolved)return s;if(/\.d\.(?:ts|mts|cts)$/.test(a.resolved))return s;let o=s.match(/[?#].*$/)?.[0]??"",c=o?s.slice(0,-o.length):s,f=sm(c),u=/^(?:\.js|\.jsx|\.mjs|\.cjs)$/.test(f)?f:"";return dm(n,Rr(a.resolved,r),u)+o};return e.replace(/\b(from\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,a,o,c)=>{return`${a}${o}${i(c)}${o}`}).replace(/\b(import\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,a,o,c)=>{return`${a}${o}${i(c)}${o}`}).replace(/\b(import\s*\(\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,a,o,c)=>{return`${a}${o}${i(c)}${o}`})}async function pm(e,t,r,n,i){let s=t;if(n)s=await n.runOnBeforeFile(e,t);let a=Mi(s,e,r.keepComments,r.isolatedDeclarations??!1);if(n)a=await n.runOnDeclarations(e,s,a);let o=0,c=0;for(let u=0;u<a.length;u++){let l=a[u];if(l.kind==="import")o++;if(l.kind==="export"||l.isExported)c++}let f=Wl(a,{filePath:e,sourceCode:s,declarations:a},r.keepComments,r.importOrder);if(f=mm(f,e,r),i)f=Tl(f,i,{filePath:e});if(r.normalizeOutput===!0||r.declarationOrder)f=Sl(f,{lineEnding:"lf",declarationOrder:r.declarationOrder,indent:{style:r.indentStyle??"spaces",size:r.indentSize??2}});if(n)f=await n.runOnAfterFile(e,s,f);return{content:f,declarationCount:a.length,importCount:o,exportCount:c}}var Kl,om=50,xr;var Ul=le(()=>{Ms();Ls();Po();pl();yl();ho();$l();bl();Rl();_s();cs();Mo();Ll();_l();wi();({Glob:Kl}=globalThis.Bun);xr=new Map});var Yl=le(()=>{Ul()});var tc={};yc(tc,{dtsWatch:()=>xm,dtsCheck:()=>Tm,dts:()=>Cs,default:()=>Om,clearCache:()=>Rm,PluginErrorCodes:()=>Sm,DtsxPluginError:()=>ar});import{createHash as ym}from"crypto";import{existsSync as Cm,readFileSync as wm,writeFileSync as $m}from"fs";import{dirname as Em,join as vm,relative as Zl,resolve as sr,sep as Gi}from"path";import Xl from"process";class zl{listeners=new Map;on(e,t){let r=this.listeners.get(e)||[];r.push(t),this.listeners.set(e,r)}async emit(e,t){let r={type:e,timestamp:Date.now(),data:t},n=this.listeners.get(e)||[];for(let i of n)await i(r)}}class ys{manifest;cacheDir;manifestPath;constructor(e,t){this.cacheDir=e,this.manifestPath=vm(e,"manifest.json"),this.manifest=this.loadManifest(t)}loadManifest(e){try{if(Cm(this.manifestPath)){let t=JSON.parse(wm(this.manifestPath,"utf-8"));if(t.configHash===e&&t.version==="1.0")return t}}catch{}return{version:"1.0",configHash:e,entries:{}}}save(){try{let{mkdirSync:e}=gm("fs");e(this.cacheDir,{recursive:!0}),$m(this.manifestPath,JSON.stringify(this.manifest,null,2))}catch{}}getEntry(e){return this.manifest.entries[e]}setEntry(e,t){this.manifest.entries[e]=t}isValid(e,t){return this.getEntry(e)?.hash===t}clear(){this.manifest.entries={},this.save()}}function bm(e){let t={root:e.root,outdir:e.outdir,entrypoints:e.entrypoints,clean:e.clean,tsconfigPath:e.tsconfigPath};return ym("md5").update(JSON.stringify(t)).digest("hex")}function Cs(e={}){let{onSuccess:t,onError:r,failOnError:n=!0,incremental:i=!1,cacheDir:s=".dtsx-cache",on:a,timeout:o=60000,continueOnError:c=!1,verbose:f=!1,...u}=e,l=new zl;if(a){for(let[g,d]of Object.entries(a))if(d)l.on(g,d)}return{name:"bun-plugin-dtsx",async setup(g){let d=Date.now(),$=null,v=0;try{let C=ec(u,g),x=bm(C);if(C.clean){let B=sr(C.cwd??Xl.cwd(),C.outdir??"./dist");if(ql.has(B))C.clean=!1;else ql.add(B)}if(i)$=new ys(sr(s),x);if(await l.emit("start",{type:"start",files:C.entrypoints||[],config:C}),f){if(console.log("[bun-plugin-dtsx] Starting declaration generation..."),i)console.log("[bun-plugin-dtsx] Incremental mode enabled")}let R=await(async()=>{return new Promise((B,W)=>{let T=setTimeout(()=>{W(new ar(`Generation timed out after ${o}ms`,"TIMEOUT_ERROR",{timeout:o}))},o);Li(C).then((D)=>{clearTimeout(T),B(D)}).catch((D)=>{clearTimeout(T),W(D)})})})(),I=Date.now()-d;if($)$.save();if(await l.emit("complete",{type:"complete",stats:R,duration:I,fromCache:v}),f){if(console.log(`[bun-plugin-dtsx] Generation complete in ${I}ms`),v>0)console.log(`[bun-plugin-dtsx] ${v} files served from cache`)}if(t)await t(R)}catch(C){let x=Ql(C);if(await l.emit("error",{type:"error",error:x}),r)await r(x);else{if(console.error("[bun-plugin-dtsx] Error generating declarations:"),console.error(` Code: ${x.code}`),console.error(` Message: ${x.message}`),x.context)console.error(` Context: ${JSON.stringify(x.context)}`);if(f&&x.stack)console.error(` Stack: ${x.stack}`)}if(n&&!c)throw x}}}}function Ql(e){if(e instanceof ar)return e;if(e instanceof Error){let t="GENERATION_ERROR";if(e.message.includes("config")||e.message.includes("Config"))t="CONFIG_ERROR";else if(e.message.includes("file")||e.message.includes("File")||e.message.includes("ENOENT"))t="FILE_ERROR";return new ar(e.message,t,{originalError:e.name},e)}return new ar(String(e),"GENERATION_ERROR")}function Am(e){let t=e.map((n)=>Em(n).split(Gi)),r=t[0];for(let n of t.slice(1)){let i=0;while(i<r.length&&i<n.length&&r[i]===n[i])i++;r=r.slice(0,i)}return r.join(Gi)||Gi}function ec(e,t){let r=e.cwd||Xl.cwd(),n=t?.config?.entrypoints,i=e.outdir||e.build?.config.outdir||t?.config.outdir||"./dist",s=e.root||e.build?.config.root||t?.config.root;if(!s&&n?.length){let o=Am(n.map((c)=>sr(r,c)));s=Zl(r,o)||"."}s=s||"./src";let a=e.entrypoints;if(!a)if(n?.length){let o=sr(r,s),c=[];for(let f of n){let u=sr(r,f);if(u===o||u.startsWith(o+Gi))c.push(Zl(o,u));else console.warn(`[bun-plugin-dtsx] Skipping entrypoint outside root "${s}": ${f}`)}a=c.length?c:["index.ts"]}else a=["index.ts"];return{...e,cwd:r,root:s,entrypoints:a,outdir:i,clean:e.clean??!0,tsconfigPath:e.tsconfigPath}}function xm(e={}){return Cs({...e,incremental:!0,verbose:e.verbose??!0})}function Tm(e){return{name:"bun-plugin-dtsx-check",async setup(t){let r=ec({...e,outdir:""},t);try{await Li({...r,clean:!1})}catch(n){let i=Ql(n);if(e.onError)await e.onError(i);if(e.failOnError!==!1)throw i}}}}function Rm(e=".dtsx-cache"){new ys(sr(e),"").clear()}var gm,Sm,ar,ql,Om;var rc=le(()=>{Yl();gm=import.meta.require,Sm={CONFIG_ERROR:"CONFIG_ERROR",GENERATION_ERROR:"GENERATION_ERROR",FILE_ERROR:"FILE_ERROR",CACHE_ERROR:"CACHE_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR"};ar=class ar extends Error{code;context;cause;constructor(e,t,r,n){super(e);if(this.name="DtsxPluginError",this.code=t,this.context=r,this.cause=n,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,context:this.context,stack:this.stack}}};ql=new Set;Om=Cs});import{mkdir as Pm,stat as km}from"fs/promises";import{bold as ws,dim as $s,green as Mm,italic as ic,log as Im}from"@stacksjs/cli";import{path as st}from"@stacksjs/path";import{glob as nc}from"@stacksjs/storage";async function Dm(e){let t=await nc([st.resolve(e,"dist","**/*.d.ts")],{absolute:!0}),r=new Bun.Transpiler({loader:"ts",target:"bun"});for(let n of t){let i=await Bun.file(n).text();try{r.transformSync(i)}catch(s){throw Error(`Invalid declaration generated at ${n}: ${s instanceof Error?s.message:String(s)}`)}}}async function Fm(e){let t=st.resolve(e,"dist","index.js");if(!await Bun.file(t).exists())return;let r=Bun.spawnSync({cmd:[process.execPath,"-e",`await import(${JSON.stringify(t)})`],stdout:"ignore",stderr:"pipe",env:{...process.env,NODE_ENV:"test"}});if(r.exitCode===0)return;let n=new TextDecoder().decode(r.stderr??new Uint8Array);if(/needs to refer to a top-level declared variable|does not provide an export named|Export named .* not found/i.test(n))throw Error(`Built package at ${t} cannot be imported: ${n.trim().split(`
|
|
214
|
+
${n}`}if(a)return`${Nd(a)}${n}`;return r+n}function Gd(e,t=!0){let r=vt(e.leadingComments,t),n=e.text;if(n.startsWith("export declare interface")||n.startsWith("declare interface"))return r+n;let i="";if(e.isExported)i+="export ";if(i+="declare interface ",i+=e.name,e.generics)i+=e.generics;if(e.extends)i+=` extends ${e.extends}`;let s=Wd(e.text);if(s!==-1)i+=` ${e.text.slice(s)}`;else i+=" {}";return r+i}function Bd(e,t=!0){let r=vt(e.leadingComments,t);if(e.text.includes("{")&&e.text.includes("}")&&e.text.includes("from"))return r+e.text;let n="";if(e.isExported)n+="export ";if(!e.isExported&&!e.text.includes(" from "))n+="declare ";let i=e.text.indexOf("type ");if(i!==-1){let o=e.text.slice(i),a=o.length;while(a>0&&(o.charCodeAt(a-1)===59||o.charCodeAt(a-1)===32||o.charCodeAt(a-1)===10||o.charCodeAt(a-1)===13))a--;if(a<o.length)o=o.slice(0,a);n+=o}else{if(n+=`type ${e.name}`,e.generics)n+=e.generics;n+=" = any"}let s=n.trimEnd();if(!s.endsWith(";")&&!s.endsWith("}"))n+=";";return r+n}function Vd(e,t=!0){return vt(e.leadingComments,t)+e.text}function _d(e,t=!0){let r=vt(e.leadingComments,t),n="";if(e.isExported)n+="export ";if(n+="declare ",e.modifiers?.includes("const"))n+="const ";n+="enum ",n+=e.name;let i=e.text.indexOf("{");if(i!==-1)n+=` ${e.text.slice(i)}`;else n+=" {}";return r+n}function Hd(e,t=!0){let r=vt(e.leadingComments,t);if(e.text.startsWith("declare global"))return r+e.text;if(e.source||(e.name.startsWith('"')||e.name.startsWith("'")||e.name.startsWith("`"))){let s="declare module ";s+=e.name;let o=e.text.indexOf("{");if(o!==-1)s+=` ${e.text.slice(o)}`;else s+=" {}";return r+s}let n="";if(e.isExported)n+="export ";if(!e.modifiers?.includes("declare"))n+="declare ";n+="namespace ",n+=e.name;let i=e.text.indexOf("{");if(i!==-1)n+=` ${e.text.slice(i)}`;else n+=" {}";return r+n}function jd(e){let t=Dt.get(e);if(t)return Dt.delete(e),Dt.set(e,t),t;return null}function Ml(e,t){if(Dt.set(e,t),Dt.size>200){let r=0;for(let n of Dt.keys()){if(r++>=20)break;Dt.delete(n)}}}function Kd(e){let t=e.indexOf(" from ");if(t===-1)return null;let r=e.slice(t+6).trim(),n=r[0];if(n!=='"'&&n!=="'")return null;let i=r.indexOf(n,1);if(i===-1)return null;let s=r.slice(1,i),o=e.slice(0,t).trim(),a=o.startsWith("import type ");if(o.startsWith("import "))o=o.slice(7).trim();if(o.startsWith("type "))o=o.slice(5).trim();let c=null,f=[],u=!1,l=o.indexOf("{"),g=o.lastIndexOf("}");if(l!==-1&&g!==-1){let d=o.slice(0,l).trim();if(d.endsWith(","))c=d.slice(0,-1).trim()||null;let E=o.slice(l+1,g),S=0;for(let C=0;C<=E.length;C++)if(C===E.length||E.charCodeAt(C)===44){let T=S,k=C;while(T<k&&(E.charCodeAt(T)===32||E.charCodeAt(T)===9||E.charCodeAt(T)===10))T++;while(k>T&&(E.charCodeAt(k-1)===32||E.charCodeAt(k-1)===9||E.charCodeAt(k-1)===10))k--;if(T<k)f.push(E.slice(T,k));S=C+1}}else{let d=o.trim();if(d.startsWith("* as "))c=d.slice(5).trim()||null,u=!0;else c=d||null}return{defaultName:c,namedItems:f,source:s,isTypeOnly:a,isNamespace:u}}function Jd(e){let t=jd(e);if(t)return t;let r=[],n=e.indexOf(" from ");if(n===-1)return Ml(e,r),r;let i=e.slice(0,n).trim();if(i.startsWith("import "))i=i.slice(7).trim();if(i.startsWith("type "))i=i.slice(5).trim();let s=i.indexOf("{"),o=i.lastIndexOf("}");if(s!==-1&&o!==-1){let a=i.slice(0,s).trim();if(a.endsWith(",")){let f=a.slice(0,-1).trim();if(f)r.push(f)}else if(a&&!a.includes(","))r.push(a);let c=i.slice(s+1,o).split(",");for(let f=0;f<c.length;f++){let u=c[f].trim();if(!u)continue;if(u.startsWith("type "))u=u.slice(5).trim();let l=u.indexOf(" as ");if(l!==-1)u=u.slice(l+4).trim();if(u)r.push(u)}}else{let a=i.trim();if(a.startsWith("* as ")){let c=a.slice(5).trim();if(c)r.push(c)}else if(a)r.push(a)}return Ml(e,r),r}function Dl(e,t){throw Error(t||`Unexpected value: ${e}`)}function Ud(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===95||e===36||e>127}function Il(e){let t=new Set,r=0,n=e.length;while(r<n){let i=e.charCodeAt(r);if(i>=65&&i<=90||i>=97&&i<=122||i===95||i===36||i>127){let s=r;r++;while(r<n&&Ud(e.charCodeAt(r)))r++;t.add(e.substring(s,r))}else r++}return t}function Ll(e,t,r=!0,n=["bun"]){let i="",s=t.sourceCode;if(s){let F=0;while(F<s.length&&(s.charCodeAt(F)===32||s.charCodeAt(F)===9||s.charCodeAt(F)===10||s.charCodeAt(F)===13))F++;if(F<s.length-2&&s.charCodeAt(F)===47&&s.charCodeAt(F+1)===47&&s.charCodeAt(F+2)===47){let j=Fd(s);if(j.length>0)for(let Z=0;Z<j.length;Z++){if(i)i+=`
|
|
215
|
+
`;i+=j[Z]}}}let o=[],a=[],c=[],f=[],u=[],l=[],g=[],d=[],E=[];for(let F of e){let j=F.kind;switch(j){case"import":o.push(F);break;case"function":a.push(F);break;case"variable":c.push(F);break;case"interface":f.push(F);break;case"type":u.push(F);break;case"class":l.push(F);break;case"enum":g.push(F);break;case"module":d.push(F);break;case"export":E.push(F);break;case"namespace":d.push(F);break;case"unknown":break;default:Dl(j,`Unhandled declaration kind: ${j}`)}}let S=new Set,C=[],T=[],k=[],O=new Set;for(let F of E){let j=vt(F.leadingComments,r);if(F.text.startsWith("export default")){let Z=F.text.endsWith(";")?F.text:`${F.text};`;k.push(j+Z)}else{let Z=F.text.trim();if(!Z.endsWith(";"))Z+=";";let oe=Z.match(Yd);if(oe){let X=oe[1],re=0;for(let z=0;z<=X.length;z++)if(z===X.length||X.charCodeAt(z)===44){let Oe=re,Pe=z;while(Oe<Pe&&X.charCodeAt(Oe)<=32)Oe++;while(Pe>Oe&&X.charCodeAt(Pe-1)<=32)Pe--;if(Oe<Pe)S.add(X.slice(Oe,Pe));re=z+1}}let J=j+Z;if(!O.has(J))if(O.add(J),J.includes("export type"))C.push(J);else T.push(J)}}let I=new Map;if(o.length>0)for(let F of o){let j=Jd(F.text);for(let Z of j)I.set(Z,F)}let V=new Set;if(f.length>0){let F=[];for(let j of a)if(j.isExported)F.push(j.text);for(let j of l)F.push(j.text);for(let j of u)F.push(j.text);if(F.length>0){let j=Il(F.join(`
|
|
216
|
+
`));for(let Z of f)if(j.has(Z.name))V.add(Z.name)}}let L=[];if(o.length>0){let F=new Set,j=[];for(let J of a)if(J.isExported)j.push(J.text);for(let J of c)if(j.push(J.text),J.typeAnnotation)j.push(J.typeAnnotation);else if(J.isExported&&J.value)j.push(kl(J,!1));for(let J of f)if(J.isExported||V.has(J.name))j.push(J.text);for(let J of u)j.push(J.text);for(let J of l)j.push(J.text);for(let J of g)j.push(J.text);for(let J of d)j.push(J.text);for(let J of E)j.push(J.text);let Z=j.join(`
|
|
217
|
+
`);if(Z&&I.size>0){let J=Il(Z);for(let X of I.keys())if(J.has(X))F.add(X)}for(let J of S)if(I.has(J))F.add(J);for(let J of o){if(J.isSideEffect){let ae=J.text.trim(),Q=ae.endsWith(";")?ae:`${ae};`;L.push(Q);continue}let X=Kd(J.text);if(!X)continue;let{defaultName:re,namedItems:z,source:Oe,isTypeOnly:Pe,isNamespace:It}=X,ke=re?F.has(re):!1,Me="",ht=0;for(let ae=0;ae<z.length;ae++){let Q=z[ae],Ft=Q.charCodeAt(0)===116&&Q.startsWith("type ")?Q.slice(5).trim():Q.trim(),lr=Ft.indexOf(" as ");if(lr!==-1)Ft=Ft.slice(lr+4).trim();if(F.has(Ft)){if(ht>0)Me+=", ";Me+=Q,ht++}}if(ke||ht>0){let ae=Pe?"import type ":"import ";if(ke&&re)if(It)ae+=`* as ${re}`;else ae+=ht>0?`${re}, { ${Me} }`:re;else if(ht>0)ae+=`{ ${Me} }`;ae+=` from '${Oe}';`,L.push(ae)}}let oe=n.length;if(L.length>1){if(Fl!==n)Fl=n,Nl=n.map((z)=>`from '${z}`),Wl=n.map((z)=>`from "${z}`);let J=Nl,X=Wl,re=new Map;for(let z of L){let Oe=oe;for(let Pe=0;Pe<n.length;Pe++)if(z.includes(J[Pe])||z.includes(X[Pe])){Oe=Pe;break}re.set(z,Oe)}L.sort((z,Oe)=>{let Pe=re.get(z),It=re.get(Oe);return Pe!==It?Pe-It:z.localeCompare(Oe)})}}for(let F=0;F<L.length;F++){if(i)i+=`
|
|
218
|
+
`;i+=L[F]}for(let F=0;F<C.length;F++){if(i)i+=`
|
|
219
|
+
`;i+=C[F]}let R=[a,c,f,u,l,g,d];for(let F=0;F<R.length;F++){let j=R[F];for(let Z=0;Z<j.length;Z++){let oe=j[Z],J="",X=oe.kind;switch(X){case"function":J=Ld(oe,r);break;case"variable":J=kl(oe,r);break;case"interface":J=Gd(oe,r);break;case"type":J=Bd(oe,r);break;case"class":J=Vd(oe,r);break;case"enum":J=_d(oe,r);break;case"module":case"namespace":J=Hd(oe,r);break;case"import":case"export":case"unknown":break;default:Dl(X,`Unhandled declaration kind in processor: ${X}`)}if(J){if(i)i+=`
|
|
220
|
+
`;i+=J}}}for(let F=0;F<T.length;F++){if(i)i+=`
|
|
221
|
+
`;i+=T[F]}for(let F=0;F<k.length;F++){if(i)i+=`
|
|
222
|
+
`;i+=k[F]}if(!i&&(o.length>0||E.length>0))return"export {};";return i}var Md,Dd,Id,Dt,Yd,Fl=null,Nl,Wl;var Gl=ce(()=>{Pl();zn();Md=/^\/\/\/\s*<reference\s+(?:path|types|lib|no-default-lib)\s*=\s*["'][^"']+["']\s*\/>/,Dd=/^\/\/\/\s*<amd-module\s+name\s*=\s*["'][^"']+["']\s*\/>/,Id=/^\/\/\/\s*<amd-dependency\s+path\s*=\s*["'][^"']+["']/;Dt=new Map;Yd=/export\s+(?:type\s+)?\{\s*([^}]+)\s*\}/,Nl=[],Wl=[]});import{existsSync as Zd,statSync as qd}from"fs";import{dirname as Xd,extname as zd,isAbsolute as us,resolve as Qd}from"path";function Ni(e){try{return qd(e).isFile()}catch{return!1}}function Wi(e,t){let r=e.replace(/[?#].*$/,"");if(!(r.startsWith("./")||r.startsWith("../")||r==="."||r==="..")&&!us(r))return{resolved:null,isRelative:!1};let n=Xd(t),i=us(r)?r:Qd(n,r);if(Ni(i))return{resolved:i,isRelative:!0};let s=zd(i),o=em[s];if(o){let a=i.slice(0,-s.length);for(let c of o){let f=a+c;if(Ni(f))return{resolved:f,isRelative:!0}}}for(let a of Bl){let c=i+a;if(Ni(c))return{resolved:c,isRelative:!0}}if(Zd(i))for(let a of Bl){let c=`${i}/index${a}`;if(Ni(c))return{resolved:c,isRelative:!0}}return{resolved:null,isRelative:!0}}function tm(e){let t=e.length,r="",n=0;while(n<t){let i=e.charCodeAt(n);if(i===34||i===39||i===96){let s=i;r+=e[n++];while(n<t){let o=e.charCodeAt(n),a=e[n++];if(r+=s===96&&o!==s?o===10||o===13?a:" ":a,o===92&&n<t){let c=e[n++];r+=s===96?c===`
|
|
223
|
+
`||c==="\r"?c:" ":c;continue}if(o===s)break}continue}if(i===47&&n+1<t){let s=e.charCodeAt(n+1);if(s===47){n+=2;while(n<t&&e.charCodeAt(n)!==10)n++;continue}if(s===42){n+=2;while(n+1<t&&!(e.charCodeAt(n)===42&&e.charCodeAt(n+1)===47))n++;n+=2;continue}}r+=e[n++]}return r}function hs(e,t={}){let r=[],n=tm(e);Vl.lastIndex=0;let i;while((i=Vl.exec(n))!==null){let s=!!i[1],o=i[3],a=i[0],c;if(a.includes("* as "))c="export-star-as";else if(a.includes("*"))c="export-star";else c="export-named";r.push({specifier:o,kind:c,isTypeOnly:s})}if(t.includeImports){_l.lastIndex=0;while((i=_l.exec(n))!==null)r.push({specifier:i[3],kind:"import",isTypeOnly:!!i[1]})}return r}async function ds(e,t={}){let r=new Set,n=new Map,i=[],s=[];for(let o of e)if(!r.has(o))r.add(o),s.push(o);while(s.length>0){let o=s.shift(),a;try{a=await $t(o)}catch{continue}let c=hs(a,t);n.set(o,c);for(let f of c){if(!(f.specifier.startsWith(".")||us(f.specifier)))continue;let u=Wi(f.specifier,o);if(u.resolved){if(!r.has(u.resolved))r.add(u.resolved),s.push(u.resolved)}else i.push({from:o,specifier:f.specifier,isTypeOnly:f.isTypeOnly})}}return{reachable:r,reExports:n,unresolved:i}}var Bl,em,Vl,_l;var Hl=ce(()=>{$i();Bl=[".ts",".tsx",".mts",".cts",".vue",".stx",".js",".jsx",".mjs",".cjs",".d.ts",".d.mts",".d.cts"],em={".js":[".ts",".tsx",".d.ts"],".jsx":[".tsx",".ts",".d.ts"],".mjs":[".mts",".d.mts"],".cjs":[".cts",".d.cts"]};Vl=/(?:^|[\n;{}])\s*export\s+(type\s+)?(?:\*(?:\s+as\s+\w+)?|\{[^}]*\})\s+from\s+(['"])([^'"]+)\2/g,_l=/(?:^|[\n;{}])\s*import\s+(type\s+)?(?:[^'";\n]+\s+from\s+)?(['"])([^'"]+)\2/g});import{mkdir as ms,readdir as rm,realpath as im,rm as nm}from"fs/promises";import{availableParallelism as sm}from"os";import{basename as Ul,dirname as Rr,extname as om,isAbsolute as ys,parse as am,relative as We,resolve as st}from"path";async function jl(e,t,r,n,i){let s=Ul(e)||"output.d.ts",o=We(Rr(e),t),a=`${s}.map`,c=r.lastIndexOf(`
|
|
224
|
+
${jn()}`),f=c===-1?r:r.slice(0,c),u=Oa(f,s,o,n),l=`${e}.map`;return await yr(l,JSON.stringify(u)),K.debug(` Generated source map: ${We(i,l)}`),a}async function Gi(e){let t=Date.now(),r={...da,...e};if(r.logLevel)en(r.logLevel);else if(r.verbose)en("debug");let n=new Mr;if(r.plugins&&r.plugins.length>0){for(let C of r.plugins)n.register(C),K.debug(`Registered plugin: ${C.name}`);r=await n.runOnStart(r)}if(await cm(r),r.isolatedDeclarations===void 0)r.isolatedDeclarations=await xa(r);let i=r.typeMappings?Fi(r.typeMappings):void 0,s=null;if(r.incremental){if(s=new Qi(r),r.clearCache){if(K.debug("Clearing build cache..."),!r.dryRun)s.clear()}else if(s.load()){let C=s.getStats();K.debug(`Loaded build cache with ${C.entries} entries`)}else K.debug("No existing build cache found, starting fresh");if(!r.dryRun)Ls(r.cwd)}let o={generationMode:r.isolatedDeclarations?"isolated":"semantic",filesProcessed:0,filesGenerated:0,filesFailed:0,filesValidated:0,validationErrors:0,declarationsFound:0,importsProcessed:0,exportsProcessed:0,durationMs:0,errors:[]},a=0;if(K.debug("Starting DTS generation..."),K.debug(`Using ${o.generationMode} declaration generation path`),K.debug("Config:",r),r.clean&&!r.dryRun)await um(r);let c=await hm(r),f=c.slice(),u=null;if(r.autoIncludeReExports!==!1&&f.length>0){u=await ds(f,{includeImports:!0});let C=st(r.cwd,r.root),T=r.exclude||[],k=[];for(let O of u.reachable){if(f.includes(O))continue;if(!gs(O))continue;if(O.endsWith(".d.ts"))continue;if(O.includes("node_modules"))continue;if(!Li(O,C)){K.warn(`Skipping auto-included source outside root: ${We(r.cwd,O)}`);continue}if(ps(O,T,C))continue;k.push(O)}if(k.length>0)f=[...f,...k],K.debug(`Auto-included ${k.length} file(s) reached via relative re-exports`)}if(dm(f,r),s&&!r.dryRun){let C=s.prune(new Set(f),r.cwd);if(C>0)K.debug(`Pruned ${C} deleted files from cache`)}if(K.debug(`Found ${f.length} TypeScript files`),r.progress&&f.length>0){let C=r.parallel?"parallel":"sequential";K.info(`Processing ${f.length} files (${C})...`)}let l=async(C,T)=>{let k;try{let O=Or(C,r),I=async(X)=>{if(!r.diff)return;try{let re=await $t(O),z=Ra(re,X,We(r.cwd,O));if(z)K.info(`
|
|
225
|
+
${z}`);else K.debug(`[no changes] ${O}`)}catch{K.info(`[new file] ${We(r.cwd,O)}`)}},V=(X)=>{if(!r.validate)return 0;let re=Ta(X,O);if(re.isValid)return K.debug(`[validation] ${O} - OK`),0;K.warn(`[validation] ${We(r.cwd,O)} has ${re.errors.length} error(s):`);for(let z of re.errors){let Oe=` Line ${z.line}:${z.column}`;if(z.code)Oe+=` [${z.code}]`;if(Oe+=` - ${z.message}`,K.warn(Oe),z.suggestion)K.warn(` Suggestion: ${z.suggestion}`)}return re.errors.length},L=(X)=>{K.info(`[dry-run] Would generate: ${O}`),K.debug("--- Content preview ---"),K.debug(X.slice(0,500)+(X.length>500?`
|
|
226
|
+
...`:"")),K.debug("--- End preview ---")};if(s){let X=s.getCachedIfValid(C,r.cwd);if(X){await I(X);let re=V(X);if(r.dryRun)L(X);else{if(await ms(Rr(O),{recursive:!0}),r.declarationMap)k=T??await $t(C),await jl(O,C,X,k,r.cwd);await yr(O,X,r.lineEnding)}return K.debug(`[cached] ${We(r.cwd,O)}`),{success:!0,file:C,declarationCount:0,importCount:0,exportCount:0,cached:!0,validationErrorCount:re}}}k=T??await $t(C);let{content:R,declarationCount:F,importCount:j,exportCount:Z}=await gm(C,k,r,n,i),oe=R;if(r.prettier||r.indentStyle||r.indentSize){let X=await yl(oe,{usePrettier:r.prettier,builtIn:{indentSize:r.indentSize||2,useTabs:r.indentStyle==="tabs",normalizeWhitespace:!0,sortImports:!0,trailingNewline:!0}},O);oe=X.content;for(let re of X.warnings??[])K.warn(`[format] ${re}`)}if(r.declarationMap){let X=`${Ul(O)||"output.d.ts"}.map`;oe=Pa(oe,X)}await I(oe);let J=V(oe);if(r.dryRun)L(oe);else{if(await ms(Rr(O),{recursive:!0}),r.declarationMap&&k)await jl(O,C,oe,k,r.cwd);if(await yr(O,oe,r.lineEnding),s&&k)s.update(C,k,oe,r.cwd);K.debug(`Generated: ${O}`)}return{success:!0,file:C,declarationCount:F,importCount:j,exportCount:Z,validationErrorCount:J}}catch(O){let I=wl(O,C,k);if(r.plugins&&r.plugins.length>0)await n.runOnError(O instanceof Error?O:Error(String(O)),C,k||"");return{success:!1,file:C,declarationCount:0,importCount:0,exportCount:0,dtsError:I,validationErrorCount:0}}},g=r.parallel||r.parallel!==!1&&f.length>=10,d=Ma(r.concurrency,sm?.()??8),E=new Map;if(g&&f.length>1){let C=f.map(async(T)=>{try{let k=await $t(T);return{file:T,source:k}}catch{return{file:T,source:null}}});for(let T of await Promise.all(C))if(T.source!==null)E.set(T.file,T.source)}let S=(C)=>{if(o.filesProcessed++,C.success){if(C.cached)a++;else o.filesGenerated++,o.declarationsFound+=C.declarationCount,o.importsProcessed+=C.importCount,o.exportsProcessed+=C.exportCount;if(r.validate){if(o.filesValidated++,C.validationErrorCount)o.validationErrors+=C.validationErrorCount}}else if(o.filesFailed++,C.dtsError){o.errors.push(C.dtsError);let T=$l(C.dtsError);if(r.continueOnError)K.warn(T);else throw K.error(T),Error(C.dtsError.message)}};if(g)for(let C=0;C<f.length;C+=d){let T=f.slice(C,C+d),k=await Promise.all(T.map((O)=>l(O,E.get(O))));for(let O of k)S(O);if(r.progress){let O=Math.round(o.filesProcessed/f.length*100);K.info(`[${o.filesProcessed}/${f.length}] ${O}%`)}}else for(let C of f){let T=await l(C);if(S(T),r.progress){let k=Math.round(o.filesProcessed/f.length*100),O=T.cached?"[cached]":"";K.info(`[${o.filesProcessed}/${f.length}] ${k}% - ${We(r.cwd,C)} ${O}`)}}if(s&&!r.dryRun)s.save(),K.debug("Saved build cache");if(!r.bundle){let C=[];if(u)for(let T of u.unresolved)C.push({from:T.from,specifier:T.specifier,reason:"missing"});if(r.autoIncludeReExports===!1&&f.length>0){let T=new Set(f);for(let k of f){let O;try{O=await $t(k)}catch{continue}for(let I of hs(O)){if(!I.specifier.startsWith("."))continue;let V=Wi(I.specifier,k);if(!V.resolved)C.push({from:k,specifier:I.specifier,reason:"missing"});else if(!/\.d\.(?:ts|mts|cts)$/.test(V.resolved)&&!T.has(V.resolved))C.push({from:k,specifier:I.specifier,reason:"not-emitted"})}}}if(C.length>0){let T=[];T.push(`Found ${C.length} re-export(s) pointing at siblings that won't be in the output:`);for(let O of C){let I=We(r.cwd,O.from);if(O.reason==="missing")T.push(` ${I} \u2192 '${O.specifier}' (path not found on disk)`);else T.push(` ${I} \u2192 '${O.specifier}' (resolved but not in entrypoints; set autoIncludeReExports: true or add to entrypoints)`)}let k=T.join(`
|
|
227
|
+
`);if(r.failOnUnresolvedReExport)throw Error(k);K.warn(k),K.warn('Generated .d.ts files reference modules that were not emitted \u2014 consumers will see "has no exported member" errors.')}}if(r.bundle&&(o.filesGenerated>0||a>0)&&c.length>0)try{K.debug("Bundling declarations...");let C=new Map,T=async(O)=>{let I=C.get(O);if(I!==void 0)return I;return I=await $t(O),C.set(O,I),I};for(let O of f)await T(O);let k=c.length===1&&!!r.bundleOutput;for(let O of c){let I=await ds([O],{includeImports:!0}),V=new Set;for(let Z of I.reachable){if(Z.endsWith(".d.ts"))continue;if(Z.includes("node_modules"))continue;V.add(Z)}let L=f.filter((Z)=>V.has(Z));if(!L.includes(O))L.push(O);let R=new Map;for(let Z of L){let oe=C.get(Z)??await T(Z);R.set(Z,oe)}let F=await ml(L,R,r),j=k?st(r.cwd,r.outdir,r.bundleOutput):Or(O,r);if(r.dryRun)K.info(`[dry-run] Would bundle ${F.files.length} files to: ${We(r.cwd,j)}`);else await ms(Rr(j),{recursive:!0}),await yr(j,F.content,r.lineEnding),K.info(`Bundled ${F.files.length} files to: ${We(r.cwd,j)}`);if(k)break}}catch(C){let T=C instanceof Error?C.message:String(C);K.error(`Bundle failed: ${T}`)}if(o.durationMs=Date.now()-t,r.stats)if(r.outputFormat==="json")console.log(JSON.stringify(o,null,2));else{if(K.info(`
|
|
228
|
+
--- Generation Statistics ---`),K.info(`Files processed: ${o.filesProcessed}`),K.info(`Files generated: ${o.filesGenerated}`),a>0)K.info(`Files cached: ${a}`);if(o.filesFailed>0)K.info(`Files failed: ${o.filesFailed}`);if(K.info(`Declarations found: ${o.declarationsFound}`),K.info(`Imports processed: ${o.importsProcessed}`),K.info(`Exports processed: ${o.exportsProcessed}`),o.filesValidated>0){if(K.info(`Files validated: ${o.filesValidated}`),o.validationErrors>0)K.info(`Validation errors: ${o.validationErrors}`)}if(K.info(`Duration: ${o.durationMs}ms`),o.errors.length>0){K.info(`
|
|
229
|
+
Errors:`);for(let C of o.errors){let T=` - ${C.file}`;if(C.location)T+=`:${C.location.line}:${C.location.column}`;if(C.code)T+=` [${C.code}]`;if(T+=`: ${C.message}`,K.info(T),C.suggestion)K.info(` Suggestion: ${C.suggestion}`)}}K.info(`-----------------------------
|
|
230
|
+
`)}if(r.plugins&&r.plugins.length>0)await n.runOnEnd(o);return K.debug("DTS generation complete!"),o}async function Kl(e){try{return await im(e)}catch{return st(e)}}async function cm(e){let t=st(e.cwd,e.outdir);if(e.bundle&&e.bundleOutput){if(ys(e.bundleOutput))throw Error("bundleOutput must be relative to outdir");let i=st(t,e.bundleOutput);if(!Li(i,t))throw Error("bundleOutput must stay within outdir")}if(!e.clean||e.dryRun)return;if(t===am(t).root)throw Error("Refusing to clean declarations from the filesystem root");let[r,n]=await Promise.all([Kl(t),Kl(st(e.cwd,e.root))]);if(Li(n,r))throw Error("Refusing to clean an outdir that contains the source root")}function fm(e){let t=Tr.get(e);if(!t){if(t=new Jl(e),Tr.set(e,t),Tr.size>lm){let r=Tr.keys().next().value;if(r!==void 0)Tr.delete(r)}}return t}async function um(e){let t=st(e.cwd,e.outdir);async function r(n){let i;try{i=await rm(n,{withFileTypes:!0})}catch{return}await Promise.all(i.map(async(s)=>{let o=st(n,s.name);if(s.isDirectory()){await r(o);return}if(s.name.endsWith(".d.ts")||s.name.endsWith(".d.mts")||s.name.endsWith(".d.cts")||s.name.endsWith(".d.ts.map")||s.name.endsWith(".d.mts.map")||s.name.endsWith(".d.cts.map"))await nm(o,{force:!0})}))}await r(t)}function ps(e,t,r){if(!t||t.length===0)return!1;let n=We(r,e);for(let i of t){let s=fm(i);if(s.match(n)||s.match(e))return!0}return!1}async function hm(e){let t=[],r=st(e.cwd,e.root),n=e.exclude||[],i=[...e.entrypoints,...e.include??[]];for(let s of i)if(ys(s)&&gs(s)){if(!s.includes("node_modules")){if(!Li(s,r)&&e.outputStructure!=="flat")K.warn(`Skipping entrypoint outside root: ${We(e.cwd,s)}`);else if(!ps(s,n,r))t.push(s)}}else{let o=new Jl(s);for await(let a of o.scan({cwd:r,absolute:!0,onlyFiles:!0}))if(gs(a)&&!a.includes("node_modules")){if(!ps(a,n,r))t.push(a)}}return[...new Set(t)].sort()}function Li(e,t){let r=We(t,e);return r!==".."&&!r.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!ys(r)}function dm(e,t){let r=new Map;for(let n of e){let i=Or(n,t),s=r.get(i);if(s&&s!==n)throw Error(`Output path collision: ${We(t.cwd,s)} and ${We(t.cwd,n)} both emit ${We(t.cwd,i)}`);r.set(i,n)}}function gs(e){return/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/.test(e)&&!/\.d\.(?:ts|mts|cts)$/.test(e)}function Or(e,t){let r=st(t.cwd,t.root),n=We(r,e).replace(/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/,(i)=>{if(i===".mts"||i===".mjs")return".d.mts";if(i===".cts"||i===".cjs")return".d.cts";return".d.ts"});if(t.outputStructure==="mirror")return st(t.cwd,t.outdir,n);else{let i=n.split("/").pop();return st(t.cwd,t.outdir,i)}}function mm(e,t,r=""){let n=We(Rr(e),t).replace(/\\/g,"/");if(n=n.replace(/\.d\.mts$/,"").replace(/\.d\.cts$/,"").replace(/\.d\.ts$/,""),r)n+=r;if(!n.startsWith("."))n=`./${n}`;return n}function pm(e,t,r){let n=Or(t,r),i=(s)=>{let o=Wi(s,t);if(!o.isRelative||!o.resolved)return s;if(/\.d\.(?:ts|mts|cts)$/.test(o.resolved))return s;let a=s.match(/[?#].*$/)?.[0]??"",c=a?s.slice(0,-a.length):s,f=om(c),u=/^(?:\.js|\.jsx|\.mjs|\.cjs)$/.test(f)?f:"";return mm(n,Or(o.resolved,r),u)+a};return e.replace(/\b(from\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,o,a,c)=>`${o}${a}${i(c)}${a}`).replace(/\b(import\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,o,a,c)=>`${o}${a}${i(c)}${a}`).replace(/\b(import\s*\(\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,o,a,c)=>`${o}${a}${i(c)}${a}`)}async function gm(e,t,r,n,i){let s=t;if(n)s=await n.runOnBeforeFile(e,t);let o=Di(s,e,r.keepComments,r.isolatedDeclarations??!1);if(n)o=await n.runOnDeclarations(e,s,o);let a=0,c=0;for(let u=0;u<o.length;u++){let l=o[u];if(l.kind==="import")a++;if(l.kind==="export"||l.isExported)c++}let f=Ll(o,{filePath:e,sourceCode:s,declarations:o},r.keepComments,r.importOrder);if(f=pm(f,e,r),i)f=Rl(f,i,{filePath:e});if(r.normalizeOutput===!0||r.declarationOrder)f=bl(f,{lineEnding:"lf",declarationOrder:r.declarationOrder,indent:{style:r.indentStyle??"spaces",size:r.indentSize??2}});if(n)f=await n.runOnAfterFile(e,s,f);return{content:f,declarationCount:o.length,importCount:a,exportCount:c}}var Jl,lm=50,Tr;var Yl=ce(()=>{Ds();Gs();ka();gl();Cl();ma();El();Al();Ol();Hs();fs();Da();Gl();Hl();$i();({Glob:Jl}=globalThis.Bun);Tr=new Map});var Zl=ce(()=>{Yl()});var rc={};Cc(rc,{DtsxPluginError:()=>ar,PluginErrorCodes:()=>bm,clearCache:()=>Om,default:()=>Pm,dts:()=>ws,dtsCheck:()=>Rm,dtsWatch:()=>Tm});import{createHash as Cm}from"crypto";import{existsSync as wm,readFileSync as $m,writeFileSync as Em}from"fs";import{dirname as vm,join as Sm,relative as ql,resolve as or,sep as Bi}from"path";import zl from"process";class Ql{listeners=new Map;on(e,t){let r=this.listeners.get(e)||[];r.push(t),this.listeners.set(e,r)}async emit(e,t){let r={type:e,timestamp:Date.now(),data:t},n=this.listeners.get(e)||[];for(let i of n)await i(r)}}class Cs{manifest;cacheDir;manifestPath;constructor(e,t){this.cacheDir=e,this.manifestPath=Sm(e,"manifest.json"),this.manifest=this.loadManifest(t)}loadManifest(e){try{if(wm(this.manifestPath)){let t=JSON.parse($m(this.manifestPath,"utf-8"));if(t.configHash===e&&t.version==="1.0")return t}}catch{}return{version:"1.0",configHash:e,entries:{}}}save(){try{let{mkdirSync:e}=ym("fs");e(this.cacheDir,{recursive:!0}),Em(this.manifestPath,JSON.stringify(this.manifest,null,2))}catch{}}getEntry(e){return this.manifest.entries[e]}setEntry(e,t){this.manifest.entries[e]=t}isValid(e,t){return this.getEntry(e)?.hash===t}clear(){this.manifest.entries={},this.save()}}function Am(e){let t={root:e.root,outdir:e.outdir,entrypoints:e.entrypoints,clean:e.clean,tsconfigPath:e.tsconfigPath};return Cm("md5").update(JSON.stringify(t)).digest("hex")}function ws(e={}){let{onSuccess:t,onError:r,failOnError:n=!0,incremental:i=!1,cacheDir:s=".dtsx-cache",on:o,timeout:a=60000,continueOnError:c=!1,verbose:f=!1,...u}=e,l=new Ql;if(o){for(let[g,d]of Object.entries(o))if(d)l.on(g,d)}return{name:"bun-plugin-dtsx",async setup(g){let d=Date.now(),E=null,S=0;try{let C=tc(u,g),T=Am(C);if(C.clean){let V=or(C.cwd??zl.cwd(),C.outdir??"./dist");if(Xl.has(V))C.clean=!1;else Xl.add(V)}if(i)E=new Cs(or(s),T);if(await l.emit("start",{type:"start",files:C.entrypoints||[],config:C}),f){if(console.log("[bun-plugin-dtsx] Starting declaration generation..."),i)console.log("[bun-plugin-dtsx] Incremental mode enabled")}let O=await(async()=>new Promise((V,L)=>{let R=setTimeout(()=>{L(new ar(`Generation timed out after ${a}ms`,"TIMEOUT_ERROR",{timeout:a}))},a);Gi(C).then((F)=>{clearTimeout(R),V(F)}).catch((F)=>{clearTimeout(R),L(F)})}))(),I=Date.now()-d;if(E)E.save();if(await l.emit("complete",{type:"complete",stats:O,duration:I,fromCache:S}),f){if(console.log(`[bun-plugin-dtsx] Generation complete in ${I}ms`),S>0)console.log(`[bun-plugin-dtsx] ${S} files served from cache`)}if(t)await t(O)}catch(C){let T=ec(C);if(await l.emit("error",{type:"error",error:T}),r)await r(T);else{if(console.error("[bun-plugin-dtsx] Error generating declarations:"),console.error(` Code: ${T.code}`),console.error(` Message: ${T.message}`),T.context)console.error(` Context: ${JSON.stringify(T.context)}`);if(f&&T.stack)console.error(` Stack: ${T.stack}`)}if(n&&!c)throw T}}}}function ec(e){if(e instanceof ar)return e;if(e instanceof Error){let t="GENERATION_ERROR";if(e.message.includes("config")||e.message.includes("Config"))t="CONFIG_ERROR";else if(e.message.includes("file")||e.message.includes("File")||e.message.includes("ENOENT"))t="FILE_ERROR";return new ar(e.message,t,{originalError:e.name},e)}return new ar(String(e),"GENERATION_ERROR")}function xm(e){let t=e.map((n)=>vm(n).split(Bi)),r=t[0];for(let n of t.slice(1)){let i=0;while(i<r.length&&i<n.length&&r[i]===n[i])i++;r=r.slice(0,i)}return r.join(Bi)||Bi}function tc(e,t){let r=e.cwd||zl.cwd(),n=t?.config?.entrypoints,i=e.outdir||e.build?.config.outdir||t?.config.outdir||"./dist",s=e.root||e.build?.config.root||t?.config.root;if(!s&&n?.length){let a=xm(n.map((c)=>or(r,c)));s=ql(r,a)||"."}s=s||"./src";let o=e.entrypoints;if(!o)if(n?.length){let a=or(r,s),c=[];for(let f of n){let u=or(r,f);if(u===a||u.startsWith(a+Bi))c.push(ql(a,u));else console.warn(`[bun-plugin-dtsx] Skipping entrypoint outside root "${s}": ${f}`)}o=c.length?c:["index.ts"]}else o=["index.ts"];return{...e,cwd:r,root:s,entrypoints:o,outdir:i,clean:e.clean??!0,tsconfigPath:e.tsconfigPath}}function Tm(e={}){return ws({...e,incremental:!0,verbose:e.verbose??!0})}function Rm(e){return{name:"bun-plugin-dtsx-check",async setup(t){let r=tc({...e,outdir:""},t);try{await Gi({...r,clean:!1})}catch(n){let i=ec(n);if(e.onError)await e.onError(i);if(e.failOnError!==!1)throw i}}}}function Om(e=".dtsx-cache"){new Cs(or(e),"").clear()}var ym,bm,ar,Xl,Pm;var ic=ce(()=>{Zl();ym=import.meta.require,bm={CONFIG_ERROR:"CONFIG_ERROR",GENERATION_ERROR:"GENERATION_ERROR",FILE_ERROR:"FILE_ERROR",CACHE_ERROR:"CACHE_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR"};ar=class ar extends Error{code;context;cause;constructor(e,t,r,n){super(e);if(this.name="DtsxPluginError",this.code=t,this.context=r,this.cause=n,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,context:this.context,stack:this.stack}}};Xl=new Set;Pm=ws});import{mkdir as km,stat as Mm}from"fs/promises";import{bold as $s,dim as Es,green as Dm,italic as nc,log as Im}from"@stacksjs/cli";import{path as ot}from"@stacksjs/path";import{glob as sc}from"@stacksjs/storage";async function Fm(e){let t=await sc([ot.resolve(e,"dist","**/*.d.ts")],{absolute:!0}),r=new Bun.Transpiler({loader:"ts",target:"bun"});for(let n of t){let i=await Bun.file(n).text();try{r.transformSync(i)}catch(s){throw Error(`Invalid declaration generated at ${n}: ${s instanceof Error?s.message:String(s)}`)}}}async function Nm(e){let t=ot.resolve(e,"dist","index.js");if(!await Bun.file(t).exists())return;let r=Bun.spawnSync({cmd:[process.execPath,"-e",`await import(${JSON.stringify(t)})`],stdout:"ignore",stderr:"pipe",env:{...process.env,NODE_ENV:"test"}});if(r.exitCode===0)return;let n=new TextDecoder().decode(r.stderr??new Uint8Array);if(/needs to refer to a top-level declared variable|does not provide an export named|Export named .* not found/i.test(n))throw Error(`Built package at ${t} cannot be imported: ${n.trim().split(`
|
|
231
231
|
`)[0]}
|
|
232
|
-
This is the minified-barrel failure. Build with \`transpilePackage\` instead of a minifying \`Bun.build\`.`)}async function
|
|
232
|
+
This is the minified-barrel failure. Build with \`transpilePackage\` instead of a minifying \`Bun.build\`.`)}async function R0(e){let r=Date.now()-e.startTime,n=e.pkgName??`@stacksjs/${ot.basename(e.dir)}`;if(e.result.errors&&e.result.errors.length>0)throw console.error("Build errors:",e.result.errors),Error(`Build failed with errors: ${JSON.stringify(e.result.errors)}`);else if(e.result.success!==void 0&&!e.result.success){let s=e.result.logs?.[0]||"Unknown build error";throw console.log(s),Error(`Build failed: ${s}`)}await Fm(e.dir),await Nm(e.dir);let i=await sc([ot.resolve(e.dir,"dist","**/*")],{absolute:!0});for(let s of i){let o=await Mm(s),a;if(o.size<1048576)a=`${(o.size/1024).toFixed(2)}kb`;else a=`${(o.size/1024/1024).toFixed(2)}mb`;let c=ot.relative(e.dir,s).replace("dist/","");console.log(`${$s(Es(`[${a}]`))} ${Es("dist/")}${c}`)}console.log(`${$s(Es(`[${r}ms]`))} Built ${nc($s(Dm(n)))}`)}async function O0(e){let t=e.pkgName??`@stacksjs/${ot.basename(e.dir)}`;if(e.styled===!1)console.log(`Building ${t}...`);else Im.info(`Building ${nc(t)}...`);return{startTime:Date.now()}}async function P0(e){let{dts:t}=await Promise.resolve().then(() => (ic(),rc)),r=ot.resolve(e.dir,"src"),n=ot.resolve(e.dir,"dist"),i=(await Array.fromAsync(new Bun.Glob("**/*.ts").scan({cwd:r}))).filter((o)=>!o.endsWith(".d.ts")).filter((o)=>!o.endsWith(".test.ts")&&!o.endsWith(".spec.ts"));await Bun.build({entrypoints:i.map((o)=>ot.resolve(r,o)),outdir:n,root:r,target:"bun",format:"esm",splitting:!1,external:e.external??Wm(),plugins:[t({root:r,outdir:n})]});let s=new Bun.Transpiler({loader:"ts",target:"bun",minifyWhitespace:!0});for(let o of i){let a=s.transformSync(await Bun.file(ot.resolve(r,o)).text());a=a.replace(/(['"])(\.\.?\/[^'"]+?)\.tsx?\1/g,"$1$2.js$1");let c=ot.resolve(n,o.replace(/\.ts$/,".js"));await km(ot.dirname(c),{recursive:!0}),await Bun.write(c,a)}}function Wm(e=[]){let t=[];try{let r=Xe("fs"),n=JSON.parse(r.readFileSync(`${process.cwd()}/package.json`,"utf8"));t=[...Object.keys(n.dependencies??{}),...Object.keys(n.peerDependencies??{}),...Object.keys(n.optionalDependencies??{})]}catch{}return["@stacksjs/*",...t,...t.map((r)=>`${r}/*`),"bun-queue","ioredis","localtunnels","localtunnels/*","@craft-native/ts","ts-md","meilisearch","algoliasearch","@opensearch-project/opensearch","*.yaml","*.yml",...e]}export{Wm as frameworkExternal,O0 as intro,R0 as outro,P0 as transpilePackage,Fm as validateDeclarations,Nm as validateRuntimeExports};
|