@stacksjs/build 0.70.326 → 0.70.328

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.
Files changed (2) hide show
  1. package/dist/index.js +159 -154
  2. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -1,164 +1,169 @@
1
1
  // @bun
2
- var sf=Object.defineProperty;var of=(e)=>e;function af(e,t){this[e]=of.bind(null,t)}var lf=(e,t)=>{for(var r in t)sf(e,r,{get:t[r],enumerable:!0,configurable:!0,set:af.bind(t,r)})};var de=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ze=import.meta.require;import{readFile as ff,stat as Am,writeFile as cf}from"fs/promises";async function Ss(e,t){if(Tr)return globalThis.Bun.write(e,t);let r=typeof t==="string"?t:t instanceof ArrayBuffer?Buffer.from(t):t;return await cf(e,r),typeof t==="string"?Buffer.byteLength(t):t.byteLength}async function ct(e){if(Tr)return globalThis.Bun.file(e).text();return ff(e,"utf-8")}var Tr,vm;var Rr=de(()=>{Tr=typeof globalThis.Bun<"u",vm=!Tr&&typeof process<"u"&&!!process.versions?.node});import{existsSync as uf,statSync as hf}from"fs";import{dirname as df,extname as mf,isAbsolute as Gi,resolve as gf}from"path";function Wr(e){try{return hf(e).isFile()}catch{return!1}}function Nr(e,t){let r=e.replace(/[?#].*$/,"");if(!(r.startsWith("./")||r.startsWith("../")||r==="."||r==="..")&&!Gi(r))return{resolved:null,isRelative:!1};let n=df(t),i=Gi(r)?r:gf(n,r);if(Wr(i))return{resolved:i,isRelative:!0};let s=mf(i),o=pf[s];if(o){let a=i.slice(0,-s.length);for(let f of o){let c=a+f;if(Wr(c))return{resolved:c,isRelative:!0}}}for(let a of Ts){let f=i+a;if(Wr(f))return{resolved:f,isRelative:!0}}if(uf(i))for(let a of Ts){let f=`${i}/index${a}`;if(Wr(f))return{resolved:f,isRelative:!0}}return{resolved:null,isRelative:!0}}function yf(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 f=e[n++];r+=s===96?f===`
3
- `||f==="\r"?f:" ":f;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 Vi(e,t={}){let r=[],n=yf(e);Rs.lastIndex=0;let i;while((i=Rs.exec(n))!==null){let s=!!i[1],o=i[3],a=i[0],f;if(a.includes("* as "))f="export-star-as";else if(a.includes("*"))f="export-star";else f="export-named";r.push({specifier:o,kind:f,isTypeOnly:s})}if(t.includeImports){Ws.lastIndex=0;while((i=Ws.exec(n))!==null)r.push({specifier:i[3],kind:"import",isTypeOnly:!!i[1]})}return r}async function Zi(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 ct(o)}catch{continue}let f=Vi(a,t);n.set(o,f);for(let c of f){if(!(c.specifier.startsWith(".")||Gi(c.specifier)))continue;let u=Nr(c.specifier,o);if(u.resolved){if(!r.has(u.resolved))r.add(u.resolved),s.push(u.resolved)}else i.push({from:o,specifier:c.specifier,isTypeOnly:c.isTypeOnly})}}return{reachable:r,reExports:n,unresolved:i}}var Ts,pf,Rs,Ws;var Ns=de(()=>{Rr();Ts=[".ts",".tsx",".mts",".cts",".vue",".stx",".js",".jsx",".mjs",".cjs",".d.ts",".d.mts",".d.cts"],pf={".js":[".ts",".tsx",".d.ts"],".jsx":[".tsx",".ts",".d.ts"],".mjs":[".mts",".d.mts"],".cjs":[".cts",".d.cts"]};Rs=/(?:^|[\n;{}])\s*export\s+(type\s+)?(?:\*(?:\s+as\s+\w+)?|\{[^}]*\})\s+from\s+(['"])([^'"]+)\2/g,Ws=/(?:^|[\n;{}])\s*import\s+(type\s+)?(?:[^'";\n]+\s+from\s+)?(['"])([^'"]+)\2/g});function Ds(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:f,importGrouping:c,preserveComments:u=!0,insertFinalNewline:l=!0}=t,p=e;if(p=Cf(p,r),c?.enabled!==!1)p=Ef(p,c||{});if(f)p=Of(p,f);if(s)p=bf(p);if(p=Af(p,i),o)p=xf(p,a);if(n||l)p=vf(p);return p}function Cf(e,t){let r=e;if(e.indexOf("\r")!==-1){if(e.indexOf(`\r
2
+ var cc=Object.defineProperty;var fc=(e)=>e;function uc(e,t){this[e]=fc.bind(null,t)}var hc=(e,t)=>{for(var r in t)cc(e,r,{get:t[r],enumerable:!0,configurable:!0,set:uc.bind(t,r)})};var ae=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ye=import.meta.require;class Or{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)},a=await i.onDeclarations(s);if(a)n=a}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)},a=await i.onAfterFile(s);if(typeof a==="string")n=a}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 dc(e){return e}var Mm,Im;var Rs=ae(()=>{Mm=new Or;Im=dc({name:"strip-internal",version:"1.0.0",description:"Removes declarations marked with @internal",onDeclarations:(e)=>{return 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})}})});import{readFile as mc,stat as Nm,writeFile as pc}from"fs/promises";async function Os(e,t){if(Pr)return globalThis.Bun.write(e,t);let r=typeof t==="string"?t:t instanceof ArrayBuffer?Buffer.from(t):t;return await pc(e,r),typeof t==="string"?Buffer.byteLength(t):t.byteLength}async function ct(e){if(Pr)return globalThis.Bun.file(e).text();return mc(e,"utf-8")}var Pr,Lm;var kr=ae(()=>{Pr=typeof globalThis.Bun<"u",Lm=!Pr&&typeof process<"u"&&!!process.versions?.node});import{existsSync as gc,statSync as yc}from"fs";import{dirname as Cc,extname as wc,isAbsolute as Ji,resolve as $c}from"path";function Mr(e){try{return yc(e).isFile()}catch{return!1}}function Ir(e,t){let r=e.replace(/[?#].*$/,"");if(!(r.startsWith("./")||r.startsWith("../")||r==="."||r==="..")&&!Ji(r))return{resolved:null,isRelative:!1};let n=Cc(t),i=Ji(r)?r:$c(n,r);if(Mr(i))return{resolved:i,isRelative:!0};let s=wc(i),a=Ec[s];if(a){let o=i.slice(0,-s.length);for(let c of a){let f=o+c;if(Mr(f))return{resolved:f,isRelative:!0}}}for(let o of Ps){let c=i+o;if(Mr(c))return{resolved:c,isRelative:!0}}if(gc(i))for(let o of Ps){let c=`${i}/index${o}`;if(Mr(c))return{resolved:c,isRelative:!0}}return{resolved:null,isRelative:!0}}function vc(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 a=e.charCodeAt(n),o=e[n++];if(r+=s===96&&a!==s?a===10||a===13?o:" ":o,a===92&&n<t){let c=e[n++];r+=s===96?c===`
3
+ `||c==="\r"?c:" ":c;continue}if(a===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 Ui(e,t={}){let r=[],n=vc(e);ks.lastIndex=0;let i;while((i=ks.exec(n))!==null){let s=!!i[1],a=i[3],o=i[0],c;if(o.includes("* as "))c="export-star-as";else if(o.includes("*"))c="export-star";else c="export-named";r.push({specifier:a,kind:c,isTypeOnly:s})}if(t.includeImports){Ms.lastIndex=0;while((i=Ms.exec(n))!==null)r.push({specifier:i[3],kind:"import",isTypeOnly:!!i[1]})}return r}async function Yi(e,t={}){let r=new Set,n=new Map,i=[],s=[];for(let a of e)if(!r.has(a))r.add(a),s.push(a);while(s.length>0){let a=s.shift(),o;try{o=await ct(a)}catch{continue}let c=Ui(o,t);n.set(a,c);for(let f of c){if(!(f.specifier.startsWith(".")||Ji(f.specifier)))continue;let u=Ir(f.specifier,a);if(u.resolved){if(!r.has(u.resolved))r.add(u.resolved),s.push(u.resolved)}else i.push({from:a,specifier:f.specifier,isTypeOnly:f.isTypeOnly})}}return{reachable:r,reExports:n,unresolved:i}}var Ps,Ec,ks,Ms;var Is=ae(()=>{kr();Ps=[".ts",".tsx",".mts",".cts",".vue",".stx",".js",".jsx",".mjs",".cjs",".d.ts",".d.mts",".d.cts"],Ec={".js":[".ts",".tsx",".d.ts"],".jsx":[".tsx",".ts",".d.ts"],".mjs":[".mts",".d.mts"],".cjs":[".cts",".d.cts"]};ks=/(?:^|[\n;{}])\s*export\s+(type\s+)?(?:\*(?:\s+as\s+\w+)?|\{[^}]*\})\s+from\s+(['"])([^'"]+)\2/g,Ms=/(?:^|[\n;{}])\s*import\s+(type\s+)?(?:[^'";\n]+\s+from\s+)?(['"])([^'"]+)\2/g});function Ns(e,t={}){let{lineEnding:r="lf",trailingNewline:n=!0,maxBlankLines:i=1,trimTrailingWhitespace:s=!0,normalizeIndentation:a=!0,indent:o={style:"spaces",size:2},declarationOrder:c,importGrouping:f,preserveComments:u=!0,insertFinalNewline:l=!0}=t,g=e;if(g=Ac(g,r),f?.enabled!==!1)g=Pc(g,f||{});if(c)g=kc(g,c);if(s)g=xc(g);if(g=Tc(g,i),a)g=Oc(g,o);if(n||l)g=Rc(g);return g}function Ac(e,t){let r=e;if(e.indexOf("\r")!==-1){if(e.indexOf(`\r
4
4
  `)!==-1)r=r.replace(/\r\n/g,`
5
5
  `);if(r.indexOf("\r")!==-1)r=r.replace(/\r/g,`
6
6
  `)}if(t==="crlf")r=r.replace(/\n/g,`\r
7
- `);return r}function bf(e){return e.split(`
7
+ `);return r}function xc(e){return e.split(`
8
8
  `).map((t)=>t.replace(/[\t ]+$/,"")).join(`
9
- `)}function Af(e,t){let r=new RegExp(`\\n{${t+2},}`,"g");return e.replace(r,`
10
- `.repeat(t+1))}function vf(e){return`${e.replace(/\s+$/,"")}
11
- `}function xf(e,t){let{style:r="spaces",size:n=2}=t,i=r==="tabs"?"\t":" ".repeat(n),s=e.split(`
12
- `),o=[];for(let a of s){let f=a.match(/^([\t ]*)(.*)$/);if(!f){o.push(a);continue}let[,c,u]=f;if(!u){o.push("");continue}let l=c.replace(/\t/g," "),p=Math.floor(l.length/2);o.push(i.repeat(p)+u)}return o.join(`
13
- `)}function Ef(e,t){let{groups:r=wf,separateGroups:n=!0,alphabetize:i=!0}=t,s=e.split(`
14
- `),o=[],a=[],f=-1;for(let w=0;w<s.length;w++){let A=s[w],$=Fs(A);if($)o.push({line:A,source:$.source,group:$.group,isType:$.isType}),f=w;else if(o.length>0&&A.trim()==="")continue;else if(o.length>0||A.trim()!==""){if(o.length===0||w>f+1)a.push(A)}}if(o.length===0)return e;let c=new Map;for(let w of r)c.set(w,[]);for(let w of o)(c.get(w.group)||c.get("external")||[]).push(w);if(i)for(let[,w]of c)w.sort((A,$)=>{if(A.isType!==$.isType)return A.isType?1:-1;return A.source.localeCompare($.source)});let u=[],l=null;for(let w of r){let A=c.get(w)||[];if(A.length===0)continue;if(n&&l!==null)u.push("");for(let $ of A)u.push($.line);l=w}let p=s.slice(0,s.findIndex((w)=>Fs(w)!==null)),h=a;while(h.length>0&&h[0].trim()==="")h.shift();return[...p,...u,"",...h].join(`
15
- `)}function Fs(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:Ps(s[1]),isType:!1};return null}let n=!!r[1],i=r[2];return{source:i,group:n?"type":Ps(i),isType:n}}function Ps(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 Of(e,t){let{kinds:r=$f,alphabetize:n=!1,groupExports:i=!0}=t,s=e.split(`
16
- `),o=[],a=[],f=[],c=null,u=0,l=!0,p=!1,h=[];for(let $=0;$<s.length;$++){let O=s[$],T=O.trim(),S=u,W=T.startsWith("///"),b=S===0&&!W&&(T.startsWith("//")||T.startsWith("/*"));if(p||b){if(h.push(O),!p&&T.startsWith("/*")&&!T.includes("*/"))p=!0;else if(p&&T.includes("*/"))p=!1;continue}if(S===0&&h.length>0&&T===""){h.push(O);continue}u+=(O.match(/\{/g)||[]).length,u-=(O.match(/\}/g)||[]).length;let L=kf(T);if(l&&L&&L.kind!=="import"&&!T.startsWith("//")&&!T.startsWith("/*"))l=!1;if(l){if(h.length>0){if(L?.kind==="import"||!L)a.push(...h),h.length=0}a.push(O);continue}if(L&&u<=1){if(c)o.push(c);c={lines:h.length>0?[...h,O]:[O],kind:L.kind,name:L.name,isExport:L.isExport},h.length=0}else if(c)c.lines.push(O);else{if(T==="")continue;f.push(O)}}if(c)o.push(c);if(h.length>0)f.push(...h);o.sort(($,O)=>{if(i&&$.isExport!==O.isExport)return $.isExport?-1:1;let T=r.indexOf($.kind),S=r.indexOf(O.kind),W=T>=0?T:r.length,b=S>=0?S:r.length;if(W!==b)return W-b;if(n)return $.name.localeCompare(O.name);return 0});let w=[...a],A=null;for(let $ of o){if(A!==null&&$.kind!==A)w.push("");w.push(...$.lines),A=$.kind}if(f.length>0)w.push(""),w.push(...f);return w.join(`
17
- `)}function kf(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 $f,wf;var Ms=de(()=>{$f=["import","type","interface","enum","class","function","variable","export","module","namespace","unknown"],wf=["builtin","external","scoped","internal","parent","sibling","index","type"]});class Fr{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 Sf(e){return e}var Rm,Wm;var Is=de(()=>{Rm=new Fr;Wm=Sf({name:"strip-internal",version:"1.0.0",description:"Removes declarations marked with @internal",onDeclarations:(e)=>{return 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 Tf(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 Qi(){Ir=!0,_e=null}function en(){Ir=!1;let e=_e;return _e=null,e}function tn(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 Rf(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 qi(e,t){let r=0,n=0;while((n=e.indexOf(t,n))!==-1)r++,n+=t.length;return r}function Bs(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 Pr(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&&Bs(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&&Bs(t.charCodeAt(a)))a++;return t.slice(o+2,a)===i&&t.charCodeAt(a)===62&&a===t.length-1}function ar(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 Ee(e,t=!1,r=!1,n=0){if(!e||typeof e!=="string")return"unknown";if(n>=20)return"unknown";let i=e.trim();if(Pr(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(`
18
- `)||i.includes("\r"))return"string";return i}if(i.charCodeAt(0)===39||i.charCodeAt(0)===34){let o=Wf(i);if(o!==null){if(o==="string"||!t)return"string";return o}}if(tn(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 Ui(i,t,n+1);if(i.startsWith("{")&&i.endsWith("}"))return Hf(i,t,n+1);if(i.startsWith("class ")||i.startsWith("class{"))return Jf(i);if(i.startsWith("new "))return _f(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 f=Dr(a),c=[];for(let u=0;u<f.length;u++)c.push(Ee(f[u].trim(),!0,!1,n+1));return`readonly [${c.join(", ")}]`}return Ee(o,!0,r,n+1)}if(Mr(i)!==-1||i.startsWith("function")||i.startsWith("async"))return Us(i,r,n,t);if(i.startsWith("`")&&i.endsWith("`"))return jf(i,t);if(i.startsWith("Promise."))return Gs(i,t,n);if(i.startsWith("await "))return"unknown";if(i.charCodeAt(i.length-1)===110&&i.length>1&&Rf(i)){if(t)return i;return"bigint"}if(i.startsWith("Symbol(")||i==="Symbol.for")return"symbol";let s=Vs(i);if(s!==null)return s;if(Mf(i))return"boolean";if(Df(i))return"number";return"unknown"}function Ls(e){let t=e.charCodeAt(0);if(t!==39&&t!==34)return!1;return Tt(e,0,t)===e.length}function Wf(e){if(Ls(e))return e;let t=Nf(e);if(t.length<2)return null;let r=!1,n=!0,i="";for(let s of t){let o=s.trim();if(Ls(o))r=!0,i+=Ff(o);else n=!1}if(n)return Pf(i);if(r)return"string";return null}function Nf(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=Tt(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 Ff(e){return e.slice(1,-1).replace(/\\(.)/g,(t,r)=>{if(r==="n")return`
19
- `;if(r==="t")return"\t";if(r==="r")return"\r";if(r==="0")return"\x00";return r})}function Pf(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function Df(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 Mf(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=Tt(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 If(e,t=!1,r=0){return Ee(e,t,!0,r)}function lr(e,t=!1,r=""){let n=Hs(r),i=[],s=!1,o=0;while(o<e.length){let f=e.charCodeAt(o);if(f===34||f===39||f===96){o=Tt(e,o,f);continue}if(f===47&&e.charCodeAt(o+1)===47){o+=2;while(o<e.length&&e.charCodeAt(o)!==10&&e.charCodeAt(o)!==13)o++;continue}if(f===47&&e.charCodeAt(o+1)===42){let c=e.indexOf("*/",o+2);o=c===-1?e.length:c+2;continue}if(e.startsWith("function",o)&&js(e,o,8)||e.startsWith("class",o)&&js(e,o,5)){let c=Lf(e,o);if(c!==-1){o=_s(e,c);continue}}if(f===61&&e.charCodeAt(o+1)===62){let c=o+2;while(c<e.length&&e.charCodeAt(c)<=32)c++;if(e.charCodeAt(c)===123){o=_s(e,c);continue}}if(e.startsWith("return",o)&&(o===0||!rt(e.charCodeAt(o-1)))&&!rt(e.charCodeAt(o+6))){o+=6;let c=!1;while(o<e.length&&e.charCodeAt(o)<=32){let $=e.charCodeAt(o);if($===10||$===13)c=!0;o++}if(c||o>=e.length||e.charCodeAt(o)===59||e.charCodeAt(o)===125){s=!0;continue}let u=o,l=0,p=0,h=0;while(o<e.length){let $=e.charCodeAt(o);if($===34||$===39||$===96){o=Tt(e,o,$);continue}if($===47&&e.charCodeAt(o+1)===47)break;if($===47&&e.charCodeAt(o+1)===42){let O=e.indexOf("*/",o+2);o=O===-1?e.length:O+2;continue}if($===40)l++;else if($===41)l--;else if($===91)p++;else if($===93)p--;else if($===123)h++;else if($===125){if(h===0&&l===0&&p===0)break;h--}else if($===59&&l===0&&p===0&&h===0)break;else if(($===10||$===13)&&l===0&&p===0&&h===0){let O=o+1;while(O<e.length&&e.charCodeAt(O)<=32)O++;if(e.startsWith("return",O)&&!rt(e.charCodeAt(O+6)))break}o++}let w=e.slice(u,o).trim(),A=St(w,n);if(!i.includes(A))i.push(A);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 Hs(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 f=r.slice(n,o).trim(),c=f.indexOf(":");if(c!==-1){let u=f.slice(0,c).trim().replace(/^\.\.\./,"").replace(/\?$/,""),l=f.slice(c+1).trim(),p=l.indexOf("=");if(p!==-1)l=l.slice(0,p).trim();if(fr(u)&&l)t.set(u,l)}n=o+1}return t}function St(e,t){let r=e.trim();while(Ys(r))r=r.slice(1,-1).trim();if(Pr(r))return"JSX.Element";if(r.startsWith("await ")){let s=St(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=Bf(r);if(n){let s=St(n.whenTrue,t),o=St(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=St(r.slice(0,s),t),f=St(r.slice(s+1),t);if(o===43&&(a==="string"||f==="string"))return"string";if(a==="number"&&f==="number")return"number";break}}return Ee(r,!1).replace(/\btypeof\s+[$A-Z_a-z][$\w]*/g,(s)=>{let o=s.slice(7);return t.get(o)??"unknown"})}function Ys(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 Bf(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 js(e,t,r){return(t===0||!rt(e.charCodeAt(t-1)))&&!rt(e.charCodeAt(t+r))}function Lf(e,t){for(let r=t;r<e.length;r++){let n=e.charCodeAt(r);if(n===34||n===39||n===96){r=Tt(e,r,n)-1;continue}if(n===123)return r;if(n===59)return-1}return-1}function _s(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=Tt(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 Tt(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 jf(e,t){if(e.includes(".raw`")||e.includes("String.raw`"))return"string";if(!t||e.includes("${")||e.includes(`
20
- `)||e.includes("\r"))return"string";return e}function _f(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&&(rt(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 f=0,c=-1;for(let u=0;u<s.length;u++)if(s[u]==="<")f++;else if(s[u]===">"){if(f--,f===0){c=u;break}}if(c!==-1){let u=s.slice(0,c+1);o=s.slice(c+1);let l=o.indexOf("(");if(l!==-1){let p=0,h=-1;for(let w=l;w<o.length;w++)if(o[w]==="(")p++;else if(o[w]===")"){if(p--,p===0){h=w;break}}if(h!==-1){if(o.slice(h+1).trimStart().startsWith("."))return"unknown"}}return`${i}${u}`}}let a=o.indexOf("(");if(a!==-1){let f=0,c=-1;for(let u=a;u<o.length;u++)if(o[u]==="(")f++;else if(o[u]===")"){if(f--,f===0){c=u;break}}if(c!==-1){if(o.slice(c+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 Jf(e){let t=e.trimStart(),r=5;while(r<t.length&&t.charCodeAt(r)<=32)r++;let n=r;if(r<t.length&&rt(t.charCodeAt(r))){while(r<t.length&&rt(t.charCodeAt(r)))r++;return`typeof ${t.slice(n,r)}`}return"{ new (...args: any[]): any }"}function Gs(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<${Ee(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=Dr(s),a=[];for(let f=0;f<o.length;f++){let c=o[f].trim();if(c.startsWith("Promise.resolve(")){let u=Gs(c,t,r+1),l=u.indexOf("<"),p=u.lastIndexOf(">");a.push(l!==-1&&p>l?u.slice(l+1,p):"unknown")}else a.push(Ee(c,t,!1,r+1))}return`Promise<[${a.join(", ")}]>`}return"Promise<unknown[]>"}return"Promise<unknown>"}function Ui(e,t,r=0){let n=e.slice(1,-1).trim();if(!n)return"never[]";if(r>=20)return"unknown[]";let i=Dr(n),s=!1;for(let p=0;p<i.length;p++){let h=i[p],w=h.length;while(w>0&&h.charCodeAt(w-1)<=32)w--;if(w>=8&&h.slice(w-8,w)==="as const"){s=!0;break}}if(s){let p=[];for(let h=0;h<i.length;h++){let w=i[h].trim();if(w.endsWith("as const")){let A=w.slice(0,-8).trim();if(A.startsWith("[")&&A.endsWith("]")){let $=A.slice(1,-1).trim(),O=Dr($),T=[];for(let S=0;S<O.length;S++)T.push(Ee(O[S].trim(),!0,!1,r+1));p.push(`readonly [${T.join(", ")}]`)}else p.push(Ee(A,!0,!1,r+1))}else if(w.startsWith("[")&&w.endsWith("]"))p.push(Ui(w,!0,r+1));else p.push(Ee(w,!0,!1,r+1))}return`readonly [
21
- ${p.join(` |
9
+ `)}function Tc(e,t){let r=new RegExp(`\\n{${t+2},}`,"g");return e.replace(r,`
10
+ `.repeat(t+1))}function Rc(e){return`${e.replace(/\s+$/,"")}
11
+ `}function Oc(e,t){let{style:r="spaces",size:n=2}=t,i=r==="tabs"?"\t":" ".repeat(n),s=e.split(`
12
+ `),a=[];for(let o of s){let c=o.match(/^([\t ]*)(.*)$/);if(!c){a.push(o);continue}let[,f,u]=c;if(!u){a.push("");continue}let l=f.replace(/\t/g," "),g=Math.floor(l.length/2);a.push(i.repeat(g)+u)}return a.join(`
13
+ `)}function Pc(e,t){let{groups:r=Sc,separateGroups:n=!0,alphabetize:i=!0}=t,s=e.split(`
14
+ `),a=[],o=[],c=-1;for(let w=0;w<s.length;w++){let v=s[w],C=Ds(v);if(C)a.push({line:v,source:C.source,group:C.group,isType:C.isType}),c=w;else if(a.length>0&&v.trim()==="")continue;else if(a.length>0||v.trim()!==""){if(a.length===0||w>c+1)o.push(v)}}if(a.length===0)return e;let f=new Map;for(let w of r)f.set(w,[]);for(let w of a)(f.get(w.group)||f.get("external")||[]).push(w);if(i)for(let[,w]of f)w.sort((v,C)=>{if(v.isType!==C.isType)return v.isType?1:-1;return v.source.localeCompare(C.source)});let u=[],l=null;for(let w of r){let v=f.get(w)||[];if(v.length===0)continue;if(n&&l!==null)u.push("");for(let C of v)u.push(C.line);l=w}let g=s.slice(0,s.findIndex((w)=>Ds(w)!==null)),h=o;while(h.length>0&&h[0].trim()==="")h.shift();return[...g,...u,"",...h].join(`
15
+ `)}function Ds(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:Fs(s[1]),isType:!1};return null}let n=!!r[1],i=r[2];return{source:i,group:n?"type":Fs(i),isType:n}}function Fs(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 kc(e,t){let{kinds:r=bc,alphabetize:n=!1,groupExports:i=!0}=t,s=e.split(`
16
+ `),a=[],o=[],c=[],f=null,u=0,l=!0,g=!1,h=[];for(let C=0;C<s.length;C++){let x=s[C],O=x.trim(),R=u,k=O.startsWith("///"),E=R===0&&!k&&(O.startsWith("//")||O.startsWith("/*"));if(g||E){if(h.push(x),!g&&O.startsWith("/*")&&!O.includes("*/"))g=!0;else if(g&&O.includes("*/"))g=!1;continue}if(R===0&&h.length>0&&O===""){h.push(x);continue}u+=(x.match(/\{/g)||[]).length,u-=(x.match(/\}/g)||[]).length;let G=Mc(O);if(l&&G&&G.kind!=="import"&&!O.startsWith("//")&&!O.startsWith("/*"))l=!1;if(l){if(h.length>0){if(G?.kind==="import"||!G)o.push(...h),h.length=0}o.push(x);continue}if(G&&u<=1){if(f)a.push(f);f={lines:h.length>0?[...h,x]:[x],kind:G.kind,name:G.name,isExport:G.isExport},h.length=0}else if(f)f.lines.push(x);else{if(O==="")continue;c.push(x)}}if(f)a.push(f);if(h.length>0)c.push(...h);a.sort((C,x)=>{if(i&&C.isExport!==x.isExport)return C.isExport?-1:1;let O=r.indexOf(C.kind),R=r.indexOf(x.kind),k=O>=0?O:r.length,E=R>=0?R:r.length;if(k!==E)return k-E;if(n)return C.name.localeCompare(x.name);return 0});let w=[...o],v=null;for(let C of a){if(v!==null&&C.kind!==v)w.push("");w.push(...C.lines),v=C.kind}if(c.length>0)w.push(""),w.push(...c);return w.join(`
17
+ `)}function Mc(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 bc,Sc;var Ls=ae(()=>{bc=["import","type","interface","enum","class","function","variable","export","module","namespace","unknown"],Sc=["builtin","external","scoped","internal","parent","sibling","index","type"]});function Ic(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 Qi(){Lr=!0,Ve=null}function en(){Lr=!1;let e=Ve;return Ve=null,e}function tn(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 Dc(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 Zi(e,t){let r=0,n=0;while((n=e.indexOf(t,n))!==-1)r++,n+=t.length;return r}function Ws(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 Dr(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&&Ws(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 a=t.lastIndexOf("</");if(a===-1)return!1;let o=a+2;while(o<t.length&&Ws(t.charCodeAt(o)))o++;return t.slice(a+2,o)===i&&t.charCodeAt(o)===62&&o===t.length-1}function or(e){let t=e.length,r=!1;for(let a=1;a<t;a++)if(e.charCodeAt(a)<=32&&e.charCodeAt(a-1)<=32){r=!0;break}if(!r)for(let a=0;a<t;a++){let o=e.charCodeAt(a);if(o===10||o===13||o===9){r=!0;break}}if(!r)return e;let n=[],i=-1,s=!1;for(let a=0;a<t;a++)if(e.charCodeAt(a)<=32){if(!s){if(i>=0)n.push(e.substring(i,a));n.push(" "),s=!0,i=-1}}else{if(s||i<0)i=a;s=!1}if(i>=0)n.push(e.substring(i));return n.join("")}function Ae(e,t=!1,r=!1,n=0){if(!e||typeof e!=="string")return"unknown";if(n>=20)return"unknown";let i=e.trim();if(Dr(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(`
18
+ `)||i.includes("\r"))return"string";return i}if(i.charCodeAt(0)===39||i.charCodeAt(0)===34){let a=Fc(i);if(a!==null){if(a==="string"||!t)return"string";return a}}if(tn(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 qi(i,t,n+1);if(i.startsWith("{")&&i.endsWith("}"))return Yc(i,t,n+1);if(i.startsWith("class ")||i.startsWith("class{"))return Jc(i);if(i.startsWith("new "))return Kc(i);if(i.endsWith("as const")){let a=i.slice(0,-8).trim();if(a.startsWith("[")&&a.endsWith("]")){let o=a.slice(1,-1).trim();if(!o)return"readonly []";let c=Fr(o),f=[];for(let u=0;u<c.length;u++)f.push(Ae(c[u].trim(),!0,!1,n+1));return`readonly [${f.join(", ")}]`}return Ae(a,!0,r,n+1)}if(Nr(i)!==-1||i.startsWith("function")||i.startsWith("async"))return qs(i,r,n,t);if(i.startsWith("`")&&i.endsWith("`"))return jc(i,t);if(i.startsWith("Promise."))return Js(i,t,n);if(i.startsWith("await "))return"unknown";if(i.charCodeAt(i.length-1)===110&&i.length>1&&Dc(i)){if(t)return i;return"bigint"}if(i.startsWith("Symbol(")||i==="Symbol.for")return"symbol";let s=Us(i);if(s!==null)return s;if(Bc(i))return"boolean";if(Gc(i))return"number";return"unknown"}function Gs(e){let t=e.charCodeAt(0);if(t!==39&&t!==34)return!1;return Ot(e,0,t)===e.length}function Fc(e){if(Gs(e))return e;let t=Nc(e);if(t.length<2)return null;let r=!1,n=!0,i="";for(let s of t){let a=s.trim();if(Gs(a))r=!0,i+=Lc(a);else n=!1}if(n)return Wc(i);if(r)return"string";return null}function Nc(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=Ot(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 Lc(e){return e.slice(1,-1).replace(/\\(.)/g,(t,r)=>{if(r==="n")return`
19
+ `;if(r==="t")return"\t";if(r==="r")return"\r";if(r==="0")return"\x00";return r})}function Wc(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function Gc(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 Bc(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=Ot(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 Vc(e,t=!1,r=0){return Ae(e,t,!0,r)}function lr(e,t=!1,r=""){let n=js(r),i=[],s=!1,a=0;while(a<e.length){let c=e.charCodeAt(a);if(c===34||c===39||c===96){a=Ot(e,a,c);continue}if(c===47&&e.charCodeAt(a+1)===47){a+=2;while(a<e.length&&e.charCodeAt(a)!==10&&e.charCodeAt(a)!==13)a++;continue}if(c===47&&e.charCodeAt(a+1)===42){let f=e.indexOf("*/",a+2);a=f===-1?e.length:f+2;continue}if(e.startsWith("function",a)&&Bs(e,a,8)||e.startsWith("class",a)&&Bs(e,a,5)){let f=Hc(e,a);if(f!==-1){a=Vs(e,f);continue}}if(c===61&&e.charCodeAt(a+1)===62){let f=a+2;while(f<e.length&&e.charCodeAt(f)<=32)f++;if(e.charCodeAt(f)===123){a=Vs(e,f);continue}}if(e.startsWith("return",a)&&(a===0||!ft(e.charCodeAt(a-1)))&&!ft(e.charCodeAt(a+6))){a+=6;let f=!1;while(a<e.length&&e.charCodeAt(a)<=32){let C=e.charCodeAt(a);if(C===10||C===13)f=!0;a++}if(f||a>=e.length||e.charCodeAt(a)===59||e.charCodeAt(a)===125){s=!0;continue}let u=a,l=0,g=0,h=0;while(a<e.length){let C=e.charCodeAt(a);if(C===34||C===39||C===96){a=Ot(e,a,C);continue}if(C===47&&e.charCodeAt(a+1)===47)break;if(C===47&&e.charCodeAt(a+1)===42){let x=e.indexOf("*/",a+2);a=x===-1?e.length:x+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)h++;else if(C===125){if(h===0&&l===0&&g===0)break;h--}else if(C===59&&l===0&&g===0&&h===0)break;else if((C===10||C===13)&&l===0&&g===0&&h===0){let x=a+1;while(x<e.length&&e.charCodeAt(x)<=32)x++;if(e.startsWith("return",x)&&!ft(e.charCodeAt(x+6)))break}a++}let w=e.slice(u,a).trim(),v=Rt(w,n);if(!i.includes(v))i.push(v);continue}a++}if(s&&!i.includes("undefined"))i.push("undefined");let o=i.includes("unknown")?"unknown":i.length===0?"void":i.join(" | ");return t&&!o.startsWith("Promise<")?`Promise<${o}>`:o}function js(e){let t=new Map,r=e.startsWith("(")&&e.endsWith(")")?e.slice(1,-1):e,n=0,i=0,s=0;for(let a=0;a<=r.length;a++){let o=r.charCodeAt(a);if(o===40||o===91||o===123)i++;else if(o===41||o===93||o===125)i--;else if(o===60)s++;else if(o===62&&r.charCodeAt(a-1)!==61&&s>0)s--;if(a!==r.length&&(o!==44||i!==0||s!==0))continue;let c=r.slice(n,a).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(cr(u)&&l)t.set(u,l)}n=a+1}return t}function Rt(e,t){let r=e.trim();while(Ks(r))r=r.slice(1,-1).trim();if(Dr(r))return"JSX.Element";if(r.startsWith("await ")){let s=Rt(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=_c(r);if(n){let s=Rt(n.whenTrue,t),a=Rt(n.whenFalse,t);return s===a?s:`${s} | ${a}`}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 a=r.charCodeAt(s);if(a===41||a===93||a===125)i++;else if(a===40||a===91||a===123)i--;else if(i===0&&(a===43||a===45||a===42||a===47||a===37)){let o=Rt(r.slice(0,s),t),c=Rt(r.slice(s+1),t);if(a===43&&(o==="string"||c==="string"))return"string";if(o==="number"&&c==="number")return"number";break}}return Ae(r,!1).replace(/\btypeof\s+[$A-Z_a-z][$\w]*/g,(s)=>{let a=s.slice(7);return t.get(a)??"unknown"})}function Ks(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 _c(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 Bs(e,t,r){return(t===0||!ft(e.charCodeAt(t-1)))&&!ft(e.charCodeAt(t+r))}function Hc(e,t){for(let r=t;r<e.length;r++){let n=e.charCodeAt(r);if(n===34||n===39||n===96){r=Ot(e,r,n)-1;continue}if(n===123)return r;if(n===59)return-1}return-1}function Vs(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=Ot(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 Ot(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 jc(e,t){if(e.includes(".raw`")||e.includes("String.raw`"))return"string";if(!t||e.includes("${")||e.includes(`
20
+ `)||e.includes("\r"))return"string";return e}function Kc(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&&(ft(e.charCodeAt(t))||e.charCodeAt(t)===46))t++;if(t===r)return"unknown";let i=e.slice(r,t);{let s=e.slice(t),a=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);a=s.slice(f+1);let l=a.indexOf("(");if(l!==-1){let g=0,h=-1;for(let w=l;w<a.length;w++)if(a[w]==="(")g++;else if(a[w]===")"){if(g--,g===0){h=w;break}}if(h!==-1){if(a.slice(h+1).trimStart().startsWith("."))return"unknown"}}return`${i}${u}`}}let o=a.indexOf("(");if(o!==-1){let c=0,f=-1;for(let u=o;u<a.length;u++)if(a[u]==="(")c++;else if(a[u]===")"){if(c--,c===0){f=u;break}}if(f!==-1){if(a.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 Jc(e){return"{ new (...args: any[]): any }"}function Js(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<${Ae(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(),a=Fr(s),o=[];for(let c=0;c<a.length;c++){let f=a[c].trim();if(f.startsWith("Promise.resolve(")){let u=Js(f,t,r+1),l=u.indexOf("<"),g=u.lastIndexOf(">");o.push(l!==-1&&g>l?u.slice(l+1,g):"unknown")}else o.push(Ae(f,t,!1,r+1))}return`Promise<[${o.join(", ")}]>`}return"Promise<unknown[]>"}return"Promise<unknown>"}function qi(e,t,r=0){let n=e.slice(1,-1).trim();if(!n)return"never[]";if(r>=20)return"unknown[]";let i=Fr(n),s=!1;for(let g=0;g<i.length;g++){let h=i[g],w=h.length;while(w>0&&h.charCodeAt(w-1)<=32)w--;if(w>=8&&h.slice(w-8,w)==="as const"){s=!0;break}}if(s){let g=[];for(let h=0;h<i.length;h++){let w=i[h].trim();if(w.endsWith("as const")){let v=w.slice(0,-8).trim();if(v.startsWith("[")&&v.endsWith("]")){let C=v.slice(1,-1).trim(),x=Fr(C),O=[];for(let R=0;R<x.length;R++)O.push(Ae(x[R].trim(),!0,!1,r+1));g.push(`readonly [${O.join(", ")}]`)}else g.push(Ae(v,!0,!1,r+1))}else if(w.startsWith("[")&&w.endsWith("]"))g.push(qi(w,!0,r+1));else g.push(Ae(w,!0,!1,r+1))}return`readonly [
21
+ ${g.join(` |
22
22
  `)}
23
- ]`}let o=Ir&&!t,a=[],f=[];for(let p of i){let h=p.trim(),w=_e;if(_e=null,h.startsWith("...")){let A=h.slice(3).trim(),$=Ee(A,!1,!1,r+1);if($.endsWith("[]"))a.push($.slice(0,-2));else if($.startsWith("readonly [")&&$.endsWith("]"))a.push($.slice(10,-1));else if(cr(A))a.push(`(typeof ${A})[number]`);else a.push("unknown")}else if(h.startsWith("[")&&h.endsWith("]"))a.push(Ui(h,t,r+1));else a.push(If(h,t,r+1));if(o)f.push(_e);_e=w}if(o)if(zi(e))_e=ar(e);else{let p=[];for(let h=0;h<i.length;h++){let w=i[h].trim();if(w.endsWith("as const"))continue;if(Xi(w)||w==="null"||w==="undefined")p.push(w);else if(w.startsWith("[")&&zi(w))p.push(ar(w));else if(w.startsWith("{")){if(f[h])p.push(f[h])}else{let A=Ee(w,!1,!1,0);if(A!=="unknown")p.push(A)}}if(p.length>0)_e=`[${p.join(", ")}]`}if(t)return`readonly [${a.join(", ")}]`;let c=new Set,u=[],l=!0;for(let p of a){if(!c.has(p))c.add(p),u.push(p);if(l){if(!(tn(p)||p==="true"||p==="false"||p.charCodeAt(0)===34&&p.charCodeAt(p.length-1)===34||p.charCodeAt(0)===39&&p.charCodeAt(p.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 Dr(e){let t=[],r=0,n=0,i=!1,s=0;for(let a=0;a<e.length;a++){let f=e.charCodeAt(a);if(!i&&(f===34||f===39||f===96))i=!0,s=f;else if(i&&f===s&&(a===0||e.charCodeAt(a-1)!==92))i=!1;if(!i){if(f===91||f===123||f===40)n++;else if(f===93||f===125||f===41)n--;else if(f===44&&n===0){let c=e.substring(r,a).trim();if(c)t.push(c);r=a+1;continue}}}let o=e.substring(r).trim();if(o)t.push(o);return t}function Xi(e){if(tn(e))return!0;if(e==="true"||e==="false")return!0;if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return!0;return!1}function Kf(e){return e==="number"||e==="string"||e==="boolean"}function zi(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 f=i;while(f<n&&e.charCodeAt(f)<=32)f++;if(f<n&&e.charCodeAt(f)===40)return!1;i--}}return!0}function Hf(e,t,r=0){let n=e.slice(1,-1).trim();if(!n)return"{}";if(r>=20)return"Record<string, unknown>";let i=qf(n),s=[],o=[],a=Ir&&!t,f=[];for(let[l,p]of i){let{comments:h,key:w}=Zf(l),A=h?`${h}
24
- `:"",$=w,O=!1;if(w==="..."){let F=p.trim(),J=cr(F)?`typeof ${F}`:Ee(F,t,!1,r+1);if(J!=="unknown")o.push(J);if(a&&(cr(F)||F.startsWith("{")))f.push(`...${ar(F)}`);continue}let T=_e;_e=null;let S,W=p.trim();if(W===w&&fr(W))S=`typeof ${W}`;else if(zf(W)){O=!0;let F=Qf(w);if(F){$=F.name;let J="";if(W.startsWith("async "))J="async ";if(W.charCodeAt(J.length)===42)J+="*";S=Js(F.name,J+F.typeParams+W.slice(J.length))}else S=Js(w,W)}else if(S=Ee(p,t,!1,r+1),S.includes("=>")||S.includes("function")||S.includes("async"))S=Yf(S);let b=_e;_e=T;let L=p.trim(),re=Uf(w);if(re){let F=Xf(re.kind,re.name,S);if(F){s.push(`${A}${F}`);continue}}if(!t&&Kf(S)&&Xi(L))s.push(`${A}/** @defaultValue ${L} */
25
- ${$}: ${S}`);else s.push(`${A}${$}: ${S}`);if(a){let F=Tf($);if(L.endsWith("as const"));else if(Xi(L))f.push(`${F}: ${L}`);else if(L.startsWith("[")&&zi(L))f.push(`${F}: ${ar(L)}`);else if(L.startsWith("{")){if(b)f.push(`${F}: ${b}`)}else if(O)f.push(`${F}: ${ar(S)}`);else if(!L.startsWith("[")&&(L.includes("=>")||L.startsWith("function")||L.startsWith("async"))){let J=Us(L,!1,0,!0);f.push(`${F}: ${J}`)}}}if(a&&f.length>0){let l=r>0?(r-1)/2:0,p=`{ ${f.join(", ")} }`;if(p.length<=80)_e=p;else{let h=" ".repeat((l+1)*2),w=" ".repeat(l*2);_e=`{
26
- ${h}${f.join(`,
23
+ ]`}let a=Lr&&!t,o=[],c=[];for(let g of i){let h=g.trim(),w=Ve;if(Ve=null,h.startsWith("...")){let v=h.slice(3).trim(),C=Ae(v,!1,!1,r+1);if(C.endsWith("[]"))o.push(C.slice(0,-2));else if(C.startsWith("readonly [")&&C.endsWith("]"))o.push(C.slice(10,-1));else if(fr(v))o.push(`(typeof ${v})[number]`);else o.push("unknown")}else if(h.startsWith("[")&&h.endsWith("]"))o.push(qi(h,t,r+1));else o.push(Vc(h,t,r+1));if(a)c.push(Ve);Ve=w}if(a)if(zi(e))Ve=or(e);else{let g=[];for(let h=0;h<i.length;h++){let w=i[h].trim();if(w.endsWith("as const"))continue;if(Xi(w)||w==="null"||w==="undefined")g.push(w);else if(w.startsWith("[")&&zi(w))g.push(or(w));else if(w.startsWith("{")){if(c[h])g.push(c[h])}else{let v=Ae(w,!1,!1,0);if(v!=="unknown")g.push(v)}}if(g.length>0)Ve=`[${g.join(", ")}]`}if(t)return`readonly [${o.join(", ")}]`;let f=new Set,u=[],l=!0;for(let g of o){if(!f.has(g))f.add(g),u.push(g);if(l){if(!(tn(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&&o.length<=10)return`readonly [${o.join(", ")}]`;if(u.length===1)return`${u[0]}[]`;return`(${u.join(" | ")})[]`}function Fr(e){let t=[],r=0,n=0,i=!1,s=0;for(let o=0;o<e.length;o++){let c=e.charCodeAt(o);if(!i&&(c===34||c===39||c===96))i=!0,s=c;else if(i&&c===s&&(o===0||e.charCodeAt(o-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,o).trim();if(f)t.push(f);r=o+1;continue}}}let a=e.substring(r).trim();if(a)t.push(a);return t}function Xi(e){if(tn(e))return!0;if(e==="true"||e==="false")return!0;if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return!0;return!1}function Uc(e){return e==="number"||e==="string"||e==="boolean"}function zi(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 a=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 o=e.slice(a,i);if(o==="new"||o==="async"||o==="await"||o==="function"||o==="yield"||o==="console"||o==="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 Yc(e,t,r=0){let n=e.slice(1,-1).trim();if(!n)return"{}";if(r>=20)return"Record<string, unknown>";let i=ef(n),s=[],a=[],o=Lr&&!t,c=[];for(let[l,g]of i){let{comments:h,key:w}=Qc(l),v=h?`${h}
24
+ `:"",C=w,x=!1;if(w==="..."){let I=g.trim(),_=fr(I)?`typeof ${I}`:Ae(I,t,!1,r+1);if(_!=="unknown")a.push(_);if(o&&(fr(I)||I.startsWith("{")))c.push(`...${or(I)}`);continue}let O=Ve;Ve=null;let R,k=g.trim();if(k===w&&cr(k))R=`typeof ${k}`;else if(nf(k)){x=!0;let I=sf(w);if(I){C=I.name;let _="";if(k.startsWith("async "))_="async ";if(k.charCodeAt(_.length)===42)_+="*";R=_s(I.name,_+I.typeParams+k.slice(_.length))}else R=_s(w,k)}else if(R=Ae(g,t,!1,r+1),R.includes("=>")||R.includes("function")||R.includes("async"))R=qc(R);let E=Ve;Ve=O;let G=g.trim(),re=tf(w);if(re){let I=rf(re.kind,re.name,R);if(I){s.push(`${v}${I}`);continue}}if(!t&&Uc(R)&&Xi(G))s.push(`${v}/** @defaultValue ${G} */
25
+ ${C}: ${R}`);else s.push(`${v}${C}: ${R}`);if(o){let I=Ic(C);if(G.endsWith("as const"));else if(Xi(G))c.push(`${I}: ${G}`);else if(G.startsWith("[")&&zi(G))c.push(`${I}: ${or(G)}`);else if(G.startsWith("{")){if(E)c.push(`${I}: ${E}`)}else if(x)c.push(`${I}: ${or(R)}`);else if(!G.startsWith("[")&&(G.includes("=>")||G.startsWith("function")||G.startsWith("async"))){let _=qs(G,!1,0,!0);c.push(`${I}: ${_}`)}}}if(o&&c.length>0){let l=r>0?(r-1)/2:0,g=`{ ${c.join(", ")} }`;if(g.length<=80)Ve=g;else{let h=" ".repeat((l+1)*2),w=" ".repeat(l*2);Ve=`{
26
+ ${h}${c.join(`,
27
27
  ${h}`)}
28
- ${w}}`}}let c=s.length>0?`{
28
+ ${w}}`}}let f=s.length>0?`{
29
29
  ${s.join(`;
30
30
  `)}
31
- }`:"{}";if(o.length===0)return c;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 ${c}> & ${c}`:u}function fr(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(!rt(e.charCodeAt(r)))return!1;return!0}function cr(e){let t=e.split(".");return t.length>0&&t.every(fr)}function Vs(e){if(e.length<3||!e.endsWith(")"))return null;let t=e.indexOf("(");if(t===-1||at(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(at(r,o,"<",">")!==r.length-1)return null;i=r.slice(0,o).trim(),s=!0}if(!cr(i))return null;let a=e.slice(t+1,-1).trim(),f=Mr(a)!==-1||a.startsWith("function")||a.startsWith("async function"),c=cr(a),u=!f&&a.endsWith(")")&&Vs(a)!==null;if(!s&&!n&&!f&&!c&&!u)return null;let l=`ReturnType<typeof ${r}>`;return n?`${l} | undefined`:l}function Yf(e){let t=e.split(`
32
- `).map((c)=>Zs(c)).join(`
33
- `),r=t.indexOf("async");if(r!==-1){let c=r>0?t.charCodeAt(r-1):32,u=r+5<t.length?t.charCodeAt(r+5):32;if(!rt(c)&&!rt(u))t=(t.slice(0,r)+t.slice(r+5)).trim()}let n=t.indexOf("(");if(n!==-1){let c=at(t,n,"(",")");if(c!==-1){let u=t.slice(n,c+1),l=Lt(u);t=t.slice(0,n)+l+t.slice(c+1)}}let i=t.length,s="",o=[],a=!1,f=!1;for(let c=0;c<i;c++){let u=t.charCodeAt(c);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)f=!0;continue}if(a&&s.length>0){let l=(o.length>0?o[o.length-1]:0)===123;if(f&&l){let p=s.charCodeAt(s.length-1),h=p===59||p===44||p===123||u===125,w=s.length>=2&&s.charCodeAt(s.length-1)===47&&s.charCodeAt(s.length-2)===42;if(!h&&!w)s+="; ";else s+=" "}else s+=" "}a=!1,f=!1,s+=t[c]}return s.trim()}function rt(e){return e>=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57||e===95||e===36}function Lt(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 w=0;for(let A=0;A<i.length;A++){let $=i.charCodeAt(A);if($===40||$===60||$===91||$===123)w++;else if($===41||$===62||$===93||$===125)w--;else if(w===0&&$===61){let O=A>0?i.charCodeAt(A-1):0,T=A+1<i.length?i.charCodeAt(A+1):0;if(O!==61&&O!==33&&O!==60&&O!==62&&T!==61&&T!==62){s=!0;break}}}}if(!s)return t;let o=[],a=[],f=0,c=0,u=!1,l=0;for(let w=0;w<=i.length;w++){if(w===i.length){o.push(i.slice(f));break}let A=i.charCodeAt(w);if(u){if(A===92){w++;continue}if(A===l)u=!1;continue}if(A===47&&w+1<i.length){let $=i.charCodeAt(w+1);if($===42){w+=2;while(w+1<i.length&&!(i.charCodeAt(w)===42&&i.charCodeAt(w+1)===47))w++;w++;continue}if($===47){while(w<i.length&&i.charCodeAt(w)!==10)w++;continue}}if(A===39||A===34||A===96){u=!0,l=A;continue}if(A===40||A===60||A===91||A===123)c++;else if(A===41||A===62||A===93||A===125)c--;else if(A===44&&c===0){o.push(i.slice(f,w));let $=",",O=w+1;while(O<i.length&&i.charCodeAt(O)<=32)$+=i[O],O++;a.push($),f=O}}let p=[];for(let w of o){let A=w.trim();if(!A){p.push(w);continue}if(A.startsWith("//"))continue;let $=Zs(A),O=w.slice(0,w.length-w.trimStart().length);p.push(O+Gf($))}let h=p[0]||"";for(let w=1;w<p.length;w++)h+=(a[w-1]||", ")+p[w];return n?`(${h})`:h}function Zs(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 Gf(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 f=e.charCodeAt(a);if(i){if(f===92){a++;continue}if(f===s)i=!1;continue}if(f===47&&a+1<e.length){let c=e.charCodeAt(a+1);if(c===42){a+=2;while(a+1<e.length&&!(e.charCodeAt(a)===42&&e.charCodeAt(a+1)===47))a++;a++;continue}if(c===47){while(a<e.length&&e.charCodeAt(a)!==10)a++;continue}}if(f===39||f===34||f===96){i=!0,s=f;continue}if(f===40||f===60||f===91||f===123)n++;else if(f===41||f===62||f===93||f===125)n--;else if(n===0){if(f===58&&t===-1)t=a;else if(f===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(),f=r!==-1?e.slice(t+1,r).trim():e.slice(t+1).trim(),c=o&&!a.endsWith("?")?"?":"";return`${a}${c}: ${f}`}else if(r!==-1){let a=e.slice(0,r).trim(),f=!a.endsWith("?")?"?":"",c=e.slice(r+1).trim(),u="unknown";if(c==="true"||c==="false")u="boolean";else if(/^-?\d+(\.\d+)?$/.test(c))u="number";else if(c.startsWith("'")&&c.endsWith("'")||c.startsWith('"')&&c.endsWith('"'))u="string";else if(c.startsWith("["))u="unknown[]";else if(c.startsWith("{"))u="Record<string, unknown>";return`${a}${f}: ${u}`}return e}function Vf(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 Zf(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(`
34
- `),key:e.slice(r).trim()}}function qf(e){let t=[],r="",n="",i=0,s=!1,o="",a=!0,f=!1,c=0,u=!1,l=!1,p=0,h=!1,w=!1;for(let A=0;A<e.length;A++){let $=e.charCodeAt(A),O=A>0?e.charCodeAt(A-1):0,T=A<e.length-1?e.charCodeAt(A+1):0;if(!s&&!f&&$===47&&T===47){A+=2;while(A<e.length&&e.charCodeAt(A)!==10)A++;continue}if(!s&&!f&&$===47&&T===42){f=!0,c=1,r+="/*",A++;continue}else if(f&&$===42&&T===47){if(c--,r+="*/",A++,c===0)f=!1;continue}else if(f&&$===47&&T===42){c++,r+="/*",A++;continue}let S=e[A];if(!s&&($===34||$===39||$===96))s=!0,o=S,r+=S;else if(s&&S===o&&O!==92)s=!1,r+=S;else if(!s&&!f)if($===40&&i===0&&a&&p===0){n=r.trim();let W=Vf(n),b=W>0?n.slice(0,W):"",L=n.slice(W),re="";if(L.startsWith("async ")||L.startsWith("async\t")||L.startsWith(`async
35
- `))L=L.slice(6).trimStart(),re="async ";if(L.startsWith("*"))L=L.slice(1).trimStart(),re+="*";n=b+L,r=re+S,a=!1,h=!0,w=!1,i=1}else if($===123||$===91||$===40){if(i++,r+=S,w&&$===123)w=!1}else if($===125||$===93||$===41){if(i--,r+=S,$===41&&i===0&&!a&&!h)u=!0;if(h){if($===41&&i===0&&!w)w=!0;else if($===125&&i===0)h=!1,w=!1}}else if($===58&&i===0&&a&&p===0)n=r.trim(),r="",a=!1;else if($===58&&i===0&&u)l=!0,r+=S;else if($===60&&l)p++,r+=S;else if($===60&&a&&i===0)p++,r+=S;else if($===62&&p>0&&O!==61)p--,r+=S;else if($===61&&T===62&&l&&p===0)l=!1,u=!1,r+=S;else if($===44&&i===0&&p===0&&!w){if(n&&r.trim()){let W=r.trim();t.push([n,W])}else if(a&&r.trim()){let W=r.trim();if(fr(W))t.push([W,W]);else if(W.startsWith("...")&&W.length>3)t.push(["...",W.slice(3).trim()])}r="",n="",a=!0,u=!1,l=!1,p=0}else r+=S;else r+=S}if(n&&r.trim()){let A=r.trim();t.push([n,A])}else if(a&&r.trim()){let A=r.trim();if(fr(A))t.push([A,A]);else if(A.startsWith("...")&&A.length>3)t.push(["...",A.slice(3).trim()])}return t}function Uf(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 Xf(e,t,r){let n=r.trim();if(n.charCodeAt(0)!==40)return null;let i=at(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 zf(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=qs(s,1);if(o?.kind==="arrow")return!1;if(o?.kind==="body")return!0}return!1}}}return!1}function Qf(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 Js(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 p=0,h=-1;for(let w=0;w<r.length;w++)if(r.charCodeAt(w)===60)p++;else if(r.charCodeAt(w)===62&&!(w>0&&r.charCodeAt(w-1)===61)){if(p--,p===0){h=w;break}}if(h!==-1)s=r.slice(0,h+1),r=r.slice(h+1).trimStart()}let o=r.indexOf("("),a=at(r,o,"(",")");if(o===-1||a===-1)return"() => unknown";let f=r.slice(o,a+1),c="unknown",u=r.slice(a+1).trimStart();if(u.charCodeAt(0)===58){let p=u.slice(1),h=qs(p,0);if(h)c=p.slice(0,h.index).trim();else c=p.trim()}if(c==="unknown"){if(n&&i)c="AsyncGenerator<unknown, void, unknown>";else if(i)c="Generator<unknown, void, unknown>";else if(n)c="Promise<void>"}else if(n&&!c.startsWith("Promise<")&&!c.startsWith("AsyncGenerator<"))c=`Promise<${c}>`;let l=Lt(f);return`${s}${l} => ${c}`}function qs(e,t){let r=0,n=0,i=0,s=0,o=!1,a=0;for(let f=t;f<e.length;f++){let c=e.charCodeAt(f);if(o){if(c===92)f++;else if(c===a)o=!1;continue}if(c===34||c===39||c===96){o=!0,a=c;continue}if(c===40)r++;else if(c===41&&r>0)r--;else if(c===91)n++;else if(c===93&&n>0)n--;else if(c===60)i++;else if(c===62&&i>0&&e.charCodeAt(f-1)!==61)i--;else if(c===125&&s>0)s--;else if(c===123){let u=r>0||n>0||i>0||s>0,l=e.slice(t,f).trimEnd(),p=l.charCodeAt(l.length-1),h=l.length===0||p===38||p===124||p===40||p===44||p===58||p===61||p===91;if(u||h)s++;else return{index:f,kind:"body"}}else if(c===61&&f+1<e.length&&e.charCodeAt(f+1)===62&&r===0&&n===0&&i===0&&s===0)return{index:f,kind:"arrow"}}return null}function at(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 Mr(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],f=s>0?e[s-1]:"";if(!n&&(o==='"'||o==="'"||o==="`"))n=!0,i=o;else if(n&&o===i&&f!=="\\")n=!1;if(!n){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 Us(e,t=!1,r=0,n=!0){let i=e.trim();if(i.length>200&&qi(i,"=>")>2&&qi(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=Mr(o);if(a===-1)return t?"(() => Promise<unknown>)":"() => Promise<unknown>";let f=o.substring(0,a).trim(),c=o.substring(a+2).trim(),u=Ks(f),l=u.params,p=u.returnType;if(l=Lt(l),l==="()"||l==="")l="()";else if(!l.startsWith("("))l=`(${l})`;let h=p;if(h);else if(c.startsWith("{"))h=lr(c.slice(1,c.endsWith("}")?-1:void 0),!0,l);else h=Ee(c,n,!1,r+1);let w=`${l} => ${p||h.startsWith("Promise<")?h:`Promise<${h}>`}`;return t?`(${w})`:w}if(i.includes("=>")){let o="",a=i;if(i.startsWith("<")){let $=at(i,0,"<",">");if($!==-1)o=i.substring(0,$+1),a=i.substring($+1).trim()}let f=Mr(a);if(f===-1)return t?"(() => unknown)":"() => unknown";let c=a.substring(0,f).trim(),u=a.substring(f+2).trim(),l=Ks(c),p=l.params,h=l.returnType;if(p=Lt(p),p==="()"||p==="")p="()";else if(!p.startsWith("("))p=`(${p})`;let w="unknown";if(h)w=h;else if(u.startsWith("{"))w=lr(u.slice(1,u.endsWith("}")?-1:void 0),!1,p);else if(Pr(u)||Ys(u)&&Pr(u.slice(1,-1).trim()))w="JSX.Element";else if(u.includes("=>")){let $=u.trimStart(),O=$.indexOf("("),T=O!==-1?at($,O,"(",")"):-1,S=T!==-1?$.indexOf("=>",T):-1;if(O===0&&T!==-1&&S!==-1){let W=$.substring(O+1,T).trim(),b=Lt(W);if(o.includes("T")&&b.includes("T"))w=`(${b}) => T`;else w=`(${b}) => any`}else w="any"}else if(t)w="unknown";else w=St(u,Hs(p));let A=`${o}${p} => ${w}`;return t?`(${A})`:A}if(i.startsWith("function")){let o=8,a=i.length;while(o<a&&i.charCodeAt(o)<=32)o++;let f=!1;if(o<a&&i.charCodeAt(o)===42){f=!0,o++;while(o<a&&i.charCodeAt(o)<=32)o++}let c="";if(o<a&&i.charCodeAt(o)===60){let p=o,h=1;o++;while(o<a&&h>0){let w=i.charCodeAt(o);if(w===60)h++;else if(w===62&&i.charCodeAt(o-1)!==61)h--;o++}c=i.substring(p,o);while(o<a&&i.charCodeAt(o)<=32)o++}let u=i.indexOf("(",o);if(u!==-1){let p=1,h=u+1;while(h<a&&p>0){let O=i.charCodeAt(h);if(O===40)p++;else if(O===41)p--;h++}let w=i.substring(u+1,h-1).trim(),A=w?`(${w})`:"()";if(f){let O=i.substring(h).trim(),T=O.indexOf("Generator<");if(T!==-1){let W=T+10,b=O.indexOf(">",W);if(b!==-1){let L=O.substring(W,b),re=`${c}${A} => Generator<${L}>`;return t?`(${re})`:re}}let S=`${c}${A} => Generator<any, any, any>`;return t?`(${S})`:S}let $=`${c}${A} => unknown`;return t?`(${$})`:$}let l="(...args: any[]) => unknown";return t?`(${l})`:l}if(i.includes("=>")&&i.includes("(")&&i.includes(")")){if(i.length>100||qi(i,"=>")>2){let o="";if(i.charCodeAt(0)===60){let l=at(i,0,"<",">");if(l!==-1)o=i.substring(0,l+1)}let a=i.indexOf("("),f=a!==-1?at(i,a,"(",")"):-1,c=a!==-1&&f!==-1?i.substring(a,f+1):"(...args: any[])";c=Lt(c);let u=`${o}${c} => any`;return t?`(${u})`:u}return t?`(${i})`:i}let s="() => unknown";return t?`(${s})`:s}function Ks(e){let t=e.trim();if(!t.startsWith("("))return{params:t,returnType:""};let r=at(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 Xs(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 zs(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 Ir=!1,_e=null;var rn=()=>{};function Re(e){return e===ke||e===Se||e===pe||e===be}function Rt(e){return e>=65&&e<=90||e>=97&&e<=122||e===tc||e===to||e>127}function Je(e){return Rt(e)||e>=48&&e<=57}function rc(e){let t=!0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n===lt){if(t)return!1;t=!0}else if(t){if(!Rt(n))return!1;t=!1}else if(!Je(n))return!1}return e.length>0&&!t}function jr(e,t,r){let n=t+1;while(n<e.length){let i=e.charCodeAt(n);if(i===Ye){n+=2;continue}if(n++,i===r)break}return n}function ic(e){if(e==="any"||e==="object"||e==="unknown")return!0;if(e.startsWith("Record<")||e.startsWith("Array<"))return!0;return e.charCodeAt(0)===_&&e.includes("[")&&e.includes("]:")}function ro(e,t,r=!0){return no(e,t,r,!0)}function io(e,t,r=!0){return no(e,t,r,!1)}function no(e,t,r,n){let i=e,s=r,o=n,a=i.length,f=[],c=new Map,u=new Set,l=0;if(l<a&&i.charCodeAt(l)===65279)l++;function p(m,d){if(m<d){let g=i.charCodeAt(m),y=i.charCodeAt(d-1);if(g!==ke&&g!==Se&&g!==pe&&g!==be&&y!==ke&&y!==Se&&y!==pe&&y!==be)return i.slice(m,d)}while(m<d&&Re(i.charCodeAt(m)))m++;while(d>m&&Re(i.charCodeAt(d-1)))d--;return i.slice(m,d)}function h(){if(l>=a)return;let m=i.charCodeAt(l);if(m!==ke&&m!==Se&&m!==pe&&m!==be&&m!==U)return;while(l<a){let d=i.charCodeAt(l);if(d===ke||d===Se||d===pe||d===be){l++;continue}if(d===U&&l+1<a){let g=i.charCodeAt(l+1);if(g===U){let y=i.indexOf(`
36
- `,l+2);l=y===-1?a:y+1;continue}if(g===Oe){let y=i.indexOf("*/",l+2);l=y===-1?a:y+2;continue}}break}}function w(m){let d=m.length,g=0,y=d;for(let C=0;C<d;C++){let v=m.charCodeAt(C);if(g){if(v===Ye){C++;continue}if(v===g)g=0;continue}if(v===ne||v===ae||v===Te){g=v;continue}if(v===U&&C+1<d){let k=m.charCodeAt(C+1);if(k===U){y=C;while(y>0&&(m.charCodeAt(y-1)===ke||m.charCodeAt(y-1)===Se))y--;return m.slice(0,y)}if(k===Oe){let R=m.indexOf("*/",C+2);if(R!==-1){m=`${m.slice(0,C)} ${m.slice(R+2)}`,C--;continue}}}}y=d;while(y>0&&(m.charCodeAt(y-1)===ke||m.charCodeAt(y-1)===Se||m.charCodeAt(y-1)===be))y--;return y<d?m.slice(0,y):m}function A(m){l++;let d=m===ne?"'":'"';while(l<a){let g=i.indexOf(d,l);if(g===-1){l=a;return}let y=0,C=g-1;while(C>=0&&i.charCodeAt(C)===Ye)y++,C--;if(y%2===0){l=g+1;return}l=g+1}}function $(){l++;let m=[];while(l<a){let d=i.charCodeAt(l);if(m.length===0){if(d===Ye){l+=2;continue}if(d===Te){l++;return}if(d===to&&l+1<a&&i.charCodeAt(l+1)===_){l+=2,m.push(0);continue}l++;continue}if(d===ne||d===ae){A(d);continue}if(d===Te){$();continue}if(d===U&&l+1<a){let g=i.charCodeAt(l+1);if(g===U){let y=i.indexOf(`
37
- `,l+2);l=y===-1?a:y+1;continue}if(g===Oe){let y=i.indexOf("*/",l+2);l=y===-1?a:y+2;continue}if(T()){S();continue}l++;continue}if(d===_){m[m.length-1]++,l++;continue}if(d===G){let g=m[m.length-1];if(g===0){m.pop(),l++;continue}m[m.length-1]=g-1,l++;continue}l++}}function O(){let m=i.charCodeAt(l);if(m===ne||m===ae)return A(m),!0;if(m===Te)return $(),!0;if(m===U&&l+1<a){let d=i.charCodeAt(l+1);if(d===U){let g=i.indexOf(`
38
- `,l+2);return l=g===-1?a:g+1,!0}if(d===Oe){let g=i.indexOf("*/",l+2);return l=g===-1?a:g+2,!0}if(T())return S(),!0}return!1}function T(){let m=l-1;while(m>=0&&(i.charCodeAt(m)===ke||i.charCodeAt(m)===Se||i.charCodeAt(m)===pe||i.charCodeAt(m)===be))m--;if(m<0)return!0;let d=i.charCodeAt(m);if(d===$e||d===Q||d===ue||d===33||d===38||d===124||d===Br||d===qe||d===Ue||d===Z||d===_||d===G||d===94||d===126||d===43||d===45||d===Oe||d===37||d===he||d===oe)return!0;if(Je(d)){let g=m;while(g>=0&&Je(i.charCodeAt(g)))g--;let y=i.slice(g+1,m+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 S(){l++;let m=!1;while(l<a){let d=i.charCodeAt(l);if(d===Ye){l+=2;continue}if(m){if(d===Ce)m=!1;l++;continue}if(d===ue){m=!0,l++;continue}if(d===U){l++;break}if(d===pe||d===be)break;l++}while(l<a&&Je(i.charCodeAt(l)))l++}function W(){let m=l;while(l<a&&Je(i.charCodeAt(l)))l++;return i.slice(m,l)}function b(m){if(l+m.length>a)return!1;for(let d=0;d<m.length;d++)if(i.charCodeAt(l+d)!==m.charCodeAt(d))return!1;if(l+m.length<a&&Je(i.charCodeAt(l+m.length)))return!1;return!0}function L(m){let d=l+m;while(d<a){let g=i.charCodeAt(d);if(g===ke||g===Se||g===pe||g===be){d++;continue}return g!==lt&&g!==$e}return!1}function re(){if(l>=a)return!1;switch(i.charCodeAt(l)){case 101:return b("export")||b("enum");case 105:return b("import")||b("interface");case 102:return b("function");case 99:return b("class")||b("const");case 116:return b("type");case 108:return b("let");case 118:return b("var");case 100:return b("declare")||b("default");case 109:return b("module");case 110:return b("namespace");case 97:return b("abstract")||b("async");default:return!1}}function F(){let m=i.charCodeAt(l);if(m!==pe&&m!==be)return!1;let d=l;if(l++,m===be&&l<a&&i.charCodeAt(l)===pe)l++;while(l<a){let y=i.charCodeAt(l);if(y===ke||y===Se||y===be||y===pe){l++;continue}if(y===U&&l+1<a){let C=i.charCodeAt(l+1);if(C===U){let v=i.indexOf(`
39
- `,l+2);l=v===-1?a:v+1;continue}if(C===Oe){let v=i.indexOf("*/",l+2);l=v===-1?a:v+2;continue}}break}let g=l>=a||re()||i.charCodeAt(l)===G;return l=d,g}function J(){let m=i.charCodeAt(l);if(m!==pe&&m!==be)return!1;let d=l;if(l++,m===be&&l<a&&i.charCodeAt(l)===pe)l++;while(l<a){let y=i.charCodeAt(l);if(y===ke||y===Se||y===be||y===pe){l++;continue}if(y===U&&l+1<a&&i.charCodeAt(l+1)===U){let C=i.indexOf(`
40
- `,l+2);l=C===-1?a:C+1;continue}break}if(l>=a)return l=d,!0;let g=i.charCodeAt(l);if(g===124||g===38||g===lt||g===Br||g===qe)return l=d,!1;if(b("extends")||b("keyof")||b("typeof")||b("infer")||b("is")||b("as")||b("in"))return l=d,!1;return l=d,!0}let X=/[{}'"`\/]/g,se=/[()'"`\/]/g,H=/[[\]'"`\/]/g,q=/[<>'"`\/]/g;function V(m,d){let g=1;l++;let y=m===_?X:m===Q?se:m===ue?H:q;y.lastIndex=l;let C;while((C=y.exec(i))!==null){let v=C.index,k=i.charCodeAt(v);if(k===ne||k===ae){l=v,A(k),y.lastIndex=l;continue}if(k===Te){l=v,$(),y.lastIndex=l;continue}if(k===U){if(l=v,O()){y.lastIndex=l;continue}y.lastIndex=v+1;continue}if(k===m)g++;else if(k===d){if(d===oe&&v>0&&i.charCodeAt(v-1)===$e){y.lastIndex=v+1;continue}if(g--,g===0)return l=v+1,l}y.lastIndex=v+1}return l=a,l}function Y(){return l>0&&i.charCodeAt(l-1)===$e}function we(){return l+1<a&&i.charCodeAt(l+1)===oe}let z=/[<{};'"`\/\n\r()[\]]/g;function ie(){let m=0,d=0,g=0,y=0,C=i.charCodeAt(l)===_;z.lastIndex=l;let v;while((v=z.exec(i))!==null){let k=v.index,R=i.charCodeAt(k);if(R===ne||R===ae){l=k,A(R),z.lastIndex=l;continue}if(R===Te){l=k,$(),z.lastIndex=l;continue}if(R===U){if(k>0&&i.charCodeAt(k-1)===he){z.lastIndex=k+1;continue}if(l=k,O()){z.lastIndex=l;continue}z.lastIndex=k+1;continue}if(R===he){let E=As(k);if(E!==null)y=Math.max(0,y+E);z.lastIndex=k+1;continue}if(R===Q){d++,z.lastIndex=k+1;continue}if(R===ge){d--,z.lastIndex=k+1;continue}if(R===ue){g++,z.lastIndex=k+1;continue}if(R===Ce){g--,z.lastIndex=k+1;continue}if(R===_){m++,z.lastIndex=k+1;continue}if(R===G){let E=m>0;if(E)m--;if((!E||C)&&m===0&&d===0&&g===0&&y===0){l=k+1;return}z.lastIndex=k+1;continue}if(R===Z&&m===0&&d===0&&g===0&&y===0){l=k+1;return}if((R===pe||R===be)&&m===0&&d===0&&g===0&&y===0){if(l=k,F())return}z.lastIndex=k+1}l=a}function kr(){l++;while(l<a&&(i.charCodeAt(l)===ke||i.charCodeAt(l)===Se))l++;let m=i.indexOf(`
41
- `,l),d=m===-1?a:m,g=i.indexOf(";",l);if(g!==-1&&g<d){let y=g-1;while(y>=l&&(i.charCodeAt(y)===ke||i.charCodeAt(y)===Se))y--;let C=i.charCodeAt(l),v=i.charCodeAt(y);if(C===_&&v===G||C===ue&&v===Ce||C===ne&&v===ne||C===ae&&v===ae||C===Te&&v===Te){l=g+1;return}}ie()}function kt(){V(_,G);while(l<a&&Re(i.charCodeAt(l)))l++;if(b("from")){l+=4;while(l<a&&Re(i.charCodeAt(l)))l++;if(l<a){let m=i.charCodeAt(l);if(m===ne||m===ae)A(m)}}while(l<a&&(i.charCodeAt(l)===ke||i.charCodeAt(l)===Se))l++;if(l<a&&i.charCodeAt(l)===Z)l++}function wt(){l++;while(l<a&&Re(i.charCodeAt(l)))l++;if(b("as")){l+=2;while(l<a&&Re(i.charCodeAt(l)))l++;W();while(l<a&&Re(i.charCodeAt(l)))l++}if(b("from")){l+=4;while(l<a&&Re(i.charCodeAt(l)))l++;if(l<a){let m=i.charCodeAt(l);if(m===ne||m===ae)A(m)}}while(l<a&&(i.charCodeAt(l)===ke||i.charCodeAt(l)===Se))l++;if(l<a&&i.charCodeAt(l)===Z)l++}function De(m){let d=m.indexOf("from ");if(d===-1)return;let g=d+5;while(g<m.length&&(m.charCodeAt(g)===32||m.charCodeAt(g)===9))g++;if(g>=m.length)return;let y=m.charCodeAt(g);if(y!==39&&y!==34)return;let C=m.indexOf(m[g],g+1);if(C===-1)return;return m.slice(g+1,C)}function ve(m){if(!s)return;let d=m-1;while(d>=0&&Re(i.charCodeAt(d)))d--;if(d<0)return;let g=[],y=!1;while(d>=0){if(d>=1&&i.charCodeAt(d)===U&&i.charCodeAt(d-1)===Oe){let k=i.lastIndexOf("/*",d-2);if(k>=0){g.push(i.slice(k,d+1)),y=!0,d=k-1;while(d>=0&&Re(i.charCodeAt(d)))d--;continue}break}let C=d;while(C>0&&i.charCodeAt(C-1)!==pe)C--;let v=p(C,d+1);if(v.startsWith("//")){if(y)break;let k=[v];d=C-1;while(d>=0&&(i.charCodeAt(d)===pe||i.charCodeAt(d)===be))d--;while(d>=0){let R=d;while(R>0&&i.charCodeAt(R-1)!==pe)R--;let E=p(R,d+1);if(E.startsWith("//")){k.push(E),d=R-1;while(d>=0&&(i.charCodeAt(d)===pe||i.charCodeAt(d)===be))d--}else if(E===""){d=R-1;while(d>=0&&(i.charCodeAt(d)===pe||i.charCodeAt(d)===be))d--}else break}k.reverse(),g.push(k.join(`
42
- `));continue}break}if(g.length===0)return;return g.reverse(),g}function Ft(m){let d=m,g=!1;while(l<a){let E=i.charCodeAt(l);if(E===Z){l++;break}if(E===ne||E===ae){A(E),g=!0;while(l<a&&(i.charCodeAt(l)===ke||i.charCodeAt(l)===Se))l++;if(l<a&&i.charCodeAt(l)===Z)l++;break}if(E===pe&&g)break;l++}let y=p(d,l),C=y.charCodeAt(7)===116&&(y.startsWith("import type ")||y.startsWith("import type{")),v=!1;{let E=6;while(E<y.length&&(y.charCodeAt(E)===ke||y.charCodeAt(E)===Se))E++;if(E<y.length&&y.charCodeAt(E)===116&&y.startsWith("type",E)){E+=4;while(E<y.length&&(y.charCodeAt(E)===ke||y.charCodeAt(E)===Se))E++}if(E<y.length){let x=y.charCodeAt(E);v=x===ne||x===ae}}let k="";{let E=y.indexOf("from ");if(E!==-1){let x=E+5;while(x<y.length&&(y.charCodeAt(x)===ke||y.charCodeAt(x)===Se))x++;if(x<y.length){let N=y.charCodeAt(x);if(N===ne||N===ae){let M=y.indexOf(String.fromCharCode(N),x+1);if(M!==-1)k=y.slice(x+1,M)}}}else if(v){let x=6;while(x<y.length&&y.charCodeAt(x)!==ne&&y.charCodeAt(x)!==ae)x++;if(x<y.length){let N=y.charCodeAt(x),M=y.indexOf(String.fromCharCode(N),x+1);if(M!==-1)k=y.slice(x+1,M)}}}let R=ve(d);return{kind:"import",name:"",text:y,isExported:!1,isTypeOnly:C,isSideEffect:v,source:k,leadingComments:R,start:d,end:l}}function Pt(){let m=l;return V(_,G),i.slice(m,l)}function $s(m){let d=m.indexOf("(");if(d===-1)return m;let g=m.slice(d);if(g.indexOf("=")===-1)return m;let y=!1;for(let E=0;E<g.length;E++)if(g.charCodeAt(E)===61){let x=E>0?g.charCodeAt(E-1):0,N=E+1<g.length?g.charCodeAt(E+1):0;if(x!==61&&x!==33&&x!==60&&x!==62&&N!==61&&N!==62){y=!0;break}}if(!y)return m;let C=0,v=-1;for(let E=d;E<m.length;E++){let x=m.charCodeAt(E);if(x===40)C++;else if(x===41){if(C--,C===0){v=E;break}}}if(v===-1)return m;let k=m.slice(d,v+1),R=Dt(k);return m.slice(0,d)+R+m.slice(v+1)}function ws(m){let d=m.indexOf("//")!==-1||m.indexOf("/*")!==-1,g=m.split(`
43
- `),y=[],C=[],v=[],k=!1,R=1/0;for(let N=0;N<g.length;N++){let M=g[N];if(d){if(k){if(M.includes("*/"))k=!1;continue}let B=M.trim();if(B.length===0)continue;let I=B.charCodeAt(0);if(I===U){let xe=B.charCodeAt(1);if(xe===U)continue;if(xe===Oe){if(!B.includes("*/"))k=!0;continue}}if(I===Oe)continue;let P=w(M);if(P.charCodeAt(P.length-1)===Z)P=P.slice(0,-1);P=$s(P);let D=P.trim();if(!D)continue;y.push(P),C.push(D);let j=0;while(j<P.length&&Re(P.charCodeAt(j)))j++;if(D!=="{"&&D!=="}"){if(j<R)R=j}v.push(j)}else{let B=M.length;while(B>0&&(M.charCodeAt(B-1)===ke||M.charCodeAt(B-1)===Se||M.charCodeAt(B-1)===be))B--;if(B===0)continue;let I=B<M.length?M.slice(0,B):M;if(I.charCodeAt(I.length-1)===Z)I=I.slice(0,-1);I=$s(I);let P=I.trim();if(!P)continue;y.push(I),C.push(P);let D=0;while(D<I.length&&Re(I.charCodeAt(D)))D++;if(P!=="{"&&P!=="}"){if(D<R)R=D}v.push(D)}}if(y.length===0)return"{}";if(R===1/0||R<=2)return y.join(`
44
- `);let E=R-2,x=Array(y.length);for(let N=0;N<y.length;N++){let M=C[N];if(M==="{"){x[N]=M;continue}let B=v[N];if(B>R)x[N]=y[N];else if(B===R&&(M.charCodeAt(0)===G||M.charCodeAt(0)===Ce||M.charCodeAt(0)===ge))x[N]=y[N];else{let I=Math.max(0,B-E);x[N]=" ".repeat(I)+M}}return x.join(`
45
- `)}function ot(){if(l>=a||i.charCodeAt(l)!==he)return"";let m=l;V(he,oe);let d=i.slice(m,l);if(d.includes(`
46
- `)){let g="",y=!1;for(let C=0;C<d.length;C++){let v=d.charCodeAt(C);if(v===32||v===9||v===10||v===13){if(!y&&g.length>0)g+=" ",y=!0}else g+=d[C],y=!1}if(g.charCodeAt(1)===32)g=`<${g.slice(2)}`;if(g.charCodeAt(g.length-2)===32)g=`${g.slice(0,-2)}>`;return g}return d}function Ct(){if(l>=a||i.charCodeAt(l)!==Q)return"()";let m=l;return V(Q,ge),i.slice(m,l)}function Dt(m){let d=m.slice(1,-1).trim();if(!d)return"()";if(m.indexOf(`
47
- `)===-1&&d.indexOf(":")!==-1&&d.indexOf("{")===-1&&d.indexOf("[")===-1&&d.indexOf("=")===-1&&d.indexOf("@")===-1&&d.indexOf("...")===-1){let E=0,x=0,N=0;for(let M=0;M<d.length;M++){let B=d.charCodeAt(M);if(B===Q||B===he||B===_)N++;else if(B===ge||B===oe||B===G)N--;else if(N===0){if(B===qe)E++;else if(B===Ue)x++}}if(E>=x+1){let M=!1;for(let B=0;B<nn.length;B++){let I=nn[B],P=d.indexOf(I);if(P!==-1){let D=P+I.length;if((P===0||!Je(d.charCodeAt(P-1)))&&(D>=d.length||!Je(d.charCodeAt(D)))){M=!0;break}}}if(!M)return m}}let g=[],y=0,C=0,v=!1,k=0;for(let E=0;E<=d.length;E++){if(E===d.length){g.push(d.slice(y).trim());break}let x=d.charCodeAt(E);if(v){if(x===Ye){E++;continue}if(x===k)v=!1;continue}if(x===U&&E+1<d.length){let N=d.charCodeAt(E+1);if(N===Oe){E+=2;while(E+1<d.length&&!(d.charCodeAt(E)===Oe&&d.charCodeAt(E+1)===U))E++;E++;continue}if(N===U){while(E<d.length&&d.charCodeAt(E)!==10)E++;continue}}if(x===ne||x===ae||x===Te){v=!0,k=x;continue}if(x===Q||x===_||x===ue||x===he)C++;else if(x===ge||x===G||x===Ce||x===oe&&!(E>0&&d.charCodeAt(E-1)===$e))C--;else if(x===Ue&&C===0)g.push(d.slice(y,E).trim()),y=E+1}let R=[];for(let E of g){if(!E)continue;let x=E.trim();if(x.startsWith("//")||x.startsWith("/*"))continue;let N=E;{let M=!1,B=0,I=0,P=0;for(let D=0;D<N.length-1;D++){let j=N.charCodeAt(D);if(j===pe){P=D+1;continue}if(M){if(j===Ye){D++;continue}if(j===B)M=!1;continue}if(j===ne||j===ae||j===Te){M=!0,B=j;continue}if(j===_||j===ue||j===Q||j===he){I++;continue}if(j===G||j===Ce||j===ge||j===oe){if(I>0)I--;continue}if(j===U&&N.charCodeAt(D+1)===U){if(I===0){N=N.slice(0,D).trimEnd();break}let xe=N.indexOf(`
48
- `,D);if(xe===-1){N=N.slice(0,P).trimEnd();break}let vt=N.slice(0,P),nf=N.slice(xe+1);N=`${vt}${nf}`,D=P-1}}}if(!N.trim())continue;R.push(Cs(N))}return`(${R.join(", ")})`}function Ul(m){if(!m.startsWith("{")&&!m.startsWith("["))return m;let d="",g=0,y=0,C=!1,v=0;while(g<m.length){let k=m.charCodeAt(g);if(C){if(k===Ye&&g+1<m.length){d+=m[g]+m[g+1],g+=2;continue}if(k===v)C=!1;d+=m[g],g++;continue}if(k===U&&g+1<m.length){let R=m.charCodeAt(g+1);if(R===Oe){let E=g;g+=2;while(g+1<m.length&&!(m.charCodeAt(g)===Oe&&m.charCodeAt(g+1)===U))g++;g=Math.min(g+2,m.length),d+=m.slice(E,g);continue}if(R===U){let E=g;while(g<m.length&&m.charCodeAt(g)!==10)g++;d+=m.slice(E,g);continue}}if(k===ne||k===ae||k===Te){C=!0,v=k,d+=m[g],g++;continue}if(k===_||k===ue||k===Q)y++;else if(k===G||k===Ce||k===ge)y--;if(y>=1&&k===$e&&(g+1>=m.length||m.charCodeAt(g+1)!==$e&&m.charCodeAt(g+1)!==oe)){while(d.length>0&&(d[d.length-1]===" "||d[d.length-1]==="\t"||d[d.length-1]===`
49
- `))d=d.slice(0,-1);g++;let R=0;while(g<m.length){let E=m.charCodeAt(g);if(E===ne||E===ae||E===Te){let x=E;g++;while(g<m.length){if(m.charCodeAt(g)===Ye){g+=2;continue}if(m.charCodeAt(g)===x){g++;break}g++}continue}if(E===_||E===ue||E===Q)R++;else if(E===G||E===Ce||E===ge){if(R===0)break;R--}else if(E===Ue&&R===0)break;g++}continue}if(y===1&&k===lt&&g+2<m.length&&m.charCodeAt(g+1)===lt&&m.charCodeAt(g+2)===lt){g+=3;continue}d+=m[g],g++}return d}function Cs(m){let d=m.trim(),g=d.startsWith("...");if(g)d=d.slice(3).trim();while(d.startsWith("@")){let P=1;while(P<d.length&&Je(d.charCodeAt(P)))P++;if(P<d.length&&d.charCodeAt(P)===Q){let D=1;P++;while(P<d.length&&D>0){if(d.charCodeAt(P)===Q)D++;else if(d.charCodeAt(P)===ge)D--;P++}}d=d.slice(P).trim()}let y=!0;while(y){y=!1;for(let P of nn)if(d.startsWith(P)&&d.length>P.length&&!Je(d.charCodeAt(P.length))){let D=d.slice(P.length).trim();if(D.charCodeAt(0)===qe||D.charCodeAt(0)===Br&&D.length>1&&D.charCodeAt(1)===qe)break;d=D,y=!0;break}}let C=-1,v=-1,k=0,R=!1,E=0;for(let P=0;P<d.length;P++){let D=d.charCodeAt(P);if(R){if(D===Ye){P++;continue}if(D===E)R=!1;continue}if(D===U&&P+1<d.length){let j=d.charCodeAt(P+1);if(j===Oe){P+=2;while(P+1<d.length&&!(d.charCodeAt(P)===Oe&&d.charCodeAt(P+1)===U))P++;P++;continue}if(j===U){while(P<d.length&&d.charCodeAt(P)!==10)P++;continue}}if(D===ne||D===ae||D===Te){R=!0,E=D;continue}if(D===Q||D===_||D===ue||D===he)k++;else if(D===ge||D===G||D===Ce||D===oe&&!(P>0&&d.charCodeAt(P-1)===$e))k--;else if(k===0){if(D===qe&&C===-1)C=P;else if(D===$e&&v===-1&&(P===0||d.charCodeAt(P-1)!==$e)&&(P+1>=d.length||d.charCodeAt(P+1)!==$e&&d.charCodeAt(P+1)!==oe))v=P}}let x,N,M=v!==-1;if(C!==-1&&(v===-1||C<v))if(x=d.slice(0,C).trim(),v!==-1)N=d.slice(C+1,v).trim();else N=d.slice(C+1).trim();else if(v!==-1)x=d.slice(0,v).trim(),N=Bi(d.slice(v+1).trim());else x=d,N="unknown";if(x=Ul(x),(x.startsWith("{")||x.startsWith("["))&&x.includes(`
50
- `)){let P=x.replace(/\s*\n\s*/g," ").replace(/\s+/g," ");if(P.length<=40)x=P;else x=x.split(`
51
- `).map((D)=>{let j=D.trim();if(!j)return"";if(j==="{"||j==="}"||j==="["||j==="]"||j.startsWith("}")||j.startsWith("]"))return j;return` ${j}`}).join(`
52
- `)}let B=x.endsWith("?")||M;if(x.endsWith("?"))x=x.slice(0,-1).trim();let I=B&&!g?"?":"";if(g)return`...${x}: ${N}`;return`${x}${I}: ${N}`}function bs(m){let d=0;if(d<m.length&&m.charCodeAt(d)===45)d++;if(d>=m.length)return!1;let g=m.charCodeAt(d);if(g<48||g>57)return!1;while(d<m.length&&m.charCodeAt(d)>=48&&m.charCodeAt(d)<=57)d++;if(d<m.length&&m.charCodeAt(d)===46){if(d++,d>=m.length||m.charCodeAt(d)<48||m.charCodeAt(d)>57)return!1;while(d<m.length&&m.charCodeAt(d)>=48&&m.charCodeAt(d)<=57)d++}return d===m.length}function Bi(m){let d=m.trim();if(d==="true"||d==="false")return"boolean";if(bs(d))return"number";if(d.startsWith("'")&&d.endsWith("'")||d.startsWith('"')&&d.endsWith('"'))return"string";if(d.startsWith("["))return"unknown[]";if(d.startsWith("{"))return"Record<string, unknown>";return"unknown"}function Li(m){let d=m.trim();if(d.endsWith("as const"))d=d.slice(0,-8).trim();if(d==="true"||d==="false")return d;if(bs(d))return d;let g=Xl(d);if(g!==null)return g;return"unknown"}function Xl(m){if(m==="")return null;if(m.charCodeAt(0)===ne||m.charCodeAt(0)===ae){if(jr(m,0,m.charCodeAt(0))===m.length)return m}let d=zl(m,"+");if(d.length>1){let g=!1,y=!0,C=[];for(let v of d){let k=v.trim(),R=k.charCodeAt(0);if((R===ne||R===ae)&&jr(k,0,R)===k.length)g=!0,C.push(Ql(k));else y=!1}if(y)return ef(C.join(""));if(g)return"string";return null}if(/^[\d\s()+*/%.\-]+$/.test(m)&&/\d/.test(m)&&/[+*/%\-\s]/.test(m))return"number";return null}function zl(m,d){let g=[],y=0,C="",v=0;while(v<m.length){let k=m.charCodeAt(v);if(k===ne||k===ae||k===Te){let R=jr(m,v,k);C+=m.slice(v,R),v=R;continue}if(k===U&&(m.charCodeAt(v+1)===U||m.charCodeAt(v+1)===42)){if(m.charCodeAt(v+1)===U){let x=m.indexOf(`
53
- `,v+2),N=x===-1?m.length:x;C+=m.slice(v,N),v=N;continue}let R=m.indexOf("*/",v+2),E=R===-1?m.length:R+2;C+=m.slice(v,E),v=E;continue}if(k===Q||k===ue||k===_)y++;else if(k===ge||k===Ce||k===G)y--;if(m[v]===d&&y===0){g.push(C),C="",v++;continue}C+=m[v],v++}return g.push(C),g}function Ql(m){return m.slice(1,-1).replace(/\\(.)/g,(d,g)=>{if(g==="n")return`
54
- `;if(g==="t")return"\t";if(g==="r")return"\r";if(g==="0")return"\x00";return g})}function ef(m){return`'${m.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function Sr(m){if(m.endsWith("as const"))return null;let d=0,g=-1;for(let y=0;y<m.length;y++){let C=m.charCodeAt(y);if(C===ne||C===ae||C===Te)y=jr(m,y,C)-1;else if(C===123||C===91||C===40)d++;else if(C===125||C===93||C===41)d--;else if(d===0&&C===32&&y+4<=m.length&&m.substring(y,y+4)===" as ")g=y}if(g===-1)return null;return m.slice(g+4).trim()||null}function or(){if(h(),l<a&&i.charCodeAt(l)===qe){l++,h();let m=l,d=0;while(l<a){if(O())continue;let g=i.charCodeAt(l);if(g===Q||g===ue||g===he)d++;else if(g===ge||g===Ce||g===oe&&!Y())d--;else if(g===_)if(d>0)d++;else{let y=p(m,l),C=(v)=>{let k=y.length-v.length;return k>=0&&y.endsWith(v)&&(k===0||!Je(y.charCodeAt(k-1)))};if(y.length===0||y.endsWith("|")||y.endsWith("&")||C("is")||C("extends"))d++;else break}else if(g===G){if(d===0)break;d--}else if(d===0&&g===Z)break;if(d===0&&J())break;l++}return p(m,l)}return""}function bt(m,d,g,y){l+=8,h();let C=l<a&&i.charCodeAt(l)===Oe;if(C)l++,h();let v=W();if(!v&&!y)return null;h();let k=ot();h();let R=Ct();h();let E=or(),x=E.length>0;if(!E)if(g&&C)E="AsyncGenerator<unknown, void, unknown>";else if(C)E="Generator<unknown, void, unknown>";else if(g)E="Promise<void>";else E="void";h();let N=!1;if(l<a&&i.charCodeAt(l)===_){N=!0;let P=l+1;if(V(_,G),!o&&!x&&!C)E=lr(i.slice(P,l-1),g,R)}else if(l<a&&i.charCodeAt(l)===Z)l++;let M=Dt(R),B=`${d?y?"export default function ":"export declare function ":"declare function "}${v||(y?"":"default")}${k}${M}: ${E};`,I=ve(m);if(N)u.add(f.length);return{kind:"function",name:v||"default",text:B,isExported:d,isDefault:y,isAsync:g,isGenerator:C,returnType:E,generics:k||void 0,leadingComments:I,start:m,end:l}}function Mt(m,d,g){l+=d.length,h();let y=[];do{if(h(),l>=a)break;let C=i.charCodeAt(l);if(C===_||C===ue)return ie(),y;let v=W();if(!v)return ie(),y;h();let k,R,E=!1;if(l<a&&i.charCodeAt(l)===qe){l++,h();let M=l,B=0;while(l<a){if(O())continue;let I=i.charCodeAt(l);if(I===Q||I===_||I===ue||I===he)B++;else if(I===ge||I===G||I===Ce||I===oe&&!Y())B--;else if(B===0&&(I===Z||I===Ue))break;else if(B===0&&I===$e&&!we())break;if(B===0&&F())break;l++}k=p(M,l)}if(l<a&&i.charCodeAt(l)===$e)if(o&&k&&(!s||!ic(k)))kr();else{l++,h();let M=l,B=0,I=0,P=0;while(l<a){if(O())continue;let D=i.charCodeAt(l);if(D===Q||D===_||D===ue)B++;else if(D===ge||D===G||D===Ce)B--;else if(D===he&&B===0){let j=As(l);if(j!==null)P=Math.max(0,P+j);else if(l+1>=a||i.charCodeAt(l+1)!==$e)I++}else if(D===oe&&B===0&&P===0&&!Y()){if(I>0&&(l+1>=a||i.charCodeAt(l+1)!==$e))I--}else if(B===0&&I===0&&P===0&&(D===Z||D===Ue))break;if(B===0&&I===0&&P===0&&F())break;l++}if(R=p(M,l),R.endsWith(" as const")||R==="const"){if(E=!0,!k){let D=R.endsWith(" as const")?R.slice(0,-9).trim():R,j=Li(D);k=j!=="unknown"?j:void 0}}else if(!k){let D=Sr(R);if(D)k=D}}if(l<a){let M=i.charCodeAt(l);if(M===Ue){l++;continue}if(M===Z)l++}let x=ve(m),N=`${g?"export ":""}declare ${d} ${v}: ${k||"unknown"};`;y.push({kind:"variable",name:v,text:N,isExported:g,typeAnnotation:k,value:R,modifiers:E?[d,"const assertion"]:[d],leadingComments:x,start:m,end:l});break}while(l<a);return y}function As(m){if(i.charCodeAt(m)!==he||m+1>=a)return null;let d=i.charCodeAt(m+1);if(d===oe)return 1;if(d===U)return-1;if(!Rt(d))return null;let g=m+2;while(g<a){let x=i.charCodeAt(g);if(!Je(x)&&x!==lt&&x!==58&&x!==45)break;g++}let y=i.slice(m+1,g),C=i.charCodeAt(g);if(C>32&&C!==oe&&C!==U)return null;let v=0,k=0,R=g;for(;R<a;R++){let x=i.charCodeAt(R);if(k!==0){if(x===Ye)R++;else if(x===k)k=0;continue}if(x===ne||x===ae||x===Te)k=x;else if(x===_)v++;else if(x===G&&v>0)v--;else if(x===oe&&v===0)break}if(R>=a)return null;let E=R-1;while(E>m&&i.charCodeAt(E)<=32)E--;if(i.charCodeAt(E)===U)return 0;return i.indexOf(`</${y}`,R+1)===-1?null:1}function ji(m,d){l+=9,h();let g=W();h();let y=ot();h();let C="";if(b("extends")){l+=7,h();let x=l,N=0;while(l<a){if(O())continue;let M=i.charCodeAt(l);if(M===he)N++;else if(M===oe&&!Y())N--;else if(M===_&&N===0)break;l++}C=p(x,l)}h();let v=l<a&&i.charCodeAt(l)===_?Pt():"{}",k=ws(v),R=`${d?"export ":""}declare interface ${g}${y}${C?` extends ${C}`:""} ${k}`,E=ve(m);return{kind:"interface",name:g,text:R,isExported:d,extends:C||void 0,generics:y||void 0,leadingComments:E,start:m,end:l}}function _i(m,d){l+=4,h();let g=W();h();let y=ot();if(h(),l<a&&i.charCodeAt(l)===$e)l++;h();let C=l,v=0;while(l<a){if(O())continue;let x=i.charCodeAt(l);if(x===Q||x===_||x===ue||x===he)v++;else if(x===ge||x===G||x===Ce||x===oe&&!Y())v--;else if(v===0&&x===Z)break;if(v===0&&F())break;l++}let k=p(C,l);if(l<a&&i.charCodeAt(l)===Z)l++;let R=`${d?"export ":""}type ${g}${y} = ${k}`,E=ve(m);return{kind:"type",name:g,text:R,isExported:d,generics:y||void 0,leadingComments:E,start:m,end:l}}function It(m,d,g){l+=4,h();let y=W();h();let C=l;if(l<a&&i.charCodeAt(l)===_)V(_,G);let v=p(m,l),k=ve(m);return{kind:"enum",name:y,text:v,isExported:d,modifiers:g?["const"]:void 0,leadingComments:k,start:m,end:l}}function At(m,d,g,y=!1){l+=5,h();let C=W()||"AnonymousClass";h();let v=ot();h();let k="";if(b("extends")){l+=7,h();let M=l,B=0;while(l<a){if(O())continue;let I=i.charCodeAt(l);if(I===he)B++;else if(I===oe&&!Y())B--;else if(B===0&&(I===_||b("implements")))break;l++}k=p(M,l)}let R;if(b("implements")){l+=10,h();let M=l,B=0;while(l<a){if(O())continue;let P=i.charCodeAt(l);if(P===he)B++;else if(P===oe&&!Y())B--;else if(B===0&&P===_)break;l++}let I=p(M,l);if(I)R=I.split(",").map((P)=>P.trim())}h();let E=Ji(),x=`${d?y?"export default ":"export declare ":"declare "}${g?"abstract ":""}class ${C}${v}${k?` extends ${k}`:""}${R&&R.length>0?` implements ${R.join(", ")}`:""} ${E}`,N=ve(m);return{kind:"class",name:C,text:x,isExported:d,isDefault:y,extends:k||void 0,implements:R,generics:v||void 0,modifiers:g?["abstract"]:void 0,leadingComments:N,start:m,end:l}}function Ji(){if(l>=a||i.charCodeAt(l)!==_)return"{}";l++;let m=[];while(l<a){if(h(),l>=a)break;if(i.charCodeAt(l)===G){l++;break}if(i.charCodeAt(l)===Z){l++;continue}if(b("static")&&vs("static")===_){l+=6,h(),V(_,G);continue}let d=!1,g=!1,y=!1,C=!1,v=!1,k=!1,R=!1,E=!1,x=!0;while(x){if(h(),b("private")){d=!0,l+=7;continue}if(b("protected")){g=!0,l+=9;continue}if(b("public")){l+=6;continue}if(b("static")){y=!0,l+=6;continue}if(b("abstract")){C=!0,l+=8;continue}if(b("readonly")){v=!0,l+=8;continue}if(b("override")){k=!0,l+=8;continue}if(b("accessor")){R=!0,l+=8;continue}if(b("async")){E=!0,l+=5;continue}if(b("declare")){l+=7;continue}break}if(h(),l>=a||i.charCodeAt(l)===G)break;if(i.charCodeAt(l)===Lr)d=!0;if(d){Hi();continue}let N=" ";if(g)N+="protected ";if(y)N+="static ";if(C)N+="abstract ";if(v)N+="readonly ";if(b("constructor")){l+=11,h();let M=Ct();if(h(),tf(M,m),l<a&&i.charCodeAt(l)===_)V(_,G);else if(l<a&&i.charCodeAt(l)===Z)l++;let B=Dt(M);m.push(` constructor${B};`)}else if(b("get"))if(l+=3,h(),l<a&&(Rt(i.charCodeAt(l))||i.charCodeAt(l)===ue||i.charCodeAt(l)===Lr)){let M=Ki();if(M.startsWith("#")){if(h(),l<a&&i.charCodeAt(l)===Q)Ct();if(h(),or(),h(),l<a&&i.charCodeAt(l)===_)V(_,G);else if(l<a&&i.charCodeAt(l)===Z)l++;continue}h(),Ct(),h();let B=or()||"unknown";if(h(),l<a&&i.charCodeAt(l)===_)V(_,G);else if(l<a&&i.charCodeAt(l)===Z)l++;m.push(`${N}get ${M}(): ${B};`)}else xs("get",N,y,v,E,m);else if(b("set"))if(l+=3,h(),l<a&&(Rt(i.charCodeAt(l))||i.charCodeAt(l)===ue||i.charCodeAt(l)===Lr)){let M=Ki();if(M.startsWith("#")){if(h(),l<a&&i.charCodeAt(l)===Q)Ct();if(h(),l<a&&i.charCodeAt(l)===_)V(_,G);else if(l<a&&i.charCodeAt(l)===Z)l++;continue}h();let B=Ct();if(h(),l<a&&i.charCodeAt(l)===_)V(_,G);else if(l<a&&i.charCodeAt(l)===Z)l++;let I=Dt(B);m.push(`${N}set ${M}${I};`)}else xs("set",N,y,v,E,m);else{let M=i.charCodeAt(l)===Oe;if(M)l++,h();let B=Ki();if(!B){Hi();continue}Es(B,N,y,v,M,C,E,m)}}return`{
31
+ }`:"{}";if(a.length===0)return f;let u=a[0];for(let l=1;l<a.length;l++)u=`Omit<${u}, keyof ${a[l]}> & ${a[l]}`;return s.length>0?`Omit<${u}, keyof ${f}> & ${f}`:u}function cr(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(!ft(e.charCodeAt(r)))return!1;return!0}function fr(e){let t=e.split(".");return t.length>0&&t.every(cr)}function Zc(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=Ze(e,n,"<",">");if(s!==-1)n=s}}return-1}function Us(e){if(e.length<3||!e.endsWith(")"))return null;let t=Zc(e);if(t===-1||Ze(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,a=r.indexOf("<");if(a!==-1){if(Ze(r,a,"<",">")!==r.length-1)return null;i=r.slice(0,a).trim(),s=!0}if(!fr(i))return null;let o=e.slice(t+1,-1).trim(),c=Nr(o)!==-1||o.startsWith("function")||o.startsWith("async function"),f=fr(o),u=!c&&o.endsWith(")")&&Us(o)!==null;if(!s&&!n&&!c&&!f&&!u)return null;let l=`ReturnType<typeof ${r}>`;return n?`${l} | undefined`:l}function qc(e){let t=e.split(`
32
+ `).map((f)=>Ys(f)).join(`
33
+ `),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(!ft(f)&&!ft(u))t=(t.slice(0,r)+t.slice(r+5)).trim()}let n=t.indexOf("(");if(n!==-1){let f=Ze(t,n,"(",")");if(f!==-1){let u=t.slice(n,f+1),l=Gt(u);t=t.slice(0,n)+l+t.slice(f+1)}}let i=t.length,s="",a=[],o=!1,c=!1;for(let f=0;f<i;f++){let u=t.charCodeAt(f);if(u===123||u===40)a.push(u);else if(u===125||u===41)a.pop();if(u<=32){if(o=!0,u===10||u===13)c=!0;continue}if(o&&s.length>0){let l=(a.length>0?a[a.length-1]:0)===123;if(c&&l){let g=s.charCodeAt(s.length-1),h=g===59||g===44||g===123||u===125,w=s.length>=2&&s.charCodeAt(s.length-1)===47&&s.charCodeAt(s.length-2)===42;if(!h&&!w)s+="; ";else s+=" "}else s+=" "}o=!1,c=!1,s+=t[f]}return s.trim()}function ft(e){return e>=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57||e===95||e===36}function Gt(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 w=0;for(let v=0;v<i.length;v++){let C=i.charCodeAt(v);if(C===40||C===60||C===91||C===123)w++;else if(C===41||C===62||C===93||C===125)w--;else if(w===0&&C===61){let x=v>0?i.charCodeAt(v-1):0,O=v+1<i.length?i.charCodeAt(v+1):0;if(x!==61&&x!==33&&x!==60&&x!==62&&O!==61&&O!==62){s=!0;break}}}}if(!s)return t;let a=[],o=[],c=0,f=0,u=!1,l=0;for(let w=0;w<=i.length;w++){if(w===i.length){a.push(i.slice(c));break}let v=i.charCodeAt(w);if(u){if(v===92){w++;continue}if(v===l)u=!1;continue}if(v===47&&w+1<i.length){let C=i.charCodeAt(w+1);if(C===42){w+=2;while(w+1<i.length&&!(i.charCodeAt(w)===42&&i.charCodeAt(w+1)===47))w++;w++;continue}if(C===47){while(w<i.length&&i.charCodeAt(w)!==10)w++;continue}}if(v===39||v===34||v===96){u=!0,l=v;continue}if(v===40||v===60||v===91||v===123)f++;else if(v===41||v===62||v===93||v===125)f--;else if(v===44&&f===0){a.push(i.slice(c,w));let C=",",x=w+1;while(x<i.length&&i.charCodeAt(x)<=32)C+=i[x],x++;o.push(C),c=x}}let g=[];for(let w of a){let v=w.trim();if(!v){g.push(w);continue}if(v.startsWith("//"))continue;let C=Ys(v),x=w.slice(0,w.length-w.trimStart().length);g.push(x+Xc(C))}let h=g[0]||"";for(let w=1;w<g.length;w++)h+=(o[w-1]||", ")+g[w];return n?`(${h})`:h}function Ys(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 Xc(e){if(e.startsWith("..."))return e;let t=-1,r=-1,n=0,i=!1,s=0;for(let o=0;o<e.length;o++){let c=e.charCodeAt(o);if(i){if(c===92){o++;continue}if(c===s)i=!1;continue}if(c===47&&o+1<e.length){let f=e.charCodeAt(o+1);if(f===42){o+=2;while(o+1<e.length&&!(e.charCodeAt(o)===42&&e.charCodeAt(o+1)===47))o++;o++;continue}if(f===47){while(o<e.length&&e.charCodeAt(o)!==10)o++;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=o;else if(c===61&&r===-1&&(o===0||e.charCodeAt(o-1)!==61)&&(o+1>=e.length||e.charCodeAt(o+1)!==61&&e.charCodeAt(o+1)!==62))r=o}}let a=r!==-1;if(t!==-1&&(r===-1||t<r)){let o=e.slice(0,t).trim(),c=r!==-1?e.slice(t+1,r).trim():e.slice(t+1).trim(),f=a&&!o.endsWith("?")?"?":"";return`${o}${f}: ${c}`}else if(r!==-1){let o=e.slice(0,r).trim(),c=!o.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`${o}${c}: ${u}`}return e}function zc(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 Qc(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(`
34
+ `),key:e.slice(r).trim()}}function ef(e){let t=[],r="",n="",i=0,s=!1,a="",o=!0,c=!1,f=0,u=!1,l=!1,g=0,h=!1,w=!1;for(let v=0;v<e.length;v++){let C=e.charCodeAt(v),x=v>0?e.charCodeAt(v-1):0,O=v<e.length-1?e.charCodeAt(v+1):0;if(!s&&!c&&C===47&&O===47){v+=2;while(v<e.length&&e.charCodeAt(v)!==10)v++;continue}if(!s&&!c&&C===47&&O===42){c=!0,f=1,r+="/*",v++;continue}else if(c&&C===42&&O===47){if(f--,r+="*/",v++,f===0)c=!1;continue}else if(c&&C===47&&O===42){f++,r+="/*",v++;continue}let R=e[v];if(!s&&(C===34||C===39||C===96))s=!0,a=R,r+=R;else if(s&&R===a&&x!==92)s=!1,r+=R;else if(!s&&!c)if(C===40&&i===0&&o&&g===0){n=r.trim();let k=zc(n),E=k>0?n.slice(0,k):"",G=n.slice(k),re="";if(G.startsWith("async ")||G.startsWith("async\t")||G.startsWith(`async
35
+ `))G=G.slice(6).trimStart(),re="async ";if(G.startsWith("*"))G=G.slice(1).trimStart(),re+="*";n=E+G,r=re+R,o=!1,h=!0,w=!1,i=1}else if(C===123||C===91||C===40){if(i++,r+=R,w&&C===123)w=!1}else if(C===125||C===93||C===41){if(i--,r+=R,C===41&&i===0&&!o&&!h)u=!0;if(h){if(C===41&&i===0&&!w)w=!0;else if(C===125&&i===0)h=!1,w=!1}}else if(C===58&&i===0&&o&&g===0)n=r.trim(),r="",o=!1;else if(C===58&&i===0&&u)l=!0,r+=R;else if(C===60&&l)g++,r+=R;else if(C===60&&o&&i===0)g++,r+=R;else if(C===62&&g>0&&x!==61)g--,r+=R;else if(C===61&&O===62&&l&&g===0)l=!1,u=!1,r+=R;else if(C===44&&i===0&&g===0&&!w){if(n&&r.trim()){let k=r.trim();t.push([n,k])}else if(o&&r.trim()){let k=r.trim();if(cr(k))t.push([k,k]);else if(k.startsWith("...")&&k.length>3)t.push(["...",k.slice(3).trim()])}r="",n="",o=!0,u=!1,l=!1,g=0}else r+=R;else r+=R}if(n&&r.trim()){let v=r.trim();t.push([n,v])}else if(o&&r.trim()){let v=r.trim();if(cr(v))t.push([v,v]);else if(v.startsWith("...")&&v.length>3)t.push(["...",v.slice(3).trim()])}return t}function tf(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 rf(e,t,r){let n=r.trim();if(n.charCodeAt(0)!==40)return null;let i=Ze(n,0,"(",")");if(i===-1)return null;let s=n.slice(1,i).trim(),a=n.slice(i+1).trimStart();if(!a.startsWith("=>"))return null;let o=a.slice(2).trim();if(e==="get")return`get ${t}(): ${o||"unknown"}`;return`set ${t}(${s})`}function nf(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 a=Zs(s,1);if(a?.kind==="arrow")return!1;if(a?.kind==="body")return!0}return!1}}}return!1}function sf(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 a=t.charCodeAt(s);if(a===62){if(s>0&&t.charCodeAt(s-1)===61)continue;r++}else if(a===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 _s(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,h=-1;for(let w=0;w<r.length;w++)if(r.charCodeAt(w)===60)g++;else if(r.charCodeAt(w)===62&&!(w>0&&r.charCodeAt(w-1)===61)){if(g--,g===0){h=w;break}}if(h!==-1)s=r.slice(0,h+1),r=r.slice(h+1).trimStart()}let a=r.indexOf("("),o=Ze(r,a,"(",")");if(a===-1||o===-1)return"() => unknown";let c=r.slice(a,o+1),f="unknown",u=r.slice(o+1).trimStart();if(u.charCodeAt(0)===58){let g=u.slice(1),h=Zs(g,0);if(h)f=g.slice(0,h.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=Gt(c);return`${s}${l} => ${f}`}function Zs(e,t){let r=0,n=0,i=0,s=0,a=!1,o=0;for(let c=t;c<e.length;c++){let f=e.charCodeAt(c);if(a){if(f===92)c++;else if(f===o)a=!1;continue}if(f===34||f===39||f===96){a=!0,o=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),h=l.length===0||g===38||g===124||g===40||g===44||g===58||g===61||g===91;if(u||h)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 Ze(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 Nr(e){let t=0,r=0,n=!1,i="";for(let s=0;s<e.length-1;s++){let a=e[s],o=e[s+1],c=s>0?e[s-1]:"";if(!n&&(a==='"'||a==="'"||a==="`"))n=!0,i=a;else if(n&&a===i&&c!=="\\")n=!1;if(!n){if(a==="<"){let f=Ze(e,s,"<",">");if(f!==-1){s=f;continue}}if(a==="(")t++;else if(a===")")t--;else if(a==="[")r++;else if(a==="]")r--;if(a==="="&&o===">"&&t===0&&r===0)return s}}return-1}function qs(e,t=!1,r=0,n=!0){let i=e.trim();if(i.length>200&&Zi(i,"=>")>2&&Zi(i,"<")>5&&!i.startsWith("function"))return t?"((...args: any[]) => any)":"(...args: any[]) => any";if(i.startsWith("async ")&&i.includes("=>")){let a=i.slice(5).trim(),o=Nr(a);if(o===-1)return t?"(() => Promise<unknown>)":"() => Promise<unknown>";let c=a.substring(0,o).trim(),f=a.substring(o+2).trim(),u=Hs(c),l=u.params,g=u.returnType;if(l=Gt(l),l==="()"||l==="")l="()";else if(!l.startsWith("("))l=`(${l})`;let h=g;if(h);else if(f.startsWith("{"))h=lr(f.slice(1,f.endsWith("}")?-1:void 0),!0,l);else h=Ae(f,n,!1,r+1);let w=`${l} => ${g||h.startsWith("Promise<")?h:`Promise<${h}>`}`;return t?`(${w})`:w}if(i.includes("=>")){let a="",o=i;if(i.startsWith("<")){let C=Ze(i,0,"<",">");if(C!==-1)a=i.substring(0,C+1),o=i.substring(C+1).trim()}let c=Nr(o);if(c===-1)return t?"(() => unknown)":"() => unknown";let f=o.substring(0,c).trim(),u=o.substring(c+2).trim(),l=Hs(f),g=l.params,h=l.returnType;if(g=Gt(g),g==="()"||g==="")g="()";else if(!g.startsWith("("))g=`(${g})`;let w="unknown";if(h)w=h;else if(u.startsWith("{"))w=lr(u.slice(1,u.endsWith("}")?-1:void 0),!1,g);else if(Dr(u)||Ks(u)&&Dr(u.slice(1,-1).trim()))w="JSX.Element";else if(u.includes("=>")){let C=u.trimStart(),x=C.indexOf("("),O=x!==-1?Ze(C,x,"(",")"):-1,R=O!==-1?C.indexOf("=>",O):-1;if(x===0&&O!==-1&&R!==-1){let k=C.substring(x+1,O).trim(),E=Gt(k);if(a.includes("T")&&E.includes("T"))w=`(${E}) => T`;else w=`(${E}) => any`}else w="any"}else if(t)w="unknown";else w=Rt(u,js(g));let v=`${a}${g} => ${w}`;return t?`(${v})`:v}if(i.startsWith("function")){let a=8,o=i.length;while(a<o&&i.charCodeAt(a)<=32)a++;let c=!1;if(a<o&&i.charCodeAt(a)===42){c=!0,a++;while(a<o&&i.charCodeAt(a)<=32)a++}let f="";if(a<o&&i.charCodeAt(a)===60){let g=a,h=1;a++;while(a<o&&h>0){let w=i.charCodeAt(a);if(w===60)h++;else if(w===62&&i.charCodeAt(a-1)!==61)h--;a++}f=i.substring(g,a);while(a<o&&i.charCodeAt(a)<=32)a++}let u=i.indexOf("(",a);if(u!==-1){let g=1,h=u+1;while(h<o&&g>0){let x=i.charCodeAt(h);if(x===40)g++;else if(x===41)g--;h++}let w=i.substring(u+1,h-1).trim(),v=w?`(${w})`:"()";if(c){let x=i.substring(h).trim(),O=x.indexOf("Generator<");if(O!==-1){let k=O+10,E=x.indexOf(">",k);if(E!==-1){let G=x.substring(k,E),re=`${f}${v} => Generator<${G}>`;return t?`(${re})`:re}}let R=`${f}${v} => Generator<any, any, any>`;return t?`(${R})`:R}let C=`${f}${v} => 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||Zi(i,"=>")>2){let a="";if(i.charCodeAt(0)===60){let l=Ze(i,0,"<",">");if(l!==-1)a=i.substring(0,l+1)}let o=i.indexOf("("),c=o!==-1?Ze(i,o,"(",")"):-1,f=o!==-1&&c!==-1?i.substring(o,c+1):"(...args: any[])";f=Gt(f);let u=`${a}${f} => any`;return t?`(${u})`:u}return t?`(${i})`:i}let s="() => unknown";return t?`(${s})`:s}function Hs(e){let t=e.trim();if(!t.startsWith("("))return{params:t,returnType:""};let r=Ze(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 Xs(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 zs(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 Lr=!1,Ve=null;var rn=()=>{};function Pe(e){return e===Te||e===Re||e===ge||e===Ee}function Pt(e){return e>=65&&e<=90||e>=97&&e<=122||e===of||e===ta||e>127}function _e(e){return Pt(e)||e>=48&&e<=57}function lf(e){let t=!0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n===ot){if(t)return!1;t=!0}else if(t){if(!Pt(n))return!1;t=!1}else if(!_e(n))return!1}return e.length>0&&!t}function Br(e,t,r){let n=t+1;while(n<e.length){let i=e.charCodeAt(n);if(i===Ke){n+=2;continue}if(n++,i===r)break}return n}function cf(e){if(e==="any"||e==="object"||e==="unknown")return!0;if(e.startsWith("Record<")||e.startsWith("Array<"))return!0;return e.charCodeAt(0)===V&&e.includes("[")&&e.includes("]:")}function ra(e,t,r=!0){return na(e,t,r,!0)}function ia(e,t,r=!0){return na(e,t,r,!1)}function na(e,t,r,n){let i=e,s=r,a=n,o=i.length,c=[],f=new Map,u=new Set,l=0;if(l<o&&i.charCodeAt(l)===65279)l++;function g(m,d){if(m<d){let p=i.charCodeAt(m),y=i.charCodeAt(d-1);if(p!==Te&&p!==Re&&p!==ge&&p!==Ee&&y!==Te&&y!==Re&&y!==ge&&y!==Ee)return i.slice(m,d)}while(m<d&&Pe(i.charCodeAt(m)))m++;while(d>m&&Pe(i.charCodeAt(d-1)))d--;return i.slice(m,d)}function h(){if(l>=o)return;let m=i.charCodeAt(l);if(m!==Te&&m!==Re&&m!==ge&&m!==Ee&&m!==q)return;while(l<o){let d=i.charCodeAt(l);if(d===Te||d===Re||d===ge||d===Ee){l++;continue}if(d===q&&l+1<o){let p=i.charCodeAt(l+1);if(p===q){let y=i.indexOf(`
36
+ `,l+2);l=y===-1?o:y+1;continue}if(p===xe){let y=i.indexOf("*/",l+2);l=y===-1?o:y+2;continue}}break}}function w(m){let d=m.length,p=0,y=d;for(let $=0;$<d;$++){let b=m.charCodeAt($);if(p){if(b===Ke){$++;continue}if(b===p)p=0;continue}if(b===ne||b===le||b===Oe){p=b;continue}if(b===q&&$+1<d){let T=m.charCodeAt($+1);if(T===q){y=$;while(y>0&&(m.charCodeAt(y-1)===Te||m.charCodeAt(y-1)===Re))y--;return m.slice(0,y)}if(T===xe){let P=m.indexOf("*/",$+2);if(P!==-1){m=`${m.slice(0,$)} ${m.slice(P+2)}`,$--;continue}}}}y=d;while(y>0&&(m.charCodeAt(y-1)===Te||m.charCodeAt(y-1)===Re||m.charCodeAt(y-1)===Ee))y--;return y<d?m.slice(0,y):m}function v(m){l++;let d=m===ne?"'":'"';while(l<o){let p=i.indexOf(d,l);if(p===-1){l=o;return}let y=0,$=p-1;while($>=0&&i.charCodeAt($)===Ke)y++,$--;if(y%2===0){l=p+1;return}l=p+1}}function C(){l++;let m=[];while(l<o){let d=i.charCodeAt(l);if(m.length===0){if(d===Ke){l+=2;continue}if(d===Oe){l++;return}if(d===ta&&l+1<o&&i.charCodeAt(l+1)===V){l+=2,m.push(0);continue}l++;continue}if(d===ne||d===le){v(d);continue}if(d===Oe){C();continue}if(d===q&&l+1<o){let p=i.charCodeAt(l+1);if(p===q){let y=i.indexOf(`
37
+ `,l+2);l=y===-1?o:y+1;continue}if(p===xe){let y=i.indexOf("*/",l+2);l=y===-1?o:y+2;continue}if(O()){R();continue}l++;continue}if(d===V){m[m.length-1]++,l++;continue}if(d===J){let p=m[m.length-1];if(p===0){m.pop(),l++;continue}m[m.length-1]=p-1,l++;continue}l++}}function x(){let m=i.charCodeAt(l);if(m===ne||m===le)return v(m),!0;if(m===Oe)return C(),!0;if(m===q&&l+1<o){let d=i.charCodeAt(l+1);if(d===q){let p=i.indexOf(`
38
+ `,l+2);return l=p===-1?o:p+1,!0}if(d===xe){let p=i.indexOf("*/",l+2);return l=p===-1?o:p+2,!0}if(O())return R(),!0}return!1}function O(){let m=l-1;while(m>=0&&(i.charCodeAt(m)===Te||i.charCodeAt(m)===Re||i.charCodeAt(m)===ge||i.charCodeAt(m)===Ee))m--;if(m<0)return!0;let d=i.charCodeAt(m);if(d===Ce||d===Q||d===he||d===33||d===38||d===124||d===Wr||d===qe||d===Xe||d===Y||d===V||d===J||d===94||d===126||d===43||d===45||d===xe||d===37||d===de||d===oe)return!0;if(_e(d)){let p=m;while(p>=0&&_e(i.charCodeAt(p)))p--;let y=i.slice(p+1,m+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 R(){l++;let m=!1;while(l<o){let d=i.charCodeAt(l);if(d===Ke){l+=2;continue}if(m){if(d===$e)m=!1;l++;continue}if(d===he){m=!0,l++;continue}if(d===q){l++;break}if(d===ge||d===Ee)break;l++}while(l<o&&_e(i.charCodeAt(l)))l++}function k(){let m=l;while(l<o&&_e(i.charCodeAt(l)))l++;return i.slice(m,l)}function E(m){if(l+m.length>o)return!1;for(let d=0;d<m.length;d++)if(i.charCodeAt(l+d)!==m.charCodeAt(d))return!1;if(l+m.length<o&&_e(i.charCodeAt(l+m.length)))return!1;return!0}function G(m){let d=l+m;while(d<o){let p=i.charCodeAt(d);if(p===Te||p===Re||p===ge||p===Ee){d++;continue}return p!==ot&&p!==Ce}return!1}function re(){if(l>=o)return!1;switch(i.charCodeAt(l)){case 101:return E("export")||E("enum");case 105:return E("import")||E("interface");case 102:return E("function");case 99:return E("class")||E("const");case 116:return E("type");case 108:return E("let");case 118:return E("var");case 100:return E("declare")||E("default");case 109:return E("module");case 110:return E("namespace");case 97:return E("abstract")||E("async");default:return!1}}function I(){let m=i.charCodeAt(l);if(m!==ge&&m!==Ee)return!1;let d=l;if(l++,m===Ee&&l<o&&i.charCodeAt(l)===ge)l++;while(l<o){let y=i.charCodeAt(l);if(y===Te||y===Re||y===Ee||y===ge){l++;continue}if(y===q&&l+1<o){let $=i.charCodeAt(l+1);if($===q){let b=i.indexOf(`
39
+ `,l+2);l=b===-1?o:b+1;continue}if($===xe){let b=i.indexOf("*/",l+2);l=b===-1?o:b+2;continue}}break}let p=l>=o||re()||i.charCodeAt(l)===J;return l=d,p}function _(){let m=i.charCodeAt(l);if(m!==ge&&m!==Ee)return!1;let d=l;if(l++,m===Ee&&l<o&&i.charCodeAt(l)===ge)l++;while(l<o){let y=i.charCodeAt(l);if(y===Te||y===Re||y===Ee||y===ge){l++;continue}if(y===q&&l+1<o&&i.charCodeAt(l+1)===q){let $=i.indexOf(`
40
+ `,l+2);l=$===-1?o:$+1;continue}break}if(l>=o)return l=d,!0;let p=i.charCodeAt(l);if(p===124||p===38||p===ot||p===Wr||p===qe)return l=d,!1;if(E("extends")||E("keyof")||E("typeof")||E("infer")||E("is")||E("as")||E("in"))return l=d,!1;return l=d,!0}let X=/[{}'"`\/]/g,se=/[()'"`\/]/g,j=/[[\]'"`\/]/g,Z=/[<>'"`\/]/g;function U(m,d){let p=1;l++;let y=m===V?X:m===Q?se:m===he?j:Z;y.lastIndex=l;let $;while(($=y.exec(i))!==null){let b=$.index,T=i.charCodeAt(b);if(T===ne||T===le){l=b,v(T),y.lastIndex=l;continue}if(T===Oe){l=b,C(),y.lastIndex=l;continue}if(T===q){if(l=b,x()){y.lastIndex=l;continue}y.lastIndex=b+1;continue}if(T===m)p++;else if(T===d){if(d===oe&&b>0&&i.charCodeAt(b-1)===Ce){y.lastIndex=b+1;continue}if(p--,p===0)return l=b+1,l}y.lastIndex=b+1}return l=o,l}function K(){return l>0&&i.charCodeAt(l-1)===Ce}function we(){return l+1<o&&i.charCodeAt(l+1)===oe}let z=/[<{};'"`\/\n\r()[\]]/g;function ie(){let m=0,d=0,p=0,y=0,$=i.charCodeAt(l)===V;z.lastIndex=l;let b;while((b=z.exec(i))!==null){let T=b.index,P=i.charCodeAt(T);if(P===ne||P===le){l=T,v(P),z.lastIndex=l;continue}if(P===Oe){l=T,C(),z.lastIndex=l;continue}if(P===q){if(T>0&&i.charCodeAt(T-1)===de){z.lastIndex=T+1;continue}if(l=T,x()){z.lastIndex=l;continue}z.lastIndex=T+1;continue}if(P===de){let A=vs(T);if(A!==null)y=Math.max(0,y+A);z.lastIndex=T+1;continue}if(P===Q){d++,z.lastIndex=T+1;continue}if(P===pe){d--,z.lastIndex=T+1;continue}if(P===he){p++,z.lastIndex=T+1;continue}if(P===$e){p--,z.lastIndex=T+1;continue}if(P===V){m++,z.lastIndex=T+1;continue}if(P===J){let A=m>0;if(A)m--;if((!A||$)&&m===0&&d===0&&p===0&&y===0){l=T+1;return}z.lastIndex=T+1;continue}if(P===Y&&m===0&&d===0&&p===0&&y===0){l=T+1;return}if((P===ge||P===Ee)&&m===0&&d===0&&p===0&&y===0){if(l=T,I())return}z.lastIndex=T+1}l=o}function Tr(){l++;while(l<o&&(i.charCodeAt(l)===Te||i.charCodeAt(l)===Re))l++;let m=i.indexOf(`
41
+ `,l),d=m===-1?o:m,p=i.indexOf(";",l);if(p!==-1&&p<d){let y=p-1;while(y>=l&&(i.charCodeAt(y)===Te||i.charCodeAt(y)===Re))y--;let $=i.charCodeAt(l),b=i.charCodeAt(y);if($===V&&b===J||$===he&&b===$e||$===ne&&b===ne||$===le&&b===le||$===Oe&&b===Oe){l=p+1;return}}ie()}function Tt(){U(V,J);while(l<o&&Pe(i.charCodeAt(l)))l++;if(E("from")){l+=4;while(l<o&&Pe(i.charCodeAt(l)))l++;if(l<o){let m=i.charCodeAt(l);if(m===ne||m===le)v(m)}}while(l<o&&(i.charCodeAt(l)===Te||i.charCodeAt(l)===Re))l++;if(l<o&&i.charCodeAt(l)===Y)l++}function wt(){l++;while(l<o&&Pe(i.charCodeAt(l)))l++;if(E("as")){l+=2;while(l<o&&Pe(i.charCodeAt(l)))l++;k();while(l<o&&Pe(i.charCodeAt(l)))l++}if(E("from")){l+=4;while(l<o&&Pe(i.charCodeAt(l)))l++;if(l<o){let m=i.charCodeAt(l);if(m===ne||m===le)v(m)}}while(l<o&&(i.charCodeAt(l)===Te||i.charCodeAt(l)===Re))l++;if(l<o&&i.charCodeAt(l)===Y)l++}function Fe(m){let d=m.indexOf("from ");if(d===-1)return;let p=d+5;while(p<m.length&&(m.charCodeAt(p)===32||m.charCodeAt(p)===9))p++;if(p>=m.length)return;let y=m.charCodeAt(p);if(y!==39&&y!==34)return;let $=m.indexOf(m[p],p+1);if($===-1)return;return m.slice(p+1,$)}function be(m){if(!s)return;let d=m-1;while(d>=0&&Pe(i.charCodeAt(d)))d--;if(d<0)return;let p=[],y=!1;while(d>=0){if(d>=1&&i.charCodeAt(d)===q&&i.charCodeAt(d-1)===xe){let T=i.lastIndexOf("/*",d-2);if(T>=0){p.push(i.slice(T,d+1)),y=!0,d=T-1;while(d>=0&&Pe(i.charCodeAt(d)))d--;continue}break}let $=d;while($>0&&i.charCodeAt($-1)!==ge)$--;let b=g($,d+1);if(b.startsWith("//")){if(y)break;let T=[b];d=$-1;while(d>=0&&(i.charCodeAt(d)===ge||i.charCodeAt(d)===Ee))d--;while(d>=0){let P=d;while(P>0&&i.charCodeAt(P-1)!==ge)P--;let A=g(P,d+1);if(A.startsWith("//")){T.push(A),d=P-1;while(d>=0&&(i.charCodeAt(d)===ge||i.charCodeAt(d)===Ee))d--}else if(A===""){d=P-1;while(d>=0&&(i.charCodeAt(d)===ge||i.charCodeAt(d)===Ee))d--}else break}T.reverse(),p.push(T.join(`
42
+ `));continue}break}if(p.length===0)return;return p.reverse(),p}function It(m){let d=m,p=!1;while(l<o){let A=i.charCodeAt(l);if(A===Y){l++;break}if(A===ne||A===le){v(A),p=!0;while(l<o&&(i.charCodeAt(l)===Te||i.charCodeAt(l)===Re))l++;if(l<o&&i.charCodeAt(l)===Y)l++;break}if(A===ge&&p)break;l++}let y=g(d,l),$=y.charCodeAt(7)===116&&(y.startsWith("import type ")||y.startsWith("import type{")),b=!1;{let A=6;while(A<y.length&&(y.charCodeAt(A)===Te||y.charCodeAt(A)===Re))A++;if(A<y.length&&y.charCodeAt(A)===116&&y.startsWith("type",A)){A+=4;while(A<y.length&&(y.charCodeAt(A)===Te||y.charCodeAt(A)===Re))A++}if(A<y.length){let S=y.charCodeAt(A);b=S===ne||S===le}}let T="";{let A=y.indexOf("from ");if(A!==-1){let S=A+5;while(S<y.length&&(y.charCodeAt(S)===Te||y.charCodeAt(S)===Re))S++;if(S<y.length){let M=y.charCodeAt(S);if(M===ne||M===le){let N=y.indexOf(String.fromCharCode(M),S+1);if(N!==-1)T=y.slice(S+1,N)}}}else if(b){let S=6;while(S<y.length&&y.charCodeAt(S)!==ne&&y.charCodeAt(S)!==le)S++;if(S<y.length){let M=y.charCodeAt(S),N=y.indexOf(String.fromCharCode(M),S+1);if(N!==-1)T=y.slice(S+1,N)}}}let P=be(d);return{kind:"import",name:"",text:y,isExported:!1,isTypeOnly:$,isSideEffect:b,source:T,leadingComments:P,start:d,end:l}}function Dt(){let m=l;return U(V,J),i.slice(m,l)}function Cs(m){let d=m.indexOf("(");if(d===-1)return m;let p=m.slice(d);if(p.indexOf("=")===-1)return m;let y=!1;for(let A=0;A<p.length;A++)if(p.charCodeAt(A)===61){let S=A>0?p.charCodeAt(A-1):0,M=A+1<p.length?p.charCodeAt(A+1):0;if(S!==61&&S!==33&&S!==60&&S!==62&&M!==61&&M!==62){y=!0;break}}if(!y)return m;let $=0,b=-1;for(let A=d;A<m.length;A++){let S=m.charCodeAt(A);if(S===40)$++;else if(S===41){if($--,$===0){b=A;break}}}if(b===-1)return m;let T=m.slice(d,b+1),P=Ft(T);return m.slice(0,d)+P+m.slice(b+1)}function ws(m){let d=m.indexOf("//")!==-1||m.indexOf("/*")!==-1,p=m.split(`
43
+ `),y=[],$=[],b=[],T=!1,P=1/0;for(let M=0;M<p.length;M++){let N=p[M];if(d){if(T){if(N.includes("*/"))T=!1;continue}let W=N.trim();if(W.length===0)continue;let L=W.charCodeAt(0);if(L===q){let Se=W.charCodeAt(1);if(Se===q)continue;if(Se===xe){if(!W.includes("*/"))T=!0;continue}}if(L===xe)continue;let D=w(N);if(D.charCodeAt(D.length-1)===Y)D=D.slice(0,-1);D=Cs(D);let F=D.trim();if(!F)continue;y.push(D),$.push(F);let B=0;while(B<D.length&&Pe(D.charCodeAt(B)))B++;if(F!=="{"&&F!=="}"){if(B<P)P=B}b.push(B)}else{let W=N.length;while(W>0&&(N.charCodeAt(W-1)===Te||N.charCodeAt(W-1)===Re||N.charCodeAt(W-1)===Ee))W--;if(W===0)continue;let L=W<N.length?N.slice(0,W):N;if(L.charCodeAt(L.length-1)===Y)L=L.slice(0,-1);L=Cs(L);let D=L.trim();if(!D)continue;y.push(L),$.push(D);let F=0;while(F<L.length&&Pe(L.charCodeAt(F)))F++;if(D!=="{"&&D!=="}"){if(F<P)P=F}b.push(F)}}if(y.length===0)return"{}";if(P===1/0||P<=2)return y.join(`
44
+ `);let A=P-2,S=Array(y.length);for(let M=0;M<y.length;M++){let N=$[M];if(N==="{"){S[M]=N;continue}let W=b[M];if(W>P)S[M]=y[M];else if(W===P&&(N.charCodeAt(0)===J||N.charCodeAt(0)===$e||N.charCodeAt(0)===pe))S[M]=y[M];else{let L=Math.max(0,W-A);S[M]=" ".repeat(L)+N}}return S.join(`
45
+ `)}function at(){if(l>=o||i.charCodeAt(l)!==de)return"";let m=l;U(de,oe);let d=i.slice(m,l);if(d.includes(`
46
+ `)){let p="",y=!1;for(let $=0;$<d.length;$++){let b=d.charCodeAt($);if(b===32||b===9||b===10||b===13){if(!y&&p.length>0)p+=" ",y=!0}else p+=d[$],y=!1}if(p.charCodeAt(1)===32)p=`<${p.slice(2)}`;if(p.charCodeAt(p.length-2)===32)p=`${p.slice(0,-2)}>`;return p}return d}function $t(){if(l>=o||i.charCodeAt(l)!==Q)return"()";let m=l;return U(Q,pe),i.slice(m,l)}function Ft(m){let d=m.slice(1,-1).trim();if(!d)return"()";if(m.indexOf(`
47
+ `)===-1&&d.indexOf(":")!==-1&&d.indexOf("{")===-1&&d.indexOf("[")===-1&&d.indexOf("=")===-1&&d.indexOf("@")===-1&&d.indexOf("...")===-1){let A=0,S=0,M=0;for(let N=0;N<d.length;N++){let W=d.charCodeAt(N);if(W===Q||W===de||W===V)M++;else if(W===pe||W===oe||W===J)M--;else if(M===0){if(W===qe)A++;else if(W===Xe)S++}}if(A>=S+1){let N=!1;for(let W=0;W<nn.length;W++){let L=nn[W],D=d.indexOf(L);if(D!==-1){let F=D+L.length;if((D===0||!_e(d.charCodeAt(D-1)))&&(F>=d.length||!_e(d.charCodeAt(F)))){N=!0;break}}}if(!N)return m}}let p=[],y=0,$=0,b=!1,T=0;for(let A=0;A<=d.length;A++){if(A===d.length){p.push(d.slice(y).trim());break}let S=d.charCodeAt(A);if(b){if(S===Ke){A++;continue}if(S===T)b=!1;continue}if(S===q&&A+1<d.length){let M=d.charCodeAt(A+1);if(M===xe){A+=2;while(A+1<d.length&&!(d.charCodeAt(A)===xe&&d.charCodeAt(A+1)===q))A++;A++;continue}if(M===q){while(A<d.length&&d.charCodeAt(A)!==10)A++;continue}}if(S===ne||S===le||S===Oe){b=!0,T=S;continue}if(S===Q||S===V||S===he||S===de)$++;else if(S===pe||S===J||S===$e||S===oe&&!(A>0&&d.charCodeAt(A-1)===Ce))$--;else if(S===Xe&&$===0)p.push(d.slice(y,A).trim()),y=A+1}let P=[];for(let A of p){if(!A)continue;let S=A.trim();if(S.startsWith("//")||S.startsWith("/*"))continue;let M=A;{let N=!1,W=0,L=0,D=0;for(let F=0;F<M.length-1;F++){let B=M.charCodeAt(F);if(B===ge){D=F+1;continue}if(N){if(B===Ke){F++;continue}if(B===W)N=!1;continue}if(B===ne||B===le||B===Oe){N=!0,W=B;continue}if(B===V||B===he||B===Q||B===de){L++;continue}if(B===J||B===$e||B===pe||B===oe){if(L>0)L--;continue}if(B===q&&M.charCodeAt(F+1)===q){if(L===0){M=M.slice(0,F).trimEnd();break}let Se=M.indexOf(`
48
+ `,F);if(Se===-1){M=M.slice(0,D).trimEnd();break}let bt=M.slice(0,D),lc=M.slice(Se+1);M=`${bt}${lc}`,F=D-1}}}if(!M.trim())continue;P.push($s(M))}return`(${P.join(", ")})`}function tc(m){if(!m.startsWith("{")&&!m.startsWith("["))return m;let d="",p=0,y=0,$=!1,b=0;while(p<m.length){let T=m.charCodeAt(p);if($){if(T===Ke&&p+1<m.length){d+=m[p]+m[p+1],p+=2;continue}if(T===b)$=!1;d+=m[p],p++;continue}if(T===q&&p+1<m.length){let P=m.charCodeAt(p+1);if(P===xe){let A=p;p+=2;while(p+1<m.length&&!(m.charCodeAt(p)===xe&&m.charCodeAt(p+1)===q))p++;p=Math.min(p+2,m.length),d+=m.slice(A,p);continue}if(P===q){let A=p;while(p<m.length&&m.charCodeAt(p)!==10)p++;d+=m.slice(A,p);continue}}if(T===ne||T===le||T===Oe){$=!0,b=T,d+=m[p],p++;continue}if(T===V||T===he||T===Q)y++;else if(T===J||T===$e||T===pe)y--;if(y>=1&&T===Ce&&(p+1>=m.length||m.charCodeAt(p+1)!==Ce&&m.charCodeAt(p+1)!==oe)){while(d.length>0&&(d[d.length-1]===" "||d[d.length-1]==="\t"||d[d.length-1]===`
49
+ `))d=d.slice(0,-1);p++;let P=0;while(p<m.length){let A=m.charCodeAt(p);if(A===ne||A===le||A===Oe){let S=A;p++;while(p<m.length){if(m.charCodeAt(p)===Ke){p+=2;continue}if(m.charCodeAt(p)===S){p++;break}p++}continue}if(A===V||A===he||A===Q)P++;else if(A===J||A===$e||A===pe){if(P===0)break;P--}else if(A===Xe&&P===0)break;p++}continue}if(y===1&&T===ot&&p+2<m.length&&m.charCodeAt(p+1)===ot&&m.charCodeAt(p+2)===ot){p+=3;continue}d+=m[p],p++}return d}function $s(m){let d=m.trim(),p=d.startsWith("...");if(p)d=d.slice(3).trim();while(d.startsWith("@")){let D=1;while(D<d.length&&_e(d.charCodeAt(D)))D++;if(D<d.length&&d.charCodeAt(D)===Q){let F=1;D++;while(D<d.length&&F>0){if(d.charCodeAt(D)===Q)F++;else if(d.charCodeAt(D)===pe)F--;D++}}d=d.slice(D).trim()}let y=!0;while(y){y=!1;for(let D of nn)if(d.startsWith(D)&&d.length>D.length&&!_e(d.charCodeAt(D.length))){let F=d.slice(D.length).trim();if(F.charCodeAt(0)===qe||F.charCodeAt(0)===Wr&&F.length>1&&F.charCodeAt(1)===qe)break;d=F,y=!0;break}}let $=-1,b=-1,T=0,P=!1,A=0;for(let D=0;D<d.length;D++){let F=d.charCodeAt(D);if(P){if(F===Ke){D++;continue}if(F===A)P=!1;continue}if(F===q&&D+1<d.length){let B=d.charCodeAt(D+1);if(B===xe){D+=2;while(D+1<d.length&&!(d.charCodeAt(D)===xe&&d.charCodeAt(D+1)===q))D++;D++;continue}if(B===q){while(D<d.length&&d.charCodeAt(D)!==10)D++;continue}}if(F===ne||F===le||F===Oe){P=!0,A=F;continue}if(F===Q||F===V||F===he||F===de)T++;else if(F===pe||F===J||F===$e||F===oe&&!(D>0&&d.charCodeAt(D-1)===Ce))T--;else if(T===0){if(F===qe&&$===-1)$=D;else if(F===Ce&&b===-1&&(D===0||d.charCodeAt(D-1)!==Ce)&&(D+1>=d.length||d.charCodeAt(D+1)!==Ce&&d.charCodeAt(D+1)!==oe))b=D}}let S,M,N=b!==-1;if($!==-1&&(b===-1||$<b))if(S=d.slice(0,$).trim(),b!==-1)M=d.slice($+1,b).trim();else M=d.slice($+1).trim();else if(b!==-1)S=d.slice(0,b).trim(),M=Wi(d.slice(b+1).trim());else S=d,M="unknown";if(S=tc(S),(S.startsWith("{")||S.startsWith("["))&&S.includes(`
50
+ `)){let D=S.replace(/\s*\n\s*/g," ").replace(/\s+/g," ");if(D.length<=40)S=D;else S=S.split(`
51
+ `).map((F)=>{let B=F.trim();if(!B)return"";if(B==="{"||B==="}"||B==="["||B==="]"||B.startsWith("}")||B.startsWith("]"))return B;return` ${B}`}).join(`
52
+ `)}let W=S.endsWith("?")||N;if(S.endsWith("?"))S=S.slice(0,-1).trim();let L=W&&!p?"?":"";if(p)return`...${S}: ${M}`;return`${S}${L}: ${M}`}function Es(m){let d=0;if(d<m.length&&m.charCodeAt(d)===45)d++;if(d>=m.length)return!1;let p=m.charCodeAt(d);if(p<48||p>57)return!1;while(d<m.length&&m.charCodeAt(d)>=48&&m.charCodeAt(d)<=57)d++;if(d<m.length&&m.charCodeAt(d)===46){if(d++,d>=m.length||m.charCodeAt(d)<48||m.charCodeAt(d)>57)return!1;while(d<m.length&&m.charCodeAt(d)>=48&&m.charCodeAt(d)<=57)d++}return d===m.length}function Wi(m){let d=m.trim();if(d==="true"||d==="false")return"boolean";if(Es(d))return"number";if(d.startsWith("'")&&d.endsWith("'")||d.startsWith('"')&&d.endsWith('"'))return"string";if(d.startsWith("["))return"unknown[]";if(d.startsWith("{"))return"Record<string, unknown>";return"unknown"}function Gi(m){let d=m.trim();if(d.endsWith("as const"))d=d.slice(0,-8).trim();if(d==="true"||d==="false")return d;if(Es(d))return d;let p=rc(d);if(p!==null)return p;return"unknown"}function rc(m){if(m==="")return null;if(m.charCodeAt(0)===ne||m.charCodeAt(0)===le){if(Br(m,0,m.charCodeAt(0))===m.length)return m}let d=ic(m,"+");if(d.length>1){let p=!1,y=!0,$=[];for(let b of d){let T=b.trim(),P=T.charCodeAt(0);if((P===ne||P===le)&&Br(T,0,P)===T.length)p=!0,$.push(nc(T));else y=!1}if(y)return sc($.join(""));if(p)return"string";return null}if(/^[\d\s()+*/%.\-]+$/.test(m)&&/\d/.test(m)&&/[+*/%\-\s]/.test(m))return"number";return null}function ic(m,d){let p=[],y=0,$="",b=0;while(b<m.length){let T=m.charCodeAt(b);if(T===ne||T===le||T===Oe){let P=Br(m,b,T);$+=m.slice(b,P),b=P;continue}if(T===q&&(m.charCodeAt(b+1)===q||m.charCodeAt(b+1)===42)){if(m.charCodeAt(b+1)===q){let S=m.indexOf(`
53
+ `,b+2),M=S===-1?m.length:S;$+=m.slice(b,M),b=M;continue}let P=m.indexOf("*/",b+2),A=P===-1?m.length:P+2;$+=m.slice(b,A),b=A;continue}if(T===Q||T===he||T===V)y++;else if(T===pe||T===$e||T===J)y--;if(m[b]===d&&y===0){p.push($),$="",b++;continue}$+=m[b],b++}return p.push($),p}function nc(m){return m.slice(1,-1).replace(/\\(.)/g,(d,p)=>{if(p==="n")return`
54
+ `;if(p==="t")return"\t";if(p==="r")return"\r";if(p==="0")return"\x00";return p})}function sc(m){return`'${m.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function Rr(m){if(m.endsWith("as const"))return null;let d=0,p=-1;for(let y=0;y<m.length;y++){let $=m.charCodeAt(y);if($===ne||$===le||$===Oe)y=Br(m,y,$)-1;else if($===123||$===91||$===40)d++;else if($===125||$===93||$===41)d--;else if(d===0&&$===32&&y+4<=m.length&&m.substring(y,y+4)===" as ")p=y}if(p===-1)return null;return m.slice(p+4).trim()||null}function ar(){if(h(),l<o&&i.charCodeAt(l)===qe){l++,h();let m=l,d=0;while(l<o){if(x())continue;let p=i.charCodeAt(l);if(p===Q||p===he||p===de)d++;else if(p===pe||p===$e||p===oe&&!K())d--;else if(p===V)if(d>0)d++;else{let y=g(m,l),$=(b)=>{let T=y.length-b.length;return T>=0&&y.endsWith(b)&&(T===0||!_e(y.charCodeAt(T-1)))};if(y.length===0||y.endsWith("|")||y.endsWith("&")||$("is")||$("extends"))d++;else break}else if(p===J){if(d===0)break;d--}else if(d===0&&p===Y)break;if(d===0&&_())break;l++}return g(m,l)}return""}function Et(m,d,p,y){l+=8,h();let $=l<o&&i.charCodeAt(l)===xe;if($)l++,h();let b=k();if(!b&&!y)return null;h();let T=at();h();let P=$t();h();let A=ar(),S=A.length>0;if(!A)if(p&&$)A="AsyncGenerator<unknown, void, unknown>";else if($)A="Generator<unknown, void, unknown>";else if(p)A="Promise<void>";else A="void";h();let M=!1;if(l<o&&i.charCodeAt(l)===V){M=!0;let D=l+1;if(U(V,J),!a&&!S&&!$)A=lr(i.slice(D,l-1),p,P)}else if(l<o&&i.charCodeAt(l)===Y)l++;let N=Ft(P),W=`${d?y?"export default function ":"export declare function ":"declare function "}${b||(y?"":"default")}${T}${N}: ${A};`,L=be(m);if(M)u.add(c.length);return{kind:"function",name:b||"default",text:W,isExported:d,isDefault:y,isAsync:p,isGenerator:$,returnType:A,generics:T||void 0,leadingComments:L,start:m,end:l}}function Nt(m,d,p){l+=d.length,h();let y=[];do{if(h(),l>=o)break;let $=i.charCodeAt(l);if($===V||$===he)return ie(),y;let b=k();if(!b)return ie(),y;h();let T,P,A=!1;if(l<o&&i.charCodeAt(l)===qe){l++,h();let N=l,W=0;while(l<o){if(x())continue;let L=i.charCodeAt(l);if(L===Q||L===V||L===he||L===de)W++;else if(L===pe||L===J||L===$e||L===oe&&!K())W--;else if(W===0&&(L===Y||L===Xe))break;else if(W===0&&L===Ce&&!we())break;if(W===0&&I())break;l++}T=g(N,l)}if(l<o&&i.charCodeAt(l)===Ce)if(a&&T&&(!s||!cf(T)))Tr();else{l++,h();let N=l,W=0,L=0,D=0;while(l<o){if(x())continue;let F=i.charCodeAt(l);if(F===Q||F===V||F===he)W++;else if(F===pe||F===J||F===$e)W--;else if(F===de&&W===0){let B=vs(l);if(B!==null)D=Math.max(0,D+B);else if(l+1>=o||i.charCodeAt(l+1)!==Ce)L++}else if(F===oe&&W===0&&D===0&&!K()){if(L>0&&(l+1>=o||i.charCodeAt(l+1)!==Ce))L--}else if(W===0&&L===0&&D===0&&(F===Y||F===Xe))break;if(W===0&&L===0&&D===0&&I())break;l++}if(P=g(N,l),P.endsWith(" as const")||P==="const"){if(A=!0,!T){let F=P.endsWith(" as const")?P.slice(0,-9).trim():P,B=Gi(F);T=B!=="unknown"?B:void 0}}else if(!T){let F=Rr(P);if(F)T=F}}if(l<o){let N=i.charCodeAt(l);if(N===Xe){l++;continue}if(N===Y)l++}let S=be(m),M=`${p?"export ":""}declare ${d} ${b}: ${T||"unknown"};`;y.push({kind:"variable",name:b,text:M,isExported:p,typeAnnotation:T,value:P,modifiers:A?[d,"const assertion"]:[d],leadingComments:S,start:m,end:l});break}while(l<o);return y}function vs(m){if(i.charCodeAt(m)!==de||m+1>=o)return null;let d=i.charCodeAt(m+1);if(d===oe)return 1;if(d===q)return-1;if(!Pt(d))return null;let p=m+2;while(p<o){let S=i.charCodeAt(p);if(!_e(S)&&S!==ot&&S!==58&&S!==45)break;p++}let y=i.slice(m+1,p),$=i.charCodeAt(p);if($>32&&$!==oe&&$!==q)return null;let b=0,T=0,P=p;for(;P<o;P++){let S=i.charCodeAt(P);if(T!==0){if(S===Ke)P++;else if(S===T)T=0;continue}if(S===ne||S===le||S===Oe)T=S;else if(S===V)b++;else if(S===J&&b>0)b--;else if(S===oe&&b===0)break}if(P>=o)return null;let A=P-1;while(A>m&&i.charCodeAt(A)<=32)A--;if(i.charCodeAt(A)===q)return 0;return i.indexOf(`</${y}`,P+1)===-1?null:1}function Bi(m,d){l+=9,h();let p=k();h();let y=at();h();let $="";if(E("extends")){l+=7,h();let S=l,M=0;while(l<o){if(x())continue;let N=i.charCodeAt(l);if(N===de)M++;else if(N===oe&&!K())M--;else if(N===V&&M===0)break;l++}$=g(S,l)}h();let b=l<o&&i.charCodeAt(l)===V?Dt():"{}",T=ws(b),P=`${d?"export ":""}declare interface ${p}${y}${$?` extends ${$}`:""} ${T}`,A=be(m);return{kind:"interface",name:p,text:P,isExported:d,extends:$||void 0,generics:y||void 0,leadingComments:A,start:m,end:l}}function Vi(m,d){l+=4,h();let p=k();h();let y=at();if(h(),l<o&&i.charCodeAt(l)===Ce)l++;h();let $=l,b=0;while(l<o){if(x())continue;let S=i.charCodeAt(l);if(S===Q||S===V||S===he||S===de)b++;else if(S===pe||S===J||S===$e||S===oe&&!K())b--;else if(b===0&&S===Y)break;if(b===0&&I())break;l++}let T=g($,l);if(l<o&&i.charCodeAt(l)===Y)l++;let P=`${d?"export ":""}type ${p}${y} = ${T}`,A=be(m);return{kind:"type",name:p,text:P,isExported:d,generics:y||void 0,leadingComments:A,start:m,end:l}}function Lt(m,d,p){l+=4,h();let y=k();h();let $=l;if(l<o&&i.charCodeAt(l)===V)U(V,J);let b=g(m,l),T=be(m);return{kind:"enum",name:y,text:b,isExported:d,modifiers:p?["const"]:void 0,leadingComments:T,start:m,end:l}}function vt(m,d,p,y=!1){l+=5,h();let $=k()||"AnonymousClass";h();let b=at();h();let T="";if(E("extends")){l+=7,h();let N=l,W=0;while(l<o){if(x())continue;let L=i.charCodeAt(l);if(L===de)W++;else if(L===oe&&!K())W--;else if(W===0&&(L===V||E("implements")))break;l++}T=g(N,l)}let P;if(E("implements")){l+=10,h();let N=l,W=0;while(l<o){if(x())continue;let D=i.charCodeAt(l);if(D===de)W++;else if(D===oe&&!K())W--;else if(W===0&&D===V)break;l++}let L=g(N,l);if(L)P=L.split(",").map((D)=>D.trim())}h();let A=_i(),S=`${d?y?"export default ":"export declare ":"declare "}${p?"abstract ":""}class ${$}${b}${T?` extends ${T}`:""}${P&&P.length>0?` implements ${P.join(", ")}`:""} ${A}`,M=be(m);return{kind:"class",name:$,text:S,isExported:d,isDefault:y,extends:T||void 0,implements:P,generics:b||void 0,modifiers:p?["abstract"]:void 0,leadingComments:M,start:m,end:l}}function _i(){if(l>=o||i.charCodeAt(l)!==V)return"{}";l++;let m=[];while(l<o){if(h(),l>=o)break;if(i.charCodeAt(l)===J){l++;break}if(i.charCodeAt(l)===Y){l++;continue}if(E("static")&&bs("static")===V){l+=6,h(),U(V,J);continue}let d=!1,p=!1,y=!1,$=!1,b=!1,T=!1,P=!1,A=!1,S=!0;while(S){if(h(),E("private")){d=!0,l+=7;continue}if(E("protected")){p=!0,l+=9;continue}if(E("public")){l+=6;continue}if(E("static")){y=!0,l+=6;continue}if(E("abstract")){$=!0,l+=8;continue}if(E("readonly")){b=!0,l+=8;continue}if(E("override")){T=!0,l+=8;continue}if(E("accessor")){P=!0,l+=8;continue}if(E("async")){A=!0,l+=5;continue}if(E("declare")){l+=7;continue}break}if(h(),l>=o||i.charCodeAt(l)===J)break;if(i.charCodeAt(l)===Gr)d=!0;if(d){ji();continue}let M=" ";if(p)M+="protected ";if(y)M+="static ";if($)M+="abstract ";if(b)M+="readonly ";if(E("constructor")){l+=11,h();let N=$t();if(h(),ac(N,m),l<o&&i.charCodeAt(l)===V)U(V,J);else if(l<o&&i.charCodeAt(l)===Y)l++;let W=Ft(N);m.push(` constructor${W};`)}else if(E("get"))if(l+=3,h(),l<o&&(Pt(i.charCodeAt(l))||i.charCodeAt(l)===he||i.charCodeAt(l)===Gr)){let N=Hi();if(N.startsWith("#")){if(h(),l<o&&i.charCodeAt(l)===Q)$t();if(h(),ar(),h(),l<o&&i.charCodeAt(l)===V)U(V,J);else if(l<o&&i.charCodeAt(l)===Y)l++;continue}h(),$t(),h();let W=ar()||"unknown";if(h(),l<o&&i.charCodeAt(l)===V)U(V,J);else if(l<o&&i.charCodeAt(l)===Y)l++;m.push(`${M}get ${N}(): ${W};`)}else Ss("get",M,y,b,A,m);else if(E("set"))if(l+=3,h(),l<o&&(Pt(i.charCodeAt(l))||i.charCodeAt(l)===he||i.charCodeAt(l)===Gr)){let N=Hi();if(N.startsWith("#")){if(h(),l<o&&i.charCodeAt(l)===Q)$t();if(h(),l<o&&i.charCodeAt(l)===V)U(V,J);else if(l<o&&i.charCodeAt(l)===Y)l++;continue}h();let W=$t();if(h(),l<o&&i.charCodeAt(l)===V)U(V,J);else if(l<o&&i.charCodeAt(l)===Y)l++;let L=Ft(W);m.push(`${M}set ${N}${L};`)}else Ss("set",M,y,b,A,m);else{let N=i.charCodeAt(l)===xe;if(N)l++,h();let W=Hi();if(!W){ji();continue}As(W,M,y,b,N,$,A,m)}}return`{
55
55
  ${m.join(`
56
56
  `)}
57
- }`}function Ki(){if(l>=a)return"";let m=i.charCodeAt(l);if(m===ue){let d=l;return V(ue,Ce),i.slice(d,l)}if(m===Lr)return l++,`#${W()}`;return W()}function vs(m){let d=l+m.length;while(d<a&&Re(i.charCodeAt(d)))d++;return d<a?i.charCodeAt(d):0}function Hi(){let m=0;while(l<a){if(O())continue;let d=i.charCodeAt(l);if(d===_||d===Q)m++;else if(d===G||d===ge){if(m===0)return;m--}else if(d===Z&&m===0){l++;return}if(m===0&&J())return;l++}}function xs(m,d,g,y,C,v){Es(m,d,g,y,!1,!1,C,v)}function Es(m,d,g,y,C,v,k,R){if(h(),l>=a)return;let E=i.charCodeAt(l),x=!1;if(E===Br)x=!0,l++,h();if(l<a&&i.charCodeAt(l)===33)l++,h();let N=l<a?i.charCodeAt(l):0;if(N===Q||N===he){let M=N===he?ot():"";h();let B=Ct();h();let I=or(),P=I.length>0;if(!I)if(k&&C)I="AsyncGenerator<unknown, void, unknown>";else if(C)I="Generator<unknown, void, unknown>";else if(k)I="Promise<void>";else I="void";if(h(),l<a&&i.charCodeAt(l)===_){let vt=l+1;if(V(_,G),!o&&!P&&!C)I=lr(i.slice(vt,l-1),k,B)}else if(l<a&&i.charCodeAt(l)===Z)l++;let D=Dt(B),j=x?"?":"",xe=C?"*":"";R.push(`${d}${xe}${m}${j}${M}${D}: ${I};`)}else if(N===qe||N===$e||N===Z||N===G||N===pe||N===be){let M="";if(N===qe){l++,h();let P=l,D=0;while(l<a){if(O())continue;let j=i.charCodeAt(l);if(j===Q||j===_||j===ue||j===he)D++;else if(j===ge||j===G||j===Ce||j===oe&&!Y()){if(D===0)break;D--}else if(D===0&&(j===Z||j===Ue))break;else if(D===0&&j===$e&&!we())break;if(D===0&&J())break;l++}M=p(P,l)}let B="";if(l<a&&i.charCodeAt(l)===$e)if(o&&M){l++;let P=0;while(l<a){if(O())continue;let D=i.charCodeAt(l);if(D===Q||D===_||D===ue)P++;else if(D===ge||D===G||D===Ce){if(P===0&&D===G)break;P--}else if(P===0&&D===Z)break;if(P===0&&J())break;l++}}else{l++,h();let P=l,D=0;while(l<a){if(O())continue;let j=i.charCodeAt(l);if(j===Q||j===_||j===ue)D++;else if(j===ge||j===G||j===Ce){if(D===0&&j===G)break;D--}else if(D===0&&j===Z)break;if(D===0&&J())break;l++}B=p(P,l)}if(l<a&&i.charCodeAt(l)===Z)l++;if(!M)if(B){let P=Sr(B);if(P)M=P;else M=B.endsWith("as const")||g&&y?Li(B):Bi(B)}else M="unknown";let I=x?"?":"";R.push(`${d}${m}${I}: ${M};`)}else Hi()}function tf(m,d){let g=m.slice(1,-1).trim();if(!g)return;let y=[],C=0,v=0,k=!1,R=0;for(let E=0;E<=g.length;E++){if(E===g.length){y.push(g.slice(C).trim());break}let x=g.charCodeAt(E);if(k){if(x===Ye){E++;continue}if(x===R)k=!1;continue}if(x===ne||x===ae||x===Te){k=!0,R=x;continue}if(x===Q||x===_||x===ue||x===he)v++;else if(x===ge||x===G||x===Ce||x===oe&&!(E>0&&g.charCodeAt(E-1)===$e))v--;else if(x===Ue&&v===0)y.push(g.slice(C,E).trim()),C=E+1}for(let E of y){let x=E.startsWith("public ")||E.startsWith("public\t"),N=E.startsWith("protected ")||E.startsWith("protected\t"),M=E.startsWith("private ")||E.startsWith("private\t"),B=E.includes("readonly ");if(!x&&!N&&!M&&!B)continue;if(M)continue;let I=E,P=[];if(x){let xe=6;while(xe<I.length&&Re(I.charCodeAt(xe)))xe++;I=I.slice(xe),P.push("public")}if(N){let xe=9;while(xe<I.length&&Re(I.charCodeAt(xe)))xe++;I=I.slice(xe),P.push("protected")}if(B){let xe=I.indexOf("readonly ");if(xe!==-1){let vt=xe+8;while(vt<I.length&&Re(I.charCodeAt(vt)))vt++;I=I.slice(0,xe)+I.slice(vt)}P.push("readonly")}let D=P.length>0?`${P.join(" ")} `:"",j=Cs(I);d.push(` ${D}${j};`)}}function Yi(m=" "){if(l>=a||i.charCodeAt(l)!==_)return"{}";l++;let d=[];while(l<a){if(h(),l>=a)break;if(i.charCodeAt(l)===G){l++;break}if(i.charCodeAt(l)===Z){l++;continue}let g=!1;if(b("export"))g=!0,l+=6,h();if(b("declare"))l+=7,h();let y=g?"export ":"";if(b("function")||b("async")&&rf("async","function")){let C=!1;if(b("async"))C=!0,l+=5,h();if(l+=8,h(),l<a&&i.charCodeAt(l)===Oe)l++,h();let v=W();h();let k=ot();h();let R=Ct();h();let E=or();if(!E)E=C?"Promise<void>":"void";if(h(),l<a&&i.charCodeAt(l)===_)V(_,G);else if(l<a&&i.charCodeAt(l)===Z)l++;let x=Dt(R);d.push(`${m}${y}function ${v}${k}${x}: ${E};`)}else if(b("const")||b("let")||b("var")){let C=b("const")?"const":b("let")?"let":"var";l+=C.length,h();let v=W();if(!v){ie();continue}h();let k="";if(l<a&&i.charCodeAt(l)===qe){l++,h();let E=l,x=0;while(l<a){if(O())continue;let N=i.charCodeAt(l);if(N===Q||N===_||N===ue||N===he)x++;else if(N===ge||N===G||N===Ce||N===oe&&!Y())x--;else if(x===0&&(N===Z||N===Ue))break;else if(x===0&&N===$e&&!we())break;if(x===0&&F())break;l++}k=p(E,l)}let R="";if(l<a&&i.charCodeAt(l)===$e){l++,h();let E=l,x=0;while(l<a){if(O())continue;let N=i.charCodeAt(l);if(N===Q||N===_||N===ue||N===he)x++;else if(N===ge||N===G||N===Ce||N===oe&&!Y())x--;else if(x===0&&(N===Z||N===Ue))break;if(x===0&&F())break;l++}R=p(E,l)}if(l<a&&i.charCodeAt(l)===Z)l++;if(!k&&R){let E=Sr(R);if(E)k=E;else if(C==="const")k=Li(R);else k=Bi(R)}if(!k)k="unknown";d.push(`${m}${y}${C} ${v}: ${k};`)}else if(b("interface")){l+=9,h();let C=W();h();let v=ot();h();let k="";if(b("extends")){l+=7,h();let E=l,x=0;while(l<a){if(O())continue;let N=i.charCodeAt(l);if(N===he)x++;else if(N===oe&&!Y())x--;else if(N===_&&x===0)break;l++}k=p(E,l)}let R=ws(Pt());d.push(`${m}${y}interface ${C}${v}${k?` extends ${k}`:""} ${R}`)}else if(b("type")){l+=4,h();let C=W();h();let v=ot();if(h(),l<a&&i.charCodeAt(l)===$e){l++,h();let k=l,R=0;while(l<a){if(O())continue;let x=i.charCodeAt(l);if(x===Q||x===_||x===ue||x===he)R++;else if(x===ge||x===G||x===Ce||x===oe&&!Y())R--;else if(R===0&&x===Z)break;if(R===0&&F())break;l++}let E=p(k,l);if(l<a&&i.charCodeAt(l)===Z)l++;d.push(`${m}${y}type ${C}${v} = ${E}`)}}else if(b("class")){l+=5,h();let C=W();h();let v=ot();h();let k=l,R=0;while(l<a){if(O())continue;let M=i.charCodeAt(l);if(M===he)R++;else if(M===oe&&!Y())R--;else if(M===_&&R===0)break;l++}let E=p(k,l),x=E?` ${E}`:"",N=Ji();d.push(`${m}${y}class ${C}${v}${x} ${N}`)}else if(b("enum")){l+=4,h();let C=W();h();let v=Pt();d.push(`${m}${y}enum ${C} ${v}`)}else if(b("namespace")||b("module")){let C=b("namespace")?"namespace":"module";l+=C.length,h();let v=W();h();let k=Yi(m);d.push(`${m}${y}${C} ${v} ${k}`)}else if(b("abstract"))if(l+=8,h(),b("class")){l+=5,h();let C=W();h();let v=ot();h();let k=l,R=0;while(l<a){if(O())continue;let M=i.charCodeAt(l);if(M===he)R++;else if(M===oe&&!Y())R--;else if(M===_&&R===0)break;l++}let E=p(k,l),x=E?` ${E}`:"",N=Ji();d.push(`${m}${y}abstract class ${C}${v}${x} ${N}`)}else ie();else if(g&&b("default")){l+=7,h();let C=l;ie();let v=p(C,l);if(v.charCodeAt(v.length-1)===Z)v=v.slice(0,-1);if(v)d.push(`${m}export default ${v};`)}else if(!g&&(i.charCodeAt(l)===ne||i.charCodeAt(l)===ae||i.charCodeAt(l)===Te))ie();else ie()}if(d.length===0)return"{}";return`{
57
+ }`}function Hi(){if(l>=o)return"";let m=i.charCodeAt(l);if(m===he){let d=l;return U(he,$e),i.slice(d,l)}if(m===Gr)return l++,`#${k()}`;return k()}function bs(m){let d=l+m.length;while(d<o&&Pe(i.charCodeAt(d)))d++;return d<o?i.charCodeAt(d):0}function ji(){let m=0;while(l<o){if(x())continue;let d=i.charCodeAt(l);if(d===V||d===Q)m++;else if(d===J||d===pe){if(m===0)return;m--}else if(d===Y&&m===0){l++;return}if(m===0&&_())return;l++}}function Ss(m,d,p,y,$,b){As(m,d,p,y,!1,!1,$,b)}function As(m,d,p,y,$,b,T,P){if(h(),l>=o)return;let A=i.charCodeAt(l),S=!1;if(A===Wr)S=!0,l++,h();if(l<o&&i.charCodeAt(l)===33)l++,h();let M=l<o?i.charCodeAt(l):0;if(M===Q||M===de){let N=M===de?at():"";h();let W=$t();h();let L=ar(),D=L.length>0;if(!L)if(T&&$)L="AsyncGenerator<unknown, void, unknown>";else if($)L="Generator<unknown, void, unknown>";else if(T)L="Promise<void>";else L="void";if(h(),l<o&&i.charCodeAt(l)===V){let bt=l+1;if(U(V,J),!a&&!D&&!$)L=lr(i.slice(bt,l-1),T,W)}else if(l<o&&i.charCodeAt(l)===Y)l++;let F=Ft(W),B=S?"?":"",Se=$?"*":"";P.push(`${d}${Se}${m}${B}${N}${F}: ${L};`)}else if(M===qe||M===Ce||M===Y||M===J||M===ge||M===Ee){let N="";if(M===qe){l++,h();let D=l,F=0;while(l<o){if(x())continue;let B=i.charCodeAt(l);if(B===Q||B===V||B===he||B===de)F++;else if(B===pe||B===J||B===$e||B===oe&&!K()){if(F===0)break;F--}else if(F===0&&(B===Y||B===Xe))break;else if(F===0&&B===Ce&&!we())break;if(F===0&&_())break;l++}N=g(D,l)}let W="";if(l<o&&i.charCodeAt(l)===Ce)if(a&&N){l++;let D=0;while(l<o){if(x())continue;let F=i.charCodeAt(l);if(F===Q||F===V||F===he)D++;else if(F===pe||F===J||F===$e){if(D===0&&F===J)break;D--}else if(D===0&&F===Y)break;if(D===0&&_())break;l++}}else{l++,h();let D=l,F=0;while(l<o){if(x())continue;let B=i.charCodeAt(l);if(B===Q||B===V||B===he)F++;else if(B===pe||B===J||B===$e){if(F===0&&B===J)break;F--}else if(F===0&&B===Y)break;if(F===0&&_())break;l++}W=g(D,l)}if(l<o&&i.charCodeAt(l)===Y)l++;if(!N)if(W){let D=Rr(W);if(D)N=D;else N=W.endsWith("as const")||p&&y?Gi(W):Wi(W)}else N="unknown";let L=S?"?":"";P.push(`${d}${m}${L}: ${N};`)}else ji()}function ac(m,d){let p=m.slice(1,-1).trim();if(!p)return;let y=[],$=0,b=0,T=!1,P=0;for(let A=0;A<=p.length;A++){if(A===p.length){y.push(p.slice($).trim());break}let S=p.charCodeAt(A);if(T){if(S===Ke){A++;continue}if(S===P)T=!1;continue}if(S===ne||S===le||S===Oe){T=!0,P=S;continue}if(S===Q||S===V||S===he||S===de)b++;else if(S===pe||S===J||S===$e||S===oe&&!(A>0&&p.charCodeAt(A-1)===Ce))b--;else if(S===Xe&&b===0)y.push(p.slice($,A).trim()),$=A+1}for(let A of y){let S=A.startsWith("public ")||A.startsWith("public\t"),M=A.startsWith("protected ")||A.startsWith("protected\t"),N=A.startsWith("private ")||A.startsWith("private\t"),W=A.includes("readonly ");if(!S&&!M&&!N&&!W)continue;if(N)continue;let L=A,D=[];if(S){let Se=6;while(Se<L.length&&Pe(L.charCodeAt(Se)))Se++;L=L.slice(Se),D.push("public")}if(M){let Se=9;while(Se<L.length&&Pe(L.charCodeAt(Se)))Se++;L=L.slice(Se),D.push("protected")}if(W){let Se=L.indexOf("readonly ");if(Se!==-1){let bt=Se+8;while(bt<L.length&&Pe(L.charCodeAt(bt)))bt++;L=L.slice(0,Se)+L.slice(bt)}D.push("readonly")}let F=D.length>0?`${D.join(" ")} `:"",B=$s(L);d.push(` ${F}${B};`)}}function Ki(m=" "){if(l>=o||i.charCodeAt(l)!==V)return"{}";l++;let d=[];while(l<o){if(h(),l>=o)break;if(i.charCodeAt(l)===J){l++;break}if(i.charCodeAt(l)===Y){l++;continue}let p=!1;if(E("export"))p=!0,l+=6,h();if(E("declare"))l+=7,h();let y=p?"export ":"";if(E("function")||E("async")&&oc("async","function")){let $=!1;if(E("async"))$=!0,l+=5,h();if(l+=8,h(),l<o&&i.charCodeAt(l)===xe)l++,h();let b=k();h();let T=at();h();let P=$t();h();let A=ar();if(!A)A=$?"Promise<void>":"void";if(h(),l<o&&i.charCodeAt(l)===V)U(V,J);else if(l<o&&i.charCodeAt(l)===Y)l++;let S=Ft(P);d.push(`${m}${y}function ${b}${T}${S}: ${A};`)}else if(E("const")||E("let")||E("var")){let $=E("const")?"const":E("let")?"let":"var";l+=$.length,h();let b=k();if(!b){ie();continue}h();let T="";if(l<o&&i.charCodeAt(l)===qe){l++,h();let A=l,S=0;while(l<o){if(x())continue;let M=i.charCodeAt(l);if(M===Q||M===V||M===he||M===de)S++;else if(M===pe||M===J||M===$e||M===oe&&!K())S--;else if(S===0&&(M===Y||M===Xe))break;else if(S===0&&M===Ce&&!we())break;if(S===0&&I())break;l++}T=g(A,l)}let P="";if(l<o&&i.charCodeAt(l)===Ce){l++,h();let A=l,S=0;while(l<o){if(x())continue;let M=i.charCodeAt(l);if(M===Q||M===V||M===he||M===de)S++;else if(M===pe||M===J||M===$e||M===oe&&!K())S--;else if(S===0&&(M===Y||M===Xe))break;if(S===0&&I())break;l++}P=g(A,l)}if(l<o&&i.charCodeAt(l)===Y)l++;if(!T&&P){let A=Rr(P);if(A)T=A;else if($==="const")T=Gi(P);else T=Wi(P)}if(!T)T="unknown";d.push(`${m}${y}${$} ${b}: ${T};`)}else if(E("interface")){l+=9,h();let $=k();h();let b=at();h();let T="";if(E("extends")){l+=7,h();let A=l,S=0;while(l<o){if(x())continue;let M=i.charCodeAt(l);if(M===de)S++;else if(M===oe&&!K())S--;else if(M===V&&S===0)break;l++}T=g(A,l)}let P=ws(Dt());d.push(`${m}${y}interface ${$}${b}${T?` extends ${T}`:""} ${P}`)}else if(E("type")){l+=4,h();let $=k();h();let b=at();if(h(),l<o&&i.charCodeAt(l)===Ce){l++,h();let T=l,P=0;while(l<o){if(x())continue;let S=i.charCodeAt(l);if(S===Q||S===V||S===he||S===de)P++;else if(S===pe||S===J||S===$e||S===oe&&!K())P--;else if(P===0&&S===Y)break;if(P===0&&I())break;l++}let A=g(T,l);if(l<o&&i.charCodeAt(l)===Y)l++;d.push(`${m}${y}type ${$}${b} = ${A}`)}}else if(E("class")){l+=5,h();let $=k();h();let b=at();h();let T=l,P=0;while(l<o){if(x())continue;let N=i.charCodeAt(l);if(N===de)P++;else if(N===oe&&!K())P--;else if(N===V&&P===0)break;l++}let A=g(T,l),S=A?` ${A}`:"",M=_i();d.push(`${m}${y}class ${$}${b}${S} ${M}`)}else if(E("enum")){l+=4,h();let $=k();h();let b=Dt();d.push(`${m}${y}enum ${$} ${b}`)}else if(E("namespace")||E("module")){let $=E("namespace")?"namespace":"module";l+=$.length,h();let b=k();h();let T=Ki(m);d.push(`${m}${y}${$} ${b} ${T}`)}else if(E("abstract"))if(l+=8,h(),E("class")){l+=5,h();let $=k();h();let b=at();h();let T=l,P=0;while(l<o){if(x())continue;let N=i.charCodeAt(l);if(N===de)P++;else if(N===oe&&!K())P--;else if(N===V&&P===0)break;l++}let A=g(T,l),S=A?` ${A}`:"",M=_i();d.push(`${m}${y}abstract class ${$}${b}${S} ${M}`)}else ie();else if(p&&E("default")){l+=7,h();let $=l;ie();let b=g($,l);if(b.charCodeAt(b.length-1)===Y)b=b.slice(0,-1);if(b)d.push(`${m}export default ${b};`)}else if(!p&&(i.charCodeAt(l)===ne||i.charCodeAt(l)===le||i.charCodeAt(l)===Oe))ie();else ie()}if(d.length===0)return"{}";return`{
58
58
  ${d.join(`
59
59
  `)}
60
- }`}function rf(m,d){let g=l+m.length;while(g<a&&Re(i.charCodeAt(g)))g++;for(let y=0;y<d.length;y++)if(g+y>=a||i.charCodeAt(g+y)!==d.charCodeAt(y))return!1;return g+d.length>=a||!Je(i.charCodeAt(g+d.length))}function Bt(m,d,g){l+=g.length,h();let y="",C=i.charCodeAt(l);if(C===ne||C===ae){let x=l;A(C),y=i.slice(x,l)}else{y=W();while(l<a&&i.charCodeAt(l)===lt)l++,y+=`.${W()}`}h();let v=l<a&&i.charCodeAt(l)===_?Yi():"{}",k=`${d?"export ":""}declare ${g} ${y} ${v}`,R=ve(m),E=y.startsWith("'")||y.startsWith('"');return{kind:"module",name:y,text:k,isExported:d,source:E?y.slice(1,-1):void 0,leadingComments:R,start:m,end:l}}function Os(m,d){ie();let g=p(d,l);if(g.charCodeAt(g.length-1)===Z)g=g.slice(0,-1).trimEnd();if(!g)return;let y=Rt(g.charCodeAt(0));for(let x=1;y&&x<g.length;x++)y=Je(g.charCodeAt(x));let C=ve(m);if(y){f.push({kind:"export",name:"default",text:`export default ${g};`,isExported:!0,isTypeOnly:!1,leadingComments:C,start:m,end:l});return}let v="__dtsx_default_export__",k=1;while(i.includes(v))v=`__dtsx_default_export_${k++}__`;let R=Sr(g)||Ee(g,!1),E=R==="unknown"&&rc(g)?`typeof ${g}`:R;f.push({kind:"variable",name:v,text:`declare const ${v}: ${E};`,isExported:!1,typeAnnotation:E,modifiers:["const"],start:m,end:l}),f.push({kind:"export",name:"default",text:`export default ${v};`,isExported:!0,isTypeOnly:!1,leadingComments:C,start:m,end:l})}while(l<a){if(h(),l>=a)break;let m=l,d=i.charCodeAt(l);if(d===105&&b("import"))f.push(Ft(m));else if(d===101&&b("export")){l+=6,h();let g=i.charCodeAt(l);if(g===100&&b("default")){l+=7,h();let y=l,C=i.charCodeAt(l);if(C===102&&b("function")){let v=bt(m,!0,!1,!0);if(v)f.push(v)}else if(C===97&&b("async")&&vs("async")!==Z)if(l+=5,h(),b("function")){let v=bt(m,!0,!0,!0);if(v)f.push(v)}else Os(m,y);else if(C===99&&b("class")){let v=At(m,!0,!1,!0);f.push(v)}else if(C===97&&b("abstract")){if(l+=8,h(),b("class")){let v=At(m,!0,!0,!0);f.push(v)}}else Os(m,y)}else if(g===116&&b("type")){let y=l;if(l+=4,h(),l<a&&i.charCodeAt(l)===_){kt();let C=p(m,l),v=ve(m);f.push({kind:"export",name:"",text:C,isExported:!0,isTypeOnly:!0,source:De(C),leadingComments:v,start:m,end:l})}else if(l<a&&i.charCodeAt(l)===Oe){wt();let C=p(m,l);f.push({kind:"export",name:"",text:C,isExported:!0,isTypeOnly:!0,source:De(C),start:m,end:l})}else{l=y;let C=_i(m,!0);f.push(C)}}else if(g===105&&b("interface")){let y=ji(m,!0);f.push(y)}else if(g===102&&b("function")){let y=bt(m,!0,!1,!1);if(y)f.push(y)}else if(g===97&&b("async"))if(l+=5,h(),b("function")){let y=bt(m,!0,!0,!1);if(y)f.push(y)}else ie();else if(g===99)if(b("class")){let y=At(m,!0,!1);f.push(y)}else if(b("const")){let y=l;if(l+=5,h(),b("enum")){l=y+5,h();let C=It(m,!0,!0);f.push(C)}else{l=y;let C=Mt(m,"const",!0);for(let v=0;v<C.length;v++)f.push(C[v])}}else ie();else if(g===97&&b("abstract")){if(l+=8,h(),b("class")){let y=At(m,!0,!0);f.push(y)}}else if(g===108&&b("let")){let y=Mt(m,"let",!0);for(let C=0;C<y.length;C++)f.push(y[C])}else if(g===118&&b("var")){let y=Mt(m,"var",!0);for(let C=0;C<y.length;C++)f.push(y[C])}else if(g===101&&b("enum")){let y=It(m,!0,!1);f.push(y)}else if(g===100&&b("declare"))l+=7,h(),ks(m,!0);else if(g===110&&b("namespace")&&L(9)){let y=Bt(m,!0,"namespace");f.push(y)}else if(g===109&&b("module")&&L(6)){let y=Bt(m,!0,"module");f.push(y)}else if(g===_){kt();let y=p(m,l),C=y.includes("export type"),v=ve(m);f.push({kind:"export",name:"",text:y,isExported:!0,isTypeOnly:C,source:De(y),leadingComments:v,start:m,end:l})}else if(g===Oe){wt();let y=p(m,l),C=ve(m);f.push({kind:"export",name:"",text:y,isExported:!0,isTypeOnly:!1,source:De(y),leadingComments:C,start:m,end:l})}else{ie();let y=p(m,l);if(y)f.push({kind:"export",name:"",text:y,isExported:!0,start:m,end:l})}}else if(d===100&&b("declare"))l+=7,h(),ks(m,!1);else if(d===105&&b("interface")){let g=ji(m,!1);c.set(g.name,g)}else if(d===116&&b("type")){let g=_i(m,!1);c.set(g.name,g),f.push(g)}else if(d===102&&b("function")){let g=bt(m,!1,!1,!1);if(g)c.set(g.name,g);else ie()}else if(d===97)if(b("async")){let g=l;if(l+=5,h(),b("function")){let y=bt(m,!1,!0,!1);if(y)c.set(y.name,y);else l=g,ie()}else l=g,ie()}else if(b("abstract"))if(l+=8,h(),b("class")){let g=At(m,!1,!1);c.set(g.name,g),f.push(g)}else ie();else l++,ie();else if(d===99)if(b("class")){let g=At(m,!1,!1);c.set(g.name,g),f.push(g)}else if(b("const")){let g=l;if(l+=5,h(),b("enum")){l=g+5,h();let y=It(m,!1,!0);c.set(y.name,y),f.push(y)}else{l=g;let y=Mt(m,"const",!1);for(let C=0;C<y.length;C++)c.set(y[C].name,y[C])}}else l++,ie();else if(d===101&&b("enum")){let g=It(m,!1,!1);c.set(g.name,g),f.push(g)}else if(d===108&&b("let"))ie();else if(d===118&&b("var"))ie();else if(d===109&&b("module")&&L(6)){let g=Bt(m,!1,"module");f.push(g)}else if(d===110&&b("namespace")&&L(9)){let g=Bt(m,!1,"namespace");f.push(g)}else{let g=i.charCodeAt(l);if(g===Z)l++;else if(g===ne||g===ae){if(A(g),l<a&&i.charCodeAt(l)===Z)l++}else if(g===Te){if($(),l<a&&i.charCodeAt(l)===Z)l++}else if(g===ec){if(l++,W(),h(),l<a&&i.charCodeAt(l)===lt)l++,W(),h();if(l<a&&i.charCodeAt(l)===Q)V(Q,ge)}else l++,ie()}}if(c.size>0)nc(f,c);if(u.size>0){let m=new Map;for(let g of f)if(g.kind==="function")m.set(g.name,(m.get(g.name)||0)+1);let d=new Set;for(let[g,y]of m)if(y>1)d.add(g);if(d.size>0){let g=new Set;for(let y of d)for(let C=f.length-1;C>=0;C--)if(f[C].kind==="function"&&f[C].name===y&&u.has(C)){g.add(C);break}if(g.size>0){let y=[...g].sort((C,v)=>v-C);for(let C of y)f.splice(C,1)}}}return f;function ks(m,d){if(b("function")){let g=bt(m,d,!1,!1);if(g)f.push(g)}else if(b("async")){if(l+=5,h(),b("function")){let g=bt(m,d,!0,!1);if(g)f.push(g)}}else if(b("class")){let g=At(m,d,!1);f.push(g)}else if(b("abstract")){if(l+=8,h(),b("class")){let g=At(m,d,!0);f.push(g)}}else if(b("interface")){let g=ji(m,d);f.push(g)}else if(b("type")){let g=_i(m,d);f.push(g)}else if(b("enum")){let g=It(m,d,!1);f.push(g)}else if(b("const")){let g=l;if(l+=5,h(),b("enum")){l=g+5,h();let y=It(m,d,!0);f.push(y)}else if(d){l=g;let y=Mt(m,"const",!0);for(let C=0;C<y.length;C++)f.push(y[C])}else ie()}else if(b("let")||b("var"))if(d){let g=b("let")?"let":"var",y=Mt(m,g,!0);for(let C=0;C<y.length;C++)f.push(y[C])}else ie();else if(b("module")){let g=Bt(m,d,"module");f.push(g)}else if(b("namespace")){let g=Bt(m,d,"namespace");f.push(g)}else if(b("global")){l+=6,h();let g=`declare global ${l<a&&i.charCodeAt(l)===_?Yi():"{}"}`,y=ve(m);f.push({kind:"module",name:"global",text:g,isExported:!1,leadingComments:y,start:m,end:l})}else ie()}}function Qs(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 eo(e,t){let r=0;while(r<e.length){let n=e.charCodeAt(r);if(n===ne||n===ae||n===Te){let u=n;r++;while(r<e.length)if(e.charCodeAt(r)===Ye)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)!==pe&&e.charCodeAt(r)!==be)r++;continue}if(n===U&&e.charCodeAt(r+1)===Oe){let u=e.indexOf("*/",r+2);r=u===-1?e.length:u+2;continue}if(!Rt(n)){r++;continue}let i=r++;while(r<e.length&&Je(e.charCodeAt(r)))r++;let s=i-1,o=r;while(s>=0&&Re(e.charCodeAt(s)))s--;while(o<e.length&&Re(e.charCodeAt(o)))o++;let a=s>=0?e.charCodeAt(s):0,f=o<e.length?e.charCodeAt(o):0,c=i>=3&&e.slice(i-3,i)==="...";if(f===qe||a===lt&&!c)continue;if(f===Q&&(a===_||a===Ue))continue;t.add(e.slice(i,r))}}function nc(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),Qs(a.text,i),typeof a.value==="string")eo(a.value,i)}}for(;;){let o=[];for(let[c,u]of t){if(r.has(c))continue;if(i.has(c)){if(!n.has(c))o.push(u),n.add(c);r.add(c)}}if(o.length===0)break;o.sort((c,u)=>(c.start??1/0)-(u.start??1/0));let a=[],f=0;for(let c=0;c<e.length;c++){let u=e[c].start??1/0;while(f<o.length&&(o[f].start??1/0)<=u)a.push(o[f++]);a.push(e[c])}while(f<o.length)a.push(o[f++]);e.length=0;for(let c=0;c<a.length;c++)e.push(a[c]);for(let c of o)if(c.kind!=="import"){if(s.push(c.text),Qs(c.text,i),typeof c.value==="string")eo(c.value,i)}}}var ke=32,Se=9,pe=10,be=13,U=47,Oe=42,ne=39,ae=34,Te=96,Ye=92,_=123,G=125,Q=40,ge=41,ue=91,Ce=93,he=60,oe=62,Z=59,qe=58,$e=61,Ue=44,lt=46,Br=63,Lr=35,ec=64,to=36,tc=95,nn;var so=de(()=>{rn();nn=["public","protected","private","readonly","override"]});function ao(e){return e.endsWith(".vue")}function sc(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 Ge(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 Xe(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 ft(e,t){if(e[t+1]==="/"){let r=e.indexOf(`
61
- `,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 on(e,t){let r=e[t];if(r==='"'||r==="'")return Ge(e,t);if(r==="`")return Xe(e,t);if(r==="/"&&(e[t+1]==="/"||e[t+1]==="*"))return ft(e,t);return t}function an(e){let t=e.split(""),r=0;while(r<e.length){let n=on(e,r);if(n>r){for(let i=r;i<n;i++)if(t[i]!==`
62
- `&&t[i]!=="\r")t[i]=" ";r=n;continue}r++}return t.join("")}function Me(e,t,r,n){let i=0,s=t;while(s<e.length){let o=e[s];if(o==='"'||o==="'"){s=Ge(e,s);continue}if(o==="`"){s=Xe(e,s);continue}if(o==="/"&&(e[s+1]==="/"||e[s+1]==="*")){s=ft(e,s);continue}if(o===r)i++;else if(o===n){if(i--,i===0)return s}s++}return-1}function ln(e,t){let r=0,n=t;while(n<e.length){let i=e[n];if(i==='"'||i==="'"){n=Ge(e,n);continue}if(i==="`"){n=Xe(e,n);continue}if(i==="/"&&(e[n+1]==="/"||e[n+1]==="*")){n=ft(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 jt(e,t=","){let r=[],n=0,i="",s=0;while(s<e.length){let o=e[s];if(o==='"'||o==="'"){let a=Ge(e,s);i+=e.slice(s,a),s=a;continue}if(o==="`"){let a=Xe(e,s);i+=e.slice(s,a),s=a;continue}if(o==="/"&&(e[s+1]==="/"||e[s+1]==="*")){s=ft(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 dr(e){let t=e.trim();if(!t.startsWith("{"))return[];let r=Me(t,0,"{","}");if(r===-1)return[];let n=t.slice(1,r),i=[];for(let s of jt(n)){let o=-1,a=0;for(let u=0;u<s.length;u++){let l=s[u];if(l==='"'||l==="'"){u=Ge(s,u)-1;continue}if(l==="`"){u=Xe(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:ur(s.slice(0,o).trim()),value:s.slice(o+1).trim(),isMethod:!1});continue}let f=/^([A-Za-z_$][\w$]*|['"][^'"]+['"])\s*\(/.exec(s.trim());if(f){i.push({key:ur(f[1]),value:s.trim(),isMethod:!0});continue}let c=s.trim();if(c)i.push({key:ur(c),value:"",isMethod:!1})}return i}function ur(e){if(e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);return e}function hr(e){return/^[A-Za-z_$][\w$]*$/.test(e)?e:JSON.stringify(e)}function mr(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 f=ln(e,i);if(f===-1)return null;s=e.slice(i+1,f).trim(),i=f+1;while(i<e.length&&/\s/.test(e[i]))i++}if(e[i]!=="(")continue;let o=Me(e,i,"(",")");if(o===-1)return null;let a=jt(e.slice(i+1,o));return{generic:s,arg:a.length>0?a[0].trim():null}}return null}function oc(e,t){let r=lo(e,t);if(!r)return null;return r.kind==="interface"?e.slice(r.bodyStart,r.end):e.slice(r.bodyStart,r.end).trim()}function lo(e,t){let r=new RegExp(`\\binterface\\s+${t}\\b[^{]*\\{`,"m").exec(e);if(r){let i=r.index+r[0].length-1,s=Me(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=Ge(e,i);continue}if(a==="`"){i=Xe(e,i);continue}if(a==="{"||a==="["||a==="("||a==="<")s++;else if(a==="}"||a==="]"||a===")"||a===">")s--;else if((a===";"||a===`
63
- `)&&s===0)break;i++}return{kind:"type",start:n.index,end:i,bodyStart:o}}return null}function ac(e){let t=e.search(/\bas\s+PropType\s*</);if(t===-1)return null;let r=e.indexOf("<",t),n=ln(e,r);if(n===-1)return null;if(e.slice(n+1).trim()!=="")return null;return e.slice(r+1,n).trim()}function sn(e){let t=e.trim(),r=ac(t);if(r!==null)return{type:r,optional:!0};if(t==="null")return{type:"unknown",optional:!0};if(t.startsWith("[")){let n=Me(t,0,"[","]");if(n!==-1){let i=jt(t.slice(1,n)).map((s)=>sn(s).type).filter((s)=>s!=="unknown");return{type:i.length>0?[...new Set(i)].join(" | "):"unknown",optional:!0}}}if(t.startsWith("{")){let n=dr(t),i=n.find((f)=>f.key==="type"),s=n.find((f)=>f.key==="required"),o=i?sn(i.value).type:"unknown",a=!(s&&s.value.trim()==="true");return{type:o,optional:a}}if(oo[t])return{type:oo[t],optional:!0};if(/^[A-Za-z_$][\w$.]*$/.test(t))return{type:t,optional:!0};return{type:"unknown",optional:!0}}function Hr(e){let t=e.trim();if(t.startsWith("{")){let r=dr(t);if(r.length===0)return"{}";return`{ ${r.map((n)=>{if(n.isMethod||n.value==="")return`${hr(n.key)}?: unknown`;let i=sn(n.value);return`${hr(n.key)}${i.optional?"?":""}: ${i.type}`}).join(", ")} }`}if(t.startsWith("[")){let r=Me(t,0,"[","]");if(r===-1)return null;let n=jt(t.slice(1,r)).map((i)=>ur(i.trim())).filter((i)=>i!=="");if(n.length===0)return"{}";return`{ ${n.map((i)=>`${hr(i)}?: unknown`).join(", ")} }`}return null}function lc(e){let t=e.trim();if(!t.startsWith("["))return null;let r=Me(t,0,"[","]");if(r===-1)return null;let n=jt(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(ur(i))).join(", ")}]`}function fc(e){let t=e.trim();if(!t.startsWith("{"))return null;let r=dr(t);if(r.length===0)return"{}";return`{ ${r.map((n)=>`${JSON.stringify(n.key)}: (...args: any[]) => void`).join(", ")} }`}function fo(e){return lc(e)??fc(e)}function cc(e){let t=[],r=0,n="",i=0;while(i<e.length){let s=e[i];if(s==='"'||s==="'"){let o=Ge(e,i);n+=e.slice(i,o),i=o;continue}if(s==="`"){let o=Xe(e,i);n+=e.slice(i,o),i=o;continue}if(s==="/"&&(e[i+1]==="/"||e[i+1]==="*")){let o=ft(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===`
64
- `)&&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 uc(e){let t=e.trim();if(!t.startsWith("{"))return null;let r=Me(t,0,"{","}");if(r===-1||t.slice(r+1).trim()!=="")return null;let n=cc(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,f=s[a];if(f!=="'"&&f!=='"'&&f!=="`")return null;let c=Ge(s,a),u=s.slice(a+1,c-1),l=Me(s,s.indexOf("(",0),"(",")");if(l===-1)return null;let p=s.slice(a,l),h=jt(p).slice(1),w=s.slice(l+1).trim();if(w.startsWith(":"))w=w.slice(1).trim();if(w==="")w="void";i.push(`${JSON.stringify(u)}: (${h.map((A)=>A.trim()).join(", ")}) => ${w}`)}return`{ ${i.join(", ")} }`}function fn(e){let t=e;for(let r of["defineProps","defineEmits","defineExpose","defineSlots","defineOptions"])t=hc(t,r);return t}function hc(e,t){let r=new RegExp(`\\b${t}\\b`,"g"),n=[],i=e,s;while((s=r.exec(e))!==null){let o=e.lastIndexOf(`
65
- `,s.index)+1,a=e.slice(o,s.index),f=/^\s*(?:(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*(?::[^=]+)?=\s*)?(withDefaults\s*\(\s*)?$/.exec(a);if(!f)continue;let c=s.index+s[0].length;while(c<e.length&&/\s/.test(e[c]))c++;if(e[c]==="<"){let p=ln(e,c);if(p===-1)continue;c=p+1;while(c<e.length&&/\s/.test(e[c]))c++}if(e[c]!=="(")continue;let u=Me(e,c,"(",")");if(u===-1)continue;if(f[1]){let p=o+a.length-f[1].length,h=e.indexOf("(",p);if(h!==-1){let w=Me(e,h,"(",")");if(w!==-1)u=w}}let l=u+1;while(l<e.length&&e[l]!==`
60
+ }`}function oc(m,d){let p=l+m.length;while(p<o&&Pe(i.charCodeAt(p)))p++;for(let y=0;y<d.length;y++)if(p+y>=o||i.charCodeAt(p+y)!==d.charCodeAt(y))return!1;return p+d.length>=o||!_e(i.charCodeAt(p+d.length))}function Wt(m,d,p){l+=p.length,h();let y="",$=i.charCodeAt(l);if($===ne||$===le){let S=l;v($),y=i.slice(S,l)}else{y=k();while(l<o&&i.charCodeAt(l)===ot)l++,y+=`.${k()}`}h();let b=l<o&&i.charCodeAt(l)===V?Ki():"{}",T=`${d?"export ":""}declare ${p} ${y} ${b}`,P=be(m),A=y.startsWith("'")||y.startsWith('"');return{kind:"module",name:y,text:T,isExported:d,source:A?y.slice(1,-1):void 0,leadingComments:P,start:m,end:l}}function xs(m,d){ie();let p=g(d,l);if(p.charCodeAt(p.length-1)===Y)p=p.slice(0,-1).trimEnd();if(!p)return;let y=Pt(p.charCodeAt(0));for(let S=1;y&&S<p.length;S++)y=_e(p.charCodeAt(S));let $=be(m);if(y){c.push({kind:"export",name:"default",text:`export default ${p};`,isExported:!0,isTypeOnly:!1,leadingComments:$,start:m,end:l});return}let b="__dtsx_default_export__",T=1;while(i.includes(b))b=`__dtsx_default_export_${T++}__`;let P=Rr(p)||Ae(p,!1),A=P==="unknown"&&lf(p)?`typeof ${p}`:P;c.push({kind:"variable",name:b,text:`declare const ${b}: ${A};`,isExported:!1,typeAnnotation:A,modifiers:["const"],start:m,end:l}),c.push({kind:"export",name:"default",text:`export default ${b};`,isExported:!0,isTypeOnly:!1,leadingComments:$,start:m,end:l})}while(l<o){if(h(),l>=o)break;let m=l,d=i.charCodeAt(l);if(d===105&&E("import"))c.push(It(m));else if(d===101&&E("export")){l+=6,h();let p=i.charCodeAt(l);if(p===100&&E("default")){l+=7,h();let y=l,$=i.charCodeAt(l);if($===102&&E("function")){let b=Et(m,!0,!1,!0);if(b)c.push(b)}else if($===97&&E("async")&&bs("async")!==Y)if(l+=5,h(),E("function")){let b=Et(m,!0,!0,!0);if(b)c.push(b)}else xs(m,y);else if($===99&&E("class")){let b=vt(m,!0,!1,!0);c.push(b)}else if($===97&&E("abstract")){if(l+=8,h(),E("class")){let b=vt(m,!0,!0,!0);c.push(b)}}else xs(m,y)}else if(p===116&&E("type")){let y=l;if(l+=4,h(),l<o&&i.charCodeAt(l)===V){Tt();let $=g(m,l),b=be(m);c.push({kind:"export",name:"",text:$,isExported:!0,isTypeOnly:!0,source:Fe($),leadingComments:b,start:m,end:l})}else if(l<o&&i.charCodeAt(l)===xe){wt();let $=g(m,l);c.push({kind:"export",name:"",text:$,isExported:!0,isTypeOnly:!0,source:Fe($),start:m,end:l})}else{l=y;let $=Vi(m,!0);c.push($)}}else if(p===105&&E("interface")){let y=Bi(m,!0);c.push(y)}else if(p===102&&E("function")){let y=Et(m,!0,!1,!1);if(y)c.push(y)}else if(p===97&&E("async"))if(l+=5,h(),E("function")){let y=Et(m,!0,!0,!1);if(y)c.push(y)}else ie();else if(p===99)if(E("class")){let y=vt(m,!0,!1);c.push(y)}else if(E("const")){let y=l;if(l+=5,h(),E("enum")){l=y+5,h();let $=Lt(m,!0,!0);c.push($)}else{l=y;let $=Nt(m,"const",!0);for(let b=0;b<$.length;b++)c.push($[b])}}else ie();else if(p===97&&E("abstract")){if(l+=8,h(),E("class")){let y=vt(m,!0,!0);c.push(y)}}else if(p===108&&E("let")){let y=Nt(m,"let",!0);for(let $=0;$<y.length;$++)c.push(y[$])}else if(p===118&&E("var")){let y=Nt(m,"var",!0);for(let $=0;$<y.length;$++)c.push(y[$])}else if(p===101&&E("enum")){let y=Lt(m,!0,!1);c.push(y)}else if(p===100&&E("declare"))l+=7,h(),Ts(m,!0);else if(p===110&&E("namespace")&&G(9)){let y=Wt(m,!0,"namespace");c.push(y)}else if(p===109&&E("module")&&G(6)){let y=Wt(m,!0,"module");c.push(y)}else if(p===V){Tt();let y=g(m,l),$=y.includes("export type"),b=be(m);c.push({kind:"export",name:"",text:y,isExported:!0,isTypeOnly:$,source:Fe(y),leadingComments:b,start:m,end:l})}else if(p===xe){wt();let y=g(m,l),$=be(m);c.push({kind:"export",name:"",text:y,isExported:!0,isTypeOnly:!1,source:Fe(y),leadingComments:$,start:m,end:l})}else{ie();let y=g(m,l);if(y)c.push({kind:"export",name:"",text:y,isExported:!0,start:m,end:l})}}else if(d===100&&E("declare"))l+=7,h(),Ts(m,!1);else if(d===105&&E("interface")){let p=Bi(m,!1);f.set(p.name,p)}else if(d===116&&E("type")){let p=Vi(m,!1);f.set(p.name,p),c.push(p)}else if(d===102&&E("function")){let p=Et(m,!1,!1,!1);if(p)f.set(p.name,p);else ie()}else if(d===97)if(E("async")){let p=l;if(l+=5,h(),E("function")){let y=Et(m,!1,!0,!1);if(y)f.set(y.name,y);else l=p,ie()}else l=p,ie()}else if(E("abstract"))if(l+=8,h(),E("class")){let p=vt(m,!1,!1);f.set(p.name,p),c.push(p)}else ie();else l++,ie();else if(d===99)if(E("class")){let p=vt(m,!1,!1);f.set(p.name,p),c.push(p)}else if(E("const")){let p=l;if(l+=5,h(),E("enum")){l=p+5,h();let y=Lt(m,!1,!0);f.set(y.name,y),c.push(y)}else{l=p;let y=Nt(m,"const",!1);for(let $=0;$<y.length;$++)f.set(y[$].name,y[$])}}else l++,ie();else if(d===101&&E("enum")){let p=Lt(m,!1,!1);f.set(p.name,p),c.push(p)}else if(d===108&&E("let"))ie();else if(d===118&&E("var"))ie();else if(d===109&&E("module")&&G(6)){let p=Wt(m,!1,"module");c.push(p)}else if(d===110&&E("namespace")&&G(9)){let p=Wt(m,!1,"namespace");c.push(p)}else{let p=i.charCodeAt(l);if(p===Y)l++;else if(p===ne||p===le){if(v(p),l<o&&i.charCodeAt(l)===Y)l++}else if(p===Oe){if(C(),l<o&&i.charCodeAt(l)===Y)l++}else if(p===af){if(l++,k(),h(),l<o&&i.charCodeAt(l)===ot)l++,k(),h();if(l<o&&i.charCodeAt(l)===Q)U(Q,pe)}else l++,ie()}}if(f.size>0)ff(c,f);if(u.size>0){let m=new Map;for(let p of c)if(p.kind==="function")m.set(p.name,(m.get(p.name)||0)+1);let d=new Set;for(let[p,y]of m)if(y>1)d.add(p);if(d.size>0){let p=new Set;for(let y of d)for(let $=c.length-1;$>=0;$--)if(c[$].kind==="function"&&c[$].name===y&&u.has($)){p.add($);break}if(p.size>0){let y=[...p].sort(($,b)=>b-$);for(let $ of y)c.splice($,1)}}}return c;function Ts(m,d){if(E("function")){let p=Et(m,d,!1,!1);if(p)c.push(p)}else if(E("async")){if(l+=5,h(),E("function")){let p=Et(m,d,!0,!1);if(p)c.push(p)}}else if(E("class")){let p=vt(m,d,!1);c.push(p)}else if(E("abstract")){if(l+=8,h(),E("class")){let p=vt(m,d,!0);c.push(p)}}else if(E("interface")){let p=Bi(m,d);c.push(p)}else if(E("type")){let p=Vi(m,d);c.push(p)}else if(E("enum")){let p=Lt(m,d,!1);c.push(p)}else if(E("const")){let p=l;if(l+=5,h(),E("enum")){l=p+5,h();let y=Lt(m,d,!0);c.push(y)}else if(d){l=p;let y=Nt(m,"const",!0);for(let $=0;$<y.length;$++)c.push(y[$])}else ie()}else if(E("let")||E("var"))if(d){let p=E("let")?"let":"var",y=Nt(m,p,!0);for(let $=0;$<y.length;$++)c.push(y[$])}else ie();else if(E("module")){let p=Wt(m,d,"module");c.push(p)}else if(E("namespace")){let p=Wt(m,d,"namespace");c.push(p)}else if(E("global")){l+=6,h();let p=`declare global ${l<o&&i.charCodeAt(l)===V?Ki():"{}"}`,y=be(m);c.push({kind:"module",name:"global",text:p,isExported:!1,leadingComments:y,start:m,end:l})}else ie()}}function Qs(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 a=e.charCodeAt(r);if(a>=65&&a<=90||a>=97&&a<=122||a>=48&&a<=57||a===95||a===36||a>127)r++;else break}t.add(e.substring(s,r))}else r++}}function ea(e,t){let r=0;while(r<e.length){let n=e.charCodeAt(r);if(n===ne||n===le||n===Oe){let u=n;r++;while(r<e.length)if(e.charCodeAt(r)===Ke)r+=2;else if(e.charCodeAt(r++)===u)break;continue}if(n===q&&e.charCodeAt(r+1)===q){r+=2;while(r<e.length&&e.charCodeAt(r)!==ge&&e.charCodeAt(r)!==Ee)r++;continue}if(n===q&&e.charCodeAt(r+1)===xe){let u=e.indexOf("*/",r+2);r=u===-1?e.length:u+2;continue}if(!Pt(n)){r++;continue}let i=r++;while(r<e.length&&_e(e.charCodeAt(r)))r++;let s=i-1,a=r;while(s>=0&&Pe(e.charCodeAt(s)))s--;while(a<e.length&&Pe(e.charCodeAt(a)))a++;let o=s>=0?e.charCodeAt(s):0,c=a<e.length?e.charCodeAt(a):0,f=i>=3&&e.slice(i-3,i)==="...";if(c===qe||o===ot&&!f)continue;if(c===Q&&(o===V||o===Xe))continue;t.add(e.slice(i,r))}}function ff(e,t){let r=new Set,n=new Set;for(let a of e)n.add(a.name);let i=new Set,s=[];for(let a=0;a<e.length;a++){let o=e[a];if(o.kind!=="import"){if(s.push(o.text),Qs(o.text,i),typeof o.value==="string")ea(o.value,i)}}for(;;){let a=[];for(let[f,u]of t){if(r.has(f))continue;if(i.has(f)){if(!n.has(f))a.push(u),n.add(f);r.add(f)}}if(a.length===0)break;a.sort((f,u)=>(f.start??1/0)-(u.start??1/0));let o=[],c=0;for(let f=0;f<e.length;f++){let u=e[f].start??1/0;while(c<a.length&&(a[c].start??1/0)<=u)o.push(a[c++]);o.push(e[f])}while(c<a.length)o.push(a[c++]);e.length=0;for(let f=0;f<o.length;f++)e.push(o[f]);for(let f of a)if(f.kind!=="import"){if(s.push(f.text),Qs(f.text,i),typeof f.value==="string")ea(f.value,i)}}}var Te=32,Re=9,ge=10,Ee=13,q=47,xe=42,ne=39,le=34,Oe=96,Ke=92,V=123,J=125,Q=40,pe=41,he=91,$e=93,de=60,oe=62,Y=59,qe=58,Ce=61,Xe=44,ot=46,Wr=63,Gr=35,af=64,ta=36,of=95,nn;var sa=ae(()=>{rn();nn=["public","protected","private","readonly","override"]});function oa(e){return e.endsWith(".vue")}function uf(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",a={content:n[2]??"",attrs:i,setup:/\bsetup\b/.test(i),lang:s};if(a.setup)t.scriptSetup=a;else t.script=a}return t}function Je(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 ze(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 lt(e,t){if(e[t+1]==="/"){let r=e.indexOf(`
61
+ `,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 an(e,t){let r=e[t];if(r==='"'||r==="'")return Je(e,t);if(r==="`")return ze(e,t);if(r==="/"&&(e[t+1]==="/"||e[t+1]==="*"))return lt(e,t);return t}function on(e){let t=e.split(""),r=0;while(r<e.length){let n=an(e,r);if(n>r){for(let i=r;i<n;i++)if(t[i]!==`
62
+ `&&t[i]!=="\r")t[i]=" ";r=n;continue}r++}return t.join("")}function Ne(e,t,r,n){let i=0,s=t;while(s<e.length){let a=e[s];if(a==='"'||a==="'"){s=Je(e,s);continue}if(a==="`"){s=ze(e,s);continue}if(a==="/"&&(e[s+1]==="/"||e[s+1]==="*")){s=lt(e,s);continue}if(a===r)i++;else if(a===n){if(i--,i===0)return s}s++}return-1}function ln(e,t){let r=0,n=t;while(n<e.length){let i=e[n];if(i==='"'||i==="'"){n=Je(e,n);continue}if(i==="`"){n=ze(e,n);continue}if(i==="/"&&(e[n+1]==="/"||e[n+1]==="*")){n=lt(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 Bt(e,t=","){let r=[],n=0,i="",s=0;while(s<e.length){let a=e[s];if(a==='"'||a==="'"){let o=Je(e,s);i+=e.slice(s,o),s=o;continue}if(a==="`"){let o=ze(e,s);i+=e.slice(s,o),s=o;continue}if(a==="/"&&(e[s+1]==="/"||e[s+1]==="*")){s=lt(e,s);continue}if(a==="{"||a==="["||a==="("||a==="<")n++;else if(a==="}"||a==="]"||a===")"||a===">")n--;if(a===t&&n===0){r.push(i),i="",s++;continue}i+=a,s++}if(i.trim()!=="")r.push(i);return r}function dr(e){let t=e.trim();if(!t.startsWith("{"))return[];let r=Ne(t,0,"{","}");if(r===-1)return[];let n=t.slice(1,r),i=[];for(let s of Bt(n)){let a=-1,o=0;for(let u=0;u<s.length;u++){let l=s[u];if(l==='"'||l==="'"){u=Je(s,u)-1;continue}if(l==="`"){u=ze(s,u)-1;continue}if(l==="{"||l==="["||l==="("||l==="<")o++;else if(l==="}"||l==="]"||l===")"||l===">")o--;else if(l===":"&&o===0){a=u;break}}if(a!==-1){i.push({key:ur(s.slice(0,a).trim()),value:s.slice(a+1).trim(),isMethod:!1});continue}let c=/^([A-Za-z_$][\w$]*|['"][^'"]+['"])\s*\(/.exec(s.trim());if(c){i.push({key:ur(c[1]),value:s.trim(),isMethod:!0});continue}let f=s.trim();if(f)i.push({key:ur(f),value:"",isMethod:!1})}return i}function ur(e){if(e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);return e}function hr(e){return/^[A-Za-z_$][\w$]*$/.test(e)?e:JSON.stringify(e)}function mr(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=ln(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 a=Ne(e,i,"(",")");if(a===-1)return null;let o=Bt(e.slice(i+1,a));return{generic:s,arg:o.length>0?o[0].trim():null}}return null}function hf(e,t){let r=la(e,t);if(!r)return null;return r.kind==="interface"?e.slice(r.bodyStart,r.end):e.slice(r.bodyStart,r.end).trim()}function la(e,t){let r=new RegExp(`\\binterface\\s+${t}\\b[^{]*\\{`,"m").exec(e);if(r){let i=r.index+r[0].length-1,s=Ne(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,a=i;while(i<e.length){let o=e[i];if(o==='"'||o==="'"){i=Je(e,i);continue}if(o==="`"){i=ze(e,i);continue}if(o==="{"||o==="["||o==="("||o==="<")s++;else if(o==="}"||o==="]"||o===")"||o===">")s--;else if((o===";"||o===`
63
+ `)&&s===0)break;i++}return{kind:"type",start:n.index,end:i,bodyStart:a}}return null}function df(e){let t=e.search(/\bas\s+PropType\s*</);if(t===-1)return null;let r=e.indexOf("<",t),n=ln(e,r);if(n===-1)return null;if(e.slice(n+1).trim()!=="")return null;return e.slice(r+1,n).trim()}function sn(e){let t=e.trim(),r=df(t);if(r!==null)return{type:r,optional:!0};if(t==="null")return{type:"unknown",optional:!0};if(t.startsWith("[")){let n=Ne(t,0,"[","]");if(n!==-1){let i=Bt(t.slice(1,n)).map((s)=>sn(s).type).filter((s)=>s!=="unknown");return{type:i.length>0?[...new Set(i)].join(" | "):"unknown",optional:!0}}}if(t.startsWith("{")){let n=dr(t),i=n.find((c)=>c.key==="type"),s=n.find((c)=>c.key==="required"),a=i?sn(i.value).type:"unknown",o=!(s&&s.value.trim()==="true");return{type:a,optional:o}}if(aa[t])return{type:aa[t],optional:!0};if(/^[A-Za-z_$][\w$.]*$/.test(t))return{type:t,optional:!0};return{type:"unknown",optional:!0}}function jr(e){let t=e.trim();if(t.startsWith("{")){let r=dr(t);if(r.length===0)return"{}";return`{ ${r.map((n)=>{if(n.isMethod||n.value==="")return`${hr(n.key)}?: unknown`;let i=sn(n.value);return`${hr(n.key)}${i.optional?"?":""}: ${i.type}`}).join(", ")} }`}if(t.startsWith("[")){let r=Ne(t,0,"[","]");if(r===-1)return null;let n=Bt(t.slice(1,r)).map((i)=>ur(i.trim())).filter((i)=>i!=="");if(n.length===0)return"{}";return`{ ${n.map((i)=>`${hr(i)}?: unknown`).join(", ")} }`}return null}function mf(e){let t=e.trim();if(!t.startsWith("["))return null;let r=Ne(t,0,"[","]");if(r===-1)return null;let n=Bt(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(ur(i))).join(", ")}]`}function pf(e){let t=e.trim();if(!t.startsWith("{"))return null;let r=dr(t);if(r.length===0)return"{}";return`{ ${r.map((n)=>`${JSON.stringify(n.key)}: (...args: any[]) => void`).join(", ")} }`}function ca(e){return mf(e)??pf(e)}function gf(e){let t=[],r=0,n="",i=0;while(i<e.length){let s=e[i];if(s==='"'||s==="'"){let a=Je(e,i);n+=e.slice(i,a),i=a;continue}if(s==="`"){let a=ze(e,i);n+=e.slice(i,a),i=a;continue}if(s==="/"&&(e[i+1]==="/"||e[i+1]==="*")){let a=lt(e,i);n+=e.slice(i,a),i=a;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===`
64
+ `)&&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 yf(e){let t=e.trim();if(!t.startsWith("{"))return null;let r=Ne(t,0,"{","}");if(r===-1||t.slice(r+1).trim()!=="")return null;let n=gf(t.slice(1,r));if(n.length===0)return"{}";let i=[];for(let s of n){let a=/^\(\s*\w+\s*:\s*/.exec(s);if(!a)return null;let o=a[0].length,c=s[o];if(c!=="'"&&c!=='"'&&c!=="`")return null;let f=Je(s,o),u=s.slice(o+1,f-1),l=Ne(s,s.indexOf("(",0),"(",")");if(l===-1)return null;let g=s.slice(o,l),h=Bt(g).slice(1),w=s.slice(l+1).trim();if(w.startsWith(":"))w=w.slice(1).trim();if(w==="")w="void";i.push(`${JSON.stringify(u)}: (${h.map((v)=>v.trim()).join(", ")}) => ${w}`)}return`{ ${i.join(", ")} }`}function cn(e){let t=e;for(let r of["defineProps","defineEmits","defineExpose","defineSlots","defineOptions"])t=Cf(t,r);return t}function Cf(e,t){let r=new RegExp(`\\b${t}\\b`,"g"),n=[],i=e,s;while((s=r.exec(e))!==null){let a=e.lastIndexOf(`
65
+ `,s.index)+1,o=e.slice(a,s.index),c=/^\s*(?:(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*(?::[^=]+)?=\s*)?(withDefaults\s*\(\s*)?$/.exec(o);if(!c)continue;let f=s.index+s[0].length;while(f<e.length&&/\s/.test(e[f]))f++;if(e[f]==="<"){let g=ln(e,f);if(g===-1)continue;f=g+1;while(f<e.length&&/\s/.test(e[f]))f++}if(e[f]!=="(")continue;let u=Ne(e,f,"(",")");if(u===-1)continue;if(c[1]){let g=a+o.length-c[1].length,h=e.indexOf("(",g);if(h!==-1){let w=Ne(e,h,"(",")");if(w!==-1)u=w}}let l=u+1;while(l<e.length&&e[l]!==`
66
66
  `&&/\s|;/.test(e[l]))l++;if(e[l]===`
67
- `)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 cn(e){let t=dc(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=Me(e,n,"{","}"),o=s;else if(e.startsWith("defineComponent",n)){let c=e.indexOf("(",n);if(c!==-1){let u=c+1;while(u<e.length&&/\s/.test(e[u]))u++;if(e[u]==="{")i=u,s=Me(e,u,"{","}"),o=Me(e,c,"(",")")}}if(i===-1||s===-1||o===-1)return{options:null,script:e,passthrough:!0};let a=o+1;if(e[a]===";")a++;let f=(e.slice(0,t)+e.slice(a)).trim();return{options:e.slice(i,s+1),script:f,passthrough:!1}}return{options:null,script:e,passthrough:!1}}function dc(e){let t=0,r=0;while(r<e.length){let n=e[r];if(n==='"'||n==="'"){r=Ge(e,r);continue}if(n==="`"){r=Xe(e,r);continue}if(n==="/"&&(e[r+1]==="/"||e[r+1]==="*")){r=ft(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 _r(e,t){let r=dr(e).find((n)=>n.key===t);return r&&r.value!==""?r.value:null}function Jr(e,t){let r=gc(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(mc(o,s.name))continue;if(new RegExp(`\\btypeof\\s+${s.name}\\b`).test(t))continue;n=o}return n}function mc(e,t){let r=0;while(r<e.length){let n=e[r];if(n==='"'||n==="'"){r=Ge(e,r);continue}if(n==="`"){r=Xe(e,r);continue}if(n==="/"&&(e[r+1]==="/"||e[r+1]==="*")){r=ft(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 gc(e){let t=[],r=pc(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(`
68
- `,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],f=i.index+i[0].length,c=-1;if(o.endsWith("function")){let u=e.indexOf("(",f);if(u===-1)continue;let l=Me(e,u,"(",")");if(l===-1)continue;f=l+1;while(f<e.length&&/\s/.test(e[f]))f++;if(e[f]===":")while(f<e.length&&e[f]!=="{"&&e[f]!==`
69
- `)f++;while(f<e.length&&/\s/.test(e[f])&&e[f]!==`
70
- `)f++;if(e[f]!=="{")continue;let p=Me(e,f,"{","}");if(p===-1)continue;c=p+1}else{let u=0;while(f<e.length){let l=e[f];if(l==='"'||l==="'"){f=Ge(e,f);continue}if(l==="`"){f=Xe(e,f);continue}if(l==="/"&&(e[f+1]==="/"||e[f+1]==="*")){f=ft(e,f);continue}if(l==="{"||l==="["||l==="(")u++;else if(l==="}"||l==="]"||l===")")u--;else if(l===";"&&u===0){c=f+1;break}else if(l===`
71
- `&&u===0){c=f;break}f++}if(c===-1)c=e.length}if(e[c]===`
72
- `)c++;t.push({name:a,start:i.index,end:c})}return t}function pc(e){let t=new Set([0]),r=0,n=0;while(n<e.length){let i=e[n];if(i==='"'||i==="'"){n=Ge(e,n);continue}if(i==="`"){n=Xe(e,n);continue}if(i==="/"&&(e[n+1]==="/"||e[n+1]==="*")){n=ft(e,n);continue}if(i==="{"||i==="["||i==="(")r++;else if(i==="}"||i==="]"||i===")")r=Math.max(0,r-1);if(i===`
73
- `&&r===0)t.add(n+1);n++}return t}function Kr(e,t,r){let n=e.indexOf(r);if(n===-1)return e;let i=e.lastIndexOf(`
74
- `,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 un(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=Ge(e,r);t+=e.slice(r,o),r=o;continue}if(s==="`"){let o=Xe(e,r);t+=e.slice(r,o),r=o;continue}if(s==="/"&&e[r+1]==="*"){let o=ft(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]!==`
75
- `)o++;let a=e.slice(r+2,o).trim();if(a!==""&&!a.includes("*/"))t+=`/* ${a} */`;r=o;continue}if(s===`
76
- `){let o=n(),a=i(r+1);if(o===""||a===""){r++;continue}let f=yc(t);if(!f&&("{;,(<:=[".includes(o)||"}),]>;|&".includes(a))){if(!t.endsWith(" ")&&!t.endsWith(";"))t+=" "}else if(f){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 yc(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 Yr(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=mr(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=lo(o,s);if(!a)continue;let f=oc(o,s);if(f===null)continue;return{type:f,inlinedLocal:{name:s,declText:o.slice(a.start,a.end)}}}return{type:s}}return{type:s}}if(i.arg){let s=Hr(i.arg);if(s!==null)return{type:s}}}return null}function hn(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=mr(n,"defineEmits");if(!i)continue;if(i.generic)return uc(i.generic)??i.generic;if(i.arg){let s=fo(i.arg);if(s!==null)return s}}return null}function dn(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=mr(n,"defineExpose");if(!i||!i.arg||!i.arg.startsWith("{"))continue;let s=dr(i.arg);if(s.length===0)return null;return`{ ${s.map((o)=>{if(o.value===""&&/^[A-Za-z_$][\w$]*$/.test(o.key))return`${hr(o.key)}: typeof ${o.key}`;let a=o.isMethod||/=>|^\s*function\b/.test(o.value);return`${hr(o.key)}: ${a?"(...args: any[]) => any":"unknown"}`}).join(", ")} }`}return null}function co(e){let t=sc(e),r="",n=null,i=null;if(t.script){let $=cn(t.script.content);if($.passthrough)return t.scriptSetup?`${t.script.content}
77
- ${t.scriptSetup.content}`:t.script.content;if(r=$.script,$.options){let O=_r($.options,"props");if(O)n=Hr(O);let T=_r($.options,"emits");if(T)i=fo(T)}}let s=t.scriptSetup?.content??null,o=s!==null?fn(s):null,a=Yr(s,s!==null?null:r),f=a?.type??n??"{}",c=hn(s,null)??i,u=dn(s,null),l=a?.inlinedLocal;if(l){if(r=Kr(r,l.name,l.declText),o!==null)o=Kr(o,l.name,l.declText)}let p=[f,u??"{}"];if(c)p.push("{}","{}","{}","{}","{}",c);let h=un(`DefineComponent<${p.join(", ")}>`),w=[],A=Jr(r,h);if(A.trim()!=="")w.push(A);if(o&&o.trim()!==""){let $=Jr(o,h);if($.trim()!=="")w.push($)}return w.push("import type { DefineComponent } from 'vue'"),w.push(`type __DtsxComponentType = ${h}`),w.push("const __dtsx_component__: __DtsxComponentType = null as unknown as __DtsxComponentType"),w.push("export default __dtsx_component__"),w.join(`
78
- `)}var oo;var mn=de(()=>{oo={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 ho(e){return e.endsWith(".stx")}function $c(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 wc(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 Cc(e){return[...$c(e),...wc(e)].sort((t,r)=>t.start-r.start)}function bc(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 Ac(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=Me(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=Me(e,s,"<",">");if(o!==-1)s=o+1}return e.slice(n,s).trim()}return null}function vc(e){return/\b(?:const|let|var)\s+\$?props\s*:\s*([^=;\n]+)/.exec(e)?.[1]?.trim()??null}function xc(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 Ec(e,t){if(!e||e==="unknown")return t;if(t==="unknown"||e===t)return e;return[...new Set([...e.split(" | "),...t.split(" | ")])].join(" | ")}function Oc(e){let t=an(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=xc(e.slice(n.lastIndex));r.set(s,Ec(r.get(s),o))}if(r.size===0)return null;return{type:`{ ${[...r].map(([s,o])=>{return`${/^[A-Za-z_$][\w$]*$/.test(s)?s:JSON.stringify(s)}?: ${o}`}).join(", ")} }`}}function kc(e){let t=Yr(e,null);if(t)return t;let r=Ac(e)??vc(e);if(!r)return Oc(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 Yr(`${e}
79
- defineProps<${r}>()`,null)}function Sc(e){return fn(e)}function uo(e){let t=an(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 Tc(e){let t=[],r=0,n=0,i=0;while(i<e.length){let o=e[i],a=on(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===`
80
- `)&&n===0){let f=i+1;if(!uo(e.slice(r,f)))t.push([r,f]);r=f}i++}if(r<e.length&&!uo(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 mo(e){let t=Cc(e).filter(bc).map((A)=>A.content).join(`
81
- `),r=null,n=cn(t);if(n.passthrough)return t;if(t=n.script,n.options){let A=_r(n.options,"props");if(A)r=Hr(A)}let i=t,s=Sc(t),o=kc(i),a=o?.type??r??"{}",f=hn(i,null),c=dn(i,null),u=mr(i,"defineSlots")?.generic??null,l=o?.inlinedLocal;if(l)s=Kr(s,l.name,l.declText);let p=`DefineComponent<${a}>`,h=[];if(f)h.push(`readonly __stxEmits?: ${f}`);if(u)h.push(`readonly __stxSlots?: ${u}`);if(c)h.push(`readonly __stxExposed?: ${c}`);if(h.length>0)p+=` & { ${h.join(", ")} }`;p=un(p),s=Tc(Jr(s,p));let w=["import type { DefineComponent } from '@stacksjs/stx'",`type __DtsxStxComponentType = ${p}`,"const __dtsx_component__: __DtsxStxComponentType = null as unknown as __DtsxStxComponentType","export default __dtsx_component__"];if(s.trim()!=="")w.push(s);return w.join(`
82
- `)}var go=de(()=>{mn()});function gr(e){if(Rc)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 Rc;var gn=de(()=>{Rc=typeof globalThis.Bun?.hash==="function"});function yo(e,t,r=!0,n=!1){if(ao(t))e=co(e);else if(ho(t))e=mo(e);let i=gr(e),s=`${t}:${r?1:0}:${n?1:0}`,o=_t.get(s);if(o&&o.contentHash===i)return o.lastAccess=++po,o.declarations;let a=n?ro(e,t,r):io(e,t,r);if(_t.set(s,{declarations:a,contentHash:i,lastAccess:++po}),_t.size>Wc){let f=Math.max(1,Math.ceil(_t.size*0.1)),c=[];for(let[u,l]of _t)c.push([u,l.lastAccess]);c.sort((u,l)=>u[1]-l[1]);for(let u=0;u<f&&u<c.length;u++)_t.delete(c[u][0])}return a}var Wc=100,po=0,_t;var $o=de(()=>{so();go();gn();mn();_t=new Map});function wo(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 Co=()=>{};function Gr(e,t,r=!0,n=!1){return yo(e,t,r,n)}var pn=de(()=>{$o()});import{dirname as Xm,relative as Nc,resolve as zm}from"path";async function bo(e,t,r){let n=new Map,i=[],s=new Set,o=0,a=0,f=0,c=[];for(let T of e){let S=t.get(T);if(!S)continue;c.push({file:T,decls:Gr(S,T,r.keepComments)})}for(let{file:T,decls:S}of c){o+=S.length;for(let W of S)if(W.kind==="import"){a++;let b=W.source||"";if(b.startsWith("."))continue;if(!n.has(b))n.set(b,{source:b,specifiers:new Map,isTypeOnly:W.isTypeOnly||!1,isSideEffect:W.isSideEffect||!1});let L=n.get(b);if(W.specifiers)for(let re of W.specifiers){let F=re.alias||re.name;if(!L.specifiers.has(F))L.specifiers.set(F,{name:re.name,alias:re.alias,isType:re.isType||!1})}if(!W.isTypeOnly)L.isTypeOnly=!1}else if(W.isExported||W.kind==="export"){if(f++,W.kind==="export"&&W.source&&(W.source.startsWith(".")||W.source.startsWith("/")))continue;if(W.name&&s.has(W.name))continue;if(W.name)s.add(W.name);i.push({declaration:W,file:T})}}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"],p=Array.from(n.values()),h=Array(p.length);for(let T=0;T<p.length;T++){let S=p[T].source,W=l.length;for(let b=0;b<l.length;b++)if(S.startsWith(l[b])){W=b;break}h[T]=W}let w=p.map((T,S)=>S);w.sort((T,S)=>{let W=h[T],b=h[S];if(W!==b)return W-b;return p[T].source.localeCompare(p[S].source)});let A=w.map((T)=>p[T]);for(let T of A)if(T.isSideEffect)u.push(`import '${T.source}';`);else if(T.specifiers.size>0){let S=Array.from(T.specifiers.values()).map((b)=>{let L=b.isType?"type ":"";return b.alias?`${L}${b.name} as ${b.alias}`:`${L}${b.name}`}),W=T.isTypeOnly?"type ":"";u.push(`import ${W}{ ${S.join(", ")} } from '${T.source}';`)}if(A.length>0)u.push("");let $=new Map;for(let{declaration:T,file:S}of i){if(!$.has(S))$.set(S,[]);$.get(S).push(T)}for(let[T,S]of $){let W=Nc(r.cwd,T);u.push(`// From: ${W}`);for(let b of S){if(r.keepComments&&b.leadingComments)for(let L of b.leadingComments)u.push(L);u.push(Ao(b))}u.push("")}let O=u.join(`
83
- `);return{content:O,files:e,declarationCount:o,importCount:a,exportCount:f,size:Buffer.byteLength(O,"utf8"),warnings:[]}}function Ao(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(`(${Fc(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(` ${Ao(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(`,
84
- `)}`)}t.push("}");break;default:return e.text||""}return t.join(" ")}function Fc(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 vo=de(()=>{pn()});import{existsSync as pr,mkdirSync as Pc,readFileSync as $n,renameSync as Dc,rmSync as xo,statSync as Eo,writeFileSync as Oo}from"fs";import{join as ko,relative as Vr,resolve as Mc}from"path";class wn{cacheDir;manifestPath;manifest=null;configHash;constructor(e){this.cacheDir=Mc(e.cwd,Zr),this.manifestPath=ko(this.cacheDir,Ic),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(gr(JSON.stringify(t)))}hashString(e){return String(gr(e))}load(){try{if(!pr(this.manifestPath))return!1;let e=$n(this.manifestPath,"utf-8"),t=JSON.parse(e);if(t.version!==yn)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:yn,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};if(this.manifest.updatedAt=Date.now(),!pr(this.cacheDir))Pc(this.cacheDir,{recursive:!0});let e=`${this.manifestPath}.${process.pid}.tmp`;try{Oo(e,JSON.stringify(this.manifest,null,2)),Dc(e,this.manifestPath)}finally{if(pr(e))xo(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=Vr(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=Eo(e),s=i.mtimeMs,o=i.ctimeMs;if(i.size!==n.sourceSize)return null;if(s!==n.sourceMtime||o!==n.sourceCtime){let a=$n(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:yn,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};let i=Vr(n,e),s,o,a;try{let f=Eo(e);s=f.mtimeMs,o=f.ctimeMs,a=f.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=Vr(t,e);delete this.manifest.entries[r]}clear(){this.manifest=null;try{if(pr(this.manifestPath))xo(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)=>Vr(t,i)));for(let i of Object.keys(this.manifest.entries))if(!n.has(i))delete this.manifest.entries[i],r++;return r}}function So(e){let t=ko(e,".gitignore");try{let r="";if(pr(t))r=$n(t,"utf-8");if(!r.split(/\r?\n/).some((n)=>n.trim()===Zr||n.trim()===`${Zr}/`)){let n=r.trimEnd(),i=`${n}${n?`
67
+ `)l++;n.push([a,l])}for(let a=n.length-1;a>=0;a--)i=i.slice(0,n[a][0])+i.slice(n[a][1]);return i}function fn(e){let t=wf(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,a=-1;if(e[n]==="{")i=n,s=Ne(e,n,"{","}"),a=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=Ne(e,u,"{","}"),a=Ne(e,f,"(",")")}}if(i===-1||s===-1||a===-1)return{options:null,script:e,passthrough:!0};let o=a+1;if(e[o]===";")o++;let c=(e.slice(0,t)+e.slice(o)).trim();return{options:e.slice(i,s+1),script:c,passthrough:!1}}return{options:null,script:e,passthrough:!1}}function wf(e){let t=0,r=0;while(r<e.length){let n=e[r];if(n==='"'||n==="'"){r=Je(e,r);continue}if(n==="`"){r=ze(e,r);continue}if(n==="/"&&(e[r+1]==="/"||e[r+1]==="*")){r=lt(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 Vr(e,t){let r=dr(e).find((n)=>n.key===t);return r&&r.value!==""?r.value:null}function _r(e,t){let r=Ef(e),n=e;for(let i=r.length-1;i>=0;i--){let s=r[i],a=n.slice(0,s.start)+n.slice(s.end);if($f(a,s.name))continue;if(new RegExp(`\\btypeof\\s+${s.name}\\b`).test(t))continue;n=a}return n}function $f(e,t){let r=0;while(r<e.length){let n=e[r];if(n==='"'||n==="'"){r=Je(e,r);continue}if(n==="`"){r=ze(e,r);continue}if(n==="/"&&(e[r+1]==="/"||e[r+1]==="*")){r=lt(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 Ef(e){let t=[],r=vf(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(`
68
+ `,i.index)+1;if(!r.has(s))continue;if(/\bexport\b/.test(e.slice(s,i.index)))continue;let a=i[1],o=i[2],c=i.index+i[0].length,f=-1;if(a.endsWith("function")){let u=e.indexOf("(",c);if(u===-1)continue;let l=Ne(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]!==`
69
+ `)c++;while(c<e.length&&/\s/.test(e[c])&&e[c]!==`
70
+ `)c++;if(e[c]!=="{")continue;let g=Ne(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=Je(e,c);continue}if(l==="`"){c=ze(e,c);continue}if(l==="/"&&(e[c+1]==="/"||e[c+1]==="*")){c=lt(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===`
71
+ `&&u===0){f=c;break}c++}if(f===-1)f=e.length}if(e[f]===`
72
+ `)f++;t.push({name:o,start:i.index,end:f})}return t}function vf(e){let t=new Set([0]),r=0,n=0;while(n<e.length){let i=e[n];if(i==='"'||i==="'"){n=Je(e,n);continue}if(i==="`"){n=ze(e,n);continue}if(i==="/"&&(e[n+1]==="/"||e[n+1]==="*")){n=lt(e,n);continue}if(i==="{"||i==="["||i==="(")r++;else if(i==="}"||i==="]"||i===")")r=Math.max(0,r-1);if(i===`
73
+ `&&r===0)t.add(n+1);n++}return t}function Hr(e,t,r){let n=e.indexOf(r);if(n===-1)return e;let i=e.lastIndexOf(`
74
+ `,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 un(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 a=s;a<e.length;a++)if(!/\s/.test(e[a]))return e[a];return""};while(r<e.length){let s=e[r];if(s==='"'||s==="'"){let a=Je(e,r);t+=e.slice(r,a),r=a;continue}if(s==="`"){let a=ze(e,r);t+=e.slice(r,a),r=a;continue}if(s==="/"&&e[r+1]==="*"){let a=lt(e,r);t+=e.slice(r,a).replace(/\s*\n\s*/g," "),r=a;continue}if(s==="/"&&e[r+1]==="/"){let a=r+2;while(a<e.length&&e[a]!==`
75
+ `)a++;let o=e.slice(r+2,a).trim();if(o!==""&&!o.includes("*/"))t+=`/* ${o} */`;r=a;continue}if(s===`
76
+ `){let a=n(),o=i(r+1);if(a===""||o===""){r++;continue}let c=bf(t);if(!c&&("{;,(<:=[".includes(a)||"}),]>;|&".includes(o))){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 bf(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 Kr(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=mr(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 a of r){let o=la(a,s);if(!o)continue;let c=hf(a,s);if(c===null)continue;return{type:c,inlinedLocal:{name:s,declText:a.slice(o.start,o.end)}}}return{type:s}}return{type:s}}if(i.arg){let s=jr(i.arg);if(s!==null)return{type:s}}}return null}function hn(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=mr(n,"defineEmits");if(!i)continue;if(i.generic)return yf(i.generic)??i.generic;if(i.arg){let s=ca(i.arg);if(s!==null)return s}}return null}function dn(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=mr(n,"defineExpose");if(!i||!i.arg||!i.arg.startsWith("{"))continue;let s=dr(i.arg);if(s.length===0)return null;return`{ ${s.map((a)=>{if(a.value===""&&/^[A-Za-z_$][\w$]*$/.test(a.key))return`${hr(a.key)}: typeof ${a.key}`;let o=a.isMethod||/=>|^\s*function\b/.test(a.value);return`${hr(a.key)}: ${o?"(...args: any[]) => any":"unknown"}`}).join(", ")} }`}return null}function fa(e){let t=uf(e),r="",n=null,i=null;if(t.script){let C=fn(t.script.content);if(C.passthrough)return t.scriptSetup?`${t.script.content}
77
+ ${t.scriptSetup.content}`:t.script.content;if(r=C.script,C.options){let x=Vr(C.options,"props");if(x)n=jr(x);let O=Vr(C.options,"emits");if(O)i=ca(O)}}let s=t.scriptSetup?.content??null,a=s!==null?cn(s):null,o=Kr(s,s!==null?null:r),c=o?.type??n??"{}",f=hn(s,null)??i,u=dn(s,null),l=o?.inlinedLocal;if(l){if(r=Hr(r,l.name,l.declText),a!==null)a=Hr(a,l.name,l.declText)}let g=[c,u??"{}"];if(f)g.push("{}","{}","{}","{}","{}",f);let h=un(`DefineComponent<${g.join(", ")}>`),w=[],v=_r(r,h);if(v.trim()!=="")w.push(v);if(a&&a.trim()!==""){let C=_r(a,h);if(C.trim()!=="")w.push(C)}return w.push("import type { DefineComponent } from 'vue'"),w.push(`type __DtsxComponentType = ${h}`),w.push("const __dtsx_component__: __DtsxComponentType = null as unknown as __DtsxComponentType"),w.push("export default __dtsx_component__"),w.join(`
78
+ `)}var aa;var mn=ae(()=>{aa={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 ha(e){return e.endsWith(".stx")}function Sf(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"),a=/\bserver\b/i.test(i)?"server":/\bclient\b/i.test(i)?"client":"universal";t.push({content:n[2]??"",kind:"script",attrs:i,context:a,lang:s,start:n.index})}return t}function Af(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 a=s.exec(e),o=a?.index??e.length;if(t.push({content:e.slice(i,o),kind:"ts",attrs:"",context:"universal",lang:"ts",start:n.index}),!a)break;r.lastIndex=s.lastIndex}return t}function xf(e){return[...Sf(e),...Af(e)].sort((t,r)=>t.start-r.start)}function Tf(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 Rf(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 a=Ne(e,n,"{","}");if(a!==-1)return e.slice(n,a+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 a=Ne(e,s,"<",">");if(a!==-1)s=a+1}return e.slice(n,s).trim()}return null}function Of(e){return/\b(?:const|let|var)\s+\$?props\s*:\s*([^=;\n]+)/.exec(e)?.[1]?.trim()??null}function Pf(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 kf(e,t){if(!e||e==="unknown")return t;if(t==="unknown"||e===t)return e;return[...new Set([...e.split(" | "),...t.split(" | ")])].join(" | ")}function Mf(e){let t=on(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],a=Pf(e.slice(n.lastIndex));r.set(s,kf(r.get(s),a))}if(r.size===0)return null;return{type:`{ ${[...r].map(([s,a])=>{return`${/^[A-Za-z_$][\w$]*$/.test(s)?s:JSON.stringify(s)}?: ${a}`}).join(", ")} }`}}function If(e){let t=Kr(e,null);if(t)return t;let r=Rf(e)??Of(e);if(!r)return Mf(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 Kr(`${e}
79
+ defineProps<${r}>()`,null)}function Df(e){return cn(e)}function ua(e){let t=on(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 Ff(e){let t=[],r=0,n=0,i=0;while(i<e.length){let a=e[i],o=an(e,i);if(o>i){i=o;continue}if(a==="{"||a==="["||a==="(")n++;else if(a==="}"||a==="]"||a===")")n=Math.max(0,n-1);if((a===";"||a===`
80
+ `)&&n===0){let c=i+1;if(!ua(e.slice(r,c)))t.push([r,c]);r=c}i++}if(r<e.length&&!ua(e.slice(r)))t.push([r,e.length]);let s=e;for(let a=t.length-1;a>=0;a--)s=s.slice(0,t[a][0])+s.slice(t[a][1]);return s}function da(e){let t=xf(e).filter(Tf).map((v)=>v.content).join(`
81
+ `),r=null,n=fn(t);if(n.passthrough)return t;if(t=n.script,n.options){let v=Vr(n.options,"props");if(v)r=jr(v)}let i=t,s=Df(t),a=If(i),o=a?.type??r??"{}",c=hn(i,null),f=dn(i,null),u=mr(i,"defineSlots")?.generic??null,l=a?.inlinedLocal;if(l)s=Hr(s,l.name,l.declText);let g=`DefineComponent<${o}>`,h=[];if(c)h.push(`readonly __stxEmits?: ${c}`);if(u)h.push(`readonly __stxSlots?: ${u}`);if(f)h.push(`readonly __stxExposed?: ${f}`);if(h.length>0)g+=` & { ${h.join(", ")} }`;g=un(g),s=Ff(_r(s,g));let w=["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()!=="")w.push(s);return w.join(`
82
+ `)}var ma=ae(()=>{mn()});function pr(e){if(Nf)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 Nf;var pn=ae(()=>{Nf=typeof globalThis.Bun?.hash==="function"});function ga(e,t,r=!0,n=!1){if(oa(t))e=fa(e);else if(ha(t))e=da(e);let i=pr(e),s=`${t}:${r?1:0}:${n?1:0}`,a=Vt.get(s);if(a&&a.contentHash===i)return a.lastAccess=++pa,a.declarations;let o=n?ra(e,t,r):ia(e,t,r);if(Vt.set(s,{declarations:o,contentHash:i,lastAccess:++pa}),Vt.size>Lf){let c=Math.max(1,Math.ceil(Vt.size*0.1)),f=[];for(let[u,l]of Vt)f.push([u,l.lastAccess]);f.sort((u,l)=>u[1]-l[1]);for(let u=0;u<c&&u<f.length;u++)Vt.delete(f[u][0])}return o}var Lf=100,pa=0,Vt;var ya=ae(()=>{sa();ma();pn();mn();Vt=new Map});function Ca(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 wa=()=>{};function Jr(e,t,r=!0,n=!1){return ga(e,t,r,n)}var gn=ae(()=>{ya()});import{dirname as lp,relative as Wf,resolve as cp}from"path";async function $a(e,t,r){let n=new Map,i=[],s=new Set,a=0,o=0,c=0,f=[];for(let O of e){let R=t.get(O);if(!R)continue;f.push({file:O,decls:Jr(R,O,r.keepComments)})}for(let{file:O,decls:R}of f){a+=R.length;for(let k of R)if(k.kind==="import"){o++;let E=k.source||"";if(E.startsWith("."))continue;if(!n.has(E))n.set(E,{source:E,specifiers:new Map,isTypeOnly:k.isTypeOnly||!1,isSideEffect:k.isSideEffect||!1});let G=n.get(E);if(k.specifiers)for(let re of k.specifiers){let I=re.alias||re.name;if(!G.specifiers.has(I))G.specifiers.set(I,{name:re.name,alias:re.alias,isType:re.isType||!1})}if(!k.isTypeOnly)G.isTypeOnly=!1}else if(k.isExported||k.kind==="export"){if(c++,k.kind==="export"&&k.source&&(k.source.startsWith(".")||k.source.startsWith("/")))continue;if(k.name&&s.has(k.name))continue;if(k.name)s.add(k.name);i.push({declaration:k,file:O})}}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()),h=Array(g.length);for(let O=0;O<g.length;O++){let R=g[O].source,k=l.length;for(let E=0;E<l.length;E++)if(R.startsWith(l[E])){k=E;break}h[O]=k}let w=g.map((O,R)=>R);w.sort((O,R)=>{let k=h[O],E=h[R];if(k!==E)return k-E;return g[O].source.localeCompare(g[R].source)});let v=w.map((O)=>g[O]);for(let O of v)if(O.isSideEffect)u.push(`import '${O.source}';`);else if(O.specifiers.size>0){let R=Array.from(O.specifiers.values()).map((E)=>{let G=E.isType?"type ":"";return E.alias?`${G}${E.name} as ${E.alias}`:`${G}${E.name}`}),k=O.isTypeOnly?"type ":"";u.push(`import ${k}{ ${R.join(", ")} } from '${O.source}';`)}if(v.length>0)u.push("");let C=new Map;for(let{declaration:O,file:R}of i){if(!C.has(R))C.set(R,[]);C.get(R).push(O)}for(let[O,R]of C){let k=Wf(r.cwd,O);u.push(`// From: ${k}`);for(let E of R){if(r.keepComments&&E.leadingComments)for(let G of E.leadingComments)u.push(G);u.push(Ea(E))}u.push("")}let x=u.join(`
83
+ `);return{content:x,files:e,declarationCount:a,importCount:o,exportCount:c,size:Buffer.byteLength(x,"utf8"),warnings:[]}}function Ea(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(`(${Gf(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(` ${Ea(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(`,
84
+ `)}`)}t.push("}");break;default:return e.text||""}return t.join(" ")}function Gf(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 va=ae(()=>{gn()});import{existsSync as gr,mkdirSync as Bf,readFileSync as Cn,renameSync as Vf,rmSync as ba,statSync as Sa,writeFileSync as Aa}from"fs";import{join as xa,relative as Ur,resolve as _f}from"path";class wn{cacheDir;manifestPath;manifest=null;configHash;constructor(e){this.cacheDir=_f(e.cwd,Yr),this.manifestPath=xa(this.cacheDir,Hf),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(pr(JSON.stringify(t)))}hashString(e){return String(pr(e))}load(){try{if(!gr(this.manifestPath))return!1;let e=Cn(this.manifestPath,"utf-8"),t=JSON.parse(e);if(t.version!==yn)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:yn,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};if(this.manifest.updatedAt=Date.now(),!gr(this.cacheDir))Bf(this.cacheDir,{recursive:!0});let e=`${this.manifestPath}.${process.pid}.tmp`;try{Aa(e,JSON.stringify(this.manifest,null,2)),Vf(e,this.manifestPath)}finally{if(gr(e))ba(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=Ur(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=Sa(e),s=i.mtimeMs,a=i.ctimeMs;if(i.size!==n.sourceSize)return null;if(s!==n.sourceMtime||a!==n.sourceCtime){let o=Cn(e,"utf-8");if(this.hashString(o)!==n.sourceHash)return null;n.sourceMtime=s,n.sourceCtime=a}return n.dtsContent}catch{return null}}update(e,t,r,n){if(!this.manifest)this.manifest={version:yn,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};let i=Ur(n,e),s,a,o;try{let c=Sa(e);s=c.mtimeMs,a=c.ctimeMs,o=c.size}catch{s=Date.now(),a=s,o=Buffer.byteLength(t)}this.manifest.entries[i]={sourcePath:i,sourceHash:this.hashString(t),sourceMtime:s,sourceCtime:a,sourceSize:o,dtsContent:r,dtsHash:this.hashString(r),generatedAt:Date.now(),configHash:this.configHash}}remove(e,t){if(!this.manifest)return;let r=Ur(t,e);delete this.manifest.entries[r]}clear(){this.manifest=null;try{if(gr(this.manifestPath))ba(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)=>Ur(t,i)));for(let i of Object.keys(this.manifest.entries))if(!n.has(i))delete this.manifest.entries[i],r++;return r}}function Ta(e){let t=xa(e,".gitignore");try{let r="";if(gr(t))r=Cn(t,"utf-8");if(!r.split(/\r?\n/).some((n)=>n.trim()===Yr||n.trim()===`${Yr}/`)){let n=r.trimEnd(),i=`${n}${n?`
85
85
 
86
86
  `:""}# dtsx cache
87
- ${Zr}/
88
- `;Oo(t,i)}}catch{}}var yn=3,Zr=".dtsx-cache",Ic="manifest.json";var To=de(()=>{gn()});function Jc(e){switch(e){case"strict":return Lc;case"readonly":return jc;case"simplified":return _c;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 Wo{rules;compiled=[];cache=new Map;constructor(e={rules:[]}){if(this.rules=[],e.includeDefaults!==!1)this.rules.push(...Bc);if(e.presets)for(let t of e.presets)this.rules.push(...Jc(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(Kc,"\\$&"),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:f}=this.compiled[o];if(a.condition){if(!s)s={type:e,...t};if(!a.condition(s))continue}if(f.lastIndex=0,f.test(i)){if(f.lastIndex=0,i=i.replace(f,a.replacement),f.lastIndex=0,!a.global)break}}if(this.cache.size>=Ro){let o=Math.ceil(Ro*0.1),a=0;for(let f of this.cache.keys()){if(a++>=o)break;this.cache.delete(f)}}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 qr(e={rules:[]}){return new Wo(e)}function No(e,t,r={}){return e.replace(/:\s*([^;,)\]}]+)/g,(n,i)=>{return`: ${t.map(i.trim(),r)}`})}var Bc,Lc,jc,_c,Kc,Ro=2048,ng,sg;var Fo=de(()=>{Bc=[{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}],Lc=[{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}],jc=[{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}],_c=[{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}];Kc=/[.*+?^${}()|[\]\\]/g;ng=qr({rules:[]}),sg=qr({rules:[],presets:["strict"]})});async function Hc(){if(Ur!==null)return Ur;try{return xt=await import("prettier"),Ur=!0,!0}catch{return Ur=!1,!1}}async function Yc(e,t){if(!xt)return null;try{if(t&&xt.resolveConfig){let r=await xt.resolveConfig(t);if(r)return r}if(e&&xt.resolveConfig){let r=await xt.resolveConfig(e);if(r)return r}return null}catch{return null}}async function Gc(e,t){if(!xt)throw Error("Prettier is not available");let r={...t,parser:t.parser||"typescript"};return xt.format(e,r)}function Vc(e,t={}){let{indentSize:r=2,useTabs:n=!1,maxLineWidth:i=100,trailingNewline:s=!0,normalizeWhitespace:o=!0,sortImports:a=!0,groupImports:f=!0}=t,c=e,u=n?"\t":" ".repeat(r);if(c.indexOf(`\r
89
- `)!==-1)c=c.replace(/\r\n/g,`
90
- `);if(o){if(/[ \t]\n/.test(c)||/[ \t]$/.test(c))c=c.replace(/[ \t]+$/gm,"");if(c.indexOf(`
87
+ ${Yr}/
88
+ `;Aa(t,i)}}catch{}}var yn=3,Yr=".dtsx-cache",Hf="manifest.json";var Ra=ae(()=>{pn()});function Yf(e){switch(e){case"strict":return Kf;case"readonly":return Jf;case"simplified":return Uf;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 Pa{rules;compiled=[];cache=new Map;constructor(e={rules:[]}){if(this.rules=[],e.includeDefaults!==!1)this.rules.push(...jf);if(e.presets)for(let t of e.presets)this.rules.push(...Yf(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(Zf,"\\$&"),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 a=0;a<this.compiled.length;a++){let{rule:o,regex:c}=this.compiled[a];if(o.condition){if(!s)s={type:e,...t};if(!o.condition(s))continue}if(c.lastIndex=0,c.test(i)){if(c.lastIndex=0,i=i.replace(c,o.replacement),c.lastIndex=0,!o.global)break}}if(this.cache.size>=Oa){let a=Math.ceil(Oa*0.1),o=0;for(let c of this.cache.keys()){if(o++>=a)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 Zr(e={rules:[]}){return new Pa(e)}function ka(e,t,r={}){return e.replace(/:\s*([^;,)\]}]+)/g,(n,i)=>{return`: ${t.map(i.trim(),r)}`})}var jf,Kf,Jf,Uf,Zf,Oa=2048,pp,gp;var Ma=ae(()=>{jf=[{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}],Kf=[{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}],Jf=[{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}],Uf=[{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}];Zf=/[.*+?^${}()|[\]\\]/g;pp=Zr({rules:[]}),gp=Zr({rules:[],presets:["strict"]})});async function qf(){if(qr!==null)return qr;try{return St=await import("prettier"),qr=!0,!0}catch{return qr=!1,!1}}async function Xf(e,t){if(!St)return null;try{if(t&&St.resolveConfig){let r=await St.resolveConfig(t);if(r)return r}if(e&&St.resolveConfig){let r=await St.resolveConfig(e);if(r)return r}return null}catch{return null}}async function zf(e,t){if(!St)throw Error("Prettier is not available");let r={...t,parser:t.parser||"typescript"};return St.format(e,r)}function Qf(e,t={}){let{indentSize:r=2,useTabs:n=!1,maxLineWidth:i=100,trailingNewline:s=!0,normalizeWhitespace:a=!0,sortImports:o=!0,groupImports:c=!0}=t,f=e,u=n?"\t":" ".repeat(r);if(f.indexOf(`\r
89
+ `)!==-1)f=f.replace(/\r\n/g,`
90
+ `);if(a){if(/[ \t]\n/.test(f)||/[ \t]$/.test(f))f=f.replace(/[ \t]+$/gm,"");if(f.indexOf(`
91
91
 
92
92
 
93
- `)!==-1)c=c.replace(/\n{3,}/g,`
93
+ `)!==-1)f=f.replace(/\n{3,}/g,`
94
94
 
95
- `);c=Zc(c,u)}if(a||f)c=qc(c,{sort:a,group:f});if(i>0)c=Xc(c,i,u);if(s&&!c.endsWith(`
96
- `))c+=`
97
- `;return c}function Zc(e,t){let r=e.split(`
98
- `),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 f=o.replace(/\t/g," ").length,c=Math.floor(f/2);n.push(t.repeat(c)+a)}return n.join(`
99
- `)}function qc(e,t){let r=e.split(`
100
- `),n=[],i=[],s=!1,o=0;for(let f=0;f<r.length;f++){let c=r[f],u=c.match(/^(import\s+(?:type\s+)?.*from\s+['"])([^'"]+)(['"].*)$/);if(u){s=!0,o=f;let l=u[1];n.push({line:c,source:u[2],isType:l.startsWith("import type ")||l.startsWith("import type\t")})}else if(s&&c.trim()==="")continue;else{if(s)s=!1;i.push(c)}}if(n.length===0)return e;if(t.sort)n.sort((f,c)=>{if(f.isType!==c.isType)return f.isType?1:-1;return Uc(f.source,c.source)});let a;if(t.group){let f=[],c=[],u=[],l=[],p=[];for(let h=0;h<n.length;h++){let w=n[h],A=w.source;if(A.charCodeAt(0)===46)p.push(w);else if(A.startsWith("node:"))f.push(w);else if(A.charCodeAt(0)===64)l.push(w);else if(A.includes("/"))u.push(w);else c.push(w)}a=[...f.map((h)=>h.line),...f.length>0&&c.length>0?[""]:[],...c.map((h)=>h.line),...(f.length>0||c.length>0)&&u.length>0?[""]:[],...u.map((h)=>h.line),...l.length>0&&(f.length>0||c.length>0||u.length>0)?[""]:[],...l.map((h)=>h.line),...p.length>0?[""]:[],...p.map((h)=>h.line)]}else a=n.map((f)=>f.line);return[...a,"",...i].join(`
101
- `)}function Uc(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 Xc(e,t,r){let n=e.split(`
102
- `),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 f=zc(s,t,o,a);i.push(...f);continue}if(s.includes(" | ")){let f=Qc(s,t,o,a);i.push(...f);continue}i.push(s)}return i.join(`
103
- `)}function zc(e,t,r,n){let i=e.match(/^(\s*)(.*?)(\{)(.+)(\}.*)$/);if(!i)return[e];let[,,s,o,a,f]=i,c=a.split(/;\s*|,\s*/).filter((u)=>u.trim());if(c.length<=1)return[e];return[`${r}${s}${o}`,...c.map((u)=>`${n}${u.trim()};`),`${r}${f.trim()}`]}function Qc(e,t,r,n){let i=e.match(/^(\s*)(.*?=\s*)(.+)$/);if(!i)return[e];let[,,s,o]=i,a=o.split(/\s*\|\s*/).filter((f)=>f.trim());if(a.length<=2)return[e];return[`${r}${s}`,...a.map((f,c)=>`${n}${c>0?"| ":" "}${f.trim()}`)]}async function Po(e,t={},r){let n=[];if(t.usePrettier!==!1){if(await Hc())try{let i={...await Yc(t.prettierConfigPath,r),...t.prettierOptions,parser:"typescript"};return{content:await Gc(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:Vc(e,t.builtIn),usedPrettier:!1,warnings:n.length>0?n:void 0}}var Ur=null,xt=null;var Do=()=>{};function Mo(e,t,r){let n={file:t,message:"Unknown error",code:yr.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=yr.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=yr.SYNTAX_ERROR,n.suggestion="Check for syntax errors in your TypeScript code.";else if(e.message.includes("type")&&e.message.includes("cannot"))n.code=yr.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=yr.PARSE_ERROR,n.suggestion="The file contains invalid TypeScript syntax."}else if(typeof e==="string")n.message=e;return n}function Io(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(`
104
- `),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 f=o;f<=a;f++){let c=(f+1).toString().padStart(4," "),u=f===s?">":" ";if(r.push(` ${u} ${c} | ${i[f]}`),f===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(`
105
- `)}var yr;var Bo=de(()=>{yr={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 ut(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}
95
+ `);f=eu(f,u)}if(o||c)f=tu(f,{sort:o,group:c});if(i>0)f=iu(f,i,u);if(s&&!f.endsWith(`
96
+ `))f+=`
97
+ `;return f}function eu(e,t){let r=e.split(`
98
+ `),n=[];for(let i of r){let s=i.match(/^(\s*)(.*)$/);if(!s){n.push(i);continue}let[,a,o]=s;if(!o){n.push("");continue}let c=a.replace(/\t/g," ").length,f=Math.floor(c/2);n.push(t.repeat(f)+o)}return n.join(`
99
+ `)}function tu(e,t){let r=e.split(`
100
+ `),n=[],i=[],s=!1,a=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,a=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 ru(c.source,f.source)});let o;if(t.group){let c=[],f=[],u=[],l=[],g=[];for(let h=0;h<n.length;h++){let w=n[h],v=w.source;if(v.charCodeAt(0)===46)g.push(w);else if(v.startsWith("node:"))c.push(w);else if(v.charCodeAt(0)===64)l.push(w);else if(v.includes("/"))u.push(w);else f.push(w)}o=[...c.map((h)=>h.line),...c.length>0&&f.length>0?[""]:[],...f.map((h)=>h.line),...(c.length>0||f.length>0)&&u.length>0?[""]:[],...u.map((h)=>h.line),...l.length>0&&(c.length>0||f.length>0||u.length>0)?[""]:[],...l.map((h)=>h.line),...g.length>0?[""]:[],...g.map((h)=>h.line)]}else o=n.map((c)=>c.line);return[...o,"",...i].join(`
101
+ `)}function ru(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 iu(e,t,r){let n=e.split(`
102
+ `),i=[];for(let s of n){if(s.length<=t){i.push(s);continue}if(s.trimStart().startsWith("import ")){i.push(s);continue}let a=s.match(/^(\s*)/)?.[1]||"",o=a+r;if(s.includes("{")&&s.includes("}")){let c=nu(s,t,a,o);i.push(...c);continue}if(s.includes(" | ")){let c=su(s,t,a,o);i.push(...c);continue}i.push(s)}return i.join(`
103
+ `)}function nu(e,t,r,n){let i=e.match(/^(\s*)(.*?)(\{)(.+)(\}.*)$/);if(!i)return[e];let[,,s,a,o,c]=i,f=o.split(/;\s*|,\s*/).filter((u)=>u.trim());if(f.length<=1)return[e];return[`${r}${s}${a}`,...f.map((u)=>`${n}${u.trim()};`),`${r}${c.trim()}`]}function su(e,t,r,n){let i=e.match(/^(\s*)(.*?=\s*)(.+)$/);if(!i)return[e];let[,,s,a]=i,o=a.split(/\s*\|\s*/).filter((c)=>c.trim());if(o.length<=2)return[e];return[`${r}${s}`,...o.map((c,f)=>`${n}${f>0?"| ":" "}${c.trim()}`)]}async function Ia(e,t={},r){let n=[];if(t.usePrettier!==!1){if(await qf())try{let i={...await Xf(t.prettierConfigPath,r),...t.prettierOptions,parser:"typescript"};return{content:await zf(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:Qf(e,t.builtIn),usedPrettier:!1,warnings:n.length>0?n:void 0}}var qr=null,St=null;var Da=()=>{};function Fa(e,t,r){let n={file:t,message:"Unknown error",code:yr.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=yr.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=yr.SYNTAX_ERROR,n.suggestion="Check for syntax errors in your TypeScript code.";else if(e.message.includes("type")&&e.message.includes("cannot"))n.code=yr.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=yr.PARSE_ERROR,n.suggestion="The file contains invalid TypeScript syntax."}else if(typeof e==="string")n.message=e;return n}function Na(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(`
104
+ `),s=e.location.line-1;if(s>=0&&s<i.length){let a=Math.max(0,s-1),o=Math.min(i.length-1,s+1);for(let c=a;c<=o;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(`
105
+ `)}var yr;var La=ae(()=>{yr={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 ut(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}
106
106
  `;return`${n.trim()}
107
107
  `}let r="";for(let n=0;n<e.length;n++){if(n>0)r+=`
108
108
  `;r+=e[n].trim()}return`${r}
109
- `}var Lo=()=>{};function iu(e){let t=[],r=0;for(let n=0;n<=e.length;n++)if(n===e.length||e[n]===`
110
- `){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(eu.test(o)||tu.test(o)||ru.test(o))t.push(o)}else if(o===""||o.startsWith("//"))continue;else break}return t}function nu(e){if(e.includes(`
109
+ `}var Wa=()=>{};function cu(e){let t=[],r=0;for(let n=0;n<=e.length;n++)if(n===e.length||e[n]===`
110
+ `){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 a=e.slice(i,s);if(r=n+1,a.startsWith("///")){if(a.indexOf("<")===-1)continue;if(au.test(a)||ou.test(a)||lu.test(a))t.push(a)}else if(a===""||a.startsWith("//"))continue;else break}return t}function fu(e){if(e.includes(`
111
111
  `))return`/**
112
112
  * ${e}
113
113
  */
114
114
  `;return`/** ${e} */
115
- `}function su(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],f=o>0?e[o-1]:"";if(!i&&(a==='"'||a==="'"||a==="`"))i=!0,s=a;else if(i&&a===s&&f!=="\\")i=!1;if(!i){if(a==="<")n++;else if(a===">")n--;else if(a==="{"&&n===0)return o}}return-1}function ou(e,t=!0){return ut(e.leadingComments,t)+e.text}function jo(e,t=!0){let r=ut(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 f=zs(o);if(f)s=f}else if(!s&&o&&o.trim().endsWith("as const"))s=Ee(o,!0);else if(!s&&o&&i==="const"){let f=o.trim(),c=f.startsWith("{")||f.startsWith("[");if(c)Qi();s=Ee(o,!c)}else if(!s&&o)s=Ee(o,i==="const");if(!s)s="unknown";let a="";if(t&&o&&!e.typeAnnotation&&!o.trim().endsWith("as const")){let f=o.trim();if(i!=="const"){if((s==="string"||s==="number"||s==="boolean")&&f.length>0)a=`@defaultValue ${f}`}else if(f.startsWith("{")||f.startsWith("[")){let c=en();if(c)if(c.includes(`
116
- `))a=`@defaultValue
115
+ `}function uu(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 a=0;a<e.length;a++){let o=e[a],c=a>0?e[a-1]:"";if(!i&&(o==='"'||o==="'"||o==="`"))i=!0,s=o;else if(i&&o===s&&c!=="\\")i=!1;if(!i){if(o==="<")n++;else if(o===">")n--;else if(o==="{"&&n===0)return a}}return-1}function hu(e,t=!0){return ut(e.leadingComments,t)+e.text}function Ga(e,t=!0){let r=ut(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:a}=e;if(a&&a.includes(" satisfies ")){let c=zs(a);if(c)s=c}else if(!s&&a&&a.trim().endsWith("as const"))s=Ae(a,!0);else if(!s&&a&&i==="const"){let c=a.trim(),f=c.startsWith("{")||c.startsWith("[");if(f)Qi();s=Ae(a,!f)}else if(!s&&a)s=Ae(a,i==="const");if(!s)s="unknown";let o="";if(t&&a&&!e.typeAnnotation&&!a.trim().endsWith("as const")){let c=a.trim();if(i!=="const"){if((s==="string"||s==="number"||s==="boolean")&&c.length>0)o=`@defaultValue ${c}`}else if(c.startsWith("{")||c.startsWith("[")){let f=en();if(f)if(f.includes(`
116
+ `))o=`@defaultValue
117
117
  * \`\`\`ts
118
- ${c.split(`
118
+ ${f.split(`
119
119
  `).map((u)=>` * ${u}`).join(`
120
120
  `)}
121
- * \`\`\``;else a=`@defaultValue \`${c}\``}}else if(t&&o&&e.typeAnnotation&&Xs(e.typeAnnotation)){Qi();let f=o.trim(),c=f.endsWith("as const")?f.slice(0,-8).trim():f;Ee(c,!1);let u=en();if(u)if(u.includes(`
122
- `))a=`@defaultValue
121
+ * \`\`\``;else o=`@defaultValue \`${f}\``}}else if(t&&a&&e.typeAnnotation&&Xs(e.typeAnnotation)){Qi();let c=a.trim(),f=c.endsWith("as const")?c.slice(0,-8).trim():c;Ae(f,!1);let u=en();if(u)if(u.includes(`
122
+ `))o=`@defaultValue
123
123
  * \`\`\`ts
124
124
  ${u.split(`
125
125
  `).map((l)=>` * ${l}`).join(`
126
126
  `)}
127
- * \`\`\``;else a=`@defaultValue \`${u}\``}if(n+=`: ${s};`,a&&r&&r.includes("@defaultValue"))a="";if(a&&r){let f=r.trimEnd(),c=f.lastIndexOf("*/");if(c!==-1){let u=f.slice(0,c).trimEnd();if(u.startsWith("/** ")&&!u.includes(`
127
+ * \`\`\``;else o=`@defaultValue \`${u}\``}if(n+=`: ${s};`,o&&r&&r.includes("@defaultValue"))o="";if(o&&r){let c=r.trimEnd(),f=c.lastIndexOf("*/");if(f!==-1){let u=c.slice(0,f).trimEnd();if(u.startsWith("/** ")&&!u.includes(`
128
128
  `))u=`/**
129
129
  * ${u.slice(4)}`;return`${u}
130
- * ${a}
130
+ * ${o}
131
131
  */
132
132
  `+n}return`/**
133
- * ${f.replace(/^\/\/\s*/,"")}
134
- * ${a}
133
+ * ${c.replace(/^\/\/\s*/,"")}
134
+ * ${o}
135
135
  */
136
- ${n}`}if(a)return`${nu(a)}${n}`;return r+n}function au(e,t=!0){let r=ut(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=su(e.text);if(s!==-1)i+=` ${e.text.slice(s)}`;else i+=" {}";return r+i}function lu(e,t=!0){let r=ut(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 fu(e,t=!0){return ut(e.leadingComments,t)+e.text}function cu(e,t=!0){let r=ut(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 uu(e,t=!0){let r=ut(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 hu(e){let t=Wt.get(e);if(t)return Wt.delete(e),Wt.set(e,t),t;return null}function _o(e,t){if(Wt.set(e,t),Wt.size>200){let r=0;for(let n of Wt.keys()){if(r++>=20)break;Wt.delete(n)}}}function du(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 f=null,c=[],u=!1,l=o.indexOf("{"),p=o.lastIndexOf("}");if(l!==-1&&p!==-1){let h=o.slice(0,l).trim();if(h.endsWith(","))f=h.slice(0,-1).trim()||null;let w=o.slice(l+1,p),A=0;for(let $=0;$<=w.length;$++)if($===w.length||w.charCodeAt($)===44){let O=A,T=$;while(O<T&&(w.charCodeAt(O)===32||w.charCodeAt(O)===9||w.charCodeAt(O)===10))O++;while(T>O&&(w.charCodeAt(T-1)===32||w.charCodeAt(T-1)===9||w.charCodeAt(T-1)===10))T--;if(O<T)c.push(w.slice(O,T));A=$+1}}else{let h=o.trim();if(h.startsWith("* as "))f=h.slice(5).trim()||null,u=!0;else f=h||null}return{defaultName:f,namedItems:c,source:s,isTypeOnly:a,isNamespace:u}}function mu(e){let t=hu(e);if(t)return t;let r=[],n=e.indexOf(" from ");if(n===-1)return _o(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 c=a.slice(0,-1).trim();if(c)r.push(c)}else if(a&&!a.includes(","))r.push(a);let f=i.slice(s+1,o).split(",");for(let c=0;c<f.length;c++){let u=f[c].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 f=a.slice(5).trim();if(f)r.push(f)}else if(a)r.push(a)}return _o(e,r),r}function Jo(e,t){throw Error(t||`Unexpected value: ${e}`)}function gu(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===95||e===36||e>127}function Ko(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&&gu(e.charCodeAt(r)))r++;t.add(e.substring(s,r))}else r++}return t}function Vo(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=iu(s);if(J.length>0)for(let X=0;X<J.length;X++){if(i)i+=`
137
- `;i+=J[X]}}}let o=[],a=[],f=[],c=[],u=[],l=[],p=[],h=[],w=[];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":f.push(F);break;case"interface":c.push(F);break;case"type":u.push(F);break;case"class":l.push(F);break;case"enum":p.push(F);break;case"module":h.push(F);break;case"export":w.push(F);break;case"namespace":h.push(F);break;case"unknown":break;default:Jo(J,`Unhandled declaration kind: ${J}`)}}let A=new Set,$=[],O=[],T=[],S=new Set;for(let F of w){let J=ut(F.leadingComments,r);if(F.text.startsWith("export default")){let X=F.text.endsWith(";")?F.text:`${F.text};`;T.push(J+X)}else{let X=F.text.trim();if(!X.endsWith(";"))X+=";";let se=X.match(pu);if(se){let q=se[1],V=0;for(let Y=0;Y<=q.length;Y++)if(Y===q.length||q.charCodeAt(Y)===44){let we=V,z=Y;while(we<z&&q.charCodeAt(we)<=32)we++;while(z>we&&q.charCodeAt(z-1)<=32)z--;if(we<z)A.add(q.slice(we,z));V=Y+1}}let H=J+X;if(!S.has(H))if(S.add(H),H.includes("export type"))$.push(H);else O.push(H)}}let W=new Map;if(o.length>0)for(let F of o){let J=mu(F.text);for(let X of J)W.set(X,F)}let b=new Set;if(c.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=Ko(F.join(`
138
- `));for(let X of c)if(J.has(X.name))b.add(X.name)}}let L=[];if(o.length>0){let F=new Set,J=[];for(let H of a)if(H.isExported)J.push(H.text);for(let H of f)if(J.push(H.text),H.typeAnnotation)J.push(H.typeAnnotation);else if(H.isExported&&H.value)J.push(jo(H,!1));for(let H of c)if(H.isExported||b.has(H.name))J.push(H.text);for(let H of u)J.push(H.text);for(let H of l)J.push(H.text);for(let H of p)J.push(H.text);for(let H of h)J.push(H.text);for(let H of w)J.push(H.text);let X=J.join(`
139
- `);if(X&&W.size>0){let H=Ko(X);for(let q of W.keys())if(H.has(q))F.add(q)}for(let H of A)if(W.has(H))F.add(H);for(let H of o){if(H.isSideEffect){let De=H.text.trim(),ve=De.endsWith(";")?De:`${De};`;L.push(ve);continue}let q=du(H.text);if(!q)continue;let{defaultName:V,namedItems:Y,source:we,isTypeOnly:z,isNamespace:ie}=q,kr=V?F.has(V):!1,kt="",wt=0;for(let De=0;De<Y.length;De++){let ve=Y[De],Ft=ve.charCodeAt(0)===116&&ve.startsWith("type ")?ve.slice(5).trim():ve.trim(),Pt=Ft.indexOf(" as ");if(Pt!==-1)Ft=Ft.slice(Pt+4).trim();if(F.has(Ft)){if(wt>0)kt+=", ";kt+=ve,wt++}}if(kr||wt>0){let De=z?"import type ":"import ";if(kr&&V)if(ie)De+=`* as ${V}`;else De+=wt>0?`${V}, { ${kt} }`:V;else if(wt>0)De+=`{ ${kt} }`;De+=` from '${we}';`,L.push(De)}}let se=n.length;if(L.length>1){if(Ho!==n)Ho=n,Yo=n.map((Y)=>`from '${Y}`),Go=n.map((Y)=>`from "${Y}`);let H=Yo,q=Go,V=new Map;for(let Y of L){let we=se;for(let z=0;z<n.length;z++)if(Y.includes(H[z])||Y.includes(q[z])){we=z;break}V.set(Y,we)}L.sort((Y,we)=>{let z=V.get(Y),ie=V.get(we);return z!==ie?z-ie:Y.localeCompare(we)})}}for(let F=0;F<L.length;F++){if(i)i+=`
140
- `;i+=L[F]}for(let F=0;F<$.length;F++){if(i)i+=`
141
- `;i+=$[F]}let re=[a,f,c,u,l,p,h];for(let F=0;F<re.length;F++){let J=re[F];for(let X=0;X<J.length;X++){let se=J[X],H="",q=se.kind;switch(q){case"function":H=ou(se,r);break;case"variable":H=jo(se,r);break;case"interface":H=au(se,r);break;case"type":H=lu(se,r);break;case"class":H=fu(se,r);break;case"enum":H=cu(se,r);break;case"module":case"namespace":H=uu(se,r);break;case"import":case"export":case"unknown":break;default:Jo(q,`Unhandled declaration kind in processor: ${q}`)}if(H){if(i)i+=`
142
- `;i+=H}}}for(let F=0;F<O.length;F++){if(i)i+=`
143
- `;i+=O[F]}for(let F=0;F<T.length;F++){if(i)i+=`
144
- `;i+=T[F]}if(!i&&(o.length>0||w.length>0))return"export {};";return i}var eu,tu,ru,Wt,pu,Ho=null,Yo,Go;var Zo=de(()=>{Lo();rn();eu=/^\/\/\/\s*<reference\s+(?:path|types|lib|no-default-lib)\s*=\s*["'][^"']+["']\s*\/>/,tu=/^\/\/\/\s*<amd-module\s+name\s*=\s*["'][^"']+["']\s*\/>/,ru=/^\/\/\/\s*<amd-dependency\s+path\s*=\s*["'][^"']+["']/;Wt=new Map;pu=/export\s+(?:type\s+)?\{\s*([^}]+)\s*\}/,Yo=[],Go=[]});function Jt(e){return qo[e]>=qo[Xr]}function wu(){if(!$u)return"";return`[${new Date().toISOString().slice(11,23)}] `}function Cu(e,t){let r=wu();if(e||r)return[`${r}${e}`,...t];return t}function Kt(e,t,r){let n=Cu(t,r);if(Uo){Uo(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 Xo(e){return{debug:(...t)=>{if(Jt("debug"))Kt("debug",e,t)},info:(...t)=>{if(Jt("info"))Kt("info",e,t)},warn:(...t)=>{if(Jt("warn"))Kt("warn",e,t)},error:(...t)=>{if(Jt("error"))Kt("error",e,t)},setLevel:(t)=>{Xr=t},getLevel:()=>Xr,child:(t)=>{let r=e?`${e}:${t}`:`[${t}]`;return Xo(r)},time:(t)=>{let r=performance.now();return()=>{let n=performance.now()-r;if(Jt("debug"))Kt("debug",e,[`${t}: ${n.toFixed(2)}ms`])}},progress:(t)=>{if(Jt("info"))if(typeof process<"u"&&process.stdout?.isTTY)process.stdout.write(`\r${e} ${t}`);else Kt("info",e,[t])}}}function Cn(e){Xr=e}var qo,Xr="info",yu="[dtsx]",$u=!1,Uo=null,K;var zo=de(()=>{qo={debug:0,info:1,warn:2,error:3,silent:4};K=Xo(yu)});import bu from"process";import{existsSync as Qo,statSync as ea}from"fs";import{existsSync as Au,mkdirSync as yg,readdirSync as $g,readFileSync as vu,writeFileSync as wg}from"fs";import{homedir as Ht}from"os";import{dirname as Ag,resolve as ze}from"path";import Wi from"process";import{existsSync as ta,statSync as ra}from"fs";import{existsSync as jn,mkdirSync as xu,readdirSync as Eu,writeFileSync as Ou}from"fs";import{homedir as Yt}from"os";import{dirname as ia,resolve as He}from"path";import Nt from"process";import{join as ku,relative as Su,resolve as na}from"path";import yi from"process";import{existsSync as La,mkdirSync as Ng,readdirSync as Fg,writeFileSync as Pg}from"fs";import{homedir as bn}from"os";import{dirname as Ig,resolve as Ke}from"path";import wr from"process";import{join as Tu,relative as Ru,resolve as sa}from"path";import $i from"process";import{existsSync as ja,mkdirSync as Jg,readdirSync as Kg,writeFileSync as Hg}from"fs";import{dirname as Gg,resolve as wi}from"path";import _n from"process";import{Buffer as Et}from"buffer";import{createCipheriv as Wu,createDecipheriv as Nu,randomBytes as An}from"crypto";import{closeSync as vn,createReadStream as oa,createWriteStream as Fu,existsSync as xn,fsyncSync as aa,openSync as la,writeFileSync as Pu}from"fs";import{access as Du,constants as fa,mkdir as Mu,readdir as zr,rename as ca,stat as Gt,unlink as Qr,writeFile as En}from"fs/promises";import{join as Vt}from"path";import Be from"process";import{pipeline as Iu}from"stream/promises";import{createGzip as ua}from"zlib";import Zt from"process";import gt from"process";import{Buffer as ht}from"buffer";import{createCipheriv as Bu,createDecipheriv as Lu,randomBytes as On}from"crypto";import{closeSync as kn,createReadStream as ha,createWriteStream as ju,existsSync as ei,fsyncSync as da,openSync as ma,writeFileSync as _u}from"fs";import{access as Ju,constants as ga,mkdir as Ku,readdir as ti,rename as pa,stat as qt,unlink as ri,writeFile as Sn}from"fs/promises";import{isAbsolute as Hu,join as Ut,resolve as Yu}from"path";import le from"process";import{pipeline as Gu}from"stream/promises";import{createGzip as ya}from"zlib";import Xt from"process";import pt from"process";import ii from"process";import{existsSync as ni}from"fs";import{resolve as Tn}from"path";import{existsSync as Vu}from"fs";import{existsSync as Zu,readdirSync as qu}from"fs";import{extname as Rn,resolve as $a}from"path";import Uu from"process";import{join as Xu,relative as zu,resolve as wa}from"path";import Ci from"process";import{Buffer as dt}from"buffer";import{createCipheriv as Qu,createDecipheriv as eh,randomBytes as Wn}from"crypto";import{closeSync as Nn,createReadStream as Ca,createWriteStream as th,existsSync as si,fsyncSync as ba,openSync as Aa,writeFileSync as rh}from"fs";import{access as ih,constants as va,mkdir as nh,readdir as oi,rename as xa,stat as zt,unlink as ai,writeFile as Fn}from"fs/promises";import{isAbsolute as sh,join as Qt,resolve as oh}from"path";import fe from"process";import{pipeline as ah}from"stream/promises";import{createGzip as Ea}from"zlib";import er from"process";import yt from"process";import li from"process";import{existsSync as fi}from"fs";import{resolve as Pn}from"path";import{existsSync as lh}from"fs";class _a{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(!Qo(e))return!0;return ea(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=Qo(r)?ea(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 Ja{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 uh(e,t){this[e]=ch.bind(null,t)}class Qn{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(!ta(e))return!0;return ra(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=ta(r)?ra(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 es{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 mh(e,t={}){let r=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return r?`${e}:${r}`:e}function gh(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function ph(e){return e.getStats().size*2}function ts(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)=>Ai(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]=ts(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 o of r[n])if(ye(o)&&"name"in o){if(!s.find((a)=>ye(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(ye(o)&&"path"in o){if(!s.find((a)=>ye(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((a)=>Ai(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 Ai(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(!Ai(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(!Ai(e[i],t[i]))return!1}return!0}return!1}function ye(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function yh(e,t){if(!ja(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 ts(t,n)}catch{return null}}catch{return null}}async function $h({name:e="",cwd:t,defaultConfig:r}){let n=t||_n.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 f=wi(n,`${o}${a}`),c=await yh(f,r);if(c!==null)return c}try{let o=wi(n,"package.json");if(ja(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return ts(r,a)}catch{}}}catch{}return r}function wh(e,t={}){let r=$i.cwd();while(r.includes("storage"))r=sa(r,"..");let n=sa(r,e||"");if(t?.relative)return Ru($i.cwd(),n);return n}async function Ch(){try{let e=await $h({name:"clarity",defaultConfig:di,cwd:$i.cwd(),endpoint:"",headers:{}});return{...di,...e}}catch{return di}}function Ae(){if(gt.env.NODE_ENV==="test"||gt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function bh(){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 Ha{async format(e){let t=await bh(),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 vi{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={...Kn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ha,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{...mi,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...mi};return{...mi,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Kn.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 Du(this.config.logDirectory,fa.F_OK|fa.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await Mu(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Et.from(e);try{if(!xn(this.currentLogFile))await En(this.currentLogFile,"",{mode:420});if(n=la(this.currentLogFile,"a",420),Pu(n,a,{flag:"a"}),aa(n),n!==void 0)vn(n),n=void 0;if((await Gt(this.currentLogFile)).size===0){if(await En(this.currentLogFile,a,{flag:"w",mode:420}),(await Gt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let c=f;if(c.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(c.code)){if(i<s-1){let u=typeof c.message==="string"?c.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let l=o*2**i;await new Promise((p)=>setTimeout(p,l)),i++;continue}}if(c?.code&&["ENOSPC","EDQUOT"].includes(c.code))throw Error(`Disk quota exceeded or no space left on device: ${c.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",c),c}finally{if(n!==void 0)try{vn(n)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(a){if(i===s-1){let c=a,u=typeof c.message==="string"?c.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}i++;let f=o*2**(i-1);await new Promise((c)=>setTimeout(c,f))}})();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 Vt(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 Vt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Vt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Ae())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=Wu("aes-256-gcm",t,r),i=Et.concat([n.update(e,"utf8"),n.final()]),s=n.getAuthTag();return{encrypted:Et.concat([r,i,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=ua(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(Et.from(Et.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(Ae())return;let e=await Gt(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 zr(this.config.logDirectory),s=i.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,c)=>{let u=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.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 Gt(r).catch(()=>null))try{if(await ca(r,a),t.compress)try{let f=`${a}.gz`;await this.compressLogFile(a,f),await Qr(a)}catch(f){console.error("Error compressing rotated file:",f)}if(s.length===0&&!i.some((f)=>f.endsWith(".log.1")))try{let f=`${r}.1`;await En(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await Gt(r).catch(()=>null))await ca(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await zr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await Qr(Vt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=oa(e),n=Fu(t),i=ua();await Iu(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()})),xn(this.currentLogFile))try{let e=la(this.currentLogFile,"r+");aa(e),vn(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(!Ae()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await zr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Qr(Vt(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?me.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,a=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(o)h.push(t);if(s==="warning")h.push("WARN");else if(s==="error")h.push("ERROR");else if(r)h.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)h.push(n.replace(/[[\]]/g,""));return h.push(i),h.join(" ")}let f=Be.stdout.columns||120,c="";if(s==="warning"||s==="error")c=`${r} ${i}`;else if(s==="info"||s==="success")c=`${r} ${n} ${i}`;else c=`${r} ${n} ${me.cyan(i)}`;if(!o)return c.trim();let u=a(c).trim().length,l=a(t).length,p=Math.max(1,f-2-u-l);return`${c.trim()}${" ".repeat(p)}${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&&!Ae()){let c=el[e],u=this.options.showTags!==!1&&this.name?me.gray(this.formatTag(this.name)):"",l;switch(e){case"debug":l=this.formatConsoleMessage({timestamp:i,icon:c,tag:u,message:me.gray(o),level:e}),console.error(l);break;case"info":l=this.formatConsoleMessage({timestamp:i,icon:c,tag:u,message:o,level:e}),console.error(l);break;case"success":l=this.formatConsoleMessage({timestamp:i,icon:c,tag:u,message:me.green(o),level:e}),console.error(l);break;case"warning":l=this.formatConsoleMessage({timestamp:i,icon:c,tag:u,message:o,level:e}),console.warn(l);break;case"error":if(l=this.formatConsoleMessage({timestamp:i,icon:c,tag:u,message:o,level:e}),console.error(l),a){let p=a.split(`
145
- `);for(let h of p)if(h.trim()&&!h.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:me.gray(` ${h}`),level:e,showTimestamp:!1}))}break}}else if(!Ae()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),a)console.error(a)}if(!this.shouldLog(e))return;let f=`${s} ${this.environment}.${e.toUpperCase()}: ${o}
146
- `;if(a)f+=`${a}
147
- `;f=f.replace(this.ANSI_PATTERN,""),await this.writeToFile(f)}time(e){let t=performance.now();if(this.fancy&&!Ae()){let r=this.options.showTags!==!1&&this.name?me.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:me.blue("\u25D0"),tag:r,message:`${me.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),f=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)f+=` ${JSON.stringify(r)}`;if(f+=`
148
- `,f=f.replace(this.ANSI_PATTERN,""),this.fancy&&!Ae()){let c=this.options.showTags!==!1&&this.name?me.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:me.green("\u2713"),tag:c,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Ae())console.error(f.trim());await this.writeToFile(f)}}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 vi(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(Ae())throw Error("createReadStream is not supported in browser environments");if(!xn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return oa(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=Et.isBuffer(e)?e:Et.from(e,"base64"),i=n.slice(0,16),s=n.slice(-16),o=n.slice(16,-16),a=Nu("aes-256-gcm",r,i);return a.setAuthTag(s),Et.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 Ae()}isServerMode(){return!Ae()}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&&!Ae()){let s=e.split(`
149
- `),o=Math.max(...s.map((u)=>u.length))+2,a=`\u250C${"\u2500".repeat(o)}\u2510`,f=`\u2514${"\u2500".repeat(o)}\u2518`,c=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:me.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:me.cyan(a)})),c.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:me.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:me.cyan(f),showTimestamp:!1}))}else if(!Ae())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let i=`${n} ${this.environment}.INFO: [BOX] ${e}
150
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(Ae())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${me.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 f=t[s++];switch(a){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return o}}),s<t.length)r+=` ${t.slice(s).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`}if(this.fancy&&!Ae()){let i=this.options.showTags!==!1&&this.name?me.gray(this.formatTag(this.name)):"",s=me.blue("\u25D0");console.error(`${s} ${i} ${me.cyan(r)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
151
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(e,t=""){if(!this.enabled||!this.fancy||Ae()||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||Ae())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||Ae())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||Ae())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||Ae()||!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=me.green("\u2501".repeat(n)),o=me.gray("\u2501".repeat(i)),a=`[${s}${o}]`,f=`${r}%`.padStart(4),c=e.message?` ${e.message}`:"",u=t||r===100?me.green("\u2713"):me.blue("\u25B6"),l=this.options.showTags!==!1&&this.name?` ${me.gray(this.formatTag(this.name))}`:"",p=`\r${u}${l} ${a} ${f}${c}`,h=Be.stdout.columns||80,w=" ".repeat(Math.max(0,h-p.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${p}${w}`,Be.stdout.write(e.lastRenderedLine),t)Be.stdout.write(`
152
- `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ae()||!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(Ae()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await zr(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=Vt(this.config.logDirectory,n);if(e.before)try{if((await Gt(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 Qr(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 hi(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)=>xi(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]=hi(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)=>xi(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 rs(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:hi(e,t);if(Array.isArray(e))return r==="replace"?t:hi(e,t);if(!ce(t)||!ce(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]=hi(o,s);else if(ce(s)&&ce(o))n[i]=rs(o,s,r);else n[i]=s}return n}function xi(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(!xi(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(!xi(e[i],t[i]))return!1}return!0}return!1}function ce(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function ci(e,t,r="replace"){if(!La(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 rs(t,i,r)}catch{return null}}catch{return null}}function Ah(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function s(o,a=[]){let f={...o};for(let[c,u]of Object.entries(o)){let l=[...a,c],p=(A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase(),h=`${n}_${l.map(p).join("_")}`,w=`${n}_${l.map((A)=>A.toUpperCase()).join("_")}`;if(r)je.info(`Checking environment variable ${h} for config ${e}.${l.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))f[c]=s(u,l);else{let A=wr.env[h]||wr.env[w];if(A!==void 0){if(r)je.info(`Using environment variable ${A?h:w} for config ${e}.${l.join(".")}`);if(typeof u==="number")f[c]=Number(A);else if(typeof u==="boolean")f[c]=A.toLowerCase()==="true";else if(Array.isArray(u))try{let $=JSON.parse(A);if(Array.isArray($))f[c]=$;else f[c]=A.split(",").map((O)=>O.trim())}catch{f[c]=A.split(",").map(($)=>$.trim())}else f[c]=A}}}return f}return s(i)}async function vh({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:s=!1,checkEnv:o=!0,arrayStrategy:a="replace"}){let f=o&&typeof i==="object"&&i!==null&&!Array.isArray(i)?Ah(e,i,s):i,c=r||wr.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)je.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${c}`);let l=[e,`.${e}`].filter(Boolean),p=[`${e}.config`,`.${e}.config`].filter(Boolean),h=t?[t,`.${t}`]:[],w=t?[`${t}.config`,`.${t}.config`]:[],A=Array.from(new Set([c,Ke(c,"config"),Ke(c,".config"),n?Ke(c,n):void 0].filter(Boolean)));for(let $ of A){if(s)je.info(`Searching for configuration in: ${$}`);let O=[Ke(c,"config"),Ke(c,".config")].concat(n?[Ke(c,n)]:[]).includes($)?[...l,...p,...h,...w]:[...p,...l,...w,...h];for(let T of O)for(let S of u){let W=Ke($,`${T}${S}`),b=await ci(W,f,a);if(b!==null){if(s)je.success(`Configuration loaded from: ${W}`);return b}}}if(e){let $=Ke(bn(),".config",e),O=["config",`${e}.config`];if(t)O.push(`${t}.config`);if(s)je.info(`Checking user config directory: ${$}`);for(let T of O)for(let S of u){let W=Ke($,`${T}${S}`),b=await ci(W,f,a);if(b!==null){if(s)je.success(`Configuration loaded from user config directory: ${W}`);return b}}}if(e){let $=Ke(bn(),".config"),O=[`.${e}.config`];if(t)O.push(`.${t}.config`);if(s)je.info(`Checking user config directory for dotfile configs: ${$}`);for(let T of O)for(let S of u){let W=Ke($,`${T}${S}`),b=await ci(W,f,a);if(b!==null){if(s)je.success(`Configuration loaded from user config directory dotfile: ${W}`);return b}}}if(e){let $=bn(),O=[`.${e}.config`,`.${e}`];if(t)O.push(`.${t}.config`),O.push(`.${t}`);if(s)je.info(`Checking user home directory for dotfile configs: ${$}`);for(let T of O)for(let S of u){let W=Ke($,`${T}${S}`),b=await ci(W,f,a);if(b!==null){if(s)je.success(`Configuration loaded from user home directory: ${W}`);return b}}}try{let $=Ke(c,"package.json");if(La($)){let O=await import($),T=O[e];if(!T&&t){if(T=O[t],T&&s)je.success(`Using alias "${t}" configuration from package.json`)}if(T&&typeof T==="object"&&!Array.isArray(T))try{if(s)je.success(`Configuration loaded from package.json: ${T===O[e]?e:t}`);return rs(f,T,a)}catch(S){if(s)je.warn("Failed to merge package.json config:",S)}}}catch($){if(s)je.warn("Failed to load package.json:",$)}if(s)je.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return f}function xh(e,t={}){let r=yi.cwd();while(r.includes("storage"))r=na(r,"..");let n=na(r,e||"");if(t?.relative)return Su(yi.cwd(),n);return n}async function Eh(){try{let e=await vh({name:"clarity",alias:"logging",defaultConfig:gi,cwd:yi.cwd()});return{...gi,...e||{}}}catch{return gi}}function We(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Oh(){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 Ya{async format(e){let t=await Oh(),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:Xt.pid,hostname:t(),environment:Xt.env.NODE_ENV||"development",platform:Xt.platform,version:Xt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Xt.env.NODE_ENV||Xt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ei{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={...Hn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ya,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??le.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{...pi,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...pi};return{...pi,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Hn.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!We()&&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 Ju(this.config.logDirectory,ga.F_OK|ga.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await Ku(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ht.from(e);try{if(!ei(this.currentLogFile))await Sn(this.currentLogFile,"",{mode:420});if(n=ma(this.currentLogFile,"a",420),_u(n,a,{flag:"a"}),da(n),n!==void 0)kn(n),n=void 0;if((await qt(this.currentLogFile)).size===0){if(await Sn(this.currentLogFile,a,{flag:"w",mode:420}),(await qt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let c=f;if(c.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(c.code)){if(i<s-1){let u=typeof c.message==="string"?c.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let l=o*2**i;await new Promise((p)=>setTimeout(p,l)),i++;continue}}if(c?.code&&["ENOSPC","EDQUOT"].includes(c.code))throw Error(`Disk quota exceeded or no space left on device: ${c.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",c),c}finally{if(n!==void 0)try{kn(n)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(a){if(i===s-1){let c=a,u=typeof c.message==="string"?c.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}i++;let f=o*2**(i-1);await new Promise((c)=>setTimeout(c,f))}})();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 Ut(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 Ut(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Ut(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(We())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 On(16).toString("hex")}generateKey(){return On(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=On(16),n=Bu("aes-256-gcm",t,r),i=ht.isBuffer(e)?e:ht.from(e,"utf8"),s=n.update(i),o=n.final(),a=s.length+o.length,f=n.getAuthTag(),c=ht.allocUnsafe(16+a+16);return r.copy(c,0),s.copy(c,16),o.copy(c,16+s.length),f.copy(c,16+a),{encrypted:c,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=ya(),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(We())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 ti(this.config.logDirectory),s=i.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,c)=>{let u=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.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 qt(r).catch(()=>null))try{if(await pa(r,a),t.compress)try{let f=`${a}.gz`;await this.compressLogFile(a,f),await ri(a)}catch(f){console.error("Error compressing rotated file:",f)}if(s.length===0&&!i.some((f)=>f.endsWith(".log.1")))try{let f=`${r}.1`;await Sn(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await qt(r).catch(()=>null))await pa(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await ti(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await ri(Ut(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=ha(e),n=ju(t),i=ya();await Gu(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()})),ei(this.currentLogFile))try{let e=ma(this.currentLogFile,"r+");da(e),kn(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(!We()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await ti(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await ri(Ut(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||We())return!1;let e=typeof le.env.NO_COLOR<"u",t=le.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof le.stderr<"u"&&le.stderr.isTTY||typeof le.stdout<"u"&&le.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,a=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(o)h.push(t);if(s==="warning")h.push("WARN");else if(s==="error")h.push("ERROR");else if(r)h.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)h.push(n.replace(/[[\]]/g,""));return h.push(i),h.join(" ")}let f=le.stdout.columns||120,c="";if(s==="warning"||s==="error")c=`${r} ${i}`;else if(s==="info"||s==="success")c=`${r} ${n} ${i}`;else c=`${r} ${n} ${ee.cyan(i)}`;if(!o)return c.trim();let u=a(c).trim().length,l=a(t).length,p=Math.max(1,f-2-u-l);return`${c.trim()}${" ".repeat(p)}${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=ee.underline(ee.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(o)}`,f="\x1B]8;;",c="\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)=>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(We())return!1;let e=le.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=le.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Hu(t)||t.startsWith("./")||t.startsWith("../"))t=Yu(t);else return null;return ei(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:f,fileText:c}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let l=this.options.showIcons===!1?"":tl[e],p=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"",h;switch(e){case"debug":h=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:ee.gray(f),level:e}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:f,level:e}),console.warn(h);break;case"success":h=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:ee.green(f),level:e}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:f,level:e}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:f,level:e}),console.error(h),a){let w=a.split(`
153
- `);for(let A of w)if(A.trim()&&!A.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:ee.gray(` ${A}`),level:e,showTimestamp:!1}))}break}}else if(!We()){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()}: ${c}
154
- `;if(a)u+=`${a}
155
- `;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()&&!We()&&le.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()&&!We()&&le.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,s="info")=>{if(!We()&&le.stdout.isTTY)le.stdout.write(`
156
- `);if(this[s==="warning"?"warn":s](i),this.activeProgressBar&&this.shouldStyleConsole()&&!We()&&le.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":ee.blue("\u25D0"),tag:r,message:`${ee.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),f=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)f+=` ${JSON.stringify(r)}`;if(f+=`
157
- `,f=f.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":ee.green("\u2713"),tag:c,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!We())console.error(f.trim());if(this.shouldWriteToFile())await this.writeToFile(f)}}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 Ei(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(We())throw Error("createReadStream is not supported in browser environments");if(!ei(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ha(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=ht.isBuffer(e)?e:ht.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),a=Lu("aes-256-gcm",r,i);a.setAuthTag(s);let f=a.update(o),c=a.final(),u=f.length+c.length,l=ht.allocUnsafe(u);return f.copy(l,0),c.copy(l,f.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 We()}isServerMode(){return!We()}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(`
158
- `),f=Math.max(...a.map((p)=>p.length))+2,c=`\u250C${"\u2500".repeat(f)}\u2510`,u=`\u2514${"\u2500".repeat(f)}\u2518`,l=a.map((p)=>{return this.formatConsoleMessage({timestamp:r,message:ee.cyan(p),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:ee.cyan(c),showTimestamp:!1})),l.forEach((p)=>console.error(p)),console.error(this.formatConsoleMessage({timestamp:r,message:ee.cyan(u),showTimestamp:!1}))}else if(!We())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
159
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(We())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${ee.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();le.stdin.removeListener("data",r);try{if(typeof le.stdin.setRawMode==="function")le.stdin.setRawMode(!1)}catch{}le.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof le.stdin.setRawMode==="function")le.stdin.setRawMode(!0)}catch{}le.stdin.resume(),le.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,(f,c)=>{if(c==="%")return"%";if(a>=t.length)return f;let u=t[a++];switch(c){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 f}}),a<t.length)r+=` ${t.slice(a).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${ee.blue("\u25D0")} `;console.error(`${a}${o} ${ee.cyan(n)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
160
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!le.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=ee.green("\u2501".repeat(n)),o=ee.gray("\u2501".repeat(i)),a=`[${s}${o}]`,f=`${r}%`.padStart(4),c=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?ee.green("\u2713"):ee.blue("\u25B6"),l=this.options.showTags!==!1&&this.name?` ${ee.gray(this.formatTag(this.name))}`:"",p=`\r${u}${l} ${a} ${f}${c}`,h=le.stdout.columns||80,w=" ".repeat(Math.max(0,h-p.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${p}${w}`,le.stdout.write(e.lastRenderedLine),t)le.stdout.write(`
161
- `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||We()||!le.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(We()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await ti(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=Ut(this.config.logDirectory,n);if(e.before)try{if((await qt(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 ri(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 Ga(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(f){if(o=f instanceof Error?f:Error(String(f)),a===r||!i(o))break;if(n>0)await new Promise((c)=>setTimeout(c,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function Va(e){return e instanceof Ve}function kh(e){return e instanceof Oi}function Sh(e){if(Va(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 Ni{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:f=!0}=r,c=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(f)return Ar.track("applyEnvironmentVariables",c,{configName:e});return c()}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)),f=`${r}_${a.join("_")}`,c=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=ii.env[f]||(c?ii.env[c]:void 0);if(u!==void 0){if(n.verbose){let l=ii.env[f]?f:c}try{e[i]=this.parseEnvironmentValue(u,typeof s,f,n.customParsers,n.configName)}catch(l){if(l instanceof ki)throw l;throw Ot.envVar(f,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 Ot.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(ii.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((f)=>this.formatEnvKey(f,!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}:
136
+ ${n}`}if(o)return`${fu(o)}${n}`;return r+n}function du(e,t=!0){let r=ut(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=uu(e.text);if(s!==-1)i+=` ${e.text.slice(s)}`;else i+=" {}";return r+i}function mu(e,t=!0){let r=ut(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 a=e.text.slice(i),o=a.length;while(o>0&&(a.charCodeAt(o-1)===59||a.charCodeAt(o-1)===32||a.charCodeAt(o-1)===10||a.charCodeAt(o-1)===13))o--;if(o<a.length)a=a.slice(0,o);n+=a}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 pu(e,t=!0){return ut(e.leadingComments,t)+e.text}function gu(e,t=!0){let r=ut(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 yu(e,t=!0){let r=ut(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 a=e.text.indexOf("{");if(a!==-1)s+=` ${e.text.slice(a)}`;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 Cu(e){let t=kt.get(e);if(t)return kt.delete(e),kt.set(e,t),t;return null}function Ba(e,t){if(kt.set(e,t),kt.size>200){let r=0;for(let n of kt.keys()){if(r++>=20)break;kt.delete(n)}}}function wu(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),a=e.slice(0,t).trim(),o=a.startsWith("import type ");if(a.startsWith("import "))a=a.slice(7).trim();if(a.startsWith("type "))a=a.slice(5).trim();let c=null,f=[],u=!1,l=a.indexOf("{"),g=a.lastIndexOf("}");if(l!==-1&&g!==-1){let h=a.slice(0,l).trim();if(h.endsWith(","))c=h.slice(0,-1).trim()||null;let w=a.slice(l+1,g),v=0;for(let C=0;C<=w.length;C++)if(C===w.length||w.charCodeAt(C)===44){let x=v,O=C;while(x<O&&(w.charCodeAt(x)===32||w.charCodeAt(x)===9||w.charCodeAt(x)===10))x++;while(O>x&&(w.charCodeAt(O-1)===32||w.charCodeAt(O-1)===9||w.charCodeAt(O-1)===10))O--;if(x<O)f.push(w.slice(x,O));v=C+1}}else{let h=a.trim();if(h.startsWith("* as "))c=h.slice(5).trim()||null,u=!0;else c=h||null}return{defaultName:c,namedItems:f,source:s,isTypeOnly:o,isNamespace:u}}function $u(e){let t=Cu(e);if(t)return t;let r=[],n=e.indexOf(" from ");if(n===-1)return Ba(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("{"),a=i.lastIndexOf("}");if(s!==-1&&a!==-1){let o=i.slice(0,s).trim();if(o.endsWith(",")){let f=o.slice(0,-1).trim();if(f)r.push(f)}else if(o&&!o.includes(","))r.push(o);let c=i.slice(s+1,a).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 o=i.trim();if(o.startsWith("* as ")){let c=o.slice(5).trim();if(c)r.push(c)}else if(o)r.push(o)}return Ba(e,r),r}function Va(e,t){throw Error(t||`Unexpected value: ${e}`)}function Eu(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===95||e===36||e>127}function _a(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&&Eu(e.charCodeAt(r)))r++;t.add(e.substring(s,r))}else r++}return t}function Ja(e,t,r=!0,n=["bun"]){let i="",s=t.sourceCode;if(s){let I=0;while(I<s.length&&(s.charCodeAt(I)===32||s.charCodeAt(I)===9||s.charCodeAt(I)===10||s.charCodeAt(I)===13))I++;if(I<s.length-2&&s.charCodeAt(I)===47&&s.charCodeAt(I+1)===47&&s.charCodeAt(I+2)===47){let _=cu(s);if(_.length>0)for(let X=0;X<_.length;X++){if(i)i+=`
137
+ `;i+=_[X]}}}let a=[],o=[],c=[],f=[],u=[],l=[],g=[],h=[],w=[];for(let I of e){let _=I.kind;switch(_){case"import":a.push(I);break;case"function":o.push(I);break;case"variable":c.push(I);break;case"interface":f.push(I);break;case"type":u.push(I);break;case"class":l.push(I);break;case"enum":g.push(I);break;case"module":h.push(I);break;case"export":w.push(I);break;case"namespace":h.push(I);break;case"unknown":break;default:Va(_,`Unhandled declaration kind: ${_}`)}}let v=new Set,C=[],x=[],O=[],R=new Set;for(let I of w){let _=ut(I.leadingComments,r);if(I.text.startsWith("export default")){let X=I.text.endsWith(";")?I.text:`${I.text};`;O.push(_+X)}else{let X=I.text.trim();if(!X.endsWith(";"))X+=";";let se=X.match(vu);if(se){let Z=se[1],U=0;for(let K=0;K<=Z.length;K++)if(K===Z.length||Z.charCodeAt(K)===44){let we=U,z=K;while(we<z&&Z.charCodeAt(we)<=32)we++;while(z>we&&Z.charCodeAt(z-1)<=32)z--;if(we<z)v.add(Z.slice(we,z));U=K+1}}let j=_+X;if(!R.has(j))if(R.add(j),j.includes("export type"))C.push(j);else x.push(j)}}let k=new Map;if(a.length>0)for(let I of a){let _=$u(I.text);for(let X of _)k.set(X,I)}let E=new Set;if(f.length>0){let I=[];for(let _ of o)if(_.isExported)I.push(_.text);for(let _ of l)I.push(_.text);for(let _ of u)I.push(_.text);if(I.length>0){let _=_a(I.join(`
138
+ `));for(let X of f)if(_.has(X.name))E.add(X.name)}}let G=[];if(a.length>0){let I=new Set,_=[];for(let j of o)if(j.isExported)_.push(j.text);for(let j of c)if(_.push(j.text),j.typeAnnotation)_.push(j.typeAnnotation);else if(j.isExported&&j.value)_.push(Ga(j,!1));for(let j of f)if(j.isExported||E.has(j.name))_.push(j.text);for(let j of u)_.push(j.text);for(let j of l)_.push(j.text);for(let j of g)_.push(j.text);for(let j of h)_.push(j.text);for(let j of w)_.push(j.text);let X=_.join(`
139
+ `);if(X&&k.size>0){let j=_a(X);for(let Z of k.keys())if(j.has(Z))I.add(Z)}for(let j of v)if(k.has(j))I.add(j);for(let j of a){if(j.isSideEffect){let Fe=j.text.trim(),be=Fe.endsWith(";")?Fe:`${Fe};`;G.push(be);continue}let Z=wu(j.text);if(!Z)continue;let{defaultName:U,namedItems:K,source:we,isTypeOnly:z,isNamespace:ie}=Z,Tr=U?I.has(U):!1,Tt="",wt=0;for(let Fe=0;Fe<K.length;Fe++){let be=K[Fe],It=be.charCodeAt(0)===116&&be.startsWith("type ")?be.slice(5).trim():be.trim(),Dt=It.indexOf(" as ");if(Dt!==-1)It=It.slice(Dt+4).trim();if(I.has(It)){if(wt>0)Tt+=", ";Tt+=be,wt++}}if(Tr||wt>0){let Fe=z?"import type ":"import ";if(Tr&&U)if(ie)Fe+=`* as ${U}`;else Fe+=wt>0?`${U}, { ${Tt} }`:U;else if(wt>0)Fe+=`{ ${Tt} }`;Fe+=` from '${we}';`,G.push(Fe)}}let se=n.length;if(G.length>1){if(Ha!==n)Ha=n,ja=n.map((K)=>`from '${K}`),Ka=n.map((K)=>`from "${K}`);let j=ja,Z=Ka,U=new Map;for(let K of G){let we=se;for(let z=0;z<n.length;z++)if(K.includes(j[z])||K.includes(Z[z])){we=z;break}U.set(K,we)}G.sort((K,we)=>{let z=U.get(K),ie=U.get(we);return z!==ie?z-ie:K.localeCompare(we)})}}for(let I=0;I<G.length;I++){if(i)i+=`
140
+ `;i+=G[I]}for(let I=0;I<C.length;I++){if(i)i+=`
141
+ `;i+=C[I]}let re=[o,c,f,u,l,g,h];for(let I=0;I<re.length;I++){let _=re[I];for(let X=0;X<_.length;X++){let se=_[X],j="",Z=se.kind;switch(Z){case"function":j=hu(se,r);break;case"variable":j=Ga(se,r);break;case"interface":j=du(se,r);break;case"type":j=mu(se,r);break;case"class":j=pu(se,r);break;case"enum":j=gu(se,r);break;case"module":case"namespace":j=yu(se,r);break;case"import":case"export":case"unknown":break;default:Va(Z,`Unhandled declaration kind in processor: ${Z}`)}if(j){if(i)i+=`
142
+ `;i+=j}}}for(let I=0;I<x.length;I++){if(i)i+=`
143
+ `;i+=x[I]}for(let I=0;I<O.length;I++){if(i)i+=`
144
+ `;i+=O[I]}if(!i&&(a.length>0||w.length>0))return"export {};";return i}var au,ou,lu,kt,vu,Ha=null,ja,Ka;var Ua=ae(()=>{Wa();rn();au=/^\/\/\/\s*<reference\s+(?:path|types|lib|no-default-lib)\s*=\s*["'][^"']+["']\s*\/>/,ou=/^\/\/\/\s*<amd-module\s+name\s*=\s*["'][^"']+["']\s*\/>/,lu=/^\/\/\/\s*<amd-dependency\s+path\s*=\s*["'][^"']+["']/;kt=new Map;vu=/export\s+(?:type\s+)?\{\s*([^}]+)\s*\}/,ja=[],Ka=[]});var Ya;var Za=ae(()=>{Ya=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 qa(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(`
145
+ `,n),o=a===-1?e.length:a;r+=" ".repeat(o-n),n=o;continue}if(i==="/*"){let a=e.indexOf("*/",n+2),o=a===-1?e.length:a+2;for(let c=n;c<o;c++)r+=e[c]===`
146
+ `?`
147
+ `:" ";n=o;continue}let s=e[n];if(t.strings&&(s==='"'||s==="'"||s==="`")){let a=s;r+=" ",n++;while(n<e.length){if(e[n]==="\\"){r+=" ",n+=2;continue}if(e[n]===a){r+=" ",n++;break}r+=e[n]===`
148
+ `?`
149
+ `:" ",n++}continue}r+=s,n++}return r}function Su(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 Au(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 o of s.split(",")){let c=o.trim();if(/^[A-Za-z_$][\w$]*$/.test(c))t.add(c)}let a=/\{([\s\S]*?)\}/.exec(n);if(a)for(let o of a[1].split(",")){let c=o.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 xu(e){let t=new Set,r=(i)=>{for(let s of i.split(",")){let a=s.trim().split(/\s+|=/)[0]?.trim();if(a&&/^[A-Za-z_$][\w$]*$/.test(a))t.add(a)}},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 Tu(e){let t=new Map,r=(i)=>{let s=1;for(let a=0;a<i&&a<e.length;a++)if(e.charCodeAt(a)===10)s++;return s},n=(i,s,a)=>{for(let o of i.matchAll(/\b([A-Z][\w$]*)\b/g)){let c=o[1];if(t.has(c))continue;let f=i.slice(o.index+c.length);if(/^\s*\??:/.test(f))continue;t.set(c,{line:r(s),context:a.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 Xa(e){let t=qa(e),r=qa(e,{strings:!1}),n=new Set([...Su(t),...Au(r),...xu(t),...Ya,...bu]),i=[];for(let[s,a]of Tu(t)){if(n.has(s))continue;if(new RegExp(`[\\w$]\\s*\\.\\s*${s}\\b`).test(t))continue;i.push({name:s,line:a.line,context:a.context})}return i.sort((s,a)=>s.line-a.line||s.name.localeCompare(a.name))}var bu;var za=ae(()=>{Za();bu=new Set(["This","True","False","Null","Undefined","Void","Never","Any","Unknown","Object","Infinity","NaN"])});function _t(e){return Qa[e]>=Qa[Xr]}function Pu(){if(!Ou)return"";return`[${new Date().toISOString().slice(11,23)}] `}function ku(e,t){let r=Pu();if(e||r)return[`${r}${e}`,...t];return t}function Ht(e,t,r){let n=ku(t,r);if(eo){eo(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 to(e){return{debug:(...t)=>{if(_t("debug"))Ht("debug",e,t)},info:(...t)=>{if(_t("info"))Ht("info",e,t)},warn:(...t)=>{if(_t("warn"))Ht("warn",e,t)},error:(...t)=>{if(_t("error"))Ht("error",e,t)},setLevel:(t)=>{Xr=t},getLevel:()=>Xr,child:(t)=>{let r=e?`${e}:${t}`:`[${t}]`;return to(r)},time:(t)=>{let r=performance.now();return()=>{let n=performance.now()-r;if(_t("debug"))Ht("debug",e,[`${t}: ${n.toFixed(2)}ms`])}},progress:(t)=>{if(_t("info"))if(typeof process<"u"&&process.stdout?.isTTY)process.stdout.write(`\r${e} ${t}`);else Ht("info",e,[t])}}}function $n(e){Xr=e}var Qa,Xr="info",Ru="[dtsx]",Ou=!1,eo=null,H;var ro=ae(()=>{Qa={debug:0,info:1,warn:2,error:3,silent:4};H=to(Ru)});import Mu from"process";import{existsSync as io,statSync as no}from"fs";import{existsSync as Iu,mkdirSync as kp,readdirSync as Mp,readFileSync as Du,writeFileSync as Ip}from"fs";import{homedir as jt}from"os";import{dirname as Np,resolve as Qe}from"path";import ki from"process";import{existsSync as so,statSync as ao}from"fs";import{existsSync as Bn,mkdirSync as Fu,readdirSync as Nu,writeFileSync as Lu}from"fs";import{homedir as Kt}from"os";import{dirname as oo,resolve as je}from"path";import Mt from"process";import{join as Wu,relative as Gu,resolve as lo}from"path";import yi from"process";import{existsSync as jo,mkdirSync as Jp,readdirSync as Up,writeFileSync as Yp}from"fs";import{homedir as En}from"os";import{dirname as Xp,resolve as He}from"path";import wr from"process";import{join as Bu,relative as Vu,resolve as co}from"path";import Ci from"process";import{existsSync as Ko,mkdirSync as rg,readdirSync as ig,writeFileSync as ng}from"fs";import{dirname as ag,resolve as wi}from"path";import Vn from"process";import{Buffer as At}from"buffer";import{createCipheriv as _u,createDecipheriv as Hu,randomBytes as vn}from"crypto";import{closeSync as bn,createReadStream as fo,createWriteStream as ju,existsSync as Sn,fsyncSync as uo,openSync as ho,writeFileSync as Ku}from"fs";import{access as Ju,constants as mo,mkdir as Uu,readdir as zr,rename as po,stat as Jt,unlink as Qr,writeFile as An}from"fs/promises";import{join as Ut}from"path";import We from"process";import{pipeline as Yu}from"stream/promises";import{createGzip as go}from"zlib";import Yt from"process";import pt from"process";import{Buffer as ht}from"buffer";import{createCipheriv as Zu,createDecipheriv as qu,randomBytes as xn}from"crypto";import{closeSync as Tn,createReadStream as yo,createWriteStream as Xu,existsSync as ei,fsyncSync as Co,openSync as wo,writeFileSync as zu}from"fs";import{access as Qu,constants as $o,mkdir as eh,readdir as ti,rename as Eo,stat as Zt,unlink as ri,writeFile as Rn}from"fs/promises";import{isAbsolute as th,join as qt,resolve as rh}from"path";import ce from"process";import{pipeline as ih}from"stream/promises";import{createGzip as vo}from"zlib";import Xt from"process";import gt from"process";import ii from"process";import{existsSync as ni}from"fs";import{resolve as On}from"path";import{existsSync as nh}from"fs";import{existsSync as sh,readdirSync as ah}from"fs";import{extname as Pn,resolve as bo}from"path";import oh from"process";import{join as lh,relative as ch,resolve as So}from"path";import $i from"process";import{Buffer as dt}from"buffer";import{createCipheriv as fh,createDecipheriv as uh,randomBytes as kn}from"crypto";import{closeSync as Mn,createReadStream as Ao,createWriteStream as hh,existsSync as si,fsyncSync as xo,openSync as To,writeFileSync as dh}from"fs";import{access as mh,constants as Ro,mkdir as ph,readdir as ai,rename as Oo,stat as zt,unlink as oi,writeFile as In}from"fs/promises";import{isAbsolute as gh,join as Qt,resolve as yh}from"path";import fe from"process";import{pipeline as Ch}from"stream/promises";import{createGzip as Po}from"zlib";import er from"process";import yt from"process";import li from"process";import{existsSync as ci}from"fs";import{resolve as Dn}from"path";import{existsSync as wh}from"fs";class Jo{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(!io(e))return!0;return no(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=io(r)?no(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 Uo{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 vh(e,t){this[e]=Eh.bind(null,t)}class Qn{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(!so(e))return!0;return ao(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=so(r)?ao(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 es{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 Ah(e,t={}){let r=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return r?`${e}:${r}`:e}function xh(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Th(e){return e.getStats().size*2}function ts(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)=>vi(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]=ts(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)=>vi(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 vi(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(!vi(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(!vi(e[i],t[i]))return!1}return!0}return!1}function ye(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Rh(e,t){if(!Ko(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 ts(t,n)}catch{return null}}catch{return null}}async function Oh({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 a of s)for(let o of i){let c=wi(n,`${a}${o}`),f=await Rh(c,r);if(f!==null)return f}try{let a=wi(n,"package.json");if(Ko(a)){let o=(await import(a))[e];if(o&&typeof o==="object"&&!Array.isArray(o))try{return ts(r,o)}catch{}}}catch{}return r}function Ph(e,t={}){let r=Ci.cwd();while(r.includes("storage"))r=co(r,"..");let n=co(r,e||"");if(t?.relative)return Vu(Ci.cwd(),n);return n}async function kh(){try{let e=await Oh({name:"clarity",defaultConfig:di,cwd:Ci.cwd(),endpoint:"",headers:{}});return{...di,...e}}catch{return di}}function ve(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Mh(){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 Zo{async format(e){let t=await Mh(),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:Yt.pid,hostname:t(),environment:Yt.env.NODE_ENV||"development",platform:Yt.platform,version:Yt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Yt.env.NODE_ENV||Yt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class bi{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={...Hn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Zo,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??We.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{...mi,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...mi};return{...mi,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Hn.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 Ju(this.config.logDirectory,mo.F_OK|mo.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Uu(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(!Sn(this.currentLogFile))await An(this.currentLogFile,"",{mode:420});if(n=ho(this.currentLogFile,"a",420),Ku(n,o,{flag:"a"}),uo(n),n!==void 0)bn(n),n=void 0;if((await Jt(this.currentLogFile)).size===0){if(await An(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{bn(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 Ut(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 Ut(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Ut(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(ve())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 vn(16).toString("hex")}generateKey(){return vn(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=vn(16),n=_u("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=go(),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(ve())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 zr(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 po(r,o),t.compress)try{let c=`${o}.gz`;await this.compressLogFile(o,c),await Qr(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 An(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 po(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await zr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of i.slice(t.maxFiles))await Qr(Ut(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=fo(e),n=ju(t),i=go();await Yu(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=ho(this.currentLogFile,"r+");uo(e),bn(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(!ve()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await zr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Qr(Ut(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?me.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:a=!0}=e,o=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(a)h.push(t);if(s==="warning")h.push("WARN");else if(s==="error")h.push("ERROR");else if(r)h.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)h.push(n.replace(/[[\]]/g,""));return h.push(i),h.join(" ")}let c=We.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} ${me.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&&!ve()){let f=sl[e],u=this.options.showTags!==!1&&this.name?me.gray(this.formatTag(this.name)):"",l;switch(e){case"debug":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:me.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:me.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(`
150
+ `);for(let h of g)if(h.trim()&&!h.includes(a))console.error(this.formatConsoleMessage({timestamp:i,message:me.gray(` ${h}`),level:e,showTimestamp:!1}))}break}}else if(!ve()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${a}`),o)console.error(o)}if(!this.shouldLog(e))return;let c=`${s} ${this.environment}.${e.toUpperCase()}: ${a}
151
+ `;if(o)c+=`${o}
152
+ `;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(e){let t=performance.now();if(this.fancy&&!ve()){let r=this.options.showTags!==!1&&this.name?me.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:me.blue("\u25D0"),tag:r,message:`${me.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,a=new Date,o=this.formatConsoleTimestamp(a),c=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
153
+ `,c=c.replace(this.ANSI_PATTERN,""),this.fancy&&!ve()){let f=this.options.showTags!==!1&&this.name?me.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:o,icon:me.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ve())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 bi(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(ve())throw Error("createReadStream is not supported in browser environments");if(!Sn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return fo(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=At.isBuffer(e)?e:At.from(e,"base64"),i=n.slice(0,16),s=n.slice(-16),a=n.slice(16,-16),o=Hu("aes-256-gcm",r,i);return o.setAuthTag(s),At.concat([o.update(a),o.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 ve()}isServerMode(){return!ve()}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&&!ve()){let s=e.split(`
154
+ `),a=Math.max(...s.map((u)=>u.length))+2,o=`\u250C${"\u2500".repeat(a)}\u2510`,c=`\u2514${"\u2500".repeat(a)}\u2518`,f=s.map((u)=>{let l=" ".repeat(a-u.length-2);return`\u2502 ${u}${l} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:me.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:me.cyan(o)})),f.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:me.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:me.cyan(c),showTimestamp:!1}))}else if(!ve())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let i=`${n} ${this.environment}.INFO: [BOX] ${e}
155
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(ve())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${me.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();We.stdin.removeListener("data",r);try{if(typeof We.stdin.setRawMode==="function")We.stdin.setRawMode(!1)}catch{}We.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof We.stdin.setRawMode==="function")We.stdin.setRawMode(!0)}catch{}We.stdin.resume(),We.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,(a,o)=>{if(o==="%")return"%";if(s>=t.length)return a;let c=t[s++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return a}}),s<t.length)r+=` ${t.slice(s).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}if(this.fancy&&!ve()){let i=this.options.showTags!==!1&&this.name?me.gray(this.formatTag(this.name)):"",s=me.blue("\u25D0");console.error(`${s} ${i} ${me.cyan(r)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
156
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(e,t=""){if(!this.enabled||!this.fancy||ve()||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||ve())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||ve())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||ve())return;We.stdout.write(`${"\r".padEnd(We.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||ve()||!We.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=me.green("\u2501".repeat(n)),a=me.gray("\u2501".repeat(i)),o=`[${s}${a}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=t||r===100?me.green("\u2713"):me.blue("\u25B6"),l=this.options.showTags!==!1&&this.name?` ${me.gray(this.formatTag(this.name))}`:"",g=`\r${u}${l} ${o} ${c}${f}`,h=We.stdout.columns||80,w=" ".repeat(Math.max(0,h-g.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${g}${w}`,We.stdout.write(e.lastRenderedLine),t)We.stdout.write(`
157
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||ve()||!We.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(ve()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await zr(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=Ut(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 Qr(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 hi(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)=>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(!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]=hi(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)=>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 rs(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:hi(e,t);if(Array.isArray(e))return r==="replace"?t:hi(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]=hi(a,s);else if(ue(s)&&ue(a))n[i]=rs(a,s,r);else n[i]=s}return n}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(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(!Si(e[i],t[i]))return!1}return!0}return!1}function ue(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function fi(e,t,r="replace"){if(!jo(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 rs(t,i,r)}catch{return null}}catch{return null}}function Ih(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(),h=`${n}_${l.map(g).join("_")}`,w=`${n}_${l.map((v)=>v.toUpperCase()).join("_")}`;if(r)Be.info(`Checking environment variable ${h} for config ${e}.${l.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))c[f]=s(u,l);else{let v=wr.env[h]||wr.env[w];if(v!==void 0){if(r)Be.info(`Using environment variable ${v?h:w} 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 Dh({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)?Ih(e,i,s):i,f=r||wr.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)Be.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${f}`);let l=[e,`.${e}`].filter(Boolean),g=[`${e}.config`,`.${e}.config`].filter(Boolean),h=t?[t,`.${t}`]:[],w=t?[`${t}.config`,`.${t}.config`]:[],v=Array.from(new Set([f,He(f,"config"),He(f,".config"),n?He(f,n):void 0].filter(Boolean)));for(let C of v){if(s)Be.info(`Searching for configuration in: ${C}`);let x=[He(f,"config"),He(f,".config")].concat(n?[He(f,n)]:[]).includes(C)?[...l,...g,...h,...w]:[...g,...l,...w,...h];for(let O of x)for(let R of u){let k=He(C,`${O}${R}`),E=await fi(k,c,o);if(E!==null){if(s)Be.success(`Configuration loaded from: ${k}`);return E}}}if(e){let C=He(En(),".config",e),x=["config",`${e}.config`];if(t)x.push(`${t}.config`);if(s)Be.info(`Checking user config directory: ${C}`);for(let O of x)for(let R of u){let k=He(C,`${O}${R}`),E=await fi(k,c,o);if(E!==null){if(s)Be.success(`Configuration loaded from user config directory: ${k}`);return E}}}if(e){let C=He(En(),".config"),x=[`.${e}.config`];if(t)x.push(`.${t}.config`);if(s)Be.info(`Checking user config directory for dotfile configs: ${C}`);for(let O of x)for(let R of u){let k=He(C,`${O}${R}`),E=await fi(k,c,o);if(E!==null){if(s)Be.success(`Configuration loaded from user config directory dotfile: ${k}`);return E}}}if(e){let C=En(),x=[`.${e}.config`,`.${e}`];if(t)x.push(`.${t}.config`),x.push(`.${t}`);if(s)Be.info(`Checking user home directory for dotfile configs: ${C}`);for(let O of x)for(let R of u){let k=He(C,`${O}${R}`),E=await fi(k,c,o);if(E!==null){if(s)Be.success(`Configuration loaded from user home directory: ${k}`);return E}}}try{let C=He(f,"package.json");if(jo(C)){let x=await import(C),O=x[e];if(!O&&t){if(O=x[t],O&&s)Be.success(`Using alias "${t}" configuration from package.json`)}if(O&&typeof O==="object"&&!Array.isArray(O))try{if(s)Be.success(`Configuration loaded from package.json: ${O===x[e]?e:t}`);return rs(c,O,o)}catch(R){if(s)Be.warn("Failed to merge package.json config:",R)}}}catch(C){if(s)Be.warn("Failed to load package.json:",C)}if(s)Be.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function Fh(e,t={}){let r=yi.cwd();while(r.includes("storage"))r=lo(r,"..");let n=lo(r,e||"");if(t?.relative)return Gu(yi.cwd(),n);return n}async function Nh(){try{let e=await Dh({name:"clarity",alias:"logging",defaultConfig:pi,cwd:yi.cwd()});return{...pi,...e||{}}}catch{return pi}}function ke(){if(gt.env.NODE_ENV==="test"||gt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Lh(){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 qo{async format(e){let t=await Lh(),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:Xt.pid,hostname:t(),environment:Xt.env.NODE_ENV||"development",platform:Xt.platform,version:Xt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Xt.env.NODE_ENV||Xt.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;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={...jn},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??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{...gi,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...gi};return{...gi,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:jn.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!ke()&&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 Qu(this.config.logDirectory,$o.F_OK|$o.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await eh(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(!ei(this.currentLogFile))await Rn(this.currentLogFile,"",{mode:420});if(n=wo(this.currentLogFile,"a",420),zu(n,o,{flag:"a"}),Co(n),n!==void 0)Tn(n),n=void 0;if((await Zt(this.currentLogFile)).size===0){if(await Rn(this.currentLogFile,o,{flag:"w",mode:420}),(await Zt(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{Tn(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 qt(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 qt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return qt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(ke())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 xn(16).toString("hex")}generateKey(){return xn(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=xn(16),n=Zu("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=vo(),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(ke())return;if(!this.shouldWriteToFile())return;let e=await Zt(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 ti(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 Zt(r).catch(()=>null))try{if(await Eo(r,o),t.compress)try{let c=`${o}.gz`;await this.compressLogFile(o,c),await ri(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 Rn(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 Zt(r).catch(()=>null))await Eo(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await ti(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of i.slice(t.maxFiles))await ri(qt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=yo(e),n=Xu(t),i=vo();await ih(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()})),ei(this.currentLogFile))try{let e=wo(this.currentLogFile,"r+");Co(e),Tn(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(!ke()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await ti(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await ri(qt(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||ke())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=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(a)h.push(t);if(s==="warning")h.push("WARN");else if(s==="error")h.push("ERROR");else if(r)h.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)h.push(n.replace(/[[\]]/g,""));return h.push(i),h.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(ke())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(th(t)||t.startsWith("./")||t.startsWith("../"))t=rh(t);else return null;return ei(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?"":al[e],g=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"",h;switch(e){case"debug":h=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:ee.gray(c),level:e}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.warn(h);break;case"success":h=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:ee.green(c),level:e}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.error(h),o){let w=o.split(`
158
+ `);for(let v of w)if(v.trim()&&!v.includes(a))console.error(this.formatConsoleMessage({timestamp:i,message:ee.gray(` ${v}`),level:e,showTimestamp:!1}))}break}}else if(!ke()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${a}`),o)console.error(o)}if(!this.shouldLog(e))return;let u=`${s} ${this.environment}.${e.toUpperCase()}: ${f}
159
+ `;if(o)u+=`${o}
160
+ `;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()&&!ke()&&ce.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()&&!ke()&&ce.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,s="info")=>{if(!ke()&&ce.stdout.isTTY)ce.stdout.write(`
161
+ `);if(this[s==="warning"?"warn":s](i),this.activeProgressBar&&this.shouldStyleConsole()&&!ke()&&ce.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":ee.blue("\u25D0"),tag:r,message:`${ee.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,a=new Date,o=this.formatConsoleTimestamp(a),c=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
162
+ `,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:o,icon:this.options.showIcons===!1?"":ee.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ke())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 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(ke())throw Error("createReadStream is not supported in browser environments");if(!ei(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return yo(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=ht.isBuffer(e)?e:ht.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),a=n.subarray(16,n.length-16),o=qu("aes-256-gcm",r,i);o.setAuthTag(s);let c=o.update(a),f=o.final(),u=c.length+f.length,l=ht.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 ke()}isServerMode(){return!ke()}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 o=i.split(`
163
+ `),c=Math.max(...o.map((g)=>g.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,l=o.map((g)=>{return this.formatConsoleMessage({timestamp:r,message:ee.cyan(g),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:ee.cyan(f),showTimestamp:!1})),l.forEach((g)=>console.error(g)),console.error(this.formatConsoleMessage({timestamp:r,message:ee.cyan(u),showTimestamp:!1}))}else if(!ke())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let a=`${n} ${this.environment}.INFO: [BOX] ${s}
164
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}async prompt(e){if(ke())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${ee.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();ce.stdin.removeListener("data",r);try{if(typeof ce.stdin.setRawMode==="function")ce.stdin.setRawMode(!1)}catch{}ce.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof ce.stdin.setRawMode==="function")ce.stdin.setRawMode(!0)}catch{}ce.stdin.resume(),ce.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,o=0;if(r=e.replace(a,(c,f)=>{if(f==="%")return"%";if(o>=t.length)return c;let u=t[o++];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}}),o<t.length)r+=` ${t.slice(o).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 a=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"",o=this.options.showIcons===!1?"":`${ee.blue("\u25D0")} `;console.error(`${o}${a} ${ee.cyan(n)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
165
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!ce.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=ee.green("\u2501".repeat(n)),a=ee.gray("\u2501".repeat(i)),o=`[${s}${a}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?ee.green("\u2713"):ee.blue("\u25B6"),l=this.options.showTags!==!1&&this.name?` ${ee.gray(this.formatTag(this.name))}`:"",g=`\r${u}${l} ${o} ${c}${f}`,h=ce.stdout.columns||80,w=" ".repeat(Math.max(0,h-g.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${g}${w}`,ce.stdout.write(e.lastRenderedLine),t)ce.stdout.write(`
166
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||ke()||!ce.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(ke()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await ti(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=qt(this.config.logDirectory,n);if(e.before)try{if((await Zt(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 ri(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 Xo(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,a=Error("Unknown error occurred");for(let o=0;o<=r;o++)try{return await e()}catch(c){if(a=c instanceof Error?c:Error(String(c)),o===r||!i(a))break;if(n>0)await new Promise((f)=>setTimeout(f,n))}if(s!==void 0)return s;throw a instanceof Error?a:Error(`Unknown error: ${String(a)}`)}function zo(e){return e instanceof Ue}function Wh(e){return e instanceof xi}function Gh(e){if(zo(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 Mi{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:a={},verbose:o=!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:a,verbose:o,configName:e}),{config:l,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return vr.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 a=[...t,i],o=a.map((u)=>this.formatEnvKey(u,n.useCamelCase)),c=`${r}_${o.join("_")}`,f=n.useBackwardCompatibility?`${r}_${a.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,a,r,n);else{let u=ii.env[c]||(f?ii.env[f]:void 0);if(u!==void 0){if(n.verbose){let l=ii.env[c]?c:f}try{e[i]=this.parseEnvironmentValue(u,typeof s,c,n.customParsers,n.configName)}catch(l){if(l instanceof Ti)throw l;throw xt.envVar(c,u,typeof s,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[s,a]of Object.entries(n))try{return a(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw xt.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(ii.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),a=[];switch(this.extractEnvVarInfo(t,[],s,a),i){case"markdown":return this.formatAsMarkdown(a,e);case"json":return JSON.stringify(a,null,2);default:return this.formatAsText(a,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,s]of Object.entries(e)){let a=[...t,i],o=`${r}_${a.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,a,r,n);else n.push({key:o,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${a.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}:
162
167
 
163
168
  `;for(let n of e)r+=`${n.key}
164
169
  `,r+=` Type: ${n.type}
@@ -170,25 +175,25 @@ ${n}`}if(a)return`${nu(a)}${n}`;return r+n}function au(e,t=!0){let r=ut(e.leadin
170
175
  `;r+=`| Variable | Type | Description | Example |
171
176
  `,r+=`|----------|------|-------------|----------|
172
177
  `;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
173
- `;return r}}function Th(e,t){let r=za("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function Za(e,t,r={}){return qa(e,t,r,new WeakMap)}function qa(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 Ua(e,t,i,n);if(!Qe(t)||!Qe(e))return t;return Fh(e,t,r,n)}function Ua(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 Rh(e,t);case"smart":return Wh(e,t,n);default:return t}return t}function Rh(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Jn(i,n)))r.push(n);return r}function Wh(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(Qe(t[0])&&Qe(e[0]))return Nh(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 Nh(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((f)=>Qe(f)&&(a in f)&&f[a]===i[a])){o=!0;break}}if(!o)n.push(i)}return n}function Fh(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],f=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(f))s[o]=qa(f,a,r,n);else if(Array.isArray(a)||Array.isArray(f))s[o]=Ua(f,a,r.arrayMergeMode||"smart",n);else s[o]=a}return s}function is(e,t,r="replace"){return Za(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Jn(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(!Jn(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(!Jn(e[i],t[i]))return!1}return!0}return!1}function Qe(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Fi{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 c=tr.getWithFileCheck("file",e);if(c){if(a)console.log(`Configuration loaded from cache: ${e}`);return c}}let f=async()=>{if(!ni(e))return null;try{let c=`?t=${Date.now()}`,u=await import(e+c),l=u.default||u,p="default"in u,h=Object.keys(u).length>0;if(!p&&!h)throw new Cr(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new Cr(e,Error("Configuration must export a valid object"),"unknown");let w={config:is(t,l,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)tr.setWithFileCheck("file",w,e,s);return w}catch(c){throw c instanceof Error?Ot.configLoad(e,c):Ot.configLoad(e,Error(String(c)))}};if(o)return Ar.track("loadFromPath",f,{path:e});return f()}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(Tn(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 Ga(async()=>{return ni(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!ni(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=Tn(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=Tn(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(!ni(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 ns{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:a=!0,verbose:f=!1}=r,c=async()=>{let u=[],l=[],p={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:a,verbose:f};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,p);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],p);else return this.validateWithJSONSchema(e,t,p)}catch(h){return u.push({path:"",message:`Validation failed: ${h}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(a)return await Ar.track("validateConfiguration",c);return c()}async validateWithSchemaFile(e,t,r){try{if(!Vu(t))throw new br(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 br(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,f]of Object.entries(t.properties))if(a in o){let c=r?`${r}.${a}`:a;if(this.validateObjectAgainstSchema(o[a],f,c,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let f of Object.keys(o))if(!a.has(f))i.push({path:r?`${r}.${f}`:f,message:`Additional property '${f}' 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:il},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class ss{fileLoader=new Fi;envProcessor=new Ni;validator=new ns;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let f=this.checkCache(o.name||"",o);if(f)return f}let a;try{a=await this.loadConfigurationStrategies(o,!0,r)}catch(f){let c=o.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(c)throw f;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(f instanceof Error&&f.name==="ConfigLoadError"){let u=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),l=!u&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),p=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(c&&(p||u))throw f;if(l&&(!c||!p))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(!c)a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}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 f={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(f);if(n.slowThreshold&&f.duration>n.slowThreshold)it.warn(`Slow configuration loading detected: ${f.duration}ms for ${o.name}`);a.metrics=f}return a}catch(a){let f=Date.now()-t;throw it.error(`Configuration loading failed after ${f}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:f=!0,arrayStrategy:c="replace",verbose:u=!1}=e,l=s||Nt.cwd(),p=[],h=await this.loadLocalConfiguration(n,i,l,o,a,c,u,f,r);if(h)return p.push(...this.getLocalSearchPaths(n,i,l,o)),this.finalizeResult(h,p,f,n,u);let w=await this.loadHomeConfiguration(n,i,a,c,u,f);if(w)return p.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(w,p,f,n,u);let A=await this.loadPackageJsonConfiguration(n,i,l,a,c,u,f);if(A)return p.push(He(l,"package.json")),this.finalizeResult(A,p,f,n,u);if(p.push(...this.getAllSearchPaths(n,i,l,o)),t)throw Ot.configNotFound(n,p,i);return{...await this.applyEnvironmentVariables(n,a,f,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,f){let c=a?$r(e,i,o):i,u=this.getLocalDirectories(r,n);for(let l of u){if(o)it.info(`Searching for configuration in: ${l}`);let p=this.fileLoader.generateConfigPaths(e,l,t),h=await this.fileLoader.tryLoadFromPaths(p,c,{arrayStrategy:s,verbose:o,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(h){if(o)it.success(`Configuration loaded from: ${h.source.path}`);return h}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?$r(e,r,i):r,a=[He(Yt(),".config",e),He(Yt(),".config"),Yt()];for(let f of a){if(i)it.info(`Checking home directory: ${f}`);let c=this.fileLoader.generateConfigPaths(e,f,t),u=await this.fileLoader.tryLoadFromPaths(c,o,{arrayStrategy:n,verbose:i});if(u){if(i)it.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?$r(e,n,s):n;try{let f=He(r,"package.json");if(!jn(f))return null;let c=await import(f),u=c[e],l=e;if(!u&&t)u=c[t],l=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)it.success(`Configuration loaded from package.json: ${l}`);return{config:is(a,u,i),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(s)it.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}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:$r(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 Ot.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return tr.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);tr.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 o of i)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[He(Yt(),".config",e),He(Yt(),".config"),Yt()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function Oa(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 Ph(e){return $t.loadConfig({...e,__strictErrorHandling:!0})}async function Xa(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 $t.loadConfig(e);else n=await $t.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)it.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 $t.applyEnvironmentVariables(o.name||"",t,!0,o.verbose||!1))?.config??t;return t}}async function Dh(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await $t.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"&&Oa(r)))return(await $t.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await $t.loadConfig({...e,cwd:e.cwd||Nt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Oa(t)))return(await $t.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Mh(e,t,r="replace"){let n=new Fi;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function $r(e,t,r=!1){let n=new Ni,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,a=[]){let f={...o};for(let[c,u]of Object.entries(o)){let l=[...a,c],p=[`${i}_${l.join("_").toUpperCase()}`,`${i}_${l.map((A)=>A.toUpperCase()).join("")}`,`${i}_${l.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],h,w;for(let A of p)if(h=Nt.env[A],h!==void 0){w=A;break}if(h!==void 0&&w)if(typeof u==="boolean")f[c]=["true","1","yes"].includes(h.toLowerCase());else if(typeof u==="number"){let A=Number(h);if(!Number.isNaN(A))f[c]=A}else if(Array.isArray(u))try{f[c]=JSON.parse(h)}catch{f[c]=h.split(",").map((A)=>A.trim())}else f[c]=h;else if(u&&typeof u==="object"&&!Array.isArray(u))f[c]=s(u,l)}return f}return s(t)}function Ih(e){let t=He(Nt.cwd(),e.configDir),r=He(Nt.cwd(),e.generatedDir),n=He(r,"config-types.ts");if(!jn(ia(n)))xu(ia(n),{recursive:!0,mode:511});let i=jn(t)?Eu(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${hd}
178
+ `;return r}}function Bh(e,t){let r=il("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function Qo(e,t,r={}){return el(e,t,r,new WeakMap)}function el(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 tl(e,t,i,n);if(!et(t)||!et(e))return t;return jh(e,t,r,n)}function tl(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 Vh(e,t);case"smart":return _h(e,t,n);default:return t}return t}function Vh(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>_n(i,n)))r.push(n);return r}function _h(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(et(t[0])&&et(e[0]))return Hh(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 Hh(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"],a=!1;for(let o of s)if(o in i){if(n.find((c)=>et(c)&&(o in c)&&c[o]===i[o])){a=!0;break}}if(!a)n.push(i)}return n}function jh(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 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(et(o)&&et(c))s[a]=el(c,o,r,n);else if(Array.isArray(o)||Array.isArray(c))s[a]=tl(c,o,r.arrayMergeMode||"smart",n);else s[a]=o}return s}function is(e,t,r="replace"){return Qo(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function _n(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(!_n(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(!_n(e[i],t[i]))return!1}return!0}return!1}function et(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Ii{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=tr.getWithFileCheck("file",e);if(f){if(o)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!ni(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,g="default"in u,h=Object.keys(u).length>0;if(!g&&!h)throw new $r(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new $r(e,Error("Configuration must export a valid object"),"unknown");let w={config:is(t,l,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)tr.setWithFileCheck("file",w,e,s);return w}catch(f){throw f instanceof Error?xt.configLoad(e,f):xt.configLoad(e,Error(String(f)))}};if(a)return vr.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(On(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 Xo(async()=>{return ni(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!ni(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=On(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=On(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(!ni(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 ns{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(h){return u.push({path:"",message:`Validation failed: ${h}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(o)return await vr.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!nh(t))throw new Er(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 Er(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:ll},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class ss{fileLoader=new Ii;envProcessor=new Mi;validator=new ns;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)it.warn(`Slow configuration loading detected: ${c.duration}ms for ${a.name}`);o.metrics=c}return o}catch(o){let c=Date.now()-t;throw it.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||Mt.cwd(),g=[],h=await this.loadLocalConfiguration(n,i,l,a,o,f,u,c,r);if(h)return g.push(...this.getLocalSearchPaths(n,i,l,a)),this.finalizeResult(h,g,c,n,u);let w=await this.loadHomeConfiguration(n,i,o,f,u,c);if(w)return g.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(w,g,c,n,u);let v=await this.loadPackageJsonConfiguration(n,i,l,o,f,u,c);if(v)return g.push(je(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?Cr(e,i,a):i,u=this.getLocalDirectories(r,n);for(let l of u){if(a)it.info(`Searching for configuration in: ${l}`);let g=this.fileLoader.generateConfigPaths(e,l,t),h=await this.fileLoader.tryLoadFromPaths(g,f,{arrayStrategy:s,verbose:a,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(h){if(a)it.success(`Configuration loaded from: ${h.source.path}`);return h}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let a=s?Cr(e,r,i):r,o=[je(Kt(),".config",e),je(Kt(),".config"),Kt()];for(let c of o){if(i)it.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)it.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?Cr(e,n,s):n;try{let c=je(r,"package.json");if(!Bn(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)it.success(`Configuration loaded from package.json: ${l}`);return{config:is(o,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)it.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:Cr(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 tr.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);tr.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 a of i)s.push(...this.fileLoader.generateConfigPaths(e,a,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[je(Kt(),".config",e),je(Kt(),".config"),Kt()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function ko(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 Kh(e){return Ct.loadConfig({...e,__strictErrorHandling:!0})}async function rl(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)it.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 Jh(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"&&ko(r)))return(await Ct.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await Ct.loadConfig({...e,cwd:e.cwd||Mt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&ko(t)))return(await Ct.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Uh(e,t,r="replace"){let n=new Ii;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function Cr(e,t,r=!1){let n=new Mi,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("")}`],h,w;for(let v of g)if(h=Mt.env[v],h!==void 0){w=v;break}if(h!==void 0&&w)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(h.toLowerCase());else if(typeof u==="number"){let v=Number(h);if(!Number.isNaN(v))c[f]=v}else if(Array.isArray(u))try{c[f]=JSON.parse(h)}catch{c[f]=h.split(",").map((v)=>v.trim())}else c[f]=h;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,l)}return c}return s(t)}function Yh(e){let t=je(Mt.cwd(),e.configDir),r=je(Mt.cwd(),e.generatedDir),n=je(r,"config-types.ts");if(!Bn(oo(n)))Fu(oo(n),{recursive:!0,mode:511});let i=Bn(t)?Nu(t).map((a)=>a.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${bd}
174
179
  export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
175
- `;Ou(n,s,{mode:438})}function Bh(e){let t=null,r=null,n=()=>{if(!r)r=Xa(e).then((s)=>{return t=s,s},(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)it.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 Lh(e){let t=$a(Uu.cwd(),e?.configDir||"./config");function r(){if(!Zu(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=qu(t).filter((f)=>i.has(Rn(f))).map((f)=>({base:f.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:f})),a=new Map;for(let{base:f,file:c}of o){let u=Rn(c).toLowerCase(),l=a.get(f);if(!l){a.set(f,c);continue}let p=Rn(l).toLowerCase();if(s.indexOf(u)<s.indexOf(p))a.set(f,c)}return Array.from(a.entries()).map(([f,c])=>({base:f,file:c})).sort((f,c)=>f.base.localeCompare(c.base))}function n(){let i=r(),s=i.map((f)=>f.base),o=s.length?s.map((f)=>`'${f}'`).join(" | "):"string",a=i.length?`{
176
- ${i.map((f)=>{let c=$a(t,f.file).replace(/\\/g,"/");return` '${f.base}': typeof import('${c}').default`}).join(`,
180
+ `;Lu(n,s,{mode:438})}function Zh(e){let t=null,r=null,n=()=>{if(!r)r=rl(e).then((s)=>{return t=s,s},(s)=>{let a="defaultConfig"in e?e.defaultConfig:{};if(t=a,"verbose"in e&&e.verbose)it.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return a});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(s,a){if(t)return t[a];let o=i[a];return n(),o},has(s,a){return a in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(s,a){return Object.getOwnPropertyDescriptor(t||i,a)},set(s,a,o){if(!t)t={...i};return t[a]=o,!0}})}function qh(e){let t=bo(oh.cwd(),e?.configDir||"./config");function r(){if(!sh(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],a=ah(t).filter((c)=>i.has(Pn(c))).map((c)=>({base:c.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:c})),o=new Map;for(let{base:c,file:f}of a){let u=Pn(f).toLowerCase(),l=o.get(c);if(!l){o.set(c,f);continue}let g=Pn(l).toLowerCase();if(s.indexOf(u)<s.indexOf(g))o.set(c,f)}return Array.from(o.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),a=s.length?s.map((c)=>`'${c}'`).join(" | "):"string",o=i.length?`{
181
+ ${i.map((c)=>{let f=bo(t,c.file).replace(/\\/g,"/");return` '${c.base}': typeof import('${f}').default`}).join(`,
177
182
  `)}
178
- }`:"Record<string, any>";return`export type ConfigNames = ${o}
179
- export type ConfigByName = ${a}
183
+ }`:"Record<string, any>";return`export type ConfigNames = ${a}
184
+ export type ConfigByName = ${o}
180
185
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
181
186
  export type ConfigOf = Config
182
- `}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 md(e,t={}){let r=Ci.cwd();while(r.includes("storage"))r=wa(r,"..");let n=wa(r,e||"");if(t?.relative)return zu(Ci.cwd(),n);return n}function Fe(){if(yt.env.NODE_ENV==="test"||yt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function pd(){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 al{async format(e){let t=await pd(),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:er.pid,hostname:t(),environment:er.env.NODE_ENV||"development",platform:er.platform,version:er.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:er.env.NODE_ENV||er.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Pi{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={...Si},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new al,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{...Ln,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Ln};return{...Ln,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Si.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 ih(this.config.logDirectory,va.F_OK|va.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await nh(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:dt.from(e);try{if(!si(this.currentLogFile))await Fn(this.currentLogFile,"",{mode:420});if(n=Aa(this.currentLogFile,"a",420),rh(n,a,{flag:"a"}),ba(n),n!==void 0)Nn(n),n=void 0;if((await zt(this.currentLogFile)).size===0){if(await Fn(this.currentLogFile,a,{flag:"w",mode:420}),(await zt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let c=f;if(c.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(c.code)){if(i<s-1){let u=typeof c.message==="string"?c.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let l=o*2**i;await new Promise((p)=>setTimeout(p,l)),i++;continue}}if(c?.code&&["ENOSPC","EDQUOT"].includes(c.code))throw Error(`Disk quota exceeded or no space left on device: ${c.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",c),c}finally{if(n!==void 0)try{Nn(n)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(a){if(i===s-1){let c=a,u=typeof c.message==="string"?c.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}i++;let f=o*2**(i-1);await new Promise((c)=>setTimeout(c,f))}})();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 Qt(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 Qt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Qt(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 Wn(16).toString("hex")}generateKey(){return Wn(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=Wn(16),n=Qu("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,f=n.getAuthTag(),c=dt.allocUnsafe(16+a+16);return r.copy(c,0),s.copy(c,16),o.copy(c,16+s.length),f.copy(c,16+a),{encrypted:c,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Ea(),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(Fe())return;if(!this.shouldWriteToFile())return;let e=await zt(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 oi(this.config.logDirectory),s=i.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,c)=>{let u=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.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 zt(r).catch(()=>null))try{if(await xa(r,a),t.compress)try{let f=`${a}.gz`;await this.compressLogFile(a,f),await ai(a)}catch(f){console.error("Error compressing rotated file:",f)}if(s.length===0&&!i.some((f)=>f.endsWith(".log.1")))try{let f=`${r}.1`;await Fn(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await zt(r).catch(()=>null))await xa(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await oi(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await ai(Qt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Ca(e),n=th(t),i=Ea();await ah(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()})),si(this.currentLogFile))try{let e=Aa(this.currentLogFile,"r+");ba(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(!Fe()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await oi(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await ai(Qt(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||Fe())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=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(o)h.push(t);if(s==="warning")h.push("WARN");else if(s==="error")h.push("ERROR");else if(r)h.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)h.push(n.replace(/[[\]]/g,""));return h.push(i),h.join(" ")}let f=fe.stdout.columns||120,c="";if(s==="warning"||s==="error")c=`${r} ${i}`;else if(s==="info"||s==="success")c=`${r} ${n} ${i}`;else c=`${r} ${n} ${te.cyan(i)}`;if(!o)return c.trim();let u=a(c).trim().length,l=a(t).length,p=Math.max(1,f-2-u-l);return`${c.trim()}${" ".repeat(p)}${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)}`,f="\x1B]8;;",c="\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(Fe())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(sh(t)||t.startsWith("./")||t.startsWith("../"))t=oh(t);else return null;return si(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:f,fileText:c}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let l=this.options.showIcons===!1?"":bd[e],p=this.options.showTags!==!1&&this.name?te.gray(this.formatTag(this.name)):"",h;switch(e){case"debug":h=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:te.gray(f),level:e}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:f,level:e}),console.warn(h);break;case"success":h=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:te.green(f),level:e}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:f,level:e}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:i,icon:l,tag:p,message:f,level:e}),console.error(h),a){let w=a.split(`
183
- `);for(let A of w)if(A.trim()&&!A.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:te.gray(` ${A}`),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()}: ${c}
184
- `;if(a)u+=`${a}
185
- `;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()&&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()&&!Fe()&&fe.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,s="info")=>{if(!Fe()&&fe.stdout.isTTY)fe.stdout.write(`
186
- `);if(this[s==="warning"?"warn":s](i),this.activeProgressBar&&this.shouldStyleConsole()&&!Fe()&&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),f=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)f+=` ${JSON.stringify(r)}`;if(f+=`
187
- `,f=f.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let c=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:c,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Fe())console.error(f.trim());if(this.shouldWriteToFile())await this.writeToFile(f)}}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 Pi(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(!si(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ca(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=eh("aes-256-gcm",r,i);a.setAuthTag(s);let f=a.update(o),c=a.final(),u=f.length+c.length,l=dt.allocUnsafe(u);return f.copy(l,0),c.copy(l,f.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(`
188
- `),f=Math.max(...a.map((p)=>p.length))+2,c=`\u250C${"\u2500".repeat(f)}\u2510`,u=`\u2514${"\u2500".repeat(f)}\u2518`,l=a.map((p)=>{return this.formatConsoleMessage({timestamp:r,message:te.cyan(p),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:te.cyan(c),showTimestamp:!1})),l.forEach((p)=>console.error(p)),console.error(this.formatConsoleMessage({timestamp:r,message:te.cyan(u),showTimestamp:!1}))}else if(!Fe())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
189
- `.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(`${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,(f,c)=>{if(c==="%")return"%";if(a>=t.length)return f;let u=t[a++];switch(c){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 f}}),a<t.length)r+=` ${t.slice(a).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let 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}
190
- `.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}]`,f=`${r}%`.padStart(4),c=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))}`:"",p=`\r${u}${l} ${a} ${f}${c}`,h=fe.stdout.columns||80,w=" ".repeat(Math.max(0,h-p.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${p}${w}`,fe.stdout.write(e.lastRenderedLine),t)fe.stdout.write(`
191
- `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Fe()||!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(Fe()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await oi(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=Qt(this.config.logDirectory,n);if(e.before)try{if((await zt(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 ai(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 Ad(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(f){if(o=f instanceof Error?f:Error(String(f)),a===r||!i(o))break;if(n>0)await new Promise((c)=>setTimeout(c,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}class as{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:f=!0}=r,c=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(f)return zn.track("applyEnvironmentVariables",c,{configName:e});return c()}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)),f=`${r}_${a.join("_")}`,c=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=li.env[f]||(c?li.env[c]:void 0);if(u!==void 0){if(n.verbose){let l=li.env[f]?f:c}try{e[i]=this.parseEnvironmentValue(u,typeof s,f,n.customParsers,n.configName)}catch(l){if(l instanceof os)throw l;throw rr.envVar(f,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 rr.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(li.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((f)=>this.formatEnvKey(f,!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}:
187
+ `}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 Ad(e,t={}){let r=$i.cwd();while(r.includes("storage"))r=So(r,"..");let n=So(r,e||"");if(t?.relative)return ch($i.cwd(),n);return n}function Ie(){if(yt.env.NODE_ENV==="test"||yt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Td(){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 hl{async format(e){let t=await Td(),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:er.pid,hostname:t(),environment:er.env.NODE_ENV||"development",platform:er.platform,version:er.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:er.env.NODE_ENV||er.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Di{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={...Ri},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new hl,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{...Gn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Gn};return{...Gn,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Ri.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!Ie()&&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 mh(this.config.logDirectory,Ro.F_OK|Ro.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await ph(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(!si(this.currentLogFile))await In(this.currentLogFile,"",{mode:420});if(n=To(this.currentLogFile,"a",420),dh(n,o,{flag:"a"}),xo(n),n!==void 0)Mn(n),n=void 0;if((await zt(this.currentLogFile)).size===0){if(await In(this.currentLogFile,o,{flag:"w",mode:420}),(await zt(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{Mn(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 Qt(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 Qt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Qt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Ie())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 kn(16).toString("hex")}generateKey(){return kn(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=kn(16),n=fh("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=Po(),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(Ie())return;if(!this.shouldWriteToFile())return;let e=await zt(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 ai(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 zt(r).catch(()=>null))try{if(await Oo(r,o),t.compress)try{let c=`${o}.gz`;await this.compressLogFile(o,c),await oi(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 In(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 zt(r).catch(()=>null))await Oo(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await ai(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of i.slice(t.maxFiles))await oi(Qt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Ao(e),n=hh(t),i=Po();await Ch(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()})),si(this.currentLogFile))try{let e=To(this.currentLogFile,"r+");xo(e),Mn(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(!Ie()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await ai(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await oi(Qt(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||Ie())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=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(a)h.push(t);if(s==="warning")h.push("WARN");else if(s==="error")h.push("ERROR");else if(r)h.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)h.push(n.replace(/[[\]]/g,""));return h.push(i),h.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(!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=te.underline(te.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)=>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(Ie())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(gh(t)||t.startsWith("./")||t.startsWith("../"))t=yh(t);else return null;return si(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?"":Md[e],g=this.options.showTags!==!1&&this.name?te.gray(this.formatTag(this.name)):"",h;switch(e){case"debug":h=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:te.gray(c),level:e}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.warn(h);break;case"success":h=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:te.green(c),level:e}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.error(h),o){let w=o.split(`
188
+ `);for(let v of w)if(v.trim()&&!v.includes(a))console.error(this.formatConsoleMessage({timestamp:i,message:te.gray(` ${v}`),level:e,showTimestamp:!1}))}break}}else if(!Ie()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${a}`),o)console.error(o)}let u=`${s} ${this.environment}.${e.toUpperCase()}: ${f}
189
+ `;if(o)u+=`${o}
190
+ `;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()&&!Ie()&&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()&&!Ie()&&fe.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,s="info")=>{if(!Ie()&&fe.stdout.isTTY)fe.stdout.write(`
191
+ `);if(this[s==="warning"?"warn":s](i),this.activeProgressBar&&this.shouldStyleConsole()&&!Ie()&&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`,a=new Date,o=this.formatConsoleTimestamp(a),c=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
192
+ `,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:o,icon:this.options.showIcons===!1?"":te.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Ie())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 Di(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(Ie())throw Error("createReadStream is not supported in browser environments");if(!si(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ao(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),a=n.subarray(16,n.length-16),o=uh("aes-256-gcm",r,i);o.setAuthTag(s);let c=o.update(a),f=o.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 Ie()}isServerMode(){return!Ie()}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 o=i.split(`
193
+ `),c=Math.max(...o.map((g)=>g.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,l=o.map((g)=>{return 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(!Ie())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let a=`${n} ${this.environment}.INFO: [BOX] ${s}
194
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}async prompt(e){if(Ie())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 a=/%([sdijfo%])/g,o=0;if(r=e.replace(a,(c,f)=>{if(f==="%")return"%";if(o>=t.length)return c;let u=t[o++];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}}),o<t.length)r+=` ${t.slice(o).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 a=this.options.showTags!==!1&&this.name?te.gray(this.formatTag(this.name)):"",o=this.options.showIcons===!1?"":`${te.blue("\u25D0")} `;console.error(`${o}${a} ${te.cyan(n)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
195
+ `.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)),a=te.gray("\u2501".repeat(i)),o=`[${s}${a}]`,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} ${o} ${c}${f}`,h=fe.stdout.columns||80,w=" ".repeat(Math.max(0,h-g.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${g}${w}`,fe.stdout.write(e.lastRenderedLine),t)fe.stdout.write(`
196
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ie()||!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(Ie()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await ai(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=Qt(this.config.logDirectory,n);if(e.before)try{if((await zt(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 oi(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 Id(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,a=Error("Unknown error occurred");for(let o=0;o<=r;o++)try{return await e()}catch(c){if(a=c instanceof Error?c:Error(String(c)),o===r||!i(a))break;if(n>0)await new Promise((f)=>setTimeout(f,n))}if(s!==void 0)return s;throw a instanceof Error?a:Error(`Unknown error: ${String(a)}`)}class os{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:a={},verbose:o=!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:a,verbose:o,configName:e}),{config:l,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return zn.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 a=[...t,i],o=a.map((u)=>this.formatEnvKey(u,n.useCamelCase)),c=`${r}_${o.join("_")}`,f=n.useBackwardCompatibility?`${r}_${a.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,a,r,n);else{let u=li.env[c]||(f?li.env[f]:void 0);if(u!==void 0){if(n.verbose){let l=li.env[c]?c:f}try{e[i]=this.parseEnvironmentValue(u,typeof s,c,n.customParsers,n.configName)}catch(l){if(l instanceof as)throw l;throw rr.envVar(c,u,typeof s,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[s,a]of Object.entries(n))try{return a(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw rr.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(li.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),a=[];switch(this.extractEnvVarInfo(t,[],s,a),i){case"markdown":return this.formatAsMarkdown(a,e);case"json":return JSON.stringify(a,null,2);default:return this.formatAsText(a,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,s]of Object.entries(e)){let a=[...t,i],o=`${r}_${a.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,a,r,n);else n.push({key:o,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${a.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}:
192
197
 
193
198
  `;for(let n of e)r+=`${n.key}
194
199
  `,r+=` Type: ${n.type}
@@ -200,23 +205,23 @@ export type ConfigOf = Config
200
205
  `;r+=`| Variable | Type | Description | Example |
201
206
  `,r+=`|----------|------|-------------|----------|
202
207
  `;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
203
- `;return r}}function vd(e,t,r={}){return gl(e,t,r,new WeakMap)}function gl(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 pl(e,t,i,n);if(!et(t)||!et(e))return t;return kd(e,t,r,n)}function pl(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 xd(e,t);case"smart":return Ed(e,t,n);default:return t}return t}function xd(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Xn(i,n)))r.push(n);return r}function Ed(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(et(t[0])&&et(e[0]))return Od(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 Od(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((f)=>et(f)&&(a in f)&&f[a]===i[a])){o=!0;break}}if(!o)n.push(i)}return n}function kd(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],f=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(f))s[o]=gl(f,a,r,n);else if(Array.isArray(a)||Array.isArray(f))s[o]=pl(f,a,r.arrayMergeMode||"smart",n);else s[o]=a}return s}function yl(e,t,r="replace"){return vd(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Xn(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(!Xn(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(!Xn(e[i],t[i]))return!1}return!0}return!1}function et(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class $l{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 c=bi.getWithFileCheck("file",e);if(c){if(a)console.log(`Configuration loaded from cache: ${e}`);return c}}let f=async()=>{if(!fi(e))return null;try{let c=`?t=${Date.now()}`,u=await import(e+c),l=u.default||u,p="default"in u,h=Object.keys(u).length>0;if(!p&&!h)throw new Ti(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new Ti(e,Error("Configuration must export a valid object"),"unknown");let w={config:yl(t,l,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)bi.setWithFileCheck("file",w,e,s);return w}catch(c){throw c instanceof Error?rr.configLoad(e,c):rr.configLoad(e,Error(String(c)))}};if(o)return zn.track("loadFromPath",f,{path:e});return f()}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 Ad(async()=>{return fi(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!fi(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(!fi(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 wl{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:a=!0,verbose:f=!1}=r,c=async()=>{let u=[],l=[],p={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:a,verbose:f};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,p);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],p);else return this.validateWithJSONSchema(e,t,p)}catch(h){return u.push({path:"",message:`Validation failed: ${h}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(a)return await zn.track("validateConfiguration",c);return c()}async validateWithSchemaFile(e,t,r){try{if(!lh(t))throw new Ri(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 Ri(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,f]of Object.entries(t.properties))if(a in o){let c=r?`${r}.${a}`:a;if(this.validateObjectAgainstSchema(o[a],f,c,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let f of Object.keys(o))if(!a.has(f))i.push({path:r?`${r}.${f}`:f,message:`Additional property '${f}' 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:Sd},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function Td(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 Cl{fileLoader=new $l;envProcessor=new as;validator=new wl;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let f=this.checkCache(o.name||"",o);if(f)return f}let a;try{a=await this.loadConfigurationStrategies(o,!0,r)}catch(f){let c=o.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(c)throw f;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(f instanceof Error&&f.name==="ConfigLoadError"){let u=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),l=!u&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),p=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(c&&(p||u))throw f;if(l&&(!c||!p))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(!c)a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}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 f={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(f);if(n.slowThreshold&&f.duration>n.slowThreshold)mt.warn(`Slow configuration loading detected: ${f.duration}ms for ${o.name}`);a.metrics=f}return a}catch(a){if(a instanceof Error&&a.name==="ConfigNotFoundError")throw a;let f=Date.now()-t;throw mt.error(`Configuration loading failed after ${f}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:f=!0,arrayStrategy:c="replace",verbose:u=!1}=e,l=s||Wi.cwd(),p=[],h=await this.loadLocalConfiguration(n,i,l,o,a,c,u,f,r);if(h)return p.push(...this.getLocalSearchPaths(n,i,l,o)),this.finalizeResult(h,p,f,n,u);let w=await this.loadHomeConfiguration(n,i,a,c,u,f);if(w)return p.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(w,p,f,n,u);let A=await this.loadPackageJsonConfiguration(n,i,l,a,c,u,f);if(A)return p.push(ze(l,"package.json")),this.finalizeResult(A,p,f,n,u);if(p.push(...this.getAllSearchPaths(n,i,l,o)),t)throw rr.configNotFound(n,p,i);return{...await this.applyEnvironmentVariables(n,a,f,u),warnings:[`No configuration file found for "${n}"${Td(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,a,f){let c=a?ui(e,i,o):i,u=this.getLocalDirectories(r,n);for(let l of u){if(o)mt.info(`Searching for configuration in: ${l}`);let p=this.fileLoader.generateConfigPaths(e,l,t),h=await this.fileLoader.tryLoadFromPaths(p,c,{arrayStrategy:s,verbose:o,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(h){if(o)mt.success(`Configuration loaded from: ${h.source.path}`);return h}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?ui(e,r,i):r,a=[ze(Ht(),".config",e),ze(Ht(),".config"),Ht()];for(let f of a){if(i)mt.info(`Checking home directory: ${f}`);let c=this.fileLoader.generateConfigPaths(e,f,t),u=await this.fileLoader.tryLoadFromPaths(c,o,{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,o){let a=o?ui(e,n,s):n;try{let f=ze(r,"package.json");if(!Au(f))return null;let c={};try{c=JSON.parse(vu(f,"utf8"))}catch(p){if(s)mt.warn("Failed to parse package.json:",[p instanceof Error?p:Error(String(p))]);return null}let u=c[e],l=e;if(!u&&t){let p=Array.isArray(t)?t:[t];for(let h of p){if(!h)continue;if(c[h]){u=c[h],l=h;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)mt.success(`Configuration loaded from package.json: ${l}`);return{config:yl(a,u,i),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(s)mt.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}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:ui(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 rr.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return bi.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);bi.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 ui(e,t,r=!1){let n=new as,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,a=[]){let f={...o};for(let[c,u]of Object.entries(o)){let l=[...a,c],p=[`${i}_${l.join("_").toUpperCase()}`,`${i}_${l.map((A)=>A.toUpperCase()).join("")}`,`${i}_${l.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],h,w;for(let A of p)if(h=Wi.env[A],h!==void 0){w=A;break}if(h!==void 0&&w)if(typeof u==="boolean")f[c]=["true","1","yes"].includes(h.toLowerCase());else if(typeof u==="number"){let A=Number(h);if(!Number.isNaN(A))f[c]=A}else if(Array.isArray(u))try{f[c]=JSON.parse(h)}catch{f[c]=h.split(",").map((A)=>A.trim())}else f[c]=h;else if(u&&typeof u==="object"&&!Array.isArray(u))f[c]=s(u,l)}return f}return s(t)}var bi,zn,fh,ch=(e)=>e,hh=(e,t)=>{for(var r in t)fh(e,r,{get:t[r],enumerable:!0,configurable:!0,set:uh.bind(t,r)})},dh=(e,t)=>()=>(e&&(t=e(e=0)),t),Ka,za,tr,Ar,Qa,jh,_h,ka,di,Kn,Le,me,Jh,Sa,Kh,Ta,Hh,Yh,Dn,Gh,Ra,Wa,Mn,Vh,Zh,qh,Uh,mi,el,Xh,je,zh,Qh,Na,gi,Hn,Ne,ee,ed,Fa,td,Pa,rd,id,In,nd,Da,Ma,sd,Bn,od,ad,ld,fd,cd,pi,tl,ud,hd="0.15.6",Ve,Oi,Cr,Yn,Gn,ki,Vn,Zn,br,qn,Un,Ot,rl,il,it,$t,nl,sl,dd,gd,ol,Si,Ip,Ie,te,Bp,yd,Lp,$d,jp,_p,Ia,Jp,wd,Cd,Kp,Ba,Hp,Yp,Gp,Vp,Zp,Ln,bd,qp,nt,ll,Ti,fl,cl,os,ul,hl,Ri,dl,ml,rr,Sd,mt,Up,Xp,zp,Rd,bl;var Al=de(()=>{bi=new _a,zn=new Ja,fh=Object.defineProperty;Ka={};hh(Ka,{withErrorRecovery:()=>Ga,tryLoadConfig:()=>Mh,loadConfigWithResult:()=>Ph,loadConfig:()=>Xa,isRetryableError:()=>Sh,isConfigNotFoundError:()=>kh,isBunfigError:()=>Va,globalPerformanceMonitor:()=>Ar,globalCache:()=>tr,getEnvOrDefault:()=>Th,generateConfigTypes:()=>Ih,defaultGeneratedDir:()=>sl,defaultConfigDir:()=>nl,deepMergeWithArrayStrategy:()=>is,deepMerge:()=>Za,createLibraryConfig:()=>Bh,config:()=>Dh,bunfigPlugin:()=>Lh,applyEnvVarsToConfig:()=>$r,TypeGenerationError:()=>Zn,SchemaValidationError:()=>br,PluginError:()=>Un,PerformanceMonitor:()=>es,FileSystemError:()=>Vn,ErrorFactory:()=>Ot,EnvVarError:()=>ki,EnvProcessor:()=>Ni,ConfigValidator:()=>ns,ConfigValidationError:()=>Yn,ConfigNotFoundError:()=>Oi,ConfigMergeError:()=>Gn,ConfigLoader:()=>ss,ConfigLoadError:()=>Cr,ConfigFileLoader:()=>Fi,ConfigCache:()=>Qn,CacheUtils:()=>Qa,BunfigError:()=>Ve,BrowserConfigError:()=>qn,ArrayMergeStrategies:()=>rl});dd=dh(async()=>{za=import.meta.require,tr=new Qn,Ar=new es,Qa={createKey:mh,isEquivalent:gh,estimateMemoryUsage:ph},jh=wi(_n.cwd(),"config"),_h=wi(_n.cwd(),"src/generated"),ka=$i.env.CLARITY_LOG_DIR||Tu(wh(),"logs"),di={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ka,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Kn=await Ch(),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`,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"},me=Le,Jh=Le.red,Sa=Le.green,Kh=Le.yellow,Ta=Le.blue,Hh=Le.magenta,Yh=Le.cyan,Dn=Le.white,Gh=Le.gray,Ra=Le.bgRed,Wa=Le.bgYellow,Mn=Le.bold,Vh=Le.dim,Zh=Le.italic,qh=Le.underline,Uh=Le.reset,mi={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},el={debug:"\uD83D\uDD0D",info:Ta("\u2139"),success:Sa("\u2713"),warning:Wa(Dn(Mn(" WARN "))),error:Ra(Dn(Mn(" ERROR ")))},Xh=new vi("stacks"),je=new vi("bunfig",{showTags:!0}),zh=Ke(wr.cwd(),"config"),Qh=Ke(wr.cwd(),"src/generated"),Na=yi.env.CLARITY_LOG_DIR||ku(xh(),"logs"),gi={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Na,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Hn=await Eh(),Ne={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=Ne,ed=Ne.red,Fa=Ne.green,td=Ne.yellow,Pa=Ne.blue,rd=Ne.magenta,id=Ne.cyan,In=Ne.white,nd=Ne.gray,Da=Ne.bgRed,Ma=Ne.bgYellow,sd=Ne.bgGray,Bn=Ne.bold,od=Ne.dim,ad=Ne.italic,ld=Ne.underline,fd=Ne.strikethrough,cd=Ne.reset,pi={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},tl={debug:"\uD83D\uDD0D",info:Pa("\u2139"),success:Fa("\u2713"),warning:Ma(In(Bn(" WARN "))),error:Da(In(Bn(" ERROR ")))},ud=new Ei("stacks"),Ve=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}`}},Oi=class extends Ve{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})}},Cr=class extends Ve{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}},Yn=class extends Ve{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Gn=class extends Ve{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}},ki=class extends Ve{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})}},Vn=class extends Ve{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}},Zn=class extends Ve{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}},br=class extends Ve{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})}},qn=class extends Ve{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})}},Un=class extends Ve{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}},Ot={configNotFound(e,t,r){return new Oi(e,t,r)},configLoad(e,t,r){return new Cr(e,t,r)},configValidation(e,t,r){return new Yn(e,t,r)},configMerge(e,t,r,n){return new Gn(e,t,r,n)},envVar(e,t,r,n){return new ki(e,t,r,n)},fileSystem(e,t,r){return new Vn(e,t,r)},typeGeneration(e,t,r){return new Zn(e,t,r)},schemaValidation(e,t,r){return new br(e,t,r)},browserConfig(e,t,r,n){return new qn(e,t,r,n)},plugin(e,t,r){return new Un(e,t,r)}},rl={replace:"replace",concat:"concat",smart:"smart"},il=/^https?:\/\//,it=new Ei("bunfig",{showTags:!0}),$t=new ss,nl=He(Nt.cwd(),"config"),sl=He(Nt.cwd(),"src/generated")});gd=Ci.env.CLARITY_LOG_DIR||Xu(md(),"logs"),ol={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:gd,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Si={...ol},Ip=(async()=>{try{let{loadConfig:e}=await dd().then(()=>Ka),t=await e({name:"clarity",alias:"logging",defaultConfig:ol,cwd:Ci.cwd()});if(t)Object.assign(Si,t)}catch{}return Si})();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,Bp=Ie.red,yd=Ie.green,Lp=Ie.yellow,$d=Ie.blue,jp=Ie.magenta,_p=Ie.cyan,Ia=Ie.white,Jp=Ie.gray,wd=Ie.bgRed,Cd=Ie.bgYellow,Kp=Ie.bgGray,Ba=Ie.bold,Hp=Ie.dim,Yp=Ie.italic,Gp=Ie.underline,Vp=Ie.strikethrough,Zp=Ie.reset,Ln={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},bd={debug:"\uD83D\uDD0D",info:$d("\u2139"),success:yd("\u2713"),warning:Cd(Ia(Ba(" WARN "))),error:wd(Ia(Ba(" ERROR ")))};qp=new Pi("stacks");nt=class nt 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}`}};ll=class ll extends nt{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})}};Ti=class Ti extends nt{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}};fl=class fl extends nt{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};cl=class cl extends nt{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}};os=class os extends nt{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})}};ul=class ul extends nt{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}};hl=class hl extends nt{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}};Ri=class Ri extends nt{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})}};dl=class dl extends nt{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})}};ml=class ml extends nt{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}};rr={configNotFound(e,t,r){return new ll(e,t,r)},configLoad(e,t,r){return new Ti(e,t,r)},configValidation(e,t,r){return new fl(e,t,r)},configMerge(e,t,r,n){return new cl(e,t,r,n)},envVar(e,t,r,n){return new os(e,t,r,n)},fileSystem(e,t,r){return new ul(e,t,r)},typeGeneration(e,t,r){return new hl(e,t,r)},schemaValidation(e,t,r){return new Ri(e,t,r)},browserConfig(e,t,r,n){return new dl(e,t,r,n)},plugin(e,t,r){return new ml(e,t,r)}};Sd=/^https?:\/\//;mt=new Pi("bunfig",{showTags:!0});Up=new Cl;Xp=ze(Wi.cwd(),"config"),zp=ze(Wi.cwd(),"src/generated"),Rd={cwd:bu.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},bl=Rd});function ir(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 vl(e){let t=[],r=[],n=[],i={")":"(","]":"[","}":"{"},s=0,o=0,a=-1;for(let c=0;c<e.length;c++){let u=e.charCodeAt(c),l=e.charCodeAt(c+1);if(a!==-1){if(u===42&&l===47)r.push({start:a,end:c+2}),a=-1,c++;continue}if(s){if(u===92)c++;else if(u===s)r.push({start:o,end:c+1}),s=0;continue}if(u===47&&l===42){a=c,c++;continue}if(u===47&&l===47){let h=c;while(c<e.length&&e.charCodeAt(c)!==10)c++;r.push({start:h,end:c});continue}if(u===39||u===34||u===96){s=u,o=c;continue}let p=e[c];if(p==="("||p==="["||p==="{")n.push({char:p,offset:c});else if(i[p]){let h=n.pop();if(!h||h.char!==i[p])t.push({...ir(e,c),message:`Unexpected closing delimiter ${p}`,code:"DTSX1004"})}}if(s)t.push({...ir(e,o),message:"Unterminated string literal",code:"DTSX1002"});if(a!==-1)t.push({...ir(e,a),message:"Unterminated block comment",code:"DTSX1003"});for(let c of n)t.push({...ir(e,c.offset),message:`Unclosed delimiter ${c.char}`,code:"DTSX1001"});let f=[[/\b(?:interface|class|enum)\s*(?=[{=])/g,"Declaration name expected"],[/\bfunction\s*(?=\()/g,"Function name expected"],[/\(\s*:/g,"Parameter name expected"]];for(let[c,u]of f)for(let l of e.matchAll(c)){if(r.some((p)=>l.index>=p.start&&l.index<p.end))continue;t.push({...ir(e,l.index),message:u,code:"DTSX1005"})}for(let c of e.matchAll(/\btype\s*(?=[{=])/g)){if(r.some((l)=>c.index>=l.start&&c.index<l.end))continue;let u=e.slice(0,c.index).trimEnd();if(u.endsWith("import")||u.endsWith("export"))continue;t.push({...ir(e,c.index),message:"Declaration name expected",code:"DTSX1005"})}return t.sort((c,u)=>c.line-u.line||c.column-u.column)}var xl=()=>{};import{statSync as Wd}from"fs";import{readFile as Nd,readdir as py}from"fs/promises";import{createRequire as Fd}from"module";import{dirname as Pd,isAbsolute as El,join as Dd,resolve as Ol}from"path";import Md from"process";function fs(){return`${String.fromCharCode(47,47,35)} sourceMappingURL=`}async function vr(e,t,r="lf"){let n=t.replace(/\r\n/g,`
208
+ `;return r}}function Dd(e,t,r={}){return $l(e,t,r,new WeakMap)}function $l(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 El(e,t,i,n);if(!tt(t)||!tt(e))return t;return Wd(e,t,r,n)}function El(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 Fd(e,t);case"smart":return Nd(e,t,n);default:return t}return t}function Fd(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Xn(i,n)))r.push(n);return r}function Nd(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(tt(t[0])&&tt(e[0]))return Ld(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 Ld(e,t,r){let n=[...t];for(let i of e){if(!tt(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)=>tt(c)&&(o in c)&&c[o]===i[o])){a=!0;break}}if(!a)n.push(i)}return n}function Wd(e,t,r,n){let i=t;if(tt(i)&&n.has(i))return n.get(i);let s={...e};if(tt(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(tt(o)&&tt(c))s[a]=$l(c,o,r,n);else if(Array.isArray(o)||Array.isArray(c))s[a]=El(c,o,r.arrayMergeMode||"smart",n);else s[a]=o}return s}function vl(e,t,r="replace"){return Dd(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Xn(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(!Xn(e[r],t[r]))return!1;return!0}if(tt(e)&&tt(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(!Xn(e[i],t[i]))return!1}return!0}return!1}function tt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class bl{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=Ei.getWithFileCheck("file",e);if(f){if(o)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!ci(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,g="default"in u,h=Object.keys(u).length>0;if(!g&&!h)throw new Oi(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new Oi(e,Error("Configuration must export a valid object"),"unknown");let w={config:vl(t,l,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)Ei.setWithFileCheck("file",w,e,s);return w}catch(f){throw f instanceof Error?rr.configLoad(e,f):rr.configLoad(e,Error(String(f)))}};if(a)return zn.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(Dn(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 Id(async()=>{return ci(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!ci(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=Dn(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=Dn(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(!ci(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 Sl{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(h){return u.push({path:"",message:`Validation failed: ${h}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(o)return await zn.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!wh(t))throw new Pi(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 Pi(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:Gd},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function Bd(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 Al{fileLoader=new bl;envProcessor=new os;validator=new Sl;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||ki.cwd(),g=[],h=await this.loadLocalConfiguration(n,i,l,a,o,f,u,c,r);if(h)return g.push(...this.getLocalSearchPaths(n,i,l,a)),this.finalizeResult(h,g,c,n,u);let w=await this.loadHomeConfiguration(n,i,o,f,u,c);if(w)return g.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(w,g,c,n,u);let v=await this.loadPackageJsonConfiguration(n,i,l,o,f,u,c);if(v)return g.push(Qe(l,"package.json")),this.finalizeResult(v,g,c,n,u);if(g.push(...this.getAllSearchPaths(n,i,l,a)),t)throw rr.configNotFound(n,g,i);return{...await this.applyEnvironmentVariables(n,o,c,u),warnings:[`No configuration file found for "${n}"${Bd(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,a,o,c){let f=o?ui(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),h=await this.fileLoader.tryLoadFromPaths(g,f,{arrayStrategy:s,verbose:a,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(h){if(a)mt.success(`Configuration loaded from: ${h.source.path}`);return h}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let a=s?ui(e,r,i):r,o=[Qe(jt(),".config",e),Qe(jt(),".config"),jt()];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?ui(e,n,s):n;try{let c=Qe(r,"package.json");if(!Iu(c))return null;let f={};try{f=JSON.parse(Du(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 h of g){if(!h)continue;if(f[h]){u=f[h],l=h;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)mt.success(`Configuration loaded from package.json: ${l}`);return{config:vl(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:ui(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 rr.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Ei.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);Ei.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,Qe(e,"config"),Qe(e,".config"),t?Qe(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(Qe(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=[Qe(jt(),".config",e),Qe(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 ui(e,t,r=!1){let n=new os,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("")}`],h,w;for(let v of g)if(h=ki.env[v],h!==void 0){w=v;break}if(h!==void 0&&w)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(h.toLowerCase());else if(typeof u==="number"){let v=Number(h);if(!Number.isNaN(v))c[f]=v}else if(Array.isArray(u))try{c[f]=JSON.parse(h)}catch{c[f]=h.split(",").map((v)=>v.trim())}else c[f]=h;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,l)}return c}return s(t)}var Ei,zn,$h,Eh=(e)=>e,bh=(e,t)=>{for(var r in t)$h(e,r,{get:t[r],enumerable:!0,configurable:!0,set:vh.bind(t,r)})},Sh=(e,t)=>()=>(e&&(t=e(e=0)),t),Yo,il,tr,vr,nl,Xh,zh,Mo,di,Hn,Ge,me,Qh,Io,ed,Do,td,rd,Fn,id,Fo,No,Nn,nd,sd,ad,od,mi,sl,ld,Be,cd,fd,Lo,pi,jn,Me,ee,ud,Wo,hd,Go,dd,md,Ln,pd,Bo,Vo,gd,Wn,yd,Cd,wd,$d,Ed,gi,al,vd,bd="0.15.6",Ue,xi,$r,Kn,Jn,Ti,Un,Yn,Er,Zn,qn,xt,ol,ll,it,Ct,cl,fl,Sd,xd,ul,Ri,Xg,Le,te,zg,Rd,Qg,Od,ey,ty,_o,ry,Pd,kd,iy,Ho,ny,sy,ay,oy,ly,Gn,Md,cy,nt,dl,Oi,ml,pl,as,gl,yl,Pi,Cl,wl,rr,Gd,mt,fy,uy,hy,Vd,xl;var Tl=ae(()=>{Ei=new Jo,zn=new Uo,$h=Object.defineProperty;Yo={};bh(Yo,{withErrorRecovery:()=>Xo,tryLoadConfig:()=>Uh,loadConfigWithResult:()=>Kh,loadConfig:()=>rl,isRetryableError:()=>Gh,isConfigNotFoundError:()=>Wh,isBunfigError:()=>zo,globalPerformanceMonitor:()=>vr,globalCache:()=>tr,getEnvOrDefault:()=>Bh,generateConfigTypes:()=>Yh,defaultGeneratedDir:()=>fl,defaultConfigDir:()=>cl,deepMergeWithArrayStrategy:()=>is,deepMerge:()=>Qo,createLibraryConfig:()=>Zh,config:()=>Jh,bunfigPlugin:()=>qh,applyEnvVarsToConfig:()=>Cr,TypeGenerationError:()=>Yn,SchemaValidationError:()=>Er,PluginError:()=>qn,PerformanceMonitor:()=>es,FileSystemError:()=>Un,ErrorFactory:()=>xt,EnvVarError:()=>Ti,EnvProcessor:()=>Mi,ConfigValidator:()=>ns,ConfigValidationError:()=>Kn,ConfigNotFoundError:()=>xi,ConfigMergeError:()=>Jn,ConfigLoader:()=>ss,ConfigLoadError:()=>$r,ConfigFileLoader:()=>Ii,ConfigCache:()=>Qn,CacheUtils:()=>nl,BunfigError:()=>Ue,BrowserConfigError:()=>Zn,ArrayMergeStrategies:()=>ol});Sd=Sh(async()=>{il=import.meta.require,tr=new Qn,vr=new es,nl={createKey:Ah,isEquivalent:xh,estimateMemoryUsage:Th},Xh=wi(Vn.cwd(),"config"),zh=wi(Vn.cwd(),"src/generated"),Mo=Ci.env.CLARITY_LOG_DIR||Bu(Ph(),"logs"),di={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Mo,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Hn=await kh(),Ge={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"},me=Ge,Qh=Ge.red,Io=Ge.green,ed=Ge.yellow,Do=Ge.blue,td=Ge.magenta,rd=Ge.cyan,Fn=Ge.white,id=Ge.gray,Fo=Ge.bgRed,No=Ge.bgYellow,Nn=Ge.bold,nd=Ge.dim,sd=Ge.italic,ad=Ge.underline,od=Ge.reset,mi={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},sl={debug:"\uD83D\uDD0D",info:Do("\u2139"),success:Io("\u2713"),warning:No(Fn(Nn(" WARN "))),error:Fo(Fn(Nn(" ERROR ")))},ld=new bi("stacks"),Be=new bi("bunfig",{showTags:!0}),cd=He(wr.cwd(),"config"),fd=He(wr.cwd(),"src/generated"),Lo=yi.env.CLARITY_LOG_DIR||Wu(Fh(),"logs"),pi={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Lo,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},jn=await Nh(),Me={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=Me,ud=Me.red,Wo=Me.green,hd=Me.yellow,Go=Me.blue,dd=Me.magenta,md=Me.cyan,Ln=Me.white,pd=Me.gray,Bo=Me.bgRed,Vo=Me.bgYellow,gd=Me.bgGray,Wn=Me.bold,yd=Me.dim,Cd=Me.italic,wd=Me.underline,$d=Me.strikethrough,Ed=Me.reset,gi={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},al={debug:"\uD83D\uDD0D",info:Go("\u2139"),success:Wo("\u2713"),warning:Vo(Ln(Wn(" WARN "))),error:Bo(Ln(Wn(" ERROR ")))},vd=new Ai("stacks"),Ue=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}`}},xi=class extends Ue{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})}},$r=class extends Ue{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}},Kn=class extends Ue{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Jn=class extends Ue{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}},Ti=class extends Ue{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})}},Un=class extends Ue{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}},Yn=class extends Ue{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}},Er=class extends Ue{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})}},Zn=class extends Ue{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})}},qn=class extends Ue{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 xi(e,t,r)},configLoad(e,t,r){return new $r(e,t,r)},configValidation(e,t,r){return new Kn(e,t,r)},configMerge(e,t,r,n){return new Jn(e,t,r,n)},envVar(e,t,r,n){return new Ti(e,t,r,n)},fileSystem(e,t,r){return new Un(e,t,r)},typeGeneration(e,t,r){return new Yn(e,t,r)},schemaValidation(e,t,r){return new Er(e,t,r)},browserConfig(e,t,r,n){return new Zn(e,t,r,n)},plugin(e,t,r){return new qn(e,t,r)}},ol={replace:"replace",concat:"concat",smart:"smart"},ll=/^https?:\/\//,it=new Ai("bunfig",{showTags:!0}),Ct=new ss,cl=je(Mt.cwd(),"config"),fl=je(Mt.cwd(),"src/generated")});xd=$i.env.CLARITY_LOG_DIR||lh(Ad(),"logs"),ul={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:xd,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ri={...ul},Xg=(async()=>{try{let{loadConfig:e}=await Sd().then(()=>Yo),t=await e({name:"clarity",alias:"logging",defaultConfig:ul,cwd:$i.cwd()});if(t)Object.assign(Ri,t)}catch{}return Ri})();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"},te=Le,zg=Le.red,Rd=Le.green,Qg=Le.yellow,Od=Le.blue,ey=Le.magenta,ty=Le.cyan,_o=Le.white,ry=Le.gray,Pd=Le.bgRed,kd=Le.bgYellow,iy=Le.bgGray,Ho=Le.bold,ny=Le.dim,sy=Le.italic,ay=Le.underline,oy=Le.strikethrough,ly=Le.reset,Gn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Md={debug:"\uD83D\uDD0D",info:Od("\u2139"),success:Rd("\u2713"),warning:kd(_o(Ho(" WARN "))),error:Pd(_o(Ho(" ERROR ")))};cy=new Di("stacks");nt=class nt 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}`}};dl=class dl extends nt{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})}};Oi=class Oi extends nt{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}};ml=class ml extends nt{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};pl=class pl extends nt{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}};as=class as extends nt{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})}};gl=class gl extends nt{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}};yl=class yl extends nt{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}};Pi=class Pi extends nt{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})}};Cl=class Cl extends nt{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})}};wl=class wl extends nt{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}};rr={configNotFound(e,t,r){return new dl(e,t,r)},configLoad(e,t,r){return new Oi(e,t,r)},configValidation(e,t,r){return new ml(e,t,r)},configMerge(e,t,r,n){return new pl(e,t,r,n)},envVar(e,t,r,n){return new as(e,t,r,n)},fileSystem(e,t,r){return new gl(e,t,r)},typeGeneration(e,t,r){return new yl(e,t,r)},schemaValidation(e,t,r){return new Pi(e,t,r)},browserConfig(e,t,r,n){return new Cl(e,t,r,n)},plugin(e,t,r){return new wl(e,t,r)}};Gd=/^https?:\/\//;mt=new Di("bunfig",{showTags:!0});fy=new Al;uy=Qe(ki.cwd(),"config"),hy=Qe(ki.cwd(),"src/generated"),Vd={cwd:Mu.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},xl=Vd});function ir(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 Rl(e){let t=[],r=[],n=[],i={")":"(","]":"[","}":"{"},s=0,a=0,o=-1;for(let f=0;f<e.length;f++){let u=e.charCodeAt(f),l=e.charCodeAt(f+1);if(o!==-1){if(u===42&&l===47)r.push({start:o,end:f+2}),o=-1,f++;continue}if(s){if(u===92)f++;else if(u===s)r.push({start:a,end:f+1}),s=0;continue}if(u===47&&l===42){o=f,f++;continue}if(u===47&&l===47){let h=f;while(f<e.length&&e.charCodeAt(f)!==10)f++;r.push({start:h,end:f});continue}if(u===39||u===34||u===96){s=u,a=f;continue}let g=e[f];if(g==="("||g==="["||g==="{")n.push({char:g,offset:f});else if(i[g]){let h=n.pop();if(!h||h.char!==i[g])t.push({...ir(e,f),message:`Unexpected closing delimiter ${g}`,code:"DTSX1004"})}}if(s)t.push({...ir(e,a),message:"Unterminated string literal",code:"DTSX1002"});if(o!==-1)t.push({...ir(e,o),message:"Unterminated block comment",code:"DTSX1003"});for(let f of n)t.push({...ir(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({...ir(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({...ir(e,f.index),message:"Declaration name expected",code:"DTSX1005"})}return t.sort((f,u)=>f.line-u.line||f.column-u.column)}var Ol=()=>{};import{statSync as _d}from"fs";import{readFile as Hd,readdir as ky}from"fs/promises";import{createRequire as jd}from"module";import{dirname as Kd,isAbsolute as Pl,join as Jd,resolve as kl}from"path";import Ud from"process";function cs(){return`${String.fromCharCode(47,47,35)} sourceMappingURL=`}async function br(e,t,r="lf"){let n=t.replace(/\r\n/g,`
204
209
  `);if(!n.endsWith(`
205
210
  `))n+=`
206
211
  `;if(r==="crlf")n=n.replace(/\n/g,`\r
207
- `);await Ss(e,n)}function Id(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+=`
208
- `;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 ls(e){let t=[e];if(!e.endsWith(".json"))t.push(`${e}.json`);t.push(Dd(e,"tsconfig.json"));for(let r of t)try{if(Wd(r).isFile())return r}catch{}return null}function Bd(e,t){if(El(e)||e.startsWith("."))return ls(Ol(Pd(t),e));let r=Fd(t);for(let n of[e,`${e}/tsconfig.json`])try{let i=ls(r.resolve(n));if(i)return i}catch{}return null}async function kl(e,t){let r=ls(e);if(!r||t.has(r))return;t.add(r);let n=await Nd(r,"utf8"),i=JSON.parse(Id(n)),s=typeof i.extends==="string"?[i.extends]:i.extends??[],o;for(let a of s){let f=Bd(a,r);if(!f)continue;let c=await kl(f,t);if(c!==void 0)o=c}return i.compilerOptions?.isolatedDeclarations??o}async function Sl(e){try{let t=e?.cwd||Md.cwd(),r=e?.tsconfigPath||"tsconfig.json",n=El(r)?r:Ol(t,r);return await kl(n,new Set)??!1}catch{return!1}}function Tl(e,t){let r={isValid:!0,errors:[]};for(let n of vl(e))r.errors.push({line:n.line,column:n.column,message:n.message,code:n.code});return r.isValid=r.errors.length===0,r}function Rl(e,t,r){if(e===t)return"";let n=e.split(`
212
+ `);await Os(e,n)}function Yd(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+=`
213
+ `;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 a=e.charCodeAt(s);if(a===93||a===125){r++;continue}}t+=e[r++]}return t}function ls(e){let t=[e];if(!e.endsWith(".json"))t.push(`${e}.json`);t.push(Jd(e,"tsconfig.json"));for(let r of t)try{if(_d(r).isFile())return r}catch{}return null}function Zd(e,t){if(Pl(e)||e.startsWith("."))return ls(kl(Kd(t),e));let r=jd(t);for(let n of[e,`${e}/tsconfig.json`])try{let i=ls(r.resolve(n));if(i)return i}catch{}return null}async function Ml(e,t){let r=ls(e);if(!r||t.has(r))return;t.add(r);let n=await Hd(r,"utf8"),i=JSON.parse(Yd(n)),s=typeof i.extends==="string"?[i.extends]:i.extends??[],a;for(let o of s){let c=Zd(o,r);if(!c)continue;let f=await Ml(c,t);if(f!==void 0)a=f}return i.compilerOptions?.isolatedDeclarations??a}async function Il(e){try{let t=e?.cwd||Ud.cwd(),r=e?.tsconfigPath||"tsconfig.json",n=Pl(r)?r:kl(t,r);return await Ml(n,new Set)??!1}catch{return!1}}function Dl(e,t){let r={isValid:!0,errors:[]};for(let n of Rl(e))r.errors.push({line:n.line,column:n.column,message:n.message,code:n.code});for(let n of Xa(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 Fl(e,t,r){if(e===t)return"";let n=e.split(`
209
214
  `),i=t.split(`
210
- `),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=[],f=[];for(let[u,l]of s){let p=l-(o.get(u)??0);for(let h=0;h<p;h++)a.push(u)}for(let[u,l]of o){let p=l-(s.get(u)??0);for(let h=0;h<p;h++)f.push(u)}if(a.length===0&&f.length===0)return"";let c=[`--- ${r}`,`+++ ${r}`];for(let u=0;u<a.length;u++)c.push(`- ${a[u]}`);for(let u=0;u<f.length;u++)c.push(`+ ${f[u]}`);return c.join(`
211
- `)}function Wl(e,t,r,n){let i=e.split(`
212
- `),s=[];function o(l){let p="",h=l<0?-l<<1|1:l<<1;do{let w=h&31;if(h>>>=5,h>0)w|=32;p+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[w]}while(h>0);return p}let a=0,f=0,c=0,u=n.split(`
213
- `).length;for(let l=0;l<i.length;l++){if(i[l].trim()===""){s.push("");continue}a=0;let p=Math.min(l,u-1),h=[],w=0-a,A=0,$=p-f,O=0-c;h.push(o(w)+o(A)+o($)+o(O)),a=0,f=p,c=0,s.push(h.join(","))}return{version:3,file:t,sourceRoot:"",sources:[r],sourcesContent:[n],mappings:s.join(";")}}function Nl(e,t){return`${e}
214
- ${fs()}${t}
215
- `}var Fl=de(()=>{Rr();xl()});import{mkdir as cs,readdir as Ld,realpath as jd,rm as _d}from"fs/promises";import{availableParallelism as Jd}from"os";import{basename as Il,dirname as Er,extname as Kd,isAbsolute as ds,parse as Hd,relative as Pe,resolve as tt}from"path";async function Pl(e,t,r,n,i){let s=Il(e)||"output.d.ts",o=Pe(Er(e),t),a=`${s}.map`,f=r.lastIndexOf(`
216
- ${fs()}`),c=f===-1?r:r.slice(0,f),u=Wl(c,s,o,n),l=`${e}.map`;return await vr(l,JSON.stringify(u)),K.debug(` Generated source map: ${Pe(i,l)}`),a}async function Mi(e){let t=Date.now(),r={...bl,...e};if(r.logLevel)Cn(r.logLevel);else if(r.verbose)Cn("debug");let n=new Fr;if(r.plugins&&r.plugins.length>0){for(let $ of r.plugins)n.register($),K.debug(`Registered plugin: ${$.name}`);r=await n.runOnStart(r)}if(await Gd(r),r.isolatedDeclarations===void 0)r.isolatedDeclarations=await Sl(r);let i=r.typeMappings?qr(r.typeMappings):void 0,s=null;if(r.incremental){if(s=new wn(r),r.clearCache){if(K.debug("Clearing build cache..."),!r.dryRun)s.clear()}else if(s.load()){let $=s.getStats();K.debug(`Loaded build cache with ${$.entries} entries`)}else K.debug("No existing build cache found, starting fresh");if(!r.dryRun)So(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 Zd(r);let f=await qd(r),c=f.slice(),u=null;if(r.autoIncludeReExports!==!1&&c.length>0){u=await Zi(c,{includeImports:!0});let $=tt(r.cwd,r.root),O=r.exclude||[],T=[];for(let S of u.reachable){if(c.includes(S))continue;if(!hs(S))continue;if(S.endsWith(".d.ts"))continue;if(S.includes("node_modules"))continue;if(!Di(S,$)){K.warn(`Skipping auto-included source outside root: ${Pe(r.cwd,S)}`);continue}if(us(S,O,$))continue;T.push(S)}if(T.length>0)c=[...c,...T],K.debug(`Auto-included ${T.length} file(s) reached via relative re-exports`)}if(Ud(c,r),s&&!r.dryRun){let $=s.prune(new Set(c),r.cwd);if($>0)K.debug(`Pruned ${$} deleted files from cache`)}if(K.debug(`Found ${c.length} TypeScript files`),r.progress&&c.length>0){let $=r.parallel?"parallel":"sequential";K.info(`Processing ${c.length} files (${$})...`)}let l=async($,O)=>{let T;try{let S=Or($,r),W=async(q)=>{if(!r.diff)return;try{let V=await ct(S),Y=Rl(V,q,Pe(r.cwd,S));if(Y)K.info(`
217
- ${Y}`);else K.debug(`[no changes] ${S}`)}catch{K.info(`[new file] ${Pe(r.cwd,S)}`)}},b=(q)=>{if(!r.validate)return 0;let V=Tl(q,S);if(V.isValid)return K.debug(`[validation] ${S} - OK`),0;K.warn(`[validation] ${Pe(r.cwd,S)} has ${V.errors.length} error(s):`);for(let Y of V.errors){let we=` Line ${Y.line}:${Y.column}`;if(Y.code)we+=` [${Y.code}]`;if(we+=` - ${Y.message}`,K.warn(we),Y.suggestion)K.warn(` Suggestion: ${Y.suggestion}`)}return V.errors.length},L=(q)=>{K.info(`[dry-run] Would generate: ${S}`),K.debug("--- Content preview ---"),K.debug(q.slice(0,500)+(q.length>500?`
218
- ...`:"")),K.debug("--- End preview ---")};if(s){let q=s.getCachedIfValid($,r.cwd);if(q){await W(q);let V=b(q);if(r.dryRun)L(q);else{if(await cs(Er(S),{recursive:!0}),r.declarationMap)T=O??await ct($),await Pl(S,$,q,T,r.cwd);await vr(S,q,r.lineEnding)}return K.debug(`[cached] ${Pe(r.cwd,S)}`),{success:!0,file:$,declarationCount:0,importCount:0,exportCount:0,cached:!0,validationErrorCount:V}}}T=O??await ct($);let{content:re,declarationCount:F,importCount:J,exportCount:X}=await Qd($,T,r,n,i),se=re;if(r.prettier||r.indentStyle||r.indentSize){let q=await Po(se,{usePrettier:r.prettier,builtIn:{indentSize:r.indentSize||2,useTabs:r.indentStyle==="tabs",normalizeWhitespace:!0,sortImports:!0,trailingNewline:!0}},S);se=q.content;for(let V of q.warnings??[])K.warn(`[format] ${V}`)}if(r.declarationMap){let q=`${Il(S)||"output.d.ts"}.map`;se=Nl(se,q)}await W(se);let H=b(se);if(r.dryRun)L(se);else{if(await cs(Er(S),{recursive:!0}),r.declarationMap&&T)await Pl(S,$,se,T,r.cwd);if(await vr(S,se,r.lineEnding),s&&T)s.update($,T,se,r.cwd);K.debug(`Generated: ${S}`)}return{success:!0,file:$,declarationCount:F,importCount:J,exportCount:X,validationErrorCount:H}}catch(S){let W=Mo(S,$,T);if(r.plugins&&r.plugins.length>0)await n.runOnError(S instanceof Error?S:Error(String(S)),$,T||"");return{success:!1,file:$,declarationCount:0,importCount:0,exportCount:0,dtsError:W,validationErrorCount:0}}},p=r.parallel||r.parallel!==!1&&c.length>=10,h=wo(r.concurrency,Jd?.()??8),w=new Map;if(p&&c.length>1){let $=c.map(async(O)=>{try{let T=await ct(O);return{file:O,source:T}}catch{return{file:O,source:null}}});for(let O of await Promise.all($))if(O.source!==null)w.set(O.file,O.source)}let A=($)=>{if(o.filesProcessed++,$.success){if($.cached)a++;else o.filesGenerated++,o.declarationsFound+=$.declarationCount,o.importsProcessed+=$.importCount,o.exportsProcessed+=$.exportCount;if(r.validate){if(o.filesValidated++,$.validationErrorCount)o.validationErrors+=$.validationErrorCount}}else if(o.filesFailed++,$.dtsError){o.errors.push($.dtsError);let O=Io($.dtsError);if(r.continueOnError)K.warn(O);else throw K.error(O),Error($.dtsError.message)}};if(p)for(let $=0;$<c.length;$+=h){let O=c.slice($,$+h),T=await Promise.all(O.map((S)=>l(S,w.get(S))));for(let S of T)A(S);if(r.progress){let S=Math.round(o.filesProcessed/c.length*100);K.info(`[${o.filesProcessed}/${c.length}] ${S}%`)}}else for(let $ of c){let O=await l($);if(A(O),r.progress){let T=Math.round(o.filesProcessed/c.length*100),S=O.cached?"[cached]":"";K.info(`[${o.filesProcessed}/${c.length}] ${T}% - ${Pe(r.cwd,$)} ${S}`)}}if(s&&!r.dryRun)s.save(),K.debug("Saved build cache");if(!r.bundle){let $=[];if(u)for(let O of u.unresolved)$.push({from:O.from,specifier:O.specifier,reason:"missing"});if(r.autoIncludeReExports===!1&&c.length>0){let O=new Set(c);for(let T of c){let S;try{S=await ct(T)}catch{continue}for(let W of Vi(S)){if(!W.specifier.startsWith("."))continue;let b=Nr(W.specifier,T);if(!b.resolved)$.push({from:T,specifier:W.specifier,reason:"missing"});else if(!/\.d\.(?:ts|mts|cts)$/.test(b.resolved)&&!O.has(b.resolved))$.push({from:T,specifier:W.specifier,reason:"not-emitted"})}}}if($.length>0){let O=[];O.push(`Found ${$.length} re-export(s) pointing at siblings that won't be in the output:`);for(let S of $){let W=Pe(r.cwd,S.from);if(S.reason==="missing")O.push(` ${W} \u2192 '${S.specifier}' (path not found on disk)`);else O.push(` ${W} \u2192 '${S.specifier}' (resolved but not in entrypoints; set autoIncludeReExports: true or add to entrypoints)`)}let T=O.join(`
219
- `);if(r.failOnUnresolvedReExport)throw Error(T);K.warn(T),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)&&f.length>0)try{K.debug("Bundling declarations...");let $=new Map,O=async(S)=>{let W=$.get(S);if(W!==void 0)return W;return W=await ct(S),$.set(S,W),W};for(let S of c)await O(S);let T=f.length===1&&!!r.bundleOutput;for(let S of f){let W=await Zi([S],{includeImports:!0}),b=new Set;for(let X of W.reachable){if(X.endsWith(".d.ts"))continue;if(X.includes("node_modules"))continue;b.add(X)}let L=c.filter((X)=>b.has(X));if(!L.includes(S))L.push(S);let re=new Map;for(let X of L){let se=$.get(X)??await O(X);re.set(X,se)}let F=await bo(L,re,r),J=T?tt(r.cwd,r.outdir,r.bundleOutput):Or(S,r);if(r.dryRun)K.info(`[dry-run] Would bundle ${F.files.length} files to: ${Pe(r.cwd,J)}`);else await cs(Er(J),{recursive:!0}),await vr(J,F.content,r.lineEnding),K.info(`Bundled ${F.files.length} files to: ${Pe(r.cwd,J)}`);if(T)break}}catch($){let O=$ instanceof Error?$.message:String($);K.error(`Bundle failed: ${O}`)}if(o.durationMs=Date.now()-t,r.stats)if(r.outputFormat==="json")console.log(JSON.stringify(o,null,2));else{if(K.info(`
220
- --- 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(`
221
- Errors:`);for(let $ of o.errors){let O=` - ${$.file}`;if($.location)O+=`:${$.location.line}:${$.location.column}`;if($.code)O+=` [${$.code}]`;if(O+=`: ${$.message}`,K.info(O),$.suggestion)K.info(` Suggestion: ${$.suggestion}`)}}K.info(`-----------------------------
222
- `)}if(r.plugins&&r.plugins.length>0)await n.runOnEnd(o);return K.debug("DTS generation complete!"),o}async function Dl(e){try{return await jd(e)}catch{return tt(e)}}async function Gd(e){let t=tt(e.cwd,e.outdir);if(e.bundle&&e.bundleOutput){if(ds(e.bundleOutput))throw Error("bundleOutput must be relative to outdir");let i=tt(t,e.bundleOutput);if(!Di(i,t))throw Error("bundleOutput must stay within outdir")}if(!e.clean||e.dryRun)return;if(t===Hd(t).root)throw Error("Refusing to clean declarations from the filesystem root");let[r,n]=await Promise.all([Dl(t),Dl(tt(e.cwd,e.root))]);if(Di(n,r))throw Error("Refusing to clean an outdir that contains the source root")}function Vd(e){let t=xr.get(e);if(!t){if(t=new Ml(e),xr.set(e,t),xr.size>Yd){let r=xr.keys().next().value;if(r!==void 0)xr.delete(r)}}return t}async function Zd(e){let t=tt(e.cwd,e.outdir);async function r(n){let i;try{i=await Ld(n,{withFileTypes:!0})}catch{return}await Promise.all(i.map(async(s)=>{let o=tt(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 _d(o,{force:!0})}))}await r(t)}function us(e,t,r){if(!t||t.length===0)return!1;let n=Pe(r,e);for(let i of t){let s=Vd(i);if(s.match(n)||s.match(e))return!0}return!1}async function qd(e){let t=[],r=tt(e.cwd,e.root),n=e.exclude||[],i=[...e.entrypoints,...e.include??[]];for(let s of i)if(ds(s)&&hs(s)){if(!s.includes("node_modules")){if(!Di(s,r)&&e.outputStructure!=="flat")K.warn(`Skipping entrypoint outside root: ${Pe(e.cwd,s)}`);else if(!us(s,n,r))t.push(s)}}else{let o=new Ml(s);for await(let a of o.scan({cwd:r,absolute:!0,onlyFiles:!0}))if(hs(a)&&!a.includes("node_modules")){if(!us(a,n,r))t.push(a)}}return[...new Set(t)].sort()}function Di(e,t){let r=Pe(t,e);return r!==".."&&!r.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!ds(r)}function Ud(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: ${Pe(t.cwd,s)} and ${Pe(t.cwd,n)} both emit ${Pe(t.cwd,i)}`);r.set(i,n)}}function hs(e){return/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/.test(e)&&!/\.d\.(?:ts|mts|cts)$/.test(e)}function Or(e,t){let r=tt(t.cwd,t.root),n=Pe(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 tt(t.cwd,t.outdir,n);else{let i=n.split("/").pop();return tt(t.cwd,t.outdir,i)}}function Xd(e,t,r=""){let n=Pe(Er(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 zd(e,t,r){let n=Or(t,r),i=(s)=>{let o=Nr(s,t);if(!o.isRelative||!o.resolved)return s;if(/\.d\.(?:ts|mts|cts)$/.test(o.resolved))return s;let a=s.match(/[?#].*$/)?.[0]??"",f=a?s.slice(0,-a.length):s,c=Kd(f),u=/^(?:\.js|\.jsx|\.mjs|\.cjs)$/.test(c)?c:"";return Xd(n,Or(o.resolved,r),u)+a};return e.replace(/\b(from\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,o,a,f)=>{return`${o}${a}${i(f)}${a}`}).replace(/\b(import\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,o,a,f)=>{return`${o}${a}${i(f)}${a}`}).replace(/\b(import\s*\(\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,o,a,f)=>{return`${o}${a}${i(f)}${a}`})}async function Qd(e,t,r,n,i){let s=t;if(n)s=await n.runOnBeforeFile(e,t);let o=Gr(s,e,r.keepComments,r.isolatedDeclarations??!1);if(n)o=await n.runOnDeclarations(e,s,o);let a=0,f=0;for(let u=0;u<o.length;u++){let l=o[u];if(l.kind==="import")a++;if(l.kind==="export"||l.isExported)f++}let c=Vo(o,{filePath:e,sourceCode:s,declarations:o},r.keepComments,r.importOrder);if(c=zd(c,e,r),i)c=No(c,i,{filePath:e});if(r.normalizeOutput===!0||r.declarationOrder)c=Ds(c,{lineEnding:"lf",declarationOrder:r.declarationOrder,indent:{style:r.indentStyle??"spaces",size:r.indentSize??2}});if(n)c=await n.runOnAfterFile(e,s,c);return{content:c,declarationCount:o.length,importCount:a,exportCount:f}}var Ml,Yd=50,xr;var Bl=de(()=>{Ns();Ms();Is();vo();To();Fo();Do();Bo();Zo();pn();Co();Fl();Rr();Al();zo();({Glob:Ml}=globalThis.Bun);xr=new Map});var Ll=de(()=>{Bl()});var Gl={};lf(Gl,{dtsWatch:()=>cm,dtsCheck:()=>um,dts:()=>gs,default:()=>dm,clearCache:()=>hm,PluginErrorCodes:()=>am,DtsxPluginError:()=>sr});import{createHash as tm}from"crypto";import{existsSync as rm,readFileSync as im,writeFileSync as nm}from"fs";import{dirname as sm,join as om,relative as jl,resolve as nr,sep as Ii}from"path";import Jl from"process";class Kl{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 ms{manifest;cacheDir;manifestPath;constructor(e,t){this.cacheDir=e,this.manifestPath=om(e,"manifest.json"),this.manifest=this.loadManifest(t)}loadManifest(e){try{if(rm(this.manifestPath)){let t=JSON.parse(im(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}=em("fs");e(this.cacheDir,{recursive:!0}),nm(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 lm(e){let t={root:e.root,outdir:e.outdir,entrypoints:e.entrypoints,clean:e.clean,tsconfigPath:e.tsconfigPath};return tm("md5").update(JSON.stringify(t)).digest("hex")}function gs(e={}){let{onSuccess:t,onError:r,failOnError:n=!0,incremental:i=!1,cacheDir:s=".dtsx-cache",on:o,timeout:a=60000,continueOnError:f=!1,verbose:c=!1,...u}=e,l=new Kl;if(o){for(let[p,h]of Object.entries(o))if(h)l.on(p,h)}return{name:"bun-plugin-dtsx",async setup(p){let h=Date.now(),w=null,A=0;try{let $=Yl(u,p),O=lm($);if($.clean){let b=nr($.cwd??Jl.cwd(),$.outdir??"./dist");if(_l.has(b))$.clean=!1;else _l.add(b)}if(i)w=new ms(nr(s),O);if(await l.emit("start",{type:"start",files:$.entrypoints||[],config:$}),c){if(console.log("[bun-plugin-dtsx] Starting declaration generation..."),i)console.log("[bun-plugin-dtsx] Incremental mode enabled")}let S=await(async()=>{return new Promise((b,L)=>{let re=setTimeout(()=>{L(new sr(`Generation timed out after ${a}ms`,"TIMEOUT_ERROR",{timeout:a}))},a);Mi($).then((F)=>{clearTimeout(re),b(F)}).catch((F)=>{clearTimeout(re),L(F)})})})(),W=Date.now()-h;if(w)w.save();if(await l.emit("complete",{type:"complete",stats:S,duration:W,fromCache:A}),c){if(console.log(`[bun-plugin-dtsx] Generation complete in ${W}ms`),A>0)console.log(`[bun-plugin-dtsx] ${A} files served from cache`)}if(t)await t(S)}catch($){let O=Hl($);if(await l.emit("error",{type:"error",error:O}),r)await r(O);else{if(console.error("[bun-plugin-dtsx] Error generating declarations:"),console.error(` Code: ${O.code}`),console.error(` Message: ${O.message}`),O.context)console.error(` Context: ${JSON.stringify(O.context)}`);if(c&&O.stack)console.error(` Stack: ${O.stack}`)}if(n&&!f)throw O}}}}function Hl(e){if(e instanceof sr)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 sr(e.message,t,{originalError:e.name},e)}return new sr(String(e),"GENERATION_ERROR")}function fm(e){let t=e.map((n)=>sm(n).split(Ii)),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(Ii)||Ii}function Yl(e,t){let r=e.cwd||Jl.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=fm(n.map((f)=>nr(r,f)));s=jl(r,a)||"."}s=s||"./src";let o=e.entrypoints;if(!o)if(n?.length){let a=nr(r,s),f=[];for(let c of n){let u=nr(r,c);if(u===a||u.startsWith(a+Ii))f.push(jl(a,u));else console.warn(`[bun-plugin-dtsx] Skipping entrypoint outside root "${s}": ${c}`)}o=f.length?f:["index.ts"]}else o=["index.ts"];return{...e,cwd:r,root:s,entrypoints:o,outdir:i,clean:e.clean??!0,tsconfigPath:e.tsconfigPath}}function cm(e={}){return gs({...e,incremental:!0,verbose:e.verbose??!0})}function um(e){return{name:"bun-plugin-dtsx-check",async setup(t){let r=Yl({...e,outdir:""},t);try{await Mi({...r,clean:!1})}catch(n){let i=Hl(n);if(e.onError)await e.onError(i);if(e.failOnError!==!1)throw i}}}}function hm(e=".dtsx-cache"){new ms(nr(e),"").clear()}var em,am,sr,_l,dm;var Vl=de(()=>{Ll();em=import.meta.require,am={CONFIG_ERROR:"CONFIG_ERROR",GENERATION_ERROR:"GENERATION_ERROR",FILE_ERROR:"FILE_ERROR",CACHE_ERROR:"CACHE_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR"};sr=class sr 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}}};_l=new Set;dm=gs});import{mkdir as mm,stat as gm}from"fs/promises";import{bold as ps,dim as ys,green as pm,italic as Zl,log as ym}from"@stacksjs/cli";import{path as st}from"@stacksjs/path";import{glob as ql}from"@stacksjs/storage";async function $m(e){let t=await ql([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 o0(e){let r=Date.now()-e.startTime,n=e.pkgName??`@stacksjs/${st.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 $m(e.dir);let i=await ql([st.resolve(e.dir,"dist","**/*")],{absolute:!0});for(let s of i){let o=await gm(s),a;if(o.size<1048576)a=`${(o.size/1024).toFixed(2)}kb`;else a=`${(o.size/1024/1024).toFixed(2)}mb`;let f=st.relative(e.dir,s).replace("dist/","");console.log(`${ps(ys(`[${a}]`))} ${ys("dist/")}${f}`)}console.log(`${ps(ys(`[${r}ms]`))} Built ${Zl(ps(pm(n)))}`)}async function a0(e){let t=e.pkgName??`@stacksjs/${st.basename(e.dir)}`;if(e.styled===!1)console.log(`Building ${t}...`);else ym.info(`Building ${Zl(t)}...`);return{startTime:Date.now()}}async function l0(e){let{dts:t}=await Promise.resolve().then(() => (Vl(),Gl)),r=st.resolve(e.dir,"src"),n=st.resolve(e.dir,"dist"),i=(await Array.fromAsync(new Bun.Glob("**/*.ts").scan({cwd:r}))).filter((o)=>!o.endsWith(".d.ts"));await Bun.build({entrypoints:i.map((o)=>st.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(st.resolve(r,o)).text());a=a.replace(/(['"])(\.\.?\/[^'"]+?)\.tsx?\1/g,"$1$2.js$1");let f=st.resolve(n,o.replace(/\.ts$/,".js"));await mm(st.dirname(f),{recursive:!0}),await Bun.write(f,a)}}function wm(e=[]){let t=[];try{let r=Ze("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,"bun-queue","ioredis","localtunnels","localtunnels/*","@craft-native/ts","ts-md","meilisearch","algoliasearch","@opensearch-project/opensearch","*.yaml","*.yml",...e]}export{$m as validateDeclarations,l0 as transpilePackage,o0 as outro,a0 as intro,wm as frameworkExternal};
215
+ `),s=new Map,a=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++)a.set(i[u],(a.get(i[u])??0)+1);let o=[],c=[];for(let[u,l]of s){let g=l-(a.get(u)??0);for(let h=0;h<g;h++)o.push(u)}for(let[u,l]of a){let g=l-(s.get(u)??0);for(let h=0;h<g;h++)c.push(u)}if(o.length===0&&c.length===0)return"";let f=[`--- ${r}`,`+++ ${r}`];for(let u=0;u<o.length;u++)f.push(`- ${o[u]}`);for(let u=0;u<c.length;u++)f.push(`+ ${c[u]}`);return f.join(`
216
+ `)}function Nl(e,t,r,n){let i=e.split(`
217
+ `),s=[];function a(l){let g="",h=l<0?-l<<1|1:l<<1;do{let w=h&31;if(h>>>=5,h>0)w|=32;g+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[w]}while(h>0);return g}let o=0,c=0,f=0,u=n.split(`
218
+ `).length;for(let l=0;l<i.length;l++){if(i[l].trim()===""){s.push("");continue}o=0;let g=Math.min(l,u-1),h=[],w=0-o,v=0,C=g-c,x=0-f;h.push(a(w)+a(v)+a(C)+a(x)),o=0,c=g,f=0,s.push(h.join(","))}return{version:3,file:t,sourceRoot:"",sources:[r],sourcesContent:[n],mappings:s.join(";")}}function Ll(e,t){return`${e}
219
+ ${cs()}${t}
220
+ `}var Wl=ae(()=>{za();kr();Ol()});import{mkdir as fs,readdir as qd,realpath as Xd,rm as zd}from"fs/promises";import{availableParallelism as Qd}from"os";import{basename as _l,dirname as Ar,extname as em,isAbsolute as ds,parse as tm,relative as De,resolve as rt}from"path";async function Gl(e,t,r,n,i){let s=_l(e)||"output.d.ts",a=De(Ar(e),t),o=`${s}.map`,c=r.lastIndexOf(`
221
+ ${cs()}`),f=c===-1?r:r.slice(0,c),u=Nl(f,s,a,n),l=`${e}.map`;return await br(l,JSON.stringify(u)),H.debug(` Generated source map: ${De(i,l)}`),o}async function Ni(e){let t=Date.now(),r={...xl,...e};if(r.logLevel)$n(r.logLevel);else if(r.verbose)$n("debug");let n=new Or;if(r.plugins&&r.plugins.length>0){for(let C of r.plugins)n.register(C),H.debug(`Registered plugin: ${C.name}`);r=await n.runOnStart(r)}if(await im(r),r.isolatedDeclarations===void 0)r.isolatedDeclarations=await Il(r);let i=r.typeMappings?Zr(r.typeMappings):void 0,s=null;if(r.incremental){if(s=new wn(r),r.clearCache){if(H.debug("Clearing build cache..."),!r.dryRun)s.clear()}else if(s.load()){let C=s.getStats();H.debug(`Loaded build cache with ${C.entries} entries`)}else H.debug("No existing build cache found, starting fresh");if(!r.dryRun)Ta(r.cwd)}let a={generationMode:r.isolatedDeclarations?"isolated":"semantic",filesProcessed:0,filesGenerated:0,filesFailed:0,filesValidated:0,validationErrors:0,declarationsFound:0,importsProcessed:0,exportsProcessed:0,durationMs:0,errors:[]},o=0;if(H.debug("Starting DTS generation..."),H.debug(`Using ${a.generationMode} declaration generation path`),H.debug("Config:",r),r.clean&&!r.dryRun)await sm(r);let c=await am(r),f=c.slice(),u=null;if(r.autoIncludeReExports!==!1&&f.length>0){u=await Yi(f,{includeImports:!0});let C=rt(r.cwd,r.root),x=r.exclude||[],O=[];for(let R of u.reachable){if(f.includes(R))continue;if(!hs(R))continue;if(R.endsWith(".d.ts"))continue;if(R.includes("node_modules"))continue;if(!Fi(R,C)){H.warn(`Skipping auto-included source outside root: ${De(r.cwd,R)}`);continue}if(us(R,x,C))continue;O.push(R)}if(O.length>0)f=[...f,...O],H.debug(`Auto-included ${O.length} file(s) reached via relative re-exports`)}if(om(f,r),s&&!r.dryRun){let C=s.prune(new Set(f),r.cwd);if(C>0)H.debug(`Pruned ${C} deleted files from cache`)}if(H.debug(`Found ${f.length} TypeScript files`),r.progress&&f.length>0){let C=r.parallel?"parallel":"sequential";H.info(`Processing ${f.length} files (${C})...`)}let l=async(C,x)=>{let O;try{let R=xr(C,r),k=async(Z)=>{if(!r.diff)return;try{let U=await ct(R),K=Fl(U,Z,De(r.cwd,R));if(K)H.info(`
222
+ ${K}`);else H.debug(`[no changes] ${R}`)}catch{H.info(`[new file] ${De(r.cwd,R)}`)}},E=(Z)=>{if(!r.validate)return 0;let U=Dl(Z,R);if(U.isValid)return H.debug(`[validation] ${R} - OK`),0;H.warn(`[validation] ${De(r.cwd,R)} has ${U.errors.length} error(s):`);for(let K of U.errors){let we=` Line ${K.line}:${K.column}`;if(K.code)we+=` [${K.code}]`;if(we+=` - ${K.message}`,H.warn(we),K.suggestion)H.warn(` Suggestion: ${K.suggestion}`)}return U.errors.length},G=(Z)=>{H.info(`[dry-run] Would generate: ${R}`),H.debug("--- Content preview ---"),H.debug(Z.slice(0,500)+(Z.length>500?`
223
+ ...`:"")),H.debug("--- End preview ---")};if(s){let Z=s.getCachedIfValid(C,r.cwd);if(Z){await k(Z);let U=E(Z);if(r.dryRun)G(Z);else{if(await fs(Ar(R),{recursive:!0}),r.declarationMap)O=x??await ct(C),await Gl(R,C,Z,O,r.cwd);await br(R,Z,r.lineEnding)}return H.debug(`[cached] ${De(r.cwd,R)}`),{success:!0,file:C,declarationCount:0,importCount:0,exportCount:0,cached:!0,validationErrorCount:U}}}O=x??await ct(C);let{content:re,declarationCount:I,importCount:_,exportCount:X}=await fm(C,O,r,n,i),se=re;if(r.prettier||r.indentStyle||r.indentSize){let Z=await Ia(se,{usePrettier:r.prettier,builtIn:{indentSize:r.indentSize||2,useTabs:r.indentStyle==="tabs",normalizeWhitespace:!0,sortImports:!0,trailingNewline:!0}},R);se=Z.content;for(let U of Z.warnings??[])H.warn(`[format] ${U}`)}if(r.declarationMap){let Z=`${_l(R)||"output.d.ts"}.map`;se=Ll(se,Z)}await k(se);let j=E(se);if(r.dryRun)G(se);else{if(await fs(Ar(R),{recursive:!0}),r.declarationMap&&O)await Gl(R,C,se,O,r.cwd);if(await br(R,se,r.lineEnding),s&&O)s.update(C,O,se,r.cwd);H.debug(`Generated: ${R}`)}return{success:!0,file:C,declarationCount:I,importCount:_,exportCount:X,validationErrorCount:j}}catch(R){let k=Fa(R,C,O);if(r.plugins&&r.plugins.length>0)await n.runOnError(R instanceof Error?R:Error(String(R)),C,O||"");return{success:!1,file:C,declarationCount:0,importCount:0,exportCount:0,dtsError:k,validationErrorCount:0}}},g=r.parallel||r.parallel!==!1&&f.length>=10,h=Ca(r.concurrency,Qd?.()??8),w=new Map;if(g&&f.length>1){let C=f.map(async(x)=>{try{let O=await ct(x);return{file:x,source:O}}catch{return{file:x,source:null}}});for(let x of await Promise.all(C))if(x.source!==null)w.set(x.file,x.source)}let v=(C)=>{if(a.filesProcessed++,C.success){if(C.cached)o++;else a.filesGenerated++,a.declarationsFound+=C.declarationCount,a.importsProcessed+=C.importCount,a.exportsProcessed+=C.exportCount;if(r.validate){if(a.filesValidated++,C.validationErrorCount)a.validationErrors+=C.validationErrorCount}}else if(a.filesFailed++,C.dtsError){a.errors.push(C.dtsError);let x=Na(C.dtsError);if(r.continueOnError)H.warn(x);else throw H.error(x),Error(C.dtsError.message)}};if(g)for(let C=0;C<f.length;C+=h){let x=f.slice(C,C+h),O=await Promise.all(x.map((R)=>l(R,w.get(R))));for(let R of O)v(R);if(r.progress){let R=Math.round(a.filesProcessed/f.length*100);H.info(`[${a.filesProcessed}/${f.length}] ${R}%`)}}else for(let C of f){let x=await l(C);if(v(x),r.progress){let O=Math.round(a.filesProcessed/f.length*100),R=x.cached?"[cached]":"";H.info(`[${a.filesProcessed}/${f.length}] ${O}% - ${De(r.cwd,C)} ${R}`)}}if(s&&!r.dryRun)s.save(),H.debug("Saved build cache");if(!r.bundle){let C=[];if(u)for(let x of u.unresolved)C.push({from:x.from,specifier:x.specifier,reason:"missing"});if(r.autoIncludeReExports===!1&&f.length>0){let x=new Set(f);for(let O of f){let R;try{R=await ct(O)}catch{continue}for(let k of Ui(R)){if(!k.specifier.startsWith("."))continue;let E=Ir(k.specifier,O);if(!E.resolved)C.push({from:O,specifier:k.specifier,reason:"missing"});else if(!/\.d\.(?:ts|mts|cts)$/.test(E.resolved)&&!x.has(E.resolved))C.push({from:O,specifier:k.specifier,reason:"not-emitted"})}}}if(C.length>0){let x=[];x.push(`Found ${C.length} re-export(s) pointing at siblings that won't be in the output:`);for(let R of C){let k=De(r.cwd,R.from);if(R.reason==="missing")x.push(` ${k} \u2192 '${R.specifier}' (path not found on disk)`);else x.push(` ${k} \u2192 '${R.specifier}' (resolved but not in entrypoints; set autoIncludeReExports: true or add to entrypoints)`)}let O=x.join(`
224
+ `);if(r.failOnUnresolvedReExport)throw Error(O);H.warn(O),H.warn('Generated .d.ts files reference modules that were not emitted \u2014 consumers will see "has no exported member" errors.')}}if(r.bundle&&(a.filesGenerated>0||o>0)&&c.length>0)try{H.debug("Bundling declarations...");let C=new Map,x=async(R)=>{let k=C.get(R);if(k!==void 0)return k;return k=await ct(R),C.set(R,k),k};for(let R of f)await x(R);let O=c.length===1&&!!r.bundleOutput;for(let R of c){let k=await Yi([R],{includeImports:!0}),E=new Set;for(let X of k.reachable){if(X.endsWith(".d.ts"))continue;if(X.includes("node_modules"))continue;E.add(X)}let G=f.filter((X)=>E.has(X));if(!G.includes(R))G.push(R);let re=new Map;for(let X of G){let se=C.get(X)??await x(X);re.set(X,se)}let I=await $a(G,re,r),_=O?rt(r.cwd,r.outdir,r.bundleOutput):xr(R,r);if(r.dryRun)H.info(`[dry-run] Would bundle ${I.files.length} files to: ${De(r.cwd,_)}`);else await fs(Ar(_),{recursive:!0}),await br(_,I.content,r.lineEnding),H.info(`Bundled ${I.files.length} files to: ${De(r.cwd,_)}`);if(O)break}}catch(C){let x=C instanceof Error?C.message:String(C);H.error(`Bundle failed: ${x}`)}if(a.durationMs=Date.now()-t,r.stats)if(r.outputFormat==="json")console.log(JSON.stringify(a,null,2));else{if(H.info(`
225
+ --- Generation Statistics ---`),H.info(`Files processed: ${a.filesProcessed}`),H.info(`Files generated: ${a.filesGenerated}`),o>0)H.info(`Files cached: ${o}`);if(a.filesFailed>0)H.info(`Files failed: ${a.filesFailed}`);if(H.info(`Declarations found: ${a.declarationsFound}`),H.info(`Imports processed: ${a.importsProcessed}`),H.info(`Exports processed: ${a.exportsProcessed}`),a.filesValidated>0){if(H.info(`Files validated: ${a.filesValidated}`),a.validationErrors>0)H.info(`Validation errors: ${a.validationErrors}`)}if(H.info(`Duration: ${a.durationMs}ms`),a.errors.length>0){H.info(`
226
+ Errors:`);for(let C of a.errors){let x=` - ${C.file}`;if(C.location)x+=`:${C.location.line}:${C.location.column}`;if(C.code)x+=` [${C.code}]`;if(x+=`: ${C.message}`,H.info(x),C.suggestion)H.info(` Suggestion: ${C.suggestion}`)}}H.info(`-----------------------------
227
+ `)}if(r.plugins&&r.plugins.length>0)await n.runOnEnd(a);return H.debug("DTS generation complete!"),a}async function Bl(e){try{return await Xd(e)}catch{return rt(e)}}async function im(e){let t=rt(e.cwd,e.outdir);if(e.bundle&&e.bundleOutput){if(ds(e.bundleOutput))throw Error("bundleOutput must be relative to outdir");let i=rt(t,e.bundleOutput);if(!Fi(i,t))throw Error("bundleOutput must stay within outdir")}if(!e.clean||e.dryRun)return;if(t===tm(t).root)throw Error("Refusing to clean declarations from the filesystem root");let[r,n]=await Promise.all([Bl(t),Bl(rt(e.cwd,e.root))]);if(Fi(n,r))throw Error("Refusing to clean an outdir that contains the source root")}function nm(e){let t=Sr.get(e);if(!t){if(t=new Vl(e),Sr.set(e,t),Sr.size>rm){let r=Sr.keys().next().value;if(r!==void 0)Sr.delete(r)}}return t}async function sm(e){let t=rt(e.cwd,e.outdir);async function r(n){let i;try{i=await qd(n,{withFileTypes:!0})}catch{return}await Promise.all(i.map(async(s)=>{let a=rt(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 zd(a,{force:!0})}))}await r(t)}function us(e,t,r){if(!t||t.length===0)return!1;let n=De(r,e);for(let i of t){let s=nm(i);if(s.match(n)||s.match(e))return!0}return!1}async function am(e){let t=[],r=rt(e.cwd,e.root),n=e.exclude||[],i=[...e.entrypoints,...e.include??[]];for(let s of i)if(ds(s)&&hs(s)){if(!s.includes("node_modules")){if(!Fi(s,r)&&e.outputStructure!=="flat")H.warn(`Skipping entrypoint outside root: ${De(e.cwd,s)}`);else if(!us(s,n,r))t.push(s)}}else{let a=new Vl(s);for await(let o of a.scan({cwd:r,absolute:!0,onlyFiles:!0}))if(hs(o)&&!o.includes("node_modules")){if(!us(o,n,r))t.push(o)}}return[...new Set(t)].sort()}function Fi(e,t){let r=De(t,e);return r!==".."&&!r.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!ds(r)}function om(e,t){let r=new Map;for(let n of e){let i=xr(n,t),s=r.get(i);if(s&&s!==n)throw Error(`Output path collision: ${De(t.cwd,s)} and ${De(t.cwd,n)} both emit ${De(t.cwd,i)}`);r.set(i,n)}}function hs(e){return/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/.test(e)&&!/\.d\.(?:ts|mts|cts)$/.test(e)}function xr(e,t){let r=rt(t.cwd,t.root),n=De(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 rt(t.cwd,t.outdir,n);else{let i=n.split("/").pop();return rt(t.cwd,t.outdir,i)}}function lm(e,t,r=""){let n=De(Ar(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 cm(e,t,r){let n=xr(t,r),i=(s)=>{let a=Ir(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=em(c),u=/^(?:\.js|\.jsx|\.mjs|\.cjs)$/.test(f)?f:"";return lm(n,xr(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 fm(e,t,r,n,i){let s=t;if(n)s=await n.runOnBeforeFile(e,t);let a=Jr(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=Ja(a,{filePath:e,sourceCode:s,declarations:a},r.keepComments,r.importOrder);if(f=cm(f,e,r),i)f=ka(f,i,{filePath:e});if(r.normalizeOutput===!0||r.declarationOrder)f=Ns(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 Vl,rm=50,Sr;var Hl=ae(()=>{Rs();Is();Ls();va();Ra();Ma();Da();La();Ua();gn();wa();Wl();Tl();kr();ro();({Glob:Vl}=globalThis.Bun);Sr=new Map});var jl=ae(()=>{Hl()});var Xl={};hc(Xl,{dtsWatch:()=>Em,dtsCheck:()=>vm,dts:()=>ps,default:()=>Sm,clearCache:()=>bm,PluginErrorCodes:()=>Cm,DtsxPluginError:()=>sr});import{createHash as hm}from"crypto";import{existsSync as dm,readFileSync as mm,writeFileSync as pm}from"fs";import{dirname as gm,join as ym,relative as Kl,resolve as nr,sep as Li}from"path";import Ul from"process";class Yl{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 ms{manifest;cacheDir;manifestPath;constructor(e,t){this.cacheDir=e,this.manifestPath=ym(e,"manifest.json"),this.manifest=this.loadManifest(t)}loadManifest(e){try{if(dm(this.manifestPath)){let t=JSON.parse(mm(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}=um("fs");e(this.cacheDir,{recursive:!0}),pm(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 wm(e){let t={root:e.root,outdir:e.outdir,entrypoints:e.entrypoints,clean:e.clean,tsconfigPath:e.tsconfigPath};return hm("md5").update(JSON.stringify(t)).digest("hex")}function ps(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 Yl;if(a){for(let[g,h]of Object.entries(a))if(h)l.on(g,h)}return{name:"bun-plugin-dtsx",async setup(g){let h=Date.now(),w=null,v=0;try{let C=ql(u,g),x=wm(C);if(C.clean){let E=nr(C.cwd??Ul.cwd(),C.outdir??"./dist");if(Jl.has(E))C.clean=!1;else Jl.add(E)}if(i)w=new ms(nr(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((E,G)=>{let re=setTimeout(()=>{G(new sr(`Generation timed out after ${o}ms`,"TIMEOUT_ERROR",{timeout:o}))},o);Ni(C).then((I)=>{clearTimeout(re),E(I)}).catch((I)=>{clearTimeout(re),G(I)})})})(),k=Date.now()-h;if(w)w.save();if(await l.emit("complete",{type:"complete",stats:R,duration:k,fromCache:v}),f){if(console.log(`[bun-plugin-dtsx] Generation complete in ${k}ms`),v>0)console.log(`[bun-plugin-dtsx] ${v} files served from cache`)}if(t)await t(R)}catch(C){let x=Zl(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 Zl(e){if(e instanceof sr)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 sr(e.message,t,{originalError:e.name},e)}return new sr(String(e),"GENERATION_ERROR")}function $m(e){let t=e.map((n)=>gm(n).split(Li)),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(Li)||Li}function ql(e,t){let r=e.cwd||Ul.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=$m(n.map((c)=>nr(r,c)));s=Kl(r,o)||"."}s=s||"./src";let a=e.entrypoints;if(!a)if(n?.length){let o=nr(r,s),c=[];for(let f of n){let u=nr(r,f);if(u===o||u.startsWith(o+Li))c.push(Kl(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 Em(e={}){return ps({...e,incremental:!0,verbose:e.verbose??!0})}function vm(e){return{name:"bun-plugin-dtsx-check",async setup(t){let r=ql({...e,outdir:""},t);try{await Ni({...r,clean:!1})}catch(n){let i=Zl(n);if(e.onError)await e.onError(i);if(e.failOnError!==!1)throw i}}}}function bm(e=".dtsx-cache"){new ms(nr(e),"").clear()}var um,Cm,sr,Jl,Sm;var zl=ae(()=>{jl();um=import.meta.require,Cm={CONFIG_ERROR:"CONFIG_ERROR",GENERATION_ERROR:"GENERATION_ERROR",FILE_ERROR:"FILE_ERROR",CACHE_ERROR:"CACHE_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR"};sr=class sr 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}}};Jl=new Set;Sm=ps});import{mkdir as Am,stat as xm}from"fs/promises";import{bold as gs,dim as ys,green as Tm,italic as Ql,log as Rm}from"@stacksjs/cli";import{path as st}from"@stacksjs/path";import{glob as ec}from"@stacksjs/storage";async function Om(e){let t=await ec([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 E0(e){let r=Date.now()-e.startTime,n=e.pkgName??`@stacksjs/${st.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 Om(e.dir);let i=await ec([st.resolve(e.dir,"dist","**/*")],{absolute:!0});for(let s of i){let a=await xm(s),o;if(a.size<1048576)o=`${(a.size/1024).toFixed(2)}kb`;else o=`${(a.size/1024/1024).toFixed(2)}mb`;let c=st.relative(e.dir,s).replace("dist/","");console.log(`${gs(ys(`[${o}]`))} ${ys("dist/")}${c}`)}console.log(`${gs(ys(`[${r}ms]`))} Built ${Ql(gs(Tm(n)))}`)}async function v0(e){let t=e.pkgName??`@stacksjs/${st.basename(e.dir)}`;if(e.styled===!1)console.log(`Building ${t}...`);else Rm.info(`Building ${Ql(t)}...`);return{startTime:Date.now()}}async function b0(e){let{dts:t}=await Promise.resolve().then(() => (zl(),Xl)),r=st.resolve(e.dir,"src"),n=st.resolve(e.dir,"dist"),i=(await Array.fromAsync(new Bun.Glob("**/*.ts").scan({cwd:r}))).filter((a)=>!a.endsWith(".d.ts"));await Bun.build({entrypoints:i.map((a)=>st.resolve(r,a)),outdir:n,root:r,target:"bun",format:"esm",splitting:!1,external:e.external??Pm(),plugins:[t({root:r,outdir:n})]});let s=new Bun.Transpiler({loader:"ts",target:"bun",minifyWhitespace:!0});for(let a of i){let o=s.transformSync(await Bun.file(st.resolve(r,a)).text());o=o.replace(/(['"])(\.\.?\/[^'"]+?)\.tsx?\1/g,"$1$2.js$1");let c=st.resolve(n,a.replace(/\.ts$/,".js"));await Am(st.dirname(c),{recursive:!0}),await Bun.write(c,o)}}function Pm(e=[]){let t=[];try{let r=Ye("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,"bun-queue","ioredis","localtunnels","localtunnels/*","@craft-native/ts","ts-md","meilisearch","algoliasearch","@opensearch-project/opensearch","*.yaml","*.yml",...e]}export{Om as validateDeclarations,b0 as transpilePackage,E0 as outro,v0 as intro,Pm as frameworkExternal};