@stacksjs/build 0.75.519 → 0.75.522

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 +254 -233
  2. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -1,257 +1,278 @@
1
1
  // @bun
2
- var he=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};var lf=import.meta.require;import{readFile as df,stat as Vp,writeFile as mf}from"fs/promises";async function ds(e,t){if(Vr)return globalThis.Bun.write(e,t);let r=typeof t==="string"?t:t instanceof ArrayBuffer?Buffer.from(t):t;return await mf(e,r),typeof t==="string"?Buffer.byteLength(t):t.byteLength}async function Pt(e){if(Vr)return globalThis.Bun.file(e).text();return df(e,"utf-8")}var Vr,Up;var Ur=he(()=>{Vr=typeof globalThis.Bun<"u",Up=!Vr&&typeof process<"u"&&!!process.versions?.node});function Ht(e){return ms[e]>=ms[Kr]}function yf(){if(!gf)return"";return`[${new Date().toISOString().slice(11,23)}] `}function Cf(e,t){let r=yf();if(e||r)return[`${r}${e}`,...t];return t}function zt(e,t,r){let n=Cf(t,r);if(ps){ps(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 gs(e){return{debug:(...t)=>{if(Ht("debug"))zt("debug",e,t)},info:(...t)=>{if(Ht("info"))zt("info",e,t)},warn:(...t)=>{if(Ht("warn"))zt("warn",e,t)},error:(...t)=>{if(Ht("error"))zt("error",e,t)},setLevel:(t)=>{Kr=t},getLevel:()=>Kr,child:(t)=>{let r=e?`${e}:${t}`:`[${t}]`;return gs(r)},time:(t)=>{let r=performance.now();return()=>{let n=performance.now()-r;if(Ht("debug"))zt("debug",e,[`${t}: ${n.toFixed(2)}ms`])}},progress:(t)=>{if(Ht("info"))if(typeof process<"u"&&process.stdout?.isTTY)process.stdout.write(`\r${e} ${t}`);else zt("info",e,[t])}}}function fn(e){Kr=e}var ms,Kr="info",pf="[dtsx]",gf=!1,ps=null,Y;var un=he(()=>{ms={debug:0,info:1,warn:2,error:3,silent:4};Y=gs(pf)});function yt(e){return e>=65&&e<=90||e>=97&&e<=122||e===95||e===36||e>127}function Ue(e){return yt(e)||e>=48&&e<=57}function ys(e,t){let r=t;for(;;){while(r>=0&&(e.charCodeAt(r)===32||e.charCodeAt(r)===9||e.charCodeAt(r)===10||e.charCodeAt(r)===13))r--;if(r<0)return-1;if(e.charCodeAt(r)===47&&r>0&&e.charCodeAt(r-1)===42){let o=e.lastIndexOf("/*",r-2);if(o===-1)return-1;r=o-1;continue}let n=e.lastIndexOf(`
3
- `,r)+1,i=wf(e,n,r);if(i!==-1){r=i-1;continue}return r}}function wf(e,t,r){let n=0;for(let i=t;i<=r;i++){let o=e.charCodeAt(i);if(n){if(o===92){i++;continue}if(o===n)n=0;continue}if(o===39||o===34||o===96){n=o;continue}if(o===47&&i+1<=r&&e.charCodeAt(i+1)===47)return i}return-1}function Cs(e){return e===61||e===40||e===91||e===33||e===38||e===124||e===63||e===58||e===44||e===59||e===123||e===125||e===94||e===126||e===43||e===45||e===42||e===37||e===60||e===62}function ws(e){return e==="return"||e==="typeof"||e==="void"||e==="delete"||e==="throw"||e==="new"||e==="in"||e==="of"||e==="case"||e==="instanceof"||e==="yield"||e==="await"||e==="else"||e==="do"}function vf(e,t){let r=[],n=[],i=0,o=!1,s="",a="",c=!0,f=0,u=(h,l=!1)=>{a=s,s=h,c=l};while(f<=t){let h=e.charCodeAt(f);if(o){if(h===92){f+=2;continue}if(h===96)o=!1,u("literal");else if(h===36&&e.charCodeAt(f+1)===123)n.push(i++),o=!1,u("{",!0),f++;f++;continue}if(h===32||h===9||h===10||h===13){f++;continue}if(h===47&&e.charCodeAt(f+1)===47){let l=e.indexOf(`
4
- `,f+2);f=l===-1?e.length:l+1;continue}if(h===47&&e.charCodeAt(f+1)===42){let l=e.indexOf("*/",f+2);f=l===-1?e.length:l+2;continue}if(h===39||h===34){let l=h;f++;while(f<e.length){let y=e.charCodeAt(f++);if(y===92)f++;else if(y===l)break}u("literal");continue}if(h===96){o=!0,f++;continue}if(yt(h)||h===35&&yt(e.charCodeAt(f+1))){let l=f++;while(Ue(e.charCodeAt(f)))f++;let y=e.slice(l,f);u(y,s!=="."&&ws(y));continue}if(h===40){let l=a!=="."&&(s==="if"||s==="while"||s==="for"||s==="with"||s==="switch"||s==="catch"||s==="await"&&a==="for");r.push(l),u("(",!0)}else if(h===41){let l=r.pop()??!1;if(f===t)return l;u(")",l)}else if(h===47&&c){f=gr(e,f),u("literal");continue}else{if(h===123)i++;else if(h===125){if(i--,n.at(-1)===i)n.pop(),o=!0}u(e[f],h===47||Cs(h))}f++}return!1}function Hr(e,t){let r=ys(e,t-1);if(r<0)return!0;let n=e.charCodeAt(r);if(n===41)return vf(e,r);if(Cs(n))return!0;if(Ue(n)){let i=r;while(i>=0&&Ue(e.charCodeAt(i)))i--;let o=e.charCodeAt(ys(e,i));if(o===46||o===35)return!1;return ws(e.slice(i+1,r+1))}return!1}function gr(e,t){let r=t,n=e.length;r++;let i=!1;while(r<n){let o=e.charCodeAt(r);if(o===92){r+=2;continue}if(i){if(o===93)i=!1;r++;continue}if(o===91){i=!0,r++;continue}if(o===47){r++;break}if(o===10||o===13)break;r++}while(r<n&&Ue(e.charCodeAt(r)))r++;return r}var hn=()=>{};function vs(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&&e.charCodeAt(r)!==13)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+=`
5
- `;r++}r=Math.min(r+2,e.length);continue}if(i===44){let o=r+1;while(o<e.length){while(o<e.length&&e.charCodeAt(o)<=32)o++;if(e.charCodeAt(o)===47&&e.charCodeAt(o+1)===47){o+=2;while(o<e.length&&e.charCodeAt(o)!==10&&e.charCodeAt(o)!==13)o++;continue}if(e.charCodeAt(o)===47&&e.charCodeAt(o+1)===42){o+=2;while(o+1<e.length&&!(e.charCodeAt(o)===42&&e.charCodeAt(o+1)===47))o++;o=Math.min(o+2,e.length);continue}break}let s=e.charCodeAt(o);if(s===93||s===125){r++;continue}}t+=e[r++]}return t}var bs=()=>{};import{readFileSync as bf,statSync as Ef}from"fs";import{readFile as Sf}from"fs/promises";import{createRequire as $f}from"module";import{dirname as yr,isAbsolute as Af,join as dn,resolve as mn}from"path";function Jt(e){let t=[e];if(!e.endsWith(".json"))t.push(`${e}.json`);t.push(dn(e,"tsconfig.json"));for(let r of t)try{if(Ef(r).isFile())return r}catch{}return null}function xf(e,t){if(Af(e)||e.startsWith("."))return Jt(mn(yr(t),e));let r=$f(t),n=e.startsWith("@")?/^@[^/]+\/[^/]+/.exec(e)?.[0]:e.split("/")[0];if(n)for(let i of r.resolve.paths(n)??[]){let o=Jt(dn(i,n,"package.json"));if(!o)continue;let s=JSON.parse(bf(o,"utf8"));if(e===n){if(s.tsconfig!==void 0){if(typeof s.tsconfig!=="string")throw Error(`Invalid tsconfig field in ${o}`);let c=Jt(mn(yr(o),s.tsconfig));if(!c)throw Error(`Cannot resolve tsconfig ${JSON.stringify(s.tsconfig)} from ${o}`);return c}let a=Jt(dn(yr(o),"tsconfig.json"));if(a)return a}break}for(let i of[`${e}/tsconfig.json`,e])try{let o=r.resolve(i),s=o.endsWith(".json")?Jt(o):null;if(s)return s}catch{}return null}async function Cr(e,t={},r=new Set){let n=Jt(e);if(!n)return;if(r.has(n)){if(t.allowCircular)return;throw Error(`Circular tsconfig extends: ${n}`)}let i=new Set(r).add(n),o=JSON.parse(vs(await Sf(n,"utf8"))),s=typeof o.extends==="string"?[o.extends]:o.extends??[];if(!Array.isArray(s)||s.some((f)=>typeof f!=="string"))throw Error(`Invalid tsconfig extends in ${n}`);let a={};for(let f of s){let u=xf(f,n);if(!u)throw Error(`Cannot resolve tsconfig extends ${JSON.stringify(f)} from ${n}`);a={...a,...await Cr(u,t,i)}}let c=o.compilerOptions??{};if(c.isolatedDeclarations!==void 0)a.isolatedDeclarations=c.isolatedDeclarations;if(c.baseUrl!==void 0){if(typeof c.baseUrl!=="string")throw Error(`Invalid baseUrl in ${n}`);a.baseUrl=mn(yr(n),c.baseUrl)}if(c.paths!==void 0){if(!c.paths||typeof c.paths!=="object"||Array.isArray(c.paths))throw Error(`Invalid paths in ${n}`);for(let[f,u]of Object.entries(c.paths))if(f.split("*").length>2||!Array.isArray(u)||u.length===0||u.some((h)=>typeof h!=="string"||h.split("*").length>2))throw Error(`Invalid path mapping ${JSON.stringify(f)} in ${n}`);a.paths=c.paths,a.pathsBasePath=yr(n)}return a}var pn=he(()=>{bs()});import{existsSync as yn,readFileSync as Es,realpathSync as wr,statSync as Tf}from"fs";import{builtinModules as Of}from"module";import{dirname as Cn,extname as Rf,isAbsolute as wn,join as Os,relative as Rs,resolve as qt}from"path";function zr(e){try{return Tf(e).isFile()}catch{return!1}}function Yt(e,t){let r=e.replace(/[?#].*$/,"");if(!(r.startsWith("./")||r.startsWith("../")||r==="."||r==="..")&&!wn(r))return{resolved:null,isRelative:!1};let n=Cn(t),i=qt(n,r);if(zr(i))return{resolved:i,isRelative:!0};let o=Rf(i),s=Pf[o];if(s){let a=i.slice(0,-o.length);for(let c of s){let f=a+c;if(zr(f))return{resolved:f,isRelative:!0}}}for(let a of Ss){let c=i+a;if(zr(c))return{resolved:c,isRelative:!0}}if(yn(i))for(let a of Ss){let c=Os(i,`index${a}`);if(zr(c))return{resolved:c,isRelative:!0}}return{resolved:null,isRelative:!0}}function Ps(e,t){let r=e.indexOf("*");return r===-1?t===e:t.startsWith(e.slice(0,r))&&t.endsWith(e.slice(r+1))&&t.length>=e.length-1}function ks(e,t){if(Object.hasOwn(e,t))return e[t]!==null;let r=Object.keys(e).filter((n)=>n.includes("*")&&Ps(n,t)).sort((n,i)=>i.indexOf("*")-n.indexOf("*")||i.length-n.length)[0];return r!==void 0&&e[r]!==null}function $s(e,t){if(!e.name||t!==e.name&&!t.startsWith(`${e.name}/`))return!1;if(e.exports===void 0)return!0;let r=t===e.name?".":`.${t.slice(e.name.length)}`;if(typeof e.exports==="string"||Array.isArray(e.exports))return r===".";if(!e.exports||typeof e.exports!=="object")return!1;let n=e.exports;if(!Object.keys(n).some((i)=>i.startsWith(".")))return r===".";return ks(n,r)}function gn(e,t){let r=Rs(e,t);return r!==".."&&!r.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!wn(r)}async function Ms(e){let t=await Cr(qt(e.cwd,e.tsconfigPath||"tsconfig.json")),r=Object.entries(t?.paths??{});if(r.length===0)return Yt;let n=t?.baseUrl??t?.pathsBasePath??e.cwd,i=qt(e.cwd,e.root),o=new Map,s=new Set([...Of,"bun"]),a=(f)=>{let u=Cn(f),h=[];while(!0){if(o.has(u)){let C=o.get(u);for(let S of h)o.set(S,C);return C}h.push(u);let l=Os(u,"package.json");if(yn(l)){let C={...JSON.parse(Es(l,"utf8")),directory:wr(u)};for(let S of h)o.set(S,C);return C}let y=Cn(u);if(y===u)return;u=y}},c=(f,u)=>{if(f.startsWith(".")||wn(f))return Yt(f,u);if(f.startsWith("node:")||f.startsWith("bun:")||s.has(f))return{resolved:null,isRelative:!1};let h=a(u),l=f.startsWith("@")?/^@[^/]+\/[^/]+/.exec(f)?.[0]:f.split("/")[0];if(h&&($s(h,f)||ks(h.imports??{},f)||l&&[h.dependencies,h.devDependencies,h.peerDependencies,h.optionalDependencies].some((G)=>Object.hasOwn(G??{},l))))return{resolved:null,isRelative:!1};let y=r.filter(([G])=>Ps(G,f)).sort(([G],[L])=>{if(!G.includes("*"))return-1;if(!L.includes("*"))return 1;return L.indexOf("*")-G.indexOf("*")})[0];if(!y)return{resolved:null,isRelative:!1};let[C,S]=y,x=C.indexOf("*"),v=x===-1?"":f.slice(x,f.length-(C.length-x-1));for(let G of S){let L=qt(n,G.replace("*",v)),P=a(L);if(P&&$s(P,f)&&!P.private&&P.directory!==h?.directory)return{resolved:null,isRelative:!1};let F=Yt(L,u);if(!F.resolved)continue;let I=wr(F.resolved),k=e.outputStructure==="flat"||yn(i)&&gn(wr(i),I);if(!h||!gn(h.directory,I)||!k||a(I)?.directory!==h.directory||/\.d\.(?:ts|mts|cts)$/.test(I))throw Error(`Local alias ${JSON.stringify(f)} from ${u} resolves outside its emitted package source: ${I}`);return Y.debug(`Resolved local declaration alias ${f} from ${u} to ${I}`),{resolved:e.outputStructure==="flat"?F.resolved:qt(i,Rs(wr(i),I)),isRelative:!0,isAlias:!0,suffix:L.match(/[?#].*$/)?.[0]??""}}throw Error(`Cannot resolve local alias ${JSON.stringify(f)} from ${u} using ${e.tsconfigPath||"tsconfig.json"} (${JSON.stringify(C)})`)};return c.isPackageLocal=(f,u)=>{let h=a(f);return!!h&&a(u)?.directory===h.directory&&gn(h.directory,wr(u))},c.cacheKey=(f)=>{let u=f.map((l)=>({file:l,references:Jr(Es(l,"utf8"),{includeImports:!0}).map((y)=>({specifier:y.specifier,resolution:c(y.specifier,l)}))})),h=[...new Set(o.values())].filter((l)=>l!==void 0).sort((l,y)=>l.directory.localeCompare(y.directory));return JSON.stringify({root:i,compilerOptions:t,packages:h,edges:u})},c}function Ds(e,t=[]){let r=e.length,n="",i=0;while(i<r){let o=e.charCodeAt(i);if(o===34||o===39||o===96){let s=o,a=i;n+=e[i++];while(i<r){let c=e.charCodeAt(i),f=e[i++];if(n+=s===96&&c!==s?c===10||c===13?f:" ":f,c===92&&i<r){let u=e[i++];n+=s===96?u===`
6
- `||u==="\r"?u:" ":u;continue}if(c===s)break}t.push({start:a,end:i});continue}if(o===47&&i+1<r){let s=e.charCodeAt(i+1);if(s===47){n+=" ",i+=2;while(i<r&&e.charCodeAt(i)!==10)n+=" ",i++;continue}if(s===42){n+=" ",i+=2;while(i<r&&!(e.charCodeAt(i)===42&&e.charCodeAt(i+1)===47))n+=e[i]===`
7
- `||e[i]==="\r"?e[i]:" ",i++;if(i<r)n+=" ",i+=2;continue}if(Hr(e,i)){let a=gr(e,i);n+=e.slice(i,a).replace(/[^\r\n]/g," "),i=a;continue}}n+=e[i++]}return n}function Jr(e,t={}){let r=[],n=[],i=Ds(e,n),o=(a)=>n.some((c)=>a>c.start&&a<c.end);As.lastIndex=0;let s;while((s=As.exec(i))!==null){if(o(s.index))continue;let a=!!s[1],c=s[3],f=s[0],u;if(f.includes("* as "))u="export-star-as";else if(f.includes("*"))u="export-star";else u="export-named";r.push({specifier:c,kind:u,isTypeOnly:a})}if(t.includeImports){Ts.lastIndex=0;while((s=Ts.exec(i))!==null){if(o(s.index))continue;r.push({specifier:s[3],kind:"import",isTypeOnly:!!s[1]})}}if(t.includeImports){xs.lastIndex=0;while((s=xs.exec(i))!==null)if(!o(s.index))r.push({specifier:s[2],kind:"import",isTypeOnly:!1})}return r}function Is(e,t){let r=[],n=Ds(e,r),i=/\b(?:from\s*|import\s*(?:\(\s*)?)(['"])([^'"]+)\1/g,o=[],s;while((s=i.exec(n))!==null){if(r.some((u)=>s.index>u.start&&s.index<u.end))continue;let c=s.index+s[0].lastIndexOf(`${s[1]}${s[2]}${s[1]}`)+1,f=t(s[2]);if(f!==s[2])o.push({start:c,end:c+s[2].length,value:f})}let a=e;for(let c of o.reverse())a=a.slice(0,c.start)+c.value+a.slice(c.end);return a}async function vn(e,t={}){let r=new Set,n=new Map,i=[],o=[];for(let s of e){let a=qt(s);if(!r.has(a))r.add(a),o.push(a)}while(o.length>0){let s=o.shift(),a;try{a=await Pt(s)}catch{continue}let c=Jr(a,t);n.set(s,c);for(let f of c){let u=(t.resolveSpecifier??Yt)(f.specifier,s);if(!u.isRelative)continue;if(u.resolved){if(!r.has(u.resolved))r.add(u.resolved),o.push(u.resolved)}else i.push({from:s,specifier:f.specifier,isTypeOnly:f.isTypeOnly})}}return{reachable:r,reExports:n,unresolved:i}}var Ss,Pf,As,xs,Ts;var bn=he(()=>{Ur();un();hn();pn();Ss=[".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"]};As=/(?:^|[\n;{}])\s*export\s+(type\s+)?(?:\*(?:\s+as\s+\w+)?|\{[^}]*\})\s+from\s+(['"])([^'"]+)\2/g,xs=/\bimport\s*\(\s*(['"])([^'"]+)\1/g,Ts=/(?:^|[\n;{}])\s*import\s+(type\s+)?(?:[^'";]+?\s+from\s+)?(['"])([^'"]+)\2/g});import{relative as Wt}from"path";function kf(e){let t=[],r=[],n=0,i=0,o=[],s=!1,a=0,c=e.length,f=(u)=>{let h=e.slice(n,u).trim();if(n=u,!h)return;if(Mf(h)){r.push(h);return}t.push({text:h,comments:r}),r=[]};while(a<c){let u=e[a];if(s){if(u==="\\"){a+=2;continue}if(u==="`"){s=!1,a++;continue}if(u==="$"&&e[a+1]==="{"){o.push(i),i++,s=!1,a+=2;continue}a++;continue}if(u==="/"&&e[a+1]==="*"){let h=e.indexOf("*/",a+2);a=h===-1?c:h+2;continue}if(u==="/"&&e[a+1]==="/"){let h=e.indexOf(`
8
- `,a);a=h===-1?c:h;continue}if(u==="'"||u==='"'){a++;while(a<c&&e[a]!==u&&e[a]!==`
9
- `){if(e[a]==="\\")a++;a++}a++;continue}if(u==="`"){s=!0,a++;continue}if(u==="("||u==="["||u==="{"){i++,a++;continue}if(u===")"||u==="]"||u==="}"){if(i--,o.length>0&&u==="}"&&i===o[o.length-1])o.pop(),s=!0;a++;continue}if(i===0&&u===";"){f(a+1),a++;continue}if(i===0&&u===`
10
- `){let h=e[a+1];if(h!==void 0&&/[\w$@/]/.test(h))f(a+1);a++;continue}a++}return f(c),t}function Mf(e){let t=0;while(t<e.length){while(t<e.length&&/\s/.test(e[t]))t++;if(t>=e.length)return!0;if(e.startsWith("//",t)){let r=e.indexOf(`
11
- `,t);t=r===-1?e.length:r;continue}if(e.startsWith("/*",t)){let r=e.indexOf("*/",t+2);if(r===-1)return!0;t=r+2;continue}return!1}return!0}function En(e){let t=[];for(let r of e.split(",")){let n=r.replace(/\/\*[\s\S]*?\*\//g,"").trim().replace(/^type\s+/,"");if(!n)continue;let i=n.match(/^([\w$]+)(?:\s+as\s+([\w$]+))?$/);if(!i)continue;t.push({local:i[1],exported:i[2]??i[1]})}return t}function Df(e){let t={named:[]},r=e.trim().replace(/^type\s+/,""),n=r.match(/\{([\s\S]*)\}/);if(n){for(let s of En(n[1]))t.named.push({imported:s.local,local:s.exported});r=r.replace(n[0],"")}let i=r.match(/\*\s*as\s+([\w$]+)/);if(i)t.namespaceName=i[1],r=r.replace(i[0],"");let o=r.replace(/,/g,"").trim();if(o&&Ns.test(o))t.defaultName=o;return t}function Ff(e,t){let r=e.replace(/^export\s+/,""),n=/^default\s+/.test(r);if(r=r.replace(/^default\s+/,""),n)r=r.replace(/^((?:declare\s+)?(?:abstract\s+)?(?:class|function\s*\*?|async\s+function\s*\*?))\s*(?=[(<{])/,(i,o)=>`${o.trimEnd()} ${t}`);if(/^(?:interface|type)\b/.test(r)||/^declare\b/.test(r))return r;return`declare ${r}`}function Nf(e,t){let r={file:e,declarations:[],declared:new Set,imports:new Map,localExports:new Map,namedReExports:[],starReExports:[],namespaceReExports:[],verbatim:[],directives:[]},n=kf(t);for(let i of n){i.comments=i.comments.filter((c)=>{if(/^\/\/\/\s*</.test(c))return r.directives.push(...c.split(`
12
- `).map((f)=>f.trim()).filter((f)=>f.startsWith("///"))),!1;return!0});let o=i.text.replace(/;\s*$/,"").trim(),s=o.match(/^import\s+(type\s+)?([\s\S]+?)\s+from\s+(['"])([^'"]+)\3/);if(s){let c=Df(s[2]),f=s[4];if(c.defaultName)r.imports.set(c.defaultName,{specifier:f,imported:"default"});if(c.namespaceName)r.imports.set(c.namespaceName,{specifier:f,imported:"*"});for(let u of c.named)r.imports.set(u.local,{specifier:f,imported:u.imported});continue}if(/^import\s+['"]/.test(o)){r.verbatim.push(i);continue}if(s=o.match(/^export\s+(?:type\s+)?\*\s+as\s+([\w$]+)\s+from\s+(['"])([^'"]+)\2/),s){r.namespaceReExports.push({specifier:s[3],exported:s[1]});continue}if(s=o.match(/^export\s+(?:type\s+)?\*\s+from\s+(['"])([^'"]+)\1/),s){r.starReExports.push(s[2]);continue}if(s=o.match(/^export\s+(?:type\s+)?\{([\s\S]*)\}\s+from\s+(['"])([^'"]+)\2/),s){for(let c of En(s[1]))r.namedReExports.push({specifier:s[3],imported:c.local,exported:c.exported});continue}if(s=o.match(/^export\s+(?:type\s+)?\{([\s\S]*)\}$/),s){for(let c of En(s[1]))r.localExports.set(c.exported,c.local);continue}if(s=o.match(/^export\s+default\s+([\w$]+)$/),s&&Ns.test(s[1])){r.localExports.set("default",s[1]);continue}if(/^export\s+as\s+namespace\b/.test(o)||/^(?:export\s+)?declare\s+(?:global\b|module\s+['"])/.test(o)){r.verbatim.push(i);continue}let a=o.match(If);if(a){let c=!!a[1],f=a[4]??(c?"_default":null);if(f){if(r.declared.add(f),/^export\s/.test(o))r.localExports.set(c?"default":f,f);r.declarations.push({statement:i,name:f,emit:Ff(i.text,f)});continue}}r.declarations.push({statement:i,name:null,emit:i.text})}return r}function Fs(e,t){if(t.size===0)return e;let r="",n=0,i=e.length,o=`
13
- `;while(n<i){let s=e[n];if(s==="/"&&e[n+1]==="*"){let a=e.indexOf("*/",n+2),c=a===-1?i:a+2;r+=e.slice(n,c),n=c;continue}if(s==="/"&&e[n+1]==="/"){let a=e.indexOf(`
14
- `,n),c=a===-1?i:a;r+=e.slice(n,c),n=c;continue}if(s==="'"||s==='"'){let a=n+1;while(a<i&&e[a]!==s&&e[a]!==`
15
- `){if(e[a]==="\\")a++;a++}r+=e.slice(n,a+1),n=a+1,o=s;continue}if(/[A-Z_$]/i.test(s)){let a=n+1;while(a<i&&/[\w$]/.test(e[a]))a++;let c=e.slice(n,a),f=t.get(c);if(f!==void 0&&o!=="."){let u=a;while(u<i&&(e[u]===" "||e[u]==="\t"))u++;let h=(e[u]===":"||e[u]==="?"&&e[u+1]===":")&&/[{;,(\n]/.test(o);r+=h?c:f}else r+=c;o="a",n=a;continue}if(r+=s,s===`
16
- `||!/\s/.test(s))o=s;n++}return r}function Ls(e,t,r,n){let i=[],o=new Map,s=[e,...t.filter((W)=>W!==e)];for(let W of s){let K=r.get(W);if(K===void 0){i.push(`No declarations were generated for ${Wt(n.cwd,W)}; it is left out of the bundle`);continue}o.set(W,Nf(W,K))}let a=(W,K)=>{if(!W.startsWith(".")&&!W.startsWith("/"))return null;let q=Yt(W,K).resolved;return q&&o.has(q)?q:null},c=(W)=>W.startsWith(".")||W.startsWith("/"),f=new Set,u=(W)=>{let K=W;for(let q=1;f.has(K);q++)K=`${W}_${q}`;return f.add(K),K},h=new Map;for(let[W,K]of o){let q=new Map;for(let Z of K.declared)q.set(Z,u(Z));h.set(W,q)}let l=new Map,y=(W,K,q)=>{let Z=`${W}\x00${K}`,te=l.get(Z);if(!te)te=u(q),l.set(Z,te);return te},C=new Map,S=new Map,x=new Set,v=(W,K,q)=>{let Z=a(K,W.file);if(Z){if(q==="*")return{kind:"namespace",file:Z};let te=L(Z).get(q);if(!te)i.push(`${Wt(n.cwd,W.file)}: '${q}' is not exported by '${K}'`);return te??null}if(c(K))return i.push(`${Wt(n.cwd,W.file)}: '${K}' is not part of the bundle`),null;return q==="*"?{kind:"external-namespace",source:K}:{kind:"external",source:K,imported:q}},G=(W,K)=>{if(W.declared.has(K))return{kind:"local",name:h.get(W.file).get(K)};let q=W.imports.get(K);if(q)return v(W,q.specifier,q.imported);return i.push(`${Wt(n.cwd,W.file)}: cannot resolve exported name '${K}'`),null};function L(W){let K=C.get(W);if(K)return K;let q=new Map,Z=o.get(W);if(!Z||x.has(W))return q;x.add(W);let te=new Set;for(let[X,oe]of Z.localExports){let Ge=G(Z,oe);if(Ge)q.set(X,Ge)}for(let X of Z.namedReExports){let oe=v(Z,X.specifier,X.imported);if(oe)q.set(X.exported,oe)}for(let X of Z.namespaceReExports){let oe=v(Z,X.specifier,"*");if(oe)q.set(X.exported,oe)}for(let X of Z.starReExports){let oe=a(X,W);if(oe){for(let[Ge,Ve]of L(oe))if(Ge!=="default"&&!q.has(Ge))q.set(Ge,Ve);for(let Ge of S.get(oe)??[])te.add(Ge)}else if(c(X))i.push(`${Wt(n.cwd,W)}: '${X}' is not part of the bundle`);else te.add(X)}return x.delete(W),C.set(W,q),S.set(W,te),q}let P=new Map,F=[],I=(W,K)=>{switch(W.kind){case"local":return W.name;case"external":return y(W.source,W.imported,W.imported==="default"?K:W.imported);case"external-namespace":return y(W.source,"*",K);case"namespace":return k(W.file,K)}};function k(W,K){let q=P.get(W);if(q)return q;let Z=u(K);P.set(W,Z);let te=[];for(let[X,oe]of L(W)){if(X==="default")continue;let Ge=I(oe,X);te.push(Ge===X?X:`${Ge} as ${X}`)}if(S.get(W)?.size)i.push(`${Wt(n.cwd,W)}: 'export * from' an external module cannot be expressed inside namespace '${Z}'`);return F.push(`declare namespace ${Z} {
17
- export { ${te.join(", ")} };
18
- }`),Z}let U=[],H=[],O=new Set;for(let[W,K]of o){for(let te of K.directives)O.add(te);let q=new Map;for(let[te,X]of h.get(W))if(te!==X)q.set(te,X);for(let[te,X]of K.imports){if(K.declared.has(te))continue;let oe=v(K,X.specifier,X.imported);if(!oe)continue;let Ge=I(oe,te);if(Ge!==te)q.set(te,Ge)}let Z=[];for(let te of K.declarations){if(n.keepComments)Z.push(...te.statement.comments);let X=Fs(te.emit,q);if(!/[;}]$/.test(X))X+=";";Z.push(X)}for(let te of K.verbatim){if(n.keepComments)H.push(...te.comments);H.push(Fs(te.text,q))}if(Z.length>0)U.push(`// From: ${Wt(n.cwd,W)}
19
- ${Z.join(`
20
- `)}`)}let z=L(e),pe=[],Oe=[];for(let[W,K]of z){if(K.kind==="external"){Oe.push(`export { ${K.imported===W?W:`${K.imported} as ${W}`} } from '${K.source}';`);continue}if(K.kind==="external-namespace"){Oe.push(`export * as ${W} from '${K.source}';`);continue}let q=I(K,W==="default"?"_default":W);pe.push(q===W?W:`${q} as ${W}`)}for(let W of S.get(e)??[])Oe.push(`export * from '${W}';`);let ie=new Map;for(let[W,K]of l){let[q,Z]=W.split("\x00"),te=ie.get(q)??{named:[],defaults:[],namespaces:[]};if(ie.set(q,te),Z==="*")te.namespaces.push(K);else if(Z==="default")te.defaults.push(K);else te.named.push(Z===K?K:`${Z} as ${K}`)}let ne=[];for(let[W,K]of[...ie].sort(([q],[Z])=>q.localeCompare(Z))){for(let q of K.defaults)ne.push(`import ${q} from '${W}';`);for(let q of K.namespaces)ne.push(`import * as ${q} from '${W}';`);if(K.named.length>0)ne.push(`import { ${K.named.join(", ")} } from '${W}';`)}let ue=[];if(O.size>0)ue.push([...O].join(`
21
- `));if(ue.push(`/**
2
+ var me=(e,t,i)=>()=>{if(e)try{t=e(e=0)}catch(r){i=[r]}if(i)throw i[0];return t};var md=import.meta.require;function Zi(e){if(vd)return Bun.hash(e);let t=0;for(let i=0;i<e.length;i++){let r=e.charCodeAt(i);t=(t<<5)-t+r,t=t&t}return t}var vd;var $o=me(()=>{vd=typeof globalThis.Bun?.hash==="function"});import{existsSync as Fr,mkdirSync as bd,readFileSync as So,renameSync as $d,rmdirSync as Ed,rmSync as Ga,statSync as Ba,writeFileSync as _a}from"fs";import{join as xo,relative as Nr,resolve as ja}from"path";function Sd(e){try{Ga(xo(e,Va),{force:!0});try{Ed(e)}catch{}}catch{}}class Ao{cacheDir;manifestPath;manifest=null;configHash;constructor(e,t){this.cacheDir=ja(e.cwd,e.cacheDir??Wr),this.manifestPath=xo(this.cacheDir,Va),this.configHash=this.hashConfig(e,t)}hashConfig(e,t){let i={resolutionContext:t,keepComments:e.keepComments,importOrder:e.importOrder,outputStructure:e.outputStructure,moduleSpecifierMode:e.moduleSpecifierMode??"preserve",root:ja(e.cwd,e.root),exclude:e.exclude??[],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(Zi(JSON.stringify(i)))}hashString(e){return String(Zi(e))}load(){try{if(!Fr(this.manifestPath))return!1;let e=So(this.manifestPath,"utf-8"),t=JSON.parse(e);if(t.version!==Eo)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:Eo,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};if(this.manifest.updatedAt=Date.now(),!Fr(this.cacheDir))bd(this.cacheDir,{recursive:!0});let e=`${this.manifestPath}.${process.pid}.tmp`;try{_a(e,JSON.stringify(this.manifest,null,2)),$d(e,this.manifestPath)}finally{if(Fr(e))Ga(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 i=Nr(t,e),r=this.manifest.entries[i];if(!r)return null;if(typeof r.dtsContent!=="string"||typeof r.dtsHash!=="string"||r.configHash!==this.configHash||this.hashString(r.dtsContent)!==r.dtsHash)return null;try{let n=Ba(e),{mtimeMs:o,ctimeMs:s}=n;if(n.size!==r.sourceSize)return null;if(o!==r.sourceMtime||s!==r.sourceCtime){let c=So(e,"utf-8");if(this.hashString(c)!==r.sourceHash)return null;r.sourceMtime=o,r.sourceCtime=s}return r.dtsContent}catch{return null}}update(e,t,i,r){if(!this.manifest)this.manifest={version:Eo,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};let n=Nr(r,e),o,s,c;try{let l=Ba(e);o=l.mtimeMs,s=l.ctimeMs,c=l.size}catch{o=Date.now(),s=o,c=Buffer.byteLength(t)}this.manifest.entries[n]={sourcePath:n,sourceHash:this.hashString(t),sourceMtime:o,sourceCtime:s,sourceSize:c,dtsContent:i,dtsHash:this.hashString(i),generatedAt:Date.now(),configHash:this.configHash}}remove(e,t){if(!this.manifest)return;let i=Nr(t,e);delete this.manifest.entries[i]}clear(){this.manifest=null,Sd(this.cacheDir)}getStats(){if(!this.manifest)return{entries:0,size:0};let e=Object.keys(this.manifest.entries).length,t=0;for(let i of Object.values(this.manifest.entries))t+=i.dtsContent.length;return{entries:e,size:t}}prune(e,t){if(!this.manifest)return 0;let i=0,r=new Set(Array.from(e).map((n)=>Nr(t,n)));for(let n of Object.keys(this.manifest.entries))if(!r.has(n))delete this.manifest.entries[n],i++;return i}}function Ua(e){let t=xo(e,".gitignore");try{let i="";if(Fr(t))i=So(t,"utf-8");if(!i.split(/\r?\n/).some((r)=>r.trim()===Wr||r.trim()===`${Wr}/`)){let r=i.trimEnd(),n=`${r}${r?`
3
+
4
+ `:""}# dtsx cache
5
+ ${Wr}/
6
+ `;_a(t,n)}}catch{}}var Eo=24,Wr=".dtsx-cache",Va="manifest.json";var Ka=me(()=>{$o()});import{readFile as xd,stat as n0,writeFile as Ad}from"fs/promises";async function za(e,t){if(Lr)return globalThis.Bun.write(e,t);let i=typeof t==="string"?t:t instanceof ArrayBuffer?Buffer.from(t):t;return await Ad(e,i),typeof t==="string"?Buffer.byteLength(t):t.byteLength}async function yt(e){if(Lr)return globalThis.Bun.file(e).text();return xd(e,"utf-8")}var Lr,o0;var Qi=me(()=>{Lr=typeof globalThis.Bun<"u",o0=!Lr&&typeof process<"u"&&!!process.versions?.node});function Ha(e,t){let i=Number.isFinite(t)?Math.max(1,Math.floor(t)):1;if(e===void 0||!Number.isFinite(e))return i;return Math.max(1,Math.floor(e))}var qa=()=>{};function Ya(e){return e.endsWith(".vue")}function Td(e){let t={script:null,scriptSetup:null},i=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,r;while((r=i.exec(e))!==null){let n=r[1]||"",o=/lang\s*=\s*["']([^"']+)["']/i.exec(n)?.[1]?.toLowerCase()??"js",s={content:r[2]??"",attrs:n,setup:/\bsetup\b/.test(n),lang:o};if(s.setup)t.scriptSetup=s;else t.script=s}return t}function wt(e,t){let i=e[t];t++;while(t<e.length){let r=e[t];if(r==="\\"){t+=2;continue}if(r===i)return t+1;t++}return t}function $t(e,t){t++;let i=0;while(t<e.length){let r=e[t];if(r==="\\"){t+=2;continue}if(r==="`"&&i===0)return t+1;if(r==="$"&&e[t+1]==="{"){i++,t+=2;continue}if(r==="}"){if(i>0)i--;t++;continue}t++}return t}function Nt(e,t){if(e[t+1]==="/"){let i=e.indexOf(`
7
+ `,t+2);return i===-1?e.length:i+1}if(e[t+1]==="*"){let i=e.indexOf("*/",t+2);return i===-1?e.length:i+2}return t+1}function ko(e,t){let i=e[t];if(i==='"'||i==="'")return wt(e,t);if(i==="`")return $t(e,t);if(i==="/"&&(e[t+1]==="/"||e[t+1]==="*"))return Nt(e,t);return t}function Oo(e){let t=e.split(""),i=0;while(i<e.length){let r=ko(e,i);if(r>i){for(let n=i;n<r;n++)if(t[n]!==`
8
+ `&&t[n]!=="\r")t[n]=" ";i=r;continue}i++}return t.join("")}function nt(e,t,i,r){let n=0,o=t;while(o<e.length){let s=e[o];if(s==='"'||s==="'"){o=wt(e,o);continue}if(s==="`"){o=$t(e,o);continue}if(s==="/"&&(e[o+1]==="/"||e[o+1]==="*")){o=Nt(e,o);continue}if(s===i)n++;else if(s===r){if(n--,n===0)return o}o++}return-1}function Ro(e,t){let i=0,r=t;while(r<e.length){let n=e[r];if(n==='"'||n==="'"){r=wt(e,r);continue}if(n==="`"){r=$t(e,r);continue}if(n==="/"&&(e[r+1]==="/"||e[r+1]==="*")){r=Nt(e,r);continue}if(n==="="&&e[r+1]===">"){r+=2;continue}if(n==="<")i++;else if(n===">"){if(i--,i===0)return r}r++}return-1}function Ai(e,t=","){let i=[],r=0,n="",o=0;while(o<e.length){let s=e[o];if(s==='"'||s==="'"){let c=wt(e,o);n+=e.slice(o,c),o=c;continue}if(s==="`"){let c=$t(e,o);n+=e.slice(o,c),o=c;continue}if(s==="/"&&(e[o+1]==="/"||e[o+1]==="*")){o=Nt(e,o);continue}if(s==="{"||s==="["||s==="("||s==="<")r++;else if(s==="}"||s==="]"||s===")"||s===">")r--;if(s===t&&r===0){i.push(n),n="",o++;continue}n+=s,o++}if(n.trim()!=="")i.push(n);return i}function ir(e){let t=e.trim();if(!t.startsWith("{"))return[];let i=nt(t,0,"{","}");if(i===-1)return[];let r=t.slice(1,i),n=[];for(let o of Ai(r)){let s=-1,c=0;for(let u=0;u<o.length;u++){let d=o[u];if(d==='"'||d==="'"){u=wt(o,u)-1;continue}if(d==="`"){u=$t(o,u)-1;continue}if(d==="{"||d==="["||d==="("||d==="<")c++;else if(d==="}"||d==="]"||d===")"||d===">")c--;else if(d===":"&&c===0){s=u;break}}if(s!==-1){n.push({key:er(o.slice(0,s).trim()),value:o.slice(s+1).trim(),isMethod:!1});continue}let l=/^([A-Za-z_$][\w$]*|['"][^'"]+['"])\s*\(/.exec(o.trim());if(l){n.push({key:er(l[1]),value:o.trim(),isMethod:!0});continue}let f=o.trim();if(f)n.push({key:er(f),value:"",isMethod:!1})}return n}function er(e){if(e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);return e}function tr(e){return/^[A-Za-z_$][\w$]*$/.test(e)?e:JSON.stringify(e)}function rr(e,t){let i=new RegExp(`\\b${t}\\b`,"g"),r;while((r=i.exec(e))!==null){let n=r.index+r[0].length;while(n<e.length&&/\s/.test(e[n]))n++;let o=null;if(e[n]==="<"){let l=Ro(e,n);if(l===-1)return null;o=e.slice(n+1,l).trim(),n=l+1;while(n<e.length&&/\s/.test(e[n]))n++}if(e[n]!=="(")continue;let s=nt(e,n,"(",")");if(s===-1)return null;let c=Ai(e.slice(n+1,s));return{generic:o,arg:c.length>0?c[0].trim():null}}return null}function kd(e,t){let i=Xa(e,t);if(!i)return null;return i.kind==="interface"?e.slice(i.bodyStart,i.end):e.slice(i.bodyStart,i.end).trim()}function Xa(e,t){let i=new RegExp(`\\binterface\\s+${t}\\b[^{]*\\{`,"m").exec(e);if(i){let n=i.index+i[0].length-1,o=nt(e,n,"{","}");if(o!==-1)return{kind:"interface",start:i.index,end:o+1,bodyStart:n}}let r=new RegExp(`\\btype\\s+${t}\\b[^=]*=`,"m").exec(e);if(r){let n=r.index+r[0].length,o=0,s=n;while(n<e.length){let c=e[n];if(c==='"'||c==="'"){n=wt(e,n);continue}if(c==="`"){n=$t(e,n);continue}if(c==="{"||c==="["||c==="("||c==="<")o++;else if(c==="}"||c==="]"||c===")"||c===">")o--;else if((c===";"||c===`
9
+ `)&&o===0)break;n++}return{kind:"type",start:r.index,end:n,bodyStart:s}}return null}function Od(e){let t=e.search(/\bas\s+PropType\s*</);if(t===-1)return null;let i=e.indexOf("<",t),r=Ro(e,i);if(r===-1)return null;if(e.slice(r+1).trim()!=="")return null;return e.slice(i+1,r).trim()}function To(e){let t=e.trim(),i=Od(t);if(i!==null)return{type:i,optional:!0};if(t==="null")return{type:"unknown",optional:!0};if(t.startsWith("[")){let r=nt(t,0,"[","]");if(r!==-1){let n=Ai(t.slice(1,r)).map((o)=>To(o).type).filter((o)=>o!=="unknown");return{type:n.length>0?[...new Set(n)].join(" | "):"unknown",optional:!0}}}if(t.startsWith("{")){let r=ir(t),n=r.find((l)=>l.key==="type"),o=r.find((l)=>l.key==="required"),s=n?To(n.value).type:"unknown",c=!(o&&o.value.trim()==="true");return{type:s,optional:c}}if(Ja[t])return{type:Ja[t],optional:!0};if(/^[A-Za-z_$][\w$.]*$/.test(t))return{type:t,optional:!0};return{type:"unknown",optional:!0}}function _r(e){let t=e.trim();if(t.startsWith("{")){let i=ir(t);if(i.length===0)return"{}";return`{ ${i.map((r)=>{if(r.isMethod||r.value==="")return`${tr(r.key)}?: unknown`;let n=To(r.value);return`${tr(r.key)}${n.optional?"?":""}: ${n.type}`}).join(", ")} }`}if(t.startsWith("[")){let i=nt(t,0,"[","]");if(i===-1)return null;let r=Ai(t.slice(1,i)).map((n)=>er(n.trim())).filter((n)=>n!=="");if(r.length===0)return"{}";return`{ ${r.map((n)=>`${tr(n)}?: unknown`).join(", ")} }`}return null}function Rd(e){let t=e.trim();if(!t.startsWith("["))return null;let i=nt(t,0,"[","]");if(i===-1)return null;let r=Ai(t.slice(1,i)).map((n)=>n.trim());if(r.length===0)return"{}";if(!r.every((n)=>n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"')))return"string[]";return`[${r.map((n)=>JSON.stringify(er(n))).join(", ")}]`}function Pd(e){let t=e.trim();if(!t.startsWith("{"))return null;let i=ir(t);if(i.length===0)return"{}";return`{ ${i.map((r)=>`${JSON.stringify(r.key)}: (...args: any[]) => void`).join(", ")} }`}function Za(e){return Rd(e)??Pd(e)}function Md(e){let t=[],i=0,r="",n=0;while(n<e.length){let o=e[n];if(o==='"'||o==="'"){let s=wt(e,n);r+=e.slice(n,s),n=s;continue}if(o==="`"){let s=$t(e,n);r+=e.slice(n,s),n=s;continue}if(o==="/"&&(e[n+1]==="/"||e[n+1]==="*")){let s=Nt(e,n);r+=e.slice(n,s),n=s;continue}if(o==="="&&e[n+1]===">"){r+="=>",n+=2;continue}if(o==="{"||o==="["||o==="("||o==="<")i++;else if(o==="}"||o==="]"||o===")"||o===">")i--;if((o===";"||o===","||o===`
10
+ `)&&i===0){if(r.trim()!=="")t.push(r.trim());r="",n++;continue}r+=o,n++}if(r.trim()!=="")t.push(r.trim());return t}function Dd(e){let t=e.trim();if(!t.startsWith("{"))return null;let i=nt(t,0,"{","}");if(i===-1||t.slice(i+1).trim()!=="")return null;let r=Md(t.slice(1,i));if(r.length===0)return"{}";let n=[];for(let o of r){let s=/^\(\s*\w+\s*:\s*/.exec(o);if(!s)return null;let c=s[0].length,l=o[c];if(l!=="'"&&l!=='"'&&l!=="`")return null;let f=wt(o,c),u=o.slice(c+1,f-1),d=nt(o,o.indexOf("(",0),"(",")");if(d===-1)return null;let h=o.slice(c,d),p=Ai(h).slice(1),m=o.slice(d+1).trim();if(m.startsWith(":"))m=m.slice(1).trim();if(m==="")m="void";n.push(`${JSON.stringify(u)}: (${p.map((a)=>a.trim()).join(", ")}) => ${m}`)}return`{ ${n.join(", ")} }`}function Po(e){let t=e;for(let i of["defineProps","defineEmits","defineExpose","defineSlots","defineOptions"])t=Id(t,i);return t}function Id(e,t){let i=new RegExp(`\\b${t}\\b`,"g"),r=[],n=e,o;while((o=i.exec(e))!==null){let s=e.lastIndexOf(`
11
+ `,o.index)+1,c=e.slice(s,o.index),l=/^\s*(?:(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*(?::[^=]+)?=\s*)?(withDefaults\s*\(\s*)?$/.exec(c);if(!l)continue;let f=o.index+o[0].length;while(f<e.length&&/\s/.test(e[f]))f++;if(e[f]==="<"){let h=Ro(e,f);if(h===-1)continue;f=h+1;while(f<e.length&&/\s/.test(e[f]))f++}if(e[f]!=="(")continue;let u=nt(e,f,"(",")");if(u===-1)continue;if(l[1]){let h=s+c.length-l[1].length,p=e.indexOf("(",h);if(p!==-1){let m=nt(e,p,"(",")");if(m!==-1)u=m}}let d=u+1;while(d<e.length&&e[d]!==`
12
+ `&&/\s|;/.test(e[d]))d++;if(e[d]===`
13
+ `)d++;r.push([s,d])}for(let s=r.length-1;s>=0;s--)n=n.slice(0,r[s][0])+n.slice(r[s][1]);return n}function Mo(e){let t=Nd(e);if(t!==-1){let i=/^export\s+default\b/.exec(e.slice(t))?.[0];if(!i)return{options:null,script:e,passthrough:!1};let r=t+i.length;while(r<e.length&&/\s/.test(e[r]))r++;let n=-1,o=-1,s=-1;if(e[r]==="{")n=r,o=nt(e,r,"{","}"),s=o;else if(e.startsWith("defineComponent",r)){let f=e.indexOf("(",r);if(f!==-1){let u=f+1;while(u<e.length&&/\s/.test(e[u]))u++;if(e[u]==="{")n=u,o=nt(e,u,"{","}"),s=nt(e,f,"(",")")}}if(n===-1||o===-1||s===-1)return{options:null,script:e,passthrough:!0};let c=s+1;if(e[c]===";")c++;let l=(e.slice(0,t)+e.slice(c)).trim();return{options:e.slice(n,o+1),script:l,passthrough:!1}}return{options:null,script:e,passthrough:!1}}function Nd(e){let t=0,i=0;while(i<e.length){let r=e[i];if(r==='"'||r==="'"){i=wt(e,i);continue}if(r==="`"){i=$t(e,i);continue}if(r==="/"&&(e[i+1]==="/"||e[i+1]==="*")){i=Nt(e,i);continue}if(r==="{"||r==="["||r==="(")t++;else if(r==="}"||r==="]"||r===")")t=Math.max(0,t-1);else if(t===0&&e.startsWith("export",i)){let n=i===0?"":e[i-1],o=e[i+6]??"";if(!/[\w$]/.test(n)&&!/[\w$]/.test(o)){if(/^export\s+default\b/.exec(e.slice(i)))return i}}i++}return-1}function Br(e,t){let i=ir(e).find((r)=>r.key===t);return i&&i.value!==""?i.value:null}function jr(e,t){let i=Wd(e),r=e;for(let n=i.length-1;n>=0;n--){let o=i[n],s=r.slice(0,o.start)+r.slice(o.end);if(Fd(s,o.name))continue;if(new RegExp(`\\btypeof\\s+${o.name}\\b`).test(t))continue;r=s}return r}function Fd(e,t){let i=0;while(i<e.length){let r=e[i];if(r==='"'||r==="'"){i=wt(e,i);continue}if(r==="`"){i=$t(e,i);continue}if(r==="/"&&(e[i+1]==="/"||e[i+1]==="*")){i=Nt(e,i);continue}if(/[A-Za-z_$]/.test(r)){let n=i+1;while(n<e.length&&/[\w$]/.test(e[n]))n++;if(e.slice(i,n)===t)return!0;i=n;continue}i++}return!1}function Wd(e){let t=[],i=Ld(e),r=/^[ \t]*(const|let|var|(?:async[ \t]+)?function)[ \t]+([A-Za-z_$][\w$]*)[ \t]*(?::[^=\n]+)?=?/gm,n;while((n=r.exec(e))!==null){let o=e.lastIndexOf(`
14
+ `,n.index)+1;if(!i.has(o))continue;if(/\bexport\b/.test(e.slice(o,n.index)))continue;let s=n[1],c=n[2],l=n.index+n[0].length,f=-1;if(s.endsWith("function")){let u=e.indexOf("(",l);if(u===-1)continue;let d=nt(e,u,"(",")");if(d===-1)continue;l=d+1;while(l<e.length&&/\s/.test(e[l]))l++;if(e[l]===":")while(l<e.length&&e[l]!=="{"&&e[l]!==`
15
+ `)l++;while(l<e.length&&/\s/.test(e[l])&&e[l]!==`
16
+ `)l++;if(e[l]!=="{")continue;let h=nt(e,l,"{","}");if(h===-1)continue;f=h+1}else{let u=0;while(l<e.length){let d=e[l];if(d==='"'||d==="'"){l=wt(e,l);continue}if(d==="`"){l=$t(e,l);continue}if(d==="/"&&(e[l+1]==="/"||e[l+1]==="*")){l=Nt(e,l);continue}if(d==="{"||d==="["||d==="(")u++;else if(d==="}"||d==="]"||d===")")u--;else if(d===";"&&u===0){f=l+1;break}else if(d===`
17
+ `&&u===0){f=l;break}l++}if(f===-1)f=e.length}if(e[f]===`
18
+ `)f++;t.push({name:c,start:n.index,end:f})}return t}function Ld(e){let t=new Set([0]),i=0,r=0;while(r<e.length){let n=e[r];if(n==='"'||n==="'"){r=wt(e,r);continue}if(n==="`"){r=$t(e,r);continue}if(n==="/"&&(e[r+1]==="/"||e[r+1]==="*")){r=Nt(e,r);continue}if(n==="{"||n==="["||n==="(")i++;else if(n==="}"||n==="]"||n===")")i=Math.max(0,i-1);if(n===`
19
+ `&&i===0)t.add(r+1);r++}return t}function Gr(e,t,i){let r=e.indexOf(i);if(r===-1)return e;let n=e.lastIndexOf(`
20
+ `,r)+1;if(/\bexport\b/.test(e.slice(n,r)))return e;let o=e.slice(0,r)+e.slice(r+i.length);if(new RegExp(`\\b${t}\\b`).test(o))return e;return o}function Do(e){let t="",i=0,r=()=>{for(let o=t.length-1;o>=0;o--)if(!/\s/.test(t[o]))return t[o];return""},n=(o)=>{for(let s=o;s<e.length;s++)if(!/\s/.test(e[s]))return e[s];return""};while(i<e.length){let o=e[i];if(o==='"'||o==="'"){let s=wt(e,i);t+=e.slice(i,s),i=s;continue}if(o==="`"){let s=$t(e,i);t+=e.slice(i,s),i=s;continue}if(o==="/"&&e[i+1]==="*"){let s=Nt(e,i);t+=e.slice(i,s).replace(/\s*\n\s*/g," "),i=s;continue}if(o==="/"&&e[i+1]==="/"){let s=i+2;while(s<e.length&&e[s]!==`
21
+ `)s++;let c=e.slice(i+2,s).trim();if(c!==""&&!c.includes("*/"))t+=`/* ${c} */`;i=s;continue}if(o===`
22
+ `){let s=r(),c=n(i+1);if(s===""||c===""){i++;continue}let l=Bd(t);if(!l&&("{;,(<:=[".includes(s)||"}),]>;|&".includes(c))){if(!t.endsWith(" ")&&!t.endsWith(";"))t+=" "}else if(l){if(!t.endsWith(" "))t+=" "}else{if(t.endsWith(" "))t=t.slice(0,-1);t+="; "}i++;while(i<e.length&&(e[i]===" "||e[i]==="\t"))i++;continue}t+=o,i++}return t}function Bd(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 i=e.lastIndexOf("/*",t);if(i===-1)return!1;for(let r=i-1;r>=0;r--){let n=e[r];if(/\s/.test(n))continue;return"{;,(<:".includes(n)}return!0}function Vr(e,t){let i=[e,t].filter((r)=>r!==null);for(let r of i){let n=rr(r,"defineProps");if(!n)continue;if(n.generic){let o=n.generic;if(o.startsWith("{"))return{type:o};if(/^[A-Za-z_$][\w$]*$/.test(o)){for(let s of i){let c=Xa(s,o);if(!c)continue;let l=kd(s,o);if(l===null)continue;return{type:l,inlinedLocal:{name:o,declText:s.slice(c.start,c.end)}}}return{type:o}}return{type:o}}if(n.arg){let o=_r(n.arg);if(o!==null)return{type:o}}}return null}function Io(e,t){let i=[e,t].filter((r)=>r!==null);for(let r of i){let n=rr(r,"defineEmits");if(!n)continue;if(n.generic)return Dd(n.generic)??n.generic;if(n.arg){let o=Za(n.arg);if(o!==null)return o}}return null}function No(e,t){let i=[e,t].filter((r)=>r!==null);for(let r of i){let n=rr(r,"defineExpose");if(!n||!n.arg||!n.arg.startsWith("{"))continue;let o=ir(n.arg);if(o.length===0)return null;return`{ ${o.map((s)=>{if(s.value===""&&/^[A-Za-z_$][\w$]*$/.test(s.key))return`${tr(s.key)}: typeof ${s.key}`;let c=s.isMethod||/=>|^\s*function\b/.test(s.value);return`${tr(s.key)}: ${c?"(...args: any[]) => any":"unknown"}`}).join(", ")} }`}return null}function Qa(e){let t=Td(e),i="",r=null,n=null;if(t.script){let C=Mo(t.script.content);if(C.passthrough)return t.scriptSetup?`${t.script.content}
23
+ ${t.scriptSetup.content}`:t.script.content;if(i=C.script,C.options){let b=Br(C.options,"props");if(b)r=_r(b);let v=Br(C.options,"emits");if(v)n=Za(v)}}let o=t.scriptSetup?.content??null,s=o!==null?Po(o):null,c=Vr(o,o!==null?null:i),l=c?.type??r??"{}",f=Io(o,null)??n,u=No(o,null),d=c?.inlinedLocal;if(d){if(i=Gr(i,d.name,d.declText),s!==null)s=Gr(s,d.name,d.declText)}let h=[l,u??"{}"];if(f)h.push("{}","{}","{}","{}","{}",f);let p=Do(`DefineComponent<${h.join(", ")}>`),m=[],a=jr(i,p);if(a.trim()!=="")m.push(a);if(s&&s.trim()!==""){let C=jr(s,p);if(C.trim()!=="")m.push(C)}return m.push("import type { DefineComponent } from 'vue'"),m.push(`type __DtsxComponentType = ${p}`),m.push("const __dtsx_component__: __DtsxComponentType = null as unknown as __DtsxComponentType"),m.push("export default __dtsx_component__"),m.join(`
24
+ `)}var Ja;var Fo=me(()=>{Ja={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 tl(e){return e.endsWith(".stx")}function jd(e){let t=[],i=/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi,r;while((r=i.exec(e))!==null){let n=r[1]??"",o=/\blang\s*=\s*["']([^"']+)["']/i.exec(n)?.[1]?.toLowerCase()??(/\b(?:type\s*=\s*["'](?:text\/)?typescript["']|typescript)\b/i.test(n)?"ts":"js"),s=/\bserver\b/i.test(n)?"server":/\bclient\b/i.test(n)?"client":"universal";t.push({content:r[2]??"",kind:"script",attrs:n,context:s,lang:o,start:r.index})}return t}function Gd(e){let t=[],i=/^[ \t]*@ts[ \t]*(?:\r?\n|$)/gm,r;while((r=i.exec(e))!==null){let n=i.lastIndex,o=/^[ \t]*@endts[ \t]*(?:\r?\n|$)/gm;o.lastIndex=n;let s=o.exec(e),c=s?.index??e.length;if(t.push({content:e.slice(n,c),kind:"ts",attrs:"",context:"universal",lang:"ts",start:r.index}),!s)break;i.lastIndex=o.lastIndex}return t}function _d(e){return[...jd(e),...Gd(e)].sort((t,i)=>t.start-i.start)}function Vd(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 Ud(e){let t=/(?:\$?props)\s+as\s+/g,i;while((i=t.exec(e))!==null){let r=t.lastIndex;while(r<e.length&&/\s/.test(e[r]))r++;if(e[r]==="{"){let s=nt(e,r,"{","}");if(s!==-1)return e.slice(r,s+1).trim();continue}let n=/^[A-Za-z_$][\w$]*/.exec(e.slice(r))?.[0];if(!n)continue;let o=r+n.length;while(o<e.length&&/\s/.test(e[o]))o++;if(e[o]==="<"){let s=nt(e,o,"<",">");if(s!==-1)o=s+1}return e.slice(r,o).trim()}return null}function Kd(e){return/\b(?:const|let|var)\s+\$?props\s*:\s*([^=;\n]+)/.exec(e)?.[1]?.trim()??null}function zd(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 Hd(e,t){if(!e||e==="unknown")return t;if(t==="unknown"||e===t)return e;return[...new Set([...e.split(" | "),...t.split(" | ")])].join(" | ")}function qd(e){let t=Oo(e),i=new Map,r=/\$props(?:\.([A-Za-z_$][\w$]*)|\[\s*(['"])([^'"\n]+)\2\s*\])/g,n;while((n=r.exec(e))!==null){if(t.slice(n.index,n.index+6)!=="$props")continue;let o=n[1]??n[3],s=zd(e.slice(r.lastIndex));i.set(o,Hd(i.get(o),s))}if(i.size===0)return null;return{type:`{ ${[...i].map(([o,s])=>`${/^[A-Za-z_$][\w$]*$/.test(o)?o:JSON.stringify(o)}?: ${s}`).join(", ")} }`}}function Jd(e){let t=Vr(e,null);if(t)return t;let i=Ud(e)??Kd(e);if(!i)return qd(e);if(/^[A-Za-z_$][\w$]*$/.test(i)){let r=i.replace(/[$]/g,"\\$&");if(new RegExp(`\\bexport\\s+(?:declare\\s+)?(?:interface|type)\\s+${r}\\b`).test(e))return{type:i}}return Vr(`${e}
25
+ defineProps<${i}>()`,null)}function Yd(e){return Po(e)}function el(e){let t=Oo(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 Xd(e){let t=[],i=0,r=0,n=0;while(n<e.length){let s=e[n],c=ko(e,n);if(c>n){n=c;continue}if(s==="{"||s==="["||s==="(")r++;else if(s==="}"||s==="]"||s===")")r=Math.max(0,r-1);if((s===";"||s===`
26
+ `)&&r===0){let l=n+1;if(!el(e.slice(i,l)))t.push([i,l]);i=l}n++}if(i<e.length&&!el(e.slice(i)))t.push([i,e.length]);let o=e;for(let s=t.length-1;s>=0;s--)o=o.slice(0,t[s][0])+o.slice(t[s][1]);return o}function il(e){let t=_d(e).filter(Vd).map((a)=>a.content).join(`
27
+ `),i=null,r=Mo(t);if(r.passthrough)return t;if(t=r.script,r.options){let a=Br(r.options,"props");if(a)i=_r(a)}let n=t,o=Yd(t),s=Jd(n),c=s?.type??i??"{}",l=Io(n,null),f=No(n,null),u=rr(n,"defineSlots")?.generic??null,d=s?.inlinedLocal;if(d)o=Gr(o,d.name,d.declText);let h=`DefineComponent<${c}>`,p=[];if(l)p.push(`readonly __stxEmits?: ${l}`);if(u)p.push(`readonly __stxSlots?: ${u}`);if(f)p.push(`readonly __stxExposed?: ${f}`);if(p.length>0)h+=` & { ${p.join(", ")} }`;h=Do(h),o=Xd(jr(o,h));let m=["import type { DefineComponent } from '@stacksjs/stx'",`type __DtsxStxComponentType = ${h}`,"const __dtsx_component__: __DtsxStxComponentType = null as unknown as __DtsxStxComponentType","export default __dtsx_component__"];if(o.trim()!=="")m.push(o);return m.join(`
28
+ `)}var rl=me(()=>{Fo()});function ft(e){return e>=65&&e<=90||e>=97&&e<=122||e===95||e===36||e>127}function ze(e){return ft(e)||e>=48&&e<=57}function nl(e,t){let i=t;for(;;){while(i>=0&&(e.charCodeAt(i)===32||e.charCodeAt(i)===9||e.charCodeAt(i)===10||e.charCodeAt(i)===13))i--;if(i<0)return-1;if(e.charCodeAt(i)===47&&i>0&&e.charCodeAt(i-1)===42){let o=e.lastIndexOf("/*",i-2);if(o===-1)return-1;i=o-1;continue}let r=e.lastIndexOf(`
29
+ `,i)+1,n=Zd(e,r,i);if(n!==-1){i=n-1;continue}return i}}function Zd(e,t,i){let r=0;for(let n=t;n<=i;n++){let o=e.charCodeAt(n);if(r){if(o===92){n++;continue}if(o===r)r=0;continue}if(o===39||o===34||o===96){r=o;continue}if(o===47&&n+1<=i&&e.charCodeAt(n+1)===47)return n}return-1}function ol(e){return e===61||e===40||e===91||e===33||e===38||e===124||e===63||e===58||e===44||e===59||e===123||e===125||e===94||e===126||e===43||e===45||e===42||e===37||e===60||e===62}function sl(e){return e==="return"||e==="typeof"||e==="void"||e==="delete"||e==="throw"||e==="new"||e==="in"||e==="of"||e==="case"||e==="instanceof"||e==="yield"||e==="await"||e==="else"||e==="do"}function Qd(e,t){let i=[],r=[],n=0,o=!1,s="",c="",l=!0,f=0,u=(d,h=!1)=>{c=s,s=d,l=h};while(f<=t){let d=e.charCodeAt(f);if(o){if(d===92){f+=2;continue}if(d===96)o=!1,u("literal");else if(d===36&&e.charCodeAt(f+1)===123)r.push(n++),o=!1,u("{",!0),f++;f++;continue}if(d===32||d===9||d===10||d===13){f++;continue}if(d===47&&e.charCodeAt(f+1)===47){let h=e.indexOf(`
30
+ `,f+2);f=h===-1?e.length:h+1;continue}if(d===47&&e.charCodeAt(f+1)===42){let h=e.indexOf("*/",f+2);f=h===-1?e.length:h+2;continue}if(d===39||d===34){let h=d;f++;while(f<e.length){let p=e.charCodeAt(f++);if(p===92)f++;else if(p===h)break}u("literal");continue}if(d===96){o=!0,f++;continue}if(ft(d)||d===35&&ft(e.charCodeAt(f+1))){let h=f++;while(ze(e.charCodeAt(f)))f++;let p=e.slice(h,f);u(p,s!=="."&&sl(p));continue}if(d===40){let h=c!=="."&&(s==="if"||s==="while"||s==="for"||s==="with"||s==="switch"||s==="catch"||s==="await"&&c==="for");i.push(h),u("(",!0)}else if(d===41){let h=i.pop()??!1;if(f===t)return h;u(")",h)}else if(d===47&&l){f=nr(e,f),u("literal");continue}else{if(d===123)n++;else if(d===125){if(n--,r.at(-1)===n)r.pop(),o=!0}u(e[f],d===47||ol(d))}f++}return!1}function Ur(e,t){let i=nl(e,t-1);if(i<0)return!0;let r=e.charCodeAt(i);if(r===41)return Qd(e,i);if(ol(r))return!0;if(ze(r)){let n=i;while(n>=0&&ze(e.charCodeAt(n)))n--;let o=e.charCodeAt(nl(e,n));if(o===46||o===35)return!1;return sl(e.slice(n+1,i+1))}return!1}function nr(e,t){let i=t,r=e.length;i++;let n=!1;while(i<r){let o=e.charCodeAt(i);if(o===92){i+=2;continue}if(n){if(o===93)n=!1;i++;continue}if(o===91){n=!0,i++;continue}if(o===47){i++;break}if(o===10||o===13)break;i++}while(i<r&&ze(e.charCodeAt(i)))i++;return i}var or=()=>{};function se(e){let t=[],i=0;function r(){let o=i++;while(i<e.length)if(e[i]==="\\")i+=2;else if(e[i]==="`"){t.push({start:o,end:++i,kind:"literal"});return}else if(e[i]==="$"&&e[i+1]==="{")t.push({start:o,end:i+1,kind:"literal"}),t.push({start:i+1,end:i+2,kind:"punctuation"}),i+=2,n(!0),o=i;else i++;t.push({start:o,end:i,kind:"literal"})}function n(o=!1){let s=0;while(i<e.length){let c=i,l=e[i];if(/\s/.test(l)){i++;continue}if(l==="/"&&e[i+1]==="/"){let f=e.indexOf(`
31
+ `,i+2);i=f===-1?e.length:f+1;continue}if(l==="/"&&e[i+1]==="*"){let f=e.indexOf("*/",i+2);i=f===-1?e.length:f+2;continue}if(l==="/"&&Ur(e,i))i=nr(e,i),t.push({start:c,end:i,kind:"literal"});else if(l==="`")r();else if(l==='"'||l==="'"){i++;let f=!1;while(i<e.length){let u=e[i++];if(u==="\\")i++;else if(u===l){f=!0;break}}t.push({start:c,end:Math.min(i,e.length),kind:f?"quoted":"literal"})}else if(ft(e.charCodeAt(i))){while(ze(e.charCodeAt(++i)));t.push({start:c,end:i,kind:"word"})}else if(t.push({start:c,end:++i,kind:"punctuation"}),o){if(l==="{")s++;else if(l==="}"){if(s===0)return;s--}}}}return n(),t}function mt(e){let t="",i=e.length-1;for(let r=1;r<i;r++){if(e[r]!=="\\"){t+=e[r];continue}let n=e[++r];if(r>=i)return;switch(n){case`
32
+ `:break;case"\r":if(e[r+1]===`
33
+ `)r++;break;case"n":t+=`
34
+ `;break;case"r":t+="\r";break;case"t":t+="\t";break;case"b":t+="\b";break;case"f":t+="\f";break;case"v":t+="\v";break;case"0":if(/\d/.test(e[r+1]??""))return;t+="\x00";break;case"x":case"u":{let o=n==="u"&&e[r+1]==="{",s=r+(o?2:1),c=o?e.indexOf("}",s):s+(n==="x"?2:4),l=e.slice(s,c);if(c<s||c>i||!/^[\da-f]+$/i.test(l)||o&&l.length>6)return;let f=Number.parseInt(l,16);if(f>1114111)return;t+=String.fromCodePoint(f),r=o?c:c-1;break}default:if(/\d/.test(n))return;t+=n}}return t}function ti(e,t){let i=t;for(let r of e){let n=r.charCodeAt(0);if(r===t||r==="\\")i+=`\\${r}`;else if(n<32||n===8232||n===8233||r.length===1&&n>=55296&&n<=57343)i+=`\\u${n.toString(16).padStart(4,"0")}`;else i+=r}return i+t}function Kr(e){let t=se(e),i=(c)=>t[c]?e.slice(t[c].start,t[c].end):"";if(i(0)!=="import")return;let r=i(1)==="type"&&i(2)!=="=",n=r?2:1;if(t[n]?.kind!=="word"||i(n+1)!=="="||i(n+2)!=="require"||i(n+3)!=="("||t[n+4]?.kind!=="quoted"||i(n+5)!==")")return;let o=n+6;if(t.length!==o&&!(t.length===o+1&&i(o)===";"))return;let s=mt(i(n+4));if(s===void 0)return;return{name:i(n),source:s,isTypeOnly:r,end:t[t.length-1].end}}function kt(e){let t=se(e),i=[],r=new Set,n=(h)=>h>=0&&h<t.length?e.slice(t[h].start,t[h].end):"",o=(h)=>t[h]?.kind==="quoted",s=(h)=>t[h]?.kind==="word",c=[],l=!1,f=0;if(e.includes("declare")&&e.includes("module"))for(let h=0;h<t.length;h++){let p=n(h);if(f===0&&s(h)&&n(h-1)!=="."&&n(h-1)!=="#"){if(p==="export"||p==="import"&&n(h+1)!=="("&&n(h+1)!==".")l=!0;if(p==="declare"&&n(h+1)==="module"&&o(h+2)&&n(h+3)==="{")c.push(h+2)}if(p==="{"||p==="("||p==="[")f++;else if(p==="}"||p===")"||p==="]")f--}function u(h,p=!1){if(n(h)==="*"){if(n(h+1)==="as")return s(h+2)||p&&o(h+2)?h+3:-1;return p?h+1:-1}if(n(h)!=="{")return-1;let m=1;for(let a=h+1;a<t.length;a++)if(n(a)==="{")m++;else if(n(a)==="}"&&--m===0)return a+1;else if(t[a].kind==="literal"||n(a)===";")return-1;return-1}function d(h,p,m,a){let C=t[h];if(!C||C.kind!=="quoted"||r.has(C.start))return;let b=mt(e.slice(C.start,C.end));if(b===void 0)return;r.add(C.start),i.push({specifier:b,kind:p,isTypeOnly:m,category:a,start:C.start,end:C.end})}for(let h=0;h<t.length;h++){if(!s(h)||n(h-1)==="."||n(h-1)==="#")continue;let p=n(h),m=h+1;if(p==="export"){let a=n(m)==="type";if(a)m++;let C=n(m)==="*"?n(m+1)==="as"?"export-star-as":"export-star":"export-named",b=u(m,!0);if(b>=0&&n(b)==="from")d(b+1,C,a,"export")}else if(p==="import"){if(o(m)){d(m,"import",!1,"static-import");continue}if(n(m)==="("){if(n(m+2)===")"||n(m+2)===",")d(m+1,"import",!1,"import-type");continue}let a=n(m)==="type"&&n(m+1)!=="from"&&n(m+1)!=="="&&n(m+1)!==",";if(a)m++;if(s(m)){if(m++,n(m)==="="){if(n(m+1)==="require"&&n(m+2)==="("&&n(m+4)===")")d(m+3,"import",a,"static-import");continue}if(n(m)===",")m=u(m+1)}else m=u(m);if(m>=0&&n(m)==="from")d(m+1,"import",a,"static-import")}}if(l&&c.length){for(let h of c)d(h,"import",!0,"augmentation");i.sort((h,p)=>h.start-p.start)}return i}var ut=me(()=>{or()});function zr(e,t){let i=se(e),r=0,n=0;for(let o=0;o<i.length;o++){let s=i[o],c=e.slice(s.start,s.end),l=i[o+1];if(r===0&&c==="function"&&l?.kind==="word"&&e.slice(l.start,l.end)===t)n++;if(["{","(","["].includes(c))r++;else if(["}",")","]"].includes(c))r--}return n}var Wo=me(()=>{ut()});function al(e){let t=se(e),i=(l)=>t[l]?e.slice(t[l].start,t[l].end):"",r=new Map,n=[];for(let l=0;l<t.length;l++)if(["(","[","{"].includes(i(l)))n.push(l);else if([")","]","}"].includes(i(l))){let f=n.pop();if(f===void 0||!["()","[]","{}"].includes(i(f)+i(l)))throw Error("Unbalanced binding pattern");r.set(f,l)}if(n.length)throw Error("Unbalanced binding pattern");for(let l=0;l<t.length;l++){if(i(l)!=="<")continue;let f=["=",",","(",":","?","[","{"].includes(i(l-1)),u=1;for(let d=l+1;d<t.length;d++){if(i(d)==="="&&i(d+1)!==">"&&u===1&&!f)break;if(i(d)==="<")u++;else if(i(d)===">"&&i(d-1)!=="="&&--u===0){if(d+1===t.length||["(","[",".",",","}","]",")","?",":",";","=",">"].includes(i(d+1)))r.set(l,d);break}let h=r.get(d);if(h!==void 0)d=h}}let o=(l,f)=>({text:l<f?e.slice(t[l].start,t[f-1].end):"",offset:t[l]?.start??e.length}),s=(l,f,u)=>{for(let d=l;d<f;d++){if(i(d)===u)return d;let h=r.get(d);if(h!==void 0)d=h}return},c=(l,f)=>{let u=s(l,f,"="),d=u===void 0?void 0:o(u+1,f);if(u!==void 0)f=u;if(l+1===f&&t[l]?.kind==="word")return{kind:"name",name:i(l),defaultValue:d};let h=i(l)==="{"?"object":i(l)==="["?"array":void 0;if(!h||r.get(l)!==f-1)throw Error(`Invalid binding target: ${o(l,f).text}`);let p=[],m=l+1;while(m<f-1){let a=s(m,f-1,","),C=a??f-1;if(m===C)p.push(void 0);else if(i(m)==="."&&i(m+1)==="."&&i(m+2)===".")p.push({rest:!0,target:c(m+3,C)});else if(h==="array")p.push({rest:!1,target:c(m,C)});else if(i(m)==="["){let b=r.get(m);if(b===void 0||i(b+1)!==":")throw Error("Computed binding needs a target");p.push({computed:o(m+1,b),rest:!1,target:c(b+2,C)})}else{let b=m+1;if(t[m].kind!=="word"&&t[m].kind!=="quoted")while(b<C&&i(b)!==":")b++;let v=i(b)===":";if(!v&&t[m].kind!=="word")throw Error("Invalid object binding key");p.push({key:o(m,v?b:m+1).text,rest:!1,target:c(v?b+1:m,C)})}if(a===void 0)break;m=a+1}return{kind:h,elements:p,defaultValue:d}};return c(0,t.length)}function Lo(e,t){if(e.kind==="name")t.push(e.name);else for(let i of e.elements)if(i)Lo(i.target,t)}function ll(e){let t=[];return Lo(al(e),t),t}function cl(e){let t=al(e.pattern),i=[];if(Lo(t,i),!i.length)return[];let r=[e.root],n=!1,o={start:e.root.start,end:e.root.end},s=(l,f)=>{let u=e.allocateName();return r.push({kind:"variable",name:u,text:`declare ${f} ${u}: unknown;`,value:l.text,initializerStart:e.patternOffset+l.offset,modifiers:[f],isExported:!1,...o}),u},c=(l,f)=>{if(l.defaultValue){let v=s(l.defaultValue,e.kind),T=e.allocateName();f=`(${f}) extends infer ${T} ? ${T} extends undefined ? typeof ${v} : ${T} : never`}if(l.kind==="name"){let v=n?void 0:e.comments;n=!0,r.push({kind:"variable",name:l.name,text:`${e.exported?"export ":""}declare ${e.kind} ${l.name}: ${f};`,typeAnnotation:f,modifiers:[e.kind],isExported:e.exported,leadingComments:v,...o});return}let u=l.elements,d=[],h=[],p=[];for(let v of u){if(!v){d.push("");continue}let T=e.allocateName(),B=v.key;if(v.computed)B=`[${s(v.computed,"const")}]`;d.push(v.rest?`...${T}`:l.kind==="object"?`${B}: ${T}`:T),h.push({target:v.target,index:p.length}),p.push(`typeof ${T}`)}let m=e.allocateName(),a=e.allocateName(),C=e.allocateName(),b=l.kind==="object"?`{ ${d.join(", ")} }`:`[${d.join(", ")}]`;r.push({kind:"function",name:m,text:`declare function ${m}(${b}: ${f}): [${p.join(", ")}];`,isExported:!1,...o}),r.push({kind:"type",name:a,text:`type ${a} = (typeof ${m}) extends (...args: never[]) => infer ${C} ? ${C} : never;`,isExported:!1,...o});for(let v of h)c(v.target,`${a}[${v.index}]`)};return c(t,`typeof ${e.root.name}`),r}var Bo=me(()=>{ut()});function Ot(e,t,i=0){if(i>=64)return;let r=e.trim(),n=se(r);if(!n.length)return;if(n[0].start!==0||n[n.length-1].end!==r.length)return Ot(r.slice(n[0].start,n[n.length-1].end),t,i+1);if(n.length===1&&n[0].kind==="quoted")return mt(r);if(n.length===1&&n[0].kind==="word"){let u=t.get(r);return typeof u==="object"?void 0:u}if(fl.exec(r)?.[0].length===r.length){let u=Number(r.replaceAll("_",""));return Number.isFinite(u)?u:void 0}let o=0,s;for(let u=0;u<n.length;u++){let d=n[u],h=r.slice(d.start,d.end);if(d.kind!=="punctuation")continue;if(["(","[","{"].includes(h)){o++;continue}if([")","]","}"].includes(h)){o--;continue}let p=fl.exec(r.slice(d.start));if(p){while(n[u+1]?.start<d.start+p[0].length)u++;continue}if(o)continue;let m=th.find((b)=>r.startsWith(b,d.start));if(!m)continue;let a=n[u-1],C=a?r.slice(a.start,a.end):"";if(!(!a||a.kind==="punctuation"&&![")","]"].includes(C)&&!/\d/.test(C))&&(!s||jo[m]<s.priority||jo[m]===s.priority&&m!=="**"))s={start:d.start,operator:m,priority:jo[m]};while(n[u+1]?.start<d.start+m.length)u++}if(s){let u=Ot(r.slice(0,s.start),t,i+1),d=Ot(r.slice(s.start+s.operator.length),t,i+1);if(u===void 0||d===void 0)return;if(s.operator==="+"&&(typeof u==="string"||typeof d==="string"))return String(u)+String(d);if(typeof u!=="number"||typeof d!=="number")return;let h;switch(s.operator){case"+":h=u+d;break;case"-":h=u-d;break;case"*":h=u*d;break;case"/":h=u/d;break;case"%":h=u%d;break;case"**":h=u**d;break;case"<<":h=u<<d;break;case">>":h=u>>d;break;case">>>":h=u>>>d;break;case"|":h=u|d;break;case"^":h=u^d;break;case"&":h=u&d;break;default:return}return Number.isFinite(h)?h:void 0}if(r.startsWith("(")&&r.endsWith(")")){let u=0;if(n.every((d,h)=>{let p=r.slice(d.start,d.end);if(p==="(")u++;if(p===")")u--;return u!==0||h===n.length-1}))return Ot(r.slice(1,-1),t,i+1)}if(["+","-","~"].includes(r[0])){let u=Ot(r.slice(1),t,i+1);if(typeof u!=="number")return;return r[0]==="-"?-u:r[0]==="~"?~u:u}if(!r.startsWith("`")||!r.endsWith("`"))return;let c="",l=1;for(let u=1;u<r.length-1;u++){if(r[u]==="\\"){u++;continue}if(r[u]!=="$"||r[u+1]!=="{")continue;let d=mt(`\`${r.slice(l,u)}\``);if(d===void 0)return;c+=d;let h=0,p=n.find((a)=>{if(a.start<u+2||a.kind!=="punctuation")return!1;let C=r.slice(a.start,a.end);if(C==="{")h++;if(C!=="}")return!1;if(h===0)return!0;return h--,!1});if(!p)return;let m=Ot(r.slice(u+2,p.start),t,i+1);if(m===void 0)return;c+=String(m),u=p.start,l=u+1}let f=mt(`\`${r.slice(l,-1)}\``);return f===void 0?void 0:c+f}function ul(e,t){let i=[...new Set([...e,...t.values()])];if(!i.some((s)=>s.kind==="variable"&&typeof s.value==="string"&&/[\[{]/.test(s.value)))return;i.sort((s,c)=>(s.start??0)-(c.start??0));let r=new Map,n=new Map,o=i.some((s)=>s.name==="Symbol");for(let s of i){if(s.kind!=="variable"||typeof s.value!=="string")continue;if(s.value.includes("{")||s.value.includes("[")){let u=new Map(r);u.mutableBindingTypes=new Map(n),s.computedKeyConstants=u}let c=se(s.value),l=c.length===1&&c[0].kind==="word"?r.get(s.value.slice(c[0].start,c[0].end)):void 0;if(s.typeAnnotation==="unique symbol"||s.typeAnnotation==="symbol"||typeof l==="object"||!o&&c[0]?.kind==="word"&&s.value.slice(c[0].start,c[0].end)==="Symbol"&&["(","."].includes(s.value.slice(c[1]?.start,c[1]?.end))){r.set(s.name,eh);continue}if(s.modifiers?.[0]!=="const"||s.typeAnnotation||s.modifiers.includes("const assertion"))continue;let f=Ot(s.value,r);if(f!==void 0){if(r.set(s.name,f),!(c.length===1&&c[0].kind==="word")||n.has(s.value.trim()))n.set(s.name,typeof f)}else if(s.value.trim()==="true"||s.value.trim()==="false")n.set(s.name,"boolean");else if(c.length===1&&c[0].kind==="word"){let u=n.get(s.value.trim());if(u)n.set(s.name,u)}}}function dl(e,t){if(!e.trimStart().startsWith("[")||!e.includes("`"))return;let i=se(e);if(e[i[0]?.start]!=="["||e[i[1]?.start]!=="`"||e[i.at(-1)?.start??-1]!=="]")return;let r=e.slice(i[0].end,i.at(-1).start).trim(),n=Ot(r,t??new Map);return typeof n==="string"?{name:ti(n,"'")}:{index:!0}}function hl(e,t){if(!t||!e.trimStart().startsWith("["))return!1;let i=se(e);return i.length===3&&e[i[0].start]==="["&&i[1].kind==="word"&&e[i[2].start]==="]"&&typeof t.get(e.slice(i[1].start,i[1].end))==="object"}function pl(e){if(!e.trimStart().startsWith("[")||!e.includes("`"))return!1;let t=se(e);return e[t[1]?.start]==="`"&&t.some((i)=>i.kind==="punctuation"&&e[i.start]==="{")}var eh,fl,jo,th;var Hr=me(()=>{ut();eh={kind:"symbol"},fl=/^(?:0[xX][\da-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:[\d_]+(?:\.[\d_]*)?|\.[\d_]+)(?:[eE][+-]?[\d_]+)?)/,jo={"|":1,"^":2,"&":3,"<<":4,">>":4,">>>":4,"+":5,"-":5,"*":6,"/":6,"%":6,"**":7},th=[">>>","<<",">>","**","+","-","*","/","%","|","^","&"]});function qr(e){let t=se(e);if(t.length!==1||t[0].kind!=="word")return;let i=e.slice(t[0].start,t[0].end);return["true","false","null","undefined","this","super"].includes(i)?void 0:i}function Go(e){let t=se(e);if(t.length===0)return!0;let i=t[t.length-1],r=e.slice(i.start,i.end);if(i.kind==="word"&&(r==="is"||r==="extends"))return!0;if(r==="|"||r==="&")return!0;let n=t[t.length-2];return r===">"&&n!==void 0&&e.slice(n.start,n.end)==="="}function hi(e){let t=se(e),i=0;for(let r=0;r<t.length;r++){let n=t[r],o=e.slice(n.start,n.end),s=t[r+1]?e.slice(t[r+1].start,t[r+1].end):"";if(i===0&&n.kind==="word"&&(o==="export"||o==="import"&&s!=="("&&s!=="."))return!0;if(o==="{"||o==="("||o==="[")i++;else if(o==="}"||o===")"||o==="]")i--}return!1}function ml(e){if(e.isExported)return!1;if(["function","variable","interface","type","class","enum","namespace"].includes(e.kind))return!0;return e.kind==="module"&&(e.moduleForm==="namespace"||e.moduleForm==="identifier")}function _o(e,t){let i=e.text,r=se(i),n=(d)=>r[d]?i.slice(r[d].start,r[d].end):"",o=(d)=>r[d]?.kind==="word",s=new Map,c=[];for(let d=0;d<r.length;d++){let h=n(d);if(h==="("||h==="["||h==="{"||h==="<")c.push(d);else if(h===")"||h==="]"||h==="}"||h===">"&&n(d-1)!=="="){let p=c.at(-1);if(p!==void 0&&(n(p)==="("&&h===")"||n(p)==="["&&h==="]"||n(p)==="{"&&h==="}"||n(p)==="<"&&h===">"))c.pop(),s.set(p,d)}}let l=[];for(let d=0;d<r.length;d++){if(n(d)!=="(")continue;let h=s.get(d);if(h===void 0||!(n(h+1)===":"||n(h+1)==="="&&n(h+2)===">"))continue;let p=new Set,m=d+1;while(m<h){let C=m;while(C<h&&n(C)!==","){let T=s.get(C);if(T!==void 0)C=T+1;else C++}let b=m;while(b<C&&n(b)!==":"&&n(b)!=="="){let T=s.get(b);if(T!==void 0)b=T+1;else b++}let v=m;while([".","public","private","protected","readonly","override"].includes(n(v)))v++;if(n(v)==="{"||n(v)==="[")for(let T of ll(i.slice(r[v].start,r[b-1].end)))p.add(T);else if(o(v))p.add(n(v));m=C+1}let a=h+(n(h+1)===":"?2:3);while(a<r.length){if([";",",",")","]","}"].includes(n(a))||n(a)===">"&&n(a-1)!=="=")break;let C=s.get(a);if(C!==void 0)a=C+1;else a++}l.push({start:d,end:a,names:p})}let f=(d)=>{if(!o(d))return;let h=n(d);if(!l.some((p)=>d>=p.start&&d<p.end&&p.names.has(h)))t.add(h)},u=(d,h)=>{for(let p=d;p<h;p++){if(n(p)==="<"&&s.has(p)){p=s.get(p);continue}if(!o(p)||n(p-1)==="."||n(p+1)===":")continue;if(["true","false","null","undefined","new","this","super","as","satisfies","typeof","void","keyof"].includes(n(p)))continue;f(p)}};for(let d=0;d<r.length;d++){if(n(d)==="typeof")f(d+1);if(n(d)==="export"){let h=d+1;if(n(h)==="default"){if(!["function","class","abstract"].includes(n(h+1)))u(h+1,r.length);continue}if(n(h)==="type")h++;if(n(h)==="{"){let p=s.get(h);if(p===void 0||n(p+1)==="from")continue;for(let m=h+1;m<p;){if(n(m)==="type"&&o(m+1)&&n(m+1)!=="as")m++;f(m);while(m<p&&n(m)!==",")m++;m++}}}if(n(d)==="["){let h=s.get(d);if(h!==void 0&&[":","?","("].includes(n(h+1))&&n(d+2)!==":"&&n(d+2)!=="in")u(d+1,h)}}if(e.kind==="class"){let d=-1;for(let h=0;h<r.length&&n(h)!=="{";h++)if(n(h)==="<"&&s.has(h))h=s.get(h);else if(n(h)==="extends"){d=h;break}if(d!==-1){let h=d+1;while(h<r.length&&n(h)!=="{"&&n(h)!=="implements"){let p=s.get(h);if(p!==void 0)h=p+1;else h++}u(d+1,h)}}}var sr=me(()=>{ut();Bo()});function Vo(e){return typeof e==="string"?ti(e,"'"):String(e)}function ih(e,t,i=new Map){let r=se(e),n=new Map(i),o=new Map,s=[],c=1,l=0,f=0;for(let d=1;d<r.length;d++){let h=r[d],p=e.slice(h.start,h.end);if(h.kind==="punctuation"&&l===0&&(p===","||p==="}")){let m=r.slice(c,d),a=m[0];if(a){let C=a.kind==="quoted"?mt(e.slice(a.start,a.end)):e.slice(a.start,a.end),b=m.findIndex((T)=>T.kind==="punctuation"&&e[T.start]==="="),v=f;if(b>=0){let T=m.slice(b+1),B="",x=m[b].end;for(let D=0;D+2<T.length;D++){let[U,j,k]=T.slice(D,D+3);if(U.kind!=="word"||k.kind!=="word"||e.slice(j.start,j.end)!==".")continue;let z=n.get(`${e.slice(U.start,U.end)}.${e.slice(k.start,k.end)}`);if(z===void 0||typeof z==="object")continue;B+=e.slice(x,U.start)+Vo(z),x=k.end,D+=2}B+=e.slice(x,m.at(-1).end),v=Ot(B,n),s.push({start:m[b].start,end:m.at(-1).end,text:v===void 0?"":`= ${Vo(v)}`})}else if(v!==void 0)s.push({start:a.end,end:a.end,text:` = ${Vo(v)}`});if(f=typeof v==="number"?v+1:void 0,C!==void 0){if(n.delete(C),n.delete(`${t}.${C}`),v!==void 0)o.set(C,v),n.set(C,v),n.set(`${t}.${C}`,v)}}c=d+1}else if(h.kind==="punctuation"){if("([{".includes(p))l++;else if(")]}".includes(p))l--}}let u=e;for(let d of s.reverse())u=u.slice(0,d.start)+d.text+u.slice(d.end);return{body:u,members:o}}function gl(e,t){let i=[...new Set([...e,...t.values()])];if(!i.some((n)=>n.kind==="enum"))return;i.sort((n,o)=>(n.start??0)-(o.start??0));let r=new Map;for(let n of i)if(n.kind==="enum"){let o=n.text.indexOf("{");if(o<0)continue;if(se(n.text.slice(0,o)).some((c)=>n.text.slice(c.start,c.end)==="declare"))continue;let s=ih(n.text.slice(o),n.name,r);n.text=n.text.slice(0,o)+s.body;for(let[c,l]of s.members)r.set(`${n.name}.${c}`,l)}else if(n.kind==="variable"&&n.modifiers?.[0]==="const"&&!n.typeAnnotation&&!n.modifiers.includes("const assertion")&&typeof n.value==="string"){let o=Ot(n.value,r);if(o!==void 0)r.set(n.name,o)}}var yl=me(()=>{ut();Hr()});function wl(e,t){if(t.kind!=="punctuation")return 0;let i=e.slice(t.start,t.end);if("([{<".includes(i))return 1;if(")]}".includes(i)||i===">"&&e[t.start-1]!=="=")return-1;return 0}function Jr(e){if(!e.includes("?"))return e;let t=e.trim(),i=t.startsWith("(")&&t.endsWith(")"),r=e.indexOf(t)+(i?1:0),n=i?t.slice(1,-1):t,o=[[]],s=0;for(let h of se(n)){if(h.kind==="punctuation"&&n[h.start]===","&&s===0)o.push([]);else o[o.length-1].push(h);s+=wl(n,h)}let c=o.map((h)=>{let p=0,m=-1;for(let[v,T]of h.entries()){if(p===0&&T.kind==="punctuation"&&n[T.start]===":"){m=v;break}p+=wl(n,T)}let a=m>0&&n[h[m-1].start]==="?"?h[m-1]:void 0,C=h[0]?n.slice(h[0].start,h[0].end):"",b=h[0]&&n.startsWith("...",h[0].start);return{tokens:h,colon:m,question:a,required:h.length>0&&!a&&!b&&C!=="this"}}),l=-1;for(let[h,p]of c.entries())if(p.required)l=h;let f=[];for(let[h,p]of c.entries()){if(h>=l||!p.question||p.colon<0)continue;let m=p.tokens[p.colon+1],a=p.tokens.at(-1);if(!m||!a)continue;f.push({start:r+p.question.start,end:r+p.question.end,text:""},{start:r+m.start,end:r+m.start,text:"("},{start:r+a.end,end:r+a.end,text:") | undefined"})}if(!f.length)return e;let u=[],d=0;for(let h of f)u.push(e.slice(d,h.start),h.text),d=h.end;return u.push(e.slice(d)),u.join("")}var Uo=me(()=>{ut()});function Ft(e,t=!0){if(!t||!e||e.length===0)return"";if(e.length===1){let r=e[0];if(r.length>0&&r.charCodeAt(0)>32&&r.charCodeAt(r.length-1)>32)return`${r}
35
+ `;return`${r.trim()}
36
+ `}let i="";for(let r=0;r<e.length;r++){if(r>0)i+=`
37
+ `;i+=e[r].trim()}return`${i}
38
+ `}function Yr(e){return e.replaceAll("*/","*\\/")}var Xr=()=>{};function zo(e){return xl(e).replace(/\n[ \t]*(?=\n)/g,"")}function xl(e){if(e.indexOf("/*")===-1)return e.trim();let t=[],i=0,r=0,n=e.length;while(r<n)if(e.charCodeAt(r)===47&&r+1<n&&e.charCodeAt(r+1)===42){if(r>i)t.push(e.substring(i,r));r+=2;while(r<n-1){if(e.charCodeAt(r)===42&&e.charCodeAt(r+1)===47){r+=2;break}r++}i=r}else r++;if(i<n)t.push(e.substring(i));return t.join("").trim()}function Qo(){nn=!0,dt=null}function es(){nn=!1;let e=dt;return dt=null,e}function ts(e){let t=e.length;if(t===0)return!1;let i=0;if(e.charCodeAt(i)===45)i++;if(i>=t)return!1;let r=i;while(i<t&&e.charCodeAt(i)>=48&&e.charCodeAt(i)<=57)i++;if(i===r)return!1;if(i<t&&e.charCodeAt(i)===46){i++;let n=i;while(i<t&&e.charCodeAt(i)>=48&&e.charCodeAt(i)<=57)i++;if(i===n)return!1}return i===t}function rh(e){for(let t=0,i=e.length-1;t<i;t++){let r=e.charCodeAt(t);if(r<48||r>57)return!1}return!0}function Ko(e,t){let i=0,r=0;while((r=e.indexOf(t,r))!==-1)i++,r+=t.length;return i}function Cl(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 Zr(e){let t=e.trim();if(t.length<3||t.charCodeAt(0)!==60)return!1;if(t.startsWith("<>"))return t.endsWith("</>");let i=t.charCodeAt(1);if(!(i>=65&&i<=90||i>=97&&i<=122||i===36||i===95))return!1;let r=2;while(r<t.length&&Cl(t.charCodeAt(r)))r++;let n=t.slice(1,r),o=t.charCodeAt(r);if(o>32&&o!==62&&o!==47)return!1;if(t.endsWith("/>"))return!0;let s=t.lastIndexOf("</");if(s===-1)return!1;let c=s+2;while(c<t.length&&Cl(t.charCodeAt(c)))c++;return t.slice(s+2,c)===n&&t.charCodeAt(c)===62&&c===t.length-1}function Qr(e){let t=e.length,i=!1;for(let s=1;s<t;s++)if(e.charCodeAt(s)<=32&&e.charCodeAt(s-1)<=32){i=!0;break}if(!i)for(let s=0;s<t;s++){let c=e.charCodeAt(s);if(c===10||c===13||c===9){i=!0;break}}if(!i)return e;let r=[],n=-1,o=!1;for(let s=0;s<t;s++)if(e.charCodeAt(s)<=32){if(!o){if(n>=0)r.push(e.substring(n,s));r.push(" "),o=!0,n=-1}}else{if(o||n<0)n=s;o=!1}if(n>=0)r.push(e.substring(n));return r.join("")}function Ae(e,t=!1,i=!1,r=0,n){if(!e||typeof e!=="string")return"unknown";if(r>=rn)return"unknown";let o=e.trim();if(Zr(o))return"JSX.Element";if(o.startsWith("BigInt("))return"bigint";if(o.startsWith("Symbol.for("))return"symbol";if(o.includes(".raw`")||o.includes("String.raw`"))return"string";if(o.startsWith("`")&&o.endsWith("`")){if(!t||o.includes("${")||o.includes(`
39
+ `)||o.includes("\r"))return"string";return o}if(o.charCodeAt(0)===39||o.charCodeAt(0)===34){let c=nh(o);if(c!==null){if(c==="string"||!t)return"string";return c}}if(ts(o)){if(!t)return"number";return o}if(o==="true"||o==="false"){if(!t)return"boolean";return o}if(o==="null")return"null";if(o==="undefined")return"undefined";if(o.startsWith("[")&&o.endsWith("]"))return qo(o,t,r+1,n);if(o.startsWith("{")&&o.endsWith("}"))return Rl(o,t,r+1,n);if(o.startsWith("class ")||o.startsWith("class{"))return yh(o);if(o.startsWith("new "))return gh(o);if(o.endsWith("as const")){let c=o.slice(0,-8).trim();if(c.startsWith("[")&&c.endsWith("]")){let l=c.slice(1,-1).trim();if(!l)return"readonly []";let f=tn(l),u=[];for(let d=0;d<f.length;d++){let h=f[d].trim();if(h.startsWith("...")){let p=h.slice(3).trim();if(mi(p))u.push(`...typeof ${p}`);else{let m=Ae(p,!0,!1,r+1,n);u.push(m.startsWith("readonly [")||m.endsWith("[]")?`...${m}`:"...unknown[]")}}else u.push(Ae(h,!0,!1,r+1,n))}return`readonly [${u.join(", ")}]`}return Ae(c,!0,i,r+1,n)}if(Ti(o)!==-1||o.startsWith("function")||o.startsWith("async"))return Ml(o,i,r,t);if(o.startsWith("`")&&o.endsWith("`"))return mh(o,t);if(o.startsWith("Promise."))return Ol(o,t,r,n);if(o.startsWith("await "))return"unknown";if(o.charCodeAt(o.length-1)===110&&o.length>1&&rh(o)){if(t)return o;return"bigint"}if(o.startsWith("Symbol(")||o==="Symbol.for")return"symbol";let s=cr(o);if(s!==null)return s;if(Al(o))return"boolean";if(lh(o))return"number";return"unknown"}function vl(e){let t=e.charCodeAt(0);if(t!==39&&t!==34)return!1;return ii(e,0,t)===e.length}function nh(e){if(vl(e))return e;let t=oh(e);if(t.length<2)return null;let i=!1,r=!0,n="";for(let o of t){let s=o.trim();if(vl(s))i=!0,n+=sh(s);else r=!1}if(r)return ah(n);if(i)return"string";return null}function oh(e){let t=[],i=0,r=0,n=0;while(n<e.length){let o=e.charCodeAt(n);if(o===39||o===34||o===96){n=ii(e,n,o);continue}if(o===40||o===91||o===123)i++;else if(o===41||o===93||o===125)i--;else if(o===43&&i===0)t.push(e.slice(r,n)),r=n+1;n++}return t.push(e.slice(r)),t}function sh(e){return e.slice(1,-1).replace(/\\(.)/g,(t,i)=>{if(i==="n")return`
40
+ `;if(i==="t")return"\t";if(i==="r")return"\r";if(i==="0")return"\x00";return i})}function ah(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function lh(e){if(e==="")return!1;let t=!1,i=!1;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>=48&&n<=57){t=!0;continue}if(n===43||n===45||n===42||n===47||n===37){i=!0;continue}if(n===46||n===40||n===41||n<=32)continue;return!1}return t&&i}function Al(e){let t=0;for(let i=0;i<e.length;i++){let r=e.charCodeAt(i);if(r===34||r===39||r===96){i=ii(e,i,r)-1;continue}if(r===40||r===91||r===123){t++;continue}if(r===41||r===93||r===125){t--;continue}if(t!==0)continue;if(e.startsWith("===",i)||e.startsWith("!==",i)||e.startsWith("==",i)||e.startsWith("!=",i)||e.startsWith(">=",i)||e.startsWith("<=",i))return!0;if((r===62||r===60)&&e.charCodeAt(i-1)!==61&&e.charCodeAt(i+1)!==61)return!0}return!1}function ch(e,t=!1,i=0,r){return Ae(e,t,!0,i,r)}function _t(e,t=!1,i="",r,n){let o=Ho(i,r),s=[],c=!1,l=0;while(l<e.length){let u=e.charCodeAt(l);if(u===34||u===39||u===96){l=ii(e,l,u);continue}if(u===47&&e.charCodeAt(l+1)===47){l+=2;while(l<e.length&&e.charCodeAt(l)!==10&&e.charCodeAt(l)!==13)l++;continue}if(u===47&&e.charCodeAt(l+1)===42){let d=e.indexOf("*/",l+2);l=d===-1?e.length:d+2;continue}if(e.startsWith("function",l)&&ar(e,l,8)||e.startsWith("class",l)&&ar(e,l,5)){let d=ph(e,l);if(d!==-1){l=en(e,d);continue}}if(u===61&&e.charCodeAt(l+1)===62){let d=kl(e,l+2);if(e.charCodeAt(d)===123){l=en(e,d);continue}}if(e.startsWith("return",l)&&(l===0||!Rt(e.charCodeAt(l-1)))&&!Rt(e.charCodeAt(l+6))){l+=6;let d=!1;while(l<e.length&&e.charCodeAt(l)<=32){let v=e.charCodeAt(l);if(v===10||v===13)d=!0;l++}if(d||l>=e.length||e.charCodeAt(l)===59||e.charCodeAt(l)===125){c=!0;continue}let h=l,p=0,m=0,a=0;while(l<e.length){let v=e.charCodeAt(l);if(v===34||v===39||v===96){l=ii(e,l,v);continue}if(v===47&&e.charCodeAt(l+1)===47){if(p===0&&m===0&&a===0)break;while(l<e.length&&e.charCodeAt(l)!==10&&e.charCodeAt(l)!==13)l++;continue}if(v===47&&e.charCodeAt(l+1)===42){let T=e.indexOf("*/",l+2);l=T===-1?e.length:T+2;continue}if(v===40)p++;else if(v===41)p--;else if(v===91)m++;else if(v===93)m--;else if(v===123)a++;else if(v===125){if(a===0&&p===0&&m===0)break;a--}else if(v===59&&p===0&&m===0&&a===0)break;else if((v===10||v===13)&&p===0&&m===0&&a===0){let T=l+1;while(T<e.length&&e.charCodeAt(T)<=32)T++;if(e.startsWith("return",T)&&!Rt(e.charCodeAt(T+6)))break}l++}let C=e.slice(h,l).trim(),b=zo(Gt(C,o,r,n,h));if(!s.includes(b))s.push(b);continue}l++}if(c&&!s.includes("undefined"))s.push("undefined");let f=s.includes("unknown")?"unknown":s.length===0?"void":Tl(s);return t&&!f.startsWith("Promise<")?`Promise<${f}>`:f}function Ho(e,t){let i=new Map,r=e.startsWith("(")&&e.endsWith(")")?e.slice(1,-1):e,n=se(r),o=0,s=0,c=[];for(let l of n){let f=r.slice(l.start,l.end);if(f===","&&s===0)c.push(r.slice(o,l.start)),o=l.end;if(["(","[","{","<"].includes(f))s++;else if([")","]","}"].includes(f)||f===">"&&r[l.start-1]!=="=")s--}c.push(r.slice(o));for(let l of c){let f=se(l),u=-1,d=-1,h=0;for(let a of f){let C=l.slice(a.start,a.end);if(h===0&&C===":"&&u===-1)u=a.start;if(h===0&&C==="="&&l[a.end]!==">"){d=a.start;break}if(["(","[","{","<"].includes(C))h++;else if([")","]","}"].includes(C)||C===">"&&l[a.start-1]!=="=")h--}let p=l.slice(0,u!==-1?u:d!==-1?d:void 0).trim().replace(/^\.\.\./,"").replace(/\?$/,"");if(!lr(p))continue;let m=u!==-1?l.slice(u+1,d!==-1?d:void 0).trim():"";if(!m&&d!==-1){let a=l.slice(d+1).trim();m=t?.(a)??Ae(a,!1)}if(m){if(d===-1&&l.slice(0,u).trim().endsWith("?"))m=`(${m}) | undefined`;i.set(p,m)}}return i}function fh(e,t){if(e=e.trim(),!e.startsWith("{")||!e.endsWith("}"))return;let i=e.slice(1,-1),r=se(i),n=0,o=0;for(let s=0;s<=r.length;s++){let c=r[s],l=c?i.slice(c.start,c.end):";";if(o===0&&(l===";"||l===",")){let f=i.slice(n,c?.start).trim(),u=f.indexOf(":");if(u!==-1&&f.slice(0,u).trim()===t)return f.slice(u+1).trim();n=c?.end??i.length}if(["(","[","{","<"].includes(l))o++;else if([")","]","}"].includes(l)||l===">"&&c&&i[c.start-1]!=="=")o--}return}function Gt(e,t,i,r,n=0,o=0){if(o>=rn)return"unknown";let s=e.trim();while(is(s))s=s.slice(1,-1).trim();let c=i?.(s);if(c)return c;if(Zr(s))return"JSX.Element";if(s.startsWith("await ")){let C=Gt(s.slice(6),t,i,r,n,o+1);return C.startsWith("Promise<")&&C.endsWith(">")?C.slice(8,-1):C}if(t.has(s))return t.get(s);let l=/^([\w$]+)\.([\w$]+)$/.exec(s);if(l){let C=t.get(l[1]),b=C&&fh(C,l[2]);if(b)return b}if(s.startsWith("!"))return"boolean";if(s.startsWith("fetch("))return"Promise<Response>";if(dh(s))return Ae(s,!1);let f=hh(s);if(f){let C=Gt(f.whenTrue,t,i,r,n,o+1),b=Gt(f.whenFalse,t,i,r,n,o+1);return C===b?C:Tl([C,b])}let u=uh(s);if(u&&r)return r(u,n);if(Al(s))return"boolean";let d=0;for(let C=s.length-1;C>=0;C--){let b=s.charCodeAt(C);if(b===41||b===93||b===125)d++;else if(b===40||b===91||b===123)d--;else if(d===0&&(b===43||b===45||b===42||b===47||b===37)){let v=Gt(s.slice(0,C),t,i,r,n,o+1),T=Gt(s.slice(C+1),t,i,r,n,o+1);if(b===43&&(v==="string"||T==="string"))return"string";if(v==="number"&&T==="number")return"number";break}}let h=s.startsWith("{")&&s.endsWith("}")?Rl(s,!1,o+1,void 0,(C)=>Gt(C,t,i,r,n,o+1)):Ae(s,!1),p=se(h),m="",a=0;for(let C=0;C<p.length;C++){let b=p[C];if(b.kind!=="word"||h.slice(b.start,b.end)!=="typeof")continue;let v=p[C+1];if(!v||v.kind!=="word")continue;let T=t.get(h.slice(v.start,v.end)),B=!T,x=b.start,D=v.end,U=C;C++;while(p[C+1]&&h.slice(p[C+1].start,p[C+1].end)==="."&&p[C+2]?.kind==="word"){let j=p[C+2];if(!B)T=`(${T})["${h.slice(j.start,j.end)}"]`;D=j.end,C+=2}if(B&&U>=2&&h.slice(p[U-2].start,p[U-2].end)==="ReturnType"&&h.slice(p[U-1].start,p[U-1].end)==="<"&&p[C+1]&&h.slice(p[C+1].start,p[C+1].end)===">")x=p[U-2].start,D=p[++C].end;m+=h.slice(a,x)+(T??"unknown"),a=D}return m+h.slice(a)}function uh(e){let t=se(e),i=0,r=-1;for(let o=0;o<t.length;o++){let s=t[o],c=e.slice(s.start,s.end);if(s.kind!=="punctuation"&&s.kind!=="word")continue;if(["(","[","{"].includes(c))i++;else if([")","]","}"].includes(c))i--;else if(!i&&c==="as"&&o>0&&e.slice(t[o-1].start,t[o-1].end)!==".")r=o}if(r===-1||r+1===t.length)return;let n=e.slice(t[r].end).trim();if(n==="const")return;i=0;for(let o of t.slice(r+1)){if(o.kind!=="punctuation")continue;let s=e.slice(o.start,o.end);if(["(","[","{","<"].includes(s))i++;else if([")","]","}",">"].includes(s))i--;else if(!i&&["+","-","*","/","%","=","!",";"].includes(s))return}return n}function Tl(e){return e.map((t)=>e.length>1&&Ti(t)!==-1?`(${t})`:t).join(" | ")}function dh(e){if(e.startsWith("function")&&ar(e,0,8))return!0;let t=Ti(e);if(t===-1)return!1;let i=e.slice(0,t).trim();if(i.startsWith("async")&&ar(i,0,5))i=i.slice(5).trim();if(i.startsWith("<")){let n=ot(i,0,"<",">");if(n===-1)return!1;i=i.slice(n+1).trim()}if(i.startsWith("(")){let n=ot(i,0,"(",")");if(n===-1)return!1;let o=i.slice(n+1).trim();if(o&&!o.startsWith(":"))return!1}let r=Zo(i);return is(r.params)||lr(r.params)}function is(e){if(!e.startsWith("(")||!e.endsWith(")"))return!1;let t=0;for(let i=0;i<e.length;i++){let r=e.charCodeAt(i);if(r===40)t++;else if(r===41&&--t===0)return i===e.length-1}return!1}function hh(e){let t=0,i=-1;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n===40||n===91||n===123)t++;else if(n===41||n===93||n===125)t--;else if(n===63&&t===0&&e.charCodeAt(r+1)!==63)i=r;else if(n===58&&t===0&&i!==-1)return{whenTrue:e.slice(i+1,r),whenFalse:e.slice(r+1)}}return null}function ar(e,t,i){return(t===0||!Rt(e.charCodeAt(t-1)))&&!Rt(e.charCodeAt(t+i))}function kl(e,t){let i=t;while(i<e.length){if(e.charCodeAt(i)<=32){i++;continue}if(e.startsWith("//",i)){while(i<e.length&&e.charCodeAt(i)!==10&&e.charCodeAt(i)!==13)i++;continue}if(e.startsWith("/*",i)){let r=e.indexOf("*/",i+2);i=r<0?e.length:r+2;continue}break}return i}function ph(e,t){let i=0,r=0,n=0,o=!1,s=!1;for(let c=t;c<e.length;c++){if(c=kl(e,c),c>=e.length)break;let l=e.charCodeAt(c);if(l===34||l===39||l===96){c=ii(e,c,l)-1,s=!1;continue}if(Rt(l)||l>=128){let f=c;while(c+1<e.length&&(Rt(e.charCodeAt(c+1))||e.charCodeAt(c+1)>=128))c++;s=o&&["keyof","typeof","readonly","unique","new","abstract","infer","extends"].includes(e.slice(f,c+1));continue}if(l===61&&e.charCodeAt(c+1)===62){c++,s=o;continue}if(l===40)i++;else if(l===41)i--,s=!1;else if(l===91)r++;else if(l===93)r--,s=!1;else if(l===60&&i===0&&r===0)n++;else if(l===62&&n>0&&i===0&&r===0)n--,s=!1;else if(l===123)if(i||r||n||o&&s)c=en(e,c)-1,s=!1;else return c;else if(i===0&&r===0&&n===0){if(l===58)o=!0,s=!0;else if(o&&[124,38,63].includes(l))s=!0;else if(l===59)return-1}}return-1}function en(e,t){let i=1,r=t+1;while(r<e.length&&i>0){let n=e.charCodeAt(r);if(n===34||n===39||n===96){r=ii(e,r,n);continue}if(n===47&&e.charCodeAt(r+1)===47){r+=2;while(r<e.length&&e.charCodeAt(r)!==10&&e.charCodeAt(r)!==13)r++;continue}if(n===47&&e.charCodeAt(r+1)===42){let o=e.indexOf("*/",r+2);r=o===-1?e.length:o+2;continue}if(n===123)i++;else if(n===125)i--;r++}return r}function ii(e,t,i){let r=t+1;while(r<e.length){let n=e.charCodeAt(r);if(n===92){r+=2;continue}if(i===96&&n===36&&e.charCodeAt(r+1)===123){r=en(e,r+1);continue}if(r++,n===i)break}return r}function mh(e,t){if(e.includes(".raw`")||e.includes("String.raw`"))return"string";if(!t||e.includes("${")||e.includes(`
41
+ `)||e.includes("\r"))return"string";return e}function gh(e){let t=4;while(t<e.length&&e.charCodeAt(t)<=32)t++;let i=t,r=e.charCodeAt(t);if(r<65||r>90)return"unknown";while(t<e.length&&(Rt(e.charCodeAt(t))||e.charCodeAt(t)===46))t++;if(t===i)return"unknown";let n=e.slice(i,t);{let o=e.slice(t),s=o;if(o.startsWith("<")){let l=0,f=-1;for(let u=0;u<o.length;u++)if(o[u]==="<")l++;else if(o[u]===">"){if(l--,l===0){f=u;break}}if(f!==-1){let u=o.slice(0,f+1);s=o.slice(f+1);let d=s.indexOf("(");if(d!==-1){let h=0,p=-1;for(let m=d;m<s.length;m++)if(s[m]==="(")h++;else if(s[m]===")"){if(h--,h===0){p=m;break}}if(p!==-1){if(s.slice(p+1).trimStart().startsWith("."))return"unknown"}}return`${n}${u}`}}let c=s.indexOf("(");if(c!==-1){let l=0,f=-1;for(let u=c;u<s.length;u++)if(s[u]==="(")l++;else if(s[u]===")"){if(l--,l===0){f=u;break}}if(f!==-1){if(s.slice(f+1).trimStart().startsWith("."))return"unknown"}}switch(n){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 n}}return"unknown"}function yh(e){return"{ new (...args: any[]): any }"}function Ol(e,t,i=0,r){if(e.startsWith("Promise.resolve(")){let n=e.indexOf(")",16);if(n!==-1){let o=e.slice(16,n).trim();if(o)return`Promise<${Ae(o,t,!1,i+1,r)}>`}return"Promise<unknown>"}if(e.startsWith("Promise.reject("))return"Promise<never>";if(e.startsWith("Promise.all(")){let n=e.indexOf("[",12),o=e.lastIndexOf("]");if(n!==-1&&o>n){let s=e.slice(n+1,o).trim(),c=tn(s),l=[];for(let f=0;f<c.length;f++){let u=c[f].trim();if(u.startsWith("Promise.resolve(")){let d=Ol(u,t,i+1,r),h=d.indexOf("<"),p=d.lastIndexOf(">");l.push(h!==-1&&p>h?d.slice(h+1,p):"unknown")}else l.push(Ae(u,t,!1,i+1,r))}return`Promise<[${l.join(", ")}]>`}return"Promise<unknown[]>"}return"Promise<unknown>"}function qo(e,t,i=0,r){let n=e.slice(1,-1).trim();if(!n)return"never[]";if(i>=rn)return"unknown[]";let o=tn(n),s=!1;for(let p=0;p<o.length;p++){let m=o[p],a=m.length;while(a>0&&m.charCodeAt(a-1)<=32)a--;if(a>=8&&m.slice(a-8,a)==="as const"){s=!0;break}}if(s){let p=[];for(let m=0;m<o.length;m++){let a=o[m].trim();if(a.endsWith("as const")){let C=a.slice(0,-8).trim();if(C.startsWith("[")&&C.endsWith("]")){let b=C.slice(1,-1).trim(),v=tn(b),T=[];for(let B=0;B<v.length;B++)T.push(Ae(v[B].trim(),!0,!1,i+1,r));p.push(`readonly [${T.join(", ")}]`)}else p.push(Ae(C,!0,!1,i+1,r))}else if(a.startsWith("[")&&a.endsWith("]"))p.push(qo(a,!0,i+1,r));else p.push(Ae(a,!0,!1,i+1,r))}return`readonly [
42
+ ${p.join(` |
43
+ `)}
44
+ ]`}let c=nn&&!t,l=[],f=[];for(let p of o){let m=p.trim(),a=dt;if(dt=null,m.startsWith("...")){let C=m.slice(3).trim(),b=Ae(C,!1,!1,i+1,r);if(b.endsWith("[]"))l.push(b.slice(0,-2));else if(b.startsWith("readonly [")&&b.endsWith("]"))l.push(b.slice(10,-1));else if(mi(C))l.push(`(typeof ${C})[number]`);else l.push("unknown")}else if(m.startsWith("[")&&m.endsWith("]"))l.push(qo(m,t,i+1,r));else l.push(ch(m,t,i+1,r));if(c)f.push(dt);dt=a}if(c)if(Yo(e))dt=Qr(e);else{let p=[];for(let m=0;m<o.length;m++){let a=o[m].trim();if(a.endsWith("as const"))continue;if(Jo(a)||a==="null"||a==="undefined")p.push(a);else if(a.startsWith("[")&&Yo(a))p.push(Qr(a));else if(a.startsWith("{")){if(f[m])p.push(f[m])}else{let C=Ae(a,!1,!1,0,r);if(C!=="unknown")p.push(C)}}if(p.length>0)dt=`[${p.join(", ")}]`}if(t)return`readonly [${l.join(", ")}]`;let u=new Set,d=[],h=!0;for(let p of l){if(!u.has(p))u.add(p),d.push(p);if(h){if(!(ts(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))h=!1}}if(h&&l.length<=10)return`readonly [${l.join(", ")}]`;if(d.length===1)return`${d[0]}[]`;return`(${d.join(" | ")})[]`}function tn(e){let t=[],i=0,r=0,n=!1,o=0;for(let c=0;c<e.length;c++){let l=e.charCodeAt(c);if(!n&&(l===34||l===39||l===96))n=!0,o=l;else if(n&&l===o&&(c===0||e.charCodeAt(c-1)!==92))n=!1;if(!n){if(l===91||l===123||l===40)r++;else if(l===93||l===125||l===41)r--;else if(l===44&&r===0){let f=e.substring(i,c).trim();if(f)t.push(f);i=c+1;continue}}}let s=e.substring(i).trim();if(s)t.push(s);return t}function Jo(e){if(ts(e))return!0;if(e==="true"||e==="false")return!0;if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return!0;return!1}function wh(e){return e==="number"||e==="string"||e==="boolean"}function Yo(e){let t=!1,i=0,r=e.length;for(let n=0;n<r;n++){let o=e.charCodeAt(n);if(t){if(o===92){n++;continue}if(o===i)t=!1;continue}if(o===34||o===39||o===96){t=!0,i=o;continue}if(o===61&&n+1<r&&e.charCodeAt(n+1)===62)return!1;if(o>=97&&o<=122){let s=n;while(n<r&&(e.charCodeAt(n)>=97&&e.charCodeAt(n)<=122||e.charCodeAt(n)>=65&&e.charCodeAt(n)<=90||e.charCodeAt(n)>=48&&e.charCodeAt(n)<=57||e.charCodeAt(n)===95||e.charCodeAt(n)===36))n++;let c=e.slice(s,n);if(c==="new"||c==="async"||c==="await"||c==="function"||c==="yield"||c==="console"||c==="process")return!1;let l=n;while(l<r&&e.charCodeAt(l)<=32)l++;if(l<r&&e.charCodeAt(l)===40)return!1;n--}}return!0}function Rl(e,t,i=0,r,n){let o=e.slice(1,-1).trim();if(!o)return"{}";if(i>=rn)return"Record<string, unknown>";let s=$h(o),c=new Set(s.flatMap(([C])=>{let b=El(Xo(C).key);return b?.kind==="get"?[b.name]:[]})),l=[],f=[],u=[],d=!1,h=nn&&!t,p=[];for(let[C,b]of s){let{comments:v,key:T}=Xo(C),B=v?`${v}
45
+ `:"",x=El(T);if(x&&pl(x.name))continue;let D=T,U=!1;if(T==="..."){let we=b.trim(),be=mi(we)?`typeof ${we}`:Ae(we,t,!1,i+1,r);if(be!=="unknown")f.push(be);if(h&&(mi(we)||we.startsWith("{")))p.push(`...${Qr(we)}`);continue}let j=dt;dt=null;let k,z=b.trim();if(z===T&&lr(z))k=(t?void 0:r?.mutableBindingTypes?.get(z))??`typeof ${z}`;else if(xh(z)){U=!0;let we=Ah(T);if(we){D=we.name;let be="";if(z.startsWith("async "))be="async ";if(z.charCodeAt(be.length)===42)be+="*";k=Sl(we.name,be+we.typeParams+z.slice(be.length))}else k=Sl(T,z)}else{if(k=n?.(b)??Ae(b,t,!1,i+1,r),k==="unknown"&&mi(z))k=(t?void 0:r?.mutableBindingTypes?.get(z))??`typeof ${z}`;if(k.includes("=>")||k.includes("function")||k.includes("async"))k=bl(k)}let Q=dt;dt=j;let ce=D,ge=b.trim(),ve=dl(D,r);if(!hl(x?.name??D,r)&&!(x?.kind==="set"&&c.has(x.name)))u.push(x?Sh(x.kind,k):k);if(ve&&"index"in ve)d=!0;else{if(ve&&"name"in ve)D=ve.name;if(x){let we=Eh(x.kind,x.name,k);if(we){l.push(`${B}${we}`);continue}}if(!t&&wh(k)&&Jo(ge))l.push(`${B}/** @defaultValue ${Yr(ge)} */
46
+ ${D}: ${k}`);else l.push(`${B}${t?"readonly ":""}${D}: ${k}`)}if(h){let we=xl(ce);if(ge.endsWith("as const"));else if(Jo(ge))p.push(`${we}: ${ge}`);else if(ge.startsWith("[")&&Yo(ge))p.push(`${we}: ${Qr(ge)}`);else if(ge.startsWith("{")){if(Q)p.push(`${we}: ${Q}`)}else if(U)p.push(`${we}: ${zo(bl(k))}`);else if(!ge.startsWith("[")&&(ge.includes("=>")||ge.startsWith("function")||ge.startsWith("async"))){let be=Ml(ge,!1,0,!0);p.push(`${we}: ${zo(be)}`)}}}if(h&&p.length>0){let C=i>0?(i-1)/2:0,b=`{ ${p.join(", ")} }`;if(b.length<=80)dt=b;else{let v=" ".repeat((C+1)*2),T=" ".repeat(C*2);dt=`{
47
+ ${v}${p.join(`,
48
+ ${v}`)}
49
+ ${T}}`}}if(d&&f.length===0){let C=[...new Set(u)].map((b)=>b.includes("=>")||b.includes(" & ")?`(${b})`:b);l.unshift(`${t?"readonly ":""}[x: string]: ${C.join(" | ")}`)}let m=l.length>0?`{
50
+ ${l.join(`;
51
+ `)}
52
+ }`:"{}";if(f.length===0)return m;let a=f[0];for(let C=1;C<f.length;C++)a=`Omit<${a}, keyof ${f[C]}> & ${f[C]}`;return l.length>0?`Omit<${a}, keyof ${m}> & ${m}`:a}function lr(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 i=1;i<e.length;i++)if(!Rt(e.charCodeAt(i)))return!1;return!0}function mi(e){let t=e.split(".");return t.length>0&&t.every(lr)}function Ch(e){let t=!1,i="";for(let r=0;r<e.length;r++){let n=e[r];if(t){if(n==="\\")r++;else if(n===i)t=!1;continue}if(n==='"'||n==="'"||n==="`"){t=!0,i=n;continue}if(n==="(")return r;if(n==="<"){let o=ot(e,r,"<",">");if(o!==-1)r=o}}return-1}function cr(e){if(e.length<3||!e.endsWith(")"))return null;let t=Ch(e);if(t===-1||ot(e,t,"(",")")!==e.length-1)return null;let i=e.slice(0,t).trim(),r=!1;if(i.endsWith("?."))r=!0,i=i.slice(0,-2).trim();let n=i,o=!1,s=i.indexOf("<");if(s!==-1){if(ot(i,s,"<",">")!==i.length-1)return null;n=i.slice(0,s).trim(),o=!0}if(!mi(n))return null;let c=e.slice(t+1,-1).trim(),l=Ti(c)!==-1||c.startsWith("function")||c.startsWith("async function"),f=mi(c),u=!l&&c.endsWith(")")&&cr(c)!==null,d=n.indexOf(".");if(d!==-1){if(n.indexOf(".",d+1)!==-1)return null}else if(!o&&!r&&!l&&!f&&!u)return null;let h=`ReturnType<typeof ${i}>`;return r?`${h} | undefined`:h}function bl(e){let t=e.split(`
53
+ `).map((f)=>Pl(f)).join(`
54
+ `),i=t.indexOf("async");if(i!==-1){let f=i>0?t.charCodeAt(i-1):32,u=i+5<t.length?t.charCodeAt(i+5):32;if(!Rt(f)&&!Rt(u))t=(t.slice(0,i)+t.slice(i+5)).trim()}let r=t.indexOf("(");if(r!==-1){let f=ot(t,r,"(",")");if(f!==-1){let u=t.slice(r,f+1),d=pi(u);t=t.slice(0,r)+d+t.slice(f+1)}}let n=t.length,o="",s=[],c=!1,l=!1;for(let f=0;f<n;f++){let u=t.charCodeAt(f);if(u===123||u===40)s.push(u);else if(u===125||u===41)s.pop();if(u<=32){if(c=!0,u===10||u===13)l=!0;continue}if(c&&o.length>0){let d=(s.length>0?s[s.length-1]:0)===123;if(l&&d){let h=o.charCodeAt(o.length-1),p=h===59||h===44||h===123||u===125,m=o.length>=2&&o.charCodeAt(o.length-1)===47&&o.charCodeAt(o.length-2)===42;if(!p&&!m)o+="; ";else o+=" "}else o+=" "}c=!1,l=!1,o+=t[f]}return o.trim()}function Rt(e){return e>=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57||e===95||e===36}function pi(e){let t=e.trim(),i,r=!1;if(t.startsWith("(")&&t.endsWith(")"))i=t.slice(1,-1),r=!0;else i=t;let n=i.trim();if(!n)return r?"()":"";let o=!1;{let m=0;for(let a=0;a<n.length;a++){let C=n.charCodeAt(a);if(C===40||C===60||C===91||C===123)m++;else if(C===41||C===93||C===125||C===62&&n.charCodeAt(a-1)!==61)m--;else if(m===0&&C===61){let b=a>0?n.charCodeAt(a-1):0,v=a+1<n.length?n.charCodeAt(a+1):0;if(b!==61&&b!==33&&b!==60&&b!==62&&v!==61&&v!==62){o=!0;break}}}}if(!o)return t;let s=[],c=[],l=0,f=0,u=!1,d=0;for(let m=0;m<=n.length;m++){if(m===n.length){s.push(n.slice(l));break}let a=n.charCodeAt(m);if(u){if(a===92){m++;continue}if(a===d)u=!1;continue}if(a===47&&m+1<n.length){let C=n.charCodeAt(m+1);if(C===42){m+=2;while(m+1<n.length&&!(n.charCodeAt(m)===42&&n.charCodeAt(m+1)===47))m++;m++;continue}if(C===47){while(m<n.length&&n.charCodeAt(m)!==10)m++;continue}}if(a===39||a===34||a===96){u=!0,d=a;continue}if(a===40||a===60||a===91||a===123)f++;else if(a===41||a===93||a===125||a===62&&n.charCodeAt(m-1)!==61)f--;else if(a===44&&f===0){s.push(n.slice(l,m));let C=",",b=m+1;while(b<n.length&&n.charCodeAt(b)<=32)C+=n[b],b++;c.push(C),l=b}}let h=[];for(let m of s){let a=m.trim();if(!a){h.push(m);continue}if(a.startsWith("//"))continue;let C=Pl(a),b=m.slice(0,m.length-m.trimStart().length);h.push(b+vh(C))}let p=h[0]||"";for(let m=1;m<h.length;m++)p+=(c[m-1]||", ")+h[m];return Jr(r?`(${p})`:p)}function Pl(e){let t=!1,i=0;for(let r=0;r<e.length-1;r++){let n=e.charCodeAt(r);if(t){if(n===92){r++;continue}if(n===i)t=!1;continue}if(n===39||n===34||n===96){t=!0,i=n;continue}if(n===47&&e.charCodeAt(r+1)===47)return e.slice(0,r).trimEnd()}return e}function vh(e){if(e.startsWith("..."))return e;let t=-1,i=-1,r=0,n=!1,o=0;for(let c=0;c<e.length;c++){let l=e.charCodeAt(c);if(n){if(l===92){c++;continue}if(l===o)n=!1;continue}if(l===47&&c+1<e.length){let f=e.charCodeAt(c+1);if(f===42){c+=2;while(c+1<e.length&&!(e.charCodeAt(c)===42&&e.charCodeAt(c+1)===47))c++;c++;continue}if(f===47){while(c<e.length&&e.charCodeAt(c)!==10)c++;continue}}if(l===39||l===34||l===96){n=!0,o=l;continue}if(l===40||l===60||l===91||l===123)r++;else if(l===41||l===93||l===125||l===62&&e.charCodeAt(c-1)!==61)r--;else if(r===0){if(l===58&&t===-1)t=c;else if(l===61&&i===-1&&(c===0||e.charCodeAt(c-1)!==61)&&(c+1>=e.length||e.charCodeAt(c+1)!==61&&e.charCodeAt(c+1)!==62))i=c}}let s=i!==-1;if(t!==-1&&(i===-1||t<i)){let c=e.slice(0,t).trim(),l=i!==-1?e.slice(t+1,i).trim():e.slice(t+1).trim(),f=s&&!c.endsWith("?")?"?":"";return`${c}${f}: ${l}`}else if(i!==-1){let c=e.slice(0,i).trim(),l=!c.endsWith("?")?"?":"",f=e.slice(i+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`${c}${l}: ${u}`}return e}function bh(e){let t=0,i=e.length;while(t<i){while(t<i&&(e.charCodeAt(t)===32||e.charCodeAt(t)===9||e.charCodeAt(t)===10||e.charCodeAt(t)===13))t++;if(t+1<i&&e.charCodeAt(t)===47&&e.charCodeAt(t+1)===42){t+=2;while(t+1<i&&!(e.charCodeAt(t)===42&&e.charCodeAt(t+1)===47))t++;t+=2;continue}break}return t}function Xo(e){let t=[],i=0,r=e.length;while(i<r){while(i<r&&e.charCodeAt(i)<=32)i++;if(i+1>=r||e.charCodeAt(i)!==47||e.charCodeAt(i+1)!==42)break;let n=i;i+=2;while(i+1<r&&!(e.charCodeAt(i)===42&&e.charCodeAt(i+1)===47))i++;i=Math.min(i+2,r),t.push(e.slice(n,i).trim())}return{comments:t.join(`
55
+ `),key:e.slice(i).trim()}}function $h(e){let t=[],i="",r="",n=0,o=!1,s="",c=!0,l=!1,f=0,u=!1,d=!1,h=0,p=!1,m=!1;for(let a=0;a<e.length;a++){let C=e.charCodeAt(a),b=a>0?e.charCodeAt(a-1):0,v=a<e.length-1?e.charCodeAt(a+1):0;if(!o&&!l&&C===47&&v===47){i=i.replace(/[ \t]+$/,""),a+=2;while(a<e.length&&e.charCodeAt(a)!==10)a++;a--;continue}if(!o&&!l&&C===47&&v===42){l=!0,f=1,i+="/*",a++;continue}else if(l&&C===42&&v===47){if(f--,i+="*/",a++,f===0)l=!1;continue}else if(l&&C===47&&v===42){f++,i+="/*",a++;continue}let T=e[a];if(!o&&!l&&(C===34||C===39||C===96))o=!0,s=T,i+=T;else if(o&&T===s&&b!==92)o=!1,i+=T;else if(!o&&!l)if(C===40&&n===0&&c&&h===0){r=i.trim();let B=bh(r),x=B>0?r.slice(0,B):"",D=r.slice(B),U="";if(D.startsWith("async ")||D.startsWith("async\t")||D.startsWith(`async
56
+ `))D=D.slice(6).trimStart(),U="async ";if(D.startsWith("*"))D=D.slice(1).trimStart(),U+="*";r=x+D,i=U+T,c=!1,p=!0,m=!1,n=1}else if(C===123||C===91||C===40){if(n++,i+=T,m&&C===123)m=!1}else if(C===125||C===93||C===41){if(n--,i+=T,C===41&&n===0&&!c&&!p)u=!0;if(p){if(C===41&&n===0&&!m)m=!0;else if(C===125&&n===0)p=!1,m=!1}}else if(C===58&&n===0&&c&&h===0)r=i.trim(),i="",c=!1;else if(C===58&&n===0&&u)d=!0,i+=T;else if(C===60&&d)h++,i+=T;else if(C===60&&c&&n===0)h++,i+=T;else if(C===62&&h>0&&b!==61)h--,i+=T;else if(C===61&&v===62&&d&&h===0)d=!1,u=!1,i+=T;else if(C===44&&n===0&&h===0&&!m){if(r&&i.trim()){let B=i.trim();t.push([r,B])}else if(c&&i.trim())$l(t,i.trim());i="",r="",c=!0,u=!1,d=!1,h=0}else i+=T;else i+=T}if(r&&i.trim()){let a=i.trim();t.push([r,a])}else if(c&&i.trim())$l(t,i.trim());return t}function $l(e,t){let{comments:i,key:r}=Xo(t);if(lr(r))e.push([i?`${i}
57
+ ${r}`:r,r]);else if(r.startsWith("...")&&r.length>3)e.push(["...",r.slice(3).trim()])}function El(e){let t=e.trim();if(t.startsWith("get ")&&t.length>4){let i=t.slice(4).trim();if(i)return{kind:"get",name:i}}if(t.startsWith("set ")&&t.length>4){let i=t.slice(4).trim();if(i)return{kind:"set",name:i}}return null}function Eh(e,t,i){let r=i.trim();if(r.charCodeAt(0)!==40)return null;let n=ot(r,0,"(",")");if(n===-1)return null;let o=r.slice(1,n).trim(),s=r.slice(n+1).trimStart();if(!s.startsWith("=>"))return null;let c=s.slice(2).trim();if(e==="get")return`get ${t}(): ${c||"unknown"}`;return`set ${t}(${o})`}function Sh(e,t){let i=t.trim(),r=ot(i,0,"(",")");if(!i.startsWith("(")||r===-1)return"unknown";if(e==="get"){let c=i.slice(r+1).trim();return c.startsWith("=>")?c.slice(2).trim():"unknown"}let n=i.slice(1,r).trim(),o=n.startsWith("{")?ot(n,0,"{","}"):n.startsWith("[")?ot(n,0,"[","]"):0,s=n.indexOf(":",Math.max(0,o));return s===-1?"unknown":n.slice(s+1).trim()}function xh(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 i=0;for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(n===40)i++;else if(n===41){if(i--,i===0){let o=t.slice(r+1).trimStart();if(o.startsWith("{"))return!0;if(o.startsWith(":")){let s=rs(o,1);if(s?.kind==="arrow")return!1;if(s?.kind==="body")return!0}return!1}}}return!1}function Ah(e){let t=e.trimEnd();if(!t.endsWith(">"))return null;let i=0,r=-1;for(let o=t.length-1;o>=0;o--){let s=t.charCodeAt(o);if(s===62){if(o>0&&t.charCodeAt(o-1)===61)continue;i++}else if(s===60){if(i--,i===0){r=o;break}}}if(r===-1)return null;let n=t.slice(0,r).trimEnd();if(!n)return null;return{name:n,typeParams:t.slice(r)}}function Sl(e,t){let i=t.trimStart(),r=!1,n=!1;if(i.startsWith("async ")||i.startsWith("async\t"))r=!0,i=i.slice(5).trimStart();if(i.startsWith("*"))n=!0,i=i.slice(1).trimStart();let o="";if(i.charCodeAt(0)===60){let h=0,p=-1;for(let m=0;m<i.length;m++)if(i.charCodeAt(m)===60)h++;else if(i.charCodeAt(m)===62&&!(m>0&&i.charCodeAt(m-1)===61)){if(h--,h===0){p=m;break}}if(p!==-1)o=i.slice(0,p+1),i=i.slice(p+1).trimStart()}let s=i.indexOf("("),c=ot(i,s,"(",")");if(s===-1||c===-1)return"() => unknown";let l=i.slice(s,c+1),f="unknown",u=i.slice(c+1).trimStart();if(u.charCodeAt(0)===58){let h=u.slice(1),p=rs(h,0);if(p)f=h.slice(0,p.index).trim();else f=h.trim()}if(f==="unknown"&&!n&&u.charCodeAt(0)===123){let h=ot(u,0,"{","}");if(h!==-1){let p=_t(u.slice(1,h),r,l);if(p!=="unknown"&&p!=="Promise<unknown>")f=r&&p.startsWith("Promise<")?p.slice(8,-1):p;else if(r)f="Promise<unknown>"}}if(f==="unknown"){if(r&&n)f="AsyncGenerator<unknown, void, unknown>";else if(n)f="Generator<unknown, void, unknown>";else if(r)f="Promise<void>"}else if(r&&!f.startsWith("Promise<")&&!f.startsWith("AsyncGenerator<"))f=`Promise<${f}>`;let d=pi(l);return`${o}${d} => ${f}`}function rs(e,t){let i=0,r=0,n=0,o=0,s=!1,c=0;for(let l=t;l<e.length;l++){let f=e.charCodeAt(l);if(s){if(f===92)l++;else if(f===c)s=!1;continue}if(f===34||f===39||f===96){s=!0,c=f;continue}if(f===40)i++;else if(f===41&&i>0)i--;else if(f===91)r++;else if(f===93&&r>0)r--;else if(f===60)n++;else if(f===62&&n>0&&e.charCodeAt(l-1)!==61)n--;else if(f===125&&o>0)o--;else if(f===123){let u=i>0||r>0||n>0||o>0,d=e.slice(t,l).trimEnd(),h=d.charCodeAt(d.length-1),p=d.length===0||h===38||h===124||h===40||h===44||h===58||h===61||h===91;if(u||p)o++;else return{index:l,kind:"body"}}else if(f===61&&l+1<e.length&&e.charCodeAt(l+1)===62&&i===0&&r===0&&n===0&&o===0)return{index:l,kind:"arrow"}}return null}function ot(e,t,i,r){let n=0;for(let o=t;o<e.length;o++)if(e[o]===i)n++;else if(e[o]===r){if(r===">"&&o>0&&e[o-1]==="=")continue;if(n--,n===0)return o}return-1}function Ti(e){let t=0,i=0,r=!1,n="";for(let o=0;o<e.length-1;o++){let s=e[o],c=e[o+1],l=o>0?e[o-1]:"";if(!r&&(s==='"'||s==="'"||s==="`"))r=!0,n=s;else if(r&&s===n&&l!=="\\")r=!1;if(!r){if(s==="<"){let f=ot(e,o,"<",">");if(f!==-1){o=f;continue}}if(s==="(")t++;else if(s===")")t--;else if(s==="[")i++;else if(s==="]")i--;if(s==="="&&c===">"&&t===0&&i===0)return o}}return-1}function Ml(e,t=!1,i=0,r=!0){let n=e.trim();if(n.length>200&&Ko(n,"=>")>2&&Ko(n,"<")>5&&!n.startsWith("function"))return t?"((...args: any[]) => any)":"(...args: any[]) => any";if(n.startsWith("async ")&&n.includes("=>")){let s=n.slice(5).trim(),c=Ti(s);if(c===-1)return t?"(() => Promise<unknown>)":"() => Promise<unknown>";let l=s.substring(0,c).trim(),f=s.substring(c+2).trim(),u=Zo(l),{params:d,returnType:h}=u;if(d=pi(d),d==="()"||d==="")d="()";else if(!d.startsWith("("))d=`(${d})`;let p=h;if(p);else if(f.startsWith("{"))p=_t(f.slice(1,f.endsWith("}")?-1:void 0),!0,u.params);else p=Gt(f,Ho(u.params));let m=`${d} => ${h||p.startsWith("Promise<")?p:`Promise<${p}>`}`;return t?`(${m})`:m}if(n.includes("=>")){let s="",c=n;if(n.startsWith("<")){let C=ot(n,0,"<",">");if(C!==-1)s=n.substring(0,C+1),c=n.substring(C+1).trim()}let l=Ti(c);if(l===-1)return t?"(() => unknown)":"() => unknown";let f=c.substring(0,l).trim(),u=c.substring(l+2).trim(),d=Zo(f),{params:h,returnType:p}=d;if(h=pi(h),h==="()"||h==="")h="()";else if(!h.startsWith("("))h=`(${h})`;let m="unknown";if(p)m=p;else if(u.startsWith("{"))m=_t(u.slice(1,u.endsWith("}")?-1:void 0),!1,d.params);else if(Zr(u)||is(u)&&Zr(u.slice(1,-1).trim()))m="JSX.Element";else if(u.includes("=>")){let C=u.trimStart(),b=C.indexOf("("),v=b!==-1?ot(C,b,"(",")"):-1,T=v!==-1?C.indexOf("=>",v):-1;if(b===0&&v!==-1&&T!==-1){let B=C.substring(b+1,v).trim(),x=pi(B);if(s.includes("T")&&x.includes("T"))m=`(${x}) => T`;else m=`(${x}) => any`}else m="any"}else if(t)m="unknown";else m=Gt(u,Ho(d.params));let a=`${s}${h} => ${m}`;return t?`(${a})`:a}if(n.startsWith("function")){let s=8,c=n.length;while(s<c&&n.charCodeAt(s)<=32)s++;let l=!1;if(s<c&&n.charCodeAt(s)===42){l=!0,s++;while(s<c&&n.charCodeAt(s)<=32)s++}let f="";if(s<c&&n.charCodeAt(s)===60){let h=s,p=1;s++;while(s<c&&p>0){let m=n.charCodeAt(s);if(m===60)p++;else if(m===62&&n.charCodeAt(s-1)!==61)p--;s++}f=n.substring(h,s);while(s<c&&n.charCodeAt(s)<=32)s++}let u=n.indexOf("(",s);if(u!==-1){let h=1,p=u+1;while(p<c&&h>0){let T=n.charCodeAt(p);if(T===40)h++;else if(T===41)h--;p++}let m=n.substring(u+1,p-1).trim(),a=m?pi(`(${m})`):"()";if(l){let T=n.substring(p).trim(),B=T.indexOf("Generator<");if(B!==-1){let D=B+10,U=T.indexOf(">",D);if(U!==-1){let j=T.substring(D,U),k=`${f}${a} => Generator<${j}>`;return t?`(${k})`:k}}let x=`${f}${a} => Generator<any, any, any>`;return t?`(${x})`:x}let C="unknown",b=n.substring(p).trimStart();if(b.charCodeAt(0)===58){let T=b.slice(1),B=rs(T,0),x=(B?T.slice(0,B.index):T).trim();if(x)C=x}let v=`${f}${a} => ${C}`;return t?`(${v})`:v}let d="(...args: any[]) => unknown";return t?`(${d})`:d}if(n.includes("=>")&&n.includes("(")&&n.includes(")")){if(n.length>100||Ko(n,"=>")>2){let s="";if(n.charCodeAt(0)===60){let d=ot(n,0,"<",">");if(d!==-1)s=n.substring(0,d+1)}let c=n.indexOf("("),l=c!==-1?ot(n,c,"(",")"):-1,f=c!==-1&&l!==-1?n.substring(c,l+1):"(...args: any[])";f=pi(f);let u=`${s}${f} => any`;return t?`(${u})`:u}return t?`(${n})`:n}let o="() => unknown";return t?`(${o})`:o}function Zo(e){let t=e.trim();if(!t.startsWith("("))return{params:t,returnType:""};let i=ot(t,0,"(",")");if(i===-1)return{params:t,returnType:""};let r=t.slice(i+1).trim();return{params:t.slice(0,i+1),returnType:r.startsWith(":")?r.slice(1).trim():""}}function Dl(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 on(e){let t=-1,i=0;for(let n=0;n<e.length;n++){let o=e.charCodeAt(n);if(o===34||o===39||o===96){n=ii(e,n,o)-1;continue}if(o===47&&e.charCodeAt(n+1)===47){while(n<e.length&&e.charCodeAt(n)!==10)n++;continue}if(o===47&&e.charCodeAt(n+1)===42){let s=e.indexOf("*/",n+2);n=s===-1?e.length:s+1;continue}if(o===47){let s=n-1;while(s>=0&&e.charCodeAt(s)<=32)s--;if(s<0||"([{:;,=!?&|+*-~>".includes(e[s])){let c=!1;for(n++;n<e.length;n++){let l=e.charCodeAt(n);if(l===92)n++;else if(l===91)c=!0;else if(l===93)c=!1;else if(l===47&&!c)break}continue}}if(o===40||o===91||o===123)i++;else if(o===41||o===93||o===125)i--;else if(i===0&&e.startsWith("satisfies",n)&&ar(e,n,9)&&e[n-1]!==".")t=n}if(t===-1)return null;let r=e.slice(t+9).trim();if(r.endsWith(";"))r=r.slice(0,-1).trim();return r||null}var rn=20,nn=!1,dt=null;var fr=me(()=>{ut();Hr();Uo();Xr()});function Il(e,t,i,r){let n=new Map,o=new Map;for(let h of[...t,...i.values(),...[...r.values()].flat()])if(n.set(h.name,h),h.kind==="function"&&!o.has(h.name))o.set(h.name,h);for(let[h,p]of r)if(p.length)o.set(h,p[0]);if(!o.size)return;let s=new Set;for(let[h,p]of r)if(p.length>1)s.add(h);let c=new Map;for(let h of t)if(h.kind==="function"){let p=(c.get(h.name)??0)+1;if(c.set(h.name,p),p>1)s.add(h.name)}let l=se(e),f=(h)=>l[h]?e.slice(l[h].start,l[h].end):"",u=new Map,d=0;for(let h=0;h<l.length;h++){let p=f(h);if(["(","[","{"].includes(p)){d++;continue}if([")","]","}"].includes(p)){d--;continue}if(d||!o.has(p)||f(h+1)!=="."||l[h+2]?.kind!=="word"||f(h+3)!=="=")continue;let m=f(h+2),a=h+4,C=a,b=0;for(;C<l.length;C++){let x=f(C);if(!b&&x===";")break;if(!b&&C>a&&/[\r\n]/.test(e.slice(l[C-1].end,l[C].start))&&(["export","const","let","var","function","class"].includes(x)||o.has(x)&&f(C+1)==="."))break;if(["(","[","{"].includes(x))b++;else if([")","]","}"].includes(x))b--}if(C===a)continue;let v=Nl(e.slice(l[a].start,l[C-1].end),n,s),T=u.get(p);if(!T)u.set(p,T=new Map);let B=T.get(m);if(!B)T.set(m,B=[]);if(!B.includes(v))B.push(v);h=C-1}for(let[h,p]of u){let m=o.get(h),a=[...p].map(([b,v])=>` let ${b}: ${v.map((T)=>T.includes("=>")&&v.length>1?`(${T})`:T).join(" | ")};`).join(`
58
+ `),C=m.isExported&&!m.isDefault?"export ":"";if(m.isDefault)m.text=m.text.replace("export default function ","declare function ");if(m.text+=`
59
+ ${C}declare namespace ${h} {
60
+ ${a}
61
+ }`,m.isDefault)m.text+=`
62
+ export default ${h};`}}function Nl(e,t,i,r=0){let n=e.trim(),o=t.get(n);if(o?.kind==="variable"&&r<64){if(o.typeAnnotation)return o.typeAnnotation==="unique symbol"?`typeof ${n}`:o.typeAnnotation;if(typeof o.value==="string")return Nl(o.value,t,i,r+1)}let s=Ae(n,!1);if(s!=="unknown")return s;let c=se(n);if(c[0]?.kind==="word"&&c[1]&&n.slice(c[1].start,c[1].end)==="("&&n.endsWith(")")){let l=0,f=-1;for(let h=1;h<c.length;h++){let p=n.slice(c[h].start,c[h].end);if(p==="(")l++;else if(p===")"&&--l===0){f=h;break}}if(f!==c.length-1)return s;let u=n.slice(c[0].start,c[0].end),d=t.get(u);if(d?.kind==="function"&&!d.generics&&!i.has(u))return`ReturnType<typeof ${u}>`}if(/^[$A-Z_a-z][$\w]*(?:\.[$A-Z_a-z][$\w]*)*$/.test(n))return`typeof ${n}`;return s}var Fl=me(()=>{ut();fr()});function Th(e){if(e.includes(`
63
+ `))return`/**
64
+ * ${e}
65
+ */
66
+ `;return`/** ${e} */
67
+ `}function kh(e){let t=e.indexOf("{");if(t===-1)return-1;let i=e.indexOf("<");if(i===-1||i>t)return t;let r=0,n=!1,o="";for(let s=0;s<e.length;s++){let c=e[s],l=s>0?e[s-1]:"";if(!n&&(c==='"'||c==="'"||c==="`"))n=!0,o=c;else if(n&&c===o&&l!=="\\")n=!1;if(!n){if(c==="<")r++;else if(c===">")r--;else if(c==="{"&&r===0)return s}}return-1}function Wl(e,t=!0){return Ft(e.leadingComments,t)+e.text}function ki(e,t=!0){if(e.inferenceError)throw Object.assign(Error(`Cannot infer alias '${e.name}': unsupported source value flow`),{code:e.inferenceError});let i=Ft(e.leadingComments,t);if(!e.typeAnnotation&&e.inferredType)return i+e.text;if(e.typeAnnotation&&!e.value)return i+e.text;let r="";if(e.isExported)r+="export ";r+="declare ";let n=e.modifiers?.[0]||"const";r+=`${n} `,r+=e.name;let{typeAnnotation:o,value:s}=e,c=!o&&s?on(s):null;if(c)o=c;else if(!o&&s&&s.trim().endsWith("as const"))o=Ae(s,!0,!1,0,e.computedKeyConstants);else if(!o&&s&&n==="const"){let f=s.trim(),u=f.startsWith("{")||f.startsWith("[");if(u)Qo();o=Ae(s,!u,!1,0,e.computedKeyConstants)}else if(!o&&s)o=Ae(s,n==="const",!1,0,e.computedKeyConstants);if(!o)o="unknown";let l="";if(t&&s&&!e.typeAnnotation&&!s.trim().endsWith("as const")){let f=s.trim();if(n!=="const"){if((o==="string"||o==="number"||o==="boolean")&&f.length>0)l=`@defaultValue ${f}`}else if(f.startsWith("{")||f.startsWith("[")){let u=es();if(u)if(u.includes(`
68
+ `))l=`@defaultValue
69
+ * \`\`\`ts
70
+ ${u.split(`
71
+ `).map((d)=>` * ${d}`).join(`
72
+ `)}
73
+ * \`\`\``;else l=`@defaultValue \`${u}\``}}else if(t&&s&&e.typeAnnotation&&Dl(e.typeAnnotation)){Qo();let f=s.trim(),u=f.endsWith("as const")?f.slice(0,-8).trim():f;Ae(u,!1,!1,0,e.computedKeyConstants);let d=es();if(d)if(d.includes(`
74
+ `))l=`@defaultValue
75
+ * \`\`\`ts
76
+ ${d.split(`
77
+ `).map((h)=>` * ${h}`).join(`
78
+ `)}
79
+ * \`\`\``;else l=`@defaultValue \`${d}\``}if(l=Yr(l),r+=`: ${o};`,l&&i&&i.includes("@defaultValue"))l="";if(l&&i){let f=i.trimEnd(),u=f.lastIndexOf("*/");if(u!==-1){let d=f.slice(0,u).trimEnd();if(d.startsWith("/** ")&&!d.includes(`
80
+ `))d=`/**
81
+ * ${d.slice(4)}`;return`${d}
82
+ * ${l}
83
+ */
84
+ `+r}return`/**
85
+ * ${f.replace(/^\/\/\s*/,"")}
86
+ * ${l}
87
+ */
88
+ ${r}`}if(l)return`${Th(l)}${r}`;return i+r}function Ll(e,t=!0){let i=Ft(e.leadingComments,t),r=e.text;if(r.startsWith("export declare interface")||r.startsWith("declare interface"))return i+r;let n="";if(e.isExported)n+="export ";if(n+="declare interface ",n+=e.name,e.generics)n+=e.generics;if(e.extends)n+=` extends ${e.extends}`;let o=kh(e.text);if(o!==-1)n+=` ${e.text.slice(o)}`;else n+=" {}";return i+n}function Bl(e,t=!0){let i=Ft(e.leadingComments,t);if(e.text.includes("{")&&e.text.includes("}")&&e.text.includes("from"))return i+e.text;let r="";if(e.isExported)r+="export ";if(!e.isExported&&!e.text.includes(" from "))r+="declare ";let n=e.text.indexOf("type ");if(n!==-1){let s=e.text.slice(n),c=s.length;while(c>0&&(s.charCodeAt(c-1)===59||s.charCodeAt(c-1)===32||s.charCodeAt(c-1)===10||s.charCodeAt(c-1)===13))c--;if(c<s.length)s=s.slice(0,c);r+=s}else{if(r+=`type ${e.name}`,e.generics)r+=e.generics;r+=" = any"}let o=r.trimEnd();if(!o.endsWith(";")&&!o.endsWith("}"))r+=";";return i+r}function jl(e,t=!0){return Ft(e.leadingComments,t)+e.text}function Gl(e,t=!0){let i=Ft(e.leadingComments,t),r="";if(e.isExported)r+="export ";if(r+="declare ",e.modifiers?.includes("const"))r+="const ";r+="enum ",r+=e.name;let n=e.text.indexOf("{");if(n!==-1)r+=` ${e.text.slice(n)}`;else r+=" {}";return i+r}function _l(e,t=!0){let i=Ft(e.leadingComments,t);if(e.text.startsWith("declare global"))return i+e.text;if(e.source||(e.name.startsWith('"')||e.name.startsWith("'")||e.name.startsWith("`"))){let o="declare module ";o+=e.name;let s=e.text.indexOf("{");if(s!==-1)o+=` ${e.text.slice(s)}`;else o+=" {}";return i+o}let r="";if(e.isExported)r+="export ";if(!e.modifiers?.includes("declare"))r+="declare ";r+="namespace ",r+=e.name;let n=e.text.indexOf("{");if(n!==-1)r+=` ${e.text.slice(n)}`;else r+=" {}";return i+r}var sn=me(()=>{Xr();fr()});function Vl(e){let t=gi.get(e);if(t)return gi.delete(e),gi.set(e,t),t;return null}function Ul(e,t){if(gi.set(e,t),gi.size>200){let i=0;for(let r of gi.keys()){if(i++>=20)break;gi.delete(r)}}}var gi;var Kl=me(()=>{gi=new Map});function ns(e){return kt(e).find((t)=>t.category==="static-import")}function Oh(e){return se(e).map((t)=>e.slice(t.start,t.end)).join(" ")}function Rh(e){let t=ns(e);return t?e.lastIndexOf(" from ",t.start):-1}function an(e){let t=ns(e);return t?ti(t.specifier,"'"):void 0}function yi(e){let t=Vl(e);if(t)return t;let i=wi(e),r=i?[i.defaultName,i.namespaceName,...i.namedItems.map((n)=>n.name)].filter((n)=>n!==null):[];return Ul(e,r),r}function Ph(e){let t=[],i=0;for(let n of se(e)){if(n.kind!=="punctuation"||e.slice(n.start,n.end)!==",")continue;let o=e.slice(i,n.start).trim();if(o)t.push(o);i=n.end}let r=e.slice(i).trim();if(r)t.push(r);return t}function wi(e){e=Oh(e);let t=Kr(e);if(t)return{defaultName:t.name,namedItems:[],source:t.source,isTypeOnly:t.isTypeOnly,isNamespace:!1,namespaceName:null,isImportEquals:!0};let i=Rh(e);if(i===-1)return null;let r=ns(e);if(!r)return null;let n=r.specifier,o=e.slice(0,i).trim(),s=r.isTypeOnly;if(o.startsWith("import "))o=o.slice(7).trim();if(s&&o.startsWith("type "))o=o.slice(5).trim();let c=null,l=[],f=!1,u=null,d=o.includes("{")?-1:o.indexOf("* as ");if(d!==-1)return f=!0,u=o.slice(d+5).trim(),c=o.slice(0,d).trim().replace(/,$/,"").trim()||null,{defaultName:c,namedItems:[],source:n,isTypeOnly:s,isNamespace:f,namespaceName:u};let h=o.indexOf("{"),p=o.lastIndexOf("}");if(h!==-1&&p!==-1){let m=o.slice(0,h).trim();if(m.endsWith(","))c=m.slice(0,-1).trim()||null;let a=o.slice(h+1,p),C=Ph(a);for(let b of C){let v=Mh(b),T=v?b.slice(5).trim():b,B=T.lastIndexOf(" as "),x,D;if(B!==-1)D=T.slice(0,B).trim(),x=T.slice(B+4).trim();else x=T,D=T;l.push({name:x,originalName:D,isTypeOnly:s||v,isDefault:!1})}}else c=o.trim()||null;return{defaultName:c,namedItems:l,source:n,isTypeOnly:s,isNamespace:f,namespaceName:u}}function Mh(e){let t=se(e),i=t[0];if(!i||i.kind!=="word"||e.slice(i.start,i.end)!=="type"||t.length<2)return!1;return!(t.length===3&&e.slice(t[1].start,t[1].end)==="as")}var Ci=me(()=>{ut();Kl()});function os(e,t){let i=(r)=>se(r).map((n)=>r.slice(n.start,n.end)).join("");return i(e)===i(t)}function Hl(e){if(["number","string","boolean","bigint","symbol","undefined","null"].includes(e))return e;let t=Ae(e,!1);return["number","string","boolean","bigint","undefined","null"].includes(t)?t:void 0}function zl(e,t){if(os(e,t))return e;let i=Hl(t);if(!i)return;let r=se(e),n=0,o=0,s=[];for(let l of r){let f=e.slice(l.start,l.end);if(f==="("||f==="["||f==="{"||f==="<")n++;else if(f===")"||f==="]"||f==="}"||f===">")n--;else if(f==="|"&&n===0)s.push(e.slice(o,l.start).trim()),o=l.end}s.push(e.slice(o).trim());let c=s.find((l)=>os(l,t));if(c)return c;if(s.includes(i))return i==="boolean"&&(t==="true"||t==="false")?t:i;return}function ql(e,t,i,r=new Set){let n=new Map,o=[],s=new Set;for(let O of[...t,...i.values()]){if(s.has(O))continue;if(s.add(O),o.push(O),O.kind==="import")for(let W of yi(O.text))n.set(W,{declared:`typeof ${W}`,flow:`typeof ${W}`,unresolved:!1});else if(["function","class","enum"].includes(O.kind))n.set(O.name,{declared:`typeof ${O.name}`,flow:`typeof ${O.name}`,unresolved:!1});else if(O.kind==="variable")n.set(O.name,{declared:O.typeAnnotation,unresolved:!1})}o.sort((O,W)=>(O.start??0)-(W.start??0));let c=new Set(o.filter((O)=>O.kind==="function"&&!O.generics).map((O)=>O.name));for(let O of r)c.add(O);let l=new Map,f=(O)=>{if(O=O.trimStart(),l.has(O))return l.get(O);if(l.set(O,void 0),!ft(O.charCodeAt(0)))return;let W=1;while(ze(O.charCodeAt(W)))W++;if(!c.has(O.slice(0,W)))return;let N=se(O);if(N[0]?.kind!=="word"||!N[1]||O.slice(N[1].start,N[1].end)!=="(")return;let V=1;for(let L=2;L<N.length;L++){let J=O.slice(N[L].start,N[L].end);if(J==="(")V++;else if(J===")"&&--V===0){let de=L===N.length-1?O.slice(N[0].start,N[0].end):void 0;return l.set(O,de),de}}return},u=new Set(o.filter((O)=>O.kind==="variable"&&!O.typeAnnotation&&typeof O.value==="string").map((O)=>f(O.value)).filter((O)=>O!==void 0)).size?se(e):void 0,d=new Map;if(u){let O=0;for(let W=0;W<u.length;W++){let N=e.slice(u[W].start,u[W].end);if(O===0&&N==="function"){let V=u[W+1],L=V&&e.slice(V.start,V.end)==="*"?u[W+2]:V;if(L?.kind==="word"){let J=e.slice(L.start,L.end);d.set(J,(d.get(J)??0)+1)}}if(["{","(","["].includes(N))O++;else if(["}",")","]"].includes(N))O--}}let h=new Map;for(let O of o)if(O.kind==="function"&&!O.generics&&d.get(O.name)===1)h.set(O.name,O);for(let O of r){let W=o.find((N)=>N.kind==="import"&&yi(N.text).includes(O));if(W)h.set(O,W)}let p="__dtsx_call_result";while(e.includes(p))p+="_";let m=(O)=>`(typeof ${O}) extends (...args: never[]) => infer ${p} ? ${p} : never`,a=new Map,C=!1;for(let O of o){if(O.kind!=="variable"||O.typeAnnotation||typeof O.value!=="string")continue;let W=f(O.value);if(W&&h.has(W))a.set(O,m(W)),n.get(O.name).active=!0,n.get(W).active=!0,C=!0;if(O.modifiers?.[0]!=="const")continue;let N=qr(O.value);if(!N||N===O.name||!n.has(N))continue;n.get(N).active=!0,n.get(O.name).active=!0,C=!0}if(!C)return;let b=u??se(e),v=(O)=>b[O]?e.slice(b[O].start,b[O].end):"",T=new Map,B=new Map,x=new Set,D=new Set,U=new Set,j=new Map,k=[];for(let O=0;O<b.length;O++){let W=v(O),N=k.at(-1);if(N!==void 0)B.set(O,N);if(W==="{"&&["=","(","[",",",":","?","return","yield"].includes(v(O-1)))x.add(O);if(["(","[","{"].includes(W))k.push(O);else if([")","]","}"].includes(W)){let V=k.at(-1);if(V!==void 0&&["()","[]","{}"].includes(v(V)+W))k.pop(),T.set(V,O)}}let z=new Map;for(let O=0;O<b.length;){if(b[O].kind!=="punctuation"){O++;continue}let W=[">>>=","**=","&&=","||=","??=","<<=",">>=","===","!==",">>>","**","&&","||","??","<<",">>","=>","==","!=","<=",">=","++","--","+=","-=","*=","/=","%=","&=","|=","^=","="].find((V)=>e.startsWith(V,b[O].start))??v(O);z.set(O,W);let N=b[O].start+W.length;do O++;while(O<b.length&&b[O].start<N)}for(let O=0;O<b.length;O++){let W=be(O);if(W!==void 0)D.add(W)}for(let O of D)ae(O);let Q=0;function ce(O){let W=qr(O);if(W){let J=n.get(W);return{type:J?.flow,unresolved:J?.unresolved??!1}}let N=f(O),V=N?h.get(N):void 0;if(V)return{type:V.returnType&&Hl(V.returnType)?V.returnType:m(N),unresolved:!1};let L=Ae(O,!0);return{type:L==="unknown"?void 0:L,unresolved:!1}}function ge(O){return z.get(O)??""}function ve(O){if(b[O]?.kind!=="word"||U.has(O)||v(O-1)==="."||v(O-1)==="#"&&v(O-2)===".")return;let W=n.get(v(O));if(!W?.active)return;let N=ge(O+1);if(["=","+=","-=","*=","/=","%=","**=","<<=",">>=",">>>=","&=","|=","^=","&&=","||=","??="].includes(N))return{binding:W,operator:N};if(["++","--"].includes(N)&&!/[\r\n]/.test(e.slice(b[O].end,b[O+1].start)))return{binding:W,operator:N};if(O>=2&&["++","--"].includes(ge(O-2))){let V=b[O-3],L=V&&(V.kind==="word"||V.kind==="quoted"||[")","]"].includes(v(O-3)));if(!V||!L||/[\r\n;]/.test(e.slice(V.end,b[O-2].start)))return{binding:W,operator:ge(O-2)}}return}function we(O){let W=ve(O);return W?.operator==="="?W.binding:void 0}function be(O){if(b[O]?.kind!=="word"||v(O)!=="class"||v(O-1)==="."||["(",":","="].includes(v(O+1)))return;let W=O+1,N=0;while(W<b.length){let V=v(W);if(V==="{"&&N===0)return W;if(V==="class"){let L=be(W);if(L!==void 0){W=(T.get(L)??L)+1;continue}}if(V==="function"){let L=ke(W,b.length);if(L){W=L.end;continue}}if(V==="<")N++;else if(V===">"&&ge(W-1)!=="=>"&&N>0)N--;if(V===";")break;W=(T.get(W)??W)+1}return}function oe(O,W,N){let V=O,L=!1,J=N?["public","protected","private","static","abstract","override","declare","readonly","accessor","async","get","set"]:["async","get","set"];while(J.includes(v(V))&&!["(","<","?","!",":","=",";","}"].includes(v(V+1))){if(v(V)==="static")L=!0;V++}if(v(V)==="*")V++;if(N&&v(V)==="#")V++;if(v(V)==="["){let Se=T.get(V);return Se===void 0?void 0:{next:Se+1,isStatic:L}}if(b[V]?.kind==="word"||b[V]?.kind==="quoted")return{next:V+1,isStatic:L};let de=V+1;while(de<W&&b[de-1].end===b[de].start&&!["(","<","?","!",":","=",";","}","[","{",","].includes(v(de)))de++;if(V<W&&Ae(e.slice(b[V].start,b[de-1].end),!1)==="number")return{next:de,isStatic:L};return}function R(O,W,N){let V=oe(O,W,N);if(!V)return;let L=V.next;if(N&&["?","!"].includes(v(L)))L++;if(v(L)==="<"){let J=1;L++;while(L<W&&J>0){if(v(L)==="<")J++;else if(v(L)===">"&&ge(L-1)!=="=>")J--;L=(T.get(L)??L)+1}if(J!==0)return}return L}function Ue(O,W,N){return R(O,W,N)===W}function K(O,W){let N=0,V=-1;for(let L=O;L<W;L=(T.get(L)??L)+1)if(v(L)==="<"&&(N>0||L>O&&(b[L-1].kind==="word"||[")","]"].includes(v(L-1))))){if(N===0)V=L;N++}else if(v(L)===">"&&ge(L-1)!=="=>"&&N>0){if(N--,L===W-1&&N===0)return V<L-1}return!1}function ee(O,W){if(v(O)==="static"&&v(O+1)==="{")return!0;let N=R(O,W,!0);return N!==void 0&&(N===W||["(",":","=",";","}"].includes(v(N)))}function ie(O,W,N=!1){let V=T.get(W)??b.length,L=O;while(L<V){if(v(L)===";"||N&&ge(L)==="=")return L;if(L>O&&B.get(L)===W&&/[\r\n]/.test(e.slice(b[L-1].end,b[L].start))){let J=v(L-1),de=!(J===">"&&K(O,L)&&ee(L,V))&&["+","-","*","/","%","=","<",">","&","|","^","!","~","?",":",",",".","(","[","{","as","in","of","new","typeof","keyof","extends","instanceof","satisfies","await","yield","void"].includes(J),Se=[".","?",":",")","]","}",",","+","-","*","/","%","<",">","=","&","|","^","`","(","[","as","satisfies","instanceof","in"].includes(v(L));if(!de&&!Se)return L}L=(T.get(L)??L)+1}return V}function ue(O,W){for(let N=O;N<W;N++){if(v(N)==="["&&T.has(N)){N=T.get(N);continue}if(b[N].kind==="word")U.add(N)}}function ae(O){let W=T.get(O)??b.length,N=O+1;while(N<W){if(v(N)===";"){N++;continue}if(v(N)==="static"&&v(N+1)==="{"){N=(T.get(N+1)??N+1)+1;continue}let V=oe(N,W,!0);if(!V){N++;continue}let L=R(N,W,!0);if(L===void 0){N++;continue}if(ue(N,L),v(L)==="("){let de=T.get(L),Se=de===void 0?void 0:$e(de,W);if(Se!==void 0){N=(T.get(Se)??Se)+1;continue}}let J=L;if(v(J)===":")J=ie(J+1,O,!0);if(ge(J)==="="){ue(N,J+1);let de=J+1,Se=ie(de,O);if(!V.isStatic&&Se>de)j.set(de,Se);N=Se}else{let de=ie(L,O);ue(N,de),N=Math.max(N+1,de)}}}function fe(O){let W=B.get(O);if(W===void 0)return!1;let N=D.has(W);if(!N&&!x.has(W))return!1;if(Ue(W+1,O,N))return!0;for(let V=W+1;V<O;V++){let L=B.get(V),J=B.get(V)===W&&(v(V)===","||N&&v(V)===";"),de=N&&v(V)==="}"&&L!==void 0&&B.get(L)===W,Se=N&&B.get(V+1)===W&&/[\r\n]/.test(e.slice(b[V].end,b[V+1].start));if((J||de||Se)&&Ue(V+1,O,N))return!0}return!1}function $e(O,W){let N=O+1,V=v(N)===":"?N+1:void 0;while(N<W){if(v(N)==="{"&&(V===void 0||!Go(e.slice(b[V].start,b[N].start))))return N;if(V===void 0)return;N=(T.get(N)??N)+1}return}function ke(O,W){let N=-1;if(v(O)==="("){let L=T.get(O);if(L!==void 0&&fe(O))N=$e(L,W)??-1;else if(L!==void 0&&ge(L+1)==="=>")N=L+3;else if(L!==void 0&&v(L+1)===":"){let J=L+2;while(J<W&&v(J)!==";"){if(ge(J)==="=>"){N=J+2;break}J=(T.get(J)??J)+1}}}else if(b[O]?.kind==="word"&&ge(O+1)==="=>")N=O+3;else if(v(O)==="function"){let L=O+1;while(L<W&&v(L)!=="(")L=(T.get(L)??L)+1;let J=T.get(L);if(J===void 0)return;N=J+1;let de=v(N)===":"?N+1:void 0;while(N<W){if(v(N)==="{"&&(de===void 0||!Go(e.slice(b[de].start,b[N].start))))break;N=(T.get(N)??N)+1}}if(N<0||N>=W)return;if(v(N)==="{")return{start:O,end:(T.get(N)??W-1)+1};let V=N;while(V<W&&![",",";",")","]","}"].includes(v(V)))V=(T.get(V)??V)+1;return{start:O,end:V}}function qe(O,W,N=!0){for(let V=O;V<W;V++){let L=j.get(V);if(L!==void 0){V=Math.min(L,W)-1;continue}let J=N?ke(V,W):void 0;if(J){let Se=J.end;while(v(Se)===")")Se++;if(v(Se)==="("||v(Se)==="."&&["call","apply"].includes(v(Se+1))&&v(Se+2)==="(")qe(J.start,J.end,!1);V=J.end-1;continue}let de=ve(V);if(de)de.binding.flow=void 0,de.binding.unresolved=!0}}function fi(O){let W=!1;while(Q<b.length&&b[Q].start<O){let N=v(Q);if(["if","else","for","while","do","switch","try","catch","finally","with"].includes(N))W=!0;if(N===";")W=!1;if(N==="("||N==="{"||N==="["){let J=T.get(Q)??Q+1;while(J<b.length&&b[J].start>=O)J--;if(qe(Q+1,J),Q=J+1,N==="{")W=!1;continue}let V=we(Q);if(V){let J=Q+2,de=J,Se=[];while(de<b.length&&b[de].start<O){let je=v(de);if(Se.length===0&&(je===";"||de>J&&/[\r\n]/.test(e.slice(b[de-1].end,b[de].start))&&(we(de)||["if","for","while","switch","try","do","return","throw"].includes(je))))break;if(je==="("||je==="{"||je==="[")Se.push(je==="("?")":je==="{"?"}":"]");else if(je===Se.at(-1))Se.pop();de++}let At=de>J?e.slice(b[J].start,b[de-1].end):"";qe(J,de);let Tt=ce(At);V.flow=!W&&Tt.type?V.declared?zl(V.declared,Tt.type):Tt.type:void 0,V.unresolved=W||Tt.unresolved||!V.flow,Q=de;continue}let L=ve(Q);if(L)L.binding.flow=void 0,L.binding.unresolved=!0;Q++}}for(let O of o){fi(O.start??0);let W=Q;while(Q<b.length&&b[Q].start<(O.end??0))Q++;if(O.kind!=="variable")continue;if(O.initializerStart!==void 0){let At=W;while(At<Q&&b[At].start<O.initializerStart)At++;qe(At,Q)}let N=n.get(O.name);if(!N.active)continue;let V=typeof O.value==="string"?O.value:"";if(!V){N.flow=N.declared;continue}let L=ce(V),J=qr(V),de=J?n.get(J):void 0,Se=a.get(O);if(Se)O.inferredType=Se,O.text=`${O.isExported?"export ":""}declare ${O.modifiers?.[0]??"const"} ${O.name}: ${Se};`;else if(!O.typeAnnotation&&O.modifiers?.[0]==="const"&&J&&J!==O.name&&de){if(L.unresolved)O.inferenceError="DTSX_UNSUPPORTED_VALUE_FLOW";else if(L.type)O.inferredType=de.declared&&os(de.declared,L.type)?`typeof ${J}`:L.type,O.text=`${O.isExported?"export ":""}declare const ${O.name}: ${O.inferredType};`}if(O.typeAnnotation)N.flow=L.type?zl(O.typeAnnotation,L.type)??O.typeAnnotation:O.typeAnnotation;else if(O.inferredType)N.declared=O.inferredType,N.flow=O.inferredType;else{let At=O.modifiers?.[0]==="const",Tt=V.trim().startsWith("{")||V.trim().startsWith("["),je=Ae(V,At&&!Tt);N.declared=je==="unknown"?void 0:je,N.flow=N.declared}N.unresolved=L.unresolved}}var Jl=me(()=>{or();ut();sr();Ci();fr()});function Dh(e,t,i,r,n=""){let o=new Map,s={start:0,end:e.length,header:0,name:"",children:[],results:new Map},c=se(e),l=[],f=[],u=[],d=new Map;for(let a=0;a<c.length;a++){let C=c[a];if(C.kind!=="punctuation")continue;let b=e.slice(C.start,C.end);if(b==="(")u.push(a);else if(b===")"){let v=u.pop();if(v!==void 0)d.set(a,v)}else if(b==="{")f.push(a);else if(b==="}"){let v=f.pop();if(v===void 0)continue;let T=c[v].start,B=v-1,x=B>=0?e.slice(c[B].start,c[B].end):"";if(x===")"){let D=d.get(B);if(D!==void 0&&D>0&&["if","for","while","switch","catch","with"].includes(e.slice(c[D-1].start,c[D-1].end)))T=c[D-1].start}else if(["else","try","finally","do"].includes(x))T=c[B].start;l.push({open:c[v].start,close:C.start,header:T})}}let h=0,p=(a,C=new Set)=>{let b=new Set(C),v=se(e.slice(a.start,a.end)),T=0;for(let z=0;z+1<v.length;z++){let Q=e.slice(a.start+v[z].start,a.start+v[z].end);if(Q==="{")T++;else if(Q==="}")T--;else if(!T&&["type","interface"].includes(Q))b.add(e.slice(a.start+v[z+1].start,a.start+v[z+1].end))}let B="",x=a.start,D=[...a.results].map(([z,Q])=>({type:z,name:Q}));for(let z of a.children.sort((Q,ce)=>Q.header-ce.header)){let Q=p(z,b);B+=e.slice(x,z.header)+`
89
+ declare namespace ${z.name} {
90
+ ${Q.text}
91
+ }
92
+ `,x=z.end+1;for(let ce of Q.exports)D.push({type:`${z.name}.${ce.name}`,name:ce.name})}B+=`${e.slice(x,a.end)}
93
+ ;
94
+ ${D.map((z)=>`export type ${z.name} = ${z.type};`).join(`
95
+ `)}`;let U=fn(B,t,!1);for(let z of D)b.add(z.name);let j=n?as(n).map((z,Q)=>[z,`${m}_capture_${Q}`]):[],k=U.map((z)=>n&&["type","interface"].includes(z.kind)?Ih(z,n,j,b):(z.kind==="variable"?ki(z,!1):z.text).replace(/^export\s+/,"").replace(/^declare\s+/,"")).join(`
96
+ `);return{declarations:U,text:k,exports:D}},m;return{resolve(a,C){m??=i();let b=s;for(let T of l.filter((B)=>B.open<C&&C<B.close).sort((B,x)=>B.open-x.open)){let B=b.children.find((x)=>x.start===T.open+1);if(!B)B={start:T.open+1,end:T.close,header:T.header,name:`${m}_scope_${h++}`,children:[],results:new Map},b.children.push(B);b=B}let v=b.results.get(a);if(!v)v=`${m}_result_${o.size}`,b.results.set(a,v),o.set(v,a);return`${m}.${v}`},finish(a){if(!m)return a;let C=p(s),b=C.declarations,v=new Set(o.keys());if(b.every((B)=>v.has(B.name))){let B=new Map(o),x=se(a),D="",U=0;for(let j=0;j+2<x.length;j++){if(a.slice(x[j].start,x[j].end)!==m||a.slice(x[j+1].start,x[j+1].end)!==".")continue;let k=B.get(a.slice(x[j+2].start,x[j+2].end));if(!k)continue;D+=a.slice(U,x[j].start)+`(${k})`,U=x[j+2].end,j+=2}return D+a.slice(U)}if(n){let B=as(n).join(", "),x=se(a),D="",U=0;for(let j=0;j+2<x.length;j++){if(a.slice(x[j].start,x[j].end)!==m||a.slice(x[j+1].start,x[j+1].end)!=="."||!v.has(a.slice(x[j+2].start,x[j+2].end)))continue;D+=`${a.slice(U,x[j+2].end)}<${B}>`,U=x[j+2].end,j+=2}a=D+a.slice(U)}let T=C.text;return r({kind:"module",name:m,text:`declare namespace ${m} {
97
+ ${T}
98
+ }`,moduleForm:"namespace",isExported:!1}),a}}}function as(e){let t=se(e),i=[],r=0,n=0,o=!1;for(let s of t){let c=e.slice(s.start,s.end);if(c==="<"){if(r++,r===1)o=!0}else if(c===">"&&e[s.start-1]!=="=")r--;else if(["(","[","{"].includes(c))n++;else if([")","]","}"].includes(c))n--;else if(c===","&&r===1&&!n)o=!0;else if(o&&s.kind==="word"&&!["const","in","out"].includes(c))i.push(c),o=!1}return i}function Ih(e,t,i,r){let n=new Set(as(e.generics||"")),o=(p,m,a)=>{let C=se(p),b="",v=0;for(let T=0;T<C.length;T++){let B=C[T],x=p.slice(B.start,B.end),D=C[T+1]&&p.slice(C[T+1].start,C[T+1].end),U=C[T+2]&&p.slice(C[T+2].start,C[T+2].end),j=C[T-1]&&p.slice(C[T-1].start,C[T-1].end);if(B.kind!=="word"||D===":"||D==="?"&&U===":")continue;let k=!a.has(x)&&j!=="."&&i.find(([z])=>z===x)?.[1];if(k)b+=p.slice(v,B.start)+k,v=B.end;else if(m&&r.has(x)&&!a.has(x)){let z=i.map(([,Q])=>Q).join(", ");b+=`${p.slice(v,B.end)}<${z}${D==="<"?", ":">"}`,v=D==="<"?C[++T].end:B.end}}return b+p.slice(v)},s=se(e.text),c=s.findIndex((p)=>["type","interface"].includes(e.text.slice(p.start,p.end))),l=s[c+1],f=e.generics||"",u=f?e.text.indexOf(f,l.end)+f.length:l.end,d=o(Nh(t),!1,new Set),h=f?`, ${o(f.slice(1,-1),!0,n)}`:"";return`${e.text.slice(0,l.end)}<${d}${h}>${o(e.text.slice(u),!0,n)}`.replace(/^export\s+/,"").replace(/^declare\s+/,"")}function Nh(e){let t=e.slice(1,-1),i=se(t),r=0,n=0,o=!1,s="";for(let c=0;c<i.length;c++){let l=i[c],f=t.slice(l.start,l.end);if(["(","[","{","<"].includes(f))r++;else if([")","]","}"].includes(f)||f===">"&&t[l.start-1]!=="=")r--;else if(!r&&f==="const")s+=t.slice(n,l.start),n=l.end;else if(!r&&f==="="&&t.slice(i[c+1]?.start,i[c+1]?.end)!==">")s+=t.slice(n,l.start),o=!0;else if(!r&&f===","&&o)n=l.start,o=!1}return s+(o?"":t.slice(n))}function Xe(e){return e===Qe||e===et||e===Ie||e===_e}function Lh(e){let t=!0;for(let i=0;i<e.length;i++){let r=e.charCodeAt(i);if(r===Wt){if(t)return!1;t=!0}else if(t){if(!ft(r))return!1;t=!1}else if(!ze(r))return!1}return e.length>0&&!t}function cn(e,t,i){let r=t+1;while(r<e.length){let n=e.charCodeAt(r);if(n===Ct){r+=2;continue}if(r++,n===i)break}return r}function Bh(e){if(e==="any"||e==="object"||e==="unknown")return!0;if(e.startsWith("Record<")||e.startsWith("Array<"))return!0;return e.charCodeAt(0)===te&&e.includes("[")&&e.includes("]:")}function ur(e,t,i=!0){return cs(e,t,i,!0)}function fn(e,t,i=!0,r){return cs(e,t,i,!1,!1,r)}function ls(e,t,i=!0){return cs(e,t,i,!0,!0)}function cs(e,t,i,r,n=!1,o){let s=e,c=i,l=r,f=s.length,u=hi(s),d=[],h=new Map,p=new Map,m=new Set,a=0,C=0,b=[];function v(g){let w=/^this\.([\w$]+)$/.exec(g);if(w){let I=b.at(-1);return I?.fields.get(`${I.isStatic?"static:":""}${w[1]}`)}let y=/^([\w$]+)\s*\(/.exec(g);if(!y||!g.endsWith(")"))return;let E=se(g),S=0;for(let I=1;I<E.length;I++){let F=g.slice(E[I].start,E[I].end);if(F==="(")S++;else if(F===")"&&--S===0&&I!==E.length-1)return}let A=[...d,...h.values()].filter((I)=>I.kind==="function"&&I.name===y[1]);if(A.length!==1||A[0].generics||zr(s,y[1])!==1)return;return A[0].returnType}function T(g){let w=g.trim(),y=v(w);if(y)return y;if(!w.startsWith("class"))return;let E=se(w);if(E[0]?.kind!=="word"||w.slice(E[0].start,E[0].end)!=="class")return;let S;do S=`__dtsx_class_${C++}`;while(s.includes(S));let A=E[1],I=A?w.slice(A.start,A.end):"",F=A?.kind==="word"&&!["extends","implements"].includes(I),P=F?I:`${S}_value`,M=F?`export ${w}`:`export class ${P} ${w.slice(5)}`,G=fn(M,t,c),X=G.find((H)=>H.kind==="class");if(!X)throw Error("Cannot extract the class expression declaration");if(se(M.slice(X.end??M.length)).some((H)=>M.slice((X.end??0)+H.start,(X.end??0)+H.end)!==";"))return;let Z=G.map((H)=>H.text.replace(/^export\s+/,"").replace(/^declare\s+/,"")).join(`
99
+ `);return h.set(S,{kind:"module",name:S,text:`declare namespace ${S} {
100
+ ${Z}
101
+ }`,moduleForm:"namespace",isExported:!1,start:a,end:a}),`typeof ${S}.${P}`}function B(g,w){let y=/^this\.([\w$]+)$/.exec(g);if(y)return b.at(-1)?.fields.get(`${w?"static:":""}${y[1]}`);return T(g)}function x(g){let w=p.get(g.name);if(w)w.push(g);else p.set(g.name,[g]);h.set(g.name,g)}if(a<f&&s.charCodeAt(a)===65279)a++;function D(g,w){if(g<w){let y=s.charCodeAt(g),E=s.charCodeAt(w-1);if(y!==Qe&&y!==et&&y!==Ie&&y!==_e&&E!==Qe&&E!==et&&E!==Ie&&E!==_e)return s.slice(g,w)}while(g<w&&Xe(s.charCodeAt(g)))g++;while(w>g&&Xe(s.charCodeAt(w-1)))w--;return s.slice(g,w)}let U=/[\r\n]/g;function j(g){return U.lastIndex=g,U.exec(s)?.index??f}function k(){if(a>=f)return;let g=s.charCodeAt(a);if(g!==Qe&&g!==et&&g!==Ie&&g!==_e&&g!==pe)return;while(a<f){let w=s.charCodeAt(a);if(w===Qe||w===et||w===Ie||w===_e){a++;continue}if(w===pe&&a+1<f){let y=s.charCodeAt(a+1);if(y===pe){a=j(a+2);continue}if(y===Le){let E=s.indexOf("*/",a+2);a=E===-1?f:E+2;continue}}break}}function z(g){let w=g.length,y=0,E=w;for(let S=0;S<w;S++){let A=g.charCodeAt(S);if(y){if(A===Ct){S++;continue}if(A===y)y=0;continue}if(A===Pe||A===De||A===Ye){y=A;continue}if(A===pe&&S+1<w){let I=g.charCodeAt(S+1);if(I===pe){E=S;while(E>0&&(g.charCodeAt(E-1)===Qe||g.charCodeAt(E-1)===et))E--;return g.slice(0,E)}if(I===Le){let F=g.indexOf("*/",S+2);if(F!==-1){g=`${g.slice(0,S)} ${g.slice(F+2)}`,S--;continue}}}}E=w;while(E>0&&(g.charCodeAt(E-1)===Qe||g.charCodeAt(E-1)===et||g.charCodeAt(E-1)===_e))E--;return E<w?g.slice(0,E):g}function Q(g){a++;let w=g===Pe?"'":'"';while(a<f){let y=s.indexOf(w,a);if(y===-1){a=f;return}let E=0,S=y-1;while(S>=0&&s.charCodeAt(S)===Ct)E++,S--;if(E%2===0){a=y+1;return}a=y+1}}function ce(){a++;let g=[];while(a<f){let w=s.charCodeAt(a);if(g.length===0){if(w===Ct){a+=2;continue}if(w===Ye){a++;return}if(w===Wh&&a+1<f&&s.charCodeAt(a+1)===te){a+=2,g.push(0);continue}a++;continue}if(w===Pe||w===De){Q(w);continue}if(w===Ye){ce();continue}if(w===pe&&a+1<f){let y=s.charCodeAt(a+1);if(y===pe){a=j(a+2);continue}if(y===Le){let E=s.indexOf("*/",a+2);a=E===-1?f:E+2;continue}if(we()){be();continue}a++;continue}if(w===te){g[g.length-1]++,a++;continue}if(w===le){let y=g[g.length-1];if(y===0){g.pop(),a++;continue}g[g.length-1]=y-1,a++;continue}a++}}let ge=!1;function ve(){ge=!1;let g=s.charCodeAt(a);if(g===Pe||g===De)return Q(g),!0;if(g===Ye)return ce(),!0;if(g===pe&&a+1<f){let w=s.charCodeAt(a+1);if(w===pe)return a=j(a+2),!0;if(w===Le){let y=s.indexOf("*/",a+2);return ge=j(a+2)<(y===-1?f:y),a=y===-1?f:y+2,!0}if(we())return be(),!0}return!1}function we(){return Ur(s,a)}function be(){a=nr(s,a)}function oe(){let g=a;while(a<f&&ze(s.charCodeAt(a)))a++;return s.slice(g,a)}function R(g){if(a+g.length>f)return!1;for(let w=0;w<g.length;w++)if(s.charCodeAt(a+w)!==g.charCodeAt(w))return!1;if(a+g.length<f&&ze(s.charCodeAt(a+g.length)))return!1;return!0}function Ue(g){let w=a+g;while(w<f){let y=s.charCodeAt(w);if(y===Qe||y===et||y===Ie||y===_e){w++;continue}return y!==Wt&&y!==Be}return!1}function K(){if(!ge)return!1;let g=a;k();let w=a>=f||ee()||s.charCodeAt(a)===le;return a=g,w}function ee(){if(a>=f)return!1;switch(s.charCodeAt(a)){case 101:return R("export")||R("enum");case 105:return R("import")||R("interface");case 102:return R("function");case 99:return R("class")||R("const");case 116:return R("type");case 108:return R("let");case 118:return R("var");case 100:return R("declare")||R("default");case 109:return R("module");case 110:return R("namespace");case 97:return R("abstract")||R("async");default:return!1}}function ie(){let g=s.charCodeAt(a);if(g!==Ie&&g!==_e)return!1;let w=a;if(a++,g===_e&&a<f&&s.charCodeAt(a)===Ie)a++;while(a<f){let E=s.charCodeAt(a);if(E===Qe||E===et||E===_e||E===Ie){a++;continue}if(E===pe&&a+1<f){let S=s.charCodeAt(a+1);if(S===pe){a=j(a+2);continue}if(S===Le){let A=s.indexOf("*/",a+2);a=A===-1?f:A+2;continue}}break}let y=a>=f||ee()||s.charCodeAt(a)===le;return a=w,y}function ue(g){let w=g-1;while(w>=0){let P=s.charCodeAt(w);if(P===Qe||P===et||P===_e||P===Ie){w--;continue}break}if(w<0)return!0;let y=s[w];if("+-*/%=<>&|^!~?:,.([{".includes(y))return!0;let E=w;while(E>0&&s.charCodeAt(E-1)!==Ie)E--;let S=s.slice(E,w+1),A=S.lastIndexOf("<");if(A!==-1&&/^<[A-Za-z]/.test(S.slice(A))&&!S.slice(A).includes(">"))return!0;let I=w;while(I>=0&&/[a-z]/i.test(s[I]))I--;let F=s.slice(I+1,w+1);return["as","in","of","new","typeof","keyof","extends","instanceof","satisfies","await","return","yield","void"].includes(F)}function ae(){let g=s.charCodeAt(a);if(g!==Ie&&g!==_e)return!1;if(ue(a))return!1;let w=a;a++;while(a<f){let A=s.charCodeAt(a);if(A===Qe||A===et||A===_e||A===Ie){a++;continue}if(A===pe&&a+1<f){let I=s.charCodeAt(a+1);if(I===pe){a=j(a+2);continue}if(I===Le){let F=s.indexOf("*/",a+2);a=F===-1?f:F+2;continue}}break}let y=a<f?s[a]:"",E=s.slice(a,a+2),S=y==="."||y==="?"||y===":"||y===")"||y==="]"||y==="}"||y===","||y==="+"||y==="-"||y==="*"||y==="/"||y==="%"||y==="<"||y===">"||y==="="||y==="&"||y==="|"||y==="^"||y==="`"||E==="=>"||R("as")||R("satisfies")||R("instanceof")||R("in");return a=w,!S}function fe(){let g=s.charCodeAt(a);if(g!==Ie&&g!==_e)return!1;if(ue(a))return!1;let w=a;a++;while(a<f){let S=s.charCodeAt(a);if(S===Qe||S===et||S===_e||S===Ie){a++;continue}if(S===pe&&a+1<f){let A=s.charCodeAt(a+1);if(A===pe){a=j(a+2);continue}if(A===Le){let I=s.indexOf("*/",a+2);a=I===-1?f:I+2;continue}}break}let y=a<f?s[a]:"",E=y==="|"||y==="&"||y==="["||y==="."||y==="?"||y===":"||y===">"||y===")"||y===","||R("extends");return a=w,!E}function $e(){let g=s.charCodeAt(a);if(g!==Ie&&g!==_e)return!1;let w=a;if(a++,g===_e&&a<f&&s.charCodeAt(a)===Ie)a++;while(a<f){let E=s.charCodeAt(a);if(E===Qe||E===et||E===_e||E===Ie){a++;continue}if(E===pe&&a+1<f&&s.charCodeAt(a+1)===pe){a=j(a+2);continue}break}if(a>=f)return a=w,!0;let y=s.charCodeAt(a);if(y===124||y===38||y===Wt||y===ln||y===Et)return a=w,!1;if(R("extends")||R("keyof")||R("typeof")||R("infer")||R("is")||R("as")||R("in"))return a=w,!1;return a=w,!0}let ke=/[{}'"`\/]/g,qe=/[()'"`\/]/g,fi=/[[\]'"`\/]/g,O=/[<>'"`\/]/g;function W(g,w){let y=1;a++;let E=g===te?ke:g===Ce?qe:g===Ge?fi:O;E.lastIndex=a;let S;while((S=E.exec(s))!==null){let A=S.index,I=s.charCodeAt(A);if(I===Pe||I===De){a=A,Q(I),E.lastIndex=a;continue}if(I===Ye){a=A,ce(),E.lastIndex=a;continue}if(I===pe){if(a=A,ve()){E.lastIndex=a;continue}E.lastIndex=A+1;continue}if(I===g)y++;else if(I===w){if(w===Re&&A>0&&s.charCodeAt(A-1)===Be){E.lastIndex=A+1;continue}if(y--,y===0)return a=A+1,a}E.lastIndex=A+1}return a=f,a}function N(){return a>0&&s.charCodeAt(a-1)===Be}function V(){return a+1<f&&s.charCodeAt(a+1)===Re}let L=/[<{};'"`\/\n\r()[\]]/g;function J(g=!1){let w=0,y=0,E=0,S=0,A=s.charCodeAt(a)===te;L.lastIndex=a;let I;while((I=L.exec(s))!==null){let F=I.index,P=s.charCodeAt(F);if(P===Pe||P===De){a=F,Q(P),L.lastIndex=a;continue}if(P===Ye){a=F,ce(),L.lastIndex=a;continue}if(P===pe){if(F>0&&s.charCodeAt(F-1)===Me){L.lastIndex=F+1;continue}if(a=F,ve()){if(w===0&&y===0&&E===0&&S===0&&K())return;L.lastIndex=a;continue}L.lastIndex=F+1;continue}if(P===Me){let M=Ra(F);if(M!==null)S=Math.max(0,S+M);L.lastIndex=F+1;continue}if(P===Ce){y++,L.lastIndex=F+1;continue}if(P===Oe){y--,L.lastIndex=F+1;continue}if(P===Ge){E++,L.lastIndex=F+1;continue}if(P===He){E--,L.lastIndex=F+1;continue}if(P===te){w++,L.lastIndex=F+1;continue}if(P===le){let M=w>0;if(!M&&g&&y===0&&E===0&&S===0){a=F;return}if(M)w--;if((!M||A)&&w===0&&y===0&&E===0&&S===0){a=F+1;return}if(M&&w===0&&y===0&&E===0&&S===0){a=F+1;let G=a;k();let X=ee();if(a=G,X)return}L.lastIndex=F+1;continue}if(P===ye&&w===0&&y===0&&E===0&&S===0){a=F+1;return}if((P===Ie||P===_e)&&w===0&&y===0&&E===0&&S===0){if(a=F,ie())return}L.lastIndex=F+1}a=f}function de(){a++;while(a<f&&(s.charCodeAt(a)===Qe||s.charCodeAt(a)===et))a++;let g=s.indexOf(`
102
+ `,a),w=g===-1?f:g,y=s.indexOf(";",a);if(y!==-1&&y<w){let E=y-1;while(E>=a&&(s.charCodeAt(E)===Qe||s.charCodeAt(E)===et))E--;let S=s.charCodeAt(a),A=s.charCodeAt(E);if(S===te&&A===le||S===Ge&&A===He||S===Pe&&A===Pe||S===De&&A===De||S===Ye&&A===Ye){a=y+1;return}}J()}function Se(){W(te,le);while(a<f&&Xe(s.charCodeAt(a)))a++;if(R("from")){a+=4;while(a<f&&Xe(s.charCodeAt(a)))a++;if(a<f){let g=s.charCodeAt(a);if(g===Pe||g===De)Q(g)}}while(a<f&&(s.charCodeAt(a)===Qe||s.charCodeAt(a)===et))a++;if(a<f&&s.charCodeAt(a)===ye)a++}function At(){a++;while(a<f&&Xe(s.charCodeAt(a)))a++;if(R("as")){a+=2;while(a<f&&Xe(s.charCodeAt(a)))a++;oe();while(a<f&&Xe(s.charCodeAt(a)))a++}if(R("from")){a+=4;while(a<f&&Xe(s.charCodeAt(a)))a++;if(a<f){let g=s.charCodeAt(a);if(g===Pe||g===De)Q(g)}}while(a<f&&(s.charCodeAt(a)===Qe||s.charCodeAt(a)===et))a++;if(a<f&&s.charCodeAt(a)===ye)a++}function Tt(g){let w=g.indexOf("from ");if(w===-1)return;let y=w+5;while(y<g.length&&(g.charCodeAt(y)===32||g.charCodeAt(y)===9))y++;if(y>=g.length)return;let E=g.charCodeAt(y);if(E!==39&&E!==34)return;let S=g.indexOf(g[y],y+1);if(S===-1)return;return g.slice(y+1,S)}function je(g){if(!c)return;let w=g-1;while(w>=0&&Xe(s.charCodeAt(w)))w--;if(w<0)return;let y=[],E=!1;while(w>=0){if(w>=1&&s.charCodeAt(w)===pe&&s.charCodeAt(w-1)===Le){let I=s.lastIndexOf("/*",w-2);if(I>=0){y.push(s.slice(I,w+1)),E=!0,w=I-1;while(w>=0&&Xe(s.charCodeAt(w)))w--;continue}break}let S=w;while(S>0&&s.charCodeAt(S-1)!==Ie)S--;let A=D(S,w+1);if(A.startsWith("//")){if(E)break;let I=[A];w=S-1;while(w>=0&&(s.charCodeAt(w)===Ie||s.charCodeAt(w)===_e))w--;while(w>=0){let F=w;while(F>0&&s.charCodeAt(F-1)!==Ie)F--;let P=D(F,w+1);if(P.startsWith("//")){I.push(P),w=F-1;while(w>=0&&(s.charCodeAt(w)===Ie||s.charCodeAt(w)===_e))w--}else if(P===""){w=F-1;while(w>=0&&(s.charCodeAt(w)===Ie||s.charCodeAt(w)===_e))w--}else break}I.reverse(),y.push(I.join(`
103
+ `));continue}break}if(y.length===0)return;return y.reverse(),y}function od(g){let w=g,y=!1,E=0,S;while(a<f){let Z=s.charCodeAt(a);if(Z===pe&&(s.charCodeAt(a+1)===pe||s.charCodeAt(a+1)===Le)){k();continue}if(Z===ye){a++;break}if(Z===te)E++;else if(Z===le&&E>0)E--;if(Z===Pe||Z===De){if(Q(Z),E>0)continue;y=!0;let H=a;if(k(),s.charCodeAt(a)===Oe){let _=a+1;S=Kr(s.slice(w,_)),a=S?_:H}else a=H;while(a<f&&(s.charCodeAt(a)===Qe||s.charCodeAt(a)===et))a++;if(a<f&&s.charCodeAt(a)===ye)a++;break}if(Z===Ie&&y)break;a++}let A=D(w,a),I=kt(A).find((Z)=>Z.category==="static-import"),F=se(A),P=S?.isTypeOnly??I?.isTypeOnly??!1,M=F[1]?.kind==="quoted",G=S?.source??I?.specifier??"",X=je(w);return{kind:"import",name:"",text:A,isExported:!1,isTypeOnly:P,isSideEffect:M,source:G,leadingComments:X,start:w,end:a}}function fo(){let g=a;return W(te,le),s.slice(g,a)}function xa(g){let w=g.indexOf("(");if(w===-1)return g;let y=g.slice(w);if(y.indexOf("=")===-1)return g;let E=!1;for(let P=0;P<y.length;P++)if(y.charCodeAt(P)===61){let M=P>0?y.charCodeAt(P-1):0,G=P+1<y.length?y.charCodeAt(P+1):0;if(M!==61&&M!==33&&M!==60&&M!==62&&G!==61&&G!==62){E=!0;break}}if(!E)return g;let S=0,A=-1;for(let P=w;P<g.length;P++){let M=g.charCodeAt(P);if(M===40)S++;else if(M===41){if(S--,S===0){A=P;break}}}if(A===-1)return g;let I=g.slice(w,A+1),F=Ei(I);return g.slice(0,w)+F+g.slice(A+1)}function Aa(g){let w=g.indexOf("//")!==-1||g.indexOf("/*")!==-1,y=g.split(`
104
+ `),E=[],S=[],A=[],I=!1,F=1/0;for(let G=0;G<y.length;G++){let X=y[G];if(w){if(I){if(X.includes("*/"))I=!1;continue}let Z=X.trim();if(Z.length===0)continue;let H=Z.charCodeAt(0);if(H===pe){let Ee=Z.charCodeAt(1);if(Ee===pe)continue;if(Ee===Le){if(!Z.includes("*/"))I=!0;continue}}if(H===Le)continue;let _=z(X);if(_.charCodeAt(_.length-1)===ye)_=_.slice(0,-1);_=xa(_);let q=_.trim();if(!q)continue;E.push(_),S.push(q);let Y=0;while(Y<_.length&&Xe(_.charCodeAt(Y)))Y++;if(q!=="{"&&q!=="}"){if(Y<F)F=Y}A.push(Y)}else{let Z=X.length;while(Z>0&&(X.charCodeAt(Z-1)===Qe||X.charCodeAt(Z-1)===et||X.charCodeAt(Z-1)===_e))Z--;if(Z===0)continue;let H=Z<X.length?X.slice(0,Z):X;if(H.charCodeAt(H.length-1)===ye)H=H.slice(0,-1);H=xa(H);let _=H.trim();if(!_)continue;E.push(H),S.push(_);let q=0;while(q<H.length&&Xe(H.charCodeAt(q)))q++;if(_!=="{"&&_!=="}"){if(q<F)F=q}A.push(q)}}if(E.length===0)return"{}";if(F===1/0||F<=2)return E.join(`
105
+ `);let P=F-2,M=Array(E.length);for(let G=0;G<E.length;G++){let X=S[G];if(X==="{"){M[G]=X;continue}let Z=A[G];if(Z>F)M[G]=E[G];else if(Z===F&&(X.charCodeAt(0)===le||X.charCodeAt(0)===He||X.charCodeAt(0)===Oe))M[G]=E[G];else{let H=Math.max(0,Z-P);M[G]=" ".repeat(H)+X}}return M.join(`
106
+ `)}function It(){if(a>=f||s.charCodeAt(a)!==Me)return"";let g=a;W(Me,Re);let w=s.slice(g,a);if(w.includes(`
107
+ `)){let y="",E=!1;for(let S=0;S<w.length;S++){let A=w.charCodeAt(S);if(A===32||A===9||A===10||A===13){if(!E&&y.length>0)y+=" ",E=!0}else y+=w[S],E=!1}if(y.charCodeAt(1)===32)y=`<${y.slice(2)}`;if(y.charCodeAt(y.length-2)===32)y=`${y.slice(0,-2)}>`;return y}return w}function Zt(){if(a>=f||s.charCodeAt(a)!==Ce)return"()";let g=a;return W(Ce,Oe),s.slice(g,a)}function Rr(g){if(g.indexOf("/")===-1)return g;let w="",y=!1,E=0;for(let S=0;S<g.length;S++){let A=g.charCodeAt(S);if(y){if(w+=g[S],A===Ct&&S+1<g.length){w+=g[++S];continue}if(A===E)y=!1;continue}if(A===Pe||A===De||A===Ye){y=!0,E=A,w+=g[S];continue}if(A===pe&&S+1<g.length){let I=g.charCodeAt(S+1);if(I===Le){let F=g.indexOf("*/",S+2);S=F===-1?g.length:F+1,w+=" ";continue}if(I===pe){let F=g.indexOf(`
108
+ `,S+2);S=F===-1?g.length:F-1;continue}}w+=g[S]}return w.trim()}function Ei(g){let w=g.slice(1,-1).trim();if(!w)return"()";if(g.indexOf(`
109
+ `)===-1&&w.indexOf(":")!==-1&&w.indexOf("{")===-1&&w.indexOf("[")===-1&&w.indexOf("=")===-1&&w.indexOf("@")===-1&&w.indexOf("...")===-1){let P=0,M=0,G=0;for(let X=0;X<w.length;X++){let Z=w.charCodeAt(X);if(Z===Ce||Z===Me||Z===te)G++;else if(Z===Oe||Z===Re||Z===le)G--;else if(G===0){if(Z===Et)P++;else if(Z===Pt)M++}}if(P>=M+1){let X=!1;for(let Z=0;Z<ss.length;Z++){let H=ss[Z],_=w.indexOf(H);if(_!==-1){let q=_+H.length;if((_===0||!ze(w.charCodeAt(_-1)))&&(q>=w.length||!ze(w.charCodeAt(q)))){X=!0;break}}}if(!X)return g}}let y=[],E=0,S=0,A=!1,I=0;for(let P=0;P<=w.length;P++){if(P===w.length){y.push(Rr(w.slice(E).trim()));break}let M=w.charCodeAt(P);if(A){if(M===Ct){P++;continue}if(M===I)A=!1;continue}if(M===pe&&P+1<w.length){let G=w.charCodeAt(P+1);if(G===Le){P+=2;while(P+1<w.length&&!(w.charCodeAt(P)===Le&&w.charCodeAt(P+1)===pe))P++;P++;continue}if(G===pe){while(P<w.length&&w.charCodeAt(P)!==10)P++;continue}}if(M===Pe||M===De||M===Ye){A=!0,I=M;continue}if(M===Ce||M===te||M===Ge||M===Me)S++;else if(M===Oe||M===le||M===He||M===Re&&!(P>0&&w.charCodeAt(P-1)===Be))S--;else if(M===Pt&&S===0)y.push(Rr(w.slice(E,P).trim())),E=P+1}let F=[];for(let P of y){if(!P)continue;let M=P.trim();if(M.startsWith("//")||M.startsWith("/*"))continue;let G=P;{let X=!1,Z=0,H=0,_=0;for(let q=0;q<G.length-1;q++){let Y=G.charCodeAt(q);if(Y===Ie){_=q+1;continue}if(X){if(Y===Ct){q++;continue}if(Y===Z)X=!1;continue}if(Y===Pe||Y===De||Y===Ye){X=!0,Z=Y;continue}if(Y===te||Y===Ge||Y===Ce||Y===Me){H++;continue}if(Y===le||Y===He||Y===Oe||Y===Re){if(H>0)H--;continue}if(Y===pe&&G.charCodeAt(q+1)===pe){if(H===0){G=G.slice(0,q).trimEnd();break}let Ee=G.indexOf(`
110
+ `,q);if(Ee===-1){G=G.slice(0,_).trimEnd();break}let re=G.slice(0,_),he=G.slice(Ee+1);G=`${re}${he}`,q=_-1}}}if(!G.trim())continue;F.push(Ta(G))}return Jr(`(${F.join(", ")})`)}function sd(g){if(!g.startsWith("{")&&!g.startsWith("["))return g;let w="",y=0,E=0,S=!1,A=0;while(y<g.length){let I=g.charCodeAt(y);if(S){if(I===Ct&&y+1<g.length){w+=g[y]+g[y+1],y+=2;continue}if(I===A)S=!1;w+=g[y],y++;continue}if(I===pe&&y+1<g.length){let F=g.charCodeAt(y+1);if(F===Le){let P=y;y+=2;while(y+1<g.length&&!(g.charCodeAt(y)===Le&&g.charCodeAt(y+1)===pe))y++;y=Math.min(y+2,g.length),w+=g.slice(P,y);continue}if(F===pe){let P=y;while(y<g.length&&g.charCodeAt(y)!==10)y++;w+=g.slice(P,y);continue}}if(I===Pe||I===De||I===Ye){S=!0,A=I,w+=g[y],y++;continue}if(I===te||I===Ge||I===Ce)E++;else if(I===le||I===He||I===Oe)E--;if(E>=1&&I===Be&&(y+1>=g.length||g.charCodeAt(y+1)!==Be&&g.charCodeAt(y+1)!==Re)){while(w.length>0&&(w[w.length-1]===" "||w[w.length-1]==="\t"||w[w.length-1]===`
111
+ `))w=w.slice(0,-1);y++;let F=0;while(y<g.length){let P=g.charCodeAt(y);if(P===Pe||P===De||P===Ye){let M=P;y++;while(y<g.length){if(g.charCodeAt(y)===Ct){y+=2;continue}if(g.charCodeAt(y)===M){y++;break}y++}continue}if(P===te||P===Ge||P===Ce)F++;else if(P===le||P===He||P===Oe){if(F===0)break;F--}else if(P===Pt&&F===0)break;y++}continue}if(E===1&&I===Wt&&y+2<g.length&&g.charCodeAt(y+1)===Wt&&g.charCodeAt(y+2)===Wt){y+=3;continue}w+=g[y],y++}return w}function Ta(g){let w=g.trim(),y=w.startsWith("...");if(y)w=w.slice(3).trim();while(w.startsWith("@")){let _=1;while(_<w.length&&ze(w.charCodeAt(_)))_++;if(_<w.length&&w.charCodeAt(_)===Ce){let q=1;_++;while(_<w.length&&q>0){if(w.charCodeAt(_)===Ce)q++;else if(w.charCodeAt(_)===Oe)q--;_++}}w=w.slice(_).trim()}let E=!0;while(E){E=!1;for(let _ of ss)if(w.startsWith(_)&&w.length>_.length&&!ze(w.charCodeAt(_.length))){let q=w.slice(_.length).trim();if(q.charCodeAt(0)===Et||q.charCodeAt(0)===ln&&q.length>1&&q.charCodeAt(1)===Et)break;w=q,E=!0;break}}let S=-1,A=-1,I=0,F=!1,P=0;for(let _=0;_<w.length;_++){let q=w.charCodeAt(_);if(F){if(q===Ct){_++;continue}if(q===P)F=!1;continue}if(q===pe&&_+1<w.length){let Y=w.charCodeAt(_+1);if(Y===Le){_+=2;while(_+1<w.length&&!(w.charCodeAt(_)===Le&&w.charCodeAt(_+1)===pe))_++;_++;continue}if(Y===pe){while(_<w.length&&w.charCodeAt(_)!==10)_++;continue}}if(q===Pe||q===De||q===Ye){F=!0,P=q;continue}if(q===Ce||q===te||q===Ge||q===Me)I++;else if(q===Oe||q===le||q===He||q===Re&&!(_>0&&w.charCodeAt(_-1)===Be))I--;else if(I===0){if(q===Et&&S===-1)S=_;else if(q===Be&&A===-1&&(_===0||w.charCodeAt(_-1)!==Be)&&(_+1>=w.length||w.charCodeAt(_+1)!==Be&&w.charCodeAt(_+1)!==Re))A=_}}let M,G,X=A!==-1;if(S!==-1&&(A===-1||S<A))if(M=w.slice(0,S).trim(),A!==-1)G=w.slice(S+1,A).trim();else G=w.slice(S+1).trim();else if(A!==-1)M=w.slice(0,A).trim(),G=uo(w.slice(A+1).trim());else M=w,G="unknown";if(M=sd(M),(M.startsWith("{")||M.startsWith("["))&&M.includes(`
112
+ `)){let _=M.replace(/\s*\n\s*/g," ").replace(/\s+/g," ");if(_.length<=40)M=_;else M=M.split(`
113
+ `).map((q)=>{let Y=q.trim();if(!Y)return"";if(Y==="{"||Y==="}"||Y==="["||Y==="]"||Y.startsWith("}")||Y.startsWith("]"))return Y;return` ${Y}`}).join(`
114
+ `)}let Z=M.endsWith("?")||X;if(M.endsWith("?"))M=M.slice(0,-1).trim();let H=Z&&!y?"?":"";if(y)return`...${M}: ${G}`;return`${M}${H}: ${G}`}function ka(g){let w=0;if(w<g.length&&g.charCodeAt(w)===45)w++;if(w>=g.length)return!1;let y=g.charCodeAt(w);if(y<48||y>57)return!1;while(w<g.length&&g.charCodeAt(w)>=48&&g.charCodeAt(w)<=57)w++;if(w<g.length&&g.charCodeAt(w)===46){if(w++,w>=g.length||g.charCodeAt(w)<48||g.charCodeAt(w)>57)return!1;while(w<g.length&&g.charCodeAt(w)>=48&&g.charCodeAt(w)<=57)w++}return w===g.length}function uo(g){let w=g.trim(),y=v(w);if(y)return y;if(w==="true"||w==="false")return"boolean";if(ka(w))return"number";if(w.startsWith("'")&&w.endsWith("'")||w.startsWith('"')&&w.endsWith('"'))return"string";if(w.startsWith("["))return"unknown[]";if(w.startsWith("{"))return"Record<string, unknown>";return cr(w)??"unknown"}function ho(g){let w=g.trim();if(w.endsWith("as const"))w=w.slice(0,-8).trim();if(w==="true"||w==="false")return w;if(ka(w))return w;let y=ad(w);if(y!==null)return y;return cr(w)??"unknown"}function ad(g){if(g==="")return null;if(g.charCodeAt(0)===Pe||g.charCodeAt(0)===De){if(cn(g,0,g.charCodeAt(0))===g.length)return g}let w=ld(g,"+");if(w.length>1){let y=!1,E=!0,S=[];for(let A of w){let I=A.trim(),F=I.charCodeAt(0);if((F===Pe||F===De)&&cn(I,0,F)===I.length)y=!0,S.push(cd(I));else E=!1}if(E)return fd(S.join(""));if(y)return"string";return null}if(/^[\d\s()+*/%.\-]+$/.test(g)&&/\d/.test(g)&&/[+*/%\-\s]/.test(g))return"number";return null}function ld(g,w){let y=[],E=0,S="",A=0;while(A<g.length){let I=g.charCodeAt(A);if(I===Pe||I===De||I===Ye){let F=cn(g,A,I);S+=g.slice(A,F),A=F;continue}if(I===pe&&(g.charCodeAt(A+1)===pe||g.charCodeAt(A+1)===42)){if(g.charCodeAt(A+1)===pe){let M=g.indexOf(`
115
+ `,A+2),G=M===-1?g.length:M;S+=g.slice(A,G),A=G;continue}let F=g.indexOf("*/",A+2),P=F===-1?g.length:F+2;S+=g.slice(A,P),A=P;continue}if(I===Ce||I===Ge||I===te)E++;else if(I===Oe||I===He||I===le)E--;if(g[A]===w&&E===0){y.push(S),S="",A++;continue}S+=g[A],A++}return y.push(S),y}function cd(g){return g.slice(1,-1).replace(/\\(.)/g,(w,y)=>{if(y==="n")return`
116
+ `;if(y==="t")return"\t";if(y==="r")return"\r";if(y==="0")return"\x00";return y})}function fd(g){return`'${g.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function Pr(g){if(g.endsWith("as const"))return null;let w=0,y=-1;for(let E=0;E<g.length;E++){let S=g.charCodeAt(E);if(S===Pe||S===De||S===Ye)E=cn(g,E,S)-1;else if(S===123||S===91||S===40)w++;else if(S===125||S===93||S===41)w--;else if(w===0&&S===32&&E+4<=g.length&&g.substring(E,E+4)===" as ")y=E}if(y===-1)return null;return g.slice(y+4).trim()||null}function Yi(){if(k(),a<f&&s.charCodeAt(a)===Et){let g=function(){let S=D(w,E),A=(I)=>{let F=S.length-I.length;return F>=0&&S.endsWith(I)&&(F===0||!ze(S.charCodeAt(F-1)))};return S.length===0||S.endsWith("=>")||S.endsWith("|")||S.endsWith("&")||A("is")||A("extends")};a++,k();let w=a,y=0,E=w;while(a<f){let S=a;if(ve()){if(s.charCodeAt(S)!==pe)E=a;continue}let A=s.charCodeAt(a);if(A===Ce||A===Ge||A===Me)y++;else if(A===Oe||A===He||A===Re&&!N())y--;else if(A===te)if(y>0)y++;else if(g())y++;else break;else if(A===le){if(y===0)break;y--}else if(y===0&&A===ye)break;if(y===0&&$e()&&!g())break;if(!Xe(A))E=a+1;a++}return D(w,a)}return""}function Qt(g,w,y,E){a+=8,k();let S=a<f&&s.charCodeAt(a)===Le;if(S)a++,k();let A=oe();if(!A&&!E)return null;k();let I=It();k();let F=Zt();k();let P=Yi(),M=P.length>0;if(!P)if(y&&S)P="AsyncGenerator<unknown, void, unknown>";else if(S)P="Generator<unknown, void, unknown>";else if(y)P="Promise<void>";else P="void";k();let G=!1;if(a<f&&s.charCodeAt(a)===te){G=!0;let q=a+1;if(W(te,le),!M&&!S){let Y=s.slice(q,a-1),Ee=Dh(Y,t,()=>{let re;do re=`__dtsx_return_${C++}`;while(s.includes(re));return re},(re)=>h.set(re.name,{...re,start:a,end:a}),I);P=Ee.finish(_t(Y,y,F,T,Ee.resolve))}}else if(a<f&&s.charCodeAt(a)===ye)a++;let X=Ei(F),Z=`${w?E?"export default function ":"export declare function ":"declare function "}${A||(E?"":"default")}${I}${X}: ${P};`,H=je(g),_={kind:"function",name:A||"default",text:Z,isExported:w,isDefault:E,isAsync:y,isGenerator:S,returnType:P,generics:I||void 0,leadingComments:H,start:g,end:a};if(G)m.add(_);return _}let po,ud=0;function Oa(){po??=new Set(se(s).filter((g)=>g.kind==="word").map((g)=>s.slice(g.start,g.end)));for(;;){let g=`__dtsx_binding_${ud++}`;if(po.has(g))continue;return po.add(g),g}}function ui(g,w,y){a+=w.length,k();let E=[];do{if(k(),a>=f)break;let S=s.charCodeAt(a),A,I=a;if(S===te||S===Ge)W(S,S===te?le:He),A=s.slice(I,a);let F=A?Oa():oe();if(!F)return J(),E;k();let P,M,G,X=!1;if(a<f&&s.charCodeAt(a)===Et){a++,k();let Ee=a,re=0;while(a<f){if(ve()){if(re===0&&K())break;continue}let he=s.charCodeAt(a);if(he===Ce||he===te||he===Ge||he===Me)re++;else if(he===Oe||he===le||he===He||he===Re&&!N())re--;else if(re===0&&(he===ye||he===Pt))break;else if(re===0&&he===Be&&!V())break;if(re===0&&(ie()||fe()))break;a++}P=D(Ee,a)}if(a<f&&s.charCodeAt(a)===Be)if(l&&P&&(!c||!Bh(P)))de();else{a++,k();let Ee=a;G=Ee;let re=0,he=0,gt=0,di=!0;for(;;){a=Ee,re=0,he=0,gt=0;while(a<f){if(ve()){if(re===0&&he===0&&gt===0&&K())break;continue}let Ze=s.charCodeAt(a);if(Ze===Ce||Ze===te||Ze===Ge)re++;else if(Ze===Oe||Ze===le||Ze===He)re--;else if(Ze===Me&&re===0){let Xi=Ra(a);if(Xi!==null)gt=Math.max(0,gt+Xi);else if(di&&(a+1>=f||s.charCodeAt(a+1)!==Be))he++}else if(Ze===Re&&re===0&&gt===0&&!N()){if(he>0&&(a+1>=f||s.charCodeAt(a+1)!==Be))he--}else if(re===0&&he===0&&gt===0&&(Ze===ye||Ze===Pt))break;if(re===0&&he===0&&gt===0&&(ie()||ae()))break;a++}if(he>0&&di){di=!1;continue}break}if(M=D(Ee,a),M.endsWith(" as const")||M==="const"){if(X=!0,!P){let Ze=M.endsWith(" as const")?M.slice(0,-9).trim():M,Xi=ho(Ze);P=Xi!=="unknown"?Xi:void 0}}else if(!P){let Ze=on(M)??Pr(M)??T(M);if(Ze)P=Ze}}let Z=E.length===0?je(g):void 0,H=A?"const":w,_=A?!1:y,q=`${_?"export ":""}declare ${H} ${F}: ${P||"unknown"};`,Y={kind:"variable",name:F,text:q,isExported:_,typeAnnotation:P,value:M,initializerStart:G,modifiers:X?[H,"const assertion"]:[H],leadingComments:A?void 0:Z,start:g,end:a};if(A)E.push(...cl({pattern:A,patternOffset:I,root:Y,kind:w,exported:y,comments:Z,allocateName:Oa}));else E.push(Y);if(s.charCodeAt(a)===Pt){a++;continue}if(s.charCodeAt(a)===ye)a++;break}while(a<f);return E}function Ra(g){if(s.charCodeAt(g)!==Me||g+1>=f)return null;let w=s.charCodeAt(g+1);if(w===Re)return 1;if(w===pe)return-1;if(!ft(w))return null;let y=g+2;while(y<f){let M=s.charCodeAt(y);if(!ze(M)&&M!==Wt&&M!==58&&M!==45)break;y++}let E=s.slice(g+1,y),S=s.charCodeAt(y);if(S>32&&S!==Re&&S!==pe)return null;let A=0,I=0,F=y;for(;F<f;F++){let M=s.charCodeAt(F);if(I!==0){if(M===Ct)F++;else if(M===I)I=0;continue}if(M===Pe||M===De||M===Ye)I=M;else if(M===te)A++;else if(M===le&&A>0)A--;else if(M===Re&&A===0)break}if(F>=f)return null;let P=F-1;while(P>g&&s.charCodeAt(P)<=32)P--;if(s.charCodeAt(P)===pe)return 0;return s.indexOf(`</${E}`,F+1)===-1?null:1}function mo(g,w){a+=9,k();let y=oe();k();let E=It();k();let S="";if(R("extends")){a+=7,k();let M=a,G=0;while(a<f){if(ve())continue;let X=s.charCodeAt(a);if(X===Me)G++;else if(X===Re&&!N())G--;else if(X===te&&G===0)break;a++}S=D(M,a)}k();let A=a<f&&s.charCodeAt(a)===te?fo():"{}",I=Aa(A),F=`${w?"export ":""}declare interface ${y}${E}${S?` extends ${S}`:""} ${I}`,P=je(g);return{kind:"interface",name:y,text:F,isExported:w,extends:S||void 0,generics:E||void 0,leadingComments:P,start:g,end:a}}function go(g,w){a+=4,k();let y=oe();k();let E=It();if(k(),a<f&&s.charCodeAt(a)===Be)a++;k();let S=a,A=0;while(a<f){if(ve())continue;let M=s.charCodeAt(a);if(M===Ce||M===te||M===Ge||M===Me)A++;else if(M===Oe||M===le||M===He||M===Re&&!N())A--;else if(A===0&&M===ye)break;if(A===0&&(ie()||fe()))break;a++}let I=D(S,a);if(a<f&&s.charCodeAt(a)===ye)a++;let F=`${w?"export ":""}type ${y}${E} = ${I}`,P=je(g);return{kind:"type",name:y,text:F,isExported:w,generics:E||void 0,leadingComments:P,start:g,end:a}}function Si(g,w,y){a+=4,k();let E=oe();k();let S=a;if(a<f&&s.charCodeAt(a)===te)W(te,le);let A=D(g,a),I=je(g);return{kind:"enum",name:E,text:A,isExported:w,modifiers:y?["const"]:void 0,leadingComments:I,start:g,end:a}}function ei(g,w,y,E=!1){a+=5,k();let S=oe()||"AnonymousClass";k();let A=It();k();let I="";if(R("extends")){a+=7,k();let X=a,Z=0;while(a<f){if(ve())continue;let H=s.charCodeAt(a);if(H===Me)Z++;else if(H===Re&&!N())Z--;else if(Z===0&&(H===te||R("implements")))break;a++}I=D(X,a)}let F;if(R("implements")){a+=10,k();let X=a,Z=0;while(a<f){if(ve())continue;let _=s.charCodeAt(a);if(_===Me)Z++;else if(_===Re&&!N())Z--;else if(Z===0&&_===te)break;a++}let H=D(X,a);if(H)F=H.split(",").map((_)=>_.trim())}k();let P=yo(),M=`${w?E?"export default ":"export declare ":"declare "}${y?"abstract ":""}class ${S}${A}${I?` extends ${I}`:""}${F&&F.length>0?` implements ${F.join(", ")}`:""} ${P}`,G=je(g);return{kind:"class",name:S,text:M,isExported:w,isDefault:E,extends:I||void 0,implements:F,generics:A||void 0,modifiers:y?["abstract"]:void 0,leadingComments:G,start:g,end:a}}function yo(){if(a>=f||s.charCodeAt(a)!==te)return"{}";a++;let g={fields:new Map,pending:[],isStatic:!1};b.push(g);let w=[],y=new Set;while(a<f){if(k(),a>=f)break;if(s.charCodeAt(a)===le){a++;break}if(s.charCodeAt(a)===ye){a++;continue}if(R("static")&&Dr("static")===te){a+=6,k(),W(te,le);continue}let E=!1,S=!1,A=!1,I=!1,F=!1,P=!1,M=!1,G=!1,X=!0;while(X){k();let Ee=a,re=oe();if(a=Ee,re){let he=Dr(re);if(he===Ce||he===Me||he===ln||he===33||he===Et||he===Be||he===ye||he===le)break}if(R("private")){E=!0,a+=7;continue}if(R("protected")){S=!0,a+=9;continue}if(R("public")){a+=6;continue}if(R("static")){A=!0,a+=6;continue}if(R("abstract")){I=!0,a+=8;continue}if(R("readonly")){F=!0,a+=8;continue}if(R("override")){P=!0,a+=8;continue}if(R("accessor")){M=!0,a+=8;continue}if(R("async")){G=!0,a+=5;continue}if(R("declare")){a+=7;continue}break}if(k(),a>=f||s.charCodeAt(a)===le)break;let Z=a;if(g.isStatic=A,(R("get")||R("set"))&&wo(Dr(s.slice(a,a+3))))a+=3,k();if(s.charCodeAt(a)===Le)a++,k();let H=Mr();a=Z;let _=H.startsWith("#");if(_)E=!0;if(E&&H&&H!=="constructor"){let Ee=_?A?" static #private_static;":" #private;":` private ${A?"static ":""}${H};`,re=H[0]==="'"||H[0]==='"'?mt(H)??H:H,he=_?`${A?"static":"instance"}#`:`${A?"static:":"instance:"}${re}`;if(!y.has(he))y.add(he),w.push(Ee)}let q=E?[]:w,Y=" ";if(S)Y+="protected ";if(A)Y+="static ";if(I)Y+="abstract ";if(F)Y+="readonly ";if(R("constructor")){a+=11,k();let Ee=Zt();if(k(),hd(Ee,w),a<f&&s.charCodeAt(a)===te)W(te,le);else if(a<f&&s.charCodeAt(a)===ye)a++;let re=Ei(Ee);w.push(E?" private constructor();":` ${S?"protected ":""}constructor${re};`)}else if(R("get"))if(a+=3,k(),a<f&&wo(s.charCodeAt(a))){let Ee=Mr();if(Ee.startsWith("#")){if(k(),a<f&&s.charCodeAt(a)===Ce)Zt();if(k(),Yi(),k(),a<f&&s.charCodeAt(a)===te)W(te,le);else if(a<f&&s.charCodeAt(a)===ye)a++;continue}k(),Zt(),k();let re=Yi(),he;if(k(),a<f&&s.charCodeAt(a)===te){let di=a+1;if(W(te,le),!re&&!l)he=s.slice(di,a-1),re=_t(he,!1,"()",(Ze)=>B(Ze,A))}else if(a<f&&s.charCodeAt(a)===ye)a++;let gt=q.length;if(q.push(`${Y}get ${Ee}(): ${re||"unknown"};`),he)g.pending.push(()=>{let di=_t(he,!1,"()",(Ze)=>B(Ze,A));q[gt]=`${Y}get ${Ee}(): ${di};`})}else Ma("get",Y,A,F,G,q);else if(R("set"))if(a+=3,k(),a<f&&wo(s.charCodeAt(a))){let Ee=Mr();if(Ee.startsWith("#")){if(k(),a<f&&s.charCodeAt(a)===Ce)Zt();if(k(),a<f&&s.charCodeAt(a)===te)W(te,le);else if(a<f&&s.charCodeAt(a)===ye)a++;continue}k();let re=Zt();if(k(),a<f&&s.charCodeAt(a)===te)W(te,le);else if(a<f&&s.charCodeAt(a)===ye)a++;let he=Ei(re);q.push(`${Y}set ${Ee}${he};`)}else Ma("set",Y,A,F,G,q);else{let Ee=s.charCodeAt(a)===Le;if(Ee)a++,k();let re=Mr();if(!re){Pa();continue}Da(re,Y,A,F,Ee,I,G,q)}}for(let E of g.pending)E();return b.pop(),`{
117
+ ${w.join(`
118
+ `)}
119
+ }`}function wo(g){return ft(g)||g===Ge||g===Yl||g===Pe||g===De}function Mr(){if(a>=f)return"";let g=s.charCodeAt(a);if(g===Ge){let w=a;return W(Ge,He),s.slice(w,a)}if(g===Yl)return a++,`#${oe()}`;if(g===Pe||g===De){let w=a;return Q(g),s.slice(w,a)}return oe()}function Dr(g){let w=a;a+=g.length,k();let y=a<f?s.charCodeAt(a):0;return a=w,y}function Pa(){let g=0;while(a<f){if(ve())continue;let w=s.charCodeAt(a);if(w===te||w===Ce)g++;else if(w===le||w===Oe){if(g===0)return;g--}else if(w===ye&&g===0){a++;return}if(g===0&&$e())return;a++}}function Ma(g,w,y,E,S,A){Da(g,w,y,E,!1,!1,S,A)}function Da(g,w,y,E,S,A,I,F){if(k(),a>=f)return;let P=s.charCodeAt(a),M=!1;if(P===ln)M=!0,a++,k();if(a<f&&s.charCodeAt(a)===33)a++,k();let G=a<f?s.charCodeAt(a):0;if(G===Ce||G===Me){let X=G===Me?It():"";k();let Z=Zt();k();let H=Yi(),_,q=H.length>0;if(!H)if(I&&S)H="AsyncGenerator<unknown, void, unknown>";else if(S)H="Generator<unknown, void, unknown>";else if(I)H="Promise<void>";else H="void";if(k(),a<f&&s.charCodeAt(a)===te){let he=a+1;if(W(te,le),!q&&!S)_=s.slice(he,a-1),H=_t(_,I,Z,(gt)=>B(gt,y))}else if(a<f&&s.charCodeAt(a)===ye)a++;let Y=Ei(Z),Ee=M?"?":"",re=F.length;if(F.push(`${w}${g}${Ee}${X}${Y}: ${H};`),_)b.at(-1)?.pending.push(()=>{let he=_t(_,I,Z,(gt)=>B(gt,y));F[re]=`${w}${g}${Ee}${X}${Y}: ${he};`})}else if(G===Et||G===Be||G===ye||G===le||G===Ie||G===_e){let X="";if(G===Et){a++,k();let _=a,q=0;while(a<f){if(ve())continue;let Y=s.charCodeAt(a);if(Y===Ce||Y===te||Y===Ge||Y===Me)q++;else if(Y===Oe||Y===le||Y===He||Y===Re&&!N()){if(q===0)break;q--}else if(q===0&&(Y===ye||Y===Pt))break;else if(q===0&&Y===Be&&!V())break;if(q===0&&$e())break;a++}X=D(_,a)}let Z="";if(a<f&&s.charCodeAt(a)===Be)if(l&&X){a++;let _=0;while(a<f){if(ve())continue;let q=s.charCodeAt(a);if(q===Ce||q===te||q===Ge)_++;else if(q===Oe||q===le||q===He){if(_===0&&q===le)break;_--}else if(_===0&&q===ye)break;if(_===0&&$e())break;a++}}else{a++,k();let _=a,q=0;while(a<f){if(ve())continue;let Y=s.charCodeAt(a);if(Y===Ce||Y===te||Y===Ge)q++;else if(Y===Oe||Y===le||Y===He){if(q===0&&Y===le)break;q--}else if(q===0&&Y===ye)break;if(q===0&&$e())break;a++}Z=D(_,a)}if(a<f&&s.charCodeAt(a)===ye)a++;if(!X)if(Z){let _=Pr(Z);if(_)X=_;else X=Z.endsWith("as const")||y&&E?ho(Z):uo(Z)}else X="unknown";let H=M?"?":"";b.at(-1)?.fields.set(`${y?"static:":""}${g}`,M?`(${X}) | undefined`:X),F.push(`${w}${g}${H}: ${X};`)}else Pa()}function dd(g){let w=0;for(let y=0;y<g.length;y++){let E=g.charCodeAt(y);if(E===Ce||E===te||E===Ge||E===Me)w++;else if(E===Oe||E===le||E===He||E===Re&&g.charCodeAt(y-1)!==Be)w--;else if(E===Be&&w===0&&g.charCodeAt(y+1)!==Re&&g.charCodeAt(y+1)!==Be)return!0}return!1}function hd(g,w){let y=g.slice(1,-1).trim();if(!y)return;let E=[],S=0,A=0,I=!1,F=0;for(let P=0;P<=y.length;P++){if(P===y.length){E.push(Rr(y.slice(S).trim()));break}let M=y.charCodeAt(P);if(I){if(M===Ct){P++;continue}if(M===F)I=!1;continue}if(M===pe&&P+1<y.length){let G=y.charCodeAt(P+1);if(G===Le){P+=2;while(P+1<y.length&&!(y.charCodeAt(P)===Le&&y.charCodeAt(P+1)===pe))P++;P++;continue}if(G===pe){while(P<y.length&&y.charCodeAt(P)!==10)P++;continue}}if(M===Pe||M===De||M===Ye){I=!0,F=M;continue}if(M===Ce||M===te||M===Ge||M===Me)A++;else if(M===Oe||M===le||M===He||M===Re&&!(P>0&&y.charCodeAt(P-1)===Be))A--;else if(M===Pt&&A===0)E.push(Rr(y.slice(S,P).trim())),S=P+1}for(let P of E){let M=P.startsWith("public ")||P.startsWith("public\t"),G=P.startsWith("protected ")||P.startsWith("protected\t"),X=P.startsWith("private ")||P.startsWith("private\t"),Z=P.includes("readonly ");if(!M&&!G&&!X&&!Z)continue;let H=P,_=[];if(X){let re=7;while(re<H.length&&Xe(H.charCodeAt(re)))re++;H=H.slice(re),_.push("private")}if(M){let re=6;while(re<H.length&&Xe(H.charCodeAt(re)))re++;H=H.slice(re),_.push("public")}if(G){let re=9;while(re<H.length&&Xe(H.charCodeAt(re)))re++;H=H.slice(re),_.push("protected")}if(Z){let re=H.indexOf("readonly ");if(re!==-1){let he=re+8;while(he<H.length&&Xe(H.charCodeAt(he)))he++;H=H.slice(0,re)+H.slice(he)}_.push("readonly")}let q=_.length>0?`${_.join(" ")} `:"",Y=Ta(H),Ee=H.search(/[?:=]/);if(Ee!==-1&&H.charCodeAt(Ee)!==63&&dd(H))Y=Y.replace(/^([\w$]+)\?:/,"$1:");w.push(X?` private ${Y.split(/[?:]/,1)[0]};`:` ${q}${Y};`)}}function Co(g=" "){if(a>=f||s.charCodeAt(a)!==te)return"{}";a++;let w=[];while(a<f){if(k(),a>=f)break;if(s.charCodeAt(a)===le){a++;break}if(s.charCodeAt(a)===ye){a++;continue}let y=!1;if(R("export"))y=!0,a+=6,k();if(R("declare"))a+=7,k();let E=y?"export ":"";if(R("function")||R("async")&&pd("async","function")){let S=!1;if(R("async"))S=!0,a+=5,k();if(a+=8,k(),a<f&&s.charCodeAt(a)===Le)a++,k();let A=oe();k();let I=It();k();let F=Zt();k();let P=Yi();if(!P)P=S?"Promise<void>":"void";if(k(),a<f&&s.charCodeAt(a)===te)W(te,le);else if(a<f&&s.charCodeAt(a)===ye)a++;let M=Ei(F);w.push(`${g}${E}function ${A}${I}${M}: ${P};`)}else if(R("const")||R("let")||R("var")){let S=R("const")?"const":R("let")?"let":"var";a+=S.length,k();let A=oe();if(!A){J(!0);continue}k();let I="";if(a<f&&s.charCodeAt(a)===Et){a++,k();let P=a,M=0;while(a<f){if(ve())continue;let G=s.charCodeAt(a);if(G===Ce||G===te||G===Ge||G===Me)M++;else if(G===le&&M===0)break;else if(G===Oe||G===le||G===He||G===Re&&!N())M--;else if(M===0&&(G===ye||G===Pt))break;else if(M===0&&G===Be&&!V())break;if(M===0&&ie())break;a++}I=D(P,a)}let F="";if(a<f&&s.charCodeAt(a)===Be){a++,k();let P=a,M=0;while(a<f){if(ve())continue;let G=s.charCodeAt(a);if(G===Ce||G===te||G===Ge||G===Me)M++;else if(G===le&&M===0)break;else if(G===Oe||G===le||G===He||G===Re&&!N())M--;else if(M===0&&(G===ye||G===Pt))break;if(M===0&&ie())break;a++}F=D(P,a)}if(a<f&&s.charCodeAt(a)===ye)a++;if(!I&&F){let P=Pr(F);if(P)I=P;else if(S==="const")I=ho(F);else I=uo(F)}if(!I)I="unknown";w.push(`${g}${E}${S} ${A}: ${I};`)}else if(R("interface")){a+=9,k();let S=oe();k();let A=It();k();let I="";if(R("extends")){a+=7,k();let P=a,M=0;while(a<f){if(ve())continue;let G=s.charCodeAt(a);if(G===Me)M++;else if(G===Re&&!N())M--;else if(G===te&&M===0)break;a++}I=D(P,a)}let F=Aa(fo());w.push(`${g}${E}interface ${S}${A}${I?` extends ${I}`:""} ${F}`)}else if(R("type")){a+=4,k();let S=oe();k();let A=It();if(k(),a<f&&s.charCodeAt(a)===Be){a++,k();let I=a,F=0;while(a<f){if(ve())continue;let M=s.charCodeAt(a);if(M===Ce||M===te||M===Ge||M===Me)F++;else if(M===le&&F===0)break;else if(M===Oe||M===le||M===He||M===Re&&!N())F--;else if(F===0&&M===ye)break;if(F===0&&ie())break;a++}let P=D(I,a);if(a<f&&s.charCodeAt(a)===ye)a++;w.push(`${g}${E}type ${S}${A} = ${P}`)}}else if(R("class")){a+=5,k();let S=oe();k();let A=It();k();let I=a,F=0;while(a<f){if(ve())continue;let X=s.charCodeAt(a);if(X===Me)F++;else if(X===Re&&!N())F--;else if(X===te&&F===0)break;a++}let P=D(I,a),M=P?` ${P}`:"",G=yo();w.push(`${g}${E}class ${S}${A}${M} ${G}`)}else if(R("enum")){a+=4,k();let S=oe();k();let A=fo();w.push(`${g}${E}enum ${S} ${A}`)}else if(R("namespace")||R("module")){let S=R("namespace")?"namespace":"module";a+=S.length,k();let A=oe();k();let I=Co(g);w.push(`${g}${E}${S} ${A} ${I}`)}else if(R("abstract"))if(a+=8,k(),R("class")){a+=5,k();let S=oe();k();let A=It();k();let I=a,F=0;while(a<f){if(ve())continue;let X=s.charCodeAt(a);if(X===Me)F++;else if(X===Re&&!N())F--;else if(X===te&&F===0)break;a++}let P=D(I,a),M=P?` ${P}`:"",G=yo();w.push(`${g}${E}abstract class ${S}${A}${M} ${G}`)}else J(!0);else if(y&&R("default")){a+=7,k();let S=a;J(!0);let A=D(S,a);if(A.charCodeAt(A.length-1)===ye)A=A.slice(0,-1);if(A)w.push(`${g}export default ${A};`)}else if(!y&&(s.charCodeAt(a)===Pe||s.charCodeAt(a)===De||s.charCodeAt(a)===Ye))J(!0);else J(!0)}if(w.length===0)return"{}";return`{
120
+ ${w.join(`
121
+ `)}
122
+ }`}function pd(g,w){let y=a+g.length;while(y<f&&Xe(s.charCodeAt(y)))y++;for(let E=0;E<w.length;E++)if(y+E>=f||s.charCodeAt(y+E)!==w.charCodeAt(E))return!1;return y+w.length>=f||!ze(s.charCodeAt(y+w.length))}function xi(g,w,y){a+=y.length,k();let E="",S=s.charCodeAt(a);if(S===Pe||S===De){let M=a;Q(S),E=s.slice(M,a)}else{E=oe();while(a<f&&s.charCodeAt(a)===Wt)a++,E+=`.${oe()}`}k();let A=a<f&&s.charCodeAt(a)===te?Co():"{}",I=`${w?"export ":""}declare ${y} ${E} ${A}`,F=je(g),P=E.startsWith("'")||E.startsWith('"');return{kind:"module",name:E,text:I,isExported:w,moduleForm:P?"quoted":y==="namespace"?"namespace":"identifier",source:P?E.slice(1,-1):void 0,leadingComments:F,start:g,end:a}}function Ia(g,w){J();let y=D(w,a);if(y.charCodeAt(y.length-1)===ye)y=y.slice(0,-1).trimEnd();if(!y)return;let E=ft(y.charCodeAt(0));for(let M=1;E&&M<y.length;M++)E=ze(y.charCodeAt(M));let S=je(g);if(E){d.push({kind:"export",name:"default",text:`export default ${y};`,isExported:!0,isTypeOnly:!1,leadingComments:S,start:g,end:a});return}let A="__dtsx_default_export__",I=1;while(s.includes(A))A=`__dtsx_default_export_${I++}__`;let F=Pr(y)||T(y)||Ae(y,!1),P=F==="unknown"&&Lh(y)?`typeof ${y}`:F;d.push({kind:"variable",name:A,text:`declare const ${A}: ${P};`,isExported:!1,typeAnnotation:P,modifiers:["const"],start:g,end:a}),d.push({kind:"export",name:"default",text:`export default ${A};`,isExported:!0,isTypeOnly:!1,leadingComments:S,start:g,end:a})}function Na(){if(s.charCodeAt(a)===te)return W(te,le),!0;let g=R("if"),w=R("do"),y=R("try"),E=R("for");if(!g&&!w&&!y&&!E&&!R("while")&&!R("switch")&&!R("with"))return!1;if(oe(),k(),E&&R("await"))a+=5,k();if(!w&&!y&&s.charCodeAt(a)===Ce)W(Ce,Oe);if(Ir(),k(),g&&R("else"))a+=4,Ir();else if(w&&R("while")){if(a+=5,k(),s.charCodeAt(a)===Ce)W(Ce,Oe);if(k(),s.charCodeAt(a)===ye)a++}else if(y){if(R("catch")){if(a+=5,k(),s.charCodeAt(a)===Ce)W(Ce,Oe);Ir(),k()}if(R("finally"))a+=7,Ir()}return!0}function Ir(){if(k(),!Na())J()}while(a<f){if(k(),a>=f)break;if(Na())continue;let g=a,w=s.charCodeAt(a);if(w===105&&R("import"))d.push(od(g));else if(w===101&&R("export")){a+=6,k();let y=s.charCodeAt(a);if(y===100&&R("default")){a+=7,k();let E=a,S=s.charCodeAt(a);if(S===102&&R("function")){let A=Qt(g,!0,!1,!0);if(A)d.push(A)}else if(S===97&&R("async")&&Dr("async")!==ye)if(a+=5,k(),R("function")){let A=Qt(g,!0,!0,!0);if(A)d.push(A)}else Ia(g,E);else if(S===99&&R("class")){let A=ei(g,!0,!1,!0);d.push(A)}else if(S===97&&R("abstract")){if(a+=8,k(),R("class")){let A=ei(g,!0,!0,!0);d.push(A)}}else Ia(g,E)}else if(y===116&&R("type")){let E=a;if(a+=4,k(),a<f&&s.charCodeAt(a)===te){Se();let S=D(g,a),A=je(g);d.push({kind:"export",name:"",text:S,isExported:!0,isTypeOnly:!0,source:Tt(S),leadingComments:A,start:g,end:a})}else if(a<f&&s.charCodeAt(a)===Le){At();let S=D(g,a);d.push({kind:"export",name:"",text:S,isExported:!0,isTypeOnly:!0,source:Tt(S),start:g,end:a})}else{a=E;let S=go(g,!0);d.push(S)}}else if(y===105&&R("interface")){let E=mo(g,!0);d.push(E)}else if(y===102&&R("function")){let E=Qt(g,!0,!1,!1);if(E)d.push(E)}else if(y===97&&R("async"))if(a+=5,k(),R("function")){let E=Qt(g,!0,!0,!1);if(E)d.push(E)}else J();else if(y===99)if(R("class")){let E=ei(g,!0,!1);d.push(E)}else if(R("const")){let E=a;if(a+=5,k(),R("enum")){a=E+5,k();let S=Si(g,!0,!0);d.push(S)}else{a=E;let S=ui(g,"const",!0);for(let A=0;A<S.length;A++)d.push(S[A])}}else J();else if(y===97&&R("abstract")){if(a+=8,k(),R("class")){let E=ei(g,!0,!0);d.push(E)}}else if(y===108&&R("let")){let E=ui(g,"let",!0);for(let S=0;S<E.length;S++)d.push(E[S])}else if(y===118&&R("var")){let E=ui(g,"var",!0);for(let S=0;S<E.length;S++)d.push(E[S])}else if(y===101&&R("enum")){let E=Si(g,!0,!1);d.push(E)}else if(y===100&&R("declare"))a+=7,k(),Wa(g,!0);else if(y===110&&R("namespace")&&Ue(9)){let E=xi(g,!0,"namespace");d.push(E)}else if(y===109&&R("module")&&Ue(6)){let E=xi(g,!0,"module");d.push(E)}else if(y===te){Se();let E=D(g,a),S=E.includes("export type"),A=je(g);d.push({kind:"export",name:"",text:E,isExported:!0,isTypeOnly:S,source:Tt(E),leadingComments:A,start:g,end:a})}else if(y===Le){At();let E=D(g,a),S=je(g);d.push({kind:"export",name:"",text:E,isExported:!0,isTypeOnly:!1,source:Tt(E),leadingComments:S,start:g,end:a})}else{J();let E=D(g,a);if(E)d.push({kind:"export",name:"",text:E,isExported:!0,start:g,end:a})}}else if(w===100&&R("declare"))a+=7,k(),Wa(g,!1);else if(w===105&&R("interface")){let y=mo(g,!1);h.set(y.name,y)}else if(w===116&&R("type")){let y=go(g,!1);h.set(y.name,y),d.push(y)}else if(w===102&&R("function")){let y=Qt(g,!1,!1,!1);if(y)x(y);else J()}else if(w===97)if(R("async")){let y=a;if(a+=5,k(),R("function")){let E=Qt(g,!1,!0,!1);if(E)x(E);else a=y,J()}else a=y,J()}else if(R("abstract"))if(a+=8,k(),R("class")){let y=ei(g,!1,!1);h.set(y.name,y),d.push(y)}else J();else a++,J();else if(w===99)if(R("class")){let y=ei(g,!1,!1);h.set(y.name,y),d.push(y)}else if(R("const")){let y=a;if(a+=5,k(),R("enum")){a=y+5,k();let E=Si(g,!1,!0);h.set(E.name,E),d.push(E)}else{a=y;let E=ui(g,"const",!1);for(let S=0;S<E.length;S++)h.set(E[S].name,E[S])}}else a++,J();else if(w===101&&R("enum")){let y=Si(g,!1,!1);h.set(y.name,y),d.push(y)}else if(w===108&&R("let")||w===118&&R("var")){let y=R("let")?"let":"var",E=ui(g,y,!1);for(let S=0;S<E.length;S++)h.set(E[S].name,E[S])}else if(w===109&&R("module")&&Ue(6)){let y=xi(g,!1,"module");d.push(y)}else if(w===110&&R("namespace")&&Ue(9)){let y=xi(g,!1,"namespace");d.push(y)}else{let y=s.charCodeAt(a);if(y===ye)a++;else if(y===Pe||y===De){if(Q(y),a<f&&s.charCodeAt(a)===ye)a++}else if(y===Ye){if(ce(),a<f&&s.charCodeAt(a)===ye)a++}else if(y===Fh){if(a++,oe(),k(),a<f&&s.charCodeAt(a)===Wt)a++,oe(),k();if(a<f&&s.charCodeAt(a)===Ce)W(Ce,Oe)}else a++,J()}}if(m.size>0){Fa(d);for(let g of p.values())Fa(g)}if(Il(s,d,h,p),gl(d,h),ul(d,h),!l)ql(s,d,h,o);if(n){let g=new Set(d);for(let w of[...h.values(),...[...p.values()].flat()])if(!g.has(w))d.push(w),g.add(w);return d.sort((w,y)=>(w.start??0)-(y.start??0))}if(h.size>0)jh(d,h,p);return d;function Fa(g){let w=new Map;for(let E of g)if(E.kind==="function")w.set(E.name,(w.get(E.name)||0)+1);let y=new Set;for(let[E,S]of w)if(S>1)y.add(E);if(y.size>0){let E=new Set;for(let S of y)for(let A=g.length-1;A>=0;A--)if(g[A].kind==="function"&&g[A].name===S&&m.has(g[A])){E.add(A);break}if(E.size>0){let S=[...E].sort((A,I)=>I-A);for(let A of S)g.splice(A,1)}}}function Wa(g,w){if(R("function")){let y=Qt(g,w,!1,!1);if(y)d.push(y)}else if(R("async")){if(a+=5,k(),R("function")){let y=Qt(g,w,!0,!1);if(y)d.push(y)}}else if(R("class")){let y=ei(g,w,!1);d.push(y)}else if(R("abstract")){if(a+=8,k(),R("class")){let y=ei(g,w,!0);d.push(y)}}else if(R("interface")){let y=mo(g,w);d.push(y)}else if(R("type")){let y=go(g,w);d.push(y)}else if(R("enum")){let y=Si(g,w,!1);d.push(y)}else if(R("const")){let y=a;if(a+=5,k(),R("enum")){a=y+5,k();let E=Si(g,w,!0);d.push(E)}else{a=y;let E=ui(g,"const",w);for(let S=0;S<E.length;S++)if(w||!u)d.push(E[S]);else h.set(E[S].name,E[S])}}else if(R("let")||R("var")){let y=R("let")?"let":"var",E=ui(g,y,w);for(let S=0;S<E.length;S++)if(w||!u)d.push(E[S]);else h.set(E[S].name,E[S])}else if(R("module")){let y=xi(g,w,"module");d.push(y)}else if(R("namespace")){let y=xi(g,w,"namespace");d.push(y)}else if(R("global")){a+=6,k();let y=`declare global ${a<f&&s.charCodeAt(a)===te?Co():"{}"}`,E=je(g);d.push({kind:"module",name:"global",text:y,isExported:!1,moduleForm:"global",leadingComments:E,start:g,end:a})}else J()}}function Xl(e,t){let i=0,r=e.length;while(i<r){let n=e.charCodeAt(i);if(n>=65&&n<=90||n>=97&&n<=122||n===95||n===36||n>127){let o=i;i++;while(i<r){let s=e.charCodeAt(i);if(s>=65&&s<=90||s>=97&&s<=122||s>=48&&s<=57||s===95||s===36||s>127)i++;else break}t.add(e.substring(o,i))}else i++}}function Zl(e,t){let i=0;while(i<e.length){let r=e.charCodeAt(i);if(r===Pe||r===De||r===Ye){let u=r;i++;while(i<e.length)if(e.charCodeAt(i)===Ct)i+=2;else if(e.charCodeAt(i++)===u)break;continue}if(r===pe&&e.charCodeAt(i+1)===pe){i+=2;while(i<e.length&&e.charCodeAt(i)!==Ie&&e.charCodeAt(i)!==_e)i++;continue}if(r===pe&&e.charCodeAt(i+1)===Le){let u=e.indexOf("*/",i+2);i=u===-1?e.length:u+2;continue}if(!ft(r)){i++;continue}let n=i++;while(i<e.length&&ze(e.charCodeAt(i)))i++;let o=n-1,s=i;while(o>=0&&Xe(e.charCodeAt(o)))o--;while(s<e.length&&Xe(e.charCodeAt(s)))s++;let c=o>=0?e.charCodeAt(o):0,l=s<e.length?e.charCodeAt(s):0,f=n>=3&&e.slice(n-3,n)==="...";if(l===Et||c===Wt&&!f)continue;if(l===Ce&&(c===te||c===Pt))continue;t.add(e.slice(n,i))}}function jh(e,t,i){let r=new Set,n=new Set;for(let f of e)n.add(f.name);let o=new Set,s=new Set,c=new Set,l=[];for(let f=0;f<e.length;f++){let u=e[f];if(u.kind!=="import"){if(l.push(u.text),Xl(u.text,o),_o(u,s),typeof u.value==="string")Zl(u.value,c)}}for(;;){let f=[];for(let[h,p]of t){if(r.has(h))continue;if((p.kind==="function"||p.kind==="variable"?s:o).has(h)||p.kind!=="function"&&c.has(h)){if(!n.has(h)){let m=p.kind==="function"?i.get(h):void 0;if(m)for(let a of m)f.push(a);else f.push(p);n.add(h)}r.add(h)}}if(f.length===0)break;f.sort((h,p)=>(h.start??1/0)-(p.start??1/0));let u=[],d=0;for(let h=0;h<e.length;h++){let p=e[h].start??1/0;while(d<f.length&&(f[d].start??1/0)<=p)u.push(f[d++]);u.push(e[h])}while(d<f.length)u.push(f[d++]);e.length=0;for(let h=0;h<u.length;h++)e.push(u[h]);for(let h of f)if(h.kind!=="import"){if(l.push(h.text),Xl(h.text,o),_o(h,s),typeof h.value==="string")Zl(h.value,c)}}}var Qe=32,et=9,Ie=10,_e=13,pe=47,Le=42,Pe=39,De=34,Ye=96,Ct=92,te=123,le=125,Ce=40,Oe=41,Ge=91,He=93,Me=60,Re=62,ye=59,Et=58,Be=61,Pt=44,Wt=46,ln=63,Yl=35,Fh=64,Wh=36,ss;var un=me(()=>{or();ut();Wo();Bo();Hr();sr();yl();Uo();fr();Fl();sn();Jl();ss=["public","protected","private","readonly","override"]});function ec(e,t,i=!0,r=!1,n){if(Ya(t))e=Qa(e);else if(tl(t))e=il(e);let o=Zi(e),s=`${t}:${i?1:0}:${r?1:0}:${JSON.stringify([...n??[]].sort())}`,c=Oi.get(s);if(c&&c.contentHash===o)return c.lastAccess=++Ql,c.declarations;let l=r?ur(e,t,i):fn(e,t,i,n);if(Oi.set(s,{declarations:l,contentHash:o,lastAccess:++Ql}),Oi.size>Gh){let f=Math.max(1,Math.ceil(Oi.size*0.1)),u=[];for(let[d,h]of Oi)u.push([d,h.lastAccess]);u.sort((d,h)=>d[1]-h[1]);for(let d=0;d<f&&d<u.length;d++)Oi.delete(u[d][0])}return l}var Gh=100,Ql=0,Oi;var tc=me(()=>{Fo();rl();$o();un();Oi=new Map});function dn(e,t,i=!0,r=!1,n){return ec(e,t,i,r,n)}var fs=me(()=>{tc()});function hn(e){let t=new Set,i=[];for(let o of e)if(o.kind==="import")for(let s of yi(o.text))t.add(s);else if(o.kind!=="unknown"){if(i.push(o.text),o.kind==="variable"){if(o.typeAnnotation)i.push(o.typeAnnotation);else if(o.value)i.push(ki(o,!1))}}let r=i.join(`
123
+ `),n=new Set;for(let o=0;o<r.length;){if(!ft(r.charCodeAt(o))){o++;continue}let s=o++;while(o<r.length&&ze(r.charCodeAt(o)))o++;let c=r.slice(s,o);if(t.has(c))n.add(c)}return{usedItems:n,referenceText:r}}var us=me(()=>{or();sn();Ci()});function _h(e){if(!e.includes("declare")||!e.includes("module"))return[];return kt(e).filter((t)=>t.category==="augmentation").map((t)=>t.specifier)}function Vh(e,t){let i=new Set([e]);for(let r of i)for(let n of t(r))i.add(n);return i}async function ic(e,t,i=!1,r){let n=new Map,o=new Map;for(let u of e){let d=r?.get(u)??await yt(u);n.set(u,d);let h=_h(d);if(h.length)o.set(u,h)}let s=new Map;if(o.size===0)return s;let c=new Map,l=(u,d)=>{let h=t(u,d);if(h.resolved)return h.resolved;if(!h.isRelative&&!h.isAlias)return`external:${u}`;return};for(let[u,d]of n){let h=dn(d,u,!1,i),p=hn(h),m={edges:[],declarations:new Set,augmentations:new Set},a=(C,b,v)=>{let T=l(C.specifier,u);if(!T)return;if(n.has(T))m.edges.push({specifier:C.specifier,target:T,import:b});if(v)m.declarations.add(T)};for(let C of h){if(C.kind!=="import")continue;let b=C.isSideEffect||yi(C.text).some((v)=>p.usedItems.has(v));for(let v of kt(C.text))a(v,!0,!!b)}for(let C of kt(p.referenceText))a(C,!1,!0);for(let C of o.get(u)??[]){let b=l(C,u);if(b)m.augmentations.add(b),m.declarations.add(b)}c.set(u,m)}let f=!0;while(f){f=!1;for(let[u,d]of c){let h=Vh(u,(p)=>c.get(p)?.declarations??[]);for(let[p,m]of c){if(h.has(p)||!m.augmentations.size||![...m.augmentations].some((v)=>h.has(v)))continue;let a=[u],C=new Map,b=new Set([u]);for(let v of a){if(v===p)break;for(let T of c.get(v).edges){if(b.has(T.target))continue;b.add(T.target),C.set(T.target,{from:v,edge:T}),a.push(T.target)}}if(!C.has(p))continue;for(let v=p;v!==u;){let{from:T,edge:B}=C.get(v),x=c.get(T);if(B.import){let D=s.get(T);if(!D)D=new Set,s.set(T,D);D.add(B.specifier)}if(!x.declarations.has(v))x.declarations.add(v),f=!0;v=T}}}}return s}var rc=me(()=>{Qi();ut();Ci();fs();us()});function Ri(e){return nc[e]>=nc[pn]}function zh(){if(!Kh)return"";return`[${new Date().toISOString().slice(11,23)}] `}function Hh(e,t){let i=zh();if(e||i)return[`${i}${e}`,...t];return t}function Pi(e,t,i){let r=Hh(t,i);if(oc){oc(e,...r);return}switch(e){case"debug":console.debug(...r);break;case"info":console.log(...r);break;case"warn":console.warn(...r);break;case"error":console.error(...r);break}}function sc(e){return{debug:(...t)=>{if(Ri("debug"))Pi("debug",e,t)},info:(...t)=>{if(Ri("info"))Pi("info",e,t)},warn:(...t)=>{if(Ri("warn"))Pi("warn",e,t)},error:(...t)=>{if(Ri("error"))Pi("error",e,t)},setLevel:(t)=>{pn=t},getLevel:()=>pn,child:(t)=>{let i=e?`${e}:${t}`:`[${t}]`;return sc(i)},time:(t)=>{let i=performance.now();return()=>{let r=performance.now()-i;if(Ri("debug"))Pi("debug",e,[`${t}: ${r.toFixed(2)}ms`])}},progress:(t)=>{if(Ri("info"))if(typeof process<"u"&&process.stdout?.isTTY)process.stdout.write(`\r${e} ${t}`);else Pi("info",e,[t])}}}function ds(e){pn=e}var nc,pn="info",Uh="[dtsx]",Kh=!1,oc=null,ne;var mn=me(()=>{nc={debug:0,info:1,warn:2,error:3,silent:4};ne=sc(Uh)});function ac(e){let t="",i=0,r=0;while(i<e.length){let n=e.charCodeAt(i);if(r){if(t+=e[i],n===92&&i+1<e.length){t+=e[i+1],i+=2;continue}if(n===r)r=0;i++;continue}if(n===34){r=n,t+=e[i++];continue}if(n===47&&e.charCodeAt(i+1)===47){i+=2;while(i<e.length&&e.charCodeAt(i)!==10&&e.charCodeAt(i)!==13)i++;continue}if(n===47&&e.charCodeAt(i+1)===42){i+=2;while(i+1<e.length&&!(e.charCodeAt(i)===42&&e.charCodeAt(i+1)===47)){if(e.charCodeAt(i)===10)t+=`
124
+ `;i++}i=Math.min(i+2,e.length);continue}if(n===44){let o=i+1;while(o<e.length){while(o<e.length&&e.charCodeAt(o)<=32)o++;if(e.charCodeAt(o)===47&&e.charCodeAt(o+1)===47){o+=2;while(o<e.length&&e.charCodeAt(o)!==10&&e.charCodeAt(o)!==13)o++;continue}if(e.charCodeAt(o)===47&&e.charCodeAt(o+1)===42){o+=2;while(o+1<e.length&&!(e.charCodeAt(o)===42&&e.charCodeAt(o+1)===47))o++;o=Math.min(o+2,e.length);continue}break}let s=e.charCodeAt(o);if(s===93||s===125){i++;continue}}t+=e[i++]}return t}var lc=()=>{};import{readFileSync as qh,statSync as Jh}from"fs";import{readFile as Yh}from"fs/promises";import{createRequire as Xh}from"module";import{dirname as dr,isAbsolute as Zh,join as hs,resolve as ps}from"path";function Mi(e){let t=[e];if(!e.endsWith(".json"))t.push(`${e}.json`);t.push(hs(e,"tsconfig.json"));for(let i of t)try{if(Jh(i).isFile())return i}catch{}return null}function Qh(e,t){if(Zh(e)||e.startsWith("."))return Mi(ps(dr(t),e));let i=Xh(t),r=e.startsWith("@")?/^@[^/]+\/[^/]+/.exec(e)?.[0]:e.split("/")[0];if(r)for(let n of i.resolve.paths(r)??[]){let o=Mi(hs(n,r,"package.json"));if(!o)continue;let s=JSON.parse(qh(o,"utf8"));if(e===r){if(s.tsconfig!==void 0){if(typeof s.tsconfig!=="string")throw Error(`Invalid tsconfig field in ${o}`);let l=Mi(ps(dr(o),s.tsconfig));if(!l)throw Error(`Cannot resolve tsconfig ${JSON.stringify(s.tsconfig)} from ${o}`);return l}let c=Mi(hs(dr(o),"tsconfig.json"));if(c)return c}break}for(let n of[`${e}/tsconfig.json`,e])try{let o=i.resolve(n),s=o.endsWith(".json")?Mi(o):null;if(s)return s}catch{}return null}async function hr(e,t={},i=new Set){let r=Mi(e);if(!r)return;if(i.has(r)){if(t.allowCircular)return;throw Error(`Circular tsconfig extends: ${r}`)}let n=new Set(i).add(r),o=JSON.parse(ac(await Yh(r,"utf8"))),s=typeof o.extends==="string"?[o.extends]:o.extends??[];if(!Array.isArray(s)||s.some((f)=>typeof f!=="string"))throw Error(`Invalid tsconfig extends in ${r}`);let c={};for(let f of s){let u=Qh(f,r);if(!u)throw Error(`Cannot resolve tsconfig extends ${JSON.stringify(f)} from ${r}`);c={...c,...await hr(u,t,n)}}let l=o.compilerOptions??{};if(l.isolatedDeclarations!==void 0)c.isolatedDeclarations=l.isolatedDeclarations;if(l.baseUrl!==void 0){if(typeof l.baseUrl!=="string")throw Error(`Invalid baseUrl in ${r}`);c.baseUrl=ps(dr(r),l.baseUrl)}if(l.paths!==void 0){if(!l.paths||typeof l.paths!=="object"||Array.isArray(l.paths))throw Error(`Invalid paths in ${r}`);for(let[f,u]of Object.entries(l.paths))if(f.split("*").length>2||!Array.isArray(u)||u.length===0||u.some((d)=>typeof d!=="string"||d.split("*").length>2))throw Error(`Invalid path mapping ${JSON.stringify(f)} in ${r}`);c.paths=l.paths,c.pathsBasePath=dr(r)}return c}var ms=me(()=>{lc()});import{existsSync as ws,readFileSync as gs,realpathSync as pr,statSync as ep}from"fs";import{builtinModules as tp}from"module";import{dirname as Cs,extname as ip,isAbsolute as vs,join as uc,relative as dc,resolve as Di}from"path";function gn(e){try{return ep(e).isFile()}catch{return!1}}function Ii(e,t){let i=e.replace(/[?#].*$/,"");if(!(i.startsWith("./")||i.startsWith("../")||i==="."||i==="..")&&!vs(i))return{resolved:null,isRelative:!1};let r=Cs(t),n=Di(r,i);if(gn(n))return{resolved:n,isRelative:!0};let o=ip(n),s=rp[o];if(s){let c=n.slice(0,-o.length);for(let l of s){let f=c+l;if(gn(f))return{resolved:f,isRelative:!0}}}for(let c of cc){let l=n+c;if(gn(l))return{resolved:l,isRelative:!0}}if(ws(n))for(let c of cc){let l=uc(n,`index${c}`);if(gn(l))return{resolved:l,isRelative:!0}}return{resolved:null,isRelative:!0}}function hc(e,t){let i=e.indexOf("*");return i===-1?t===e:t.startsWith(e.slice(0,i))&&t.endsWith(e.slice(i+1))&&t.length>=e.length-1}function pc(e,t){if(Object.hasOwn(e,t))return e[t]!==null;let i=Object.keys(e).filter((r)=>r.includes("*")&&hc(r,t)).sort((r,n)=>n.indexOf("*")-r.indexOf("*")||n.length-r.length)[0];return i!==void 0&&e[i]!==null}function fc(e,t){if(!e.name||t!==e.name&&!t.startsWith(`${e.name}/`))return!1;if(e.exports===void 0)return!0;let i=t===e.name?".":`.${t.slice(e.name.length)}`;if(typeof e.exports==="string"||Array.isArray(e.exports))return i===".";if(!e.exports||typeof e.exports!=="object")return!1;let r=e.exports;if(!Object.keys(r).some((n)=>n.startsWith(".")))return i===".";return pc(r,i)}function ys(e,t){let i=dc(e,t);return i!==".."&&!i.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!vs(i)}async function yn(e){let t=await hr(Di(e.cwd,e.tsconfigPath||"tsconfig.json")),i=Object.entries(t?.paths??{});if(i.length===0){let f=(u,d)=>Ii(u,d);return f.cacheKey=(u)=>JSON.stringify(u.map((d)=>({file:d,references:vi(gs(d,"utf8"),{includeImports:!0}).map((h)=>({specifier:h.specifier,resolution:f(h.specifier,d)}))}))),f}let r=t?.baseUrl??t?.pathsBasePath??e.cwd,n=Di(e.cwd,e.root),o=new Map,s=new Set([...tp,"bun"]),c=(f)=>{let u=Cs(f),d=[];while(!0){if(o.has(u)){let m=o.get(u);for(let a of d)o.set(a,m);return m}d.push(u);let h=uc(u,"package.json");if(ws(h)){let m={...JSON.parse(gs(h,"utf8")),directory:pr(u)};for(let a of d)o.set(a,m);return m}let p=Cs(u);if(p===u)return;u=p}},l=(f,u)=>{if(f.startsWith(".")||vs(f))return Ii(f,u);if(f.startsWith("node:")||f.startsWith("bun:")||s.has(f))return{resolved:null,isRelative:!1};let d=c(u),h=f.startsWith("@")?/^@[^/]+\/[^/]+/.exec(f)?.[0]:f.split("/")[0];if(d&&(fc(d,f)||pc(d.imports??{},f)||h&&[d.dependencies,d.devDependencies,d.peerDependencies,d.optionalDependencies].some((v)=>Object.hasOwn(v??{},h))))return{resolved:null,isRelative:!1};let p=i.filter(([v])=>hc(v,f)).sort(([v],[T])=>{if(!v.includes("*"))return-1;if(!T.includes("*"))return 1;return T.indexOf("*")-v.indexOf("*")})[0];if(!p)return{resolved:null,isRelative:!1};let[m,a]=p,C=m.indexOf("*"),b=C===-1?"":f.slice(C,f.length-(m.length-C-1));for(let v of a){let T=Di(r,v.replace("*",b)),B=c(T);if(B&&fc(B,f)&&!B.private&&B.directory!==d?.directory)return{resolved:null,isRelative:!1};let x=Ii(T,u);if(!x.resolved)continue;let D=pr(x.resolved),U=e.outputStructure==="flat"||ws(n)&&ys(pr(n),D);if(!d||!ys(d.directory,D)||!U||c(D)?.directory!==d.directory||/\.d\.(?:ts|mts|cts)$/.test(D))throw Error(`Local alias ${JSON.stringify(f)} from ${u} resolves outside its emitted package source: ${D}`);return ne.debug(`Resolved local declaration alias ${f} from ${u} to ${D}`),{resolved:e.outputStructure==="flat"?x.resolved:Di(n,dc(pr(n),D)),isRelative:!0,isAlias:!0,suffix:T.match(/[?#].*$/)?.[0]??""}}throw Error(`Cannot resolve local alias ${JSON.stringify(f)} from ${u} using ${e.tsconfigPath||"tsconfig.json"} (${JSON.stringify(m)})`)};return l.isPackageLocal=(f,u)=>{let d=c(f);return!!d&&c(u)?.directory===d.directory&&ys(d.directory,pr(u))},l.cacheKey=(f)=>{let u=f.map((h)=>({file:h,references:vi(gs(h,"utf8"),{includeImports:!0}).map((p)=>({specifier:p.specifier,resolution:l(p.specifier,h)}))})),d=[...new Set(o.values())].filter((h)=>h!==void 0).sort((h,p)=>h.directory.localeCompare(p.directory));return JSON.stringify({root:n,compilerOptions:t,packages:d,edges:u})},l}function vi(e,t={}){let i=kt(e);return(t.includeImports?["export","static-import","import-type","augmentation"]:["export"]).flatMap((r)=>i.filter((n)=>n.category===r).map(({specifier:n,kind:o,isTypeOnly:s})=>({specifier:n,kind:o,isTypeOnly:s})))}function mc(e,t){let i=[];for(let n of kt(e)){let o=t(n.specifier);if(o!==n.specifier)i.push({start:n.start,end:n.end,value:ti(o,e[n.start])})}let r=e;for(let n of i.reverse())r=r.slice(0,n.start)+n.value+r.slice(n.end);return r}async function mr(e,t={}){let i=new Set,r=new Map,n=[],o=new Map,s=[];for(let c of e){let l=Di(c);if(!i.has(l))i.add(l),s.push(l)}while(s.length>0){let c=s.shift(),l;try{l=await yt(c)}catch{continue}o.set(c,l);let f=vi(l,t);r.set(c,f);for(let u of f){let d=(t.resolveSpecifier??Ii)(u.specifier,c);if(!d.isRelative)continue;if(d.resolved){if(!i.has(d.resolved))i.add(d.resolved),s.push(d.resolved)}else n.push({from:c,specifier:u.specifier,isTypeOnly:u.isTypeOnly})}}return{reachable:i,reExports:r,unresolved:n,sources:o}}var cc,rp;var wn=me(()=>{Qi();mn();ut();ms();cc=[".ts",".tsx",".mts",".cts",".vue",".stx",".js",".jsx",".mjs",".cjs",".d.ts",".d.mts",".d.cts"],rp={".js":[".ts",".tsx",".d.ts"],".jsx":[".tsx",".ts",".d.ts"],".mjs":[".mts",".d.mts"],".cjs":[".cts",".d.cts"]}});import{relative as bi}from"path";function bs(e){let t=se(e),i=(c)=>t[c]?e.slice(t[c].start,t[c].end):"",r=i(0)==="export"?1:0;if(i(r++)!=="declare")return;let n;if(i(r)==="module"&&t[r+1]?.kind==="quoted"){if(n=mt(i(r+1)),n===void 0)return;r+=2}else if(i(r++)!=="global")return;if(i(r)!=="{")return;let o=t[r].end,s=1;for(r++;r<t.length;r++)if(i(r)==="{")s++;else if(i(r)==="}"&&--s===0)return{specifier:n,body:e.slice(o,t[r].start),start:o,end:t[r].start};return}function op(e){let t=[],i=[],r=0,n=0,o=[],s=!1,c=0,l=e.length,f=(u)=>{let d=e.slice(r,u).trim();if(r=u,!d)return;if(sp(d)){i.push(d);return}t.push({text:d,comments:i}),i=[]};while(c<l){let u=e[c];if(s){if(u==="\\"){c+=2;continue}if(u==="`"){s=!1,c++;continue}if(u==="$"&&e[c+1]==="{"){o.push(n),n++,s=!1,c+=2;continue}c++;continue}if(u==="/"&&e[c+1]==="*"){let d=e.indexOf("*/",c+2);c=d===-1?l:d+2;continue}if(u==="/"&&e[c+1]==="/"){let d=e.indexOf(`
125
+ `,c);c=d===-1?l:d;continue}if(u==="'"||u==='"'){c++;while(c<l&&e[c]!==u&&e[c]!==`
126
+ `){if(e[c]==="\\")c++;c++}c++;continue}if(u==="`"){s=!0,c++;continue}if(u==="("||u==="["||u==="{"){n++,c++;continue}if(u===")"||u==="]"||u==="}"){if(n--,o.length>0&&u==="}"&&n===o[o.length-1])o.pop(),s=!0;c++;continue}if(n===0&&u===";"){f(c+1),c++;continue}if(n===0&&u===`
127
+ `){let d=e[c+1];if(d!==void 0&&/[\w$@/]/.test(d))f(c+1);c++;continue}c++}return f(l),t}function sp(e){let t=0;while(t<e.length){while(t<e.length&&/\s/.test(e[t]))t++;if(t>=e.length)return!0;if(e.startsWith("//",t)){let i=e.indexOf(`
128
+ `,t);t=i===-1?e.length:i;continue}if(e.startsWith("/*",t)){let i=e.indexOf("*/",t+2);if(i===-1)return!0;t=i+2;continue}return!1}return!0}function gc(e){let t=[];for(let i of e.split(",")){let r=i.replace(/\/\*[\s\S]*?\*\//g,"").trim().replace(/^type\s+/,"");if(!r)continue;let n=r.match(/^([\w$]+)(?:\s+as\s+([\w$]+))?$/);if(!n)continue;t.push({local:n[1],exported:n[2]??n[1]})}return t}function lp(e,t){let i=e.replace(/^export\s+/,""),r=/^default\s+/.test(i);if(i=i.replace(/^default\s+/,""),r)i=i.replace(/^((?:declare\s+)?(?:abstract\s+)?(?:class|function\s*\*?|async\s+function\s*\*?))\s*(?=[(<{])/,(n,o)=>`${o.trimEnd()} ${t}`);if(/^(?:interface|type)\b/.test(i)||/^declare\b/.test(i))return i;return`declare ${i}`}function Cn(e,t,i=!1){let r={file:e,declarations:[],declared:new Set,imports:new Map,localExports:new Map,namedReExports:[],starReExports:[],namespaceReExports:[],verbatim:[],augmentations:[],directives:[]},n=i?ls(t,e).map((o)=>({text:o.text,comments:[...o.leadingComments??[]]})):op(t);for(let o of n){o.comments=o.comments.filter((d)=>{if(/^\/\/\/\s*</.test(d))return r.directives.push(...d.split(`
129
+ `).map((h)=>h.trim()).filter((h)=>h.startsWith("///"))),!1;return!0});let s=o.text.replace(/;\s*$/,"").trim(),c=s.startsWith("import")?wi(s):null;if(c&&!c.isImportEquals){let d=c.source;if(c.defaultName)r.imports.set(c.defaultName,{specifier:d,imported:"default"});if(c.namespaceName)r.imports.set(c.namespaceName,{specifier:d,imported:"*"});for(let h of c.namedItems)r.imports.set(h.name,{specifier:d,imported:/^['"]/.test(h.originalName)?mt(h.originalName):h.originalName});continue}if(/^import\s+['"]/.test(s)){r.verbatim.push(o);continue}let l=s.match(/^export\s+(?:type\s+)?\*\s+as\s+([\w$]+)\s+from\s+(['"])([^'"]+)\2/);if(l){r.namespaceReExports.push({specifier:l[3],exported:l[1]});continue}if(l=s.match(/^export\s+(?:type\s+)?\*\s+from\s+(['"])([^'"]+)\1/),l){r.starReExports.push(l[2]);continue}if(l=s.match(/^export\s+(?:type\s+)?\{([\s\S]*)\}\s+from\s+(['"])([^'"]+)\2/),l){for(let d of gc(l[1]))r.namedReExports.push({specifier:l[3],imported:d.local,exported:d.exported});continue}if(l=s.match(/^export\s+(?:type\s+)?\{([\s\S]*)\}$/),l){for(let d of gc(l[1]))r.localExports.set(d.exported,d.local);continue}if(l=s.match(/^export\s+default\s+([\w$]+)$/),l&&np.test(l[1])){r.localExports.set("default",l[1]);continue}let f=bs(s);if(f?.specifier!==void 0&&hi(t)){r.augmentations.push({statement:o,specifier:f.specifier,body:f.body});continue}if(/^export\s+as\s+namespace\b/.test(s)||f){r.verbatim.push(o);continue}let u=s.match(ap);if(u){let d=!!u[1],h=u[4]??(d?"_default":null);if(h){if(r.declared.add(h),/^export\s/.test(s))r.localExports.set(d?"default":h,h);r.declarations.push({statement:o,name:h,emit:lp(o.text,h)});continue}}r.declarations.push({statement:o,name:null,emit:o.text})}return r}function gr(e,t){if(t.size===0)return e;let i=se(e),r=new Map(i.filter((p)=>p.kind==="literal").map((p)=>[p.start,p.end])),n=(p)=>i[p]?e.slice(i[p].start,i[p].end):"",o=new Map,s=[];for(let p=0;p<i.length;p++){let m=n(p);if(["(","[","{","<"].includes(m))s.push(p);else if([")","]","}",">"].includes(m)&&!(m===">"&&n(p-1)==="=")){let a=s.at(-1);if(a!==void 0&&["()","[]","{}","<>"].includes(n(a)+m))s.pop(),o.set(a,p)}}let c=(p)=>{for(let m=p;m<i.length;m++){if([";",",",")","]","}"].includes(n(m))||n(m)===">"&&n(m-1)!=="=")return m;let a=o.get(m);if(a!==void 0)m=a}return i.length},l=new Set;for(let p=0;p<i.length;p++){let m=o.get(p);if(n(p)!=="<"||m===void 0)continue;let a=["class","interface","type"].includes(n(p-2));if(!a&&n(m+1)!=="(")continue;let C=new Set;for(let v=p+1;v<m;v++){if(v===p+1||n(v-1)===","){while(["const","in","out"].includes(n(v)))v++;if(i[v]?.kind==="word")C.add(n(v))}let T=o.get(v);if(T!==void 0)v=T}let b=c(m+1);if(a&&n(p-2)!=="type")for(let v=m+1;v<i.length;v++){if(n(v)==="{"){b=o.get(v)??b;break}let T=o.get(v);if(T!==void 0)v=T}for(let v=p+1;v<b;v++){let T=n(p-2)==="class"&&v>m&&n(v-1)==="extends";if(C.has(n(v))&&n(v-1)!=="typeof"&&!T)l.add(i[v].start)}}for(let p=0;p<i.length;p++){if(!["namespace","module"].includes(n(p))||i[p+1]?.kind!=="word"||n(p+2)!=="{")continue;let m=o.get(p+2);if(m===void 0)continue;let a=ls(e.slice(i[p+2].end,i[m].start),"bundle-namespace.ts"),C=new Set(a.filter((v)=>["class","interface","type","enum","module","namespace"].includes(v.kind)).map((v)=>v.name)),b=new Set(a.filter((v)=>["class","variable","function","enum","module","namespace"].includes(v.kind)).map((v)=>v.name));for(let v=p+3;v<m;v++)if((n(v-1)==="typeof"?b:C).has(n(v)))l.add(i[v].start)}let f="",u=0,d=e.length,h=`
130
+ `;while(u<d){let p=r.get(u);if(p!==void 0){f+=e.slice(u,p),u=p,h="`";continue}let m=e[u];if(m==="/"&&e[u+1]==="*"){let a=e.indexOf("*/",u+2),C=a===-1?d:a+2;f+=e.slice(u,C),u=C;continue}if(m==="/"&&e[u+1]==="/"){let a=e.indexOf(`
131
+ `,u),C=a===-1?d:a;f+=e.slice(u,C),u=C;continue}if(m==="'"||m==='"'){let a=u+1;while(a<d&&e[a]!==m&&e[a]!==`
132
+ `){if(e[a]==="\\")a++;a++}f+=e.slice(u,a+1),u=a+1,h=m;continue}if(/[A-Z_$]/i.test(m)){let a=u+1;while(a<d&&/[\w$]/.test(e[a]))a++;let C=e.slice(u,a),b=t.get(C);if(b!==void 0&&h!=="."&&!l.has(u)){let v=a;while(v<d&&(e[v]===" "||e[v]==="\t"))v++;let T=(e[v]===":"||e[v]==="?"&&e[v+1]===":")&&/[{;,(\n]/.test(h);f+=T?C:b}else f+=C;h="a",u=a;continue}if(f+=m,m===`
133
+ `||!/\s/.test(m))h=m;u++}return f}function yc(e,t,i,r){let n=[],o=new Map,s=[e,...t.filter((K)=>K!==e)];for(let K of s){let ee=i.get(K);if(ee===void 0){n.push(`No declarations were generated for ${bi(r.cwd,K)}; it is left out of the bundle`);continue}o.set(K,Cn(K,ee))}let c=(K,ee)=>{if(!K.startsWith(".")&&!K.startsWith("/"))return null;let ie=Ii(K,ee).resolved;return ie&&o.has(ie)?ie:null},l=(K)=>K.startsWith(".")||K.startsWith("/"),f=new Set,u=(K)=>{let ee=K;for(let ie=1;f.has(ee);ie++)ee=`${K}_${ie}`;return f.add(ee),ee},d=new Map;for(let[K,ee]of o){let ie=new Map;for(let ue of ee.declared)ie.set(ue,u(ue));d.set(K,ie)}let h=new Map,p=(K,ee,ie)=>{let ue=`${K}\x00${ee}`,ae=h.get(ue);if(!ae)ae=u(ie),h.set(ue,ae);return ae},m=new Map,a=new Map,C=new Set,b=new Map,v=!0,T=(K,ee,ie)=>{let ue=c(ee,K.file);if(ue){if(ie==="*")return{kind:"namespace",file:ue};let ae=x(ue).get(ie);if(!ae&&!v)n.push(`${bi(r.cwd,K.file)}: '${ie}' is not exported by '${ee}'`);return ae??null}if(l(ee))return n.push(`${bi(r.cwd,K.file)}: '${ee}' is not part of the bundle`),null;return ie==="*"?{kind:"external-namespace",source:ee}:{kind:"external",source:ee,imported:ie}},B=(K,ee)=>{if(K.declared.has(ee))return{kind:"local",name:d.get(K.file).get(ee)};let ie=K.imports.get(ee);if(ie)return T(K,ie.specifier,ie.imported);return n.push(`${bi(r.cwd,K.file)}: cannot resolve exported name '${ee}'`),null};function x(K){let ee=m.get(K);if(ee)return ee;let ie=new Map,ue=o.get(K);if(!ue||C.has(K))return ie;C.add(K);let ae=new Set;for(let[fe,$e]of ue.localExports){let ke=B(ue,$e);if(ke)ie.set(fe,ke)}for(let fe of ue.namedReExports){let $e=T(ue,fe.specifier,fe.imported);if($e)ie.set(fe.exported,$e)}for(let fe of ue.namespaceReExports){let $e=T(ue,fe.specifier,"*");if($e)ie.set(fe.exported,$e)}for(let fe of ue.starReExports){let $e=c(fe,K);if($e){for(let[ke,qe]of x($e))if(ke!=="default"&&!ie.has(ke))ie.set(ke,qe);for(let ke of a.get($e)??[])ae.add(ke)}else if(l(fe))n.push(`${bi(r.cwd,K)}: '${fe}' is not part of the bundle`);else ae.add(fe)}for(let[fe,$e]of b.get(K)??[])ie.set(fe,$e);return C.delete(K),m.set(K,ie),a.set(K,ae),ie}for(let[K,ee]of o)for(let ie of ee.augmentations){let ue=c(ie.specifier,K);if(!ue)continue;for(let ae of Cn(K,ie.body,!0).declared){if(x(ue).has(ae))continue;let fe=b.get(ue);if(!fe)fe=new Map,b.set(ue,fe);fe.set(ae,{kind:"local",name:u(ae)}),m.clear()}}v=!1,m.clear(),a.clear();let D=new Map,U=[],j=(K,ee)=>{switch(K.kind){case"local":return K.name;case"external":return p(K.source,K.imported,K.imported==="default"?ee:K.imported);case"external-namespace":return p(K.source,"*",ee);case"namespace":return k(K.file,ee)}};function k(K,ee){let ie=D.get(K);if(ie)return ie;let ue=u(ee);D.set(K,ue);let ae=[];for(let[fe,$e]of x(K)){if(fe==="default")continue;let ke=j($e,fe);ae.push(ke===fe?fe:`${ke} as ${fe}`)}if(a.get(K)?.size)n.push(`${bi(r.cwd,K)}: 'export * from' an external module cannot be expressed inside namespace '${ue}'`);return U.push(`declare namespace ${ue} {
134
+ export { ${ae.join(", ")} };
135
+ }`),ue}let z=[],Q=[],ce=new Set;for(let[K,ee]of o){for(let ae of ee.directives)ce.add(ae);let ie=new Map;for(let[ae,fe]of d.get(K))if(ae!==fe)ie.set(ae,fe);for(let[ae,fe]of ee.imports){if(ee.declared.has(ae))continue;let $e=T(ee,fe.specifier,fe.imported);if(!$e)continue;let ke=j($e,ae);if(ke!==ae)ie.set(ae,ke)}let ue=[];for(let ae of ee.declarations){if(r.keepComments)ue.push(...ae.statement.comments);let fe=gr(ae.emit,ie);if(!/[;}]$/.test(fe))fe+=";";ue.push(fe)}for(let ae of ee.verbatim){if(r.keepComments)Q.push(...ae.comments);let fe=bs(ae.text);if(fe){let $e=new Map(ie);for(let ke of Cn(K,fe.body,!0).declared)$e.delete(ke);Q.push(ae.text.slice(0,fe.start)+gr(fe.body,$e)+ae.text.slice(fe.end))}else{let $e=se(ae.text),ke=$e[1]?.kind==="quoted"?mt(ae.text.slice($e[1].start,$e[1].end)):void 0;if(ke===void 0||!c(ke,K))Q.push(gr(ae.text,ie))}}for(let ae of ee.augmentations){let fe=c(ae.specifier,K),$e=Cn(K,ae.body,!0),ke=new Map(ie);if(!fe){for(let fi of $e.declared)ke.delete(fi);let qe=bs(ae.statement.text);if(r.keepComments)Q.push(...ae.statement.comments);Q.push(ae.statement.text.slice(0,qe.start)+gr(qe.body,ke)+ae.statement.text.slice(qe.end));continue}for(let[qe,fi]of x(fe))ke.set(qe,j(fi,qe));if(r.keepComments)ue.push(...ae.statement.comments);for(let qe of $e.declarations){if(!qe.name||!x(fe).has(qe.name))throw Error(`Cannot link augmentation '${ae.specifier}' member '${qe.name??qe.emit}'`);if(r.keepComments)ue.push(...qe.statement.comments);ue.push(gr(qe.emit,ke))}}if(ue.length>0)z.push(`// From: ${bi(r.cwd,K)}
136
+ ${ue.join(`
137
+ `)}`)}let ge=x(e),ve=[],we=[];for(let[K,ee]of ge){if(ee.kind==="external"){we.push(`export { ${ee.imported===K?K:`${ee.imported} as ${K}`} } from '${ee.source}';`);continue}if(ee.kind==="external-namespace"){we.push(`export * as ${K} from '${ee.source}';`);continue}let ie=j(ee,K==="default"?"_default":K);ve.push(ie===K?K:`${ie} as ${K}`)}for(let K of a.get(e)??[])we.push(`export * from '${K}';`);let be=new Map;for(let[K,ee]of h){let[ie,ue]=K.split("\x00"),ae=be.get(ie)??{named:[],defaults:[],namespaces:[]};if(be.set(ie,ae),ue==="*")ae.namespaces.push(ee);else if(ue==="default")ae.defaults.push(ee);else ae.named.push(ue===ee?ee:`${ue} as ${ee}`)}let oe=[];for(let[K,ee]of[...be].sort(([ie],[ue])=>ie.localeCompare(ue))){for(let ie of ee.defaults)oe.push(`import ${ie} from '${K}';`);for(let ie of ee.namespaces)oe.push(`import * as ${ie} from '${K}';`);if(ee.named.length>0)oe.push(`import { ${ee.named.join(", ")} } from '${K}';`)}let R=[];if(ce.size>0)R.push([...ce].join(`
138
+ `));if(R.push(`/**
22
139
  * Bundled TypeScript declarations
23
140
  * Generated from ${o.size} source files
24
- */`),ne.length>0)ue.push(ne.join(`
25
- `));if(ue.push(...U),F.length>0)ue.push(F.join(`
26
- `));if(H.length>0)ue.push(H.join(`
27
- `));let se=[];if(pe.length>0)se.push(`export { ${pe.join(", ")} };`);if(se.push(...Oe),se.length===0)se.push("export {};");return ue.push(se.join(`
28
- `)),{content:`${ue.join(`
141
+ */`),oe.length>0)R.push(oe.join(`
142
+ `));if(R.push(...z),U.length>0)R.push(U.join(`
143
+ `));if(Q.length>0)R.push(Q.join(`
144
+ `));let Ue=[];if(ve.length>0)Ue.push(`export { ${ve.join(", ")} };`);if(Ue.push(...we),Ue.length===0)Ue.push("export {};");return R.push(Ue.join(`
145
+ `)),{content:`${R.join(`
29
146
 
30
147
  `)}
31
- `,files:[...o.keys()],exportCount:z.size,warnings:i}}var Ns,If;var Ws=he(()=>{bn();Ns=/^[A-Z_$][\w$]*$/i;If=/^(?:export\s+)?(default\s+)?(?:declare\s+)?(abstract\s+)?(class|interface|type|function\s*\*?|enum|const\s+enum|namespace|module|const|let|var|async\s+function)\b\s*([\w$]+)?/});function vr(e){if(Lf)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 Lf;var Sn=he(()=>{Lf=typeof globalThis.Bun?.hash==="function"});import{existsSync as br,mkdirSync as Wf,readFileSync as An,renameSync as Bf,rmSync as Bs,statSync as Gs,writeFileSync as js}from"fs";import{join as _s,relative as qr,resolve as Gf}from"path";class xn{cacheDir;manifestPath;manifest=null;configHash;constructor(e,t){this.cacheDir=Gf(e.cwd,Yr),this.manifestPath=_s(this.cacheDir,jf),this.configHash=this.hashConfig(e,t)}hashConfig(e,t){let r={resolutionContext: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((n)=>({pattern:typeof n.pattern==="string"?{kind:"string",value:n.pattern}:{kind:"regex",source:n.pattern.source,flags:n.pattern.flags},replacement:n.replacement,global:n.global,priority:n.priority,hasCondition:Boolean(n.condition)}))}:void 0,lineEnding:e.lineEnding,normalizeOutput:e.normalizeOutput,declarationOrder:e.declarationOrder,plugins:e.plugins?.map((n)=>({name:n.name,version:n.version,cacheKey:n.cacheKey}))};return String(vr(JSON.stringify(r)))}hashString(e){return String(vr(e))}load(){try{if(!br(this.manifestPath))return!1;let e=An(this.manifestPath,"utf-8"),t=JSON.parse(e);if(t.version!==$n)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:$n,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};if(this.manifest.updatedAt=Date.now(),!br(this.cacheDir))Wf(this.cacheDir,{recursive:!0});let e=`${this.manifestPath}.${process.pid}.tmp`;try{js(e,JSON.stringify(this.manifest,null,2)),Bf(e,this.manifestPath)}finally{if(br(e))Bs(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=qr(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=Gs(e),{mtimeMs:o,ctimeMs:s}=i;if(i.size!==n.sourceSize)return null;if(o!==n.sourceMtime||s!==n.sourceCtime){let a=An(e,"utf-8");if(this.hashString(a)!==n.sourceHash)return null;n.sourceMtime=o,n.sourceCtime=s}return n.dtsContent}catch{return null}}update(e,t,r,n){if(!this.manifest)this.manifest={version:$n,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};let i=qr(n,e),o,s,a;try{let c=Gs(e);o=c.mtimeMs,s=c.ctimeMs,a=c.size}catch{o=Date.now(),s=o,a=Buffer.byteLength(t)}this.manifest.entries[i]={sourcePath:i,sourceHash:this.hashString(t),sourceMtime:o,sourceCtime:s,sourceSize:a,dtsContent:r,dtsHash:this.hashString(r),generatedAt:Date.now(),configHash:this.configHash}}remove(e,t){if(!this.manifest)return;let r=qr(t,e);delete this.manifest.entries[r]}clear(){this.manifest=null;try{if(br(this.manifestPath))Bs(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)=>qr(t,i)));for(let i of Object.keys(this.manifest.entries))if(!n.has(i))delete this.manifest.entries[i],r++;return r}}function Vs(e){let t=_s(e,".gitignore");try{let r="";if(br(t))r=An(t,"utf-8");if(!r.split(/\r?\n/).some((n)=>n.trim()===Yr||n.trim()===`${Yr}/`)){let n=r.trimEnd(),i=`${n}${n?`
32
-
33
- `:""}# dtsx cache
34
- ${Yr}/
35
- `;js(t,i)}}catch{}}var $n=3,Yr=".dtsx-cache",jf="manifest.json";var Us=he(()=>{Sn()});function Ks(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 Hs=()=>{};import _f from"process";import{existsSync as zs,statSync as Js}from"fs";import{existsSync as Vf,mkdirSync as bg,readdirSync as Eg,readFileSync as Uf,writeFileSync as Sg}from"fs";import{homedir as Zt}from"os";import{dirname as xg,resolve as st}from"path";import Pi from"process";import{existsSync as qs,statSync as Ys}from"fs";import{existsSync as Hn,mkdirSync as Kf,readdirSync as Hf,writeFileSync as zf}from"fs";import{homedir as Xt}from"os";import{dirname as Zs,resolve as Ze}from"path";import Bt from"process";import{join as Jf,relative as qf,resolve as Xs}from"path";import gi from"process";import{existsSync as Da,mkdirSync as Ng,readdirSync as Lg,writeFileSync as Wg}from"fs";import{homedir as Tn}from"os";import{dirname as jg,resolve as Ye}from"path";import Sr from"process";import{join as Yf,relative as Zf,resolve as Qs}from"path";import yi from"process";import{existsSync as Ia,mkdirSync as Hg,readdirSync as zg,writeFileSync as Jg}from"fs";import{dirname as Yg,resolve as Ci}from"path";import zn from"process";import{Buffer as kt}from"buffer";import{createCipheriv as Xf,createDecipheriv as Qf,randomBytes as On}from"crypto";import{closeSync as Rn,createReadStream as ea,createWriteStream as eu,existsSync as Pn,fsyncSync as ta,openSync as ra,writeFileSync as tu}from"fs";import{access as ru,constants as ia,mkdir as iu,readdir as Zr,rename as na,stat as Qt,unlink as Xr,writeFile as kn}from"fs/promises";import{join as er}from"path";import Ke from"process";import{pipeline as nu}from"stream/promises";import{createGzip as oa}from"zlib";import tr from"process";import bt from"process";import{Buffer as Ct}from"buffer";import{createCipheriv as ou,createDecipheriv as su,randomBytes as Mn}from"crypto";import{closeSync as Dn,createReadStream as sa,createWriteStream as au,existsSync as Qr,fsyncSync as aa,openSync as la,writeFileSync as lu}from"fs";import{access as cu,constants as ca,mkdir as fu,readdir as ei,rename as fa,stat as rr,unlink as ti,writeFile as In}from"fs/promises";import{isAbsolute as uu,join as ir,resolve as hu}from"path";import ge from"process";import{pipeline as du}from"stream/promises";import{createGzip as ua}from"zlib";import nr from"process";import Et from"process";import ri from"process";import{existsSync as ii}from"fs";import{resolve as Fn}from"path";import{existsSync as mu}from"fs";import{existsSync as pu,readdirSync as gu}from"fs";import{extname as Nn,resolve as ha}from"path";import yu from"process";import{join as Cu,relative as wu,resolve as da}from"path";import wi from"process";import{Buffer as wt}from"buffer";import{createCipheriv as vu,createDecipheriv as bu,randomBytes as Ln}from"crypto";import{closeSync as Wn,createReadStream as ma,createWriteStream as Eu,existsSync as ni,fsyncSync as pa,openSync as ga,writeFileSync as Su}from"fs";import{access as $u,constants as ya,mkdir as Au,readdir as oi,rename as Ca,stat as or,unlink as si,writeFile as Bn}from"fs/promises";import{isAbsolute as xu,join as sr,resolve as Tu}from"path";import ye from"process";import{pipeline as Ou}from"stream/promises";import{createGzip as wa}from"zlib";import ar from"process";import St from"process";import ai from"process";import{existsSync as li}from"fs";import{resolve as Gn}from"path";import{existsSync as Ru}from"fs";class Fa{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),o=n??this.options.ttl,s=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:o,hits:0,size:s}),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(!zs(e))return!0;return Js(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=zs(r)?Js(r):null,o=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},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 Na{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let o=await t(),s=performance.now()-n;return this.recordMetric({operation:e,duration:s,timestamp:i,...r}),o}catch(o){let s=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:i,...r}),o}}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,o)=>i+o,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 Mu(e,t){this[e]=ku.bind(null,t)}class oo{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),o=n??this.options.ttl,s=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:o,hits:0,size:s}),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(!qs(e))return!0;return Ys(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=qs(r)?Ys(r):null,o=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},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 so{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let o=await t(),s=performance.now()-n;return this.recordMetric({operation:e,duration:s,timestamp:i,...r}),o}catch(o){let s=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:i,...r}),o}}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,o)=>i+o,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 Fu(e,t={}){let r=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return r?`${e}:${r}`:e}function Nu(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Lu(e){return e.getStats().size*2}function ao(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Te(t[0])&&"id"in t[0]&&t[0].id===3&&Te(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Te(t)&&Te(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(Te(e)&&"arr"in e&&Array.isArray(e.arr)&&Te(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Te(t[0])&&Te(e[0])){let n=[...t];for(let i of e)if(Te(i)&&"name"in i){if(!n.find((o)=>Te(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(Te(i)&&"path"in i){if(!n.find((o)=>Te(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((o)=>bi(o,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(!Te(t)||!Te(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(Te(i)&&Te(r[n]))r[n]=ao(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&Te(i[0])&&Te(r[n][0])){let o=[...i];for(let s of r[n])if(Te(s)&&"name"in s){if(!o.find((a)=>Te(a)&&("name"in a)&&a.name===s.name))o.push(s)}else if(Te(s)&&"path"in s){if(!o.find((a)=>Te(a)&&("path"in a)&&a.path===s.path))o.push(s)}else if(!o.some((a)=>bi(a,s)))o.push(s);r[n]=o}else if(i.every((o)=>typeof o==="string")&&r[n].every((o)=>typeof o==="string")){let o=[...i];for(let s of r[n])if(!o.includes(s))o.push(s);r[n]=o}else r[n]=i;else r[n]=i}return r}function bi(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(!bi(e[r],t[r]))return!1;return!0}if(Te(e)&&Te(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(!bi(e[i],t[i]))return!1}return!0}return!1}function Te(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Wu(e,t){if(!Ia(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 ao(t,n)}catch{return null}}catch{return null}}async function Bu({name:e="",cwd:t,defaultConfig:r}){let n=t||zn.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],o=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let s of o)for(let a of i){let c=Ci(n,`${s}${a}`),f=await Wu(c,r);if(f!==null)return f}try{let s=Ci(n,"package.json");if(Ia(s)){let a=(await import(s))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return ao(r,a)}catch{}}}catch{}return r}function Gu(e,t={}){let r=yi.cwd();while(r.includes("storage"))r=Qs(r,"..");let n=Qs(r,e||"");if(t?.relative)return Zf(yi.cwd(),n);return n}async function ju(){try{let e=await Bu({name:"clarity",defaultConfig:hi,cwd:yi.cwd(),endpoint:"",headers:{}});return{...hi,...e}}catch{return hi}}function Pe(){if(bt.env.NODE_ENV==="test"||bt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function _u(){if(bt.env.NODE_ENV==="test"||bt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof bt<"u"){let e=bt.type;if(e==="renderer"||e==="worker")return!1;return!!(bt.versions&&(bt.versions.node||bt.versions.bun))}return!1}class Wa{async format(e){let t=await _u(),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:tr.pid,hostname:t(),environment:tr.env.NODE_ENV||"development",platform:tr.platform,version:tr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:tr.env.NODE_ENV||tr.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;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={...qn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Wa,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??Ke.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(),o=this.generateKey();this.currentKeyId=i,this.keys.set(i,o),this.encryptionKeys.set(i,{key:o,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...di,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...di};return{...di,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:qn.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,o=3,s=1000;while(i<o)try{try{try{await ru(this.config.logDirectory,ia.F_OK|ia.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await iu(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:kt.from(e);try{if(!Pn(this.currentLogFile))await kn(this.currentLogFile,"",{mode:420});if(n=ra(this.currentLogFile,"a",420),tu(n,a,{flag:"a"}),ta(n),n!==void 0)Rn(n),n=void 0;if((await Qt(this.currentLogFile)).size===0){if(await kn(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(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(i<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,u);let h=s*2**i;await new Promise((l)=>setTimeout(l,h)),i++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(n!==void 0)try{Rn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}i++;let c=s*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 er(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 er(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return er(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Pe())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(([,s],[,a])=>a.createdAt.getTime()-s.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,o=Math.max(1,i);if(n.length>o)for(let[s]of n.slice(o))this.encryptionKeys.delete(s),this.keys.delete(s)}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=Xf("aes-256-gcm",t,r),i=kt.concat([n.update(e,"utf8"),n.final()]),o=n.getAuthTag();return{encrypted:kt.concat([r,i,o]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=oa(),i=[];n.on("data",(o)=>i.push(o)),n.on("end",()=>t(kt.from(kt.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(Pe())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 Zr(this.config.logDirectory),o=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}),s=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${s}`;if(await Qt(r).catch(()=>null))try{if(await na(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await Xr(a)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await kn(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,"-"),o=r.replace(/\.log$/,`-${i}.log`);if(await Qt(r).catch(()=>null))await na(r,o)}if(this.currentLogFile=n,t.maxFiles){let i=(await Zr(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of i.slice(t.maxFiles))await Xr(er(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=ea(e),n=eu(t),i=oa();await nu(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()})),Pn(this.currentLogFile))try{let e=ra(this.currentLogFile,"r+");ta(e),Rn(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Pe()&&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 Xr(er(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?Ee.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:o,showTimestamp:s=!0}=e,a=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(s)y.push(t);if(o==="warning")y.push("WARN");else if(o==="error")y.push("ERROR");else if(r)y.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)y.push(n.replace(/[[\]]/g,""));return y.push(i),y.join(" ")}let c=Ke.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${r} ${i}`;else if(o==="info"||o==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${Ee.cyan(i)}`;if(!s)return f.trim();let u=a(f).trim().length,h=a(t).length,l=Math.max(1,c-2-u-h);return`${f.trim()}${" ".repeat(l)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let a=Number.parseInt(s,10);return a<t[0].length?String(t[0][a]):o});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let a=t[n++];switch(s){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 o}});if(n<t.length)i+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),o=this.formatFileTimestamp(n),s,a;if(t instanceof Error)s=t.message,a=t.stack;else s=this.formatMessage(t,r);if(this.fancy&&!Pe()){let f=Ja[e],u=this.options.showTags!==!1&&this.name?Ee.gray(this.formatTag(this.name)):"",h;switch(e){case"debug":h=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:Ee.gray(s),level:e}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:s,level:e}),console.error(h);break;case"success":h=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:Ee.green(s),level:e}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:s,level:e}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:s,level:e}),console.error(h),a){let l=a.split(`
36
- `);for(let y of l)if(y.trim()&&!y.includes(s))console.error(this.formatConsoleMessage({timestamp:i,message:Ee.gray(` ${y}`),level:e,showTimestamp:!1}))}break}}else if(!Pe()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${s}`),a)console.error(a)}if(!this.shouldLog(e))return;let c=`${o} ${this.environment}.${e.toUpperCase()}: ${s}
37
- `;if(a)c+=`${a}
38
- `;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(e){let t=performance.now();if(this.fancy&&!Pe()){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: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),o=`${e} completed in ${i}ms`,s=new Date,a=this.formatConsoleTimestamp(s),c=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
39
- `,c=c.replace(this.ANSI_PATTERN,""),this.fancy&&!Pe()){let f=this.options.showTags!==!1&&this.name?Ee.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:Ee.green("\u2713"),tag:f,message:`${o}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Pe())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 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(Pe())throw Error("createReadStream is not supported in browser environments");if(!Pn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ea(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=kt.isBuffer(e)?e:kt.from(e,"base64"),i=n.slice(0,16),o=n.slice(-16),s=n.slice(16,-16),a=Qf("aes-256-gcm",r,i);return a.setAuthTag(o),kt.concat([a.update(s),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 Pe()}isServerMode(){return!Pe()}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&&!Pe()){let o=e.split(`
40
- `),s=Math.max(...o.map((u)=>u.length))+2,a=`\u250C${"\u2500".repeat(s)}\u2510`,c=`\u2514${"\u2500".repeat(s)}\u2518`,f=o.map((u)=>{let h=" ".repeat(s-u.length-2);return`\u2502 ${u}${h} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:Ee.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:Ee.cyan(a)})),f.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:Ee.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:Ee.cyan(c),showTimestamp:!1}))}else if(!Pe())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let i=`${n} ${this.environment}.INFO: [BOX] ${e}
41
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(Pe())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${Ee.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();Ke.stdin.removeListener("data",r);try{if(typeof Ke.stdin.setRawMode==="function")Ke.stdin.setRawMode(!1)}catch{}Ke.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof Ke.stdin.setRawMode==="function")Ke.stdin.setRawMode(!0)}catch{}Ke.stdin.resume(),Ke.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,o=0;if(r=e.replace(i,(s,a)=>{if(a==="%")return"%";if(o>=t.length)return s;let c=t[o++];switch(a){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}}),o<t.length)r+=` ${t.slice(o).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`}if(this.fancy&&!Pe()){let i=this.options.showTags!==!1&&this.name?Ee.gray(this.formatTag(this.name)):"",o=Ee.blue("\u25D0");console.error(`${o} ${i} ${Ee.cyan(r)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
42
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(e,t=""){if(!this.enabled||!this.fancy||Pe()||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||Pe())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,n)),i!==void 0)this.activeProgressBar.message=i;let o=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,o)},finish:(n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Pe())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||Pe())return;Ke.stdout.write(`${"\r".padEnd(Ke.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||Pe()||!Ke.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,o=Ee.green("\u2501".repeat(n)),s=Ee.gray("\u2501".repeat(i)),a=`[${o}${s}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=t||r===100?Ee.green("\u2713"):Ee.blue("\u25B6"),h=this.options.showTags!==!1&&this.name?` ${Ee.gray(this.formatTag(this.name))}`:"",l=`\r${u}${h} ${a} ${c}${f}`,y=Ke.stdout.columns||80,C=" ".repeat(Math.max(0,y-l.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${l}${C}`,Ke.stdout.write(e.lastRenderedLine),t)Ke.stdout.write(`
43
- `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Pe()||!Ke.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(Pe()){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=er(this.config.logDirectory,n);if(e.before)try{if((await Qt(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);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 Xr(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 ui(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((o)=>Ce(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(Ce(i)&&"path"in i){if(!n.find((o)=>Ce(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((o)=>Si(o,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]=ui(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 o=[...i];for(let s of r[n])if(Ce(s)&&"name"in s){if(!o.find((a)=>Ce(a)&&("name"in a)&&a.name===s.name))o.push(s)}else if(Ce(s)&&"path"in s){if(!o.find((a)=>Ce(a)&&("path"in a)&&a.path===s.path))o.push(s)}else if(!o.some((a)=>Si(a,s)))o.push(s);r[n]=o}else if(i.every((o)=>typeof o==="string")&&r[n].every((o)=>typeof o==="string")){let o=[...i];for(let s of r[n])if(!o.includes(s))o.push(s);r[n]=o}else r[n]=i;else r[n]=i}return r}function lo(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:ui(e,t);if(Array.isArray(e))return r==="replace"?t:ui(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 o=t[i],s=n[i];if(o===null||o===void 0)continue;if(Array.isArray(o)||Array.isArray(s))if(r==="replace")n[i]=o;else n[i]=ui(s,o);else if(Ce(o)&&Ce(s))n[i]=lo(s,o,r);else n[i]=o}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(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(!Si(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(!Da(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 lo(t,i,r)}catch{return null}}catch{return null}}function Vu(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function o(s,a=[]){let c={...s};for(let[f,u]of Object.entries(s)){let h=[...a,f],l=(S)=>S.replace(/([A-Z])/g,"_$1").toUpperCase(),y=`${n}_${h.map(l).join("_")}`,C=`${n}_${h.map((S)=>S.toUpperCase()).join("_")}`;if(r)ze.info(`Checking environment variable ${y} for config ${e}.${h.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))c[f]=o(u,h);else{let S=Sr.env[y]||Sr.env[C];if(S!==void 0){if(r)ze.info(`Using environment variable ${S?y:C} for config ${e}.${h.join(".")}`);if(typeof u==="number")c[f]=Number(S);else if(typeof u==="boolean")c[f]=S.toLowerCase()==="true";else if(Array.isArray(u))try{let x=JSON.parse(S);if(Array.isArray(x))c[f]=x;else c[f]=S.split(",").map((v)=>v.trim())}catch{c[f]=S.split(",").map((x)=>x.trim())}else c[f]=S}}}return c}return o(i)}async function Uu({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:o=!1,checkEnv:s=!0,arrayStrategy:a="replace"}){let c=s&&typeof i==="object"&&i!==null&&!Array.isArray(i)?Vu(e,i,o):i,f=r||Sr.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(o)ze.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${f}`);let h=[e,`.${e}`].filter(Boolean),l=[`${e}.config`,`.${e}.config`].filter(Boolean),y=t?[t,`.${t}`]:[],C=t?[`${t}.config`,`.${t}.config`]:[],S=Array.from(new Set([f,Ye(f,"config"),Ye(f,".config"),n?Ye(f,n):void 0].filter(Boolean)));for(let x of S){if(o)ze.info(`Searching for configuration in: ${x}`);let v=[Ye(f,"config"),Ye(f,".config")].concat(n?[Ye(f,n)]:[]).includes(x)?[...h,...l,...y,...C]:[...l,...h,...C,...y];for(let G of v)for(let L of u){let P=Ye(x,`${G}${L}`),F=await ci(P,c,a);if(F!==null){if(o)ze.success(`Configuration loaded from: ${P}`);return F}}}if(e){let x=Ye(Tn(),".config",e),v=["config",`${e}.config`];if(t)v.push(`${t}.config`);if(o)ze.info(`Checking user config directory: ${x}`);for(let G of v)for(let L of u){let P=Ye(x,`${G}${L}`),F=await ci(P,c,a);if(F!==null){if(o)ze.success(`Configuration loaded from user config directory: ${P}`);return F}}}if(e){let x=Ye(Tn(),".config"),v=[`.${e}.config`];if(t)v.push(`.${t}.config`);if(o)ze.info(`Checking user config directory for dotfile configs: ${x}`);for(let G of v)for(let L of u){let P=Ye(x,`${G}${L}`),F=await ci(P,c,a);if(F!==null){if(o)ze.success(`Configuration loaded from user config directory dotfile: ${P}`);return F}}}if(e){let x=Tn(),v=[`.${e}.config`,`.${e}`];if(t)v.push(`.${t}.config`),v.push(`.${t}`);if(o)ze.info(`Checking user home directory for dotfile configs: ${x}`);for(let G of v)for(let L of u){let P=Ye(x,`${G}${L}`),F=await ci(P,c,a);if(F!==null){if(o)ze.success(`Configuration loaded from user home directory: ${P}`);return F}}}try{let x=Ye(f,"package.json");if(Da(x)){let v=await import(x),G=v[e];if(!G&&t){if(G=v[t],G&&o)ze.success(`Using alias "${t}" configuration from package.json`)}if(G&&typeof G==="object"&&!Array.isArray(G))try{if(o)ze.success(`Configuration loaded from package.json: ${G===v[e]?e:t}`);return lo(c,G,a)}catch(L){if(o)ze.warn("Failed to merge package.json config:",L)}}}catch(x){if(o)ze.warn("Failed to load package.json:",x)}if(o)ze.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function Ku(e,t={}){let r=gi.cwd();while(r.includes("storage"))r=Xs(r,"..");let n=Xs(r,e||"");if(t?.relative)return qf(gi.cwd(),n);return n}async function Hu(){try{let e=await Uu({name:"clarity",alias:"logging",defaultConfig:mi,cwd:gi.cwd()});return{...mi,...e||{}}}catch{return mi}}function Ne(){if(Et.env.NODE_ENV==="test"||Et.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function zu(){if(Et.env.NODE_ENV==="test"||Et.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Et<"u"){let e=Et.type;if(e==="renderer"||e==="worker")return!1;return!!(Et.versions&&(Et.versions.node||Et.versions.bun))}return!1}class Ba{async format(e){let t=await zu(),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:nr.pid,hostname:t(),environment:nr.env.NODE_ENV||"development",platform:nr.platform,version:nr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:nr.env.NODE_ENV||nr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class $i{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={...Yn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ba,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??ge.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),o=this.generateKey();this.currentKeyId=i,this.keys.set(i,o),this.encryptionKeys.set(i,{key:o,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:Yn.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!Ne()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,i=0,o=3,s=1000;while(i<o)try{try{try{await cu(this.config.logDirectory,ca.F_OK|ca.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await fu(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Ct.from(e);try{if(!Qr(this.currentLogFile))await In(this.currentLogFile,"",{mode:420});if(n=la(this.currentLogFile,"a",420),lu(n,a,{flag:"a"}),aa(n),n!==void 0)Dn(n),n=void 0;if((await rr(this.currentLogFile)).size===0){if(await In(this.currentLogFile,a,{flag:"w",mode:420}),(await rr(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<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,u);let h=s*2**i;await new Promise((l)=>setTimeout(l,h)),i++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(n!==void 0)try{Dn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}i++;let c=s*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 ir(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 ir(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ir(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Ne())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(([,s],[,a])=>a.createdAt.getTime()-s.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,o=Math.max(1,i);if(n.length>o)for(let[s]of n.slice(o))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return Mn(16).toString("hex")}generateKey(){return Mn(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=Mn(16),n=ou("aes-256-gcm",t,r),i=Ct.isBuffer(e)?e:Ct.from(e,"utf8"),o=n.update(i),s=n.final(),a=o.length+s.length,c=n.getAuthTag(),f=Ct.allocUnsafe(16+a+16);return r.copy(f,0),o.copy(f,16),s.copy(f,16+o.length),c.copy(f,16+a),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=ua(),i=[];n.on("data",(o)=>i.push(o)),n.on("end",()=>t(Ct.from(Ct.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(Ne())return;if(!this.shouldWriteToFile())return;let e=await rr(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 ei(this.config.logDirectory),o=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}),s=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${s}`;if(await rr(r).catch(()=>null))try{if(await fa(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await ti(a)}catch(c){console.error("Error compressing rotated file:",c)}if(o.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,"-"),o=r.replace(/\.log$/,`-${i}.log`);if(await rr(r).catch(()=>null))await fa(r,o)}if(this.currentLogFile=n,t.maxFiles){let i=(await ei(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of i.slice(t.maxFiles))await ti(ir(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=sa(e),n=au(t),i=ua();await du(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()})),Qr(this.currentLogFile))try{let e=la(this.currentLogFile,"r+");aa(e),Dn(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Ne()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await ei(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await ti(ir(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()?ce.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Ne())return!1;let e=typeof ge.env.NO_COLOR<"u",t=ge.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof ge.stderr<"u"&&ge.stderr.isTTY||typeof ge.stdout<"u"&&ge.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:o,showTimestamp:s=!0}=e,a=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(s)y.push(t);if(o==="warning")y.push("WARN");else if(o==="error")y.push("ERROR");else if(r)y.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)y.push(n.replace(/[[\]]/g,""));return y.push(i),y.join(" ")}let c=ge.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${r} ${i}`;else if(o==="info"||o==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${ce.cyan(i)}`;if(!s)return f.trim();let u=a(f).trim().length,h=a(t).length,l=Math.max(1,c-2-u-h);return`${f.trim()}${" ".repeat(l)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let a=Number.parseInt(s,10);return a<t[0].length?String(t[0][a]):o});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let a=t[n++];switch(s){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 o}});if(n<t.length)i+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let o=ce.underline(ce.blue(n)),s=this.toAbsoluteFilePath(i);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(s)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${a}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),t=t.replace(/`([^`]+)`/g,(r,n)=>ce.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>ce.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>ce.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>ce.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>ce.strikethrough(n)),t}supportsHyperlinks(){if(Ne())return!1;let e=ge.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=ge.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(uu(t)||t.startsWith("./")||t.startsWith("../"))t=hu(t);else return null;return Qr(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),o=this.formatFileTimestamp(n),s,a;if(t instanceof Error)s=t.message,a=t.stack;else s=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let h=this.options.showIcons===!1?"":qa[e],l=this.options.showTags!==!1&&this.name?ce.gray(this.formatTag(this.name)):"",y;switch(e){case"debug":y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:ce.gray(c),level:e}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:c,level:e}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:ce.green(c),level:e}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:c,level:e}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:c,level:e}),console.error(y),a){let C=a.split(`
44
- `);for(let S of C)if(S.trim()&&!S.includes(s))console.error(this.formatConsoleMessage({timestamp:i,message:ce.gray(` ${S}`),level:e,showTimestamp:!1}))}break}}else if(!Ne()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${s}`),a)console.error(a)}if(!this.shouldLog(e))return;let u=`${o} ${this.environment}.${e.toUpperCase()}: ${f}
45
- `;if(a)u+=`${a}
46
- `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(i,o)=>{},finish:(i)=>{},interrupt:(i,o)=>{}};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()&&!Ne()&&ge.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(i,o)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,i),this.activeProgressBar.total),o!==void 0)this.activeProgressBar.message=o;if(this.shouldStyleConsole()&&!Ne()&&ge.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,o="info")=>{if(!Ne()&&ge.stdout.isTTY)ge.stdout.write(`
47
- `);if(this[o==="warning"?"warn":o](i),this.activeProgressBar&&this.shouldStyleConsole()&&!Ne()&&ge.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?ce.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":ce.blue("\u25D0"),tag:r,message:`${ce.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),o=`${e} completed in ${i}ms`,s=new Date,a=this.formatConsoleTimestamp(s),c=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
48
- `,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?ce.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":ce.green("\u2713"),tag:f,message:`${o}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Ne())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 $i(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(Ne())throw Error("createReadStream is not supported in browser environments");if(!Qr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return sa(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=Ct.isBuffer(e)?e:Ct.from(e,"base64"),i=n.subarray(0,16),o=n.subarray(n.length-16),s=n.subarray(16,n.length-16),a=su("aes-256-gcm",r,i);a.setAuthTag(o);let c=a.update(s),f=a.final(),u=c.length+f.length,h=Ct.allocUnsafe(u);return c.copy(h,0),f.copy(h,c.length),h.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 Ne()}isServerMode(){return!Ne()}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:o}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let a=i.split(`
49
- `),c=Math.max(...a.map((l)=>l.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,h=a.map((l)=>this.formatConsoleMessage({timestamp:r,message:ce.cyan(l),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:ce.cyan(f),showTimestamp:!1})),h.forEach((l)=>console.error(l)),console.error(this.formatConsoleMessage({timestamp:r,message:ce.cyan(u),showTimestamp:!1}))}else if(!Ne())console.error(`${n} ${this.environment}.INFO: [BOX] ${o}`);let s=`${n} ${this.environment}.INFO: [BOX] ${o}
50
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(e){if(Ne())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${ce.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();ge.stdin.removeListener("data",r);try{if(typeof ge.stdin.setRawMode==="function")ge.stdin.setRawMode(!1)}catch{}ge.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof ge.stdin.setRawMode==="function")ge.stdin.setRawMode(!0)}catch{}ge.stdin.resume(),ge.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 s=/%([sdijfo%])/g,a=0;if(r=e.replace(s,(c,f)=>{if(f==="%")return"%";if(a>=t.length)return c;let u=t[a++];switch(f){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return c}}),a<t.length)r+=` ${t.slice(a).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?ce.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${ce.blue("\u25D0")} `;console.error(`${a}${s} ${ce.cyan(n)}`)}let o=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
51
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!ge.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,o=ce.green("\u2501".repeat(n)),s=ce.gray("\u2501".repeat(i)),a=`[${o}${s}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?ce.green("\u2713"):ce.blue("\u25B6"),h=this.options.showTags!==!1&&this.name?` ${ce.gray(this.formatTag(this.name))}`:"",l=`\r${u}${h} ${a} ${c}${f}`,y=ge.stdout.columns||80,C=" ".repeat(Math.max(0,y-l.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${l}${C}`,ge.stdout.write(e.lastRenderedLine),t)ge.stdout.write(`
52
- `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ne()||!ge.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Ne()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await ei(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=ir(this.config.logDirectory,n);if(e.before)try{if((await rr(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);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 ti(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:o}=t,s=Error("Unknown error occurred");for(let a=0;a<=r;a++)try{return await e()}catch(c){if(s=c instanceof Error?c:Error(String(c)),a===r||!i(s))break;if(n>0)await new Promise((f)=>setTimeout(f,n))}if(o!==void 0)return o;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}function ja(e){return e instanceof rt}function Ju(e){return e instanceof Ai}function qu(e){if(ja(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 ki{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:o=!0,customParsers:s={},verbose:a=!1,trackPerformance:c=!0}=r,f=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),h={...t};return this.processObject(h,[],u,{useCamelCase:i,useBackwardCompatibility:o,customParsers:s,verbose:a,configName:e}),{config:h,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return xr.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,o]of Object.entries(e)){let s=[...t,i],a=s.map((u)=>this.formatEnvKey(u,n.useCamelCase)),c=`${r}_${a.join("_")}`,f=n.useBackwardCompatibility?`${r}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.processObject(o,s,r,n);else{let u=ri.env[c]||(f?ri.env[f]:void 0);if(u!==void 0){if(n.verbose){let h=ri.env[c]?c:f}try{e[i]=this.parseEnvironmentValue(u,typeof o,c,n.customParsers,n.configName)}catch(h){if(h instanceof xi)throw h;throw Mt.envVar(c,u,typeof o,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[o,s]of Object.entries(n))try{return s(e)}catch{continue}for(let o of this.defaultParsers)if(o.canParse(e,t))try{return o.parse(e)}catch{throw Mt.envVar(r,e,`${t} (via ${o.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(ri.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,o=n||this.generateEnvPrefix(e),s=[];switch(this.extractEnvVarInfo(t,[],o,s),i){case"markdown":return this.formatAsMarkdown(s,e);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,o]of Object.entries(e)){let s=[...t,i],a=`${r}_${s.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.extractEnvVarInfo(o,s,r,n);else n.push({key:a,type:Array.isArray(o)?"array":typeof o,description:`Configuration for ${s.join(".")}`,example:this.generateExample(o)})}}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}:
148
+ `,files:[...o.keys()],exportCount:ge.size,warnings:n}}var np,ap;var wc=me(()=>{ut();sr();un();Ci();wn();np=/^[A-Z_$][\w$]*$/i;ap=/^(?:export\s+)?(default\s+)?(?:declare\s+)?(abstract\s+)?(class|interface|type|function\s*\*?|enum|const\s+enum|namespace|module|const|let|var|async\s+function)\b\s*([\w$]+)?/});import cp from"process";import{existsSync as Cc,statSync as vc}from"fs";import{resolve as wr}from"path";import fp from"process";import{existsSync as tw,mkdirSync as iw,readdirSync as rw,readFileSync as up,writeFileSync as nw}from"fs";import{homedir as Ni}from"os";import{dirname as aw,resolve as Lt}from"path";import Xn from"process";import{existsSync as bc,statSync as $c}from"fs";import{existsSync as _s,mkdirSync as dp,readdirSync as hp,writeFileSync as pp}from"fs";import{homedir as Fi}from"os";import{dirname as Ec,resolve as pt}from"path";import $i from"process";import{join as mp,relative as gp,resolve as Sc}from"path";import Ln from"process";import{existsSync as lf,mkdirSync as yw,readdirSync as ww,writeFileSync as Cw}from"fs";import{homedir as $s}from"os";import{dirname as $w,resolve as ht}from"path";import br from"process";import{join as yp,relative as wp,resolve as xc}from"path";import Bn from"process";import{existsSync as cf,mkdirSync as Tw,readdirSync as kw,writeFileSync as Ow}from"fs";import{dirname as Pw,resolve as jn}from"path";import Vs from"process";import{Buffer as ri}from"buffer";import{createCipheriv as Cp,createDecipheriv as vp,randomBytes as Es}from"crypto";import{closeSync as Ss,createReadStream as Ac,createWriteStream as bp,existsSync as xs,fsyncSync as Tc,openSync as kc,writeFileSync as $p}from"fs";import{access as Ep,constants as Oc,mkdir as Sp,readdir as vn,rename as Rc,stat as Wi,unlink as bn,writeFile as As}from"fs/promises";import{join as Li}from"path";import st from"process";import{pipeline as xp}from"stream/promises";import{createGzip as Pc}from"zlib";import Bi from"process";import zt from"process";import{Buffer as Vt}from"buffer";import{createCipheriv as Ap,createDecipheriv as Tp,randomBytes as Ts}from"crypto";import{closeSync as ks,createReadStream as Mc,createWriteStream as kp,existsSync as $n,fsyncSync as Dc,openSync as Ic,writeFileSync as Op}from"fs";import{access as Rp,constants as Nc,mkdir as Pp,readdir as En,rename as Fc,stat as ji,unlink as Sn,writeFile as Os}from"fs/promises";import{isAbsolute as Mp,join as Gi,resolve as Dp}from"path";import Ne from"process";import{pipeline as Ip}from"stream/promises";import{createGzip as Wc}from"zlib";import _i from"process";import Ht from"process";import xn from"process";import{existsSync as An}from"fs";import{resolve as Rs}from"path";import{existsSync as Np}from"fs";import{existsSync as Fp,readdirSync as Wp}from"fs";import{extname as Ps,resolve as Lc}from"path";import Lp from"process";import{join as Bp,relative as jp,resolve as Bc}from"path";import Gn from"process";import{Buffer as Ut}from"buffer";import{createCipheriv as Gp,createDecipheriv as _p,randomBytes as Ms}from"crypto";import{closeSync as Ds,createReadStream as jc,createWriteStream as Vp,existsSync as Tn,fsyncSync as Gc,openSync as _c,writeFileSync as Up}from"fs";import{access as Kp,constants as Vc,mkdir as zp,readdir as kn,rename as Uc,stat as Vi,unlink as On,writeFile as Is}from"fs/promises";import{isAbsolute as Hp,join as Ui,resolve as qp}from"path";import Fe from"process";import{pipeline as Jp}from"stream/promises";import{createGzip as Kc}from"zlib";import Ki from"process";import qt from"process";import Rn from"process";import{readFileSync as Yp,realpathSync as Xp}from"fs";import{createRequire as Zp}from"module";import{pathToFileURL as Qp}from"url";import{existsSync as Ns,statSync as em}from"fs";import{resolve as zc}from"path";import{existsSync as tm}from"fs";class ff{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 i=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${i}`}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(([,i],[,r])=>i.timestamp.getTime()-r.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let i=0;i<t;i++)this.cache.delete(e[i][0])}set(e,t,i,r){if(!this.options.enabled)return;let n=this.generateKey(e,i),o=r??this.options.ttl,s=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:o,hits:0,size:s}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let i=this.generateKey(e,t),r=this.cache.get(i);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(i),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(e,t){try{if(!Cc(e))return!0;return vc(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let i=this.get(e,t);if(!i)return;if(this.isFileModified(t,i.fileTimestamp)){this.delete(e,t);return}return i.value}setWithFileCheck(e,t,i,r){try{let n=Cc(i)?vc(i):null,o=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},i,r)}catch{this.set(e,t,i,r)}}delete(e,t){let i=this.generateKey(e,t);return this.cache.delete(i)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,i]of this.cache.entries())if(this.isExpired(i))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((r,n)=>r+n.size,0),i=e.map((r)=>r.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:i[0],newestEntry:i[i.length-1]}}export(){let e={};for(let[t,i]of this.cache.entries())e[t]={value:i.value,timestamp:i.timestamp.toISOString(),ttl:i.ttl,hits:i.hits,size:i.size};return e}import(e){this.cache.clear();for(let[t,i]of Object.entries(e))if(typeof i==="object"&&i!==null){let r=i;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class uf{metrics=[];maxMetrics=1000;async track(e,t,i={}){let r=performance.now(),n=new Date;try{let o=await t(),s=performance.now()-r;return this.recordMetric({operation:e,duration:s,timestamp:n,...i}),o}catch(o){let s=performance.now()-r;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:n,...i}),o}}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((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let i=t.map((n)=>n.duration),r=i.reduce((n,o)=>n+o,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...i),maxDuration:Math.max(...i),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function hf(e={}){let{name:t="",alias:i}=e,r=["config",".config"];if(t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let n=i===void 0?[]:Array.isArray(i)?i:[i];for(let o of n){if(!o)continue;if(r.push(o,`.${o}.config`,`${o}.config`,`.${o}`),t)r.push(`${t}.${o}.config`,`.${t}.${o}.config`)}return Array.from(new Set(r.filter(Boolean)))}function im(e){return hf(e).flatMap((t)=>df.map((i)=>wr(e.directory,`${t}${i}`)))}function rm(e={}){let t=wr(e.cwd||fp.cwd());return Array.from(new Set([t,wr(t,"config"),wr(t,".config"),e.configDir?wr(t,e.configDir):void 0].filter((i)=>Boolean(i))))}function sm(e,t){this[e]=om.bind(null,t)}class ta{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 i=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${i}`}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(([,i],[,r])=>i.timestamp.getTime()-r.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let i=0;i<t;i++)this.cache.delete(e[i][0])}set(e,t,i,r){if(!this.options.enabled)return;let n=this.generateKey(e,i),o=r??this.options.ttl,s=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:o,hits:0,size:s}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let i=this.generateKey(e,t),r=this.cache.get(i);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(i),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(e,t){try{if(!bc(e))return!0;return $c(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let i=this.get(e,t);if(!i)return;if(this.isFileModified(t,i.fileTimestamp)){this.delete(e,t);return}return i.value}setWithFileCheck(e,t,i,r){try{let n=bc(i)?$c(i):null,o=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},i,r)}catch{this.set(e,t,i,r)}}delete(e,t){let i=this.generateKey(e,t);return this.cache.delete(i)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,i]of this.cache.entries())if(this.isExpired(i))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((r,n)=>r+n.size,0),i=e.map((r)=>r.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:i[0],newestEntry:i[i.length-1]}}export(){let e={};for(let[t,i]of this.cache.entries())e[t]={value:i.value,timestamp:i.timestamp.toISOString(),ttl:i.ttl,hits:i.hits,size:i.size};return e}import(e){this.cache.clear();for(let[t,i]of Object.entries(e))if(typeof i==="object"&&i!==null){let r=i;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class ia{metrics=[];maxMetrics=1000;async track(e,t,i={}){let r=performance.now(),n=new Date;try{let o=await t(),s=performance.now()-r;return this.recordMetric({operation:e,duration:s,timestamp:n,...i}),o}catch(o){let s=performance.now()-r;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:n,...i}),o}}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((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let i=t.map((n)=>n.duration),r=i.reduce((n,o)=>n+o,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...i),maxDuration:Math.max(...i),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function cm(e,t={}){let i=Object.keys(t).sort().map((r)=>`${r}:${t[r]}`).join("|");return i?`${e}:${i}`:e}function fm(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function um(e){return e.getStats().size*2}function ra(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Ke(t[0])&&"id"in t[0]&&t[0].id===3&&Ke(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Ke(t)&&Ke(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(Ke(e)&&"arr"in e&&Array.isArray(e.arr)&&Ke(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Ke(t[0])&&Ke(e[0])){let r=[...t];for(let n of e)if(Ke(n)&&"name"in n){if(!r.find((o)=>Ke(o)&&("name"in o)&&o.name===n.name))r.push(n)}else if(Ke(n)&&"path"in n){if(!r.find((o)=>Ke(o)&&("path"in o)&&o.path===n.path))r.push(n)}else if(!r.some((o)=>Vn(o,n)))r.push(n);return r}if(t.every((r)=>typeof r==="string")&&e.every((r)=>typeof r==="string")){let r=[...t];for(let n of e)if(!r.includes(n))r.push(n);return r}return t}if(!Ke(t)||!Ke(e))return t;let i={...e};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(n===null||n===void 0)continue;else if(Ke(n)&&Ke(i[r]))i[r]=ra(i[r],n);else if(Array.isArray(n)&&Array.isArray(i[r]))if(n.length>0&&i[r].length>0&&Ke(n[0])&&Ke(i[r][0])){let o=[...n];for(let s of i[r])if(Ke(s)&&"name"in s){if(!o.find((c)=>Ke(c)&&("name"in c)&&c.name===s.name))o.push(s)}else if(Ke(s)&&"path"in s){if(!o.find((c)=>Ke(c)&&("path"in c)&&c.path===s.path))o.push(s)}else if(!o.some((c)=>Vn(c,s)))o.push(s);i[r]=o}else if(n.every((o)=>typeof o==="string")&&i[r].every((o)=>typeof o==="string")){let o=[...n];for(let s of i[r])if(!o.includes(s))o.push(s);i[r]=o}else i[r]=n;else i[r]=n}return i}function Vn(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!Vn(e[i],t[i]))return!1;return!0}if(Ke(e)&&Ke(t)){let i=Object.keys(e),r=Object.keys(t);if(i.length!==r.length)return!1;for(let n of i){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Vn(e[n],t[n]))return!1}return!0}return!1}function Ke(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function dm(e,t){if(!cf(e))return null;try{let i=await import(e),r=i.default||i;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return ra(t,r)}catch{return null}}catch{return null}}async function hm({name:e="",cwd:t,defaultConfig:i}){let r=t||Vs.cwd(),n=[".ts",".js",".mjs",".cjs",".json"],o=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let s of o)for(let c of n){let l=jn(r,`${s}${c}`),f=await dm(l,i);if(f!==null)return f}try{let s=jn(r,"package.json");if(cf(s)){let c=(await import(s))[e];if(c&&typeof c==="object"&&!Array.isArray(c))try{return ra(i,c)}catch{}}}catch{}return i}function pm(e,t={}){let i=Bn.cwd();while(i.includes("storage"))i=xc(i,"..");let r=xc(i,e||"");if(t?.relative)return wp(Bn.cwd(),r);return r}async function mm(){try{let e=await hm({name:"clarity",defaultConfig:In,cwd:Bn.cwd(),endpoint:"",headers:{}});return{...In,...e}}catch{return In}}function Je(){if(zt.env.NODE_ENV==="test"||zt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function gm(){if(zt.env.NODE_ENV==="test"||zt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof zt<"u"){let e=zt.type;if(e==="renderer"||e==="worker")return!1;return!!(zt.versions&&(zt.versions.node||zt.versions.bun))}return!1}class mf{async format(e){let t=await gm(),i=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:i})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Bi.pid,hostname:t(),environment:Bi.env.NODE_ENV||"development",platform:Bi.platform,version:Bi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Bi.env.NODE_ENV||Bi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Un{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={...Ks},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new mf,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??st.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let i={...t},r=t.timestamp!==void 0;if(r)delete i.timestamp;if(this.config={...this.config,...i,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),o=this.generateKey();this.currentKeyId=n,this.keys.set(n,o),this.encryptionKeys.set(n,{key:o,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Nn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Nn};return{...Nn,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Ks.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},i={...t,...Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0))};if(!i.level||!["debug","info","success","warning","error"].includes(i.level))i.level=t.level;return i}async writeToFile(e){let t=(async()=>{let r,n=0,o=3,s=1000;while(n<o)try{try{try{await Ep(this.config.logDirectory,Oc.F_OK|Oc.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Sp(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ri.from(e);try{if(!xs(this.currentLogFile))await As(this.currentLogFile,"",{mode:420});if(r=kc(this.currentLogFile,"a",420),$p(r,c,{flag:"a"}),Tc(r),r!==void 0)Ss(r),r=void 0;if((await Wi(this.currentLogFile)).size===0){if(await As(this.currentLogFile,c,{flag:"w",mode:420}),(await Wi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(n<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${o}:`,u);let d=s*2**n;await new Promise((h)=>setTimeout(h,d)),n++;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(r!==void 0)try{Ss(r)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(n===o-1){let f=c,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}n++;let l=s*2**(n-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(t);let i=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(i,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 Li(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 Li(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Li(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Je())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,i=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),i=this.generateKey();this.currentKeyId=t,this.keys.set(t,i),this.encryptionKeys.set(t,{key:i,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,s],[,c])=>c.createdAt.getTime()-s.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,o=Math.max(1,n);if(r.length>o)for(let[s]of r.slice(o))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return Es(16).toString("hex")}generateKey(){return Es(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(),i=Es(16),r=Cp("aes-256-gcm",t,i),n=ri.concat([r.update(e,"utf8"),r.final()]),o=r.getAuthTag();return{encrypted:ri.concat([i,n,o]),iv:i}}async compressData(e){return new Promise((t,i)=>{let r=Pc(),n=[];r.on("data",(o)=>n.push(o)),r.on("end",()=>t(ri.from(ri.concat(n)))),r.on("error",i),r.write(e),r.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(Je())return;let e=await Wi(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 i=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await vn(this.config.logDirectory),o=n.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,f)=>{let u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${i}.${s}`;if(await Wi(i).catch(()=>null))try{if(await Rc(i,c),t.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await bn(c)}catch(l){console.error("Error compressing rotated file:",l)}if(o.length===0&&!n.some((l)=>l.endsWith(".log.1")))try{let l=`${i}.1`;await As(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),o=i.replace(/\.log$/,`-${n}.log`);if(await Wi(i).catch(()=>null))await Rc(i,o)}if(this.currentLogFile=r,t.maxFiles){let n=(await vn(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of n.slice(t.maxFiles))await bn(Li(this.config.logDirectory,o))}}}async compressLogFile(e,t){let i=Ac(e),r=bp(t),n=Pc();await xp(i,n,r)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let i of this.logBuffer){let r=await this.formatter.format(i);await this.writeToFile(r),console.log(r)}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 i={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(i)}}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()})),xs(this.currentLogFile))try{let e=kc(this.currentLogFile,"r+");Tc(e),Ss(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(!Je()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await vn(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await bn(Li(this.config.logDirectory,t))}catch(i){console.error(`Failed to delete temp file ${t}:`,i)}}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?Ve.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:i="",tag:r="",message:n,level:o,showTimestamp:s=!0}=e,c=(p)=>p.replace(this.ANSI_PATTERN,"");if(!this.fancy){let p=[];if(s)p.push(t);if(o==="warning")p.push("WARN");else if(o==="error")p.push("ERROR");else if(i)p.push(i.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)p.push(r.replace(/[[\]]/g,""));return p.push(n),p.join(" ")}let l=st.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${i} ${n}`;else if(o==="info"||o==="success")f=`${i} ${r} ${n}`;else f=`${i} ${r} ${Ve.cyan(n)}`;if(!s)return f.trim();let u=c(f).trim().length,d=c(t).length,h=Math.max(1,l-2-u-d);return`${f.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let c=Number.parseInt(s,10);return c<t[0].length?String(t[0][c]):o});let i=/%([sdijfo%])/g,r=0,n=e.replace(i,(o,s)=>{if(s==="%")return"%";if(r>=t.length)return o;let c=t[r++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return o}});if(r<t.length)n+=` ${t.slice(r).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return n}async log(e,t,...i){let r=new Date,n=this.formatConsoleTimestamp(r),o=this.formatFileTimestamp(r),s,c;if(t instanceof Error)s=t.message,c=t.stack;else s=this.formatMessage(t,i);if(this.fancy&&!Je()){let f=xf[e],u=this.options.showTags!==!1&&this.name?Ve.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:Ve.gray(s),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:s,level:e}),console.error(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:Ve.green(s),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:s,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:s,level:e}),console.error(d),c){let h=c.split(`
149
+ `);for(let p of h)if(p.trim()&&!p.includes(s))console.error(this.formatConsoleMessage({timestamp:n,message:Ve.gray(` ${p}`),level:e,showTimestamp:!1}))}break}}else if(!Je()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(e))return;let l=`${o} ${this.environment}.${e.toUpperCase()}: ${s}
150
+ `;if(c)l+=`${c}
151
+ `;l=l.replace(this.ANSI_PATTERN,""),await this.writeToFile(l)}time(e){let t=performance.now();if(this.fancy&&!Je()){let i=this.options.showTags!==!1&&this.name?Ve.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:Ve.blue("\u25D0"),tag:i,message:`${Ve.cyan(e)}...`}))}return async(i)=>{if(!this.enabled)return;let r=performance.now(),n=Math.round(r-t),o=`${e} completed in ${n}ms`,s=new Date,c=this.formatConsoleTimestamp(s),l=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(i)l+=` ${JSON.stringify(i)}`;if(l+=`
152
+ `,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!Je()){let f=this.options.showTags!==!1&&this.name?Ve.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:Ve.green("\u2713"),tag:f,message:`${o}${i?` ${JSON.stringify(i)}`:""}`}))}else if(!Je())console.error(l.trim());await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,i=new Un(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(i),i}createReadStream(){if(Je())throw Error("createReadStream is not supported in browser environments");if(!xs(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ac(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 i=this.keys.get(this.currentKeyId);try{let r=ri.isBuffer(e)?e:ri.from(e,"base64"),n=r.slice(0,16),o=r.slice(-16),s=r.slice(16,-16),c=vp("aes-256-gcm",i,n);return c.setAuthTag(o),ri.concat([c.update(s),c.final()]).toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Je()}isServerMode(){return!Je()}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,i=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t);if(this.fancy&&!Je()){let o=e.split(`
153
+ `),s=Math.max(...o.map((u)=>u.length))+2,c=`\u250C${"\u2500".repeat(s)}\u2510`,l=`\u2514${"\u2500".repeat(s)}\u2518`,f=o.map((u)=>{let d=" ".repeat(s-u.length-2);return`\u2502 ${u}${d} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:i,message:Ve.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:i,message:Ve.cyan(c)})),f.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:i,message:Ve.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:i,message:Ve.cyan(l),showTimestamp:!1}))}else if(!Je())console.error(`${r} ${this.environment}.INFO: [BOX] ${e}`);let n=`${r} ${this.environment}.INFO: [BOX] ${e}
154
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}async prompt(e){if(Je())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${Ve.cyan("?")} ${e} (y/n) `);let i=(r)=>{let n=r.toString().trim().toLowerCase();st.stdin.removeListener("data",i);try{if(typeof st.stdin.setRawMode==="function")st.stdin.setRawMode(!1)}catch{}st.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof st.stdin.setRawMode==="function")st.stdin.setRawMode(!0)}catch{}st.stdin.resume(),st.stdin.once("data",i)})}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 i=e;if(t&&t.length>0){let n=/%([sdijfo%])/g,o=0;if(i=e.replace(n,(s,c)=>{if(c==="%")return"%";if(o>=t.length)return s;let l=t[o++];switch(c){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return s}}),o<t.length)i+=` ${t.slice(o).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`}if(this.fancy&&!Je()){let n=this.options.showTags!==!1&&this.name?Ve.gray(this.formatTag(this.name)):"",o=Ve.blue("\u25D0");console.error(`${o} ${n} ${Ve.cyan(i)}`)}let r=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
155
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(r)}progress(e,t=""){if(!this.enabled||!this.fancy||Je()||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 i=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:i,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(r,n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Je())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,r)),n!==void 0)this.activeProgressBar.message=n;let o=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,o)},finish:(r)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Je())return;if(this.activeProgressBar.current=this.activeProgressBar.total,r!==void 0)this.activeProgressBar.message=r;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(r,n="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Je())return;st.stdout.write(`${"\r".padEnd(st.stdout.columns||80)}\r`),this.log(n,r),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||Je()||!st.stdout.isTTY)return;let i=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),r=Math.round(e.barLength*i/100),n=e.barLength-r,o=Ve.green("\u2501".repeat(r)),s=Ve.gray("\u2501".repeat(n)),c=`[${o}${s}]`,l=`${i}%`.padStart(4),f=e.message?` ${e.message}`:"",u=t||i===100?Ve.green("\u2713"):Ve.blue("\u25B6"),d=this.options.showTags!==!1&&this.name?` ${Ve.gray(this.formatTag(this.name))}`:"",h=`\r${u}${d} ${c} ${l}${f}`,p=st.stdout.columns||80,m=" ".repeat(Math.max(0,p-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${m}`,st.stdout.write(e.lastRenderedLine),t)st.stdout.write(`
156
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Je()||!st.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(Je()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await vn(this.config.logDirectory),i=[];for(let r of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let n=Li(this.config.logDirectory,r);if(e.before)try{if((await Wi(n)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${n}:`,o);continue}i.push(n)}if(i.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${i.length} log file(s)...`);for(let r of i)try{await bn(r),console.warn(`Deleted log file: ${r}`)}catch(n){console.error(`Failed to delete log file ${r}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function Dn(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&We(t[0])&&"id"in t[0]&&t[0].id===3&&We(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(We(t)&&We(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(We(e)&&"arr"in e&&Array.isArray(e.arr)&&We(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&We(t[0])&&We(e[0])){let r=[...t];for(let n of e)if(We(n)&&"name"in n){if(!r.find((o)=>We(o)&&("name"in o)&&o.name===n.name))r.push(n)}else if(We(n)&&"path"in n){if(!r.find((o)=>We(o)&&("path"in o)&&o.path===n.path))r.push(n)}else if(!r.some((o)=>Kn(o,n)))r.push(n);return r}if(t.every((r)=>typeof r==="string")&&e.every((r)=>typeof r==="string")){let r=[...t];for(let n of e)if(!r.includes(n))r.push(n);return r}return t}if(!We(t)||!We(e))return t;let i={...e};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(n===null||n===void 0)continue;else if(We(n)&&We(i[r]))i[r]=Dn(i[r],n);else if(Array.isArray(n)&&Array.isArray(i[r]))if(n.length>0&&i[r].length>0&&We(n[0])&&We(i[r][0])){let o=[...n];for(let s of i[r])if(We(s)&&"name"in s){if(!o.find((c)=>We(c)&&("name"in c)&&c.name===s.name))o.push(s)}else if(We(s)&&"path"in s){if(!o.find((c)=>We(c)&&("path"in c)&&c.path===s.path))o.push(s)}else if(!o.some((c)=>Kn(c,s)))o.push(s);i[r]=o}else if(n.every((o)=>typeof o==="string")&&i[r].every((o)=>typeof o==="string")){let o=[...n];for(let s of i[r])if(!o.includes(s))o.push(s);i[r]=o}else i[r]=n;else i[r]=n}return i}function na(e,t,i="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return i==="replace"?t:Dn(e,t);if(Array.isArray(e))return i==="replace"?t:Dn(e,t);if(!We(t)||!We(e))return t;let r={...e};for(let n of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let o=t[n],s=r[n];if(o===null||o===void 0)continue;if(Array.isArray(o)||Array.isArray(s))if(i==="replace")r[n]=o;else r[n]=Dn(s,o);else if(We(o)&&We(s))r[n]=na(s,o,i);else r[n]=o}return r}function Kn(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!Kn(e[i],t[i]))return!1;return!0}if(We(e)&&We(t)){let i=Object.keys(e),r=Object.keys(t);if(i.length!==r.length)return!1;for(let n of i){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Kn(e[n],t[n]))return!1}return!0}return!1}function We(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Pn(e,t,i="replace"){if(!lf(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 na(t,n,i)}catch{return null}}catch{return null}}function ym(e,t,i=!1){if(!e)return t;let r=e.toUpperCase().replace(/-/g,"_"),n={...t};function o(s,c=[]){let l={...s};for(let[f,u]of Object.entries(s)){let d=[...c,f],h=(a)=>a.replace(/([A-Z])/g,"_$1").toUpperCase(),p=`${r}_${d.map(h).join("_")}`,m=`${r}_${d.map((a)=>a.toUpperCase()).join("_")}`;if(i)lt.info(`Checking environment variable ${p} for config ${e}.${d.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))l[f]=o(u,d);else{let a=br.env[p]||br.env[m];if(a!==void 0){if(i)lt.info(`Using environment variable ${a?p:m} for config ${e}.${d.join(".")}`);if(typeof u==="number")l[f]=Number(a);else if(typeof u==="boolean")l[f]=a.toLowerCase()==="true";else if(Array.isArray(u))try{let C=JSON.parse(a);if(Array.isArray(C))l[f]=C;else l[f]=a.split(",").map((b)=>b.trim())}catch{l[f]=a.split(",").map((C)=>C.trim())}else l[f]=a}}}return l}return o(n)}async function wm({name:e="",alias:t,cwd:i,configDir:r,defaultConfig:n,verbose:o=!1,checkEnv:s=!0,arrayStrategy:c="replace"}){let l=s&&typeof n==="object"&&n!==null&&!Array.isArray(n)?ym(e,n,o):n,f=i||br.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(o)lt.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${f}`);let d=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),p=t?[t,`.${t}`]:[],m=t?[`${t}.config`,`.${t}.config`]:[],a=Array.from(new Set([f,ht(f,"config"),ht(f,".config"),r?ht(f,r):void 0].filter(Boolean)));for(let C of a){if(o)lt.info(`Searching for configuration in: ${C}`);let b=[ht(f,"config"),ht(f,".config")].concat(r?[ht(f,r)]:[]).includes(C)?[...d,...h,...p,...m]:[...h,...d,...m,...p];for(let v of b)for(let T of u){let B=ht(C,`${v}${T}`),x=await Pn(B,l,c);if(x!==null){if(o)lt.success(`Configuration loaded from: ${B}`);return x}}}if(e){let C=ht($s(),".config",e),b=["config",`${e}.config`];if(t)b.push(`${t}.config`);if(o)lt.info(`Checking user config directory: ${C}`);for(let v of b)for(let T of u){let B=ht(C,`${v}${T}`),x=await Pn(B,l,c);if(x!==null){if(o)lt.success(`Configuration loaded from user config directory: ${B}`);return x}}}if(e){let C=ht($s(),".config"),b=[`.${e}.config`];if(t)b.push(`.${t}.config`);if(o)lt.info(`Checking user config directory for dotfile configs: ${C}`);for(let v of b)for(let T of u){let B=ht(C,`${v}${T}`),x=await Pn(B,l,c);if(x!==null){if(o)lt.success(`Configuration loaded from user config directory dotfile: ${B}`);return x}}}if(e){let C=$s(),b=[`.${e}.config`,`.${e}`];if(t)b.push(`.${t}.config`),b.push(`.${t}`);if(o)lt.info(`Checking user home directory for dotfile configs: ${C}`);for(let v of b)for(let T of u){let B=ht(C,`${v}${T}`),x=await Pn(B,l,c);if(x!==null){if(o)lt.success(`Configuration loaded from user home directory: ${B}`);return x}}}try{let C=ht(f,"package.json");if(lf(C)){let b=await import(C),v=b[e];if(!v&&t){if(v=b[t],v&&o)lt.success(`Using alias "${t}" configuration from package.json`)}if(v&&typeof v==="object"&&!Array.isArray(v))try{if(o)lt.success(`Configuration loaded from package.json: ${v===b[e]?e:t}`);return na(l,v,c)}catch(T){if(o)lt.warn("Failed to merge package.json config:",T)}}}catch(C){if(o)lt.warn("Failed to load package.json:",C)}if(o)lt.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return l}function Cm(e,t={}){let i=Ln.cwd();while(i.includes("storage"))i=Sc(i,"..");let r=Sc(i,e||"");if(t?.relative)return gp(Ln.cwd(),r);return r}async function vm(){try{let e=await wm({name:"clarity",alias:"logging",defaultConfig:Fn,cwd:Ln.cwd()});return{...Fn,...e||{}}}catch{return Fn}}function tt(){if(Ht.env.NODE_ENV==="test"||Ht.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function bm(){if(Ht.env.NODE_ENV==="test"||Ht.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Ht<"u"){let e=Ht.type;if(e==="renderer"||e==="worker")return!1;return!!(Ht.versions&&(Ht.versions.node||Ht.versions.bun))}return!1}class gf{async format(e){let t=await bm(),i=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:i})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:_i.pid,hostname:t(),environment:_i.env.NODE_ENV||"development",platform:_i.platform,version:_i.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:_i.env.NODE_ENV||_i.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class zn{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={...zs},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new gf,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??Ne.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let i={...t},r=t.timestamp!==void 0;if(r)delete i.timestamp;if(this.config={...this.config,...i,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),o=this.generateKey();this.currentKeyId=n,this.keys.set(n,o),this.encryptionKeys.set(n,{key:o,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},i=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[i]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Wn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Wn};return{...Wn,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:zs.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},i={...t,...Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0))};if(!i.level||!["debug","info","success","warning","error"].includes(i.level))i.level=t.level;return i}shouldWriteToFile(){return!tt()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let r,n=0,o=3,s=1000;while(n<o)try{try{try{await Rp(this.config.logDirectory,Nc.F_OK|Nc.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Pp(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Vt.from(e);try{if(!$n(this.currentLogFile))await Os(this.currentLogFile,"",{mode:420});if(r=Ic(this.currentLogFile,"a",420),Op(r,c,{flag:"a"}),Dc(r),r!==void 0)ks(r),r=void 0;if((await ji(this.currentLogFile)).size===0){if(await Os(this.currentLogFile,c,{flag:"w",mode:420}),(await ji(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(n<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${o}:`,u);let d=s*2**n;await new Promise((h)=>setTimeout(h,d)),n++;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(r!==void 0)try{ks(r)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(n===o-1){let f=c,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}n++;let l=s*2**(n-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(t);let i=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(i,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 Gi(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 Gi(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Gi(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(tt())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,i=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),i=this.generateKey();this.currentKeyId=t,this.keys.set(t,i),this.encryptionKeys.set(t,{key:i,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,s],[,c])=>c.createdAt.getTime()-s.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,o=Math.max(1,n);if(r.length>o)for(let[s]of r.slice(o))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return Ts(16).toString("hex")}generateKey(){return Ts(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(),i=Ts(16),r=Ap("aes-256-gcm",t,i),n=Vt.isBuffer(e)?e:Vt.from(e,"utf8"),o=r.update(n),s=r.final(),c=o.length+s.length,l=r.getAuthTag(),f=Vt.allocUnsafe(16+c+16);return i.copy(f,0),o.copy(f,16),s.copy(f,16+o.length),l.copy(f,16+c),{encrypted:f,iv:i}}async compressData(e){return new Promise((t,i)=>{let r=Wc(),n=[];r.on("data",(o)=>n.push(o)),r.on("end",()=>t(Vt.from(Vt.concat(n)))),r.on("error",i),r.write(e),r.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(tt())return;if(!this.shouldWriteToFile())return;let e=await ji(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 i=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await En(this.config.logDirectory),o=n.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,f)=>{let u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${i}.${s}`;if(await ji(i).catch(()=>null))try{if(await Fc(i,c),t.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await Sn(c)}catch(l){console.error("Error compressing rotated file:",l)}if(o.length===0&&!n.some((l)=>l.endsWith(".log.1")))try{let l=`${i}.1`;await Os(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),o=i.replace(/\.log$/,`-${n}.log`);if(await ji(i).catch(()=>null))await Fc(i,o)}if(this.currentLogFile=r,t.maxFiles){let n=(await En(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of n.slice(t.maxFiles))await Sn(Gi(this.config.logDirectory,o))}}}async compressLogFile(e,t){let i=Mc(e),r=kp(t),n=Wc();await Ip(i,n,r)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let i of this.logBuffer){let r=await this.formatter.format(i);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}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()})),$n(this.currentLogFile))try{let e=Ic(this.currentLogFile,"r+");Dc(e),ks(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(!tt()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await En(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Sn(Gi(this.config.logDirectory,t))}catch(i){console.error(`Failed to delete temp file ${t}:`,i)}}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()?xe.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||tt())return!1;let e=typeof Ne.env.NO_COLOR<"u",t=Ne.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof Ne.stderr<"u"&&Ne.stderr.isTTY||typeof Ne.stdout<"u"&&Ne.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:i="",tag:r="",message:n,level:o,showTimestamp:s=!0}=e,c=(p)=>p.replace(this.ANSI_PATTERN,"");if(!this.fancy){let p=[];if(s)p.push(t);if(o==="warning")p.push("WARN");else if(o==="error")p.push("ERROR");else if(i)p.push(i.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)p.push(r.replace(/[[\]]/g,""));return p.push(n),p.join(" ")}let l=Ne.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${i} ${n}`;else if(o==="info"||o==="success")f=`${i} ${r} ${n}`;else f=`${i} ${r} ${xe.cyan(n)}`;if(!s)return f.trim();let u=c(f).trim().length,d=c(t).length,h=Math.max(1,l-2-u-d);return`${f.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let c=Number.parseInt(s,10);return c<t[0].length?String(t[0][c]):o});let i=/%([sdijfo%])/g,r=0,n=e.replace(i,(o,s)=>{if(s==="%")return"%";if(r>=t.length)return o;let c=t[r++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return o}});if(r<t.length)n+=` ${t.slice(r).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(i,r,n)=>{let o=xe.underline(xe.blue(r)),s=this.toAbsoluteFilePath(n);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${c}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),t=t.replace(/`([^`]+)`/g,(i,r)=>xe.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(i,r)=>xe.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(i,r)=>xe.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(i,r)=>xe.italic(r)),t=t.replace(/~([^~]+)~/g,(i,r)=>xe.strikethrough(r)),t}supportsHyperlinks(){if(tt())return!1;let e=Ne.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 i=Ne.env.HOME||"";if(i)t=t.replace(/^~(?=$|\/)/,i)}if(Mp(t)||t.startsWith("./")||t.startsWith("../"))t=Dp(t);else return null;return $n(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,i=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:i}}async log(e,t,...i){let r=new Date,n=this.formatConsoleTimestamp(r),o=this.formatFileTimestamp(r),s,c;if(t instanceof Error)s=t.message,c=t.stack;else s=this.formatMessage(t,i);let{consoleText:l,fileText:f}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let d=this.options.showIcons===!1?"":Af[e],h=this.options.showTags!==!1&&this.name?xe.gray(this.formatTag(this.name)):"",p;switch(e){case"debug":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:xe.gray(l),level:e}),console.error(p);break;case"info":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:l,level:e}),console.warn(p);break;case"success":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:xe.green(l),level:e}),console.error(p);break;case"warning":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:l,level:e}),console.warn(p);break;case"error":if(p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:l,level:e}),console.error(p),c){let m=c.split(`
157
+ `);for(let a of m)if(a.trim()&&!a.includes(s))console.error(this.formatConsoleMessage({timestamp:n,message:xe.gray(` ${a}`),level:e,showTimestamp:!1}))}break}}else if(!tt()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(e))return;let u=`${o} ${this.environment}.${e.toUpperCase()}: ${f}
158
+ `;if(c)u+=`${c}
159
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let i={update:(n,o)=>{},finish:(n)=>{},interrupt:(n,o)=>{}};if(!this.enabled)return i;let r=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!tt()&&Ne.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(n,o)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,n),this.activeProgressBar.total),o!==void 0)this.activeProgressBar.message=o;if(this.shouldStyleConsole()&&!tt()&&Ne.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(n)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,n)},interrupt:(n,o="info")=>{if(!tt()&&Ne.stdout.isTTY)Ne.stdout.write(`
160
+ `);if(this[o==="warning"?"warn":o](n),this.activeProgressBar&&this.shouldStyleConsole()&&!tt()&&Ne.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let i=this.options.showTags!==!1&&this.name?xe.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":xe.blue("\u25D0"),tag:i,message:`${xe.cyan(e)}...`}))}return async(i)=>{if(!this.enabled)return;let r=performance.now(),n=Math.round(r-t),o=`${e} completed in ${n}ms`,s=new Date,c=this.formatConsoleTimestamp(s),l=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(i)l+=` ${JSON.stringify(i)}`;if(l+=`
161
+ `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?xe.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":xe.green("\u2713"),tag:f,message:`${o}${i?` ${JSON.stringify(i)}`:""}`}))}else if(!tt())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,i=new zn(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(i),i}createReadStream(){if(tt())throw Error("createReadStream is not supported in browser environments");if(!$n(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Mc(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 i=this.keys.get(this.currentKeyId);try{let r=Vt.isBuffer(e)?e:Vt.from(e,"base64"),n=r.subarray(0,16),o=r.subarray(r.length-16),s=r.subarray(16,r.length-16),c=Tp("aes-256-gcm",i,n);c.setAuthTag(o);let l=c.update(s),f=c.final(),u=l.length+f.length,d=Vt.allocUnsafe(u);return l.copy(d,0),f.copy(d,l.length),d.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return tt()}isServerMode(){return!tt()}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,i=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:n,fileText:o}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=n.split(`
162
+ `),l=Math.max(...c.map((h)=>h.length))+2,f=`\u250C${"\u2500".repeat(l)}\u2510`,u=`\u2514${"\u2500".repeat(l)}\u2518`,d=c.map((h)=>this.formatConsoleMessage({timestamp:i,message:xe.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:i,message:xe.cyan(f),showTimestamp:!1})),d.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:i,message:xe.cyan(u),showTimestamp:!1}))}else if(!tt())console.error(`${r} ${this.environment}.INFO: [BOX] ${o}`);let s=`${r} ${this.environment}.INFO: [BOX] ${o}
163
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(e){if(tt())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${xe.cyan("?")} ${e} (y/n) `);let i=(r)=>{let n=r.toString().trim().toLowerCase();Ne.stdin.removeListener("data",i);try{if(typeof Ne.stdin.setRawMode==="function")Ne.stdin.setRawMode(!1)}catch{}Ne.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof Ne.stdin.setRawMode==="function")Ne.stdin.setRawMode(!0)}catch{}Ne.stdin.resume(),Ne.stdin.once("data",i)})}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 i=e;if(t&&t.length>0){let s=/%([sdijfo%])/g,c=0;if(i=e.replace(s,(l,f)=>{if(f==="%")return"%";if(c>=t.length)return l;let u=t[c++];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 l}}),c<t.length)i+=` ${t.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:r,fileText:n}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?xe.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${xe.blue("\u25D0")} `;console.error(`${c}${s} ${xe.cyan(r)}`)}let o=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
164
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!Ne.stdout.isTTY)return;let i=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),r=Math.round(e.barLength*i/100),n=e.barLength-r,o=xe.green("\u2501".repeat(r)),s=xe.gray("\u2501".repeat(n)),c=`[${o}${s}]`,l=`${i}%`.padStart(4),f=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||i===100?xe.green("\u2713"):xe.blue("\u25B6"),d=this.options.showTags!==!1&&this.name?` ${xe.gray(this.formatTag(this.name))}`:"",h=`\r${u}${d} ${c} ${l}${f}`,p=Ne.stdout.columns||80,m=" ".repeat(Math.max(0,p-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${m}`,Ne.stdout.write(e.lastRenderedLine),t)Ne.stdout.write(`
165
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||tt()||!Ne.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(tt()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await En(this.config.logDirectory),i=[];for(let r of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let n=Gi(this.config.logDirectory,r);if(e.before)try{if((await ji(n)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${n}:`,o);continue}i.push(n)}if(i.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${i.length} log file(s)...`);for(let r of i)try{await Sn(r),console.warn(`Deleted log file: ${r}`)}catch(n){console.error(`Failed to delete log file ${r}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function yf(e,t={}){let{maxRetries:i=3,retryDelay:r=1000,isRetryable:n=()=>!0,fallback:o}=t,s=Error("Unknown error occurred");for(let c=0;c<=i;c++)try{return await e()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===i||!n(s))break;if(r>0)await new Promise((f)=>setTimeout(f,r))}if(o!==void 0)return o;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}function wf(e){return e instanceof vt}function $m(e){return e instanceof Hn}function Em(e){if(wf(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 Zn{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,i={}){let{prefix:r,useCamelCase:n=!0,useBackwardCompatibility:o=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=i,f=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=r||this.generateEnvPrefix(e),d={...t};return this.processObject(d,[],u,{useCamelCase:n,useBackwardCompatibility:o,customParsers:s,verbose:c,configName:e}),{config:d,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return Sr.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,i,r){for(let[n,o]of Object.entries(e)){let s=[...t,n],c=s.map((u)=>this.formatEnvKey(u,r.useCamelCase)),l=`${i}_${c.join("_")}`,f=r.useBackwardCompatibility?`${i}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.processObject(o,s,i,r);else{let u=xn.env[l]||(f?xn.env[f]:void 0);if(u!==void 0){if(r.verbose){let d=xn.env[l]?l:f}try{e[n]=this.parseEnvironmentValue(u,typeof o,l,r.customParsers,r.configName)}catch(d){if(d instanceof qn)throw d;throw oi.envVar(l,u,typeof o,r.configName)}}}}}parseEnvironmentValue(e,t,i,r,n){for(let[o,s]of Object.entries(r))try{return s(e)}catch{continue}for(let o of this.defaultParsers)if(o.canParse(e,t))try{return o.parse(e)}catch{throw oi.envVar(i,e,`${t} (via ${o.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},i=e.toUpperCase();for(let[r,n]of Object.entries(xn.env))if(r.startsWith(i)&&n!==void 0)t[r]=n;return t}validateEnvironmentVariable(e,t,i){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))r.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(i)try{this.parseEnvironmentValue(e,t,i,{})}catch(n){r.push(`Cannot parse value "${t}" as ${i}: ${n}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(e,t,i={}){let{prefix:r,format:n="text"}=i,o=r||this.generateEnvPrefix(e),s=[];switch(this.extractEnvVarInfo(t,[],o,s),n){case"markdown":return this.formatAsMarkdown(s,e);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,e)}}extractEnvVarInfo(e,t,i,r){for(let[n,o]of Object.entries(e)){let s=[...t,n],c=`${i}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.extractEnvVarInfo(o,s,i,r);else r.push({key:c,type:Array.isArray(o)?"array":typeof o,description:`Configuration for ${s.join(".")}`,example:this.generateExample(o)})}}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 i=`Environment Variables for ${t}:
53
166
 
54
- `;for(let n of e)r+=`${n.key}
55
- `,r+=` Type: ${n.type}
56
- `,r+=` Description: ${n.description}
57
- `,r+=` Example: ${n.example}
167
+ `;for(let r of e)i+=`${r.key}
168
+ `,i+=` Type: ${r.type}
169
+ `,i+=` Description: ${r.description}
170
+ `,i+=` Example: ${r.example}
58
171
 
59
- `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
172
+ `;return i}formatAsMarkdown(e,t){let i=`# Environment Variables for ${t}
60
173
 
61
- `;r+=`| Variable | Type | Description | Example |
62
- `,r+=`|----------|------|-------------|----------|
63
- `;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
64
- `;return r}}function Yu(e,t){let r=Ha("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function _a(e,t,r={}){return Va(e,t,r,new WeakMap)}function Va(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:o=!1,customMerger:s}=r;if(t===null||t===void 0)return o?e:t;if(s){let a=s(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return Ua(e,t,i,n);if(!at(t)||!at(e))return t;return eh(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 Zu(e,t);case"smart":return Xu(e,t,n);default:return t}return t}function Zu(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Jn(i,n)))r.push(n);return r}function Xu(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(at(t[0])&&at(e[0]))return Qu(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 Qu(e,t,r){let n=[...t];for(let i of e){if(!at(i)){n.push(i);continue}let o=["id","name","key","path","type"],s=!1;for(let a of o)if(a in i){if(n.find((c)=>at(c)&&(a in c)&&c[a]===i[a])){s=!0;break}}if(!s)n.push(i)}return n}function eh(e,t,r,n){let i=t;if(at(i)&&n.has(i))return n.get(i);let o={...e};if(at(i))n.set(i,o);for(let s in i){if(!Object.prototype.hasOwnProperty.call(i,s))continue;let a=i[s],c=o[s];if(r.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){o[s]=a;continue}if(at(a)&&at(c))o[s]=Va(c,a,r,n);else if(Array.isArray(a)||Array.isArray(c))o[s]=Ua(c,a,r.arrayMergeMode||"smart",n);else o[s]=a}return o}function co(e,t,r="replace"){return _a(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(at(e)&&at(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 at(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Mi{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:o,trackPerformance:s=!0,verbose:a=!1}=r;if(i){let f=lr.getWithFileCheck("file",e);if(f){if(a)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!ii(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),h=u.default||u,l="default"in u,y=Object.keys(u).length>0;if(!l&&!y)throw new $r(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new $r(e,Error("Configuration must export a valid object"),"unknown");let C={config:co(t,h,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)lr.setWithFileCheck("file",C,e,o);return C}catch(f){throw f instanceof Error?Mt.configLoad(e,f):Mt.configLoad(e,Error(String(f)))}};if(s)return xr.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 o of n)for(let s of this.extensions)i.push(Fn(t,`${o}${s}`));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()=>ii(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!ii(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let o of i)for(let s of this.extensions){let a=Fn(e,`${o}${s}`);if(await this.checkFileAccess(a))n.push(a)}}else try{let{readdirSync:i}=await import("fs"),o=i(e);for(let s of o)if(this.looksLikeConfigFile(s)){let a=Fn(e,s);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(!ii(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"),o=i(e,"utf8");JSON.parse(o)}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 fo{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:a=!0,verbose:c=!1}=r,f=async()=>{let u=[],h=[],l={stopOnFirstError:n,validateRequired:i,validateTypes:o,customRules:s,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,l);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],l);else return this.validateWithJSONSchema(e,t,l)}catch(y){return u.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:u,warnings:h}}};if(a)return await xr.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!mu(t))throw new Ar(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 Ar(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,o){if(o.validateTypes&&t.type){let s=Array.isArray(e)?"array":typeof e,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(s)){if(n.push({path:r,message:`Expected type ${a.join(" or ")}, got ${s}`,expected:a.join(" or "),actual:s,rule:"type"}),o.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"}),o.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 s=0;s<e.length;s++){let a=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,a,n,i,o),o.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let s=e;if(o.validateRequired&&t.required){for(let a of t.required)if(!(a in s)){if(n.push({path:r?`${r}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[a,c]of Object.entries(t.properties))if(a in s){let f=r?`${r}.${a}`:a;if(this.validateObjectAgainstSchema(s[a],c,f,n,i,o),o.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(s))if(!a.has(c))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let o of t)try{let s=this.getValueByPath(e,o.path),a=this.validateWithRule(s,o,o.path);if(n.push(...a),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:o.path,message:`Rule validation failed: ${s}`,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,o,s]=n;t.push({path:i,required:!o,type:this.mapTypeScriptType(s)})}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:Za},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class uo{fileLoader=new Mi;envProcessor=new ki;validator=new fo;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:o,...s}=e;try{if(r?.enabled){let c=this.checkCache(s.name||"",s);if(c)return c}let a;try{a=await this.loadConfigurationStrategies(s,!0,r)}catch(c){let f=s.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.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"),h=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),l=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(l||u))throw c;if(h&&(!f||!l))a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(i||o)await this.validateConfiguration(a.config,i,o,s.name);if(r?.enabled&&a)this.cacheResult(s.name||"",a,r,s);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)ut.warn(`Slow configuration loading detected: ${c.duration}ms for ${s.name}`);a.metrics=c}return a}catch(a){let c=Date.now()-t;throw ut.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:o,configDir:s,defaultConfig:a,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,h=o||Bt.cwd(),l=[],y=await this.loadLocalConfiguration(n,i,h,s,a,f,u,c,r);if(y)return l.push(...this.getLocalSearchPaths(n,i,h,s)),this.finalizeResult(y,l,c,n,u);let C=await this.loadHomeConfiguration(n,i,a,f,u,c);if(C)return l.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(C,l,c,n,u);let S=await this.loadPackageJsonConfiguration(n,i,h,a,f,u,c);if(S)return l.push(Ze(h,"package.json")),this.finalizeResult(S,l,c,n,u);if(l.push(...this.getAllSearchPaths(n,i,h,s)),t)throw Mt.configNotFound(n,l,i);return{...await this.applyEnvironmentVariables(n,a,c,u),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,o,s,a,c){let f=a?Er(e,i,s):i,u=this.getLocalDirectories(r,n);for(let h of u){if(s)ut.info(`Searching for configuration in: ${h}`);let l=this.fileLoader.generateConfigPaths(e,h,t),y=await this.fileLoader.tryLoadFromPaths(l,f,{arrayStrategy:o,verbose:s,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(y){if(s)ut.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(e,t,r,n,i,o){if(!e)return null;let s=o?Er(e,r,i):r,a=[Ze(Xt(),".config",e),Ze(Xt(),".config"),Xt()];for(let c of a){if(i)ut.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,s,{arrayStrategy:n,verbose:i});if(u){if(i)ut.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,o,s){let a=s?Er(e,n,o):n;try{let c=Ze(r,"package.json");if(!Hn(c))return null;let f=await import(c),u=f[e],h=e;if(!u&&t)u=f[t],h=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(o)ut.success(`Configuration loaded from package.json: ${h}`);return{config:co(a,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(o)ut.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:Er(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 o=r(e);if(o)i.push(...o)}if(t){let o=await this.validator.validateConfiguration(e,t);if(!o.isValid)i.push(...o.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(i.length>0)throw Mt.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return lr.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);lr.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,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),o=[];for(let s of i)o.push(...this.fileLoader.generateConfigPaths(e,s,t));return o}getHomeSearchPaths(e,t){if(!e)return[];let r=[Ze(Xt(),".config",e),Ze(Xt(),".config"),Xt()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function va(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 th(e){return $t.loadConfig({...e,__strictErrorHandling:!0})}async function Ka(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",o=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||o.includes("config"))&&e.verbose)ut.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let s=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(s.name||"",t,!0,s.verbose||!1))?.config??t;return t}}async function rh(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"&&va(r)))return(await $t.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await $t.loadConfig({...e,cwd:e.cwd||Bt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&va(t)))return(await $t.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function ih(e,t,r="replace"){let n=new Mi;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function Er(e,t,r=!1){let n=new ki,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,a=[]){let c={...s};for(let[f,u]of Object.entries(s)){let h=[...a,f],l=[`${i}_${h.join("_").toUpperCase()}`,`${i}_${h.map((S)=>S.toUpperCase()).join("")}`,`${i}_${h.map((S)=>S.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,C;for(let S of l)if(y=Bt.env[S],y!==void 0){C=S;break}if(y!==void 0&&C)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(y.toLowerCase());else if(typeof u==="number"){let S=Number(y);if(!Number.isNaN(S))c[f]=S}else if(Array.isArray(u))try{c[f]=JSON.parse(y)}catch{c[f]=y.split(",").map((S)=>S.trim())}else c[f]=y;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=o(u,h)}return c}return o(t)}function nh(e){let t=Ze(Bt.cwd(),e.configDir),r=Ze(Bt.cwd(),e.generatedDir),n=Ze(r,"config-types.ts");if(!Hn(Zs(n)))Kf(Zs(n),{recursive:!0,mode:511});let i=Hn(t)?Hf(t).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],o=`// Generated by bunfig v${Dh}
65
- export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
66
- `;zf(n,o,{mode:438})}function oh(e){let t=null,r=null,n=()=>{if(!r)r=Ka(e).then((o)=>(t=o,o),(o)=>{let s="defaultConfig"in e?e.defaultConfig:{};if(t=s,"verbose"in e&&e.verbose)ut.warn("Config loading failed, using defaults:",[o instanceof Error?o:Error(String(o))]);return s});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(o,s){if(t)return t[s];let a=i[s];return n(),a},has(o,s){return s in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(o,s){return Object.getOwnPropertyDescriptor(t||i,s)},set(o,s,a){if(!t)t={...i};return t[s]=a,!0}})}function sh(e){let t=ha(yu.cwd(),e?.configDir||"./config");function r(){if(!pu(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),o=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=gu(t).filter((c)=>i.has(Nn(c))).map((c)=>({base:c.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:c})),a=new Map;for(let{base:c,file:f}of s){let u=Nn(f).toLowerCase(),h=a.get(c);if(!h){a.set(c,f);continue}let l=Nn(h).toLowerCase();if(o.indexOf(u)<o.indexOf(l))a.set(c,f)}return Array.from(a.entries()).map(([c,f])=>({base:c,file:f})).sort((c,f)=>c.base.localeCompare(f.base))}function n(){let i=r(),o=i.map((c)=>c.base),s=o.length?o.map((c)=>`'${c}'`).join(" | "):"string",a=i.length?`{
67
- ${i.map((c)=>{let f=ha(t,c.file).replace(/\\/g,"/");return` '${c.base}': typeof import('${f}').default`}).join(`,
174
+ `;i+=`| Variable | Type | Description | Example |
175
+ `,i+=`|----------|------|-------------|----------|
176
+ `;for(let r of e)i+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
177
+ `;return i}}function Sm(e,t){let i=Ef("process");if(typeof i>"u"||!i.env)return t;let r=i.env[e];return r!==void 0?r:t}function Cf(e,t,i={}){return vf(e,t,i,new WeakMap)}function vf(e,t,i,r){let{arrayMergeMode:n="replace",skipNullish:o=!1,customMerger:s}=i;if(t===null||t===void 0)return o?e:t;if(s){let c=s(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return bf(e,t,n,r);if(!St(t)||!St(e))return t;return km(e,t,i,r)}function bf(e,t,i,r){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(i){case"replace":return t;case"concat":return xm(e,t);case"smart":return Am(e,t,r);default:return t}return t}function xm(e,t){let i=[...t];for(let r of e)if(!i.some((n)=>Us(n,r)))i.push(r);return i}function Am(e,t,i){if(t.length===0)return e;if(e.length===0)return t;if(St(t[0])&&St(e[0]))return Tm(e,t,i);if(t.every((r)=>typeof r==="string")&&e.every((r)=>typeof r==="string")){let r=[...t];for(let n of e)if(!r.includes(n))r.push(n);return r}return t}function Tm(e,t,i){let r=[...t];for(let n of e){if(!St(n)){r.push(n);continue}let o=["id","name","key","path","type"],s=!1;for(let c of o)if(c in n){if(r.find((l)=>St(l)&&(c in l)&&l[c]===n[c])){s=!0;break}}if(!s)r.push(n)}return r}function km(e,t,i,r){let n=t;if(St(n)&&r.has(n))return r.get(n);let o={...e};if(St(n))r.set(n,o);for(let s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;let c=n[s],l=o[s];if(i.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){o[s]=c;continue}if(St(c)&&St(l))o[s]=vf(l,c,i,r);else if(Array.isArray(c)||Array.isArray(l))o[s]=bf(l,c,i.arrayMergeMode||"smart",r);else o[s]=c}return o}function oa(e,t,i="replace"){return Cf(e,t,{arrayMergeMode:i==="replace"?"replace":"smart",skipNullish:!0})}function Us(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!Us(e[i],t[i]))return!1;return!0}if(St(e)&&St(t)){let i=Object.keys(e),r=Object.keys(t);if(i.length!==r.length)return!1;for(let n of i){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Us(e[n],t[n]))return!1}return!0}return!1}function St(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Qn{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,i={}){let{arrayStrategy:r="replace",useCache:n=!0,cacheTtl:o,trackPerformance:s=!0,verbose:c=!1}=i;if(n){let f=Hi.getWithFileCheck("file",e);if(f){if(c)console.log(`Configuration loaded from cache: ${e}`);return f}}let l=async()=>{if(!An(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),d=u.default||u,h="default"in u,p=Object.keys(u).length>0;if(!h&&!p)throw new $r(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof d!=="object"||d===null||Array.isArray(d))throw new $r(e,Error("Configuration must export a valid object"),"unknown");let m={config:oa(t,d,r),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)Hi.setWithFileCheck("file",m,e,o);return m}catch(f){throw f instanceof Error?oi.configLoad(e,f):oi.configLoad(e,Error(String(f)))}};if(s)return Sr.track("loadFromPath",l,{path:e});return l()}async tryLoadFromPaths(e,t,i={}){for(let r of e)try{let n=await this.loadFromPath(r,t,i);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(i.verbose)console.warn(`Failed to load config from ${r}:`,n)}return null}generateConfigPaths(e,t,i){let r=this.generateNamePatterns(e,i),n=[];for(let o of r)for(let s of this.extensions)n.push(Rs(t,`${o}${s}`));return n}generateNamePatterns(e,t){let i=[];if(i.push("config",".config"),e)i.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(i.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)i.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return i.filter(Boolean)}checkFileAccess(e){return yf(async()=>An(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,i){let r=[];if(!An(e))return r;if(t||i){let n=this.generateNamePatterns(t||"",i);for(let o of n)for(let s of this.extensions){let c=Rs(e,`${o}${s}`);if(await this.checkFileAccess(c))r.push(c)}}else try{let{readdirSync:n}=await import("fs"),o=n(e);for(let s of o)if(this.looksLikeConfigFile(s)){let c=Rs(e,s);if(await this.checkFileAccess(c))r.push(c)}}catch{return[]}return r}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(!An(e))return t.push("Configuration file does not exist"),t;let i=await import(e),r=i.default||i;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),o=n(e,"utf8");JSON.parse(o)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(i){t.push(`Failed to load configuration file: ${i}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let i=new Map;return await Promise.allSettled(e.map(async(r)=>{try{let n=await this.loadFromPath(r,{},t);if(n)i.set(r,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${r}:`,n)}})),i}}class sa{async validateConfiguration(e,t,i={}){let{stopOnFirstError:r=!1,validateRequired:n=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=i,f=async()=>{let u=[],d=[],h={stopOnFirstError:r,validateRequired:n,validateTypes:o,customRules:s,trackPerformance:c,verbose:l};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],h);else return this.validateWithJSONSchema(e,t,h)}catch(p){return u.push({path:"",message:`Validation failed: ${p}`,rule:"system"}),{isValid:!1,errors:u,warnings:d}}};if(c)return await Sr.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,i){try{if(!Np(t))throw new Er(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),n=r.default||r;if(Array.isArray(n))return this.validateWithRules(e,n,i);else return this.validateWithJSONSchema(e,n,i)}catch(r){throw new Er(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(e,t,i){let r=[],n=[];return this.validateObjectAgainstSchema(e,t,"",r,n,i),{isValid:r.length===0,errors:r,warnings:n}}validateObjectAgainstSchema(e,t,i,r,n,o){if(o.validateTypes&&t.type){let s=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(s)){if(r.push({path:i,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),o.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(r.push({path:i,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),o.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)r.push({path:i,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)r.push({path:i,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))r.push({path:i,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)r.push({path:i,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)r.push({path:i,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let s=0;s<e.length;s++){let c=i?`${i}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,c,r,n,o),o.stopOnFirstError&&r.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let s=e;if(o.validateRequired&&t.required){for(let c of t.required)if(!(c in s)){if(r.push({path:i?`${i}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[c,l]of Object.entries(t.properties))if(c in s){let f=i?`${i}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,f,r,n,o),o.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let l of Object.keys(s))if(!c.has(l))n.push({path:i?`${i}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,i){let r=[],n=[];for(let o of t)try{let s=this.getValueByPath(e,o.path),c=this.validateWithRule(s,o,o.path);if(r.push(...c),i.stopOnFirstError&&r.length>0)break}catch(s){r.push({path:o.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:n}}validateWithRule(e,t,i){let r=[];if(t.required&&(e===void 0||e===null))return r.push({path:i,message:t.message||`Property '${i}' is required`,expected:"required",rule:"required"}),r;if(e===void 0||e===null)return r;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)r.push({path:i,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)r.push({path:i,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)r.push({path:i,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))r.push({path:i,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))r.push({path:i,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)r.push({path:i,message:t.message||n,rule:"custom"})}return r}getValueByPath(e,t){if(!t)return e;let i=t.split("."),r=e;for(let n of i)if(r&&typeof r==="object"&&n in r)r=r[n];else return;return r}generateRulesFromInterface(e){let t=[],i=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of i){let[,n,o,s]=r;t.push({path:n,required:!o,type:this.mapTypeScriptType(s)})}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:kf},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class aa{fileLoader=new Qn;envProcessor=new Zn;validator=new sa;async loadConfig(e){let t=Date.now(),{cache:i,performance:r,schema:n,validate:o,...s}=e;try{if(i?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,i)}catch(l){let f=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(f)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let u=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),d=!u&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),h=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(f&&(h||u))throw l;if(d&&(!f||!h))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(n||o)await this.validateConfiguration(c.config,n,o,s.name);if(i?.enabled&&c)this.cacheResult(s.name||"",c,i,s);if(r?.enabled){let l={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(l);if(r.slowThreshold&&l.duration>r.slowThreshold)Mt.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){let l=Date.now()-t;throw Mt.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,i){let{name:r="",alias:n,cwd:o,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:f="replace",verbose:u=!1}=e,d=o||$i.cwd(),h=[],p=await this.loadLocalConfiguration(r,n,d,s,c,f,u,l,i);if(p)return h.push(...this.getLocalSearchPaths(r,n,d,s)),this.finalizeResult(p,h,l,r,u);let m=await this.loadHomeConfiguration(r,n,c,f,u,l);if(m)return h.push(...this.getHomeSearchPaths(r,n)),this.finalizeResult(m,h,l,r,u);let a=await this.loadPackageJsonConfiguration(r,n,d,c,f,u,l);if(a)return h.push(pt(d,"package.json")),this.finalizeResult(a,h,l,r,u);if(h.push(...this.getAllSearchPaths(r,n,d,s)),t)throw oi.configNotFound(r,h,n);return{...await this.applyEnvironmentVariables(r,c,l,u),warnings:[`No configuration file found for "${r}"${n?` or alias "${n}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,i,r,n,o,s,c,l){let f=c?Cr(e,n,s):n,u=this.getLocalDirectories(i,r);for(let d of u){if(s)Mt.info(`Searching for configuration in: ${d}`);let h=this.fileLoader.generateConfigPaths(e,d,t),p=await this.fileLoader.tryLoadFromPaths(h,f,{arrayStrategy:o,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(p){if(s)Mt.success(`Configuration loaded from: ${p.source.path}`);return p}}return null}async loadHomeConfiguration(e,t,i,r,n,o){if(!e)return null;let s=o?Cr(e,i,n):i,c=[pt(Fi(),".config",e),pt(Fi(),".config"),Fi()];for(let l of c){if(n)Mt.info(`Checking home directory: ${l}`);let f=this.fileLoader.generateConfigPaths(e,l,t),u=await this.fileLoader.tryLoadFromPaths(f,s,{arrayStrategy:r,verbose:n});if(u){if(n)Mt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,i,r,n,o,s){let c=s?Cr(e,r,o):r;try{let l=pt(i,"package.json");if(!_s(l))return null;let f=await import(l),u=f[e],d=e;if(!u&&t)u=f[t],d=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(o)Mt.success(`Configuration loaded from package.json: ${d}`);return{config:oa(c,u,n),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(o)Mt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(e,t,i,r){if(!i||!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,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,i,r,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,i,r){let n=[];if(i){let o=i(e);if(o)n.push(...o)}if(t){let o=await this.validator.validateConfiguration(e,t);if(!o.isValid)n.push(...o.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(n.length>0)throw oi.configValidation(r||"unknown",n,r)}checkCache(e,t){let i=this.generateCacheKey(e,t);return Hi.get(i)||null}cacheResult(e,t,i,r){let n=this.generateCacheKey(e,r);Hi.set(n,t,void 0,i.ttl)}generateCacheKey(e,t){let i=[e];if(t.alias)i.push(`alias:${t.alias}`);if(t.cwd)i.push(`cwd:${t.cwd}`);if(t.configDir)i.push(`configDir:${t.configDir}`);if("checkEnv"in t)i.push(`checkEnv:${t.checkEnv}`);return i.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,pt(e,"config"),pt(e,".config"),t?pt(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,i,r){let n=[];return n.push(...this.getLocalSearchPaths(e,t,i,r)),n.push(...this.getHomeSearchPaths(e,t)),n.push(pt(i,"package.json")),n}getLocalSearchPaths(e,t,i,r){let n=this.getLocalDirectories(i,r),o=[];for(let s of n)o.push(...this.fileLoader.generateConfigPaths(e,s,t));return o}getHomeSearchPaths(e,t){if(!e)return[];let i=[pt(Fi(),".config",e),pt(Fi(),".config"),Fi()],r=[];for(let n of i)r.push(...this.fileLoader.generateConfigPaths(e,n,t));return r}async loadConfigWithResult(e){return this.loadConfig(e)}}function Hc(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")),i=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return t||i}async function Om(e){return Jt.loadConfig({...e,__strictErrorHandling:!0})}async function $f(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},i="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let r;if(i)r=await Jt.loadConfig(e);else r=await Jt.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??t}catch(r){let n=r instanceof Error?r.name:"UnknownError",o=r instanceof Error?r.message:String(r);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||o.includes("config"))&&e.verbose)Mt.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let s=i?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await Jt.applyEnvironmentVariables(s.name||"",t,!0,s.verbose||!1))?.config??t;return t}}async function Rm(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await Jt.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&Hc(i)))return(await Jt.applyEnvironmentVariables(e,{},!0,!1)).config;throw i}}try{return(await Jt.loadConfig({...e,cwd:e.cwd||$i.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Hc(t)))return(await Jt.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Pm(e,t,i="replace"){let r=new Qn;try{let n=await r.loadFromPath(e,t,{arrayStrategy:i,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function Cr(e,t,i=!1){let r=new Zn,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,c=[]){let l={...s};for(let[f,u]of Object.entries(s)){let d=[...c,f],h=[`${n}_${d.join("_").toUpperCase()}`,`${n}_${d.map((a)=>a.toUpperCase()).join("")}`,`${n}_${d.map((a)=>a.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],p,m;for(let a of h)if(p=$i.env[a],p!==void 0){m=a;break}if(p!==void 0&&m)if(typeof u==="boolean")l[f]=["true","1","yes"].includes(p.toLowerCase());else if(typeof u==="number"){let a=Number(p);if(!Number.isNaN(a))l[f]=a}else if(Array.isArray(u))try{l[f]=JSON.parse(p)}catch{l[f]=p.split(",").map((a)=>a.trim())}else l[f]=p;else if(u&&typeof u==="object"&&!Array.isArray(u))l[f]=o(u,d)}return l}return o(t)}function Mm(e){let t=pt($i.cwd(),e.configDir),i=pt($i.cwd(),e.generatedDir),r=pt(i,"config-types.ts");if(!_s(Ec(r)))dp(Ec(r),{recursive:!0,mode:511});let n=_s(t)?hp(t).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],o=`// Generated by bunfig v${ag}
178
+ export type ConfigNames = ${n.length?`'${n.join("' | '")}'`:"string"}
179
+ `;pp(r,o,{mode:438})}function Dm(e){let t=null,i=null,r=()=>{if(!i)i=$f(e).then((o)=>(t=o,o),(o)=>{let s="defaultConfig"in e?e.defaultConfig:{};if(t=s,"verbose"in e&&e.verbose)Mt.warn("Config loading failed, using defaults:",[o instanceof Error?o:Error(String(o))]);return s});return i},n="defaultConfig"in e?e.defaultConfig:{};return t=n,r(),new Proxy({},{get(o,s){if(t)return t[s];let c=n[s];return r(),c},has(o,s){return s in(t||n)},ownKeys(){return Object.keys(t||n)},getOwnPropertyDescriptor(o,s){return Object.getOwnPropertyDescriptor(t||n,s)},set(o,s,c){if(!t)t={...n};return t[s]=c,!0}})}function Im(e){let t=Lc(Lp.cwd(),e?.configDir||"./config");function i(){if(!Fp(t))return[];let n=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),o=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=Wp(t).filter((l)=>n.has(Ps(l))).map((l)=>({base:l.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:l})),c=new Map;for(let{base:l,file:f}of s){let u=Ps(f).toLowerCase(),d=c.get(l);if(!d){c.set(l,f);continue}let h=Ps(d).toLowerCase();if(o.indexOf(u)<o.indexOf(h))c.set(l,f)}return Array.from(c.entries()).map(([l,f])=>({base:l,file:f})).sort((l,f)=>l.base.localeCompare(f.base))}function r(){let n=i(),o=n.map((l)=>l.base),s=o.length?o.map((l)=>`'${l}'`).join(" | "):"string",c=n.length?`{
180
+ ${n.map((l)=>{let f=Lc(t,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${f}').default`}).join(`,
68
181
  `)}
69
182
  }`:"Record<string, any>";return`export type ConfigNames = ${s}
70
- export type ConfigByName = ${a}
183
+ export type ConfigByName = ${c}
71
184
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
72
185
  export type ConfigOf = Config
73
- `}return{name:"bunfig-plugin",setup(i){i.onResolve({filter:/^virtual:bunfig-types$/},(o)=>({path:o.path,namespace:"bunfig-virtual"})),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:n(),loader:"ts"}))}}}function Fh(e,t={}){let r=wi.cwd();while(r.includes("storage"))r=da(r,"..");let n=da(r,e||"");if(t?.relative)return wu(wi.cwd(),n);return n}function We(){if(St.env.NODE_ENV==="test"||St.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Lh(){if(St.env.NODE_ENV==="test"||St.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof St<"u"){let e=St.type;if(e==="renderer"||e==="worker")return!1;return!!(St.versions&&(St.versions.node||St.versions.bun))}return!1}class tl{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:ar.pid,hostname:t(),environment:ar.env.NODE_ENV||"development",platform:ar.platform,version:ar.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ar.env.NODE_ENV||ar.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={...Ti},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new tl,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??ye.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(),o=this.generateKey();this.currentKeyId=i,this.keys.set(i,o),this.encryptionKeys.set(i,{key:o,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{...Kn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Kn};return{...Kn,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Ti.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,o=3,s=1000;while(i<o)try{try{try{await $u(this.config.logDirectory,ya.F_OK|ya.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Au(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:wt.from(e);try{if(!ni(this.currentLogFile))await Bn(this.currentLogFile,"",{mode:420});if(n=ga(this.currentLogFile,"a",420),Su(n,a,{flag:"a"}),pa(n),n!==void 0)Wn(n),n=void 0;if((await or(this.currentLogFile)).size===0){if(await Bn(this.currentLogFile,a,{flag:"w",mode:420}),(await or(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<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,u);let h=s*2**i;await new Promise((l)=>setTimeout(l,h)),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{Wn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}i++;let c=s*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 sr(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 sr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return sr(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(([,s],[,a])=>a.createdAt.getTime()-s.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,o=Math.max(1,i);if(n.length>o)for(let[s]of n.slice(o))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return Ln(16).toString("hex")}generateKey(){return Ln(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=Ln(16),n=vu("aes-256-gcm",t,r),i=wt.isBuffer(e)?e:wt.from(e,"utf8"),o=n.update(i),s=n.final(),a=o.length+s.length,c=n.getAuthTag(),f=wt.allocUnsafe(16+a+16);return r.copy(f,0),o.copy(f,16),s.copy(f,16+o.length),c.copy(f,16+a),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=wa(),i=[];n.on("data",(o)=>i.push(o)),n.on("end",()=>t(wt.from(wt.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 or(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),o=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}),s=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${s}`;if(await or(r).catch(()=>null))try{if(await Ca(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await si(a)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await Bn(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,"-"),o=r.replace(/\.log$/,`-${i}.log`);if(await or(r).catch(()=>null))await Ca(r,o)}if(this.currentLogFile=n,t.maxFiles){let i=(await oi(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of i.slice(t.maxFiles))await si(sr(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=ma(e),n=Eu(t),i=wa();await Ou(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()})),ni(this.currentLogFile))try{let e=ga(this.currentLogFile,"r+");pa(e),Wn(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 oi(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await si(sr(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()?de.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||We())return!1;let e=typeof ye.env.NO_COLOR<"u",t=ye.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof ye.stderr<"u"&&ye.stderr.isTTY||typeof ye.stdout<"u"&&ye.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:o,showTimestamp:s=!0}=e,a=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(s)y.push(t);if(o==="warning")y.push("WARN");else if(o==="error")y.push("ERROR");else if(r)y.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)y.push(n.replace(/[[\]]/g,""));return y.push(i),y.join(" ")}let c=ye.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${r} ${i}`;else if(o==="info"||o==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${de.cyan(i)}`;if(!s)return f.trim();let u=a(f).trim().length,h=a(t).length,l=Math.max(1,c-2-u-h);return`${f.trim()}${" ".repeat(l)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let a=Number.parseInt(s,10);return a<t[0].length?String(t[0][a]):o});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let a=t[n++];switch(s){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 o}});if(n<t.length)i+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let o=de.underline(de.blue(n)),s=this.toAbsoluteFilePath(i);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(s)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${a}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),t=t.replace(/`([^`]+)`/g,(r,n)=>de.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>de.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>de.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>de.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>de.strikethrough(n)),t}supportsHyperlinks(){if(We())return!1;let e=ye.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=ye.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(xu(t)||t.startsWith("./")||t.startsWith("../"))t=Tu(t);else return null;return ni(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),o=this.formatFileTimestamp(n),s,a;if(t instanceof Error)s=t.message,a=t.stack;else s=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let h=this.options.showIcons===!1?"":_h[e],l=this.options.showTags!==!1&&this.name?de.gray(this.formatTag(this.name)):"",y;switch(e){case"debug":y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:de.gray(c),level:e}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:c,level:e}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:de.green(c),level:e}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:c,level:e}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:i,icon:h,tag:l,message:c,level:e}),console.error(y),a){let C=a.split(`
74
- `);for(let S of C)if(S.trim()&&!S.includes(s))console.error(this.formatConsoleMessage({timestamp:i,message:de.gray(` ${S}`),level:e,showTimestamp:!1}))}break}}else if(!We()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${s}`),a)console.error(a)}let u=`${o} ${this.environment}.${e.toUpperCase()}: ${f}
75
- `;if(a)u+=`${a}
76
- `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(i,o)=>{},finish:(i)=>{},interrupt:(i,o)=>{}};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()&&ye.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(i,o)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,i),this.activeProgressBar.total),o!==void 0)this.activeProgressBar.message=o;if(this.shouldStyleConsole()&&!We()&&ye.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,o="info")=>{if(!We()&&ye.stdout.isTTY)ye.stdout.write(`
77
- `);if(this[o==="warning"?"warn":o](i),this.activeProgressBar&&this.shouldStyleConsole()&&!We()&&ye.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?de.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":de.blue("\u25D0"),tag:r,message:`${de.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),o=`${e} completed in ${i}ms`,s=new Date,a=this.formatConsoleTimestamp(s),c=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
78
- `,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?de.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":de.green("\u2713"),tag:f,message:`${o}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!We())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(We())throw Error("createReadStream is not supported in browser environments");if(!ni(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ma(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=wt.isBuffer(e)?e:wt.from(e,"base64"),i=n.subarray(0,16),o=n.subarray(n.length-16),s=n.subarray(16,n.length-16),a=bu("aes-256-gcm",r,i);a.setAuthTag(o);let c=a.update(s),f=a.final(),u=c.length+f.length,h=wt.allocUnsafe(u);return c.copy(h,0),f.copy(h,c.length),h.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:o}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let a=i.split(`
79
- `),c=Math.max(...a.map((l)=>l.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,h=a.map((l)=>this.formatConsoleMessage({timestamp:r,message:de.cyan(l),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:de.cyan(f),showTimestamp:!1})),h.forEach((l)=>console.error(l)),console.error(this.formatConsoleMessage({timestamp:r,message:de.cyan(u),showTimestamp:!1}))}else if(!We())console.error(`${n} ${this.environment}.INFO: [BOX] ${o}`);let s=`${n} ${this.environment}.INFO: [BOX] ${o}
80
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(e){if(We())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${de.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();ye.stdin.removeListener("data",r);try{if(typeof ye.stdin.setRawMode==="function")ye.stdin.setRawMode(!1)}catch{}ye.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof ye.stdin.setRawMode==="function")ye.stdin.setRawMode(!0)}catch{}ye.stdin.resume(),ye.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 s=/%([sdijfo%])/g,a=0;if(r=e.replace(s,(c,f)=>{if(f==="%")return"%";if(a>=t.length)return c;let u=t[a++];switch(f){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return c}}),a<t.length)r+=` ${t.slice(a).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?de.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${de.blue("\u25D0")} `;console.error(`${a}${s} ${de.cyan(n)}`)}let o=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
81
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!ye.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,o=de.green("\u2501".repeat(n)),s=de.gray("\u2501".repeat(i)),a=`[${o}${s}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?de.green("\u2713"):de.blue("\u25B6"),h=this.options.showTags!==!1&&this.name?` ${de.gray(this.formatTag(this.name))}`:"",l=`\r${u}${h} ${a} ${c}${f}`,y=ye.stdout.columns||80,C=" ".repeat(Math.max(0,y-l.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${l}${C}`,ye.stdout.write(e.lastRenderedLine),t)ye.stdout.write(`
82
- `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||We()||!ye.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 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=sr(this.config.logDirectory,n);if(e.before)try{if((await or(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);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 si(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 Vh(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:o}=t,s=Error("Unknown error occurred");for(let a=0;a<=r;a++)try{return await e()}catch(c){if(s=c instanceof Error?c:Error(String(c)),a===r||!i(s))break;if(n>0)await new Promise((f)=>setTimeout(f,n))}if(o!==void 0)return o;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}class mo{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:o=!0,customParsers:s={},verbose:a=!1,trackPerformance:c=!0}=r,f=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),h={...t};return this.processObject(h,[],u,{useCamelCase:i,useBackwardCompatibility:o,customParsers:s,verbose:a,configName:e}),{config:h,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return no.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,o]of Object.entries(e)){let s=[...t,i],a=s.map((u)=>this.formatEnvKey(u,n.useCamelCase)),c=`${r}_${a.join("_")}`,f=n.useBackwardCompatibility?`${r}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.processObject(o,s,r,n);else{let u=ai.env[c]||(f?ai.env[f]:void 0);if(u!==void 0){if(n.verbose){let h=ai.env[c]?c:f}try{e[i]=this.parseEnvironmentValue(u,typeof o,c,n.customParsers,n.configName)}catch(h){if(h instanceof ho)throw h;throw cr.envVar(c,u,typeof o,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[o,s]of Object.entries(n))try{return s(e)}catch{continue}for(let o of this.defaultParsers)if(o.canParse(e,t))try{return o.parse(e)}catch{throw cr.envVar(r,e,`${t} (via ${o.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(ai.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,o=n||this.generateEnvPrefix(e),s=[];switch(this.extractEnvVarInfo(t,[],o,s),i){case"markdown":return this.formatAsMarkdown(s,e);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,o]of Object.entries(e)){let s=[...t,i],a=`${r}_${s.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.extractEnvVarInfo(o,s,r,n);else n.push({key:a,type:Array.isArray(o)?"array":typeof o,description:`Configuration for ${s.join(".")}`,example:this.generateExample(o)})}}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}:
186
+ `}return{name:"bunfig-plugin",setup(n){n.onResolve({filter:/^virtual:bunfig-types$/},(o)=>({path:o.path,namespace:"bunfig-virtual"})),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:r(),loader:"ts"}))}}}function cg(e,t={}){let i=Gn.cwd();while(i.includes("storage"))i=Bc(i,"..");let r=Bc(i,e||"");if(t?.relative)return jp(Gn.cwd(),r);return r}function rt(){if(qt.env.NODE_ENV==="test"||qt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ug(){if(qt.env.NODE_ENV==="test"||qt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof qt<"u"){let e=qt.type;if(e==="renderer"||e==="worker")return!1;return!!(qt.versions&&(qt.versions.node||qt.versions.bun))}return!1}class Mf{async format(e){let t=await ug(),i=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:i})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Ki.pid,hostname:t(),environment:Ki.env.NODE_ENV||"development",platform:Ki.platform,version:Ki.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ki.env.NODE_ENV||Ki.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class eo{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 Mf,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 i={...t},r=t.timestamp!==void 0;if(r)delete i.timestamp;if(this.config={...this.config,...i,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),o=this.generateKey();this.currentKeyId=n,this.keys.set(n,o),this.encryptionKeys.set(n,{key:o,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},i=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[i]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...js,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...js};return{...js,...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},i={...t,...Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0))};if(!i.level||!["debug","info","success","warning","error"].includes(i.level))i.level=t.level;return i}shouldWriteToFile(){return!rt()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let r,n=0,o=3,s=1000;while(n<o)try{try{try{await Kp(this.config.logDirectory,Vc.F_OK|Vc.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await zp(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Ut.from(e);try{if(!Tn(this.currentLogFile))await Is(this.currentLogFile,"",{mode:420});if(r=_c(this.currentLogFile,"a",420),Up(r,c,{flag:"a"}),Gc(r),r!==void 0)Ds(r),r=void 0;if((await Vi(this.currentLogFile)).size===0){if(await Is(this.currentLogFile,c,{flag:"w",mode:420}),(await Vi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(n<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${o}:`,u);let d=s*2**n;await new Promise((h)=>setTimeout(h,d)),n++;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(r!==void 0)try{Ds(r)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(n===o-1){let f=c,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}n++;let l=s*2**(n-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(t);let i=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(i,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 Ui(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 Ui(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Ui(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(rt())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,i=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),i=this.generateKey();this.currentKeyId=t,this.keys.set(t,i),this.encryptionKeys.set(t,{key:i,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,s],[,c])=>c.createdAt.getTime()-s.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,o=Math.max(1,n);if(r.length>o)for(let[s]of r.slice(o))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return Ms(16).toString("hex")}generateKey(){return Ms(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(),i=Ms(16),r=Gp("aes-256-gcm",t,i),n=Ut.isBuffer(e)?e:Ut.from(e,"utf8"),o=r.update(n),s=r.final(),c=o.length+s.length,l=r.getAuthTag(),f=Ut.allocUnsafe(16+c+16);return i.copy(f,0),o.copy(f,16),s.copy(f,16+o.length),l.copy(f,16+c),{encrypted:f,iv:i}}async compressData(e){return new Promise((t,i)=>{let r=Kc(),n=[];r.on("data",(o)=>n.push(o)),r.on("end",()=>t(Ut.from(Ut.concat(n)))),r.on("error",i),r.write(e),r.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(rt())return;if(!this.shouldWriteToFile())return;let e=await Vi(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 i=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await kn(this.config.logDirectory),o=n.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,f)=>{let u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${i}.${s}`;if(await Vi(i).catch(()=>null))try{if(await Uc(i,c),t.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await On(c)}catch(l){console.error("Error compressing rotated file:",l)}if(o.length===0&&!n.some((l)=>l.endsWith(".log.1")))try{let l=`${i}.1`;await Is(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),o=i.replace(/\.log$/,`-${n}.log`);if(await Vi(i).catch(()=>null))await Uc(i,o)}if(this.currentLogFile=r,t.maxFiles){let n=(await kn(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of n.slice(t.maxFiles))await On(Ui(this.config.logDirectory,o))}}}async compressLogFile(e,t){let i=jc(e),r=Vp(t),n=Kc();await Jp(i,n,r)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let i of this.logBuffer){let r=await this.formatter.format(i);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}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()})),Tn(this.currentLogFile))try{let e=_c(this.currentLogFile,"r+");Gc(e),Ds(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(!rt()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await kn(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await On(Ui(this.config.logDirectory,t))}catch(i){console.error(`Failed to delete temp file ${t}:`,i)}}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||rt())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:i="",tag:r="",message:n,level:o,showTimestamp:s=!0}=e,c=(p)=>p.replace(this.ANSI_PATTERN,"");if(!this.fancy){let p=[];if(s)p.push(t);if(o==="warning")p.push("WARN");else if(o==="error")p.push("ERROR");else if(i)p.push(i.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)p.push(r.replace(/[[\]]/g,""));return p.push(n),p.join(" ")}let l=Fe.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${i} ${n}`;else if(o==="info"||o==="success")f=`${i} ${r} ${n}`;else f=`${i} ${r} ${Te.cyan(n)}`;if(!s)return f.trim();let u=c(f).trim().length,d=c(t).length,h=Math.max(1,l-2-u-d);return`${f.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let c=Number.parseInt(s,10);return c<t[0].length?String(t[0][c]):o});let i=/%([sdijfo%])/g,r=0,n=e.replace(i,(o,s)=>{if(s==="%")return"%";if(r>=t.length)return o;let c=t[r++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return o}});if(r<t.length)n+=` ${t.slice(r).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(i,r,n)=>{let o=Te.underline(Te.blue(r)),s=this.toAbsoluteFilePath(n);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${c}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),t=t.replace(/`([^`]+)`/g,(i,r)=>Te.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(i,r)=>Te.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(i,r)=>Te.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(i,r)=>Te.italic(r)),t=t.replace(/~([^~]+)~/g,(i,r)=>Te.strikethrough(r)),t}supportsHyperlinks(){if(rt())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 i=Fe.env.HOME||"";if(i)t=t.replace(/^~(?=$|\/)/,i)}if(Hp(t)||t.startsWith("./")||t.startsWith("../"))t=qp(t);else return null;return Tn(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,i=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:i}}async log(e,t,...i){if(!this.shouldLog(e))return;let r=new Date,n=this.formatConsoleTimestamp(r),o=this.formatFileTimestamp(r),s,c;if(t instanceof Error)s=t.message,c=t.stack;else s=this.formatMessage(t,i);let{consoleText:l,fileText:f}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let d=this.options.showIcons===!1?"":gg[e],h=this.options.showTags!==!1&&this.name?Te.gray(this.formatTag(this.name)):"",p;switch(e){case"debug":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:Te.gray(l),level:e}),console.error(p);break;case"info":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:l,level:e}),console.warn(p);break;case"success":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:Te.green(l),level:e}),console.error(p);break;case"warning":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:l,level:e}),console.warn(p);break;case"error":if(p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:l,level:e}),console.error(p),c){let m=c.split(`
187
+ `);for(let a of m)if(a.trim()&&!a.includes(s))console.error(this.formatConsoleMessage({timestamp:n,message:Te.gray(` ${a}`),level:e,showTimestamp:!1}))}break}}else if(!rt()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${s}`),c)console.error(c)}let u=`${o} ${this.environment}.${e.toUpperCase()}: ${f}
188
+ `;if(c)u+=`${c}
189
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let i={update:(n,o)=>{},finish:(n)=>{},interrupt:(n,o)=>{}};if(!this.enabled)return i;let r=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!rt()&&Fe.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(n,o)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,n),this.activeProgressBar.total),o!==void 0)this.activeProgressBar.message=o;if(this.shouldStyleConsole()&&!rt()&&Fe.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(n)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,n)},interrupt:(n,o="info")=>{if(!rt()&&Fe.stdout.isTTY)Fe.stdout.write(`
190
+ `);if(this[o==="warning"?"warn":o](n),this.activeProgressBar&&this.shouldStyleConsole()&&!rt()&&Fe.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let i=this.options.showTags!==!1&&this.name?Te.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":Te.blue("\u25D0"),tag:i,message:`${Te.cyan(e)}...`}))}return async(i)=>{if(!this.enabled)return;let r=performance.now(),n=Math.round(r-t),o=`${e} completed in ${n}ms`,s=new Date,c=this.formatConsoleTimestamp(s),l=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(i)l+=` ${JSON.stringify(i)}`;if(l+=`
191
+ `,l=l.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:c,icon:this.options.showIcons===!1?"":Te.green("\u2713"),tag:f,message:`${o}${i?` ${JSON.stringify(i)}`:""}`}))}else if(!rt())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,i=new eo(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(i),i}createReadStream(){if(rt())throw Error("createReadStream is not supported in browser environments");if(!Tn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return jc(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 i=this.keys.get(this.currentKeyId);try{let r=Ut.isBuffer(e)?e:Ut.from(e,"base64"),n=r.subarray(0,16),o=r.subarray(r.length-16),s=r.subarray(16,r.length-16),c=_p("aes-256-gcm",i,n);c.setAuthTag(o);let l=c.update(s),f=c.final(),u=l.length+f.length,d=Ut.allocUnsafe(u);return l.copy(d,0),f.copy(d,l.length),d.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return rt()}isServerMode(){return!rt()}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,i=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:n,fileText:o}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=n.split(`
192
+ `),l=Math.max(...c.map((h)=>h.length))+2,f=`\u250C${"\u2500".repeat(l)}\u2510`,u=`\u2514${"\u2500".repeat(l)}\u2518`,d=c.map((h)=>this.formatConsoleMessage({timestamp:i,message:Te.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:i,message:Te.cyan(f),showTimestamp:!1})),d.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:i,message:Te.cyan(u),showTimestamp:!1}))}else if(!rt())console.error(`${r} ${this.environment}.INFO: [BOX] ${o}`);let s=`${r} ${this.environment}.INFO: [BOX] ${o}
193
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(e){if(rt())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${Te.cyan("?")} ${e} (y/n) `);let i=(r)=>{let n=r.toString().trim().toLowerCase();Fe.stdin.removeListener("data",i);try{if(typeof Fe.stdin.setRawMode==="function")Fe.stdin.setRawMode(!1)}catch{}Fe.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof Fe.stdin.setRawMode==="function")Fe.stdin.setRawMode(!0)}catch{}Fe.stdin.resume(),Fe.stdin.once("data",i)})}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 i=e;if(t&&t.length>0){let s=/%([sdijfo%])/g,c=0;if(i=e.replace(s,(l,f)=>{if(f==="%")return"%";if(c>=t.length)return l;let u=t[c++];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 l}}),c<t.length)i+=` ${t.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:r,fileText:n}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?Te.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${Te.blue("\u25D0")} `;console.error(`${c}${s} ${Te.cyan(r)}`)}let o=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
194
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!Fe.stdout.isTTY)return;let i=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),r=Math.round(e.barLength*i/100),n=e.barLength-r,o=Te.green("\u2501".repeat(r)),s=Te.gray("\u2501".repeat(n)),c=`[${o}${s}]`,l=`${i}%`.padStart(4),f=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||i===100?Te.green("\u2713"):Te.blue("\u25B6"),d=this.options.showTags!==!1&&this.name?` ${Te.gray(this.formatTag(this.name))}`:"",h=`\r${u}${d} ${c} ${l}${f}`,p=Fe.stdout.columns||80,m=" ".repeat(Math.max(0,p-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${m}`,Fe.stdout.write(e.lastRenderedLine),t)Fe.stdout.write(`
195
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||rt()||!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(rt()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await kn(this.config.logDirectory),i=[];for(let r of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let n=Ui(this.config.logDirectory,r);if(e.before)try{if((await Vi(n)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${n}:`,o);continue}i.push(n)}if(i.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${i.length} log file(s)...`);for(let r of i)try{await On(r),console.warn(`Deleted log file: ${r}`)}catch(n){console.error(`Failed to delete log file ${r}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function yg(e,t={}){let{maxRetries:i=3,retryDelay:r=1000,isRetryable:n=()=>!0,fallback:o}=t,s=Error("Unknown error occurred");for(let c=0;c<=i;c++)try{return await e()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===i||!n(s))break;if(r>0)await new Promise((f)=>setTimeout(f,r))}if(o!==void 0)return o;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}class ca{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,i={}){let{prefix:r,useCamelCase:n=!0,useBackwardCompatibility:o=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=i,f=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=r||this.generateEnvPrefix(e),d={...t};return this.processObject(d,[],u,{useCamelCase:n,useBackwardCompatibility:o,customParsers:s,verbose:c,configName:e}),{config:d,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return ea.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,i,r){for(let[n,o]of Object.entries(e)){let s=[...t,n],c=s.map((u)=>this.formatEnvKey(u,r.useCamelCase)),l=`${i}_${c.join("_")}`,f=r.useBackwardCompatibility?`${i}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.processObject(o,s,i,r);else{let u=Rn.env[l]||(f?Rn.env[f]:void 0);if(u!==void 0){if(r.verbose){let d=Rn.env[l]?l:f}try{e[n]=this.parseEnvironmentValue(u,typeof o,l,r.customParsers,r.configName)}catch(d){if(d instanceof la)throw d;throw ni.envVar(l,u,typeof o,r.configName)}}}}}parseEnvironmentValue(e,t,i,r,n){for(let[o,s]of Object.entries(r))try{return s(e)}catch{continue}for(let o of this.defaultParsers)if(o.canParse(e,t))try{return o.parse(e)}catch{throw ni.envVar(i,e,`${t} (via ${o.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},i=e.toUpperCase();for(let[r,n]of Object.entries(Rn.env))if(r.startsWith(i)&&n!==void 0)t[r]=n;return t}validateEnvironmentVariable(e,t,i){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))r.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(i)try{this.parseEnvironmentValue(e,t,i,{})}catch(n){r.push(`Cannot parse value "${t}" as ${i}: ${n}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(e,t,i={}){let{prefix:r,format:n="text"}=i,o=r||this.generateEnvPrefix(e),s=[];switch(this.extractEnvVarInfo(t,[],o,s),n){case"markdown":return this.formatAsMarkdown(s,e);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,e)}}extractEnvVarInfo(e,t,i,r){for(let[n,o]of Object.entries(e)){let s=[...t,n],c=`${i}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.extractEnvVarInfo(o,s,i,r);else r.push({key:c,type:Array.isArray(o)?"array":typeof o,description:`Configuration for ${s.join(".")}`,example:this.generateExample(o)})}}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 i=`Environment Variables for ${t}:
83
196
 
84
- `;for(let n of e)r+=`${n.key}
85
- `,r+=` Type: ${n.type}
86
- `,r+=` Description: ${n.description}
87
- `,r+=` Example: ${n.example}
197
+ `;for(let r of e)i+=`${r.key}
198
+ `,i+=` Type: ${r.type}
199
+ `,i+=` Description: ${r.description}
200
+ `,i+=` Example: ${r.example}
88
201
 
89
- `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
202
+ `;return i}formatAsMarkdown(e,t){let i=`# Environment Variables for ${t}
90
203
 
91
- `;r+=`| Variable | Type | Description | Example |
92
- `,r+=`|----------|------|-------------|----------|
93
- `;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
94
- `;return r}}function Uh(e,t,r={}){return fl(e,t,r,new WeakMap)}function fl(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:o=!1,customMerger:s}=r;if(t===null||t===void 0)return o?e:t;if(s){let a=s(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return ul(e,t,i,n);if(!lt(t)||!lt(e))return t;return Jh(e,t,r,n)}function ul(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 Kh(e,t);case"smart":return Hh(e,t,n);default:return t}return t}function Kh(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>io(i,n)))r.push(n);return r}function Hh(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(lt(t[0])&&lt(e[0]))return zh(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 zh(e,t,r){let n=[...t];for(let i of e){if(!lt(i)){n.push(i);continue}let o=["id","name","key","path","type"],s=!1;for(let a of o)if(a in i){if(n.find((c)=>lt(c)&&(a in c)&&c[a]===i[a])){s=!0;break}}if(!s)n.push(i)}return n}function Jh(e,t,r,n){let i=t;if(lt(i)&&n.has(i))return n.get(i);let o={...e};if(lt(i))n.set(i,o);for(let s in i){if(!Object.prototype.hasOwnProperty.call(i,s))continue;let a=i[s],c=o[s];if(r.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){o[s]=a;continue}if(lt(a)&&lt(c))o[s]=fl(c,a,r,n);else if(Array.isArray(a)||Array.isArray(c))o[s]=ul(c,a,r.arrayMergeMode||"smart",n);else o[s]=a}return o}function hl(e,t,r="replace"){return Uh(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function io(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(!io(e[r],t[r]))return!1;return!0}if(lt(e)&&lt(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(!io(e[i],t[i]))return!1}return!0}return!1}function lt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class dl{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:o,trackPerformance:s=!0,verbose:a=!1}=r;if(i){let f=vi.getWithFileCheck("file",e);if(f){if(a)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!li(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),h=u.default||u,l="default"in u,y=Object.keys(u).length>0;if(!l&&!y)throw new Oi(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new Oi(e,Error("Configuration must export a valid object"),"unknown");let C={config:hl(t,h,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)vi.setWithFileCheck("file",C,e,o);return C}catch(f){throw f instanceof Error?cr.configLoad(e,f):cr.configLoad(e,Error(String(f)))}};if(s)return no.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 o of n)for(let s of this.extensions)i.push(Gn(t,`${o}${s}`));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 o of n){if(!o)continue;if(r.push(o,`.${o}.config`,`${o}.config`,`.${o}`),e)r.push(`${e}.${o}.config`,`.${e}.${o}.config`)}let i=new Set;return r.filter((o)=>{if(!o||i.has(o))return!1;return i.add(o),!0})}checkFileAccess(e){return Vh(async()=>li(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!li(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let o of i)for(let s of this.extensions){let a=Gn(e,`${o}${s}`);if(await this.checkFileAccess(a))n.push(a)}}else try{let{readdirSync:i}=await import("fs"),o=i(e);for(let s of o)if(this.looksLikeConfigFile(s)){let a=Gn(e,s);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(!li(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"),o=i(e,"utf8");JSON.parse(o)}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 ml{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:a=!0,verbose:c=!1}=r,f=async()=>{let u=[],h=[],l={stopOnFirstError:n,validateRequired:i,validateTypes:o,customRules:s,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,l);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],l);else return this.validateWithJSONSchema(e,t,l)}catch(y){return u.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:u,warnings:h}}};if(a)return await no.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!Ru(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,o){if(o.validateTypes&&t.type){let s=Array.isArray(e)?"array":typeof e,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(s)){if(n.push({path:r,message:`Expected type ${a.join(" or ")}, got ${s}`,expected:a.join(" or "),actual:s,rule:"type"}),o.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"}),o.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 s=0;s<e.length;s++){let a=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,a,n,i,o),o.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let s=e;if(o.validateRequired&&t.required){for(let a of t.required)if(!(a in s)){if(n.push({path:r?`${r}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[a,c]of Object.entries(t.properties))if(a in s){let f=r?`${r}.${a}`:a;if(this.validateObjectAgainstSchema(s[a],c,f,n,i,o),o.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(s))if(!a.has(c))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let o of t)try{let s=this.getValueByPath(e,o.path),a=this.validateWithRule(s,o,o.path);if(n.push(...a),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:o.path,message:`Rule validation failed: ${s}`,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,o,s]=n;t.push({path:i,required:!o,type:this.mapTypeScriptType(s)})}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:qh},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function Yh(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 pl{fileLoader=new dl;envProcessor=new mo;validator=new ml;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:o,...s}=e;try{if(r?.enabled){let c=this.checkCache(s.name||"",s);if(c)return c}let a;try{a=await this.loadConfigurationStrategies(s,!0,r)}catch(c){let f=s.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.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"),h=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),l=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(l||u))throw c;if(h&&(!f||!l))a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(i||o)await this.validateConfiguration(a.config,i,o,s.name);if(r?.enabled&&a)this.cacheResult(s.name||"",a,r,s);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)vt.warn(`Slow configuration loading detected: ${c.duration}ms for ${s.name}`);a.metrics=c}return a}catch(a){if(a instanceof Error&&a.name==="ConfigNotFoundError")throw a;let c=Date.now()-t;throw vt.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:o,configDir:s,defaultConfig:a,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,h=o||Pi.cwd(),l=[],y=await this.loadLocalConfiguration(n,i,h,s,a,f,u,c,r);if(y)return l.push(...this.getLocalSearchPaths(n,i,h,s)),this.finalizeResult(y,l,c,n,u);let C=await this.loadHomeConfiguration(n,i,a,f,u,c);if(C)return l.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(C,l,c,n,u);let S=await this.loadPackageJsonConfiguration(n,i,h,a,f,u,c);if(S)return l.push(st(h,"package.json")),this.finalizeResult(S,l,c,n,u);if(l.push(...this.getAllSearchPaths(n,i,h,s)),t)throw cr.configNotFound(n,l,i);return{...await this.applyEnvironmentVariables(n,a,c,u),warnings:[`No configuration file found for "${n}"${Yh(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,o,s,a,c){let f=a?fi(e,i,s):i,u=this.getLocalDirectories(r,n);for(let h of u){if(s)vt.info(`Searching for configuration in: ${h}`);let l=this.fileLoader.generateConfigPaths(e,h,t),y=await this.fileLoader.tryLoadFromPaths(l,f,{arrayStrategy:o,verbose:s,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(y){if(s)vt.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(e,t,r,n,i,o){if(!e)return null;let s=o?fi(e,r,i):r,a=[st(Zt(),".config",e),st(Zt(),".config"),Zt()];for(let c of a){if(i)vt.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,s,{arrayStrategy:n,verbose:i});if(u){if(i)vt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,o,s){let a=s?fi(e,n,o):n;try{let c=st(r,"package.json");if(!Vf(c))return null;let f={};try{f=JSON.parse(Uf(c,"utf8"))}catch(l){if(o)vt.warn("Failed to parse package.json:",[l instanceof Error?l:Error(String(l))]);return null}let u=f[e],h=e;if(!u&&t){let l=Array.isArray(t)?t:[t];for(let y of l){if(!y)continue;if(f[y]){u=f[y],h=y;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(o)vt.success(`Configuration loaded from package.json: ${h}`);return{config:hl(a,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(o)vt.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:fi(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 o=r(e);if(o)i.push(...o)}if(t){let o=await this.validator.validateConfiguration(e,t);if(!o.isValid)i.push(...o.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(i.length>0)throw cr.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return vi.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);vi.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,st(e,"config"),st(e,".config"),t?st(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(st(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),o=[];for(let s of i)o.push(...this.fileLoader.generateConfigPaths(e,s,t));return o}getHomeSearchPaths(e,t){if(!e)return[];let r=[st(Zt(),".config",e),st(Zt(),".config"),Zt()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function fi(e,t,r=!1){let n=new mo,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,a=[]){let c={...s};for(let[f,u]of Object.entries(s)){let h=[...a,f],l=[`${i}_${h.join("_").toUpperCase()}`,`${i}_${h.map((S)=>S.toUpperCase()).join("")}`,`${i}_${h.map((S)=>S.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,C;for(let S of l)if(y=Pi.env[S],y!==void 0){C=S;break}if(y!==void 0&&C)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(y.toLowerCase());else if(typeof u==="number"){let S=Number(y);if(!Number.isNaN(S))c[f]=S}else if(Array.isArray(u))try{c[f]=JSON.parse(y)}catch{c[f]=y.split(",").map((S)=>S.trim())}else c[f]=y;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=o(u,h)}return c}return o(t)}var vi,no,Pu,ku=(e)=>e,Du=(e,t)=>{for(var r in t)Pu(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Mu.bind(t,r)})},Iu=(e,t)=>()=>(e&&(t=e(e=0)),t),La,Ha,lr,xr,za,ah,lh,ba,hi,qn,He,Ee,ch,Ea,fh,Sa,uh,hh,jn,dh,$a,Aa,_n,mh,ph,gh,yh,di,Ja,Ch,ze,wh,vh,xa,mi,Yn,Le,ce,bh,Ta,Eh,Oa,Sh,$h,Vn,Ah,Ra,Pa,xh,Un,Th,Oh,Rh,Ph,kh,pi,qa,Mh,Dh="0.15.6",rt,Ai,$r,Zn,Xn,xi,Qn,eo,Ar,to,ro,Mt,Ya,Za,ut,$t,Xa,Qa,Ih,Nh,el,Ti,jy,rl,de,_y,Wh,Vy,Bh,Uy,Ky,ka,Hy,Gh,jh,zy,Ma,Jy,qy,Yy,Zy,Xy,Kn,_h,Qy,ht,il,Oi,nl,ol,ho,sl,al,Ri,ll,cl,cr,qh,vt,e0,t0,r0,Zh,gl;var yl=he(()=>{vi=new Fa,no=new Na,Pu=Object.defineProperty;La={};Du(La,{withErrorRecovery:()=>Ga,tryLoadConfig:()=>ih,loadConfigWithResult:()=>th,loadConfig:()=>Ka,isRetryableError:()=>qu,isConfigNotFoundError:()=>Ju,isBunfigError:()=>ja,globalPerformanceMonitor:()=>xr,globalCache:()=>lr,getEnvOrDefault:()=>Yu,generateConfigTypes:()=>nh,defaultGeneratedDir:()=>Qa,defaultConfigDir:()=>Xa,deepMergeWithArrayStrategy:()=>co,deepMerge:()=>_a,createLibraryConfig:()=>oh,config:()=>rh,bunfigPlugin:()=>sh,applyEnvVarsToConfig:()=>Er,TypeGenerationError:()=>eo,SchemaValidationError:()=>Ar,PluginError:()=>ro,PerformanceMonitor:()=>so,FileSystemError:()=>Qn,ErrorFactory:()=>Mt,EnvVarError:()=>xi,EnvProcessor:()=>ki,ConfigValidator:()=>fo,ConfigValidationError:()=>Zn,ConfigNotFoundError:()=>Ai,ConfigMergeError:()=>Xn,ConfigLoader:()=>uo,ConfigLoadError:()=>$r,ConfigFileLoader:()=>Mi,ConfigCache:()=>oo,CacheUtils:()=>za,BunfigError:()=>rt,BrowserConfigError:()=>to,ArrayMergeStrategies:()=>Ya});Ih=Iu(async()=>{Ha=import.meta.require,lr=new oo,xr=new so,za={createKey:Fu,isEquivalent:Nu,estimateMemoryUsage:Lu},ah=Ci(zn.cwd(),"config"),lh=Ci(zn.cwd(),"src/generated"),ba=yi.env.CLARITY_LOG_DIR||Yf(Gu(),"logs"),hi={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ba,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},qn=await ju(),He={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"},Ee=He,ch=He.red,Ea=He.green,fh=He.yellow,Sa=He.blue,uh=He.magenta,hh=He.cyan,jn=He.white,dh=He.gray,$a=He.bgRed,Aa=He.bgYellow,_n=He.bold,mh=He.dim,ph=He.italic,gh=He.underline,yh=He.reset,di={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ja={debug:"\uD83D\uDD0D",info:Sa("\u2139"),success:Ea("\u2713"),warning:Aa(jn(_n(" WARN "))),error:$a(jn(_n(" ERROR ")))},Ch=new Ei("stacks"),ze=new Ei("bunfig",{showTags:!0}),wh=Ye(Sr.cwd(),"config"),vh=Ye(Sr.cwd(),"src/generated"),xa=gi.env.CLARITY_LOG_DIR||Jf(Ku(),"logs"),mi={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:xa,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Yn=await Hu(),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"},ce=Le,bh=Le.red,Ta=Le.green,Eh=Le.yellow,Oa=Le.blue,Sh=Le.magenta,$h=Le.cyan,Vn=Le.white,Ah=Le.gray,Ra=Le.bgRed,Pa=Le.bgYellow,xh=Le.bgGray,Un=Le.bold,Th=Le.dim,Oh=Le.italic,Rh=Le.underline,Ph=Le.strikethrough,kh=Le.reset,pi={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},qa={debug:"\uD83D\uDD0D",info:Oa("\u2139"),success:Ta("\u2713"),warning:Pa(Vn(Un(" WARN "))),error:Ra(Vn(Un(" ERROR ")))},Mh=new $i("stacks"),rt=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}`}},Ai=class extends rt{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 rt{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}},Zn=class extends rt{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Xn=class extends rt{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}},xi=class extends rt{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})}},Qn=class extends rt{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}},eo=class extends rt{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}},Ar=class extends rt{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})}},to=class extends rt{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})}},ro=class extends rt{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}},Mt={configNotFound(e,t,r){return new Ai(e,t,r)},configLoad(e,t,r){return new $r(e,t,r)},configValidation(e,t,r){return new Zn(e,t,r)},configMerge(e,t,r,n){return new Xn(e,t,r,n)},envVar(e,t,r,n){return new xi(e,t,r,n)},fileSystem(e,t,r){return new Qn(e,t,r)},typeGeneration(e,t,r){return new eo(e,t,r)},schemaValidation(e,t,r){return new Ar(e,t,r)},browserConfig(e,t,r,n){return new to(e,t,r,n)},plugin(e,t,r){return new ro(e,t,r)}},Ya={replace:"replace",concat:"concat",smart:"smart"},Za=/^https?:\/\//,ut=new $i("bunfig",{showTags:!0}),$t=new uo,Xa=Ze(Bt.cwd(),"config"),Qa=Ze(Bt.cwd(),"src/generated")});Nh=wi.env.CLARITY_LOG_DIR||Cu(Fh(),"logs"),el={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Nh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ti={...el},jy=(async()=>{try{let{loadConfig:e}=await Ih().then(()=>La),t=await e({name:"clarity",alias:"logging",defaultConfig:el,cwd:wi.cwd()});if(t)Object.assign(Ti,t)}catch{}return Ti})();rl={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"},de=rl,{red:_y,green:Wh,yellow:Vy,blue:Bh,magenta:Uy,cyan:Ky,white:ka,gray:Hy,bgRed:Gh,bgYellow:jh,bgGray:zy,bold:Ma,dim:Jy,italic:qy,underline:Yy,strikethrough:Zy,reset:Xy}=rl,Kn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},_h={debug:"\uD83D\uDD0D",info:Bh("\u2139"),success:Wh("\u2713"),warning:jh(ka(Ma(" WARN "))),error:Gh(ka(Ma(" ERROR ")))};Qy=new Di("stacks");ht=class ht 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}`}};il=class il extends ht{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((o)=>`"${o}"`).join(", ")}`;super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}};Oi=class Oi extends ht{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}};nl=class nl extends ht{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};ol=class ol extends ht{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}};ho=class ho extends ht{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})}};sl=class sl extends ht{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}};al=class al extends ht{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 ht{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})}};ll=class ll extends ht{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})}};cl=class cl extends ht{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}};cr={configNotFound(e,t,r){return new il(e,t,r)},configLoad(e,t,r){return new Oi(e,t,r)},configValidation(e,t,r){return new nl(e,t,r)},configMerge(e,t,r,n){return new ol(e,t,r,n)},envVar(e,t,r,n){return new ho(e,t,r,n)},fileSystem(e,t,r){return new sl(e,t,r)},typeGeneration(e,t,r){return new al(e,t,r)},schemaValidation(e,t,r){return new Ri(e,t,r)},browserConfig(e,t,r,n){return new ll(e,t,r,n)},plugin(e,t,r){return new cl(e,t,r)}};qh=/^https?:\/\//;vt=new Di("bunfig",{showTags:!0});e0=new pl;t0=st(Pi.cwd(),"config"),r0=st(Pi.cwd(),"src/generated"),Zh={cwd:_f.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},gl=Zh});function Cl(e,t,r){let n={file:t,message:"Unknown error",code:Tr.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=Tr.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=Tr.SYNTAX_ERROR,n.suggestion="Check for syntax errors in your TypeScript code.";else if(e.message.includes("type")&&e.message.includes("cannot"))n.code=Tr.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=Tr.PARSE_ERROR,n.suggestion="The file contains invalid TypeScript syntax."}else if(typeof e==="string")n.message=e;return n}function wl(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(`
95
- `),o=e.location.line-1;if(o>=0&&o<i.length){let s=Math.max(0,o-1),a=Math.min(i.length-1,o+1);for(let c=s;c<=a;c++){let f=(c+1).toString().padStart(4," "),u=c===o?">":" ";if(r.push(` ${u} ${f} | ${i[c]}`),c===o&&e.location.column>0){let h=" ".repeat(10+e.location.column-1);r.push(` ${h}^`)}}}}if(e.suggestion)r.push(""),r.push(` Suggestion: ${e.suggestion}`);return r.join(`
96
- `)}var Tr;var vl=he(()=>{Tr={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 El(e){return e.endsWith(".vue")}function Xh(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]||"",o=/lang\s*=\s*["']([^"']+)["']/i.exec(i)?.[1]?.toLowerCase()??"js",s={content:n[2]??"",attrs:i,setup:/\bsetup\b/.test(i),lang:o};if(s.setup)t.scriptSetup=s;else t.script=s}return t}function it(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 ct(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 pt(e,t){if(e[t+1]==="/"){let r=e.indexOf(`
97
- `,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 go(e,t){let r=e[t];if(r==='"'||r==="'")return it(e,t);if(r==="`")return ct(e,t);if(r==="/"&&(e[t+1]==="/"||e[t+1]==="*"))return pt(e,t);return t}function yo(e){let t=e.split(""),r=0;while(r<e.length){let n=go(e,r);if(n>r){for(let i=r;i<n;i++)if(t[i]!==`
98
- `&&t[i]!=="\r")t[i]=" ";r=n;continue}r++}return t.join("")}function je(e,t,r,n){let i=0,o=t;while(o<e.length){let s=e[o];if(s==='"'||s==="'"){o=it(e,o);continue}if(s==="`"){o=ct(e,o);continue}if(s==="/"&&(e[o+1]==="/"||e[o+1]==="*")){o=pt(e,o);continue}if(s===r)i++;else if(s===n){if(i--,i===0)return o}o++}return-1}function Co(e,t){let r=0,n=t;while(n<e.length){let i=e[n];if(i==='"'||i==="'"){n=it(e,n);continue}if(i==="`"){n=ct(e,n);continue}if(i==="/"&&(e[n+1]==="/"||e[n+1]==="*")){n=pt(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 fr(e,t=","){let r=[],n=0,i="",o=0;while(o<e.length){let s=e[o];if(s==='"'||s==="'"){let a=it(e,o);i+=e.slice(o,a),o=a;continue}if(s==="`"){let a=ct(e,o);i+=e.slice(o,a),o=a;continue}if(s==="/"&&(e[o+1]==="/"||e[o+1]==="*")){o=pt(e,o);continue}if(s==="{"||s==="["||s==="("||s==="<")n++;else if(s==="}"||s==="]"||s===")"||s===">")n--;if(s===t&&n===0){r.push(i),i="",o++;continue}i+=s,o++}if(i.trim()!=="")r.push(i);return r}function Pr(e){let t=e.trim();if(!t.startsWith("{"))return[];let r=je(t,0,"{","}");if(r===-1)return[];let n=t.slice(1,r),i=[];for(let o of fr(n)){let s=-1,a=0;for(let u=0;u<o.length;u++){let h=o[u];if(h==='"'||h==="'"){u=it(o,u)-1;continue}if(h==="`"){u=ct(o,u)-1;continue}if(h==="{"||h==="["||h==="("||h==="<")a++;else if(h==="}"||h==="]"||h===")"||h===">")a--;else if(h===":"&&a===0){s=u;break}}if(s!==-1){i.push({key:Or(o.slice(0,s).trim()),value:o.slice(s+1).trim(),isMethod:!1});continue}let c=/^([A-Za-z_$][\w$]*|['"][^'"]+['"])\s*\(/.exec(o.trim());if(c){i.push({key:Or(c[1]),value:o.trim(),isMethod:!0});continue}let f=o.trim();if(f)i.push({key:Or(f),value:"",isMethod:!1})}return i}function Or(e){if(e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);return e}function Rr(e){return/^[A-Za-z_$][\w$]*$/.test(e)?e:JSON.stringify(e)}function kr(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 o=null;if(e[i]==="<"){let c=Co(e,i);if(c===-1)return null;o=e.slice(i+1,c).trim(),i=c+1;while(i<e.length&&/\s/.test(e[i]))i++}if(e[i]!=="(")continue;let s=je(e,i,"(",")");if(s===-1)return null;let a=fr(e.slice(i+1,s));return{generic:o,arg:a.length>0?a[0].trim():null}}return null}function Qh(e,t){let r=Sl(e,t);if(!r)return null;return r.kind==="interface"?e.slice(r.bodyStart,r.end):e.slice(r.bodyStart,r.end).trim()}function Sl(e,t){let r=new RegExp(`\\binterface\\s+${t}\\b[^{]*\\{`,"m").exec(e);if(r){let i=r.index+r[0].length-1,o=je(e,i,"{","}");if(o!==-1)return{kind:"interface",start:r.index,end:o+1,bodyStart:i}}let n=new RegExp(`\\btype\\s+${t}\\b[^=]*=`,"m").exec(e);if(n){let i=n.index+n[0].length,o=0,s=i;while(i<e.length){let a=e[i];if(a==='"'||a==="'"){i=it(e,i);continue}if(a==="`"){i=ct(e,i);continue}if(a==="{"||a==="["||a==="("||a==="<")o++;else if(a==="}"||a==="]"||a===")"||a===">")o--;else if((a===";"||a===`
99
- `)&&o===0)break;i++}return{kind:"type",start:n.index,end:i,bodyStart:s}}return null}function ed(e){let t=e.search(/\bas\s+PropType\s*</);if(t===-1)return null;let r=e.indexOf("<",t),n=Co(e,r);if(n===-1)return null;if(e.slice(n+1).trim()!=="")return null;return e.slice(r+1,n).trim()}function po(e){let t=e.trim(),r=ed(t);if(r!==null)return{type:r,optional:!0};if(t==="null")return{type:"unknown",optional:!0};if(t.startsWith("[")){let n=je(t,0,"[","]");if(n!==-1){let i=fr(t.slice(1,n)).map((o)=>po(o).type).filter((o)=>o!=="unknown");return{type:i.length>0?[...new Set(i)].join(" | "):"unknown",optional:!0}}}if(t.startsWith("{")){let n=Pr(t),i=n.find((c)=>c.key==="type"),o=n.find((c)=>c.key==="required"),s=i?po(i.value).type:"unknown",a=!(o&&o.value.trim()==="true");return{type:s,optional:a}}if(bl[t])return{type:bl[t],optional:!0};if(/^[A-Za-z_$][\w$.]*$/.test(t))return{type:t,optional:!0};return{type:"unknown",optional:!0}}function Li(e){let t=e.trim();if(t.startsWith("{")){let r=Pr(t);if(r.length===0)return"{}";return`{ ${r.map((n)=>{if(n.isMethod||n.value==="")return`${Rr(n.key)}?: unknown`;let i=po(n.value);return`${Rr(n.key)}${i.optional?"?":""}: ${i.type}`}).join(", ")} }`}if(t.startsWith("[")){let r=je(t,0,"[","]");if(r===-1)return null;let n=fr(t.slice(1,r)).map((i)=>Or(i.trim())).filter((i)=>i!=="");if(n.length===0)return"{}";return`{ ${n.map((i)=>`${Rr(i)}?: unknown`).join(", ")} }`}return null}function td(e){let t=e.trim();if(!t.startsWith("["))return null;let r=je(t,0,"[","]");if(r===-1)return null;let n=fr(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(Or(i))).join(", ")}]`}function rd(e){let t=e.trim();if(!t.startsWith("{"))return null;let r=Pr(t);if(r.length===0)return"{}";return`{ ${r.map((n)=>`${JSON.stringify(n.key)}: (...args: any[]) => void`).join(", ")} }`}function $l(e){return td(e)??rd(e)}function id(e){let t=[],r=0,n="",i=0;while(i<e.length){let o=e[i];if(o==='"'||o==="'"){let s=it(e,i);n+=e.slice(i,s),i=s;continue}if(o==="`"){let s=ct(e,i);n+=e.slice(i,s),i=s;continue}if(o==="/"&&(e[i+1]==="/"||e[i+1]==="*")){let s=pt(e,i);n+=e.slice(i,s),i=s;continue}if(o==="="&&e[i+1]===">"){n+="=>",i+=2;continue}if(o==="{"||o==="["||o==="("||o==="<")r++;else if(o==="}"||o==="]"||o===")"||o===">")r--;if((o===";"||o===","||o===`
100
- `)&&r===0){if(n.trim()!=="")t.push(n.trim());n="",i++;continue}n+=o,i++}if(n.trim()!=="")t.push(n.trim());return t}function nd(e){let t=e.trim();if(!t.startsWith("{"))return null;let r=je(t,0,"{","}");if(r===-1||t.slice(r+1).trim()!=="")return null;let n=id(t.slice(1,r));if(n.length===0)return"{}";let i=[];for(let o of n){let s=/^\(\s*\w+\s*:\s*/.exec(o);if(!s)return null;let a=s[0].length,c=o[a];if(c!=="'"&&c!=='"'&&c!=="`")return null;let f=it(o,a),u=o.slice(a+1,f-1),h=je(o,o.indexOf("(",0),"(",")");if(h===-1)return null;let l=o.slice(a,h),y=fr(l).slice(1),C=o.slice(h+1).trim();if(C.startsWith(":"))C=C.slice(1).trim();if(C==="")C="void";i.push(`${JSON.stringify(u)}: (${y.map((S)=>S.trim()).join(", ")}) => ${C}`)}return`{ ${i.join(", ")} }`}function wo(e){let t=e;for(let r of["defineProps","defineEmits","defineExpose","defineSlots","defineOptions"])t=od(t,r);return t}function od(e,t){let r=new RegExp(`\\b${t}\\b`,"g"),n=[],i=e,o;while((o=r.exec(e))!==null){let s=e.lastIndexOf(`
101
- `,o.index)+1,a=e.slice(s,o.index),c=/^\s*(?:(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*(?::[^=]+)?=\s*)?(withDefaults\s*\(\s*)?$/.exec(a);if(!c)continue;let f=o.index+o[0].length;while(f<e.length&&/\s/.test(e[f]))f++;if(e[f]==="<"){let l=Co(e,f);if(l===-1)continue;f=l+1;while(f<e.length&&/\s/.test(e[f]))f++}if(e[f]!=="(")continue;let u=je(e,f,"(",")");if(u===-1)continue;if(c[1]){let l=s+a.length-c[1].length,y=e.indexOf("(",l);if(y!==-1){let C=je(e,y,"(",")");if(C!==-1)u=C}}let h=u+1;while(h<e.length&&e[h]!==`
102
- `&&/\s|;/.test(e[h]))h++;if(e[h]===`
103
- `)h++;n.push([s,h])}for(let s=n.length-1;s>=0;s--)i=i.slice(0,n[s][0])+i.slice(n[s][1]);return i}function vo(e){let t=sd(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,o=-1,s=-1;if(e[n]==="{")i=n,o=je(e,n,"{","}"),s=o;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,o=je(e,u,"{","}"),s=je(e,f,"(",")")}}if(i===-1||o===-1||s===-1)return{options:null,script:e,passthrough:!0};let a=s+1;if(e[a]===";")a++;let c=(e.slice(0,t)+e.slice(a)).trim();return{options:e.slice(i,o+1),script:c,passthrough:!1}}return{options:null,script:e,passthrough:!1}}function sd(e){let t=0,r=0;while(r<e.length){let n=e[r];if(n==='"'||n==="'"){r=it(e,r);continue}if(n==="`"){r=ct(e,r);continue}if(n==="/"&&(e[r+1]==="/"||e[r+1]==="*")){r=pt(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],o=e[r+6]??"";if(!/[\w$]/.test(i)&&!/[\w$]/.test(o)){if(/^export\s+default\b/.exec(e.slice(r)))return r}}r++}return-1}function Ii(e,t){let r=Pr(e).find((n)=>n.key===t);return r&&r.value!==""?r.value:null}function Fi(e,t){let r=ld(e),n=e;for(let i=r.length-1;i>=0;i--){let o=r[i],s=n.slice(0,o.start)+n.slice(o.end);if(ad(s,o.name))continue;if(new RegExp(`\\btypeof\\s+${o.name}\\b`).test(t))continue;n=s}return n}function ad(e,t){let r=0;while(r<e.length){let n=e[r];if(n==='"'||n==="'"){r=it(e,r);continue}if(n==="`"){r=ct(e,r);continue}if(n==="/"&&(e[r+1]==="/"||e[r+1]==="*")){r=pt(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 ld(e){let t=[],r=cd(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 o=e.lastIndexOf(`
104
- `,i.index)+1;if(!r.has(o))continue;if(/\bexport\b/.test(e.slice(o,i.index)))continue;let s=i[1],a=i[2],c=i.index+i[0].length,f=-1;if(s.endsWith("function")){let u=e.indexOf("(",c);if(u===-1)continue;let h=je(e,u,"(",")");if(h===-1)continue;c=h+1;while(c<e.length&&/\s/.test(e[c]))c++;if(e[c]===":")while(c<e.length&&e[c]!=="{"&&e[c]!==`
105
- `)c++;while(c<e.length&&/\s/.test(e[c])&&e[c]!==`
106
- `)c++;if(e[c]!=="{")continue;let l=je(e,c,"{","}");if(l===-1)continue;f=l+1}else{let u=0;while(c<e.length){let h=e[c];if(h==='"'||h==="'"){c=it(e,c);continue}if(h==="`"){c=ct(e,c);continue}if(h==="/"&&(e[c+1]==="/"||e[c+1]==="*")){c=pt(e,c);continue}if(h==="{"||h==="["||h==="(")u++;else if(h==="}"||h==="]"||h===")")u--;else if(h===";"&&u===0){f=c+1;break}else if(h===`
107
- `&&u===0){f=c;break}c++}if(f===-1)f=e.length}if(e[f]===`
108
- `)f++;t.push({name:a,start:i.index,end:f})}return t}function cd(e){let t=new Set([0]),r=0,n=0;while(n<e.length){let i=e[n];if(i==='"'||i==="'"){n=it(e,n);continue}if(i==="`"){n=ct(e,n);continue}if(i==="/"&&(e[n+1]==="/"||e[n+1]==="*")){n=pt(e,n);continue}if(i==="{"||i==="["||i==="(")r++;else if(i==="}"||i==="]"||i===")")r=Math.max(0,r-1);if(i===`
109
- `&&r===0)t.add(n+1);n++}return t}function Ni(e,t,r){let n=e.indexOf(r);if(n===-1)return e;let i=e.lastIndexOf(`
110
- `,n)+1;if(/\bexport\b/.test(e.slice(i,n)))return e;let o=e.slice(0,n)+e.slice(n+r.length);if(new RegExp(`\\b${t}\\b`).test(o))return e;return o}function bo(e){let t="",r=0,n=()=>{for(let o=t.length-1;o>=0;o--)if(!/\s/.test(t[o]))return t[o];return""},i=(o)=>{for(let s=o;s<e.length;s++)if(!/\s/.test(e[s]))return e[s];return""};while(r<e.length){let o=e[r];if(o==='"'||o==="'"){let s=it(e,r);t+=e.slice(r,s),r=s;continue}if(o==="`"){let s=ct(e,r);t+=e.slice(r,s),r=s;continue}if(o==="/"&&e[r+1]==="*"){let s=pt(e,r);t+=e.slice(r,s).replace(/\s*\n\s*/g," "),r=s;continue}if(o==="/"&&e[r+1]==="/"){let s=r+2;while(s<e.length&&e[s]!==`
111
- `)s++;let a=e.slice(r+2,s).trim();if(a!==""&&!a.includes("*/"))t+=`/* ${a} */`;r=s;continue}if(o===`
112
- `){let s=n(),a=i(r+1);if(s===""||a===""){r++;continue}let c=fd(t);if(!c&&("{;,(<:=[".includes(s)||"}),]>;|&".includes(a))){if(!t.endsWith(" ")&&!t.endsWith(";"))t+=" "}else if(c){if(!t.endsWith(" "))t+=" "}else{if(t.endsWith(" "))t=t.slice(0,-1);t+="; "}r++;while(r<e.length&&(e[r]===" "||e[r]==="\t"))r++;continue}t+=o,r++}return t}function fd(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 Wi(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=kr(n,"defineProps");if(!i)continue;if(i.generic){let o=i.generic;if(o.startsWith("{"))return{type:o};if(/^[A-Za-z_$][\w$]*$/.test(o)){for(let s of r){let a=Sl(s,o);if(!a)continue;let c=Qh(s,o);if(c===null)continue;return{type:c,inlinedLocal:{name:o,declText:s.slice(a.start,a.end)}}}return{type:o}}return{type:o}}if(i.arg){let o=Li(i.arg);if(o!==null)return{type:o}}}return null}function Eo(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=kr(n,"defineEmits");if(!i)continue;if(i.generic)return nd(i.generic)??i.generic;if(i.arg){let o=$l(i.arg);if(o!==null)return o}}return null}function So(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=kr(n,"defineExpose");if(!i||!i.arg||!i.arg.startsWith("{"))continue;let o=Pr(i.arg);if(o.length===0)return null;return`{ ${o.map((s)=>{if(s.value===""&&/^[A-Za-z_$][\w$]*$/.test(s.key))return`${Rr(s.key)}: typeof ${s.key}`;let a=s.isMethod||/=>|^\s*function\b/.test(s.value);return`${Rr(s.key)}: ${a?"(...args: any[]) => any":"unknown"}`}).join(", ")} }`}return null}function Al(e){let t=Xh(e),r="",n=null,i=null;if(t.script){let x=vo(t.script.content);if(x.passthrough)return t.scriptSetup?`${t.script.content}
113
- ${t.scriptSetup.content}`:t.script.content;if(r=x.script,x.options){let v=Ii(x.options,"props");if(v)n=Li(v);let G=Ii(x.options,"emits");if(G)i=$l(G)}}let o=t.scriptSetup?.content??null,s=o!==null?wo(o):null,a=Wi(o,o!==null?null:r),c=a?.type??n??"{}",f=Eo(o,null)??i,u=So(o,null),h=a?.inlinedLocal;if(h){if(r=Ni(r,h.name,h.declText),s!==null)s=Ni(s,h.name,h.declText)}let l=[c,u??"{}"];if(f)l.push("{}","{}","{}","{}","{}",f);let y=bo(`DefineComponent<${l.join(", ")}>`),C=[],S=Fi(r,y);if(S.trim()!=="")C.push(S);if(s&&s.trim()!==""){let x=Fi(s,y);if(x.trim()!=="")C.push(x)}return C.push("import type { DefineComponent } from 'vue'"),C.push(`type __DtsxComponentType = ${y}`),C.push("const __dtsx_component__: __DtsxComponentType = null as unknown as __DtsxComponentType"),C.push("export default __dtsx_component__"),C.join(`
114
- `)}var bl;var $o=he(()=>{bl={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 Tl(e){return e.endsWith(".stx")}function ud(e){let t=[],r=/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi,n;while((n=r.exec(e))!==null){let i=n[1]??"",o=/\blang\s*=\s*["']([^"']+)["']/i.exec(i)?.[1]?.toLowerCase()??(/\b(?:type\s*=\s*["'](?:text\/)?typescript["']|typescript)\b/i.test(i)?"ts":"js"),s=/\bserver\b/i.test(i)?"server":/\bclient\b/i.test(i)?"client":"universal";t.push({content:n[2]??"",kind:"script",attrs:i,context:s,lang:o,start:n.index})}return t}function hd(e){let t=[],r=/^[ \t]*@ts[ \t]*(?:\r?\n|$)/gm,n;while((n=r.exec(e))!==null){let i=r.lastIndex,o=/^[ \t]*@endts[ \t]*(?:\r?\n|$)/gm;o.lastIndex=i;let s=o.exec(e),a=s?.index??e.length;if(t.push({content:e.slice(i,a),kind:"ts",attrs:"",context:"universal",lang:"ts",start:n.index}),!s)break;r.lastIndex=o.lastIndex}return t}function dd(e){return[...ud(e),...hd(e)].sort((t,r)=>t.start-r.start)}function md(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 pd(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 s=je(e,n,"{","}");if(s!==-1)return e.slice(n,s+1).trim();continue}let i=/^[A-Za-z_$][\w$]*/.exec(e.slice(n))?.[0];if(!i)continue;let o=n+i.length;while(o<e.length&&/\s/.test(e[o]))o++;if(e[o]==="<"){let s=je(e,o,"<",">");if(s!==-1)o=s+1}return e.slice(n,o).trim()}return null}function gd(e){return/\b(?:const|let|var)\s+\$?props\s*:\s*([^=;\n]+)/.exec(e)?.[1]?.trim()??null}function yd(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 Cd(e,t){if(!e||e==="unknown")return t;if(t==="unknown"||e===t)return e;return[...new Set([...e.split(" | "),...t.split(" | ")])].join(" | ")}function wd(e){let t=yo(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 o=i[1]??i[3],s=yd(e.slice(n.lastIndex));r.set(o,Cd(r.get(o),s))}if(r.size===0)return null;return{type:`{ ${[...r].map(([o,s])=>`${/^[A-Za-z_$][\w$]*$/.test(o)?o:JSON.stringify(o)}?: ${s}`).join(", ")} }`}}function vd(e){let t=Wi(e,null);if(t)return t;let r=pd(e)??gd(e);if(!r)return wd(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 Wi(`${e}
115
- defineProps<${r}>()`,null)}function bd(e){return wo(e)}function xl(e){let t=yo(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 Ed(e){let t=[],r=0,n=0,i=0;while(i<e.length){let s=e[i],a=go(e,i);if(a>i){i=a;continue}if(s==="{"||s==="["||s==="(")n++;else if(s==="}"||s==="]"||s===")")n=Math.max(0,n-1);if((s===";"||s===`
116
- `)&&n===0){let c=i+1;if(!xl(e.slice(r,c)))t.push([r,c]);r=c}i++}if(r<e.length&&!xl(e.slice(r)))t.push([r,e.length]);let o=e;for(let s=t.length-1;s>=0;s--)o=o.slice(0,t[s][0])+o.slice(t[s][1]);return o}function Ol(e){let t=dd(e).filter(md).map((S)=>S.content).join(`
117
- `),r=null,n=vo(t);if(n.passthrough)return t;if(t=n.script,n.options){let S=Ii(n.options,"props");if(S)r=Li(S)}let i=t,o=bd(t),s=vd(i),a=s?.type??r??"{}",c=Eo(i,null),f=So(i,null),u=kr(i,"defineSlots")?.generic??null,h=s?.inlinedLocal;if(h)o=Ni(o,h.name,h.declText);let l=`DefineComponent<${a}>`,y=[];if(c)y.push(`readonly __stxEmits?: ${c}`);if(u)y.push(`readonly __stxSlots?: ${u}`);if(f)y.push(`readonly __stxExposed?: ${f}`);if(y.length>0)l+=` & { ${y.join(", ")} }`;l=bo(l),o=Ed(Fi(o,l));let C=["import type { DefineComponent } from '@stacksjs/stx'",`type __DtsxStxComponentType = ${l}`,"const __dtsx_component__: __DtsxStxComponentType = null as unknown as __DtsxStxComponentType","export default __dtsx_component__"];if(o.trim()!=="")C.push(o);return C.join(`
118
- `)}var Rl=he(()=>{$o()});function xt(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}
119
- `;return`${n.trim()}
120
- `}let r="";for(let n=0;n<e.length;n++){if(n>0)r+=`
121
- `;r+=e[n].trim()}return`${r}
122
- `}function Do(e){return e.replaceAll("*/","*\\/")}function xo(e){return Fl(e).replace(/\n[ \t]*(?=\n)/g,"")}function Fl(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 Fo(){_i=!0,Xe=null}function No(){_i=!1;let e=Xe;return Xe=null,e}function Lo(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 Sd(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 Ao(e,t){let r=0,n=0;while((n=e.indexOf(t,n))!==-1)r++,n+=t.length;return r}function Pl(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 Bi(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&&Pl(t.charCodeAt(n)))n++;let i=t.slice(1,n),o=t.charCodeAt(n);if(o>32&&o!==62&&o!==47)return!1;if(t.endsWith("/>"))return!0;let s=t.lastIndexOf("</");if(s===-1)return!1;let a=s+2;while(a<t.length&&Pl(t.charCodeAt(a)))a++;return t.slice(s+2,a)===i&&t.charCodeAt(a)===62&&a===t.length-1}function Gi(e){let t=e.length,r=!1;for(let s=1;s<t;s++)if(e.charCodeAt(s)<=32&&e.charCodeAt(s-1)<=32){r=!0;break}if(!r)for(let s=0;s<t;s++){let a=e.charCodeAt(s);if(a===10||a===13||a===9){r=!0;break}}if(!r)return e;let n=[],i=-1,o=!1;for(let s=0;s<t;s++)if(e.charCodeAt(s)<=32){if(!o){if(i>=0)n.push(e.substring(i,s));n.push(" "),o=!0,i=-1}}else{if(o||i<0)i=s;o=!1}if(i>=0)n.push(e.substring(i));return n.join("")}function Ie(e,t=!1,r=!1,n=0){if(!e||typeof e!=="string")return"unknown";if(n>=Io)return"unknown";let i=e.trim();if(Bi(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(`
123
- `)||i.includes("\r"))return"string";return i}if(i.charCodeAt(0)===39||i.charCodeAt(0)===34){let s=$d(i);if(s!==null){if(s==="string"||!t)return"string";return s}}if(Lo(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 Ro(i,t,n+1);if(i.startsWith("{")&&i.endsWith("}"))return Ld(i,t,n+1);if(i.startsWith("class ")||i.startsWith("class{"))return Fd(i);if(i.startsWith("new "))return Id(i);if(i.endsWith("as const")){let s=i.slice(0,-8).trim();if(s.startsWith("[")&&s.endsWith("]")){let a=s.slice(1,-1).trim();if(!a)return"readonly []";let c=ji(a),f=[];for(let u=0;u<c.length;u++)f.push(Ie(c[u].trim(),!0,!1,n+1));return`readonly [${f.join(", ")}]`}return Ie(s,!0,r,n+1)}if(dr(i)!==-1||i.startsWith("function")||i.startsWith("async"))return _l(i,r,n,t);if(i.startsWith("`")&&i.endsWith("`"))return Dd(i,t);if(i.startsWith("Promise."))return Wl(i,t,n);if(i.startsWith("await "))return"unknown";if(i.charCodeAt(i.length-1)===110&&i.length>1&&Sd(i)){if(t)return i;return"bigint"}if(i.startsWith("Symbol(")||i==="Symbol.for")return"symbol";let o=Bl(i);if(o!==null)return o;if(Nl(i))return"boolean";if(Od(i))return"number";return"unknown"}function kl(e){let t=e.charCodeAt(0);if(t!==39&&t!==34)return!1;return It(e,0,t)===e.length}function $d(e){if(kl(e))return e;let t=Ad(e);if(t.length<2)return null;let r=!1,n=!0,i="";for(let o of t){let s=o.trim();if(kl(s))r=!0,i+=xd(s);else n=!1}if(n)return Td(i);if(r)return"string";return null}function Ad(e){let t=[],r=0,n=0,i=0;while(i<e.length){let o=e.charCodeAt(i);if(o===39||o===34||o===96){i=It(e,i,o);continue}if(o===40||o===91||o===123)r++;else if(o===41||o===93||o===125)r--;else if(o===43&&r===0)t.push(e.slice(n,i)),n=i+1;i++}return t.push(e.slice(n)),t}function xd(e){return e.slice(1,-1).replace(/\\(.)/g,(t,r)=>{if(r==="n")return`
124
- `;if(r==="t")return"\t";if(r==="r")return"\r";if(r==="0")return"\x00";return r})}function Td(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function Od(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 Nl(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=It(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 Rd(e,t=!1,r=0){return Ie(e,t,!0,r)}function hr(e,t=!1,r=""){let n=To(r),i=[],o=!1,s=0;while(s<e.length){let c=e.charCodeAt(s);if(c===34||c===39||c===96){s=It(e,s,c);continue}if(c===47&&e.charCodeAt(s+1)===47){s+=2;while(s<e.length&&e.charCodeAt(s)!==10&&e.charCodeAt(s)!==13)s++;continue}if(c===47&&e.charCodeAt(s+1)===42){let f=e.indexOf("*/",s+2);s=f===-1?e.length:f+2;continue}if(e.startsWith("function",s)&&Mr(e,s,8)||e.startsWith("class",s)&&Mr(e,s,5)){let f=Md(e,s);if(f!==-1){s=Oo(e,f);continue}}if(c===61&&e.charCodeAt(s+1)===62){let f=s+2;while(f<e.length&&e.charCodeAt(f)<=32)f++;if(e.charCodeAt(f)===123){s=Oo(e,f);continue}}if(e.startsWith("return",s)&&(s===0||!At(e.charCodeAt(s-1)))&&!At(e.charCodeAt(s+6))){s+=6;let f=!1;while(s<e.length&&e.charCodeAt(s)<=32){let x=e.charCodeAt(s);if(x===10||x===13)f=!0;s++}if(f||s>=e.length||e.charCodeAt(s)===59||e.charCodeAt(s)===125){o=!0;continue}let u=s,h=0,l=0,y=0;while(s<e.length){let x=e.charCodeAt(s);if(x===34||x===39||x===96){s=It(e,s,x);continue}if(x===47&&e.charCodeAt(s+1)===47){if(h===0&&l===0&&y===0)break;while(s<e.length&&e.charCodeAt(s)!==10&&e.charCodeAt(s)!==13)s++;continue}if(x===47&&e.charCodeAt(s+1)===42){let v=e.indexOf("*/",s+2);s=v===-1?e.length:v+2;continue}if(x===40)h++;else if(x===41)h--;else if(x===91)l++;else if(x===93)l--;else if(x===123)y++;else if(x===125){if(y===0&&h===0&&l===0)break;y--}else if(x===59&&h===0&&l===0&&y===0)break;else if((x===10||x===13)&&h===0&&l===0&&y===0){let v=s+1;while(v<e.length&&e.charCodeAt(v)<=32)v++;if(e.startsWith("return",v)&&!At(e.charCodeAt(v+6)))break}s++}let C=e.slice(u,s).trim(),S=xo(Dt(C,n));if(!i.includes(S))i.push(S);continue}s++}if(o&&!i.includes("undefined"))i.push("undefined");let a=i.includes("unknown")?"unknown":i.length===0?"void":Ll(i);return t&&!a.startsWith("Promise<")?`Promise<${a}>`:a}function To(e){let t=new Map,r=e.startsWith("(")&&e.endsWith(")")?e.slice(1,-1):e,n=0,i=0,o=0;for(let s=0;s<=r.length;s++){let a=r.charCodeAt(s);if(a===40||a===91||a===123)i++;else if(a===41||a===93||a===125)i--;else if(a===60)o++;else if(a===62&&r.charCodeAt(s-1)!==61&&o>0)o--;if(s!==r.length&&(a!==44||i!==0||o!==0))continue;let c=r.slice(n,s).trim(),f=c.indexOf(":");if(f!==-1){let u=c.slice(0,f).trim().replace(/^\.\.\./,"").replace(/\?$/,""),h=c.slice(f+1).trim(),l=h.indexOf("=");if(l!==-1)h=h.slice(0,l).trim();if(Dr(u)&&h)t.set(u,h)}n=s+1}return t}function Dt(e,t){let r=e.trim();while(Wo(r))r=r.slice(1,-1).trim();if(Bi(r))return"JSX.Element";if(r.startsWith("await ")){let o=Dt(r.slice(6),t);return o.startsWith("Promise<")&&o.endsWith(">")?o.slice(8,-1):o}if(t.has(r))return t.get(r);if(r.startsWith("!"))return"boolean";if(r.startsWith("fetch("))return"Promise<Response>";if(Pd(r))return Ie(r,!1);let n=kd(r);if(n){let o=Dt(n.whenTrue,t),s=Dt(n.whenFalse,t);return o===s?o:Ll([o,s])}if(Nl(r))return"boolean";let i=0;for(let o=r.length-1;o>=0;o--){let s=r.charCodeAt(o);if(s===41||s===93||s===125)i++;else if(s===40||s===91||s===123)i--;else if(i===0&&(s===43||s===45||s===42||s===47||s===37)){let a=Dt(r.slice(0,o),t),c=Dt(r.slice(o+1),t);if(s===43&&(a==="string"||c==="string"))return"string";if(a==="number"&&c==="number")return"number";break}}return Ie(r,!1).replace(/\btypeof\s+[$A-Z_a-z][$\w]*/g,(o)=>{let s=o.slice(7);return t.get(s)??"unknown"})}function Ll(e){return e.map((t)=>e.length>1&&dr(t)!==-1?`(${t})`:t).join(" | ")}function Pd(e){if(e.startsWith("function")&&Mr(e,0,8))return!0;let t=dr(e);if(t===-1)return!1;let r=e.slice(0,t).trim();if(r.startsWith("async")&&Mr(r,0,5))r=r.slice(5).trim();if(r.startsWith("<")){let i=Qe(r,0,"<",">");if(i===-1)return!1;r=r.slice(i+1).trim()}if(r.startsWith("(")){let i=Qe(r,0,"(",")");if(i===-1)return!1;let o=r.slice(i+1).trim();if(o&&!o.startsWith(":"))return!1}let n=Mo(r);return Wo(n.params)||Dr(n.params)}function Wo(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 kd(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 Mr(e,t,r){return(t===0||!At(e.charCodeAt(t-1)))&&!At(e.charCodeAt(t+r))}function Md(e,t){for(let r=t;r<e.length;r++){let n=e.charCodeAt(r);if(n===34||n===39||n===96){r=It(e,r,n)-1;continue}if(n===123)return r;if(n===59)return-1}return-1}function Oo(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=It(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 o=e.indexOf("*/",n+2);n=o===-1?e.length:o+2;continue}if(i===123)r++;else if(i===125)r--;n++}return n}function It(e,t,r){let n=t+1;while(n<e.length){let i=e.charCodeAt(n);if(i===92){n+=2;continue}if(r===96&&i===36&&e.charCodeAt(n+1)===123){n=Oo(e,n+1);continue}if(n++,i===r)break}return n}function Dd(e,t){if(e.includes(".raw`")||e.includes("String.raw`"))return"string";if(!t||e.includes("${")||e.includes(`
125
- `)||e.includes("\r"))return"string";return e}function Id(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&&(At(e.charCodeAt(t))||e.charCodeAt(t)===46))t++;if(t===r)return"unknown";let i=e.slice(r,t);{let o=e.slice(t),s=o;if(o.startsWith("<")){let c=0,f=-1;for(let u=0;u<o.length;u++)if(o[u]==="<")c++;else if(o[u]===">"){if(c--,c===0){f=u;break}}if(f!==-1){let u=o.slice(0,f+1);s=o.slice(f+1);let h=s.indexOf("(");if(h!==-1){let l=0,y=-1;for(let C=h;C<s.length;C++)if(s[C]==="(")l++;else if(s[C]===")"){if(l--,l===0){y=C;break}}if(y!==-1){if(s.slice(y+1).trimStart().startsWith("."))return"unknown"}}return`${i}${u}`}}let a=s.indexOf("(");if(a!==-1){let c=0,f=-1;for(let u=a;u<s.length;u++)if(s[u]==="(")c++;else if(s[u]===")"){if(c--,c===0){f=u;break}}if(f!==-1){if(s.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 Fd(e){return"{ new (...args: any[]): any }"}function Wl(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<${Ie(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 o=e.slice(n+1,i).trim(),s=ji(o),a=[];for(let c=0;c<s.length;c++){let f=s[c].trim();if(f.startsWith("Promise.resolve(")){let u=Wl(f,t,r+1),h=u.indexOf("<"),l=u.lastIndexOf(">");a.push(h!==-1&&l>h?u.slice(h+1,l):"unknown")}else a.push(Ie(f,t,!1,r+1))}return`Promise<[${a.join(", ")}]>`}return"Promise<unknown[]>"}return"Promise<unknown>"}function Ro(e,t,r=0){let n=e.slice(1,-1).trim();if(!n)return"never[]";if(r>=Io)return"unknown[]";let i=ji(n),o=!1;for(let l=0;l<i.length;l++){let y=i[l],C=y.length;while(C>0&&y.charCodeAt(C-1)<=32)C--;if(C>=8&&y.slice(C-8,C)==="as const"){o=!0;break}}if(o){let l=[];for(let y=0;y<i.length;y++){let C=i[y].trim();if(C.endsWith("as const")){let S=C.slice(0,-8).trim();if(S.startsWith("[")&&S.endsWith("]")){let x=S.slice(1,-1).trim(),v=ji(x),G=[];for(let L=0;L<v.length;L++)G.push(Ie(v[L].trim(),!0,!1,r+1));l.push(`readonly [${G.join(", ")}]`)}else l.push(Ie(S,!0,!1,r+1))}else if(C.startsWith("[")&&C.endsWith("]"))l.push(Ro(C,!0,r+1));else l.push(Ie(C,!0,!1,r+1))}return`readonly [
126
- ${l.join(` |
127
- `)}
128
- ]`}let s=_i&&!t,a=[],c=[];for(let l of i){let y=l.trim(),C=Xe;if(Xe=null,y.startsWith("...")){let S=y.slice(3).trim(),x=Ie(S,!1,!1,r+1);if(x.endsWith("[]"))a.push(x.slice(0,-2));else if(x.startsWith("readonly [")&&x.endsWith("]"))a.push(x.slice(10,-1));else if(ur(S))a.push(`(typeof ${S})[number]`);else a.push("unknown")}else if(y.startsWith("[")&&y.endsWith("]"))a.push(Ro(y,t,r+1));else a.push(Rd(y,t,r+1));if(s)c.push(Xe);Xe=C}if(s)if(ko(e))Xe=Gi(e);else{let l=[];for(let y=0;y<i.length;y++){let C=i[y].trim();if(C.endsWith("as const"))continue;if(Po(C)||C==="null"||C==="undefined")l.push(C);else if(C.startsWith("[")&&ko(C))l.push(Gi(C));else if(C.startsWith("{")){if(c[y])l.push(c[y])}else{let S=Ie(C,!1,!1,0);if(S!=="unknown")l.push(S)}}if(l.length>0)Xe=`[${l.join(", ")}]`}if(t)return`readonly [${a.join(", ")}]`;let f=new Set,u=[],h=!0;for(let l of a){if(!f.has(l))f.add(l),u.push(l);if(h){if(!(Lo(l)||l==="true"||l==="false"||l.charCodeAt(0)===34&&l.charCodeAt(l.length-1)===34||l.charCodeAt(0)===39&&l.charCodeAt(l.length-1)===39))h=!1}}if(h&&a.length<=10)return`readonly [${a.join(", ")}]`;if(u.length===1)return`${u[0]}[]`;return`(${u.join(" | ")})[]`}function ji(e){let t=[],r=0,n=0,i=!1,o=0;for(let a=0;a<e.length;a++){let c=e.charCodeAt(a);if(!i&&(c===34||c===39||c===96))i=!0,o=c;else if(i&&c===o&&(a===0||e.charCodeAt(a-1)!==92))i=!1;if(!i){if(c===91||c===123||c===40)n++;else if(c===93||c===125||c===41)n--;else if(c===44&&n===0){let f=e.substring(r,a).trim();if(f)t.push(f);r=a+1;continue}}}let s=e.substring(r).trim();if(s)t.push(s);return t}function Po(e){if(Lo(e))return!0;if(e==="true"||e==="false")return!0;if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return!0;return!1}function Nd(e){return e==="number"||e==="string"||e==="boolean"}function ko(e){let t=!1,r=0,n=e.length;for(let i=0;i<n;i++){let o=e.charCodeAt(i);if(t){if(o===92){i++;continue}if(o===r)t=!1;continue}if(o===34||o===39||o===96){t=!0,r=o;continue}if(o===61&&i+1<n&&e.charCodeAt(i+1)===62)return!1;if(o>=97&&o<=122){let s=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(s,i);if(a==="new"||a==="async"||a==="await"||a==="function"||a==="yield"||a==="console"||a==="process")return!1;let c=i;while(c<n&&e.charCodeAt(c)<=32)c++;if(c<n&&e.charCodeAt(c)===40)return!1;i--}}return!0}function Ld(e,t,r=0){let n=e.slice(1,-1).trim();if(!n)return"{}";if(r>=Io)return"Record<string, unknown>";let i=jd(n),o=[],s=[],a=_i&&!t,c=[];for(let[h,l]of i){let{comments:y,key:C}=jl(h),S=y?`${y}
129
- `:"",x=C,v=!1;if(C==="..."){let U=l.trim(),H=ur(U)?`typeof ${U}`:Ie(U,t,!1,r+1);if(H!=="unknown")s.push(H);if(a&&(ur(U)||U.startsWith("{")))c.push(`...${Gi(U)}`);continue}let G=Xe;Xe=null;let L,P=l.trim();if(P===C&&Dr(P))L=`typeof ${P}`;else if(Ud(P)){v=!0;let U=Kd(C);if(U){x=U.name;let H="";if(P.startsWith("async "))H="async ";if(P.charCodeAt(H.length)===42)H+="*";L=Il(U.name,H+U.typeParams+P.slice(H.length))}else L=Il(C,P)}else{if(L=Ie(l,t,!1,r+1),L==="unknown"&&ur(P))L=`typeof ${P}`;if(L.includes("=>")||L.includes("function")||L.includes("async"))L=Ml(L)}let F=Xe;Xe=G;let I=l.trim(),k=_d(C);if(k){let U=Vd(k.kind,k.name,L);if(U){o.push(`${S}${U}`);continue}}if(!t&&Nd(L)&&Po(I))o.push(`${S}/** @defaultValue ${Do(I)} */
130
- ${x}: ${L}`);else o.push(`${S}${x}: ${L}`);if(a){let U=Fl(x);if(I.endsWith("as const"));else if(Po(I))c.push(`${U}: ${I}`);else if(I.startsWith("[")&&ko(I))c.push(`${U}: ${Gi(I)}`);else if(I.startsWith("{")){if(F)c.push(`${U}: ${F}`)}else if(v)c.push(`${U}: ${xo(Ml(L))}`);else if(!I.startsWith("[")&&(I.includes("=>")||I.startsWith("function")||I.startsWith("async"))){let H=_l(I,!1,0,!0);c.push(`${U}: ${xo(H)}`)}}}if(a&&c.length>0){let h=r>0?(r-1)/2:0,l=`{ ${c.join(", ")} }`;if(l.length<=80)Xe=l;else{let y=" ".repeat((h+1)*2),C=" ".repeat(h*2);Xe=`{
131
- ${y}${c.join(`,
132
- ${y}`)}
133
- ${C}}`}}let f=o.length>0?`{
134
- ${o.join(`;
135
- `)}
136
- }`:"{}";if(s.length===0)return f;let u=s[0];for(let h=1;h<s.length;h++)u=`Omit<${u}, keyof ${s[h]}> & ${s[h]}`;return o.length>0?`Omit<${u}, keyof ${f}> & ${f}`:u}function Dr(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(!At(e.charCodeAt(r)))return!1;return!0}function ur(e){let t=e.split(".");return t.length>0&&t.every(Dr)}function Wd(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 o=Qe(e,n,"<",">");if(o!==-1)n=o}}return-1}function Bl(e){if(e.length<3||!e.endsWith(")"))return null;let t=Wd(e);if(t===-1||Qe(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,o=!1,s=r.indexOf("<");if(s!==-1){if(Qe(r,s,"<",">")!==r.length-1)return null;i=r.slice(0,s).trim(),o=!0}if(!ur(i))return null;let a=e.slice(t+1,-1).trim(),c=dr(a)!==-1||a.startsWith("function")||a.startsWith("async function"),f=ur(a),u=!c&&a.endsWith(")")&&Bl(a)!==null;if(!o&&!n&&!c&&!f&&!u)return null;let h=`ReturnType<typeof ${r}>`;return n?`${h} | undefined`:h}function Ml(e){let t=e.split(`
137
- `).map((f)=>Gl(f)).join(`
138
- `),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(!At(f)&&!At(u))t=(t.slice(0,r)+t.slice(r+5)).trim()}let n=t.indexOf("(");if(n!==-1){let f=Qe(t,n,"(",")");if(f!==-1){let u=t.slice(n,f+1),h=Gt(u);t=t.slice(0,n)+h+t.slice(f+1)}}let i=t.length,o="",s=[],a=!1,c=!1;for(let f=0;f<i;f++){let u=t.charCodeAt(f);if(u===123||u===40)s.push(u);else if(u===125||u===41)s.pop();if(u<=32){if(a=!0,u===10||u===13)c=!0;continue}if(a&&o.length>0){let h=(s.length>0?s[s.length-1]:0)===123;if(c&&h){let l=o.charCodeAt(o.length-1),y=l===59||l===44||l===123||u===125,C=o.length>=2&&o.charCodeAt(o.length-1)===47&&o.charCodeAt(o.length-2)===42;if(!y&&!C)o+="; ";else o+=" "}else o+=" "}a=!1,c=!1,o+=t[f]}return o.trim()}function At(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 o=!1;{let C=0;for(let S=0;S<i.length;S++){let x=i.charCodeAt(S);if(x===40||x===60||x===91||x===123)C++;else if(x===41||x===93||x===125||x===62&&i.charCodeAt(S-1)!==61)C--;else if(C===0&&x===61){let v=S>0?i.charCodeAt(S-1):0,G=S+1<i.length?i.charCodeAt(S+1):0;if(v!==61&&v!==33&&v!==60&&v!==62&&G!==61&&G!==62){o=!0;break}}}}if(!o)return t;let s=[],a=[],c=0,f=0,u=!1,h=0;for(let C=0;C<=i.length;C++){if(C===i.length){s.push(i.slice(c));break}let S=i.charCodeAt(C);if(u){if(S===92){C++;continue}if(S===h)u=!1;continue}if(S===47&&C+1<i.length){let x=i.charCodeAt(C+1);if(x===42){C+=2;while(C+1<i.length&&!(i.charCodeAt(C)===42&&i.charCodeAt(C+1)===47))C++;C++;continue}if(x===47){while(C<i.length&&i.charCodeAt(C)!==10)C++;continue}}if(S===39||S===34||S===96){u=!0,h=S;continue}if(S===40||S===60||S===91||S===123)f++;else if(S===41||S===93||S===125||S===62&&i.charCodeAt(C-1)!==61)f--;else if(S===44&&f===0){s.push(i.slice(c,C));let x=",",v=C+1;while(v<i.length&&i.charCodeAt(v)<=32)x+=i[v],v++;a.push(x),c=v}}let l=[];for(let C of s){let S=C.trim();if(!S){l.push(C);continue}if(S.startsWith("//"))continue;let x=Gl(S),v=C.slice(0,C.length-C.trimStart().length);l.push(v+Bd(x))}let y=l[0]||"";for(let C=1;C<l.length;C++)y+=(a[C-1]||", ")+l[C];return n?`(${y})`:y}function Gl(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 Bd(e){if(e.startsWith("..."))return e;let t=-1,r=-1,n=0,i=!1,o=0;for(let a=0;a<e.length;a++){let c=e.charCodeAt(a);if(i){if(c===92){a++;continue}if(c===o)i=!1;continue}if(c===47&&a+1<e.length){let f=e.charCodeAt(a+1);if(f===42){a+=2;while(a+1<e.length&&!(e.charCodeAt(a)===42&&e.charCodeAt(a+1)===47))a++;a++;continue}if(f===47){while(a<e.length&&e.charCodeAt(a)!==10)a++;continue}}if(c===39||c===34||c===96){i=!0,o=c;continue}if(c===40||c===60||c===91||c===123)n++;else if(c===41||c===93||c===125||c===62&&e.charCodeAt(a-1)!==61)n--;else if(n===0){if(c===58&&t===-1)t=a;else if(c===61&&r===-1&&(a===0||e.charCodeAt(a-1)!==61)&&(a+1>=e.length||e.charCodeAt(a+1)!==61&&e.charCodeAt(a+1)!==62))r=a}}let s=r!==-1;if(t!==-1&&(r===-1||t<r)){let a=e.slice(0,t).trim(),c=r!==-1?e.slice(t+1,r).trim():e.slice(t+1).trim(),f=s&&!a.endsWith("?")?"?":"";return`${a}${f}: ${c}`}else if(r!==-1){let a=e.slice(0,r).trim(),c=!a.endsWith("?")?"?":"",f=e.slice(r+1).trim(),u="unknown";if(f==="true"||f==="false")u="boolean";else if(/^-?\d+(\.\d+)?$/.test(f))u="number";else if(f.startsWith("'")&&f.endsWith("'")||f.startsWith('"')&&f.endsWith('"'))u="string";else if(f.startsWith("["))u="unknown[]";else if(f.startsWith("{"))u="Record<string, unknown>";return`${a}${c}: ${u}`}return e}function Gd(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 jl(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(`
139
- `),key:e.slice(r).trim()}}function jd(e){let t=[],r="",n="",i=0,o=!1,s="",a=!0,c=!1,f=0,u=!1,h=!1,l=0,y=!1,C=!1;for(let S=0;S<e.length;S++){let x=e.charCodeAt(S),v=S>0?e.charCodeAt(S-1):0,G=S<e.length-1?e.charCodeAt(S+1):0;if(!o&&!c&&x===47&&G===47){r=r.replace(/[ \t]+$/,""),S+=2;while(S<e.length&&e.charCodeAt(S)!==10)S++;S--;continue}if(!o&&!c&&x===47&&G===42){c=!0,f=1,r+="/*",S++;continue}else if(c&&x===42&&G===47){if(f--,r+="*/",S++,f===0)c=!1;continue}else if(c&&x===47&&G===42){f++,r+="/*",S++;continue}let L=e[S];if(!o&&!c&&(x===34||x===39||x===96))o=!0,s=L,r+=L;else if(o&&L===s&&v!==92)o=!1,r+=L;else if(!o&&!c)if(x===40&&i===0&&a&&l===0){n=r.trim();let P=Gd(n),F=P>0?n.slice(0,P):"",I=n.slice(P),k="";if(I.startsWith("async ")||I.startsWith("async\t")||I.startsWith(`async
140
- `))I=I.slice(6).trimStart(),k="async ";if(I.startsWith("*"))I=I.slice(1).trimStart(),k+="*";n=F+I,r=k+L,a=!1,y=!0,C=!1,i=1}else if(x===123||x===91||x===40){if(i++,r+=L,C&&x===123)C=!1}else if(x===125||x===93||x===41){if(i--,r+=L,x===41&&i===0&&!a&&!y)u=!0;if(y){if(x===41&&i===0&&!C)C=!0;else if(x===125&&i===0)y=!1,C=!1}}else if(x===58&&i===0&&a&&l===0)n=r.trim(),r="",a=!1;else if(x===58&&i===0&&u)h=!0,r+=L;else if(x===60&&h)l++,r+=L;else if(x===60&&a&&i===0)l++,r+=L;else if(x===62&&l>0&&v!==61)l--,r+=L;else if(x===61&&G===62&&h&&l===0)h=!1,u=!1,r+=L;else if(x===44&&i===0&&l===0&&!C){if(n&&r.trim()){let P=r.trim();t.push([n,P])}else if(a&&r.trim())Dl(t,r.trim());r="",n="",a=!0,u=!1,h=!1,l=0}else r+=L;else r+=L}if(n&&r.trim()){let S=r.trim();t.push([n,S])}else if(a&&r.trim())Dl(t,r.trim());return t}function Dl(e,t){let{comments:r,key:n}=jl(t);if(Dr(n))e.push([r?`${r}
141
- ${n}`:n,n]);else if(n.startsWith("...")&&n.length>3)e.push(["...",n.slice(3).trim()])}function _d(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 Vd(e,t,r){let n=r.trim();if(n.charCodeAt(0)!==40)return null;let i=Qe(n,0,"(",")");if(i===-1)return null;let o=n.slice(1,i).trim(),s=n.slice(i+1).trimStart();if(!s.startsWith("=>"))return null;let a=s.slice(2).trim();if(e==="get")return`get ${t}(): ${a||"unknown"}`;return`set ${t}(${o})`}function Ud(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 o=t.slice(n+1).trimStart();if(o.startsWith("{"))return!0;if(o.startsWith(":")){let s=Bo(o,1);if(s?.kind==="arrow")return!1;if(s?.kind==="body")return!0}return!1}}}return!1}function Kd(e){let t=e.trimEnd();if(!t.endsWith(">"))return null;let r=0,n=-1;for(let o=t.length-1;o>=0;o--){let s=t.charCodeAt(o);if(s===62){if(o>0&&t.charCodeAt(o-1)===61)continue;r++}else if(s===60){if(r--,r===0){n=o;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 Il(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 o="";if(r.charCodeAt(0)===60){let l=0,y=-1;for(let C=0;C<r.length;C++)if(r.charCodeAt(C)===60)l++;else if(r.charCodeAt(C)===62&&!(C>0&&r.charCodeAt(C-1)===61)){if(l--,l===0){y=C;break}}if(y!==-1)o=r.slice(0,y+1),r=r.slice(y+1).trimStart()}let s=r.indexOf("("),a=Qe(r,s,"(",")");if(s===-1||a===-1)return"() => unknown";let c=r.slice(s,a+1),f="unknown",u=r.slice(a+1).trimStart();if(u.charCodeAt(0)===58){let l=u.slice(1),y=Bo(l,0);if(y)f=l.slice(0,y.index).trim();else f=l.trim()}if(f==="unknown"&&!i&&u.charCodeAt(0)===123){let l=Qe(u,0,"{","}");if(l!==-1){let y=hr(u.slice(1,l),n,c);if(y!=="unknown"&&y!=="Promise<unknown>")f=n&&y.startsWith("Promise<")?y.slice(8,-1):y;else if(n)f="Promise<unknown>"}}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 h=Gt(c);return`${o}${h} => ${f}`}function Bo(e,t){let r=0,n=0,i=0,o=0,s=!1,a=0;for(let c=t;c<e.length;c++){let f=e.charCodeAt(c);if(s){if(f===92)c++;else if(f===a)s=!1;continue}if(f===34||f===39||f===96){s=!0,a=f;continue}if(f===40)r++;else if(f===41&&r>0)r--;else if(f===91)n++;else if(f===93&&n>0)n--;else if(f===60)i++;else if(f===62&&i>0&&e.charCodeAt(c-1)!==61)i--;else if(f===125&&o>0)o--;else if(f===123){let u=r>0||n>0||i>0||o>0,h=e.slice(t,c).trimEnd(),l=h.charCodeAt(h.length-1),y=h.length===0||l===38||l===124||l===40||l===44||l===58||l===61||l===91;if(u||y)o++;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&&o===0)return{index:c,kind:"arrow"}}return null}function Qe(e,t,r,n){let i=0;for(let o=t;o<e.length;o++)if(e[o]===r)i++;else if(e[o]===n){if(n===">"&&o>0&&e[o-1]==="=")continue;if(i--,i===0)return o}return-1}function dr(e){let t=0,r=0,n=!1,i="";for(let o=0;o<e.length-1;o++){let s=e[o],a=e[o+1],c=o>0?e[o-1]:"";if(!n&&(s==='"'||s==="'"||s==="`"))n=!0,i=s;else if(n&&s===i&&c!=="\\")n=!1;if(!n){if(s==="<"){let f=Qe(e,o,"<",">");if(f!==-1){o=f;continue}}if(s==="(")t++;else if(s===")")t--;else if(s==="[")r++;else if(s==="]")r--;if(s==="="&&a===">"&&t===0&&r===0)return o}}return-1}function _l(e,t=!1,r=0,n=!0){let i=e.trim();if(i.length>200&&Ao(i,"=>")>2&&Ao(i,"<")>5&&!i.startsWith("function"))return t?"((...args: any[]) => any)":"(...args: any[]) => any";if(i.startsWith("async ")&&i.includes("=>")){let s=i.slice(5).trim(),a=dr(s);if(a===-1)return t?"(() => Promise<unknown>)":"() => Promise<unknown>";let c=s.substring(0,a).trim(),f=s.substring(a+2).trim(),u=Mo(c),{params:h,returnType:l}=u;if(h=Gt(h),h==="()"||h==="")h="()";else if(!h.startsWith("("))h=`(${h})`;let y=l;if(y);else if(f.startsWith("{"))y=hr(f.slice(1,f.endsWith("}")?-1:void 0),!0,h);else y=Dt(f,To(h));let C=`${h} => ${l||y.startsWith("Promise<")?y:`Promise<${y}>`}`;return t?`(${C})`:C}if(i.includes("=>")){let s="",a=i;if(i.startsWith("<")){let x=Qe(i,0,"<",">");if(x!==-1)s=i.substring(0,x+1),a=i.substring(x+1).trim()}let c=dr(a);if(c===-1)return t?"(() => unknown)":"() => unknown";let f=a.substring(0,c).trim(),u=a.substring(c+2).trim(),h=Mo(f),{params:l,returnType:y}=h;if(l=Gt(l),l==="()"||l==="")l="()";else if(!l.startsWith("("))l=`(${l})`;let C="unknown";if(y)C=y;else if(u.startsWith("{"))C=hr(u.slice(1,u.endsWith("}")?-1:void 0),!1,l);else if(Bi(u)||Wo(u)&&Bi(u.slice(1,-1).trim()))C="JSX.Element";else if(u.includes("=>")){let x=u.trimStart(),v=x.indexOf("("),G=v!==-1?Qe(x,v,"(",")"):-1,L=G!==-1?x.indexOf("=>",G):-1;if(v===0&&G!==-1&&L!==-1){let P=x.substring(v+1,G).trim(),F=Gt(P);if(s.includes("T")&&F.includes("T"))C=`(${F}) => T`;else C=`(${F}) => any`}else C="any"}else if(t)C="unknown";else C=Dt(u,To(l));let S=`${s}${l} => ${C}`;return t?`(${S})`:S}if(i.startsWith("function")){let s=8,a=i.length;while(s<a&&i.charCodeAt(s)<=32)s++;let c=!1;if(s<a&&i.charCodeAt(s)===42){c=!0,s++;while(s<a&&i.charCodeAt(s)<=32)s++}let f="";if(s<a&&i.charCodeAt(s)===60){let l=s,y=1;s++;while(s<a&&y>0){let C=i.charCodeAt(s);if(C===60)y++;else if(C===62&&i.charCodeAt(s-1)!==61)y--;s++}f=i.substring(l,s);while(s<a&&i.charCodeAt(s)<=32)s++}let u=i.indexOf("(",s);if(u!==-1){let l=1,y=u+1;while(y<a&&l>0){let L=i.charCodeAt(y);if(L===40)l++;else if(L===41)l--;y++}let C=i.substring(u+1,y-1).trim(),S=C?Gt(`(${C})`):"()";if(c){let L=i.substring(y).trim(),P=L.indexOf("Generator<");if(P!==-1){let I=P+10,k=L.indexOf(">",I);if(k!==-1){let U=L.substring(I,k),H=`${f}${S} => Generator<${U}>`;return t?`(${H})`:H}}let F=`${f}${S} => Generator<any, any, any>`;return t?`(${F})`:F}let x="unknown",v=i.substring(y).trimStart();if(v.charCodeAt(0)===58){let L=v.slice(1),P=Bo(L,0),F=(P?L.slice(0,P.index):L).trim();if(F)x=F}let G=`${f}${S} => ${x}`;return t?`(${G})`:G}let h="(...args: any[]) => unknown";return t?`(${h})`:h}if(i.includes("=>")&&i.includes("(")&&i.includes(")")){if(i.length>100||Ao(i,"=>")>2){let s="";if(i.charCodeAt(0)===60){let h=Qe(i,0,"<",">");if(h!==-1)s=i.substring(0,h+1)}let a=i.indexOf("("),c=a!==-1?Qe(i,a,"(",")"):-1,f=a!==-1&&c!==-1?i.substring(a,c+1):"(...args: any[])";f=Gt(f);let u=`${s}${f} => any`;return t?`(${u})`:u}return t?`(${i})`:i}let o="() => unknown";return t?`(${o})`:o}function Mo(e){let t=e.trim();if(!t.startsWith("("))return{params:t,returnType:""};let r=Qe(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 Vl(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 Vi(e){let t=-1,r=0;for(let i=0;i<e.length;i++){let o=e.charCodeAt(i);if(o===34||o===39||o===96){i=It(e,i,o)-1;continue}if(o===47&&e.charCodeAt(i+1)===47){while(i<e.length&&e.charCodeAt(i)!==10)i++;continue}if(o===47&&e.charCodeAt(i+1)===42){let s=e.indexOf("*/",i+2);i=s===-1?e.length:s+1;continue}if(o===47){let s=i-1;while(s>=0&&e.charCodeAt(s)<=32)s--;if(s<0||"([{:;,=!?&|+*-~>".includes(e[s])){let a=!1;for(i++;i<e.length;i++){let c=e.charCodeAt(i);if(c===92)i++;else if(c===91)a=!0;else if(c===93)a=!1;else if(c===47&&!a)break}continue}}if(o===40||o===91||o===123)r++;else if(o===41||o===93||o===125)r--;else if(r===0&&e.startsWith("satisfies",i)&&Mr(e,i,9)&&e[i-1]!==".")t=i}if(t===-1)return null;let n=e.slice(t+9).trim();if(n.endsWith(";"))n=n.slice(0,-1).trim();return n||null}var Io=20,_i=!1,Xe=null;var Go=()=>{};function _e(e){return e===Me||e===De||e===ve||e===xe}function Jd(e){let t=!0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n===gt){if(t)return!1;t=!0}else if(t){if(!yt(n))return!1;t=!1}else if(!Ue(n))return!1}return e.length>0&&!t}function Ki(e,t,r){let n=t+1;while(n<e.length){let i=e.charCodeAt(n);if(i===nt){n+=2;continue}if(n++,i===r)break}return n}function qd(e){if(e==="any"||e==="object"||e==="unknown")return!0;if(e.startsWith("Record<")||e.startsWith("Array<"))return!0;return e.charCodeAt(0)===J&&e.includes("[")&&e.includes("]:")}function Hl(e,t,r=!0){return Jl(e,t,r,!0)}function zl(e,t,r=!0){return Jl(e,t,r,!1)}function Jl(e,t,r,n){let i=e,o=r,s=n,a=i.length,c=[],f=new Map,u=new Map,h=new Set,l=0;function y(d){let p=u.get(d.name);if(p)p.push(d);else u.set(d.name,[d]);f.set(d.name,d)}if(l<a&&i.charCodeAt(l)===65279)l++;function C(d,p){if(d<p){let m=i.charCodeAt(d),g=i.charCodeAt(p-1);if(m!==Me&&m!==De&&m!==ve&&m!==xe&&g!==Me&&g!==De&&g!==ve&&g!==xe)return i.slice(d,p)}while(d<p&&_e(i.charCodeAt(d)))d++;while(p>d&&_e(i.charCodeAt(p-1)))p--;return i.slice(d,p)}let S=/[\r\n]/g;function x(d){return S.lastIndex=d,S.exec(i)?.index??a}function v(){if(l>=a)return;let d=i.charCodeAt(l);if(d!==Me&&d!==De&&d!==ve&&d!==xe&&d!==ee)return;while(l<a){let p=i.charCodeAt(l);if(p===Me||p===De||p===ve||p===xe){l++;continue}if(p===ee&&l+1<a){let m=i.charCodeAt(l+1);if(m===ee){l=x(l+2);continue}if(m===Ae){let g=i.indexOf("*/",l+2);l=g===-1?a:g+2;continue}}break}}function G(d){let p=d.length,m=0,g=p;for(let w=0;w<p;w++){let b=d.charCodeAt(w);if(m){if(b===nt){w++;continue}if(b===m)m=0;continue}if(b===le||b===fe||b===Fe){m=b;continue}if(b===ee&&w+1<p){let T=d.charCodeAt(w+1);if(T===ee){g=w;while(g>0&&(d.charCodeAt(g-1)===Me||d.charCodeAt(g-1)===De))g--;return d.slice(0,g)}if(T===Ae){let R=d.indexOf("*/",w+2);if(R!==-1){d=`${d.slice(0,w)} ${d.slice(R+2)}`,w--;continue}}}}g=p;while(g>0&&(d.charCodeAt(g-1)===Me||d.charCodeAt(g-1)===De||d.charCodeAt(g-1)===xe))g--;return g<p?d.slice(0,g):d}function L(d){l++;let p=d===le?"'":'"';while(l<a){let m=i.indexOf(p,l);if(m===-1){l=a;return}let g=0,w=m-1;while(w>=0&&i.charCodeAt(w)===nt)g++,w--;if(g%2===0){l=m+1;return}l=m+1}}function P(){l++;let d=[];while(l<a){let p=i.charCodeAt(l);if(d.length===0){if(p===nt){l+=2;continue}if(p===Fe){l++;return}if(p===zd&&l+1<a&&i.charCodeAt(l+1)===J){l+=2,d.push(0);continue}l++;continue}if(p===le||p===fe){L(p);continue}if(p===Fe){P();continue}if(p===ee&&l+1<a){let m=i.charCodeAt(l+1);if(m===ee){l=x(l+2);continue}if(m===Ae){let g=i.indexOf("*/",l+2);l=g===-1?a:g+2;continue}if(k()){U();continue}l++;continue}if(p===J){d[d.length-1]++,l++;continue}if(p===Q){let m=d[d.length-1];if(m===0){d.pop(),l++;continue}d[d.length-1]=m-1,l++;continue}l++}}let F=!1;function I(){F=!1;let d=i.charCodeAt(l);if(d===le||d===fe)return L(d),!0;if(d===Fe)return P(),!0;if(d===ee&&l+1<a){let p=i.charCodeAt(l+1);if(p===ee)return l=x(l+2),!0;if(p===Ae){let m=i.indexOf("*/",l+2);return F=x(l+2)<(m===-1?a:m),l=m===-1?a:m+2,!0}if(k())return U(),!0}return!1}function k(){return Hr(i,l)}function U(){l=gr(i,l)}function H(){let d=l;while(l<a&&Ue(i.charCodeAt(l)))l++;return i.slice(d,l)}function O(d){if(l+d.length>a)return!1;for(let p=0;p<d.length;p++)if(i.charCodeAt(l+p)!==d.charCodeAt(p))return!1;if(l+d.length<a&&Ue(i.charCodeAt(l+d.length)))return!1;return!0}function z(d){let p=l+d;while(p<a){let m=i.charCodeAt(p);if(m===Me||m===De||m===ve||m===xe){p++;continue}return m!==gt&&m!==be}return!1}function pe(){if(!F)return!1;let d=l;v();let p=l>=a||Oe()||i.charCodeAt(l)===Q;return l=d,p}function Oe(){if(l>=a)return!1;switch(i.charCodeAt(l)){case 101:return O("export")||O("enum");case 105:return O("import")||O("interface");case 102:return O("function");case 99:return O("class")||O("const");case 116:return O("type");case 108:return O("let");case 118:return O("var");case 100:return O("declare")||O("default");case 109:return O("module");case 110:return O("namespace");case 97:return O("abstract")||O("async");default:return!1}}function ie(){let d=i.charCodeAt(l);if(d!==ve&&d!==xe)return!1;let p=l;if(l++,d===xe&&l<a&&i.charCodeAt(l)===ve)l++;while(l<a){let g=i.charCodeAt(l);if(g===Me||g===De||g===xe||g===ve){l++;continue}if(g===ee&&l+1<a){let w=i.charCodeAt(l+1);if(w===ee){l=x(l+2);continue}if(w===Ae){let b=i.indexOf("*/",l+2);l=b===-1?a:b+2;continue}}break}let m=l>=a||Oe()||i.charCodeAt(l)===Q;return l=p,m}function ne(d){let p=d-1;while(p>=0){let E=i.charCodeAt(p);if(E===Me||E===De||E===xe||E===ve){p--;continue}break}if(p<0)return!0;let m=i[p];if("+-*/%=<>&|^!~?:,.([{".includes(m))return!0;let g=p;while(g>0&&i.charCodeAt(g-1)!==ve)g--;let w=i.slice(g,p+1),b=w.lastIndexOf("<");if(b!==-1&&/^<[A-Za-z]/.test(w.slice(b))&&!w.slice(b).includes(">"))return!0;let T=p;while(T>=0&&/[a-z]/i.test(i[T]))T--;let R=i.slice(T+1,p+1);return["as","in","of","new","typeof","keyof","extends","instanceof","satisfies","await","return","yield","void"].includes(R)}function ue(){let d=i.charCodeAt(l);if(d!==ve&&d!==xe)return!1;if(ne(l))return!1;let p=l;l++;while(l<a){let b=i.charCodeAt(l);if(b===Me||b===De||b===xe||b===ve){l++;continue}if(b===ee&&l+1<a){let T=i.charCodeAt(l+1);if(T===ee){l=x(l+2);continue}if(T===Ae){let R=i.indexOf("*/",l+2);l=R===-1?a:R+2;continue}}break}let m=l<a?i[l]:"",g=i.slice(l,l+2),w=m==="."||m==="?"||m===":"||m===")"||m==="]"||m==="}"||m===","||m==="+"||m==="-"||m==="*"||m==="/"||m==="%"||m==="<"||m===">"||m==="="||m==="&"||m==="|"||m==="^"||m==="`"||g==="=>"||O("as")||O("satisfies")||O("instanceof")||O("in");return l=p,!w}function se(){let d=i.charCodeAt(l);if(d!==ve&&d!==xe)return!1;if(ne(l))return!1;let p=l;l++;while(l<a){let w=i.charCodeAt(l);if(w===Me||w===De||w===xe||w===ve){l++;continue}if(w===ee&&l+1<a){let b=i.charCodeAt(l+1);if(b===ee){l=x(l+2);continue}if(b===Ae){let T=i.indexOf("*/",l+2);l=T===-1?a:T+2;continue}}break}let m=l<a?i[l]:"",g=m==="|"||m==="&"||m==="["||m==="."||m==="?"||m===":"||m===">"||m===")"||m===","||O("extends");return l=p,!g}function W(){let d=i.charCodeAt(l);if(d!==ve&&d!==xe)return!1;let p=l;if(l++,d===xe&&l<a&&i.charCodeAt(l)===ve)l++;while(l<a){let g=i.charCodeAt(l);if(g===Me||g===De||g===xe||g===ve){l++;continue}if(g===ee&&l+1<a&&i.charCodeAt(l+1)===ee){l=x(l+2);continue}break}if(l>=a)return l=p,!0;let m=i.charCodeAt(l);if(m===124||m===38||m===gt||m===Ui||m===ft)return l=p,!1;if(O("extends")||O("keyof")||O("typeof")||O("infer")||O("is")||O("as")||O("in"))return l=p,!1;return l=p,!0}let K=/[{}'"`\/]/g,q=/[()'"`\/]/g,Z=/[[\]'"`\/]/g,te=/[<>'"`\/]/g;function X(d,p){let m=1;l++;let g=d===J?K:d===ae?q:d===$e?Z:te;g.lastIndex=l;let w;while((w=g.exec(i))!==null){let b=w.index,T=i.charCodeAt(b);if(T===le||T===fe){l=b,L(T),g.lastIndex=l;continue}if(T===Fe){l=b,P(),g.lastIndex=l;continue}if(T===ee){if(l=b,I()){g.lastIndex=l;continue}g.lastIndex=b+1;continue}if(T===d)m++;else if(T===p){if(p===me&&b>0&&i.charCodeAt(b-1)===be){g.lastIndex=b+1;continue}if(m--,m===0)return l=b+1,l}g.lastIndex=b+1}return l=a,l}function oe(){return l>0&&i.charCodeAt(l-1)===be}function Ge(){return l+1<a&&i.charCodeAt(l+1)===me}let Ve=/[<{};'"`\/\n\r()[\]]/g;function Re(d=!1){let p=0,m=0,g=0,w=0,b=i.charCodeAt(l)===J;Ve.lastIndex=l;let T;while((T=Ve.exec(i))!==null){let R=T.index,E=i.charCodeAt(R);if(E===le||E===fe){l=R,L(E),Ve.lastIndex=l;continue}if(E===Fe){l=R,P(),Ve.lastIndex=l;continue}if(E===ee){if(R>0&&i.charCodeAt(R-1)===we){Ve.lastIndex=R+1;continue}if(l=R,I()){if(p===0&&m===0&&g===0&&w===0&&pe())return;Ve.lastIndex=l;continue}Ve.lastIndex=R+1;continue}if(E===we){let A=ns(R);if(A!==null)w=Math.max(0,w+A);Ve.lastIndex=R+1;continue}if(E===ae){m++,Ve.lastIndex=R+1;continue}if(E===Se){m--,Ve.lastIndex=R+1;continue}if(E===$e){g++,Ve.lastIndex=R+1;continue}if(E===ke){g--,Ve.lastIndex=R+1;continue}if(E===J){p++,Ve.lastIndex=R+1;continue}if(E===Q){let A=p>0;if(!A&&d&&m===0&&g===0&&w===0){l=R;return}if(A)p--;if((!A||b)&&p===0&&m===0&&g===0&&w===0){l=R+1;return}Ve.lastIndex=R+1;continue}if(E===re&&p===0&&m===0&&g===0&&w===0){l=R+1;return}if((E===ve||E===xe)&&p===0&&m===0&&g===0&&w===0){if(l=R,ie())return}Ve.lastIndex=R+1}l=a}function Zc(){l++;while(l<a&&(i.charCodeAt(l)===Me||i.charCodeAt(l)===De))l++;let d=i.indexOf(`
142
- `,l),p=d===-1?a:d,m=i.indexOf(";",l);if(m!==-1&&m<p){let g=m-1;while(g>=l&&(i.charCodeAt(g)===Me||i.charCodeAt(g)===De))g--;let w=i.charCodeAt(l),b=i.charCodeAt(g);if(w===J&&b===Q||w===$e&&b===ke||w===le&&b===le||w===fe&&b===fe||w===Fe&&b===Fe){l=m+1;return}}Re()}function Xo(){X(J,Q);while(l<a&&_e(i.charCodeAt(l)))l++;if(O("from")){l+=4;while(l<a&&_e(i.charCodeAt(l)))l++;if(l<a){let d=i.charCodeAt(l);if(d===le||d===fe)L(d)}}while(l<a&&(i.charCodeAt(l)===Me||i.charCodeAt(l)===De))l++;if(l<a&&i.charCodeAt(l)===re)l++}function Qo(){l++;while(l<a&&_e(i.charCodeAt(l)))l++;if(O("as")){l+=2;while(l<a&&_e(i.charCodeAt(l)))l++;H();while(l<a&&_e(i.charCodeAt(l)))l++}if(O("from")){l+=4;while(l<a&&_e(i.charCodeAt(l)))l++;if(l<a){let d=i.charCodeAt(l);if(d===le||d===fe)L(d)}}while(l<a&&(i.charCodeAt(l)===Me||i.charCodeAt(l)===De))l++;if(l<a&&i.charCodeAt(l)===re)l++}function Gr(d){let p=d.indexOf("from ");if(p===-1)return;let m=p+5;while(m<d.length&&(d.charCodeAt(m)===32||d.charCodeAt(m)===9))m++;if(m>=d.length)return;let g=d.charCodeAt(m);if(g!==39&&g!==34)return;let w=d.indexOf(d[m],m+1);if(w===-1)return;return d.slice(m+1,w)}function tt(d){if(!o)return;let p=d-1;while(p>=0&&_e(i.charCodeAt(p)))p--;if(p<0)return;let m=[],g=!1;while(p>=0){if(p>=1&&i.charCodeAt(p)===ee&&i.charCodeAt(p-1)===Ae){let T=i.lastIndexOf("/*",p-2);if(T>=0){m.push(i.slice(T,p+1)),g=!0,p=T-1;while(p>=0&&_e(i.charCodeAt(p)))p--;continue}break}let w=p;while(w>0&&i.charCodeAt(w-1)!==ve)w--;let b=C(w,p+1);if(b.startsWith("//")){if(g)break;let T=[b];p=w-1;while(p>=0&&(i.charCodeAt(p)===ve||i.charCodeAt(p)===xe))p--;while(p>=0){let R=p;while(R>0&&i.charCodeAt(R-1)!==ve)R--;let E=C(R,p+1);if(E.startsWith("//")){T.push(E),p=R-1;while(p>=0&&(i.charCodeAt(p)===ve||i.charCodeAt(p)===xe))p--}else if(E===""){p=R-1;while(p>=0&&(i.charCodeAt(p)===ve||i.charCodeAt(p)===xe))p--}else break}T.reverse(),m.push(T.join(`
143
- `));continue}break}if(m.length===0)return;return m.reverse(),m}function Xc(d){let p=d,m=!1;while(l<a){let E=i.charCodeAt(l);if(E===re){l++;break}if(E===le||E===fe){L(E),m=!0;while(l<a&&(i.charCodeAt(l)===Me||i.charCodeAt(l)===De))l++;if(l<a&&i.charCodeAt(l)===re)l++;break}if(E===ve&&m)break;l++}let g=C(p,l),w=g.charCodeAt(7)===116&&(g.startsWith("import type ")||g.startsWith("import type{")),b=!1;{let E=6;while(E<g.length&&(g.charCodeAt(E)===Me||g.charCodeAt(E)===De))E++;if(E<g.length&&g.charCodeAt(E)===116&&g.startsWith("type",E)){E+=4;while(E<g.length&&(g.charCodeAt(E)===Me||g.charCodeAt(E)===De))E++}if(E<g.length){let A=g.charCodeAt(E);b=A===le||A===fe}}let T="";{let E=g.indexOf("from ");if(E!==-1){let A=E+5;while(A<g.length&&(g.charCodeAt(A)===Me||g.charCodeAt(A)===De))A++;if(A<g.length){let M=g.charCodeAt(A);if(M===le||M===fe){let _=g.indexOf(String.fromCharCode(M),A+1);if(_!==-1)T=g.slice(A+1,_)}}}else if(b){let A=6;while(A<g.length&&g.charCodeAt(A)!==le&&g.charCodeAt(A)!==fe)A++;if(A<g.length){let M=g.charCodeAt(A),_=g.indexOf(String.fromCharCode(M),A+1);if(_!==-1)T=g.slice(A+1,_)}}}let R=tt(p);return{kind:"import",name:"",text:g,isExported:!1,isTypeOnly:w,isSideEffect:b,source:T,leadingComments:R,start:p,end:l}}function Xi(){let d=l;return X(J,Q),i.slice(d,l)}function es(d){let p=d.indexOf("(");if(p===-1)return d;let m=d.slice(p);if(m.indexOf("=")===-1)return d;let g=!1;for(let E=0;E<m.length;E++)if(m.charCodeAt(E)===61){let A=E>0?m.charCodeAt(E-1):0,M=E+1<m.length?m.charCodeAt(E+1):0;if(A!==61&&A!==33&&A!==60&&A!==62&&M!==61&&M!==62){g=!0;break}}if(!g)return d;let w=0,b=-1;for(let E=p;E<d.length;E++){let A=d.charCodeAt(E);if(A===40)w++;else if(A===41){if(w--,w===0){b=E;break}}}if(b===-1)return d;let T=d.slice(p,b+1),R=_t(T);return d.slice(0,p)+R+d.slice(b+1)}function ts(d){let p=d.indexOf("//")!==-1||d.indexOf("/*")!==-1,m=d.split(`
144
- `),g=[],w=[],b=[],T=!1,R=1/0;for(let M=0;M<m.length;M++){let _=m[M];if(p){if(T){if(_.includes("*/"))T=!1;continue}let B=_.trim();if(B.length===0)continue;let N=B.charCodeAt(0);if(N===ee){let Je=B.charCodeAt(1);if(Je===ee)continue;if(Je===Ae){if(!B.includes("*/"))T=!0;continue}}if(N===Ae)continue;let D=G(_);if(D.charCodeAt(D.length-1)===re)D=D.slice(0,-1);D=es(D);let j=D.trim();if(!j)continue;g.push(D),w.push(j);let V=0;while(V<D.length&&_e(D.charCodeAt(V)))V++;if(j!=="{"&&j!=="}"){if(V<R)R=V}b.push(V)}else{let B=_.length;while(B>0&&(_.charCodeAt(B-1)===Me||_.charCodeAt(B-1)===De||_.charCodeAt(B-1)===xe))B--;if(B===0)continue;let N=B<_.length?_.slice(0,B):_;if(N.charCodeAt(N.length-1)===re)N=N.slice(0,-1);N=es(N);let D=N.trim();if(!D)continue;g.push(N),w.push(D);let j=0;while(j<N.length&&_e(N.charCodeAt(j)))j++;if(D!=="{"&&D!=="}"){if(j<R)R=j}b.push(j)}}if(g.length===0)return"{}";if(R===1/0||R<=2)return g.join(`
145
- `);let E=R-2,A=Array(g.length);for(let M=0;M<g.length;M++){let _=w[M];if(_==="{"){A[M]=_;continue}let B=b[M];if(B>R)A[M]=g[M];else if(B===R&&(_.charCodeAt(0)===Q||_.charCodeAt(0)===ke||_.charCodeAt(0)===Se))A[M]=g[M];else{let N=Math.max(0,B-E);A[M]=" ".repeat(N)+_}}return A.join(`
146
- `)}function mt(){if(l>=a||i.charCodeAt(l)!==we)return"";let d=l;X(we,me);let p=i.slice(d,l);if(p.includes(`
147
- `)){let m="",g=!1;for(let w=0;w<p.length;w++){let b=p.charCodeAt(w);if(b===32||b===9||b===10||b===13){if(!g&&m.length>0)m+=" ",g=!0}else m+=p[w],g=!1}if(m.charCodeAt(1)===32)m=`<${m.slice(2)}`;if(m.charCodeAt(m.length-2)===32)m=`${m.slice(0,-2)}>`;return m}return p}function Tt(){if(l>=a||i.charCodeAt(l)!==ae)return"()";let d=l;return X(ae,Se),i.slice(d,l)}function jr(d){if(d.indexOf("/")===-1)return d;let p="",m=!1,g=0;for(let w=0;w<d.length;w++){let b=d.charCodeAt(w);if(m){if(p+=d[w],b===nt&&w+1<d.length){p+=d[++w];continue}if(b===g)m=!1;continue}if(b===le||b===fe||b===Fe){m=!0,g=b,p+=d[w];continue}if(b===ee&&w+1<d.length){let T=d.charCodeAt(w+1);if(T===Ae){let R=d.indexOf("*/",w+2);w=R===-1?d.length:R+1,p+=" ";continue}if(T===ee){let R=d.indexOf(`
148
- `,w+2);w=R===-1?d.length:R-1;continue}}p+=d[w]}return p.trim()}function _t(d){let p=d.slice(1,-1).trim();if(!p)return"()";if(d.indexOf(`
149
- `)===-1&&p.indexOf(":")!==-1&&p.indexOf("{")===-1&&p.indexOf("[")===-1&&p.indexOf("=")===-1&&p.indexOf("@")===-1&&p.indexOf("...")===-1){let E=0,A=0,M=0;for(let _=0;_<p.length;_++){let B=p.charCodeAt(_);if(B===ae||B===we||B===J)M++;else if(B===Se||B===me||B===Q)M--;else if(M===0){if(B===ft)E++;else if(B===dt)A++}}if(E>=A+1){let _=!1;for(let B=0;B<_o.length;B++){let N=_o[B],D=p.indexOf(N);if(D!==-1){let j=D+N.length;if((D===0||!Ue(p.charCodeAt(D-1)))&&(j>=p.length||!Ue(p.charCodeAt(j)))){_=!0;break}}}if(!_)return d}}let m=[],g=0,w=0,b=!1,T=0;for(let E=0;E<=p.length;E++){if(E===p.length){m.push(jr(p.slice(g).trim()));break}let A=p.charCodeAt(E);if(b){if(A===nt){E++;continue}if(A===T)b=!1;continue}if(A===ee&&E+1<p.length){let M=p.charCodeAt(E+1);if(M===Ae){E+=2;while(E+1<p.length&&!(p.charCodeAt(E)===Ae&&p.charCodeAt(E+1)===ee))E++;E++;continue}if(M===ee){while(E<p.length&&p.charCodeAt(E)!==10)E++;continue}}if(A===le||A===fe||A===Fe){b=!0,T=A;continue}if(A===ae||A===J||A===$e||A===we)w++;else if(A===Se||A===Q||A===ke||A===me&&!(E>0&&p.charCodeAt(E-1)===be))w--;else if(A===dt&&w===0)m.push(jr(p.slice(g,E).trim())),g=E+1}let R=[];for(let E of m){if(!E)continue;let A=E.trim();if(A.startsWith("//")||A.startsWith("/*"))continue;let M=E;{let _=!1,B=0,N=0,D=0;for(let j=0;j<M.length-1;j++){let V=M.charCodeAt(j);if(V===ve){D=j+1;continue}if(_){if(V===nt){j++;continue}if(V===B)_=!1;continue}if(V===le||V===fe||V===Fe){_=!0,B=V;continue}if(V===J||V===$e||V===ae||V===we){N++;continue}if(V===Q||V===ke||V===Se||V===me){if(N>0)N--;continue}if(V===ee&&M.charCodeAt(j+1)===ee){if(N===0){M=M.slice(0,j).trimEnd();break}let Je=M.indexOf(`
150
- `,j);if(Je===-1){M=M.slice(0,D).trimEnd();break}let qe=M.slice(0,D),Kt=M.slice(Je+1);M=`${qe}${Kt}`,j=D-1}}}if(!M.trim())continue;R.push(rs(M))}return`(${R.join(", ")})`}function Qc(d){if(!d.startsWith("{")&&!d.startsWith("["))return d;let p="",m=0,g=0,w=!1,b=0;while(m<d.length){let T=d.charCodeAt(m);if(w){if(T===nt&&m+1<d.length){p+=d[m]+d[m+1],m+=2;continue}if(T===b)w=!1;p+=d[m],m++;continue}if(T===ee&&m+1<d.length){let R=d.charCodeAt(m+1);if(R===Ae){let E=m;m+=2;while(m+1<d.length&&!(d.charCodeAt(m)===Ae&&d.charCodeAt(m+1)===ee))m++;m=Math.min(m+2,d.length),p+=d.slice(E,m);continue}if(R===ee){let E=m;while(m<d.length&&d.charCodeAt(m)!==10)m++;p+=d.slice(E,m);continue}}if(T===le||T===fe||T===Fe){w=!0,b=T,p+=d[m],m++;continue}if(T===J||T===$e||T===ae)g++;else if(T===Q||T===ke||T===Se)g--;if(g>=1&&T===be&&(m+1>=d.length||d.charCodeAt(m+1)!==be&&d.charCodeAt(m+1)!==me)){while(p.length>0&&(p[p.length-1]===" "||p[p.length-1]==="\t"||p[p.length-1]===`
151
- `))p=p.slice(0,-1);m++;let R=0;while(m<d.length){let E=d.charCodeAt(m);if(E===le||E===fe||E===Fe){let A=E;m++;while(m<d.length){if(d.charCodeAt(m)===nt){m+=2;continue}if(d.charCodeAt(m)===A){m++;break}m++}continue}if(E===J||E===$e||E===ae)R++;else if(E===Q||E===ke||E===Se){if(R===0)break;R--}else if(E===dt&&R===0)break;m++}continue}if(g===1&&T===gt&&m+2<d.length&&d.charCodeAt(m+1)===gt&&d.charCodeAt(m+2)===gt){m+=3;continue}p+=d[m],m++}return p}function rs(d){let p=d.trim(),m=p.startsWith("...");if(m)p=p.slice(3).trim();while(p.startsWith("@")){let D=1;while(D<p.length&&Ue(p.charCodeAt(D)))D++;if(D<p.length&&p.charCodeAt(D)===ae){let j=1;D++;while(D<p.length&&j>0){if(p.charCodeAt(D)===ae)j++;else if(p.charCodeAt(D)===Se)j--;D++}}p=p.slice(D).trim()}let g=!0;while(g){g=!1;for(let D of _o)if(p.startsWith(D)&&p.length>D.length&&!Ue(p.charCodeAt(D.length))){let j=p.slice(D.length).trim();if(j.charCodeAt(0)===ft||j.charCodeAt(0)===Ui&&j.length>1&&j.charCodeAt(1)===ft)break;p=j,g=!0;break}}let w=-1,b=-1,T=0,R=!1,E=0;for(let D=0;D<p.length;D++){let j=p.charCodeAt(D);if(R){if(j===nt){D++;continue}if(j===E)R=!1;continue}if(j===ee&&D+1<p.length){let V=p.charCodeAt(D+1);if(V===Ae){D+=2;while(D+1<p.length&&!(p.charCodeAt(D)===Ae&&p.charCodeAt(D+1)===ee))D++;D++;continue}if(V===ee){while(D<p.length&&p.charCodeAt(D)!==10)D++;continue}}if(j===le||j===fe||j===Fe){R=!0,E=j;continue}if(j===ae||j===J||j===$e||j===we)T++;else if(j===Se||j===Q||j===ke||j===me&&!(D>0&&p.charCodeAt(D-1)===be))T--;else if(T===0){if(j===ft&&w===-1)w=D;else if(j===be&&b===-1&&(D===0||p.charCodeAt(D-1)!==be)&&(D+1>=p.length||p.charCodeAt(D+1)!==be&&p.charCodeAt(D+1)!==me))b=D}}let A,M,_=b!==-1;if(w!==-1&&(b===-1||w<b))if(A=p.slice(0,w).trim(),b!==-1)M=p.slice(w+1,b).trim();else M=p.slice(w+1).trim();else if(b!==-1)A=p.slice(0,b).trim(),M=Qi(p.slice(b+1).trim());else A=p,M="unknown";if(A=Qc(A),(A.startsWith("{")||A.startsWith("["))&&A.includes(`
152
- `)){let D=A.replace(/\s*\n\s*/g," ").replace(/\s+/g," ");if(D.length<=40)A=D;else A=A.split(`
153
- `).map((j)=>{let V=j.trim();if(!V)return"";if(V==="{"||V==="}"||V==="["||V==="]"||V.startsWith("}")||V.startsWith("]"))return V;return` ${V}`}).join(`
154
- `)}let B=A.endsWith("?")||_;if(A.endsWith("?"))A=A.slice(0,-1).trim();let N=B&&!m?"?":"";if(m)return`...${A}: ${M}`;return`${A}${N}: ${M}`}function is(d){let p=0;if(p<d.length&&d.charCodeAt(p)===45)p++;if(p>=d.length)return!1;let m=d.charCodeAt(p);if(m<48||m>57)return!1;while(p<d.length&&d.charCodeAt(p)>=48&&d.charCodeAt(p)<=57)p++;if(p<d.length&&d.charCodeAt(p)===46){if(p++,p>=d.length||d.charCodeAt(p)<48||d.charCodeAt(p)>57)return!1;while(p<d.length&&d.charCodeAt(p)>=48&&d.charCodeAt(p)<=57)p++}return p===d.length}function Qi(d){let p=d.trim();if(p==="true"||p==="false")return"boolean";if(is(p))return"number";if(p.startsWith("'")&&p.endsWith("'")||p.startsWith('"')&&p.endsWith('"'))return"string";if(p.startsWith("["))return"unknown[]";if(p.startsWith("{"))return"Record<string, unknown>";return"unknown"}function en(d){let p=d.trim();if(p.endsWith("as const"))p=p.slice(0,-8).trim();if(p==="true"||p==="false")return p;if(is(p))return p;let m=ef(p);if(m!==null)return m;return"unknown"}function ef(d){if(d==="")return null;if(d.charCodeAt(0)===le||d.charCodeAt(0)===fe){if(Ki(d,0,d.charCodeAt(0))===d.length)return d}let p=tf(d,"+");if(p.length>1){let m=!1,g=!0,w=[];for(let b of p){let T=b.trim(),R=T.charCodeAt(0);if((R===le||R===fe)&&Ki(T,0,R)===T.length)m=!0,w.push(rf(T));else g=!1}if(g)return nf(w.join(""));if(m)return"string";return null}if(/^[\d\s()+*/%.\-]+$/.test(d)&&/\d/.test(d)&&/[+*/%\-\s]/.test(d))return"number";return null}function tf(d,p){let m=[],g=0,w="",b=0;while(b<d.length){let T=d.charCodeAt(b);if(T===le||T===fe||T===Fe){let R=Ki(d,b,T);w+=d.slice(b,R),b=R;continue}if(T===ee&&(d.charCodeAt(b+1)===ee||d.charCodeAt(b+1)===42)){if(d.charCodeAt(b+1)===ee){let A=d.indexOf(`
155
- `,b+2),M=A===-1?d.length:A;w+=d.slice(b,M),b=M;continue}let R=d.indexOf("*/",b+2),E=R===-1?d.length:R+2;w+=d.slice(b,E),b=E;continue}if(T===ae||T===$e||T===J)g++;else if(T===Se||T===ke||T===Q)g--;if(d[b]===p&&g===0){m.push(w),w="",b++;continue}w+=d[b],b++}return m.push(w),m}function rf(d){return d.slice(1,-1).replace(/\\(.)/g,(p,m)=>{if(m==="n")return`
156
- `;if(m==="t")return"\t";if(m==="r")return"\r";if(m==="0")return"\x00";return m})}function nf(d){return`'${d.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function _r(d){if(d.endsWith("as const"))return null;let p=0,m=-1;for(let g=0;g<d.length;g++){let w=d.charCodeAt(g);if(w===le||w===fe||w===Fe)g=Ki(d,g,w)-1;else if(w===123||w===91||w===40)p++;else if(w===125||w===93||w===41)p--;else if(p===0&&w===32&&g+4<=d.length&&d.substring(g,g+4)===" as ")m=g}if(m===-1)return null;return d.slice(m+4).trim()||null}function pr(){if(v(),l<a&&i.charCodeAt(l)===ft){l++,v();let d=l,p=0;while(l<a){if(I())continue;let m=i.charCodeAt(l);if(m===ae||m===$e||m===we)p++;else if(m===Se||m===ke||m===me&&!oe())p--;else if(m===J)if(p>0)p++;else{let g=C(d,l),w=(b)=>{let T=g.length-b.length;return T>=0&&g.endsWith(b)&&(T===0||!Ue(g.charCodeAt(T-1)))};if(g.length===0||g.endsWith("|")||g.endsWith("&")||w("is")||w("extends"))p++;else break}else if(m===Q){if(p===0)break;p--}else if(p===0&&m===re)break;if(p===0&&W())break;l++}return C(d,l)}return""}function Ot(d,p,m,g){l+=8,v();let w=l<a&&i.charCodeAt(l)===Ae;if(w)l++,v();let b=H();if(!b&&!g)return null;v();let T=mt();v();let R=Tt();v();let E=pr(),A=E.length>0;if(!E)if(m&&w)E="AsyncGenerator<unknown, void, unknown>";else if(w)E="Generator<unknown, void, unknown>";else if(m)E="Promise<void>";else E="void";v();let M=!1;if(l<a&&i.charCodeAt(l)===J){M=!0;let j=l+1;if(X(J,Q),!A&&!w)E=hr(i.slice(j,l-1),m,R)}else if(l<a&&i.charCodeAt(l)===re)l++;let _=_t(R),B=`${p?g?"export default function ":"export declare function ":"declare function "}${b||(g?"":"default")}${T}${_}: ${E};`,N=tt(d),D={kind:"function",name:b||"default",text:B,isExported:p,isDefault:g,isAsync:m,isGenerator:w,returnType:E,generics:T||void 0,leadingComments:N,start:d,end:l};if(M)h.add(D);return D}function Lt(d,p,m){l+=p.length,v();let g=[];do{if(v(),l>=a)break;let w=i.charCodeAt(l);if(w===J||w===$e)return Re(),g;let b=H();if(!b)return Re(),g;v();let T,R,E=!1;if(l<a&&i.charCodeAt(l)===ft){l++,v();let _=l,B=0;while(l<a){if(I()){if(B===0&&pe())break;continue}let N=i.charCodeAt(l);if(N===ae||N===J||N===$e||N===we)B++;else if(N===Se||N===Q||N===ke||N===me&&!oe())B--;else if(B===0&&(N===re||N===dt))break;else if(B===0&&N===be&&!Ge())break;if(B===0&&(ie()||se()))break;l++}T=C(_,l)}if(l<a&&i.charCodeAt(l)===be)if(s&&T&&(!o||!qd(T)))Zc();else{l++,v();let _=l,B=0,N=0,D=0,j=!0;for(;;){l=_,B=0,N=0,D=0;while(l<a){if(I()){if(B===0&&N===0&&D===0&&pe())break;continue}let V=i.charCodeAt(l);if(V===ae||V===J||V===$e)B++;else if(V===Se||V===Q||V===ke)B--;else if(V===we&&B===0){let Je=ns(l);if(Je!==null)D=Math.max(0,D+Je);else if(j&&(l+1>=a||i.charCodeAt(l+1)!==be))N++}else if(V===me&&B===0&&D===0&&!oe()){if(N>0&&(l+1>=a||i.charCodeAt(l+1)!==be))N--}else if(B===0&&N===0&&D===0&&(V===re||V===dt))break;if(B===0&&N===0&&D===0&&(ie()||ue()))break;l++}if(N>0&&j){j=!1;continue}break}if(R=C(_,l),R.endsWith(" as const")||R==="const"){if(E=!0,!T){let V=R.endsWith(" as const")?R.slice(0,-9).trim():R,Je=en(V);T=Je!=="unknown"?Je:void 0}}else if(!T){let V=Vi(R)??_r(R);if(V)T=V}}if(l<a){let _=i.charCodeAt(l);if(_===dt){l++;continue}if(_===re)l++}let A=tt(d),M=`${m?"export ":""}declare ${p} ${b}: ${T||"unknown"};`;g.push({kind:"variable",name:b,text:M,isExported:m,typeAnnotation:T,value:R,modifiers:E?[p,"const assertion"]:[p],leadingComments:A,start:d,end:l});break}while(l<a);return g}function ns(d){if(i.charCodeAt(d)!==we||d+1>=a)return null;let p=i.charCodeAt(d+1);if(p===me)return 1;if(p===ee)return-1;if(!yt(p))return null;let m=d+2;while(m<a){let A=i.charCodeAt(m);if(!Ue(A)&&A!==gt&&A!==58&&A!==45)break;m++}let g=i.slice(d+1,m),w=i.charCodeAt(m);if(w>32&&w!==me&&w!==ee)return null;let b=0,T=0,R=m;for(;R<a;R++){let A=i.charCodeAt(R);if(T!==0){if(A===nt)R++;else if(A===T)T=0;continue}if(A===le||A===fe||A===Fe)T=A;else if(A===J)b++;else if(A===Q&&b>0)b--;else if(A===me&&b===0)break}if(R>=a)return null;let E=R-1;while(E>d&&i.charCodeAt(E)<=32)E--;if(i.charCodeAt(E)===ee)return 0;return i.indexOf(`</${g}`,R+1)===-1?null:1}function tn(d,p){l+=9,v();let m=H();v();let g=mt();v();let w="";if(O("extends")){l+=7,v();let A=l,M=0;while(l<a){if(I())continue;let _=i.charCodeAt(l);if(_===we)M++;else if(_===me&&!oe())M--;else if(_===J&&M===0)break;l++}w=C(A,l)}v();let b=l<a&&i.charCodeAt(l)===J?Xi():"{}",T=ts(b),R=`${p?"export ":""}declare interface ${m}${g}${w?` extends ${w}`:""} ${T}`,E=tt(d);return{kind:"interface",name:m,text:R,isExported:p,extends:w||void 0,generics:g||void 0,leadingComments:E,start:d,end:l}}function rn(d,p){l+=4,v();let m=H();v();let g=mt();if(v(),l<a&&i.charCodeAt(l)===be)l++;v();let w=l,b=0;while(l<a){if(I())continue;let A=i.charCodeAt(l);if(A===ae||A===J||A===$e||A===we)b++;else if(A===Se||A===Q||A===ke||A===me&&!oe())b--;else if(b===0&&A===re)break;if(b===0&&(ie()||se()))break;l++}let T=C(w,l);if(l<a&&i.charCodeAt(l)===re)l++;let R=`${p?"export ":""}type ${m}${g} = ${T}`,E=tt(d);return{kind:"type",name:m,text:R,isExported:p,generics:g||void 0,leadingComments:E,start:d,end:l}}function Vt(d,p,m){l+=4,v();let g=H();v();let w=l;if(l<a&&i.charCodeAt(l)===J)X(J,Q);let b=C(d,l),T=tt(d);return{kind:"enum",name:g,text:b,isExported:p,modifiers:m?["const"]:void 0,leadingComments:T,start:d,end:l}}function Rt(d,p,m,g=!1){l+=5,v();let w=H()||"AnonymousClass";v();let b=mt();v();let T="";if(O("extends")){l+=7,v();let _=l,B=0;while(l<a){if(I())continue;let N=i.charCodeAt(l);if(N===we)B++;else if(N===me&&!oe())B--;else if(B===0&&(N===J||O("implements")))break;l++}T=C(_,l)}let R;if(O("implements")){l+=10,v();let _=l,B=0;while(l<a){if(I())continue;let D=i.charCodeAt(l);if(D===we)B++;else if(D===me&&!oe())B--;else if(B===0&&D===J)break;l++}let N=C(_,l);if(N)R=N.split(",").map((D)=>D.trim())}v();let E=nn(),A=`${p?g?"export default ":"export declare ":"declare "}${m?"abstract ":""}class ${w}${b}${T?` extends ${T}`:""}${R&&R.length>0?` implements ${R.join(", ")}`:""} ${E}`,M=tt(d);return{kind:"class",name:w,text:A,isExported:p,isDefault:g,extends:T||void 0,implements:R,generics:b||void 0,modifiers:m?["abstract"]:void 0,leadingComments:M,start:d,end:l}}function nn(){if(l>=a||i.charCodeAt(l)!==J)return"{}";l++;let d=[];while(l<a){if(v(),l>=a)break;if(i.charCodeAt(l)===Q){l++;break}if(i.charCodeAt(l)===re){l++;continue}if(O("static")&&sn("static")===J){l+=6,v(),X(J,Q);continue}let p=!1,m=!1,g=!1,w=!1,b=!1,T=!1,R=!1,E=!1,A=!0;while(A){v();let B=l,N=H();if(l=B,N){let D=sn(N);if(D===ae||D===we||D===Ui||D===33||D===ft||D===be||D===re||D===Q)break}if(O("private")){p=!0,l+=7;continue}if(O("protected")){m=!0,l+=9;continue}if(O("public")){l+=6;continue}if(O("static")){g=!0,l+=6;continue}if(O("abstract")){w=!0,l+=8;continue}if(O("readonly")){b=!0,l+=8;continue}if(O("override")){T=!0,l+=8;continue}if(O("accessor")){R=!0,l+=8;continue}if(O("async")){E=!0,l+=5;continue}if(O("declare")){l+=7;continue}break}if(v(),l>=a||i.charCodeAt(l)===Q)break;if(i.charCodeAt(l)===jo)p=!0;let M=p?[]:d,_=" ";if(m)_+="protected ";if(g)_+="static ";if(w)_+="abstract ";if(b)_+="readonly ";if(O("constructor")){l+=11,v();let B=Tt();if(v(),sf(B,M),l<a&&i.charCodeAt(l)===J)X(J,Q);else if(l<a&&i.charCodeAt(l)===re)l++;let N=_t(B);M.push(` constructor${N};`)}else if(O("get"))if(l+=3,v(),l<a&&os(i.charCodeAt(l))){let B=on();if(B.startsWith("#")){if(v(),l<a&&i.charCodeAt(l)===ae)Tt();if(v(),pr(),v(),l<a&&i.charCodeAt(l)===J)X(J,Q);else if(l<a&&i.charCodeAt(l)===re)l++;continue}v(),Tt(),v();let N=pr()||"unknown";if(v(),l<a&&i.charCodeAt(l)===J)X(J,Q);else if(l<a&&i.charCodeAt(l)===re)l++;M.push(`${_}get ${B}(): ${N};`)}else as("get",_,g,b,E,M);else if(O("set"))if(l+=3,v(),l<a&&os(i.charCodeAt(l))){let B=on();if(B.startsWith("#")){if(v(),l<a&&i.charCodeAt(l)===ae)Tt();if(v(),l<a&&i.charCodeAt(l)===J)X(J,Q);else if(l<a&&i.charCodeAt(l)===re)l++;continue}v();let N=Tt();if(v(),l<a&&i.charCodeAt(l)===J)X(J,Q);else if(l<a&&i.charCodeAt(l)===re)l++;let D=_t(N);M.push(`${_}set ${B}${D};`)}else as("set",_,g,b,E,M);else{let B=i.charCodeAt(l)===Ae;if(B)l++,v();let N=on();if(!N){ss();continue}ls(N,_,g,b,B,w,E,M)}}return`{
157
- ${d.join(`
158
- `)}
159
- }`}function os(d){return yt(d)||d===$e||d===jo||d===le||d===fe}function on(){if(l>=a)return"";let d=i.charCodeAt(l);if(d===$e){let p=l;return X($e,ke),i.slice(p,l)}if(d===jo)return l++,`#${H()}`;if(d===le||d===fe){let p=l;return L(d),i.slice(p,l)}return H()}function sn(d){let p=l;l+=d.length,v();let m=l<a?i.charCodeAt(l):0;return l=p,m}function ss(){let d=0;while(l<a){if(I())continue;let p=i.charCodeAt(l);if(p===J||p===ae)d++;else if(p===Q||p===Se){if(d===0)return;d--}else if(p===re&&d===0){l++;return}if(d===0&&W())return;l++}}function as(d,p,m,g,w,b){ls(d,p,m,g,!1,!1,w,b)}function ls(d,p,m,g,w,b,T,R){if(v(),l>=a)return;let E=i.charCodeAt(l),A=!1;if(E===Ui)A=!0,l++,v();if(l<a&&i.charCodeAt(l)===33)l++,v();let M=l<a?i.charCodeAt(l):0;if(M===ae||M===we){let _=M===we?mt():"";v();let B=Tt();v();let N=pr(),D=N.length>0;if(!N)if(T&&w)N="AsyncGenerator<unknown, void, unknown>";else if(w)N="Generator<unknown, void, unknown>";else if(T)N="Promise<void>";else N="void";if(v(),l<a&&i.charCodeAt(l)===J){let Je=l+1;if(X(J,Q),!D&&!w)N=hr(i.slice(Je,l-1),T,B)}else if(l<a&&i.charCodeAt(l)===re)l++;let j=_t(B),V=A?"?":"";R.push(`${p}${d}${V}${_}${j}: ${N};`)}else if(M===ft||M===be||M===re||M===Q||M===ve||M===xe){let _="";if(M===ft){l++,v();let D=l,j=0;while(l<a){if(I())continue;let V=i.charCodeAt(l);if(V===ae||V===J||V===$e||V===we)j++;else if(V===Se||V===Q||V===ke||V===me&&!oe()){if(j===0)break;j--}else if(j===0&&(V===re||V===dt))break;else if(j===0&&V===be&&!Ge())break;if(j===0&&W())break;l++}_=C(D,l)}let B="";if(l<a&&i.charCodeAt(l)===be)if(s&&_){l++;let D=0;while(l<a){if(I())continue;let j=i.charCodeAt(l);if(j===ae||j===J||j===$e)D++;else if(j===Se||j===Q||j===ke){if(D===0&&j===Q)break;D--}else if(D===0&&j===re)break;if(D===0&&W())break;l++}}else{l++,v();let D=l,j=0;while(l<a){if(I())continue;let V=i.charCodeAt(l);if(V===ae||V===J||V===$e)j++;else if(V===Se||V===Q||V===ke){if(j===0&&V===Q)break;j--}else if(j===0&&V===re)break;if(j===0&&W())break;l++}B=C(D,l)}if(l<a&&i.charCodeAt(l)===re)l++;if(!_)if(B){let D=_r(B);if(D)_=D;else _=B.endsWith("as const")||m&&g?en(B):Qi(B)}else _="unknown";let N=A?"?":"";R.push(`${p}${d}${N}: ${_};`)}else ss()}function of(d){let p=0;for(let m=0;m<d.length;m++){let g=d.charCodeAt(m);if(g===ae||g===J||g===$e||g===we)p++;else if(g===Se||g===Q||g===ke||g===me&&d.charCodeAt(m-1)!==be)p--;else if(g===be&&p===0&&d.charCodeAt(m+1)!==me&&d.charCodeAt(m+1)!==be)return!0}return!1}function sf(d,p){let m=d.slice(1,-1).trim();if(!m)return;let g=[],w=0,b=0,T=!1,R=0;for(let E=0;E<=m.length;E++){if(E===m.length){g.push(jr(m.slice(w).trim()));break}let A=m.charCodeAt(E);if(T){if(A===nt){E++;continue}if(A===R)T=!1;continue}if(A===ee&&E+1<m.length){let M=m.charCodeAt(E+1);if(M===Ae){E+=2;while(E+1<m.length&&!(m.charCodeAt(E)===Ae&&m.charCodeAt(E+1)===ee))E++;E++;continue}if(M===ee){while(E<m.length&&m.charCodeAt(E)!==10)E++;continue}}if(A===le||A===fe||A===Fe){T=!0,R=A;continue}if(A===ae||A===J||A===$e||A===we)b++;else if(A===Se||A===Q||A===ke||A===me&&!(E>0&&m.charCodeAt(E-1)===be))b--;else if(A===dt&&b===0)g.push(jr(m.slice(w,E).trim())),w=E+1}for(let E of g){let A=E.startsWith("public ")||E.startsWith("public\t"),M=E.startsWith("protected ")||E.startsWith("protected\t"),_=E.startsWith("private ")||E.startsWith("private\t"),B=E.includes("readonly ");if(!A&&!M&&!_&&!B)continue;if(_)continue;let N=E,D=[];if(A){let qe=6;while(qe<N.length&&_e(N.charCodeAt(qe)))qe++;N=N.slice(qe),D.push("public")}if(M){let qe=9;while(qe<N.length&&_e(N.charCodeAt(qe)))qe++;N=N.slice(qe),D.push("protected")}if(B){let qe=N.indexOf("readonly ");if(qe!==-1){let Kt=qe+8;while(Kt<N.length&&_e(N.charCodeAt(Kt)))Kt++;N=N.slice(0,qe)+N.slice(Kt)}D.push("readonly")}let j=D.length>0?`${D.join(" ")} `:"",V=rs(N),Je=N.search(/[?:=]/);if(Je!==-1&&N.charCodeAt(Je)!==63&&of(N))V=V.replace(/^([\w$]+)\?:/,"$1:");p.push(` ${j}${V};`)}}function an(d=" "){if(l>=a||i.charCodeAt(l)!==J)return"{}";l++;let p=[];while(l<a){if(v(),l>=a)break;if(i.charCodeAt(l)===Q){l++;break}if(i.charCodeAt(l)===re){l++;continue}let m=!1;if(O("export"))m=!0,l+=6,v();if(O("declare"))l+=7,v();let g=m?"export ":"";if(O("function")||O("async")&&af("async","function")){let w=!1;if(O("async"))w=!0,l+=5,v();if(l+=8,v(),l<a&&i.charCodeAt(l)===Ae)l++,v();let b=H();v();let T=mt();v();let R=Tt();v();let E=pr();if(!E)E=w?"Promise<void>":"void";if(v(),l<a&&i.charCodeAt(l)===J)X(J,Q);else if(l<a&&i.charCodeAt(l)===re)l++;let A=_t(R);p.push(`${d}${g}function ${b}${T}${A}: ${E};`)}else if(O("const")||O("let")||O("var")){let w=O("const")?"const":O("let")?"let":"var";l+=w.length,v();let b=H();if(!b){Re(!0);continue}v();let T="";if(l<a&&i.charCodeAt(l)===ft){l++,v();let E=l,A=0;while(l<a){if(I())continue;let M=i.charCodeAt(l);if(M===ae||M===J||M===$e||M===we)A++;else if(M===Q&&A===0)break;else if(M===Se||M===Q||M===ke||M===me&&!oe())A--;else if(A===0&&(M===re||M===dt))break;else if(A===0&&M===be&&!Ge())break;if(A===0&&ie())break;l++}T=C(E,l)}let R="";if(l<a&&i.charCodeAt(l)===be){l++,v();let E=l,A=0;while(l<a){if(I())continue;let M=i.charCodeAt(l);if(M===ae||M===J||M===$e||M===we)A++;else if(M===Q&&A===0)break;else if(M===Se||M===Q||M===ke||M===me&&!oe())A--;else if(A===0&&(M===re||M===dt))break;if(A===0&&ie())break;l++}R=C(E,l)}if(l<a&&i.charCodeAt(l)===re)l++;if(!T&&R){let E=_r(R);if(E)T=E;else if(w==="const")T=en(R);else T=Qi(R)}if(!T)T="unknown";p.push(`${d}${g}${w} ${b}: ${T};`)}else if(O("interface")){l+=9,v();let w=H();v();let b=mt();v();let T="";if(O("extends")){l+=7,v();let E=l,A=0;while(l<a){if(I())continue;let M=i.charCodeAt(l);if(M===we)A++;else if(M===me&&!oe())A--;else if(M===J&&A===0)break;l++}T=C(E,l)}let R=ts(Xi());p.push(`${d}${g}interface ${w}${b}${T?` extends ${T}`:""} ${R}`)}else if(O("type")){l+=4,v();let w=H();v();let b=mt();if(v(),l<a&&i.charCodeAt(l)===be){l++,v();let T=l,R=0;while(l<a){if(I())continue;let A=i.charCodeAt(l);if(A===ae||A===J||A===$e||A===we)R++;else if(A===Q&&R===0)break;else if(A===Se||A===Q||A===ke||A===me&&!oe())R--;else if(R===0&&A===re)break;if(R===0&&ie())break;l++}let E=C(T,l);if(l<a&&i.charCodeAt(l)===re)l++;p.push(`${d}${g}type ${w}${b} = ${E}`)}}else if(O("class")){l+=5,v();let w=H();v();let b=mt();v();let T=l,R=0;while(l<a){if(I())continue;let _=i.charCodeAt(l);if(_===we)R++;else if(_===me&&!oe())R--;else if(_===J&&R===0)break;l++}let E=C(T,l),A=E?` ${E}`:"",M=nn();p.push(`${d}${g}class ${w}${b}${A} ${M}`)}else if(O("enum")){l+=4,v();let w=H();v();let b=Xi();p.push(`${d}${g}enum ${w} ${b}`)}else if(O("namespace")||O("module")){let w=O("namespace")?"namespace":"module";l+=w.length,v();let b=H();v();let T=an(d);p.push(`${d}${g}${w} ${b} ${T}`)}else if(O("abstract"))if(l+=8,v(),O("class")){l+=5,v();let w=H();v();let b=mt();v();let T=l,R=0;while(l<a){if(I())continue;let _=i.charCodeAt(l);if(_===we)R++;else if(_===me&&!oe())R--;else if(_===J&&R===0)break;l++}let E=C(T,l),A=E?` ${E}`:"",M=nn();p.push(`${d}${g}abstract class ${w}${b}${A} ${M}`)}else Re(!0);else if(m&&O("default")){l+=7,v();let w=l;Re(!0);let b=C(w,l);if(b.charCodeAt(b.length-1)===re)b=b.slice(0,-1);if(b)p.push(`${d}export default ${b};`)}else if(!m&&(i.charCodeAt(l)===le||i.charCodeAt(l)===fe||i.charCodeAt(l)===Fe))Re(!0);else Re(!0)}if(p.length===0)return"{}";return`{
160
- ${p.join(`
161
- `)}
162
- }`}function af(d,p){let m=l+d.length;while(m<a&&_e(i.charCodeAt(m)))m++;for(let g=0;g<p.length;g++)if(m+g>=a||i.charCodeAt(m+g)!==p.charCodeAt(g))return!1;return m+p.length>=a||!Ue(i.charCodeAt(m+p.length))}function Ut(d,p,m){l+=m.length,v();let g="",w=i.charCodeAt(l);if(w===le||w===fe){let A=l;L(w),g=i.slice(A,l)}else{g=H();while(l<a&&i.charCodeAt(l)===gt)l++,g+=`.${H()}`}v();let b=l<a&&i.charCodeAt(l)===J?an():"{}",T=`${p?"export ":""}declare ${m} ${g} ${b}`,R=tt(d),E=g.startsWith("'")||g.startsWith('"');return{kind:"module",name:g,text:T,isExported:p,source:E?g.slice(1,-1):void 0,leadingComments:R,start:d,end:l}}function cs(d,p){Re();let m=C(p,l);if(m.charCodeAt(m.length-1)===re)m=m.slice(0,-1).trimEnd();if(!m)return;let g=yt(m.charCodeAt(0));for(let A=1;g&&A<m.length;A++)g=Ue(m.charCodeAt(A));let w=tt(d);if(g){c.push({kind:"export",name:"default",text:`export default ${m};`,isExported:!0,isTypeOnly:!1,leadingComments:w,start:d,end:l});return}let b="__dtsx_default_export__",T=1;while(i.includes(b))b=`__dtsx_default_export_${T++}__`;let R=_r(m)||Ie(m,!1),E=R==="unknown"&&Jd(m)?`typeof ${m}`:R;c.push({kind:"variable",name:b,text:`declare const ${b}: ${E};`,isExported:!1,typeAnnotation:E,modifiers:["const"],start:d,end:l}),c.push({kind:"export",name:"default",text:`export default ${b};`,isExported:!0,isTypeOnly:!1,leadingComments:w,start:d,end:l})}while(l<a){if(v(),l>=a)break;let d=l,p=i.charCodeAt(l);if(p===105&&O("import"))c.push(Xc(d));else if(p===101&&O("export")){l+=6,v();let m=i.charCodeAt(l);if(m===100&&O("default")){l+=7,v();let g=l,w=i.charCodeAt(l);if(w===102&&O("function")){let b=Ot(d,!0,!1,!0);if(b)c.push(b)}else if(w===97&&O("async")&&sn("async")!==re)if(l+=5,v(),O("function")){let b=Ot(d,!0,!0,!0);if(b)c.push(b)}else cs(d,g);else if(w===99&&O("class")){let b=Rt(d,!0,!1,!0);c.push(b)}else if(w===97&&O("abstract")){if(l+=8,v(),O("class")){let b=Rt(d,!0,!0,!0);c.push(b)}}else cs(d,g)}else if(m===116&&O("type")){let g=l;if(l+=4,v(),l<a&&i.charCodeAt(l)===J){Xo();let w=C(d,l),b=tt(d);c.push({kind:"export",name:"",text:w,isExported:!0,isTypeOnly:!0,source:Gr(w),leadingComments:b,start:d,end:l})}else if(l<a&&i.charCodeAt(l)===Ae){Qo();let w=C(d,l);c.push({kind:"export",name:"",text:w,isExported:!0,isTypeOnly:!0,source:Gr(w),start:d,end:l})}else{l=g;let w=rn(d,!0);c.push(w)}}else if(m===105&&O("interface")){let g=tn(d,!0);c.push(g)}else if(m===102&&O("function")){let g=Ot(d,!0,!1,!1);if(g)c.push(g)}else if(m===97&&O("async"))if(l+=5,v(),O("function")){let g=Ot(d,!0,!0,!1);if(g)c.push(g)}else Re();else if(m===99)if(O("class")){let g=Rt(d,!0,!1);c.push(g)}else if(O("const")){let g=l;if(l+=5,v(),O("enum")){l=g+5,v();let w=Vt(d,!0,!0);c.push(w)}else{l=g;let w=Lt(d,"const",!0);for(let b=0;b<w.length;b++)c.push(w[b])}}else Re();else if(m===97&&O("abstract")){if(l+=8,v(),O("class")){let g=Rt(d,!0,!0);c.push(g)}}else if(m===108&&O("let")){let g=Lt(d,"let",!0);for(let w=0;w<g.length;w++)c.push(g[w])}else if(m===118&&O("var")){let g=Lt(d,"var",!0);for(let w=0;w<g.length;w++)c.push(g[w])}else if(m===101&&O("enum")){let g=Vt(d,!0,!1);c.push(g)}else if(m===100&&O("declare"))l+=7,v(),us(d,!0);else if(m===110&&O("namespace")&&z(9)){let g=Ut(d,!0,"namespace");c.push(g)}else if(m===109&&O("module")&&z(6)){let g=Ut(d,!0,"module");c.push(g)}else if(m===J){Xo();let g=C(d,l),w=g.includes("export type"),b=tt(d);c.push({kind:"export",name:"",text:g,isExported:!0,isTypeOnly:w,source:Gr(g),leadingComments:b,start:d,end:l})}else if(m===Ae){Qo();let g=C(d,l),w=tt(d);c.push({kind:"export",name:"",text:g,isExported:!0,isTypeOnly:!1,source:Gr(g),leadingComments:w,start:d,end:l})}else{Re();let g=C(d,l);if(g)c.push({kind:"export",name:"",text:g,isExported:!0,start:d,end:l})}}else if(p===100&&O("declare"))l+=7,v(),us(d,!1);else if(p===105&&O("interface")){let m=tn(d,!1);f.set(m.name,m)}else if(p===116&&O("type")){let m=rn(d,!1);f.set(m.name,m),c.push(m)}else if(p===102&&O("function")){let m=Ot(d,!1,!1,!1);if(m)y(m);else Re()}else if(p===97)if(O("async")){let m=l;if(l+=5,v(),O("function")){let g=Ot(d,!1,!0,!1);if(g)y(g);else l=m,Re()}else l=m,Re()}else if(O("abstract"))if(l+=8,v(),O("class")){let m=Rt(d,!1,!1);f.set(m.name,m),c.push(m)}else Re();else l++,Re();else if(p===99)if(O("class")){let m=Rt(d,!1,!1);f.set(m.name,m),c.push(m)}else if(O("const")){let m=l;if(l+=5,v(),O("enum")){l=m+5,v();let g=Vt(d,!1,!0);f.set(g.name,g),c.push(g)}else{l=m;let g=Lt(d,"const",!1);for(let w=0;w<g.length;w++)f.set(g[w].name,g[w])}}else l++,Re();else if(p===101&&O("enum")){let m=Vt(d,!1,!1);f.set(m.name,m),c.push(m)}else if(p===108&&O("let")||p===118&&O("var")){let m=O("let")?"let":"var",g=Lt(d,m,!1);for(let w=0;w<g.length;w++)f.set(g[w].name,g[w])}else if(p===109&&O("module")&&z(6)){let m=Ut(d,!1,"module");c.push(m)}else if(p===110&&O("namespace")&&z(9)){let m=Ut(d,!1,"namespace");c.push(m)}else{let m=i.charCodeAt(l);if(m===re)l++;else if(m===le||m===fe){if(L(m),l<a&&i.charCodeAt(l)===re)l++}else if(m===Fe){if(P(),l<a&&i.charCodeAt(l)===re)l++}else if(m===Hd){if(l++,H(),v(),l<a&&i.charCodeAt(l)===gt)l++,H(),v();if(l<a&&i.charCodeAt(l)===ae)X(ae,Se)}else l++,Re()}}if(h.size>0){fs(c);for(let d of u.values())fs(d)}if(f.size>0)Yd(c,f,u);return c;function fs(d){let p=new Map;for(let g of d)if(g.kind==="function")p.set(g.name,(p.get(g.name)||0)+1);let m=new Set;for(let[g,w]of p)if(w>1)m.add(g);if(m.size>0){let g=new Set;for(let w of m)for(let b=d.length-1;b>=0;b--)if(d[b].kind==="function"&&d[b].name===w&&h.has(d[b])){g.add(b);break}if(g.size>0){let w=[...g].sort((b,T)=>T-b);for(let b of w)d.splice(b,1)}}}function us(d,p){if(O("function")){let m=Ot(d,p,!1,!1);if(m)c.push(m)}else if(O("async")){if(l+=5,v(),O("function")){let m=Ot(d,p,!0,!1);if(m)c.push(m)}}else if(O("class")){let m=Rt(d,p,!1);c.push(m)}else if(O("abstract")){if(l+=8,v(),O("class")){let m=Rt(d,p,!0);c.push(m)}}else if(O("interface")){let m=tn(d,p);c.push(m)}else if(O("type")){let m=rn(d,p);c.push(m)}else if(O("enum")){let m=Vt(d,p,!1);c.push(m)}else if(O("const")){let m=l;if(l+=5,v(),O("enum")){l=m+5,v();let g=Vt(d,p,!0);c.push(g)}else if(p){l=m;let g=Lt(d,"const",!0);for(let w=0;w<g.length;w++)c.push(g[w])}else Re()}else if(O("let")||O("var"))if(p){let m=O("let")?"let":"var",g=Lt(d,m,!0);for(let w=0;w<g.length;w++)c.push(g[w])}else Re();else if(O("module")){let m=Ut(d,p,"module");c.push(m)}else if(O("namespace")){let m=Ut(d,p,"namespace");c.push(m)}else if(O("global")){l+=6,v();let m=`declare global ${l<a&&i.charCodeAt(l)===J?an():"{}"}`,g=tt(d);c.push({kind:"module",name:"global",text:m,isExported:!1,leadingComments:g,start:d,end:l})}else Re()}}function Ul(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 o=r;r++;while(r<n){let s=e.charCodeAt(r);if(s>=65&&s<=90||s>=97&&s<=122||s>=48&&s<=57||s===95||s===36||s>127)r++;else break}t.add(e.substring(o,r))}else r++}}function Kl(e,t){let r=0;while(r<e.length){let n=e.charCodeAt(r);if(n===le||n===fe||n===Fe){let u=n;r++;while(r<e.length)if(e.charCodeAt(r)===nt)r+=2;else if(e.charCodeAt(r++)===u)break;continue}if(n===ee&&e.charCodeAt(r+1)===ee){r+=2;while(r<e.length&&e.charCodeAt(r)!==ve&&e.charCodeAt(r)!==xe)r++;continue}if(n===ee&&e.charCodeAt(r+1)===Ae){let u=e.indexOf("*/",r+2);r=u===-1?e.length:u+2;continue}if(!yt(n)){r++;continue}let i=r++;while(r<e.length&&Ue(e.charCodeAt(r)))r++;let o=i-1,s=r;while(o>=0&&_e(e.charCodeAt(o)))o--;while(s<e.length&&_e(e.charCodeAt(s)))s++;let a=o>=0?e.charCodeAt(o):0,c=s<e.length?e.charCodeAt(s):0,f=i>=3&&e.slice(i-3,i)==="...";if(c===ft||a===gt&&!f)continue;if(c===ae&&(a===J||a===dt))continue;t.add(e.slice(i,r))}}function Yd(e,t,r){let n=new Set,i=new Set;for(let a of e)i.add(a.name);let o=new Set,s=[];for(let a=0;a<e.length;a++){let c=e[a];if(c.kind!=="import"){if(s.push(c.text),Ul(c.text,o),typeof c.value==="string")Kl(c.value,o)}}for(;;){let a=[];for(let[u,h]of t){if(n.has(u))continue;if(o.has(u)){if(!i.has(u)){let l=h.kind==="function"?r.get(u):void 0;if(l)for(let y of l)a.push(y);else a.push(h);i.add(u)}n.add(u)}}if(a.length===0)break;a.sort((u,h)=>(u.start??1/0)-(h.start??1/0));let c=[],f=0;for(let u=0;u<e.length;u++){let h=e[u].start??1/0;while(f<a.length&&(a[f].start??1/0)<=h)c.push(a[f++]);c.push(e[u])}while(f<a.length)c.push(a[f++]);e.length=0;for(let u=0;u<c.length;u++)e.push(c[u]);for(let u of a)if(u.kind!=="import"){if(s.push(u.text),Ul(u.text,o),typeof u.value==="string")Kl(u.value,o)}}}var Me=32,De=9,ve=10,xe=13,ee=47,Ae=42,le=39,fe=34,Fe=96,nt=92,J=123,Q=125,ae=40,Se=41,$e=91,ke=93,we=60,me=62,re=59,ft=58,be=61,dt=44,gt=46,Ui=63,jo=35,Hd=64,zd=36,_o;var ql=he(()=>{hn();Go();_o=["public","protected","private","readonly","override"]});function Zl(e,t,r=!0,n=!1){if(El(t))e=Al(e);else if(Tl(t))e=Ol(e);let i=vr(e),o=`${t}:${r?1:0}:${n?1:0}`,s=mr.get(o);if(s&&s.contentHash===i)return s.lastAccess=++Yl,s.declarations;let a=n?Hl(e,t,r):zl(e,t,r);if(mr.set(o,{declarations:a,contentHash:i,lastAccess:++Yl}),mr.size>Zd){let c=Math.max(1,Math.ceil(mr.size*0.1)),f=[];for(let[u,h]of mr)f.push([u,h.lastAccess]);f.sort((u,h)=>u[1]-h[1]);for(let u=0;u<c&&u<f.length;u++)mr.delete(f[u][0])}return a}var Zd=100,Yl=0,mr;var Xl=he(()=>{$o();Rl();ql();Sn();mr=new Map});function Ql(e,t,r=!0,n=!1){return Zl(e,t,r,n)}var ec=he(()=>{Xl()});async function Xd(){if(Hi!==null)return Hi;try{return Ft=await import("prettier"),Hi=!0,!0}catch{return Hi=!1,!1}}async function Qd(e,t){if(!Ft)return null;try{if(t&&Ft.resolveConfig){let r=await Ft.resolveConfig(t);if(r)return r}if(e&&Ft.resolveConfig){let r=await Ft.resolveConfig(e);if(r)return r}return null}catch{return null}}async function em(e,t){if(!Ft)throw Error("Prettier is not available");let r={...t,parser:t.parser||"typescript"};return Ft.format(e,r)}function tm(e,t={}){let{indentSize:r=2,useTabs:n=!1,maxLineWidth:i=100,trailingNewline:o=!0,normalizeWhitespace:s=!0,sortImports:a=!0,groupImports:c=!0}=t,f=e,u=n?"\t":" ".repeat(r);if(f.indexOf(`\r
204
+ `;i+=`| Variable | Type | Description | Example |
205
+ `,i+=`|----------|------|-------------|----------|
206
+ `;for(let r of e)i+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
207
+ `;return i}}function jf(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}async function Gf(e){let t=Xp(e),i=Mn.get(t),r,n=new Promise((o)=>{r=o});Mn.set(t,n),await i;try{if(Yp(t),af.cache[t]?.loaded===!0||Gs.has(t))delete af.cache[t];try{let o=await import(Qp(t).href);return Gs.delete(t),o}catch(o){throw Gs.add(t),o}}finally{if(r(),Mn.get(t)===n)Mn.delete(t)}}function wg(e,t,i={}){return _f(e,t,i,new WeakMap)}function _f(e,t,i,r){let{arrayMergeMode:n="replace",skipNullish:o=!1,customMerger:s}=i;if(t===null||t===void 0)return o?e:t;if(s){let c=s(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return Vf(e,t,n,r);if(!xt(t)||!xt(e))return t;return $g(e,t,i,r)}function Vf(e,t,i,r){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(i){case"replace":return t;case"concat":return Cg(e,t);case"smart":return vg(e,t,r);default:return t}return t}function Cg(e,t){let i=[...t];for(let r of e)if(!i.some((n)=>Qs(n,r)))i.push(r);return i}function vg(e,t,i){if(t.length===0)return e;if(e.length===0)return t;if(xt(t[0])&&xt(e[0]))return bg(e,t,i);if(t.every((r)=>typeof r==="string")&&e.every((r)=>typeof r==="string")){let r=[...t];for(let n of e)if(!r.includes(n))r.push(n);return r}return t}function bg(e,t,i){let r=[...t];for(let n of e){if(!xt(n)){r.push(n);continue}let o=["id","name","key","path","type"],s=!1;for(let c of o)if(c in n){if(r.find((l)=>xt(l)&&(c in l)&&l[c]===n[c])){s=!0;break}}if(!s)r.push(n)}return r}function $g(e,t,i,r){let n=t;if(xt(n)&&r.has(n))return r.get(n);let o={...e};if(xt(n))r.set(n,o);for(let s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;let c=n[s],l=o[s];if(i.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){o[s]=c;continue}if(xt(c)&&xt(l))o[s]=_f(l,c,i,r);else if(Array.isArray(c)||Array.isArray(l))o[s]=Vf(l,c,i.arrayMergeMode||"smart",r);else o[s]=c}return o}function Uf(e,t,i="replace"){return wg(e,t,{arrayMergeMode:i==="replace"?"replace":"smart",skipNullish:!0})}function Qs(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!Qs(e[i],t[i]))return!1;return!0}if(xt(e)&&xt(t)){let i=Object.keys(e),r=Object.keys(t);if(i.length!==r.length)return!1;for(let n of i){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Qs(e[n],t[n]))return!1}return!0}return!1}function xt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Kf{extensions=df;async loadFromPath(e,t,i={}){let{arrayStrategy:r="replace",useCache:n=!0,cacheTtl:o,trackPerformance:s=!0,verbose:c=!1,strictDiscovery:l=!1}=i;if(n){let u=_n.getWithFileCheck("file",e);if(u){if(c)console.log(`Configuration loaded from cache: ${e}`);return u}}let f=async()=>{try{try{em(e)}catch(a){if(jf(a)||!l)return null;throw a}let u=await Gf(e),d=Object.hasOwn(u,"default"),h=Object.keys(u).length>0,p=d?u.default:u;if(!d&&!h)throw new zi(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof p!=="object"||p===null||Array.isArray(p))throw new zi(e,Error("Configuration must export a valid object"),"unknown");let m={config:Uf(t,p,r),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)_n.setWithFileCheck("file",m,e,o);return m}catch(u){throw u instanceof Error?ni.configLoad(e,u):ni.configLoad(e,Error(String(u)))}};if(s)return ea.track("loadFromPath",f,{path:e});return f()}async tryLoadFromPaths(e,t,i={}){for(let r of e)try{let n=await this.loadFromPath(r,t,i);if(n)return n}catch(n){if(n instanceof zi)throw n;if(i.verbose)console.warn(`Failed to load config from ${r}:`,n)}return null}generateConfigPaths(e,t,i){return im({name:e,directory:t,alias:i})}generateNamePatterns(e,t){return hf({name:e,alias:t})}checkFileAccess(e){return yg(async()=>Ns(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,i){let r=[];if(!Ns(e))return r;if(t||i){let n=this.generateNamePatterns(t||"",i);for(let o of n)for(let s of this.extensions){let c=zc(e,`${o}${s}`);if(await this.checkFileAccess(c))r.push(c)}}else try{let{readdirSync:n}=await import("fs"),o=n(e);for(let s of o)if(this.looksLikeConfigFile(s)){let c=zc(e,s);if(await this.checkFileAccess(c))r.push(c)}}catch{return[]}return r}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(!Ns(e))return t.push("Configuration file does not exist"),t;let i=await import(e),r=i.default||i;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),o=n(e,"utf8");JSON.parse(o)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(i){t.push(`Failed to load configuration file: ${i}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let i=new Map;return await Promise.allSettled(e.map(async(r)=>{try{let n=await this.loadFromPath(r,{},t);if(n)i.set(r,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${r}:`,n)}})),i}}class zf{async validateConfiguration(e,t,i={}){let{stopOnFirstError:r=!1,validateRequired:n=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=i,f=async()=>{let u=[],d=[],h={stopOnFirstError:r,validateRequired:n,validateTypes:o,customRules:s,trackPerformance:c,verbose:l};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],h);else return this.validateWithJSONSchema(e,t,h)}catch(p){return u.push({path:"",message:`Validation failed: ${p}`,rule:"system"}),{isValid:!1,errors:u,warnings:d}}};if(c)return await ea.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,i){try{if(!tm(t))throw new Yn(t,[{path:"",message:"Schema file does not exist"}]);let r=await Gf(t),n=Object.hasOwn(r,"default")?r.default:r;if(Array.isArray(n))return this.validateWithRules(e,n,i);else{if(typeof n!=="object"||n===null)throw Error("Schema must export an object or validation rule array");return this.validateWithJSONSchema(e,n,i)}}catch(r){throw new Yn(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(e,t,i){let r=[],n=[];return this.validateObjectAgainstSchema(e,t,"",r,n,i),{isValid:r.length===0,errors:r,warnings:n}}validateObjectAgainstSchema(e,t,i,r,n,o){if(o.validateTypes&&t.type){let s=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(s)){if(r.push({path:i,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),o.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(r.push({path:i,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),o.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)r.push({path:i,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)r.push({path:i,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))r.push({path:i,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)r.push({path:i,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)r.push({path:i,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let s=0;s<e.length;s++){let c=i?`${i}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,c,r,n,o),o.stopOnFirstError&&r.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let s=e;if(o.validateRequired&&t.required){for(let c of t.required)if(!(c in s)){if(r.push({path:i?`${i}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[c,l]of Object.entries(t.properties))if(c in s){let f=i?`${i}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,f,r,n,o),o.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let l of Object.keys(s))if(!c.has(l))n.push({path:i?`${i}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,i){let r=[],n=[];for(let o of t)try{let s=this.getValueByPath(e,o.path),c=this.validateWithRule(s,o,o.path);if(r.push(...c),i.stopOnFirstError&&r.length>0)break}catch(s){r.push({path:o.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:n}}validateWithRule(e,t,i){let r=[];if(t.required&&(e===void 0||e===null))return r.push({path:i,message:t.message||`Property '${i}' is required`,expected:"required",rule:"required"}),r;if(e===void 0||e===null)return r;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)r.push({path:i,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)r.push({path:i,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)r.push({path:i,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))r.push({path:i,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))r.push({path:i,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)r.push({path:i,message:t.message||n,rule:"custom"})}return r}getValueByPath(e,t){if(!t)return e;let i=t.split("."),r=e;for(let n of i)if(r&&typeof r==="object"&&n in r)r=r[n];else return;return r}generateRulesFromInterface(e){let t=[],i=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of i){let[,n,o,s]=r;t.push({path:n,required:!o,type:this.mapTypeScriptType(s)})}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:Eg},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function Sg(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((i)=>`"${i}"`).join(", ")}`}class Hf{fileLoader=new Kf;envProcessor=new ca;validator=new zf;async loadConfig(e){let t=Date.now(),{cache:i,performance:r,schema:n,validate:o,...s}=e,c=s.errorPolicy==="throw"?{...i,enabled:!1}:i;try{if(c?.enabled){let f=this.checkCache(s.name||"",s);if(f)return f}let l;try{l=await this.loadConfigurationStrategies(s,!0,c)}catch(f){if(s.configFile||s.errorPolicy==="throw"&&!(f instanceof vr))throw f;let u=s.__strictErrorHandling;if(f instanceof vr){if(u&&s.errorPolicy!=="throw")throw f;l={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(f instanceof zi){let d=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),h=!d&&(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(u&&(p||d))throw f;if(h&&(!u||!p))l={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!u)l={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else l={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(n||o)await this.validateConfiguration(l.config,n,o,s.name);if(c?.enabled&&l)this.cacheResult(s.name||"",l,c,s);if(r?.enabled){let f={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(f);if(r.slowThreshold&&f.duration>r.slowThreshold)Kt.warn(`Slow configuration loading detected: ${f.duration}ms for ${s.name}`);l.metrics=f}return l}catch(l){if(l instanceof vr)throw l;let f=Date.now()-t;throw Kt.error(`Configuration loading failed after ${f}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(e,t=!1,i){let{name:r="",alias:n,configFile:o,cwd:s,configDir:c,defaultConfig:l,checkEnv:f=!0,arrayStrategy:u="replace",verbose:d=!1}=e,h=s||Xn.cwd(),p=[];if(o){let b=Lt(h,o);p.push(b);let v=f?yr(r,l,d):l,T=await this.fileLoader.tryLoadFromPaths([b],v,{arrayStrategy:u,verbose:d,cacheTtl:i?.ttl,useCache:i?.enabled!==!1&&(!i?.ttl||i.ttl>100),strictDiscovery:!0});if(!T)throw ni.configNotFound(r||o,p,n);if(d)Kt.success(`Configuration loaded from explicit path: ${b}`);return this.finalizeResult(T,p,f,r,d)}let m=await this.loadLocalConfiguration(r,n,h,c,l,u,d,f,i,e.errorPolicy==="throw");if(m)return p.push(...this.getLocalSearchPaths(r,n,h,c)),this.finalizeResult(m,p,f,r,d);let a=await this.loadHomeConfiguration(r,n,l,u,d,f,i,e.errorPolicy==="throw");if(a)return p.push(...this.getHomeSearchPaths(r,n)),this.finalizeResult(a,p,f,r,d);let C=await this.loadPackageJsonConfiguration(r,n,h,l,u,d,f,e.errorPolicy);if(C)return p.push(Lt(h,"package.json")),this.finalizeResult(C,p,f,r,d);if(p.push(...this.getAllSearchPaths(r,n,h,c)),t)throw ni.configNotFound(r,p,n);return{...await this.applyEnvironmentVariables(r,l,f,d),warnings:[`No configuration file found for "${r}"${Sg(n)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,i,r,n,o,s,c,l,f=!1){let u=c?yr(e,n,s):n,d=this.getLocalDirectories(i,r);for(let h of d){if(s)Kt.info(`Searching for configuration in: ${h}`);let p=this.fileLoader.generateConfigPaths(e,h,t),m=await this.fileLoader.tryLoadFromPaths(p,u,{arrayStrategy:o,verbose:s,cacheTtl:l?.ttl,useCache:l?.enabled!==!1&&(!l?.ttl||l.ttl>100),strictDiscovery:f});if(m){if(s)Kt.success(`Configuration loaded from: ${m.source.path}`);return m}}return null}async loadHomeConfiguration(e,t,i,r,n,o,s,c=!1){if(!e)return null;let l=o?yr(e,i,n):i,f=[Lt(Ni(),".config",e),Lt(Ni(),".config"),Ni()];for(let u of f){if(n)Kt.info(`Checking home directory: ${u}`);let d=this.fileLoader.generateConfigPaths(e,u,t),h=await this.fileLoader.tryLoadFromPaths(d,l,{arrayStrategy:r,verbose:n,cacheTtl:s?.ttl,useCache:s?.enabled!==!1&&(!s?.ttl||s.ttl>100),strictDiscovery:c});if(h){if(n)Kt.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(e,t,i,r,n,o,s,c){let l=s?yr(e,r,o):r,f=Lt(i,"package.json"),u=c==="throw";try{let d=JSON.parse(up(f,"utf8"));if(typeof d!=="object"||d===null||Array.isArray(d))throw Error("package.json must contain an object");let h=d,p=t===void 0?[]:Array.isArray(t)?t:[t],m=[e,...p.filter(Boolean)].find((C)=>Object.hasOwn(h,C)&&(u||Boolean(h[C])));if(m===void 0)return null;let a=h[m];if(typeof a!=="object"||a===null||Array.isArray(a))throw Error(`Configuration field "${m}" must contain an object`);if(o)Kt.success(`Configuration loaded from package.json: ${m}`);return{config:Uf(l,a,n),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}catch(d){if(jf(d))return null;if(u)throw ni.configLoad(f,d instanceof Error?d:Error(String(d)));if(o)Kt.warn("Failed to load package.json:",[d instanceof Error?d:Error(String(d))]);return null}}async applyEnvironmentVariables(e,t,i,r){if(!i||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:yr(e,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,i,r,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,i,r){let n=[];if(i){let o=i(e);if(o)n.push(...o)}if(t){let o=await this.validator.validateConfiguration(e,t);if(!o.isValid)n.push(...o.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(n.length>0)throw ni.configValidation(r||"unknown",n,r)}checkCache(e,t){let i=this.generateCacheKey(e,t);return _n.get(i)||null}cacheResult(e,t,i,r){let n=this.generateCacheKey(e,r);_n.set(n,t,void 0,i.ttl)}generateCacheKey(e,t){let i=[e];if(t.alias){let r=Array.isArray(t.alias)?t.alias.join(","):t.alias;i.push(`alias:${r}`)}if(t.cwd)i.push(`cwd:${t.cwd}`);if(t.configFile)i.push(`configFile:${t.configFile}`);if(t.configDir)i.push(`configDir:${t.configDir}`);if("checkEnv"in t)i.push(`checkEnv:${t.checkEnv}`);return i.join("|")}getLocalDirectories(e,t){return rm({cwd:e,configDir:t})}getAllSearchPaths(e,t,i,r){let n=[];return n.push(...this.getLocalSearchPaths(e,t,i,r)),n.push(...this.getHomeSearchPaths(e,t)),n.push(Lt(i,"package.json")),n}getLocalSearchPaths(e,t,i,r){let n=this.getLocalDirectories(i,r),o=[];for(let s of n)o.push(...this.fileLoader.generateConfigPaths(e,s,t));return o}getHomeSearchPaths(e,t){if(!e)return[];let i=[Lt(Ni(),".config",e),Lt(Ni(),".config"),Ni()],r=[];for(let n of i)r.push(...this.fileLoader.generateConfigPaths(e,n,t));return r}async loadConfigWithResult(e){return this.loadConfig(e)}}function yr(e,t,i=!1){let r=new ca,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,c=[]){let l={...s};for(let[f,u]of Object.entries(s)){let d=[...c,f],h=[`${n}_${d.join("_").toUpperCase()}`,`${n}_${d.map((a)=>a.toUpperCase()).join("")}`,`${n}_${d.map((a)=>a.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],p,m;for(let a of h)if(p=Xn.env[a],p!==void 0){m=a;break}if(p!==void 0&&m)if(typeof u==="boolean")l[f]=["true","1","yes"].includes(p.toLowerCase());else if(typeof u==="number"){let a=Number(p);if(!Number.isNaN(a))l[f]=a}else if(Array.isArray(u))try{l[f]=JSON.parse(p)}catch{l[f]=p.split(",").map((a)=>a.trim())}else l[f]=p;else if(u&&typeof u==="object"&&!Array.isArray(u))l[f]=o(u,d)}return l}return o(t)}var _n,ea,df,nm,om=(e)=>e,am=(e,t)=>{for(var i in t)nm(e,i,{get:t[i],enumerable:!0,configurable:!0,set:sm.bind(t,i)})},lm=(e,t)=>()=>(e&&(t=e(e=0)),t),pf,Ef,Hi,Sr,Sf,Nm,Fm,qc,In,Ks,at,Ve,Wm,Jc,Lm,Yc,Bm,jm,Fs,Gm,Xc,Zc,Ws,_m,Vm,Um,Km,Nn,xf,zm,lt,Hm,qm,Qc,Fn,zs,it,xe,Jm,ef,Ym,tf,Xm,Zm,Ls,Qm,rf,nf,eg,Bs,tg,ig,rg,ng,og,Wn,Af,sg,ag="0.15.6",vt,Hn,$r,Hs,qs,qn,Js,Ys,Er,Xs,Zs,oi,Tf,kf,Mt,Jt,Of,Rf,lg,fg,Pf,Jn,xC,Df,Te,AC,dg,TC,hg,kC,OC,of,RC,pg,mg,PC,sf,MC,DC,IC,NC,FC,js,gg,WC,Dt,vr,zi,If,Nf,la,Ff,Wf,Yn,Lf,Bf,ni,af,Mn,Gs,Eg,Kt,LC,BC,jC,xg,qf;var Jf=me(()=>{_n=new ff,ea=new uf,df=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];nm=Object.defineProperty;pf={};am(pf,{withErrorRecovery:()=>yf,tryLoadConfig:()=>Pm,loadConfigWithResult:()=>Om,loadConfig:()=>$f,isRetryableError:()=>Em,isConfigNotFoundError:()=>$m,isBunfigError:()=>wf,globalPerformanceMonitor:()=>Sr,globalCache:()=>Hi,getEnvOrDefault:()=>Sm,generateConfigTypes:()=>Mm,defaultGeneratedDir:()=>Rf,defaultConfigDir:()=>Of,deepMergeWithArrayStrategy:()=>oa,deepMerge:()=>Cf,createLibraryConfig:()=>Dm,config:()=>Rm,bunfigPlugin:()=>Im,applyEnvVarsToConfig:()=>Cr,TypeGenerationError:()=>Ys,SchemaValidationError:()=>Er,PluginError:()=>Zs,PerformanceMonitor:()=>ia,FileSystemError:()=>Js,ErrorFactory:()=>oi,EnvVarError:()=>qn,EnvProcessor:()=>Zn,ConfigValidator:()=>sa,ConfigValidationError:()=>Hs,ConfigNotFoundError:()=>Hn,ConfigMergeError:()=>qs,ConfigLoader:()=>aa,ConfigLoadError:()=>$r,ConfigFileLoader:()=>Qn,ConfigCache:()=>ta,CacheUtils:()=>Sf,BunfigError:()=>vt,BrowserConfigError:()=>Xs,ArrayMergeStrategies:()=>Tf});lg=lm(async()=>{Ef=import.meta.require,Hi=new ta,Sr=new ia,Sf={createKey:cm,isEquivalent:fm,estimateMemoryUsage:um},Nm=jn(Vs.cwd(),"config"),Fm=jn(Vs.cwd(),"src/generated"),qc=Bn.env.CLARITY_LOG_DIR||yp(pm(),"logs"),In={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:qc,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Ks=await mm(),at={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"},Ve=at,Wm=at.red,Jc=at.green,Lm=at.yellow,Yc=at.blue,Bm=at.magenta,jm=at.cyan,Fs=at.white,Gm=at.gray,Xc=at.bgRed,Zc=at.bgYellow,Ws=at.bold,_m=at.dim,Vm=at.italic,Um=at.underline,Km=at.reset,Nn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},xf={debug:"\uD83D\uDD0D",info:Yc("\u2139"),success:Jc("\u2713"),warning:Zc(Fs(Ws(" WARN "))),error:Xc(Fs(Ws(" ERROR ")))},zm=new Un("stacks"),lt=new Un("bunfig",{showTags:!0}),Hm=ht(br.cwd(),"config"),qm=ht(br.cwd(),"src/generated"),Qc=Ln.env.CLARITY_LOG_DIR||mp(Cm(),"logs"),Fn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Qc,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},zs=await vm(),it={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"},xe=it,Jm=it.red,ef=it.green,Ym=it.yellow,tf=it.blue,Xm=it.magenta,Zm=it.cyan,Ls=it.white,Qm=it.gray,rf=it.bgRed,nf=it.bgYellow,eg=it.bgGray,Bs=it.bold,tg=it.dim,ig=it.italic,rg=it.underline,ng=it.strikethrough,og=it.reset,Wn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Af={debug:"\uD83D\uDD0D",info:tf("\u2139"),success:ef("\u2713"),warning:nf(Ls(Bs(" WARN "))),error:rf(Ls(Bs(" ERROR ")))},sg=new zn("stacks"),vt=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,i])=>`${t}: ${i}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},Hn=class extends vt{code="CONFIG_NOT_FOUND";constructor(e,t,i){let r=i?` or alias "${i}"`:"";super(`Configuration "${e}"${r} not found`,{configName:e,alias:i,searchPaths:t,searchPathCount:t.length})}},$r=class extends vt{code="CONFIG_LOAD_ERROR";constructor(e,t,i){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:i,originalError:t.name,originalMessage:t.message});this.cause=t}},Hs=class extends vt{code="CONFIG_VALIDATION_ERROR";constructor(e,t,i){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:i,validationErrors:t,errorCount:t.length})}},qs=class extends vt{code="CONFIG_MERGE_ERROR";constructor(e,t,i,r){super(`Failed to merge configuration from "${e}" with "${t}": ${i.message}`,{sourcePath:e,targetPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}},qn=class extends vt{code="ENV_VAR_ERROR";constructor(e,t,i,r){super(`Failed to parse environment variable "${e}" with value "${t}" as ${i}`,{envKey:e,envValue:t,expectedType:i,configName:r})}},Js=class extends vt{code="FILE_SYSTEM_ERROR";constructor(e,t,i){super(`File system ${e} failed for "${t}": ${i.message}`,{operation:e,path:t,originalError:i.name,originalMessage:i.message});this.cause=i}},Ys=class extends vt{code="TYPE_GENERATION_ERROR";constructor(e,t,i){super(`Failed to generate types from "${e}" to "${t}": ${i.message}`,{configDir:e,outputPath:t,originalError:i.name,originalMessage:i.message});this.cause=i}},Er=class extends vt{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,i){super(`Schema validation failed${i?` for config "${i}"`:""}`,{schemaPath:e,configName:i,validationErrors:t,errorCount:t.length})}},Xs=class extends vt{code="BROWSER_CONFIG_ERROR";constructor(e,t,i,r){super(`Failed to fetch configuration from "${e}": ${t} ${i}`,{endpoint:e,status:t,statusText:i,configName:r})}},Zs=class extends vt{code="PLUGIN_ERROR";constructor(e,t,i){super(`Plugin "${e}" failed during ${t}: ${i.message}`,{pluginName:e,operation:t,originalError:i.name,originalMessage:i.message});this.cause=i}},oi={configNotFound(e,t,i){return new Hn(e,t,i)},configLoad(e,t,i){return new $r(e,t,i)},configValidation(e,t,i){return new Hs(e,t,i)},configMerge(e,t,i,r){return new qs(e,t,i,r)},envVar(e,t,i,r){return new qn(e,t,i,r)},fileSystem(e,t,i){return new Js(e,t,i)},typeGeneration(e,t,i){return new Ys(e,t,i)},schemaValidation(e,t,i){return new Er(e,t,i)},browserConfig(e,t,i,r){return new Xs(e,t,i,r)},plugin(e,t,i){return new Zs(e,t,i)}},Tf={replace:"replace",concat:"concat",smart:"smart"},kf=/^https?:\/\//,Mt=new zn("bunfig",{showTags:!0}),Jt=new aa,Of=pt($i.cwd(),"config"),Rf=pt($i.cwd(),"src/generated")});fg=Gn.env.CLARITY_LOG_DIR||Bp(cg(),"logs"),Pf={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:fg,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Jn={...Pf},xC=(async()=>{try{let{loadConfig:e}=await lg().then(()=>pf),t=await e({name:"clarity",alias:"logging",defaultConfig:Pf,cwd:Gn.cwd()});if(t)Object.assign(Jn,t)}catch{}return Jn})();Df={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=Df,{red:AC,green:dg,yellow:TC,blue:hg,magenta:kC,cyan:OC,white:of,gray:RC,bgRed:pg,bgYellow:mg,bgGray:PC,bold:sf,dim:MC,italic:DC,underline:IC,strikethrough:NC,reset:FC}=Df,js={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},gg={debug:"\uD83D\uDD0D",info:hg("\u2139"),success:dg("\u2713"),warning:mg(of(sf(" WARN "))),error:pg(of(sf(" ERROR ")))};WC=new eo("stacks");Dt=class Dt 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,i])=>`${t}: ${i}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}};vr=class vr extends Dt{name="ConfigNotFoundError";code="CONFIG_NOT_FOUND";constructor(e,t,i){let r=i===void 0?[]:Array.isArray(i)?i.filter(Boolean):[i],n="";if(r.length===1)n=` or alias "${r[0]}"`;else if(r.length>1)n=` or aliases ${r.map((o)=>`"${o}"`).join(", ")}`;super(`Configuration "${e}"${n} not found`,{configName:e,alias:i,searchPaths:t,searchPathCount:t.length})}};zi=class zi extends Dt{name="ConfigLoadError";code="CONFIG_LOAD_ERROR";constructor(e,t,i){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:i,originalError:t.name,originalMessage:t.message});this.cause=t}};If=class If extends Dt{name="ConfigValidationError";code="CONFIG_VALIDATION_ERROR";constructor(e,t,i){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:i,validationErrors:t,errorCount:t.length})}};Nf=class Nf extends Dt{name="ConfigMergeError";code="CONFIG_MERGE_ERROR";constructor(e,t,i,r){super(`Failed to merge configuration from "${e}" with "${t}": ${i.message}`,{sourcePath:e,targetPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}};la=class la extends Dt{name="EnvVarError";code="ENV_VAR_ERROR";constructor(e,t,i,r){super(`Failed to parse environment variable "${e}" with value "${t}" as ${i}`,{envKey:e,envValue:t,expectedType:i,configName:r})}};Ff=class Ff extends Dt{name="FileSystemError";code="FILE_SYSTEM_ERROR";constructor(e,t,i){super(`File system ${e} failed for "${t}": ${i.message}`,{operation:e,path:t,originalError:i.name,originalMessage:i.message});this.cause=i}};Wf=class Wf extends Dt{name="TypeGenerationError";code="TYPE_GENERATION_ERROR";constructor(e,t,i){super(`Failed to generate types from "${e}" to "${t}": ${i.message}`,{configDir:e,outputPath:t,originalError:i.name,originalMessage:i.message});this.cause=i}};Yn=class Yn extends Dt{name="SchemaValidationError";code="SCHEMA_VALIDATION_ERROR";constructor(e,t,i){super(`Schema validation failed${i?` for config "${i}"`:""}`,{schemaPath:e,configName:i,validationErrors:t,errorCount:t.length})}};Lf=class Lf extends Dt{name="BrowserConfigError";code="BROWSER_CONFIG_ERROR";constructor(e,t,i,r){super(`Failed to fetch configuration from "${e}": ${t} ${i}`,{endpoint:e,status:t,statusText:i,configName:r})}};Bf=class Bf extends Dt{name="PluginError";code="PLUGIN_ERROR";constructor(e,t,i){super(`Plugin "${e}" failed during ${t}: ${i.message}`,{pluginName:e,operation:t,originalError:i.name,originalMessage:i.message});this.cause=i}};ni={configNotFound(e,t,i){return new vr(e,t,i)},configLoad(e,t,i){return new zi(e,t,i)},configValidation(e,t,i){return new If(e,t,i)},configMerge(e,t,i,r){return new Nf(e,t,i,r)},envVar(e,t,i,r){return new la(e,t,i,r)},fileSystem(e,t,i){return new Ff(e,t,i)},typeGeneration(e,t,i){return new Wf(e,t,i)},schemaValidation(e,t,i){return new Yn(e,t,i)},browserConfig(e,t,i,r){return new Lf(e,t,i,r)},plugin(e,t,i){return new Bf(e,t,i)}};af=Zp(import.meta.url),Mn=new Map,Gs=new Set;Eg=/^https?:\/\//;Kt=new eo("bunfig",{showTags:!0});LC=new Hf;BC=Lt(Xn.cwd(),"config"),jC=Lt(Xn.cwd(),"src/generated"),xg={cwd:cp.cwd(),root:"./src",entrypoints:["**/*.{ts,tsx,mts,cts,vue,stx}"],outdir:"./dist",keepComments:!0,clean:!0,tsconfigPath:"./tsconfig.json",outputStructure:"mirror",moduleSpecifierMode:"preserve",verbose:!1,importOrder:["bun"],declarationMap:!1},qf=xg});import{existsSync as Yf}from"fs";import{basename as Ag,dirname as Tg,extname as Xf,isAbsolute as to,relative as Yt,resolve as Xt}from"path";async function Qf(e,t){let i=await Mg(e);Pg(e,i);let r=i.slice(),n=await(t?t():yn(e)),o=null;if(e.autoIncludeReExports!==!1&&r.length>0){o=await mr(r,{includeImports:!0,resolveSpecifier:n});let d=Xt(e.cwd,e.root),h=e.exclude||[],p=[];for(let m of o.reachable){if(r.includes(m))continue;if(!fa(m))continue;if(m.endsWith(".d.ts"))continue;if(m.includes("node_modules"))continue;let a=e.outputStructure==="flat"&&i.some((C)=>n.isPackageLocal?.(C,m));if(!Bt(m,d)&&!a){ne.warn(`Skipping auto-included source outside root: ${Yt(e.cwd,m)}`);continue}if(Ar(m,h,d))continue;p.push(m)}if(p.length>0)r=[...r,...p],ne.debug(`Auto-included ${p.length} file(s) reached via relative re-exports`)}let s=Dg(r,e),c=o??await mr(r,{includeImports:!0,resolveSpecifier:n}),l=await ic([...c.sources.keys()],n,e.isolatedDeclarations??!1,c.sources),f=new Set(r);for(let[d,h]of l){if(!f.has(d))continue;for(let p of h){let m=n(p,d).resolved;if(m&&!f.has(m))throw Error(`Module augmentation import ${JSON.stringify(p)} from ${d} requires a source not emitted by this package build: ${m}`)}}let u=[...l].map(([d,h])=>[d,[...h].sort()]).sort(([d],[h])=>d.localeCompare(h));return Object.freeze({entryFiles:Object.freeze(i),files:Object.freeze(r),outputBySource:s,resolver:n,reachability:o,augmentationImports:l,getResolutionFingerprint:()=>JSON.stringify({resolution:n.cacheKey?.(r),augmentations:u})})}function Og(e){let t=xr.get(e);if(!t){if(t=new Zf(e),xr.set(e,t),xr.size>kg){let i=xr.keys().next().value;if(i!==void 0)xr.delete(i)}}return t}function Ar(e,t,i){if(!t||t.length===0)return!1;let r=Yt(i,e);for(let n of t){let o=Og(n);if(o.match(r)||o.match(e))return!0}return!1}function Pg(e,t){let i=Xt(e.cwd,e.root),r=` root: ${i}
208
+ entrypoints: ${e.entrypoints.map((o)=>JSON.stringify(o)).join(", ")||"(none)"}
209
+ `+(e.exclude?.length?` exclude: ${e.exclude.map((o)=>JSON.stringify(o)).join(", ")}
210
+ `:"")+"Entrypoints are resolved relative to --root. Pass several by repeating --entrypoints or separating them with commas.";if(t.length===0){if(e.entrypoints.filter((o)=>to(o)&&Yf(o)&&!Bt(o,i)).length===e.entrypoints.length)return;throw Error(`No source files matched. Nothing was generated.
211
+ ${r}`)}let n=e.entrypoints.filter((o)=>{if(Rg.test(o))return!1;return!Yf(to(o)?o:Xt(i,o))});if(n.length>0)throw Error(`Entrypoint${n.length>1?"s":""} not found: ${n.map((o)=>JSON.stringify(o)).join(", ")}
212
+ ${r}`)}async function Mg(e){let t=[],i=Xt(e.cwd,e.root),r=e.exclude||[],n=[...e.entrypoints,...e.include??[]];for(let o of n)if(to(o)&&fa(o)){if(!o.includes("node_modules")){if(!Bt(o,i)&&e.outputStructure!=="flat")ne.warn(`Skipping entrypoint outside root: ${Yt(e.cwd,o)}`);else if(!Ar(o,r,i))t.push(o)}}else{let s=new Zf(o);for await(let c of s.scan({cwd:i,absolute:!0,onlyFiles:!0}))if(fa(c)&&!c.includes("node_modules")){if(!Ar(c,r,i))t.push(c)}}return[...new Set(t.map((o)=>Xt(o)))].sort()}function Bt(e,t){let i=Yt(t,e);return i!==".."&&!i.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!to(i)}function Dg(e,t){let i=new Map,r=new Map;for(let n of e){let o=qi(n,t),s=i.get(o);if(s&&s!==n)throw Error(`Output path collision: ${Yt(t.cwd,s)} and ${Yt(t.cwd,n)} both emit ${Yt(t.cwd,o)}`);i.set(o,n),r.set(n,o)}return r}function fa(e){return/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/.test(e)&&!/\.d\.(?:ts|mts|cts)$/.test(e)}function qi(e,t){let i=Xt(t.cwd,t.root),r=Yt(i,e),n=/\.d\.(?:ts|mts|cts)$/.test(r)?r:r.replace(/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/,(o)=>{if(o===".mts"||o===".mjs")return".d.mts";if(o===".cts"||o===".cjs")return".d.cts";return".d.ts"});if(t.outputStructure==="mirror")return Xt(t.cwd,t.outdir,n);else{let o=Ag(n);return Xt(t.cwd,t.outdir,o)}}function Ig(e,t,i=""){let r=Yt(Tg(e),t).replace(/\\/g,"/");if(r=r.replace(/\.d\.mts$/,"").replace(/\.d\.cts$/,"").replace(/\.d\.ts$/,""),i)r+=i;if(!r.startsWith("."))r=`./${r}`;return r}function eu(e,t,i,r){let n=qi(e,t);return(o)=>{let s=i(o,e);if(!s.isRelative||!s.resolved)return{kind:"unchanged",reason:s.isRelative?"unresolved":"external",specifier:o,emittedSpecifier:o};if(/\.d\.(?:ts|mts|cts)$/.test(s.resolved)){if(t.moduleSpecifierMode!=="node")return{kind:"unchanged",reason:"preserved-declaration",specifier:o,emittedSpecifier:o};if(r&&!r.has(s.resolved))throw Error(`Local declaration ${JSON.stringify(o)} from ${e} targets an authored declaration not emitted by this package build: ${s.resolved}. Declaration-only dependencies must be delivered with the package before this importer can be emitted.`)}if(s.isAlias&&r&&!r.has(s.resolved))throw Error(`Local alias ${JSON.stringify(o)} from ${e} targets a declaration excluded from this package build: ${s.resolved}`);if(r&&!r.has(s.resolved)&&Ar(s.resolved,t.exclude??[],Xt(t.cwd,t.root)))throw Error(`Local reference ${JSON.stringify(o)} from ${e} targets a source excluded from this package build: ${s.resolved}`);let c=s.isAlias?s.suffix??"":o.match(/[?#].*$/)?.[0]??"",l=c?o.slice(0,-c.length):o,f=Xf(l),u=/^(?:\.js|\.jsx|\.mjs|\.cjs)$/.test(f)?f:"";if(!u&&t.moduleSpecifierMode==="node"){let h=Xf(s.resolved);u=h===".mts"||h===".mjs"?".mjs":h===".cts"||h===".cjs"?".cjs":".js"}let d=qi(s.resolved,t);return{kind:"local",specifier:o,resolvedSource:s.resolved,declarationOutput:d,emittedSpecifier:Ig(n,d,u)+c}}}var Zf,kg=50,xr,Rg;var ua=me(()=>{rc();mn();wn();({Glob:Zf}=globalThis.Bun);xr=new Map;Rg=/[*?[\]{}!]/});var tu;var iu=me(()=>{tu=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 ru(e,t={strings:!0}){let i="",r=0;while(r<e.length){let n=e.slice(r,r+2);if(n==="//"){let s=e.indexOf(`
213
+ `,r),c=s===-1?e.length:s;i+=" ".repeat(c-r),r=c;continue}if(n==="/*"){let s=e.indexOf("*/",r+2),c=s===-1?e.length:s+2;for(let l=r;l<c;l++)i+=e[l]===`
214
+ `?`
215
+ `:" ";r=c;continue}let o=e[r];if(t.strings&&(o==='"'||o==="'"||o==="`")){let s=o;i+=" ",r++;while(r<e.length){if(e[r]==="\\"){i+=" ",r+=2;continue}if(e[r]===s){i+=" ",r++;break}i+=e[r]===`
216
+ `?`
217
+ `:" ",r++}continue}i+=o,r++}return i}function Fg(e){let t=new Set,i=[/\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 r of i)for(let n of e.matchAll(r))t.add(n[1]);return t}function Wg(e){let t=new Set;for(let i of e.matchAll(/\bimport\s+(?:type\s+)?([\s\S]*?)\s+from\s*['"`]/g)){let r=i[1],n=/\*\s*as\s+([A-Za-z_$][\w$]*)/.exec(r);if(n)t.add(n[1]);let o=r.split("{")[0].replace(/\*\s*as\s+[A-Za-z_$][\w$]*/,"");for(let c of o.split(",")){let l=c.trim();if(/^[A-Za-z_$][\w$]*$/.test(l))t.add(l)}let s=/\{([\s\S]*?)\}/.exec(r);if(s)for(let c of s[1].split(",")){let l=c.trim().replace(/^type\s+/,"");if(!l)continue;let f=/\bas\s+([A-Za-z_$][\w$]*)$/.exec(l);t.add(f?f[1]:l.split(/\s+/)[0])}}for(let i of e.matchAll(/\bimport\s*\(\s*['"`][^'"`]*['"`]\s*\)\s*\.\s*([A-Za-z_$][\w$]*)/g))t.add(i[1]);return t}function Lg(e){let t=new Set,i=(n)=>{for(let o of n.split(",")){let s=o.trim().split(/\s+|=/)[0]?.trim();if(s&&/^[A-Za-z_$][\w$]*$/.test(s))t.add(s)}},r=/\b(?:type|interface|class|function)\s+[A-Za-z_$][\w$]*\s*<([^<>]*(?:<[^<>]*>[^<>]*)*)>/g;for(let n of e.matchAll(r))i(n[1]);for(let n of e.matchAll(/(?:\b[A-Za-z_$][\w$]*)?\s*<([^<>()]*)>\s*\(/g))i(n[1]);for(let n of e.matchAll(/\binfer\s+([A-Za-z_$][\w$]*)/g))t.add(n[1]);for(let n of e.matchAll(/\[\s*([A-Za-z_$][\w$]*)\s+in\b/g))t.add(n[1]);return t}function Bg(e){let t=new Map,i=(n)=>{let o=1;for(let s=0;s<n&&s<e.length;s++)if(e.charCodeAt(s)===10)o++;return o},r=(n,o,s)=>{for(let c of n.matchAll(/\b([A-Z][\w$]*)\b/g)){let l=c[1];if(t.has(l))continue;let f=n.slice(c.index+l.length);if(/^\s*\??:/.test(f))continue;t.set(l,{line:i(o),context:s.trim().slice(0,120)})}};for(let n of e.matchAll(/\btype\s+[A-Za-z_$][\w$]*\s*(?:<[^=]*?>)?\s*=([^;]*)/g))r(n[1],n.index+n[0].indexOf("="),n[0]);for(let n of e.matchAll(/\b(?:extends|implements)\s+([^{;]*)/g))r(n[1],n.index,n[0]);for(let n of e.matchAll(/:\s*([^;,){}\n=]+)/g))r(n[1],n.index,n[0]);for(let n of e.matchAll(/<([^<>()]*)>/g))r(n[1],n.index,n[0]);return t}function nu(e){let t=ru(e),i=ru(e,{strings:!1}),r=new Set([...Fg(t),...Wg(i),...Lg(t),...tu,...Ng]),n=[];for(let[o,s]of Bg(t)){if(r.has(o))continue;if(new RegExp(`[\\w$]\\s*\\.\\s*${o}\\b`).test(t))continue;n.push({name:o,line:s.line,context:s.context})}return n.sort((o,s)=>o.line-s.line||o.name.localeCompare(s.name))}var Ng;var ou=me(()=>{iu();Ng=new Set(["This","True","False","Null","Undefined","Void","Never","Any","Unknown","Object","Infinity","NaN"])});function si(e,t){let i=1,r=1;for(let n=0;n<t;n++)if(e.charCodeAt(n)===10)i++,r=1;else r++;return{line:i,column:r}}function au(e){let t=[],i=[],r=[],n={")":"(","]":"[","}":"{"},o=0,s=0,c=-1;for(let f=0;f<e.length;f++){let u=e.charCodeAt(f),d=e.charCodeAt(f+1);if(c!==-1){if(u===42&&d===47)i.push({start:c,end:f+2}),c=-1,f++;continue}if(o){if(u===92)f++;else if(u===o)i.push({start:s,end:f+1}),o=0;continue}if(u===47&&d===42){c=f,f++;continue}if(u===47&&d===47){let p=f;while(f<e.length&&e.charCodeAt(f)!==10)f++;i.push({start:p,end:f});continue}if(u===39||u===34||u===96){o=u,s=f;continue}let h=e[f];if(h==="("||h==="["||h==="{")r.push({char:h,offset:f});else if(n[h]){let p=r.pop();if(!p||p.char!==n[h])t.push({...si(e,f),message:`Unexpected closing delimiter ${h}`,code:"DTSX1004"})}}if(o)t.push({...si(e,s),message:"Unterminated string literal",code:"DTSX1002"});if(c!==-1)t.push({...si(e,c),message:"Unterminated block comment",code:"DTSX1003"});for(let f of r)t.push({...si(e,f.offset),message:`Unclosed delimiter ${f.char}`,code:"DTSX1001"});let l=[[/\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 l)for(let d of e.matchAll(f)){if(i.some((h)=>d.index>=h.start&&d.index<h.end))continue;t.push({...si(e,d.index),message:u,code:"DTSX1005"})}for(let f of e.matchAll(/\btype\s*(?=[{=])/g)){if(i.some((d)=>f.index>=d.start&&f.index<d.end))continue;let u=e.slice(0,f.index).trimEnd();if(u.endsWith("import")||u.endsWith("export"))continue;t.push({...si(e,f.index),message:"Declaration name expected",code:"DTSX1005"})}return t.push(...Gg(e,i)),t.sort((f,u)=>f.line-u.line||f.column-u.column)}function Gg(e,t){let i=[],r=(n)=>t.some((o)=>n>=o.start&&n<o.end);for(let n of e.matchAll(/\b(import|export)\s+(?:type\s+)?\{/g)){let o=n.index;if(r(o))continue;let s=o+n[0].length-1,c=-1;for(let u=s+1;u<e.length;u++){if(r(u))continue;let d=e[u];if(d==="{"){c=-2;break}if(d==="}"){c=u;break}}if(c<0)continue;let l=e.slice(s+1,c);if(!l.trim())continue;let f=s+1;for(let u of l.split(",")){let d=u.trim();if(d){let h=f+u.indexOf(d);if(d.includes(";"))i.push({...si(e,h),message:`Unexpected ';' in ${n[1]} clause \u2014 specifiers are separated by ','`,code:"DTSX1006"});else if(!jg.test(d))i.push({...si(e,h),message:`Invalid ${n[1]} specifier '${d}'`,code:"DTSX1006"})}f+=u.length+1}}return i}var su,jg;var lu=me(()=>{su=String.raw`(?:[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*|'[^']*'|"[^"]*")`,jg=new RegExp(`^(?:type\\s+)?${su}(?:\\s+as\\s+${su})?$`,"u")});import _g from"process";import{join as mv,resolve as Vg}from"path";function da(){return`${String.fromCharCode(47,47,35)} sourceMappingURL=`}async function io(e,t,i="lf"){let r=t.replace(/\r\n/g,`
218
+ `);if(!r.endsWith(`
219
+ `))r+=`
220
+ `;if(i==="crlf")r=r.replace(/\n/g,`\r
221
+ `);if(await za(e,r)!==Buffer.byteLength(r,"utf8"))throw Error(`Incomplete declaration write: ${e}`)}async function cu(e){try{let t=e?.cwd||_g.cwd();return(await hr(Vg(t,e?.tsconfigPath||"tsconfig.json"),{allowCircular:!0}))?.isolatedDeclarations??!1}catch{return!1}}function fu(e,t){let i={isValid:!0,errors:[]};for(let r of au(e))i.errors.push({line:r.line,column:r.column,message:r.message,code:r.code});for(let r of nu(e))i.errors.push({line:r.line,column:1,message:`'${r.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: ${r.context}`,code:"dangling-type-reference"});return i.isValid=i.errors.length===0,i}function uu(e,t,i){if(e===t)return"";let r=e.split(`
222
+ `),n=t.split(`
223
+ `),o=new Map,s=new Map;for(let u=0;u<r.length;u++)o.set(r[u],(o.get(r[u])??0)+1);for(let u=0;u<n.length;u++)s.set(n[u],(s.get(n[u])??0)+1);let c=[],l=[];for(let[u,d]of o){let h=d-(s.get(u)??0);for(let p=0;p<h;p++)c.push(u)}for(let[u,d]of s){let h=d-(o.get(u)??0);for(let p=0;p<h;p++)l.push(u)}if(c.length===0&&l.length===0)return"";let f=[`--- ${i}`,`+++ ${i}`];for(let u=0;u<c.length;u++)f.push(`- ${c[u]}`);for(let u=0;u<l.length;u++)f.push(`+ ${l[u]}`);return f.join(`
224
+ `)}function du(e,t,i,r){let n=e.split(`
225
+ `),o=[];function s(d){let h="",p=d<0?-d<<1|1:d<<1;do{let m=p&31;if(p>>>=5,p>0)m|=32;h+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[m]}while(p>0);return h}let c=0,l=0,f=0,u=r.split(`
226
+ `).length;for(let d=0;d<n.length;d++){if(n[d].trim()===""){o.push("");continue}c=0;let h=Math.min(d,u-1),p=[],m=0-c,a=0,C=h-l,b=0-f;p.push(s(m)+s(a)+s(C)+s(b)),c=0,l=h,f=0,o.push(p.join(","))}return{version:3,file:t,sourceRoot:"",sources:[i],sourcesContent:[r],mappings:o.join(";")}}function hu(e,t){return`${e}
227
+ ${da()}${t}
228
+ `}var ha=me(()=>{Qi();ou();lu();ms()});import{chmod as Ug,lstat as ya,mkdir as ro,readdir as Kg,realpath as zg,rename as pa,rm as pu,rmdir as Hg,stat as mu,writeFile as qg}from"fs/promises";import{basename as Jg,dirname as Tr,isAbsolute as yu,parse as Yg,relative as gu,resolve as ct}from"path";function li(e,t){return e instanceof Error&&"code"in e&&e.code===t}async function ai(e){try{return await ya(e)}catch(t){if(li(t,"ENOENT"))return;throw t}}async function Ji(e){let t=ct(e);try{return await zg(t)}catch(i){if(!li(i,"ENOENT")||Tr(t)===t)throw i;return ct(await Ji(Tr(t)),Jg(t))}}async function Ca(e){let t=ct(e.cwd,e.outdir);if(e.bundle&&e.bundleOutput){if(yu(e.bundleOutput))throw Error("bundleOutput must be relative to outdir");if(!Bt(ct(t,e.bundleOutput),t))throw Error("bundleOutput must stay within outdir")}if(!e.clean||e.dryRun)return;if(t===Yg(t).root)throw Error("Refusing to clean declarations from the filesystem root");let[i,r]=await Promise.all([Ji(t),Ji(ct(e.cwd,e.root))]);if(Bt(r,i))throw Error("Refusing to clean an outdir that contains the source root")}function wu(e){return[".d.ts",".d.mts",".d.cts",".d.ts.map",".d.mts.map",".d.cts.map"].some((t)=>e.endsWith(t))}function ma(e,t){return e.dev===t.dev&&e.ino===t.ino}async function wa(e,t){try{if(!(await mu(e)).isDirectory())throw Error(`Declaration output parent is not a directory: ${e}`);return}catch(r){if(!li(r,"ENOENT"))throw r}let i=Tr(e);if(i===e)throw Error(`Cannot create declaration output directory: ${e}`);await wa(i,t);try{await ro(e),t.push(e)}catch(r){if(!li(r,"EEXIST")||!(await mu(e)).isDirectory())throw r}}async function Cu(e,t,i){for(let r of(await Kg(e,{withFileTypes:!0})).sort((n,o)=>n.name.localeCompare(o.name))){let n=ct(e,r.name);if(n===t)continue;if(r.isDirectory())await Cu(n,t,i);else if(wu(r.name)){let o=await ai(n);if(!o)throw Error(`Declaration output changed during inventory: ${n}`);i.set(n,o)}}}function ga(e,t,i,r,n){return Object.assign(AggregateError(t,e),{code:"DTSX_PUBLICATION_FAILED",phase:i,recoveryDirectory:r,outputsCommitted:n})}async function vu(e,t){if(e.dryRun||t.size===0&&!e.clean)return;await Ca(e);let i=ct(e.cwd,e.outdir);if(t.size===0&&!await ai(i))return;let r=ct(i,".dtsx-publication"),n=new Map;for(let[m,a]of t){let C=ct(m);if(!yu(m)||C===i||!Bt(C,i)||Bt(C,r)||!wu(C))throw Error(`Invalid declaration publication target: ${m}`);if(n.has(C))throw Error(`Duplicate declaration publication target: ${m}`);n.set(C,a)}let o=[],s=[],c=[],l=!1,f,u,d=!1;async function h(m,a){let C=await Ji(Tr(m));if(!Bt(C,a))throw Error(`Declaration publication parent escapes outdir: ${m}`);if(Bt(C,ct(a,".dtsx-publication")))throw Error(`Declaration publication target overlaps its transaction directory: ${m}`)}async function p(){if(!l)return;if(!f)throw Error(`Cannot verify declaration publication ownership: ${r}`);let m=await ai(r);if(!m||!ma(m,f))throw Error(`Declaration publication ownership changed: ${r}`);if(u&&await Ji(r)!==ct(u,".dtsx-publication"))throw Error(`Declaration publication location changed: ${r}`);await pu(r,{recursive:!0})}try{await wa(i,o);try{await ro(r)}catch(C){if(li(C,"EEXIST"))throw Error(`Declaration publication is active or requires recovery at ${r}`,{cause:C});throw C}l=!0,f=await ya(r),u=await Ji(i);let m=new Map;if(e.clean)await Cu(i,r,m);for(let C of n.keys()){await h(C,u);let b=await ai(C);if(b&&!b.isFile())throw Error(`Declaration publication target is not a regular file: ${C}`);if(b)m.set(C,b)}for(let C of m.keys())await h(C,u);await ro(ct(r,"staged")),await ro(ct(r,"backups"));let a=new Map;for(let C of new Set([...m.keys(),...n.keys()])){let b=a.size.toString();a.set(C,{path:C,existing:m.get(C),backup:ct(r,"backups",b),staged:n.has(C)?ct(r,"staged",b):void 0})}await qg(ct(r,"manifest.json"),JSON.stringify({version:1,outdir:i,targets:[...a.values()].map((C)=>({path:gu(i,C.path),backup:gu(r,C.backup),hadPrevious:!!C.existing}))}));for(let[C,b]of n){let v=a.get(C),T=v.staged;if(await io(T,b.content,b.lineEnding),!e.clean&&v.existing)await Ug(T,v.existing.mode&511);v.stagedIdentity=await ya(T)}for(let C of a.values()){if(!C.existing)continue;await h(C.path,u);let b=await ai(C.path);if(!b||!ma(b,C.existing))throw Error(`Declaration output changed before commit: ${C.path}`);await pa(C.path,C.backup),s.push(C)}for(let C of a.values()){if(!C.staged||!C.stagedIdentity)continue;if(await h(C.path,u),await wa(Tr(C.path),o),await h(C.path,u),await ai(C.path))throw Error(`Declaration output appeared during commit: ${C.path}`);await pa(C.staged,C.path),c.push({path:C.path,identity:C.stagedIdentity})}d=!0;try{await p()}catch(C){throw ga(`Declaration outputs committed, but transaction cleanup failed at ${r}`,[C],"finalize",r,!0)}}catch(m){if(d)throw m;let a=[];for(let b of c.toReversed())try{if(u)await h(b.path,u);let v=await ai(b.path);if(!v)continue;if(!ma(v,b.identity))throw Error(`Installed declaration changed before rollback: ${b.path}`);await pu(b.path)}catch(v){a.push(v)}for(let b of s.toReversed())try{if(u)await h(b.path,u);if(await ai(b.path))throw Error(`Cannot restore declaration over an existing path: ${b.path}`);await pa(b.backup,b.path)}catch(v){a.push(v)}if(a.length>0)throw ga(`Declaration rollback failed; recovery data retained at ${r}`,[m,...a],"rollback",r,!1);let C=[];try{await p()}catch(b){C.push(b)}for(let b of o.toReversed())try{await Hg(b)}catch(v){if(!li(v,"ENOENT")&&!li(v,"ENOTEMPTY")&&!li(v,"EEXIST"))C.push(v)}if(C.length>0)throw ga(`Prior declarations retained, but publication cleanup failed at ${r}`,[m,...C],"cleanup",l?r:void 0,!1);throw m}}var bu=me(()=>{ua();ha()});function $u(e,t,i){let r={file:t,message:"Unknown error",code:kr.UNKNOWN_ERROR};if(e instanceof Error){r.message=e.message,r.stack=e.stack;let n=e.message.match(/\((\d+),(\d+)\)/);if(n)r.location={line:Number.parseInt(n[1],10),column:Number.parseInt(n[2],10)};if(e.message.includes("Cannot find")||e.message.includes("not found"))r.code=kr.FILE_NOT_FOUND,r.suggestion="Check that the file path is correct and the file exists.";else if(e.message.includes("syntax")||e.message.includes("Unexpected token"))r.code=kr.SYNTAX_ERROR,r.suggestion="Check for syntax errors in your TypeScript code.";else if(e.message.includes("type")&&e.message.includes("cannot"))r.code=kr.TYPE_INFERENCE_ERROR,r.suggestion="Add explicit type annotations to help with type inference.";else if(e.message.includes("parse")||e.message.includes("Parse"))r.code=kr.PARSE_ERROR,r.suggestion="The file contains invalid TypeScript syntax."}else if(typeof e==="string")r.message=e;return r}function Eu(e,t){let i=[],r=e.file;if(e.location)r+=`:${e.location.line}:${e.location.column}`;if(e.code)r+=` [${e.code}]`;if(i.push(r),i.push(` Error: ${e.message}`),t&&e.location){i.push("");let n=t.split(`
229
+ `),o=e.location.line-1;if(o>=0&&o<n.length){let s=Math.max(0,o-1),c=Math.min(n.length-1,o+1);for(let l=s;l<=c;l++){let f=(l+1).toString().padStart(4," "),u=l===o?">":" ";if(i.push(` ${u} ${f} | ${n[l]}`),l===o&&e.location.column>0){let d=" ".repeat(10+e.location.column-1);i.push(` ${d}^`)}}}}if(e.suggestion)i.push(""),i.push(` Suggestion: ${e.suggestion}`);return i.join(`
230
+ `)}var kr;var Su=me(()=>{kr={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"}});async function Xg(){if(no!==null)return no;try{return ci=await import("prettier"),no=!0,!0}catch{return no=!1,!1}}async function Zg(e,t){if(!ci)return null;try{if(t&&ci.resolveConfig){let i=await ci.resolveConfig(t);if(i)return i}if(e&&ci.resolveConfig){let i=await ci.resolveConfig(e);if(i)return i}return null}catch{return null}}async function Qg(e,t){if(!ci)throw Error("Prettier is not available");let i={...t,parser:t.parser||"typescript"};return ci.format(e,i)}function ey(e,t={}){let{indentSize:i=2,useTabs:r=!1,maxLineWidth:n=100,trailingNewline:o=!0,normalizeWhitespace:s=!0,sortImports:c=!0,groupImports:l=!0}=t,f=e,u=r?"\t":" ".repeat(i);if(f.indexOf(`\r
163
231
  `)!==-1)f=f.replace(/\r\n/g,`
164
232
  `);if(s){if(/[ \t]\n/.test(f)||/[ \t]$/.test(f))f=f.replace(/[ \t]+$/gm,"");if(f.indexOf(`
165
233
 
166
234
 
167
235
  `)!==-1)f=f.replace(/\n{3,}/g,`
168
236
 
169
- `);f=rm(f,u)}if(a||c)f=im(f,{sort:a,group:c});if(i>0)f=om(f,i,u);if(o&&!f.endsWith(`
237
+ `);f=ty(f,u)}if(c||l)f=iy(f,{sort:c,group:l});if(n>0)f=ny(f,n,u);if(o&&!f.endsWith(`
170
238
  `))f+=`
171
- `;return f}function rm(e,t){let r=e.split(`
172
- `),n=[];for(let i of r){let o=i.match(/^(\s*)(.*)$/);if(!o){n.push(i);continue}let[,s,a]=o;if(!a){n.push("");continue}let c=s.replace(/\t/g," ").length,f=Math.floor(c/2);n.push(t.repeat(f)+a)}return n.join(`
173
- `)}function im(e,t){let r=e.split(`
174
- `),n=[],i=[],o=!1,s=0;for(let c=0;c<r.length;c++){let f=r[c],u=f.match(/^(import\s+(?:type\s+)?.*from\s+['"])([^'"]+)(['"].*)$/);if(u){o=!0,s=c;let h=u[1];n.push({line:f,source:u[2],isType:h.startsWith("import type ")||h.startsWith("import type\t")})}else if(o&&f.trim()==="")continue;else{if(o)o=!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 nm(c.source,f.source)});let a;if(t.group){let c=[],f=[],u=[],h=[],l=[];for(let y=0;y<n.length;y++){let C=n[y],S=C.source;if(S.charCodeAt(0)===46)l.push(C);else if(S.startsWith("node:"))c.push(C);else if(S.charCodeAt(0)===64)h.push(C);else if(S.includes("/"))u.push(C);else f.push(C)}a=[...c.map((y)=>y.line),...c.length>0&&f.length>0?[""]:[],...f.map((y)=>y.line),...(c.length>0||f.length>0)&&u.length>0?[""]:[],...u.map((y)=>y.line),...h.length>0&&(c.length>0||f.length>0||u.length>0)?[""]:[],...h.map((y)=>y.line),...l.length>0?[""]:[],...l.map((y)=>y.line)]}else a=n.map((c)=>c.line);return[...a,"",...i].join(`
175
- `)}function nm(e,t){let r=e.startsWith("node:"),n=t.startsWith("node:");if(r!==n)return r?-1:1;let i=e.startsWith("."),o=t.startsWith(".");if(i!==o)return i?1:-1;return e.localeCompare(t)}function om(e,t,r){let n=e.split(`
176
- `),i=[];for(let o of n){if(o.length<=t){i.push(o);continue}if(o.trimStart().startsWith("import ")){i.push(o);continue}let s=o.match(/^(\s*)/)?.[1]||"",a=s+r,c=am(o,s,a);if(c){i.push(...c);continue}if(o.includes("{")&&o.includes("}")){let f=lm(o,t,s,a);i.push(...f);continue}if(o.includes(" | ")){let f=cm(o,t,s,a);i.push(...f);continue}i.push(o)}return i.join(`
177
- `)}function am(e,t,r){let n=e.match(sm);if(!n)return null;let[,i,o,s,a]=n,c=s.split(",").map((h)=>h.trim()).filter(Boolean);if(c.length<=1)return[e];let f=`${t}${i}${o??""} {`,u=a?`${t}} ${a};`:`${t}};`;return[f,...c.map((h)=>`${r}${h},`),u]}function lm(e,t,r,n){let i=e.match(/^(\s*)(.*?)(\{)(.+)(\}.*)$/);if(!i)return[e];let[,,o,s,a,c]=i,f=a.split(/;\s*|,\s*/).filter((u)=>u.trim());if(f.length<=1)return[e];return[`${r}${o}${s}`,...f.map((u)=>`${n}${u.trim()};`),`${r}${c.trim()}`]}function cm(e,t,r,n){let i=e.match(/^(\s*)(.*?=\s*)(.+)$/);if(!i)return[e];let[,,o,s]=i,a=s.split(/\s*\|\s*/).filter((c)=>c.trim());if(a.length<=2)return[e];return[`${r}${o}`,...a.map((c,f)=>`${n}${f>0?"| ":" "}${c.trim()}`)]}async function tc(e,t={},r){let n=[];if(t.usePrettier!==!1){if(await Xd())try{let i={...await Qd(t.prettierConfigPath,r),...t.prettierOptions,parser:"typescript"};return{content:await em(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:tm(e,t.builtIn),usedPrettier:!1,warnings:n.length>0?n:void 0}}var Hi=null,Ft=null,sm;var rc=he(()=>{sm=/^\s*(export|import)(\s+type)?\s*\{([^{}]*)\}\s*(from\s*(?:'[^']*'|"[^"]*")(?:\s*(?:with|assert)\s*\{[^{}]*\})?)?\s*;?\s*$/});class zi{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)},o=await n.onBeforeFile(i);if(typeof o==="string")r=o}return r}async runOnDeclarations(e,t,r){let n=r;for(let i of this.plugins)if(i.onDeclarations){let o={filePath:e,sourceCode:t,declarations:n,config:this.config,log:this.createLogger(i.name)},s=await i.onDeclarations(o);if(s)n=s}return n}async runOnAfterFile(e,t,r){let n=r;for(let i of this.plugins)if(i.onAfterFile){let o={filePath:e,sourceCode:t,content:n,config:this.config,log:this.createLogger(i.name)},s=await i.onAfterFile(o);if(typeof s==="string")n=s}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 fm(e){return e}var M0,D0;var ic=he(()=>{M0=new zi;D0=fm({name:"strip-internal",version:"1.0.0",description:"Removes declarations marked with @internal",onDeclarations:(e)=>e.declarations.filter((t)=>{if(t.leadingComments){if(t.leadingComments.some((r)=>r.includes("@internal")))return e.log.debug(`Stripping internal declaration: ${t.name}`),!1}return!0})})});function sc(e,t={}){let{lineEnding:r="lf",trailingNewline:n=!0,maxBlankLines:i=1,trimTrailingWhitespace:o=!0,normalizeIndentation:s=!0,indent:a={style:"spaces",size:2},declarationOrder:c,importGrouping:f,preserveComments:u=!0,insertFinalNewline:h=!0}=t,l=e;if(l=dm(l,r),f?.enabled!==!1)l=Cm(l,f||{});if(c)l=wm(l,c);if(o)l=mm(l);if(l=pm(l,i),s)l=ym(l,a);if(n||h)l=gm(l);return l}function dm(e,t){let r=e;if(e.indexOf("\r")!==-1){if(e.indexOf(`\r
178
- `)!==-1)r=r.replace(/\r\n/g,`
179
- `);if(r.indexOf("\r")!==-1)r=r.replace(/\r/g,`
180
- `)}if(t==="crlf")r=r.replace(/\n/g,`\r
181
- `);return r}function mm(e){return e.split(`
239
+ `;return f}function ty(e,t){let i=e.split(`
240
+ `),r=[];for(let n of i){let o=n.match(/^(\s*)(.*)$/);if(!o){r.push(n);continue}let[,s,c]=o;if(!c){r.push("");continue}let l=s.replace(/\t/g," ").length,f=Math.floor(l/2);r.push(t.repeat(f)+c)}return r.join(`
241
+ `)}function iy(e,t){let i=e.split(`
242
+ `),r=[],n=[],o=!1,s=0;for(let l=0;l<i.length;l++){let f=i[l],u=f.match(/^(import\s+(?:type\s+)?.*from\s+['"])([^'"]+)(['"].*)$/);if(u){o=!0,s=l;let d=u[1];r.push({line:f,source:u[2],isType:d.startsWith("import type ")||d.startsWith("import type\t")})}else if(o&&f.trim()==="")continue;else{if(o)o=!1;n.push(f)}}if(r.length===0)return e;if(t.sort)r.sort((l,f)=>{if(l.isType!==f.isType)return l.isType?1:-1;return ry(l.source,f.source)});let c;if(t.group){let l=[],f=[],u=[],d=[],h=[];for(let p=0;p<r.length;p++){let m=r[p],a=m.source;if(a.charCodeAt(0)===46)h.push(m);else if(a.startsWith("node:"))l.push(m);else if(a.charCodeAt(0)===64)d.push(m);else if(a.includes("/"))u.push(m);else f.push(m)}c=[...l.map((p)=>p.line),...l.length>0&&f.length>0?[""]:[],...f.map((p)=>p.line),...(l.length>0||f.length>0)&&u.length>0?[""]:[],...u.map((p)=>p.line),...d.length>0&&(l.length>0||f.length>0||u.length>0)?[""]:[],...d.map((p)=>p.line),...h.length>0?[""]:[],...h.map((p)=>p.line)]}else c=r.map((l)=>l.line);return[...c,"",...n].join(`
243
+ `)}function ry(e,t){let i=e.startsWith("node:"),r=t.startsWith("node:");if(i!==r)return i?-1:1;let n=e.startsWith("."),o=t.startsWith(".");if(n!==o)return n?1:-1;return e.localeCompare(t)}function ny(e,t,i){let r=e.split(`
244
+ `),n=[];for(let o of r){if(o.length<=t){n.push(o);continue}if(o.trimStart().startsWith("import ")){n.push(o);continue}let s=o.match(/^(\s*)/)?.[1]||"",c=s+i,l=sy(o,s,c);if(l){n.push(...l);continue}if(o.includes("{")&&o.includes("}")){let f=ay(o,t,s,c);n.push(...f);continue}if(o.includes(" | ")){let f=ly(o,t,s,c);n.push(...f);continue}n.push(o)}return n.join(`
245
+ `)}function sy(e,t,i){let r=e.match(oy);if(!r)return null;let[,n,o,s,c]=r,l=s.split(",").map((d)=>d.trim()).filter(Boolean);if(l.length<=1)return[e];let f=`${t}${n}${o??""} {`,u=c?`${t}} ${c};`:`${t}};`;return[f,...l.map((d)=>`${i}${d},`),u]}function ay(e,t,i,r){let n=e.match(/^(\s*)(.*?)(\{)(.+)(\}.*)$/);if(!n)return[e];let[,,o,s,c,l]=n,f=c.split(/;\s*|,\s*/).filter((u)=>u.trim());if(f.length<=1)return[e];return[`${i}${o}${s}`,...f.map((u)=>`${r}${u.trim()};`),`${i}${l.trim()}`]}function ly(e,t,i,r){let n=e.match(/^(\s*)(.*?=\s*)(.+)$/);if(!n)return[e];let[,,o,s]=n,c=s.split(/\s*\|\s*/).filter((l)=>l.trim());if(c.length<=2)return[e];return[`${i}${o}`,...c.map((l,f)=>`${r}${f>0?"| ":" "}${l.trim()}`)]}async function xu(e,t={},i){let r=[];if(t.usePrettier!==!1){if(await Xg())try{let n={...await Zg(t.prettierConfigPath,i),...t.prettierOptions,parser:"typescript"};return{content:await Qg(e,n),usedPrettier:!0}}catch(n){r.push(`Prettier formatting failed: ${n}. Using built-in formatter.`)}else if(t.usePrettier===!0)r.push("Prettier requested but not available. Using built-in formatter.")}return{content:ey(e,t.builtIn),usedPrettier:!1,warnings:r.length>0?r:void 0}}var no=null,ci=null,oy;var Au=me(()=>{oy=/^\s*(export|import)(\s+type)?\s*\{([^{}]*)\}\s*(from\s*(?:'[^']*'|"[^"]*")(?:\s*(?:with|assert)\s*\{[^{}]*\})?)?\s*;?\s*$/});function Tu(e,t){let i=new Set;for(let r of ur(e,"imports.ts",!1)){if(r.kind!=="import")continue;let n=wi(r.text),o=n&&t.get(n.source);if(!n||n.isTypeOnly||!o)continue;let s=oo(o);for(let c of n.namedItems)if(!c.isTypeOnly&&s.some((l)=>l.name===c.originalName))i.add(c.name);if(n.defaultName&&s.some((c)=>c.isDefault))i.add(n.defaultName)}return i}function oo(e){let t=ur(e,"dependency.ts",!1).filter((i)=>i.kind==="function");return t.filter((i)=>i.isExported&&!i.generics&&t.filter((r)=>r.name===i.name).length===1&&zr(e,i.name)===1).map((i)=>({name:i.name,isDefault:Boolean(i.isDefault)})).sort((i,r)=>i.name.localeCompare(r.name))}var ku=me(()=>{Wo();un();Ci()});function Pu(e,t={}){let{lineEnding:i="lf",trailingNewline:r=!0,maxBlankLines:n=1,trimTrailingWhitespace:o=!0,normalizeIndentation:s=!0,indent:c={style:"spaces",size:2},declarationOrder:l,importGrouping:f,preserveComments:u=!0,insertFinalNewline:d=!0}=t,h=e;if(h=uy(h,i),f?.enabled!==!1)h=gy(h,f||{});if(l)h=yy(h,l);if(o)h=dy(h);if(h=hy(h,n),s)h=my(h,c);if(r||d)h=py(h);return h}function uy(e,t){let i=e;if(e.indexOf("\r")!==-1){if(e.indexOf(`\r
246
+ `)!==-1)i=i.replace(/\r\n/g,`
247
+ `);if(i.indexOf("\r")!==-1)i=i.replace(/\r/g,`
248
+ `)}if(t==="crlf")i=i.replace(/\n/g,`\r
249
+ `);return i}function dy(e){return e.split(`
182
250
  `).map((t)=>t.replace(/[\t ]+$/,"")).join(`
183
- `)}function pm(e,t){let r=new RegExp(`\\n{${t+2},}`,"g");return e.replace(r,`
184
- `.repeat(t+1))}function gm(e){return`${e.replace(/\s+$/,"")}
185
- `}function ym(e,t){let{style:r="spaces",size:n=2}=t,i=r==="tabs"?"\t":" ".repeat(n),o=e.split(`
186
- `),s=[];for(let a of o){let c=a.match(/^([\t ]*)(.*)$/);if(!c){s.push(a);continue}let[,f,u]=c;if(!u){s.push("");continue}let h=f.replace(/\t/g," "),l=Math.floor(h.length/2);s.push(i.repeat(l)+u)}return s.join(`
187
- `)}function Cm(e,t){let{groups:r=hm,separateGroups:n=!0,alphabetize:i=!0}=t,o=e.split(`
188
- `),s=[],a=[],c=-1;for(let C=0;C<o.length;C++){let S=o[C],x=nc(S);if(x)s.push({line:S,source:x.source,group:x.group,isType:x.isType}),c=C;else if(s.length>0&&S.trim()==="")continue;else if(s.length>0||S.trim()!==""){if(s.length===0||C>c+1)a.push(S)}}if(s.length===0)return e;let f=new Map;for(let C of r)f.set(C,[]);for(let C of s)(f.get(C.group)||f.get("external")||[]).push(C);if(i)for(let[,C]of f)C.sort((S,x)=>{if(S.isType!==x.isType)return S.isType?1:-1;return S.source.localeCompare(x.source)});let u=[],h=null;for(let C of r){let S=f.get(C)||[];if(S.length===0)continue;if(n&&h!==null)u.push("");for(let x of S)u.push(x.line);h=C}let l=o.slice(0,o.findIndex((C)=>nc(C)!==null)),y=a;while(y.length>0&&y[0].trim()==="")y.shift();return[...l,...u,"",...y].join(`
189
- `)}function nc(e){let t=e.trim(),r=t.match(/^import\s+(type\s+)?.*from\s+['"]([^'"]+)['"]/);if(!r){let o=t.match(/^import\s+['"]([^'"]+)['"]/);if(o)return{source:o[1],group:oc(o[1]),isType:!1};return null}let n=!!r[1],i=r[2];return{source:i,group:n?"type":oc(i),isType:n}}function oc(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 wm(e,t){let{kinds:r=um,alphabetize:n=!1,groupExports:i=!0}=t,o=e.split(`
190
- `),s=[],a=[],c=[],f=null,u=0,h=!0,l=!1,y=[];for(let x=0;x<o.length;x++){let v=o[x],G=v.trim(),L=u,P=G.startsWith("///"),F=L===0&&!P&&(G.startsWith("//")||G.startsWith("/*"));if(l||F){if(y.push(v),!l&&G.startsWith("/*")&&!G.includes("*/"))l=!0;else if(l&&G.includes("*/"))l=!1;continue}if(L===0&&y.length>0&&G===""){y.push(v);continue}u+=(v.match(/\{/g)||[]).length,u-=(v.match(/\}/g)||[]).length;let I=vm(G);if(h&&I&&I.kind!=="import"&&!G.startsWith("//")&&!G.startsWith("/*"))h=!1;if(h){if(y.length>0){if(I?.kind==="import"||!I)a.push(...y),y.length=0}a.push(v);continue}if(I&&u<=1){if(f)s.push(f);f={lines:y.length>0?[...y,v]:[v],kind:I.kind,name:I.name,isExport:I.isExport},y.length=0}else if(f)f.lines.push(v);else{if(G==="")continue;c.push(v)}}if(f)s.push(f);if(y.length>0)c.push(...y);s.sort((x,v)=>{if(i&&x.isExport!==v.isExport)return x.isExport?-1:1;let G=r.indexOf(x.kind),L=r.indexOf(v.kind),P=G>=0?G:r.length,F=L>=0?L:r.length;if(P!==F)return P-F;if(n)return x.name.localeCompare(v.name);return 0});let C=[...a],S=null;for(let x of s){if(S!==null&&x.kind!==S)C.push("");C.push(...x.lines),S=x.kind}if(c.length>0)C.push(""),C.push(...c);return C.join(`
191
- `)}function vm(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 um,hm;var ac=he(()=>{um=["import","type","interface","enum","class","function","variable","export","module","namespace","unknown"],hm=["builtin","external","scoped","internal","parent","sibling","index","type"]});function Am(e){switch(e){case"strict":return Em;case"readonly":return Sm;case"simplified":return $m;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 cc{rules;compiled=[];cache=new Map;constructor(e={rules:[]}){if(this.rules=[],e.includeDefaults!==!1)this.rules.push(...bm);if(e.presets)for(let t of e.presets)this.rules.push(...Am(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(xm,"\\$&"),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,o=null;for(let s=0;s<this.compiled.length;s++){let{rule:a,regex:c}=this.compiled[s];if(a.condition){if(!o)o={type:e,...t};if(!a.condition(o))continue}if(c.lastIndex=0,c.test(i)){if(c.lastIndex=0,i=i.replace(c,a.replacement),c.lastIndex=0,!a.global)break}}if(this.cache.size>=lc){let s=Math.ceil(lc*0.1),a=0;for(let c of this.cache.keys()){if(a++>=s)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 Ji(e={rules:[]}){return new cc(e)}function fc(e,t,r={}){return e.replace(/:\s*([^;,)\]}]+)/g,(n,i)=>`: ${t.map(i.trim(),r)}`)}var bm,Em,Sm,$m,xm,lc=2048,N0,L0;var uc=he(()=>{bm=[{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}],Em=[{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}],Sm=[{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}],$m=[{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}];xm=/[.*+?^${}()|[\]\\]/g;N0=Ji({rules:[]}),L0=Ji({rules:[],presets:["strict"]})});var hc;var dc=he(()=>{hc=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 mc(e,t={strings:!0}){let r="",n=0;while(n<e.length){let i=e.slice(n,n+2);if(i==="//"){let s=e.indexOf(`
192
- `,n),a=s===-1?e.length:s;r+=" ".repeat(a-n),n=a;continue}if(i==="/*"){let s=e.indexOf("*/",n+2),a=s===-1?e.length:s+2;for(let c=n;c<a;c++)r+=e[c]===`
193
- `?`
194
- `:" ";n=a;continue}let o=e[n];if(t.strings&&(o==='"'||o==="'"||o==="`")){let s=o;r+=" ",n++;while(n<e.length){if(e[n]==="\\"){r+=" ",n+=2;continue}if(e[n]===s){r+=" ",n++;break}r+=e[n]===`
195
- `?`
196
- `:" ",n++}continue}r+=o,n++}return r}function Om(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 Rm(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 o=n.split("{")[0].replace(/\*\s*as\s+[A-Za-z_$][\w$]*/,"");for(let a of o.split(",")){let c=a.trim();if(/^[A-Za-z_$][\w$]*$/.test(c))t.add(c)}let s=/\{([\s\S]*?)\}/.exec(n);if(s)for(let a of s[1].split(",")){let c=a.trim().replace(/^type\s+/,"");if(!c)continue;let f=/\bas\s+([A-Za-z_$][\w$]*)$/.exec(c);t.add(f?f[1]:c.split(/\s+/)[0])}}for(let r of e.matchAll(/\bimport\s*\(\s*['"`][^'"`]*['"`]\s*\)\s*\.\s*([A-Za-z_$][\w$]*)/g))t.add(r[1]);return t}function Pm(e){let t=new Set,r=(i)=>{for(let o of i.split(",")){let s=o.trim().split(/\s+|=/)[0]?.trim();if(s&&/^[A-Za-z_$][\w$]*$/.test(s))t.add(s)}},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 km(e){let t=new Map,r=(i)=>{let o=1;for(let s=0;s<i&&s<e.length;s++)if(e.charCodeAt(s)===10)o++;return o},n=(i,o,s)=>{for(let a of i.matchAll(/\b([A-Z][\w$]*)\b/g)){let c=a[1];if(t.has(c))continue;let f=i.slice(a.index+c.length);if(/^\s*\??:/.test(f))continue;t.set(c,{line:r(o),context:s.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 pc(e){let t=mc(e),r=mc(e,{strings:!1}),n=new Set([...Om(t),...Rm(r),...Pm(t),...hc,...Tm]),i=[];for(let[o,s]of km(t)){if(n.has(o))continue;if(new RegExp(`[\\w$]\\s*\\.\\s*${o}\\b`).test(t))continue;i.push({name:o,line:s.line,context:s.context})}return i.sort((o,s)=>o.line-s.line||o.name.localeCompare(s.name))}var Tm;var gc=he(()=>{dc();Tm=new Set(["This","True","False","Null","Undefined","Void","Never","Any","Unknown","Object","Infinity","NaN"])});function Nt(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 Cc(e){let t=[],r=[],n=[],i={")":"(","]":"[","}":"{"},o=0,s=0,a=-1;for(let f=0;f<e.length;f++){let u=e.charCodeAt(f),h=e.charCodeAt(f+1);if(a!==-1){if(u===42&&h===47)r.push({start:a,end:f+2}),a=-1,f++;continue}if(o){if(u===92)f++;else if(u===o)r.push({start:s,end:f+1}),o=0;continue}if(u===47&&h===42){a=f,f++;continue}if(u===47&&h===47){let y=f;while(f<e.length&&e.charCodeAt(f)!==10)f++;r.push({start:y,end:f});continue}if(u===39||u===34||u===96){o=u,s=f;continue}let l=e[f];if(l==="("||l==="["||l==="{")n.push({char:l,offset:f});else if(i[l]){let y=n.pop();if(!y||y.char!==i[l])t.push({...Nt(e,f),message:`Unexpected closing delimiter ${l}`,code:"DTSX1004"})}}if(o)t.push({...Nt(e,s),message:"Unterminated string literal",code:"DTSX1002"});if(a!==-1)t.push({...Nt(e,a),message:"Unterminated block comment",code:"DTSX1003"});for(let f of n)t.push({...Nt(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 h of e.matchAll(f)){if(r.some((l)=>h.index>=l.start&&h.index<l.end))continue;t.push({...Nt(e,h.index),message:u,code:"DTSX1005"})}for(let f of e.matchAll(/\btype\s*(?=[{=])/g)){if(r.some((h)=>f.index>=h.start&&f.index<h.end))continue;let u=e.slice(0,f.index).trimEnd();if(u.endsWith("import")||u.endsWith("export"))continue;t.push({...Nt(e,f.index),message:"Declaration name expected",code:"DTSX1005"})}return t.push(...Dm(e,r)),t.sort((f,u)=>f.line-u.line||f.column-u.column)}function Dm(e,t){let r=[],n=(i)=>t.some((o)=>i>=o.start&&i<o.end);for(let i of e.matchAll(/\b(import|export)\s+(?:type\s+)?\{/g)){let o=i.index;if(n(o))continue;let s=o+i[0].length-1,a=-1;for(let u=s+1;u<e.length;u++){if(n(u))continue;let h=e[u];if(h==="{"){a=-2;break}if(h==="}"){a=u;break}}if(a<0)continue;let c=e.slice(s+1,a);if(!c.trim())continue;let f=s+1;for(let u of c.split(",")){let h=u.trim();if(h){let l=f+u.indexOf(h);if(h.includes(";"))r.push({...Nt(e,l),message:`Unexpected ';' in ${i[1]} clause \u2014 specifiers are separated by ','`,code:"DTSX1006"});else if(!Mm.test(h))r.push({...Nt(e,l),message:`Invalid ${i[1]} specifier '${h}'`,code:"DTSX1006"})}f+=u.length+1}}return r}var yc,Mm;var wc=he(()=>{yc=String.raw`(?:[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*|'[^']*'|"[^"]*")`,Mm=new RegExp(`^(?:type\\s+)?${yc}(?:\\s+as\\s+${yc})?$`,"u")});import{join as J0,resolve as Im}from"path";import Fm from"process";function Vo(){return`${String.fromCharCode(47,47,35)} sourceMappingURL=`}async function qi(e,t,r="lf"){let n=t.replace(/\r\n/g,`
197
- `);if(!n.endsWith(`
198
- `))n+=`
199
- `;if(r==="crlf")n=n.replace(/\n/g,`\r
200
- `);await ds(e,n)}async function vc(e){try{let t=e?.cwd||Fm.cwd();return(await Cr(Im(t,e?.tsconfigPath||"tsconfig.json"),{allowCircular:!0}))?.isolatedDeclarations??!1}catch{return!1}}function bc(e,t){let r={isValid:!0,errors:[]};for(let n of Cc(e))r.errors.push({line:n.line,column:n.column,message:n.message,code:n.code});for(let n of pc(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 Ec(e,t,r){if(e===t)return"";let n=e.split(`
201
- `),i=t.split(`
202
- `),o=new Map,s=new Map;for(let u=0;u<n.length;u++)o.set(n[u],(o.get(n[u])??0)+1);for(let u=0;u<i.length;u++)s.set(i[u],(s.get(i[u])??0)+1);let a=[],c=[];for(let[u,h]of o){let l=h-(s.get(u)??0);for(let y=0;y<l;y++)a.push(u)}for(let[u,h]of s){let l=h-(o.get(u)??0);for(let y=0;y<l;y++)c.push(u)}if(a.length===0&&c.length===0)return"";let f=[`--- ${r}`,`+++ ${r}`];for(let u=0;u<a.length;u++)f.push(`- ${a[u]}`);for(let u=0;u<c.length;u++)f.push(`+ ${c[u]}`);return f.join(`
203
- `)}function Sc(e,t,r,n){let i=e.split(`
204
- `),o=[];function s(h){let l="",y=h<0?-h<<1|1:h<<1;do{let C=y&31;if(y>>>=5,y>0)C|=32;l+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[C]}while(y>0);return l}let a=0,c=0,f=0,u=n.split(`
205
- `).length;for(let h=0;h<i.length;h++){if(i[h].trim()===""){o.push("");continue}a=0;let l=Math.min(h,u-1),y=[],C=0-a,S=0,x=l-c,v=0-f;y.push(s(C)+s(S)+s(x)+s(v)),a=0,c=l,f=0,o.push(y.join(","))}return{version:3,file:t,sourceRoot:"",sources:[r],sourcesContent:[n],mappings:o.join(";")}}function $c(e,t){return`${e}
206
- ${Vo()}${t}
207
- `}var Ac=he(()=>{Ur();pn();gc();wc()});function Bm(e){let t=[],r=0;for(let n=0;n<=e.length;n++)if(n===e.length||e[n]===`
208
- `){let i=r,o=n;while(i<o&&(e[i]===" "||e[i]==="\t"||e[i]==="\r"))i++;while(o>i&&(e[o-1]===" "||e[o-1]==="\t"||e[o-1]==="\r"))o--;let s=e.slice(i,o);if(r=n+1,s.startsWith("///")){if(s.indexOf("<")===-1)continue;if(Nm.test(s)||Lm.test(s)||Wm.test(s))t.push(s)}else if(s===""||s.startsWith("//"))continue;else break}return t}function Gm(e){if(e.includes(`
209
- `))return`/**
210
- * ${e}
211
- */
212
- `;return`/** ${e} */
213
- `}function jm(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,o="";for(let s=0;s<e.length;s++){let a=e[s],c=s>0?e[s-1]:"";if(!i&&(a==='"'||a==="'"||a==="`"))i=!0,o=a;else if(i&&a===o&&c!=="\\")i=!1;if(!i){if(a==="<")n++;else if(a===">")n--;else if(a==="{"&&n===0)return s}}return-1}function _m(e,t=!0){return xt(e.leadingComments,t)+e.text}function xc(e,t=!0){let r=xt(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:o,value:s}=e,a=!o&&s?Vi(s):null;if(a)o=a;else if(!o&&s&&s.trim().endsWith("as const"))o=Ie(s,!0);else if(!o&&s&&i==="const"){let f=s.trim(),u=f.startsWith("{")||f.startsWith("[");if(u)Fo();o=Ie(s,!u)}else if(!o&&s)o=Ie(s,i==="const");if(!o)o="unknown";let c="";if(t&&s&&!e.typeAnnotation&&!s.trim().endsWith("as const")){let f=s.trim();if(i!=="const"){if((o==="string"||o==="number"||o==="boolean")&&f.length>0)c=`@defaultValue ${f}`}else if(f.startsWith("{")||f.startsWith("[")){let u=No();if(u)if(u.includes(`
214
- `))c=`@defaultValue
215
- * \`\`\`ts
216
- ${u.split(`
217
- `).map((h)=>` * ${h}`).join(`
218
- `)}
219
- * \`\`\``;else c=`@defaultValue \`${u}\``}}else if(t&&s&&e.typeAnnotation&&Vl(e.typeAnnotation)){Fo();let f=s.trim(),u=f.endsWith("as const")?f.slice(0,-8).trim():f;Ie(u,!1);let h=No();if(h)if(h.includes(`
220
- `))c=`@defaultValue
221
- * \`\`\`ts
222
- ${h.split(`
223
- `).map((l)=>` * ${l}`).join(`
224
- `)}
225
- * \`\`\``;else c=`@defaultValue \`${h}\``}if(c=Do(c),n+=`: ${o};`,c&&r&&r.includes("@defaultValue"))c="";if(c&&r){let f=r.trimEnd(),u=f.lastIndexOf("*/");if(u!==-1){let h=f.slice(0,u).trimEnd();if(h.startsWith("/** ")&&!h.includes(`
226
- `))h=`/**
227
- * ${h.slice(4)}`;return`${h}
228
- * ${c}
229
- */
230
- `+n}return`/**
231
- * ${f.replace(/^\/\/\s*/,"")}
232
- * ${c}
233
- */
234
- ${n}`}if(c)return`${Gm(c)}${n}`;return r+n}function Vm(e,t=!0){let r=xt(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 o=jm(e.text);if(o!==-1)i+=` ${e.text.slice(o)}`;else i+=" {}";return r+i}function Um(e,t=!0){let r=xt(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 s=e.text.slice(i),a=s.length;while(a>0&&(s.charCodeAt(a-1)===59||s.charCodeAt(a-1)===32||s.charCodeAt(a-1)===10||s.charCodeAt(a-1)===13))a--;if(a<s.length)s=s.slice(0,a);n+=s}else{if(n+=`type ${e.name}`,e.generics)n+=e.generics;n+=" = any"}let o=n.trimEnd();if(!o.endsWith(";")&&!o.endsWith("}"))n+=";";return r+n}function Km(e,t=!0){return xt(e.leadingComments,t)+e.text}function Hm(e,t=!0){let r=xt(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 zm(e,t=!0){let r=xt(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 o="declare module ";o+=e.name;let s=e.text.indexOf("{");if(s!==-1)o+=` ${e.text.slice(s)}`;else o+=" {}";return r+o}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 Jm(e){let t=jt.get(e);if(t)return jt.delete(e),jt.set(e,t),t;return null}function Tc(e,t){if(jt.set(e,t),jt.size>200){let r=0;for(let n of jt.keys()){if(r++>=20)break;jt.delete(n)}}}function qm(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 o=r.slice(1,i),s=e.slice(0,t).trim(),a=s.startsWith("import type ");if(s.startsWith("import "))s=s.slice(7).trim();if(s.startsWith("type "))s=s.slice(5).trim();let c=null,f=[],u=!1,h=s.indexOf("{"),l=s.lastIndexOf("}");if(h!==-1&&l!==-1){let y=s.slice(0,h).trim();if(y.endsWith(","))c=y.slice(0,-1).trim()||null;let C=s.slice(h+1,l),S=0;for(let x=0;x<=C.length;x++)if(x===C.length||C.charCodeAt(x)===44){let v=S,G=x;while(v<G&&(C.charCodeAt(v)===32||C.charCodeAt(v)===9||C.charCodeAt(v)===10))v++;while(G>v&&(C.charCodeAt(G-1)===32||C.charCodeAt(G-1)===9||C.charCodeAt(G-1)===10))G--;if(v<G)f.push(C.slice(v,G));S=x+1}}else{let y=s.trim();if(y.startsWith("* as "))c=y.slice(5).trim()||null,u=!0;else c=y||null}return{defaultName:c,namedItems:f,source:o,isTypeOnly:a,isNamespace:u}}function Ym(e){let t=Jm(e);if(t)return t;let r=[],n=e.indexOf(" from ");if(n===-1)return Tc(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 o=i.indexOf("{"),s=i.lastIndexOf("}");if(o!==-1&&s!==-1){let a=i.slice(0,o).trim();if(a.endsWith(",")){let f=a.slice(0,-1).trim();if(f)r.push(f)}else if(a&&!a.includes(","))r.push(a);let c=i.slice(o+1,s).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 h=u.indexOf(" as ");if(h!==-1)u=u.slice(h+4).trim();if(u)r.push(u)}}else{let a=i.trim();if(a.startsWith("* as ")){let c=a.slice(5).trim();if(c)r.push(c)}else if(a)r.push(a)}return Tc(e,r),r}function Oc(e,t){throw Error(t||`Unexpected value: ${e}`)}function Zm(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===95||e===36||e>127}function Xm(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 o=r;r++;while(r<n&&Zm(e.charCodeAt(r)))r++;t.add(e.substring(o,r))}else r++}return t}function Mc(e,t,r=!0,n=["bun"]){let i="",o=t.sourceCode;if(o){let k=0;while(k<o.length&&(o.charCodeAt(k)===32||o.charCodeAt(k)===9||o.charCodeAt(k)===10||o.charCodeAt(k)===13))k++;if(k<o.length-2&&o.charCodeAt(k)===47&&o.charCodeAt(k+1)===47&&o.charCodeAt(k+2)===47){let U=Bm(o);if(U.length>0)for(let H=0;H<U.length;H++){if(i)i+=`
235
- `;i+=U[H]}}}let s=[],a=[],c=[],f=[],u=[],h=[],l=[],y=[],C=[];for(let k of e){let U=k.kind;switch(U){case"import":s.push(k);break;case"function":a.push(k);break;case"variable":c.push(k);break;case"interface":f.push(k);break;case"type":u.push(k);break;case"class":h.push(k);break;case"enum":l.push(k);break;case"module":y.push(k);break;case"export":C.push(k);break;case"namespace":y.push(k);break;case"unknown":break;default:Oc(U,`Unhandled declaration kind: ${U}`)}}let S=new Set,x=[],v=[],G=[],L=new Set;for(let k of C){let U=xt(k.leadingComments,r);if(k.text.startsWith("export default")){let H=k.text.endsWith(";")?k.text:`${k.text};`;G.push(U+H)}else{let H=k.text.trim();if(!H.endsWith(";"))H+=";";let O=H.match(Qm);if(O){let pe=O[1],Oe=0;for(let ie=0;ie<=pe.length;ie++)if(ie===pe.length||pe.charCodeAt(ie)===44){let ne=Oe,ue=ie;while(ne<ue&&pe.charCodeAt(ne)<=32)ne++;while(ue>ne&&pe.charCodeAt(ue-1)<=32)ue--;if(ne<ue)S.add(pe.slice(ne,ue));Oe=ie+1}}let z=U+H;if(!L.has(z))if(L.add(z),z.includes("export type"))x.push(z);else v.push(z)}}let P=new Map;if(s.length>0)for(let k of s){let U=Ym(k.text);for(let H of U)P.set(H,k)}let F=[];if(s.length>0){let k=new Set,U=[];for(let z of a)U.push(z.text);for(let z of c)if(U.push(z.text),z.typeAnnotation)U.push(z.typeAnnotation);else if(z.isExported&&z.value)U.push(xc(z,!1));for(let z of f)U.push(z.text);for(let z of u)U.push(z.text);for(let z of h)U.push(z.text);for(let z of l)U.push(z.text);for(let z of y)U.push(z.text);for(let z of C)U.push(z.text);let H=U.join(`
236
- `);if(H&&P.size>0){let z=Xm(H);for(let pe of P.keys())if(z.has(pe))k.add(pe)}for(let z of S)if(P.has(z))k.add(z);for(let z of s){if(z.isSideEffect){let Z=z.text.trim(),te=Z.endsWith(";")?Z:`${Z};`;F.push(te);continue}let pe=qm(z.text);if(!pe)continue;let{defaultName:Oe,namedItems:ie,source:ne,isTypeOnly:ue,isNamespace:se}=pe,W=Oe?k.has(Oe):!1,K="",q=0;for(let Z=0;Z<ie.length;Z++){let te=ie[Z],X=te.charCodeAt(0)===116&&te.startsWith("type ")?te.slice(5).trim():te.trim(),oe=X.indexOf(" as ");if(oe!==-1)X=X.slice(oe+4).trim();if(k.has(X)){if(q>0)K+=", ";K+=te,q++}}if(W||q>0){let Z=ue?"import type ":"import ";if(W&&Oe)if(se)Z+=`* as ${Oe}`;else Z+=q>0?`${Oe}, { ${K} }`:Oe;else if(q>0)Z+=`{ ${K} }`;Z+=` from '${ne}';`,F.push(Z)}}let O=n.length;if(F.length>1){if(Rc!==n)Rc=n,Pc=n.map((ie)=>`from '${ie}`),kc=n.map((ie)=>`from "${ie}`);let z=Pc,pe=kc,Oe=new Map;for(let ie of F){let ne=O;for(let ue=0;ue<n.length;ue++)if(ie.includes(z[ue])||ie.includes(pe[ue])){ne=ue;break}Oe.set(ie,ne)}F.sort((ie,ne)=>{let ue=Oe.get(ie),se=Oe.get(ne);return ue!==se?ue-se:ie.localeCompare(ne)})}}for(let k=0;k<F.length;k++){if(i)i+=`
237
- `;i+=F[k]}for(let k=0;k<x.length;k++){if(i)i+=`
238
- `;i+=x[k]}let I=[a,c,f,u,h,l,y];for(let k=0;k<I.length;k++){let U=I[k];for(let H=0;H<U.length;H++){let O=U[H],z="",pe=O.kind;switch(pe){case"function":z=_m(O,r);break;case"variable":z=xc(O,r);break;case"interface":z=Vm(O,r);break;case"type":z=Um(O,r);break;case"class":z=Km(O,r);break;case"enum":z=Hm(O,r);break;case"module":case"namespace":z=zm(O,r);break;case"import":case"export":case"unknown":break;default:Oc(pe,`Unhandled declaration kind in processor: ${pe}`)}if(z){if(i)i+=`
239
- `;i+=z}}}for(let k=0;k<v.length;k++){if(i)i+=`
240
- `;i+=v[k]}for(let k=0;k<G.length;k++){if(i)i+=`
241
- `;i+=G[k]}if(!i&&(s.length>0||C.length>0))return"export {};";return i}var Nm,Lm,Wm,jt,Qm,Rc=null,Pc,kc;var Dc=he(()=>{Go();Nm=/^\/\/\/\s*<reference\s+(?:path|types|lib|no-default-lib)\s*=\s*["'][^"']+["']\s*\/>/,Lm=/^\/\/\/\s*<amd-module\s+name\s*=\s*["'][^"']+["']\s*\/>/,Wm=/^\/\/\/\s*<amd-dependency\s+path\s*=\s*["'][^"']+["']/;jt=new Map;Qm=/export\s+(?:type\s+)?\{\s*([^}]+)\s*\}/,Pc=[],kc=[]});import{existsSync as Ic}from"fs";import{mkdir as Fc,readdir as ep,realpath as tp,rm as rp}from"fs/promises";import{availableParallelism as ip}from"os";import{basename as Jo,dirname as Yi,extname as np,isAbsolute as Fr,parse as op,relative as Be,resolve as et}from"path";function Bc(e){let t=Uo.get(e);if(!t)t=Ms(e),Uo.set(e,t),t.catch(()=>Uo.delete(e));return t}async function Nc(e,t,r,n,i,o=qi){let s=Jo(e)||"output.d.ts",a=Be(Yi(e),t),c=`${s}.map`,f=r.lastIndexOf(`
242
- ${Vo()}`),u=f===-1?r:r.slice(0,f),h=Sc(u,s,a,n),l=`${e}.map`;return await o(l,JSON.stringify(h)),Y.debug(` Generated source map: ${Be(i,l)}`),c}async function qo(e){let t=Date.now(),r={...gl,...e};if(r.logLevel)fn(r.logLevel);else if(r.verbose)fn("debug");let n=new zi;if(r.plugins&&r.plugins.length>0){for(let P of r.plugins)n.register(P),Y.debug(`Registered plugin: ${P.name}`);r=await n.runOnStart(r)}if(await ap(r),r.isolatedDeclarations===void 0)r.isolatedDeclarations=await vc(r);let i=r.typeMappings?Ji(r.typeMappings):void 0,o=null,s={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;Y.debug("Starting DTS generation..."),Y.debug(`Using ${s.generationMode} declaration generation path`),Y.debug("Config:",r);let c=await hp(r);up(r,c);let f=c.slice(),u=await Bc(r),h=null;if(r.autoIncludeReExports!==!1&&f.length>0){h=await vn(f,{includeImports:!0,resolveSpecifier:u});let P=et(r.cwd,r.root),F=r.exclude||[],I=[];for(let k of h.reachable){if(f.includes(k))continue;if(!zo(k))continue;if(k.endsWith(".d.ts"))continue;if(k.includes("node_modules"))continue;let U=r.outputStructure==="flat"&&c.some((H)=>u.isPackageLocal?.(H,k));if(!Nr(k,P)&&!U){Y.warn(`Skipping auto-included source outside root: ${Be(r.cwd,k)}`);continue}if(Ho(k,F,P))continue;I.push(k)}if(I.length>0)f=[...f,...I],Y.debug(`Auto-included ${I.length} file(s) reached via relative re-exports`)}if(dp(f,r),Ko.set(r,new Set(f)),r.incremental){if(o=new xn(r,u.cacheKey?.(f)),r.clearCache){if(Y.debug("Clearing build cache..."),!r.dryRun)o.clear()}else if(o.load()){let P=o.getStats();Y.debug(`Loaded build cache with ${P.entries} entries`)}else Y.debug("No existing build cache found, starting fresh");if(!r.dryRun)Vs(r.cwd)}if(o&&!r.dryRun){let P=o.prune(new Set(f),r.cwd);if(P>0)Y.debug(`Pruned ${P} deleted files from cache`)}if(Y.debug(`Found ${f.length} TypeScript files`),r.progress&&f.length>0){let P=r.parallel?"parallel":"sequential";Y.info(`Processing ${f.length} files (${P})...`)}let l=new Map,y=new Map,C=async(P,F,I="lf")=>{y.set(P,{content:F,lineEnding:I})},S=async(P,F)=>{let I;try{let k=Lr(P,r),U=async(se)=>{if(!r.diff)return;try{let W=await Pt(k),K=Ec(W,se,Be(r.cwd,k));if(K)Y.info(`
243
- ${K}`);else Y.debug(`[no changes] ${k}`)}catch{Y.info(`[new file] ${Be(r.cwd,k)}`)}},H=(se)=>{if(!r.validate)return 0;let W=bc(se,k);if(W.isValid)return Y.debug(`[validation] ${k} - OK`),0;Y.warn(`[validation] ${Be(r.cwd,k)} has ${W.errors.length} error(s):`);for(let K of W.errors){let q=` Line ${K.line}:${K.column}`;if(K.code)q+=` [${K.code}]`;if(q+=` - ${K.message}`,Y.warn(q),K.suggestion)Y.warn(` Suggestion: ${K.suggestion}`)}return W.errors.length},O=(se)=>{Y.info(`[dry-run] Would generate: ${k}`),Y.debug("--- Content preview ---"),Y.debug(se.slice(0,500)+(se.length>500?`
244
- ...`:"")),Y.debug("--- End preview ---")};if(o){let se=o.getCachedIfValid(P,r.cwd);if(se){if(r.bundle)l.set(P,se);await U(se);let W=H(se);if(r.dryRun)O(se);else{if(r.declarationMap)I=F??await Pt(P),await Nc(k,P,se,I,r.cwd,C);await C(k,se,r.lineEnding)}return Y.debug(`[cached] ${Be(r.cwd,k)}`),{success:!0,file:P,declarationCount:0,importCount:0,exportCount:0,cached:!0,validationErrorCount:W}}}I=F??await Pt(P);let{content:z,declarationCount:pe,importCount:Oe,exportCount:ie}=await gp(P,I,r,n,i);if(r.bundle)l.set(P,z);let ne=z;if(r.prettier||r.indentStyle||r.indentSize){let se=await tc(ne,{usePrettier:r.prettier,builtIn:{indentSize:r.indentSize||2,useTabs:r.indentStyle==="tabs",normalizeWhitespace:!0,sortImports:!0,trailingNewline:!0}},k);ne=se.content;for(let W of se.warnings??[])Y.warn(`[format] ${W}`)}if(r.declarationMap){let se=`${Jo(k)||"output.d.ts"}.map`;ne=$c(ne,se)}await U(ne);let ue=H(ne);if(r.dryRun)O(ne);else{if(r.declarationMap&&I)await Nc(k,P,ne,I,r.cwd,C);if(await C(k,ne,r.lineEnding),o&&I)o.update(P,I,ne,r.cwd);Y.debug(`Generated: ${k}`)}return{success:!0,file:P,declarationCount:pe,importCount:Oe,exportCount:ie,validationErrorCount:ue}}catch(k){let U=Cl(k,P,I);if(r.plugins&&r.plugins.length>0)await n.runOnError(k instanceof Error?k:Error(String(k)),P,I||"");return{success:!1,file:P,declarationCount:0,importCount:0,exportCount:0,dtsError:U,validationErrorCount:0}}},x=r.parallel||r.parallel!==!1&&f.length>=10,v=Ks(r.concurrency,ip?.()??8),G=new Map;if(x&&f.length>1){let P=f.map(async(F)=>{try{let I=await Pt(F);return{file:F,source:I}}catch{return{file:F,source:null}}});for(let F of await Promise.all(P))if(F.source!==null)G.set(F.file,F.source)}let L=(P)=>{if(s.filesProcessed++,P.success){if(P.cached)a++;else s.filesGenerated++,s.declarationsFound+=P.declarationCount,s.importsProcessed+=P.importCount,s.exportsProcessed+=P.exportCount;if(r.validate){if(s.filesValidated++,P.validationErrorCount)s.validationErrors+=P.validationErrorCount}}else if(s.filesFailed++,P.dtsError){s.errors.push(P.dtsError);let F=wl(P.dtsError);if(r.continueOnError)Y.warn(F);else throw Y.error(F),Error(P.dtsError.message)}};if(x)for(let P=0;P<f.length;P+=v){let F=f.slice(P,P+v),I=await Promise.all(F.map((k)=>S(k,G.get(k))));for(let k of I)L(k);if(r.progress){let k=Math.round(s.filesProcessed/f.length*100);Y.info(`[${s.filesProcessed}/${f.length}] ${k}%`)}}else for(let P of f){let F=await S(P);if(L(F),r.progress){let I=Math.round(s.filesProcessed/f.length*100),k=F.cached?"[cached]":"";Y.info(`[${s.filesProcessed}/${f.length}] ${I}% - ${Be(r.cwd,P)} ${k}`)}}if(!r.dryRun){if(r.clean)await cp(r);for(let[P,F]of y)await Fc(Yi(P),{recursive:!0}),await qi(P,F.content,F.lineEnding)}if(o&&!r.dryRun)o.save(),Y.debug("Saved build cache");if(!r.bundle){let P=[];if(h)for(let F of h.unresolved)P.push({from:F.from,specifier:F.specifier,reason:"missing"});if(r.autoIncludeReExports===!1&&f.length>0){let F=new Set(f);for(let I of f){let k;try{k=await Pt(I)}catch{continue}for(let U of Jr(k)){let H=u(U.specifier,I);if(!H.isRelative)continue;if(!H.resolved)P.push({from:I,specifier:U.specifier,reason:"missing"});else if(!/\.d\.(?:ts|mts|cts)$/.test(H.resolved)&&!F.has(H.resolved))P.push({from:I,specifier:U.specifier,reason:"not-emitted"})}}}if(P.length>0){let F=[];F.push(`Found ${P.length} re-export(s) pointing at siblings that won't be in the output:`);for(let k of P){let U=Be(r.cwd,k.from);if(k.reason==="missing")F.push(` ${U} \u2192 '${k.specifier}' (path not found on disk)`);else F.push(` ${U} \u2192 '${k.specifier}' (resolved but not in entrypoints; set autoIncludeReExports: true or add to entrypoints)`)}let I=F.join(`
245
- `);if(r.failOnUnresolvedReExport)throw Error(I);Y.warn(I),Y.warn('Generated .d.ts files reference modules that were not emitted \u2014 consumers will see "has no exported member" errors.')}}if(r.bundle&&(s.filesGenerated>0||a>0)&&c.length>0)try{Y.debug("Bundling declarations...");let P=c.length===1&&!!r.bundleOutput;for(let F of c){let I=await vn([F],{includeImports:!0,resolveSpecifier:u}),k=new Set;for(let z of I.reachable){if(z.endsWith(".d.ts"))continue;if(z.includes("node_modules"))continue;k.add(z)}let U=f.filter((z)=>k.has(z));if(!U.includes(F))U.push(F);let H=Ls(F,U,l,{cwd:r.cwd,keepComments:r.keepComments});for(let z of new Set(H.warnings))Y.warn(`[bundle] ${z}`);let O=P?et(r.cwd,r.outdir,r.bundleOutput):Lr(F,r);if(r.dryRun)Y.info(`[dry-run] Would bundle ${H.files.length} files to: ${Be(r.cwd,O)}`);else await Fc(Yi(O),{recursive:!0}),await qi(O,H.content,r.lineEnding),Y.info(`Bundled ${H.files.length} files to: ${Be(r.cwd,O)}`);if(P)break}}catch(P){let F=P instanceof Error?P.message:String(P);Y.error(`Bundle failed: ${F}`)}if(s.durationMs=Date.now()-t,r.stats)if(r.outputFormat==="json")console.log(JSON.stringify(s,null,2));else{if(Y.info(`
246
- --- Generation Statistics ---`),Y.info(`Files processed: ${s.filesProcessed}`),Y.info(`Files generated: ${s.filesGenerated}`),a>0)Y.info(`Files cached: ${a}`);if(s.filesFailed>0)Y.info(`Files failed: ${s.filesFailed}`);if(Y.info(`Declarations found: ${s.declarationsFound}`),Y.info(`Imports processed: ${s.importsProcessed}`),Y.info(`Exports processed: ${s.exportsProcessed}`),s.filesValidated>0){if(Y.info(`Files validated: ${s.filesValidated}`),s.validationErrors>0)Y.info(`Validation errors: ${s.validationErrors}`)}if(Y.info(`Duration: ${s.durationMs}ms`),s.errors.length>0){Y.info(`
247
- Errors:`);for(let P of s.errors){let F=` - ${P.file}`;if(P.location)F+=`:${P.location.line}:${P.location.column}`;if(P.code)F+=` [${P.code}]`;if(F+=`: ${P.message}`,Y.info(F),P.suggestion)Y.info(` Suggestion: ${P.suggestion}`)}}Y.info(`-----------------------------
248
- `)}if(r.plugins&&r.plugins.length>0)await n.runOnEnd(s);return Y.debug("DTS generation complete!"),s}async function Lc(e){try{return await tp(e)}catch{return et(e)}}async function ap(e){let t=et(e.cwd,e.outdir);if(e.bundle&&e.bundleOutput){if(Fr(e.bundleOutput))throw Error("bundleOutput must be relative to outdir");let i=et(t,e.bundleOutput);if(!Nr(i,t))throw Error("bundleOutput must stay within outdir")}if(!e.clean||e.dryRun)return;if(t===op(t).root)throw Error("Refusing to clean declarations from the filesystem root");let[r,n]=await Promise.all([Lc(t),Lc(et(e.cwd,e.root))]);if(Nr(n,r))throw Error("Refusing to clean an outdir that contains the source root")}function lp(e){let t=Ir.get(e);if(!t){if(t=new Wc(e),Ir.set(e,t),Ir.size>sp){let r=Ir.keys().next().value;if(r!==void 0)Ir.delete(r)}}return t}async function cp(e){let t=et(e.cwd,e.outdir);async function r(n){let i;try{i=await ep(n,{withFileTypes:!0})}catch{return}await Promise.all(i.map(async(o)=>{let s=et(n,o.name);if(o.isDirectory()){await r(s);return}if(o.name.endsWith(".d.ts")||o.name.endsWith(".d.mts")||o.name.endsWith(".d.cts")||o.name.endsWith(".d.ts.map")||o.name.endsWith(".d.mts.map")||o.name.endsWith(".d.cts.map"))await rp(s,{force:!0})}))}await r(t)}function Ho(e,t,r){if(!t||t.length===0)return!1;let n=Be(r,e);for(let i of t){let o=lp(i);if(o.match(n)||o.match(e))return!0}return!1}function up(e,t){let r=et(e.cwd,e.root),n=` root: ${r}
249
- entrypoints: ${e.entrypoints.map((o)=>JSON.stringify(o)).join(", ")||"(none)"}
250
- `+(e.exclude?.length?` exclude: ${e.exclude.map((o)=>JSON.stringify(o)).join(", ")}
251
- `:"")+"Entrypoints are resolved relative to --root. Pass several by repeating --entrypoints or separating them with commas.";if(t.length===0){if(e.entrypoints.filter((o)=>Fr(o)&&Ic(o)&&!Nr(o,r)).length===e.entrypoints.length)return;throw Error(`No source files matched. Nothing was generated.
252
- ${n}`)}let i=e.entrypoints.filter((o)=>{if(fp.test(o))return!1;return!Ic(Fr(o)?o:et(r,o))});if(i.length>0)throw Error(`Entrypoint${i.length>1?"s":""} not found: ${i.map((o)=>JSON.stringify(o)).join(", ")}
253
- ${n}`)}async function hp(e){let t=[],r=et(e.cwd,e.root),n=e.exclude||[],i=[...e.entrypoints,...e.include??[]];for(let o of i)if(Fr(o)&&zo(o)){if(!o.includes("node_modules")){if(!Nr(o,r)&&e.outputStructure!=="flat")Y.warn(`Skipping entrypoint outside root: ${Be(e.cwd,o)}`);else if(!Ho(o,n,r))t.push(o)}}else{let s=new Wc(o);for await(let a of s.scan({cwd:r,absolute:!0,onlyFiles:!0}))if(zo(a)&&!a.includes("node_modules")){if(!Ho(a,n,r))t.push(a)}}return[...new Set(t.map((o)=>et(o)))].sort()}function Nr(e,t){let r=Be(t,e);return r!==".."&&!r.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!Fr(r)}function dp(e,t){let r=new Map;for(let n of e){let i=Lr(n,t),o=r.get(i);if(o&&o!==n)throw Error(`Output path collision: ${Be(t.cwd,o)} and ${Be(t.cwd,n)} both emit ${Be(t.cwd,i)}`);r.set(i,n)}}function zo(e){return/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/.test(e)&&!/\.d\.(?:ts|mts|cts)$/.test(e)}function Lr(e,t){let r=et(t.cwd,t.root),n=Be(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 et(t.cwd,t.outdir,n);else{let i=Jo(n);return et(t.cwd,t.outdir,i)}}function mp(e,t,r=""){let n=Be(Yi(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}async function pp(e,t,r){let n=await Bc(r),i=Lr(t,r);return Is(e,(o)=>{let s=n(o,t);if(!s.isRelative||!s.resolved)return o;if(/\.d\.(?:ts|mts|cts)$/.test(s.resolved))return o;if(s.isAlias&&Ko.has(r)&&!Ko.get(r).has(s.resolved))throw Error(`Local alias ${JSON.stringify(o)} from ${t} targets a declaration excluded from this package build: ${s.resolved}`);let a=s.isAlias?s.suffix??"":o.match(/[?#].*$/)?.[0]??"",c=a?o.slice(0,-a.length):o,f=np(c),u=/^(?:\.js|\.jsx|\.mjs|\.cjs)$/.test(f)?f:"";return mp(i,Lr(s.resolved,r),u)+a})}async function gp(e,t,r,n,i){let o=t;if(n)o=await n.runOnBeforeFile(e,t);let s=Ql(o,e,r.keepComments,r.isolatedDeclarations??!1);if(n)s=await n.runOnDeclarations(e,o,s);let a=0,c=0;for(let u=0;u<s.length;u++){let h=s[u];if(h.kind==="import")a++;if(h.kind==="export"||h.isExported)c++}let f=Mc(s,{filePath:e,sourceCode:o,declarations:s},r.keepComments,r.importOrder);if(f=await pp(f,e,r),i)f=fc(f,i,{filePath:e});if(r.normalizeOutput===!0||r.declarationOrder)f=sc(f,{lineEnding:"lf",declarationOrder:r.declarationOrder,indent:{style:r.indentStyle??"spaces",size:r.indentSize??2}});if(n)f=await n.runOnAfterFile(e,o,f);return{content:f,declarationCount:s.length,importCount:a,exportCount:c}}var Wc,Uo,Ko,sp=50,Ir,fp;var Gc=he(()=>{Ur();un();bn();Ws();Us();Hs();yl();vl();ec();rc();ic();ac();uc();Ac();Dc();({Glob:Wc}=globalThis.Bun),Uo=new WeakMap,Ko=new WeakMap;Ir=new Map;fp=/[*?[\]{}!]/});var jc=he(()=>{Gc()});import{createHash as Cp}from"crypto";import{existsSync as wp,readFileSync as vp,writeFileSync as bp}from"fs";import{dirname as Ep,join as Sp,relative as _c,resolve as Wr,sep as Zi}from"path";import Uc from"process";class Kc{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 Hc{manifest;cacheDir;manifestPath;constructor(e,t){this.cacheDir=e,this.manifestPath=Sp(e,"manifest.json"),this.manifest=this.loadManifest(t)}loadManifest(e){try{if(wp(this.manifestPath)){let t=JSON.parse(vp(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}=yp("fs");e(this.cacheDir,{recursive:!0}),bp(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 $p(e){let t={root:e.root,outdir:e.outdir,entrypoints:e.entrypoints,clean:e.clean,tsconfigPath:e.tsconfigPath};return Cp("md5").update(JSON.stringify(t)).digest("hex")}function zc(e={}){let{onSuccess:t,onError:r,failOnError:n=!0,incremental:i=!1,cacheDir:o=".dtsx-cache",on:s,timeout:a=60000,continueOnError:c=!1,verbose:f=!1,...u}=e,h=new Kc;if(s){for(let[l,y]of Object.entries(s))if(y)h.on(l,y)}return{name:"bun-plugin-dtsx",async setup(l){let y=Date.now(),C=null,S=0;try{let x=Tp(u,l),v=$p(x);if(x.clean){let F=Wr(x.cwd??Uc.cwd(),x.outdir??"./dist");if(Vc.has(F))x.clean=!1;else Vc.add(F)}if(i)C=new Hc(Wr(o),v);if(await h.emit("start",{type:"start",files:x.entrypoints||[],config:x}),f){if(console.log("[bun-plugin-dtsx] Starting declaration generation..."),i)console.log("[bun-plugin-dtsx] Incremental mode enabled")}let L=await(async()=>new Promise((F,I)=>{let k=setTimeout(()=>{I(new Br(`Generation timed out after ${a}ms`,"TIMEOUT_ERROR",{timeout:a}))},a);qo(x).then((U)=>{clearTimeout(k),F(U)}).catch((U)=>{clearTimeout(k),I(U)})}))(),P=Date.now()-y;if(C)C.save();if(await h.emit("complete",{type:"complete",stats:L,duration:P,fromCache:S}),f){if(console.log(`[bun-plugin-dtsx] Generation complete in ${P}ms`),S>0)console.log(`[bun-plugin-dtsx] ${S} files served from cache`)}if(t)await t(L)}catch(x){let v=Ap(x);if(await h.emit("error",{type:"error",error:v}),r)await r(v);else{if(console.error("[bun-plugin-dtsx] Error generating declarations:"),console.error(` Code: ${v.code}`),console.error(` Message: ${v.message}`),v.context)console.error(` Context: ${JSON.stringify(v.context)}`);if(f&&v.stack)console.error(` Stack: ${v.stack}`)}if(n&&!c)throw v}}}}function Ap(e){if(e instanceof Br)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 Br(e.message,t,{originalError:e.name},e)}return new Br(String(e),"GENERATION_ERROR")}function xp(e){let t=e.map((n)=>Ep(n).split(Zi)),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(Zi)||Zi}function Tp(e,t){let r=e.cwd||Uc.cwd(),n=t?.config?.entrypoints,i=e.outdir||e.build?.config.outdir||t?.config.outdir||"./dist",o=e.root||e.build?.config.root||t?.config.root;if(!o&&n?.length){let a=xp(n.map((c)=>Wr(r,c)));o=_c(r,a)||"."}o=o||"./src";let s=e.entrypoints;if(!s)if(n?.length){let a=Wr(r,o),c=[];for(let f of n){let u=Wr(r,f);if(u===a||u.startsWith(a+Zi))c.push(_c(a,u));else console.warn(`[bun-plugin-dtsx] Skipping entrypoint outside root "${o}": ${f}`)}s=c.length?c:["index.ts"]}else s=["index.ts"];return{...e,cwd:r,root:o,entrypoints:s,outdir:i,clean:e.clean??!0,tsconfigPath:e.tsconfigPath}}var yp,Br,Vc;var Jc=he(()=>{jc();yp=import.meta.require;Br=class Br 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}}};Vc=new Set});import{mkdir as Op,stat as Rp}from"fs/promises";import{bold as Yo,dim as Zo,green as Pp,italic as qc,log as kp}from"@stacksjs/cli";import{path as ot}from"@stacksjs/path";import{glob as Yc}from"@stacksjs/storage";function ln(e){let t=new Map;for(let s of e){if(t.has(s.name))throw Error(`duplicate package name: ${s.name}`);t.set(s.name,s)}let r=new Map,n=new Set,i=(s,a)=>{let c=r.get(s);if(c!==void 0)return c;if(n.has(s))throw Error(`dependency cycle: ${[...a,s].join(" -> ")}`);n.add(s);let f=t.get(s).dependencies.filter((h)=>h!==s&&t.has(h)),u=f.length?1+Math.max(...f.map((h)=>i(h,[...a,s]))):0;return n.delete(s),r.set(s,u),u},o=[];for(let s of[...e].sort((a,c)=>a.name.localeCompare(c.name)))(o[i(s.name,[])]||=[]).push(s);return o.filter(Boolean)}import{existsSync as cf,readdirSync as ff,readFileSync as hs}from"fs";import{join as cn}from"path";function uf(e){return[...ff(e,{withFileTypes:!0}).filter((r)=>r.isDirectory()).map((r)=>cn(e,r.name)),e].filter((r)=>{let n=cn(r,"package.json");if(!cf(n))return!1;let i=JSON.parse(hs(n,"utf8"));return!i.private&&!!i.scripts?.build})}async function hf(e){let t=e.map((i)=>{let o=JSON.parse(hs(cn(i,"package.json"),"utf8"));if(!o.name||!o.scripts?.build)throw Error(`Not a buildable workspace package: ${i}`);return{name:o.name,dir:i,dependencies:Object.keys(o.dependencies??{})}}),r=ln(t),n=[];for(let{name:i,dir:o,dependencies:s}of r.flat()){let a=n.filter((f)=>f.exitCode!==0&&s.includes(f.name)).map((f)=>f.name);if(a.length){console.error(`Cannot build ${o}: dependencies failed: ${a.join(", ")}`),n.push({name:i,dir:o,exitCode:null,blockedBy:a});continue}console.log(`Building ${o}`);let c=Bun.spawn([process.execPath,"run","build"],{cwd:o,stdout:"inherit",stderr:"inherit"});n.push({name:i,dir:o,exitCode:await c.exited,blockedBy:[]})}return n}async function Mp(e){let t=await Yc([ot.resolve(e,"dist","**/*.d.ts")],{absolute:!0}),r=new Bun.Transpiler({loader:"ts",target:"bun"});for(let n of t){let i=await Bun.file(n).text();try{r.transformSync(i)}catch(o){throw Error(`Invalid declaration generated at ${n}: ${o instanceof Error?o.message:String(o)}`)}}}async function Dp(e){let t=ot.resolve(e,"dist","index.js");if(!await Bun.file(t).exists())return;let r=Bun.spawnSync({cmd:[process.execPath,"-e",`try { await import(${JSON.stringify(t)}) } catch (error) { console.error(error); process.exit(1) }`],stdout:"ignore",stderr:"pipe",env:{...process.env,NODE_ENV:"test"}});if(r.exitCode===0)return;let n=new TextDecoder().decode(r.stderr??new Uint8Array),i=/SyntaxError|needs to refer to a top-level declared variable|does not provide an export named|Export named .* not found/i;if(i.test(n)){let o=n.split(`
254
- `).find((s)=>i.test(s))??n.trim().split(`
251
+ `)}function hy(e,t){let i=new RegExp(`\\n{${t+2},}`,"g");return e.replace(i,`
252
+ `.repeat(t+1))}function py(e){return`${e.replace(/\s+$/,"")}
253
+ `}function my(e,t){let{style:i="spaces",size:r=2}=t,n=i==="tabs"?"\t":" ".repeat(r),o=e.split(`
254
+ `),s=[];for(let c of o){let l=c.match(/^([\t ]*)(.*)$/);if(!l){s.push(c);continue}let[,f,u]=l;if(!u){s.push("");continue}let d=f.replace(/\t/g," "),h=Math.floor(d.length/2);s.push(n.repeat(h)+u)}return s.join(`
255
+ `)}function gy(e,t){let{groups:i=fy,separateGroups:r=!0,alphabetize:n=!0}=t,o=e.split(`
256
+ `),s=[],c=[],l=-1;for(let m=0;m<o.length;m++){let a=o[m],C=Ou(a);if(C)s.push({line:a,source:C.source,group:C.group,isType:C.isType}),l=m;else if(s.length>0&&a.trim()==="")continue;else if(s.length>0||a.trim()!==""){if(s.length===0||m>l+1)c.push(a)}}if(s.length===0)return e;let f=new Map;for(let m of i)f.set(m,[]);for(let m of s)(f.get(m.group)||f.get("external")||[]).push(m);if(n)for(let[,m]of f)m.sort((a,C)=>{if(a.isType!==C.isType)return a.isType?1:-1;return a.source.localeCompare(C.source)});let u=[],d=null;for(let m of i){let a=f.get(m)||[];if(a.length===0)continue;if(r&&d!==null)u.push("");for(let C of a)u.push(C.line);d=m}let h=o.slice(0,o.findIndex((m)=>Ou(m)!==null)),p=c;while(p.length>0&&p[0].trim()==="")p.shift();return[...h,...u,"",...p].join(`
257
+ `)}function Ou(e){let t=e.trim(),i=t.match(/^import\s+(type\s+)?.*from\s+['"]([^'"]+)['"]/);if(!i){let o=t.match(/^import\s+['"]([^'"]+)['"]/);if(o)return{source:o[1],group:Ru(o[1]),isType:!1};return null}let r=!!i[1],n=i[2];return{source:n,group:r?"type":Ru(n),isType:r}}function Ru(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 yy(e,t){let{kinds:i=cy,alphabetize:r=!1,groupExports:n=!0}=t,o=e.split(`
258
+ `),s=[],c=[],l=[],f=null,u=0,d=!0,h=!1,p=[];for(let C=0;C<o.length;C++){let b=o[C],v=b.trim(),T=u,B=v.startsWith("///"),x=T===0&&!B&&(v.startsWith("//")||v.startsWith("/*"));if(h||x){if(p.push(b),!h&&v.startsWith("/*")&&!v.includes("*/"))h=!0;else if(h&&v.includes("*/"))h=!1;continue}if(T===0&&p.length>0&&v===""){p.push(b);continue}u+=(b.match(/\{/g)||[]).length,u-=(b.match(/\}/g)||[]).length;let D=wy(v);if(d&&D&&D.kind!=="import"&&!v.startsWith("//")&&!v.startsWith("/*"))d=!1;if(d){if(p.length>0){if(D?.kind==="import"||!D)c.push(...p),p.length=0}c.push(b);continue}if(D&&u<=1){if(f)s.push(f);f={lines:p.length>0?[...p,b]:[b],kind:D.kind,name:D.name,isExport:D.isExport},p.length=0}else if(f)f.lines.push(b);else{if(v==="")continue;l.push(b)}}if(f)s.push(f);if(p.length>0)l.push(...p);s.sort((C,b)=>{if(n&&C.isExport!==b.isExport)return C.isExport?-1:1;let v=i.indexOf(C.kind),T=i.indexOf(b.kind),B=v>=0?v:i.length,x=T>=0?T:i.length;if(B!==x)return B-x;if(r)return C.name.localeCompare(b.name);return 0});let m=[...c],a=null;for(let C of s){if(a!==null&&C.kind!==a)m.push("");m.push(...C.lines),a=C.kind}if(l.length>0)m.push(""),m.push(...l);return m.join(`
259
+ `)}function wy(e){let t=e.startsWith("export "),i=t?e.slice(7):e;if(e.startsWith("import "))return{kind:"import",name:e.match(/from\s+['"]([^'"]+)['"]/)?.[1]||"",isExport:!1};if(i.startsWith("type ")||i.startsWith("declare type "))return{kind:"type",name:i.match(/type\s+(\w+)/)?.[1]||"",isExport:t};if(i.startsWith("interface ")||i.startsWith("declare interface "))return{kind:"interface",name:i.match(/interface\s+(\w+)/)?.[1]||"",isExport:t};if(i.startsWith("class ")||i.startsWith("abstract class ")||i.startsWith("declare class ")||i.startsWith("declare abstract class "))return{kind:"class",name:i.match(/class\s+(\w+)/)?.[1]||"",isExport:t};if(i.startsWith("enum ")||i.startsWith("const enum ")||i.startsWith("declare enum ")||i.startsWith("declare const enum "))return{kind:"enum",name:i.match(/enum\s+(\w+)/)?.[1]||"",isExport:t};if(i.startsWith("function ")||i.startsWith("async function ")||i.startsWith("declare function ")||i.startsWith("declare async function "))return{kind:"function",name:i.match(/function\s+(\w+)/)?.[1]||"",isExport:t};if(i.startsWith("const ")||i.startsWith("let ")||i.startsWith("var ")||i.startsWith("declare const ")||i.startsWith("declare let ")||i.startsWith("declare var "))return{kind:"variable",name:i.match(/(?:const|let|var)\s+(\w+)/)?.[1]||"",isExport:t};if(i.startsWith("namespace ")||i.startsWith("declare namespace "))return{kind:"namespace",name:i.match(/namespace\s+(\w+)/)?.[1]||"",isExport:t};if(i.startsWith("module ")||i.startsWith("declare module "))return{kind:"module",name:i.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 cy,fy;var Mu=me(()=>{cy=["import","type","interface","enum","class","function","variable","export","module","namespace","unknown"],fy=["builtin","external","scoped","internal","parent","sibling","index","type"]});class so{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((i)=>i.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 i of this.plugins)if(i.onStart){let r=await i.onStart(t);if(r)t=r}return this.config=t,t}async runOnBeforeFile(e,t){let i=t;for(let r of this.plugins)if(r.onBeforeFile){let n={filePath:e,sourceCode:t,content:i,config:this.config,log:this.createLogger(r.name)},o=await r.onBeforeFile(n);if(typeof o==="string")i=o}return i}async runOnDeclarations(e,t,i){let r=i;for(let n of this.plugins)if(n.onDeclarations){let o={filePath:e,sourceCode:t,declarations:r,config:this.config,log:this.createLogger(n.name)},s=await n.onDeclarations(o);if(s)r=s}return r}async runOnAfterFile(e,t,i){let r=i;for(let n of this.plugins)if(n.onAfterFile){let o={filePath:e,sourceCode:t,content:r,config:this.config,log:this.createLogger(n.name)},s=await n.onAfterFile(o);if(typeof s==="string")r=s}return r}async runOnEnd(e){for(let t of this.plugins)if(t.onEnd)await t.onEnd(e)}async runOnError(e,t,i){for(let r of this.plugins)if(r.onError){let n={filePath:t,sourceCode:i,config:this.config,log:this.createLogger(r.name)};await r.onError(e,n)}}}function Cy(e){return e}var Ov,Rv;var Du=me(()=>{Ov=new so;Rv=Cy({name:"strip-internal",version:"1.0.0",description:"Removes declarations marked with @internal",onDeclarations:(e)=>e.declarations.filter((t)=>{if(t.leadingComments){if(t.leadingComments.some((i)=>i.includes("@internal")))return e.log.debug(`Stripping internal declaration: ${t.name}`),!1}return!0})})});function Iu(e){let t=[],i=0;for(let r=0;r<=e.length;r++)if(r===e.length||e[r]===`
260
+ `){let n=i,o=r;while(n<o&&(e[n]===" "||e[n]==="\t"||e[n]==="\r"))n++;while(o>n&&(e[o-1]===" "||e[o-1]==="\t"||e[o-1]==="\r"))o--;let s=e.slice(n,o);if(i=r+1,s.startsWith("///")){if(s.indexOf("<")===-1)continue;if(vy.test(s)||by.test(s)||$y.test(s))t.push(s)}else if(s===""||s.startsWith("//"))continue;else break}return t}var vy,by,$y;var Nu=me(()=>{vy=/^\/\/\/\s*<reference\s+(?:path|types|lib|no-default-lib)\s*=\s*["'][^"']+["']\s*\/>/,by=/^\/\/\/\s*<amd-module\s+name\s*=\s*["'][^"']+["']\s*\/>/,$y=/^\/\/\/\s*<amd-dependency\s+path\s*=\s*["'][^"']+["']/});function Fu(e,t){throw Error(t||`Unexpected value: ${e}`)}function ju(e,t,i=!0,r=["bun"]){let n="",o=t.sourceCode;if(o){let x=0;while(x<o.length&&(o.charCodeAt(x)===32||o.charCodeAt(x)===9||o.charCodeAt(x)===10||o.charCodeAt(x)===13))x++;if(x<o.length-2&&o.charCodeAt(x)===47&&o.charCodeAt(x+1)===47&&o.charCodeAt(x+2)===47){let D=Iu(o);if(D.length>0)for(let U=0;U<D.length;U++){if(n)n+=`
261
+ `;n+=D[U]}}}let s=[],c=[],l=[],f=[],u=[],d=[],h=[],p=[],m=[];for(let x of e){let D=x.kind;switch(D){case"import":s.push(x);break;case"function":c.push(x);break;case"variable":l.push(x);break;case"interface":f.push(x);break;case"type":u.push(x);break;case"class":d.push(x);break;case"enum":h.push(x);break;case"module":p.push(x);break;case"export":m.push(x);break;case"namespace":p.push(x);break;case"unknown":break;default:Fu(D,`Unhandled declaration kind: ${D}`)}}let a=[],C=[],b=[],v=new Set;for(let x of m){let D=Ft(x.leadingComments,i);if(x.text.startsWith("export default")){let U=x.text.endsWith(";")?x.text:`${x.text};`;b.push(D+U)}else{let U=x.text.trim();if(!U.endsWith(";"))U+=";";let j=D+U;if(!v.has(j))if(v.add(j),j.includes("export type"))a.push(j);else C.push(j)}}let T=[];if(s.length>0){let{usedItems:x}=hn(e);for(let U of s){if(U.isSideEffect){let oe=U.text.trim(),R=oe.endsWith(";")?oe:`${oe};`;T.push(R);continue}let j=wi(U.text);if(!j)continue;let{defaultName:k,namedItems:z,isTypeOnly:Q,namespaceName:ce}=j,ge=k?x.has(k):!1,ve=ce?x.has(ce):!1;if(j.isImportEquals){if(ge){let oe=U.text.trim();T.push(oe.endsWith(";")?oe:`${oe};`)}else if(t.augmentationImports?.has(j.source)){let oe=an(U.text);if(!oe)throw Error("Cannot locate an augmentation import module literal");T.push(`import ${oe};`)}continue}let we="",be=0;for(let oe=0;oe<z.length;oe++){let R=z[oe];if(x.has(R.name)){if(be>0)we+=", ";if(!Q&&R.isTypeOnly)we+="type ";we+=R.originalName===R.name?R.name:`${R.originalName} as ${R.name}`,be++}}if(ge||ve||be>0){let oe=Q?"import type ":"import ";if(ve&&ce){if(ge&&k)oe+=`${k}, `;oe+=`* as ${ce}`}else if(ge&&k)oe+=be>0?`${k}, { ${we} }`:k;else if(be>0)oe+=`{ ${we} }`;let R=an(U.text);if(!R)throw Error("Cannot locate a grammatical module literal in the import declaration");oe+=` from ${R};`,T.push(oe)}else if(t.augmentationImports?.has(j.source)){let oe=an(U.text);if(!oe)throw Error("Cannot locate an augmentation import module literal");T.push(`import ${oe};`)}}let D=r.length;if(T.length>1){if(Wu!==r)Wu=r,Lu=r.map((z)=>`from '${z}`),Bu=r.map((z)=>`from "${z}`);let U=Lu,j=Bu,k=new Map;for(let z of T){let Q=D;for(let ce=0;ce<r.length;ce++)if(z.includes(U[ce])||z.includes(j[ce])){Q=ce;break}k.set(z,Q)}T.sort((z,Q)=>{let ce=k.get(z),ge=k.get(Q);return ce!==ge?ce-ge:z.localeCompare(Q)})}}for(let x=0;x<T.length;x++){if(n)n+=`
262
+ `;n+=T[x]}for(let x=0;x<a.length;x++){if(n)n+=`
263
+ `;n+=a[x]}let B=[c,l,f,u,d,h,p];for(let x=0;x<B.length;x++){let D=B[x];for(let U=0;U<D.length;U++){let j=D[U],k="",z=j.kind;switch(z){case"function":k=Wl(j,i);break;case"variable":k=ki(j,i);break;case"interface":k=Ll(j,i);break;case"type":k=Bl(j,i);break;case"class":k=jl(j,i);break;case"enum":k=Gl(j,i);break;case"module":case"namespace":k=_l(j,i);break;case"import":case"export":case"unknown":break;default:Fu(z,`Unhandled declaration kind in processor: ${z}`)}if(k){if(n)n+=`
264
+ `;n+=k}}}for(let x=0;x<C.length;x++){if(n)n+=`
265
+ `;n+=C[x]}for(let x=0;x<b.length;x++){if(n)n+=`
266
+ `;n+=b[x]}if(hi(t.sourceCode)&&m.length===0&&(!hi(n)||e.some(ml)))n+=`${n?`
267
+ `:""}export {};`;return n}var Wu=null,Lu,Bu;var Gu=me(()=>{sr();Nu();Xr();sn();Ci();us();Lu=[],Bu=[]});function Ty(e){switch(e){case"strict":return Sy;case"readonly":return xy;case"simplified":return Ay;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 Vu{rules;compiled=[];cache=new Map;constructor(e={rules:[]}){if(this.rules=[],e.includeDefaults!==!1)this.rules.push(...Ey);if(e.presets)for(let t of e.presets)this.rules.push(...Ty(t));this.rules.push(...e.rules),this.rules.sort((t,i)=>(i.priority||0)-(t.priority||0)),this.recompile()}recompile(){let e=Array(this.rules.length);for(let t=0;t<this.rules.length;t++){let i=this.rules[t],r=typeof i.pattern==="string"?new RegExp(i.pattern.replace(ky,"\\$&"),i.global?"g":""):i.pattern;e[t]={rule:i,regex:r}}this.compiled=e}map(e,t={}){let i=!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":""}`,r=this.cache.get(i);if(r!==void 0)return r;let n=e,o=null;for(let s=0;s<this.compiled.length;s++){let{rule:c,regex:l}=this.compiled[s];if(c.condition){if(!o)o={type:e,...t};if(!c.condition(o))continue}if(l.lastIndex=0,l.test(n)){if(l.lastIndex=0,n=n.replace(l,c.replacement),l.lastIndex=0,!c.global)break}}if(this.cache.size>=_u){let s=Math.ceil(_u*0.1),c=0;for(let l of this.cache.keys()){if(c++>=s)break;this.cache.delete(l)}}return this.cache.set(i,n),n}mapAll(e,t={}){return e.map((i)=>this.map(i,{...t,type:i}))}addRule(e){this.rules.push(e),this.rules.sort((t,i)=>(i.priority||0)-(t.priority||0)),this.recompile(),this.cache.clear()}removeRules(e){let t=this.rules.length;return this.rules=this.rules.filter((i)=>{let r=typeof i.pattern==="string"?i.pattern:i.pattern.source;if(e instanceof RegExp)e.lastIndex=0;return typeof e==="string"?r!==e:!e.test(r)}),this.recompile(),this.cache.clear(),t-this.rules.length}clearCache(){this.cache.clear()}getRules(){return this.rules}}function ao(e={rules:[]}){return new Vu(e)}function Uu(e,t,i={}){return e.replace(/:\s*([^;,)\]}]+)/g,(r,n)=>`: ${t.map(n.trim(),i)}`)}var Ey,Sy,xy,Ay,ky,_u=2048,jv,Gv;var Ku=me(()=>{Ey=[{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}],Sy=[{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}],xy=[{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}],Ay=[{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}];ky=/[.*+?^${}()|[\]\\]/g;jv=ao({rules:[]}),Gv=ao({rules:[],presets:["strict"]})});import{availableParallelism as Oy}from"os";import{basename as Hu,dirname as Ry,relative as jt,resolve as Py}from"path";function ba(e){let t=va.get(e);if(!t)t=yn(e),va.set(e,t),t.catch(()=>va.delete(e));return t}async function zu(e,t,i,r,n,o=io){let s=Hu(e)||"output.d.ts",c=jt(Ry(e),t),l=`${s}.map`,f=i.lastIndexOf(`
268
+ ${da()}`),u=f===-1?i:i.slice(0,f),d=du(u,s,c,r),h=`${e}.map`;return await o(h,JSON.stringify(d)),ne.debug(` Generated source map: ${jt(n,h)}`),l}async function $a(e){let t=Date.now(),i={...qf,...e};if(i.logLevel)ds(i.logLevel);else if(i.verbose)ds("debug");let r=new so;if(i.plugins&&i.plugins.length>0){for(let x of i.plugins)r.register(x),ne.debug(`Registered plugin: ${x.name}`);i=await r.runOnStart(i)}if(i.moduleSpecifierMode!==void 0&&i.moduleSpecifierMode!=="preserve"&&i.moduleSpecifierMode!=="node")throw Error("moduleSpecifierMode must be preserve or node");if(await Ca(i),i.isolatedDeclarations===void 0)i.isolatedDeclarations=await cu(i);let n=i.typeMappings?ao(i.typeMappings):void 0,o=null,s={generationMode:i.isolatedDeclarations?"isolated":"semantic",filesProcessed:0,filesGenerated:0,filesFailed:0,filesValidated:0,validationErrors:0,declarationsFound:0,importsProcessed:0,exportsProcessed:0,durationMs:0,errors:[]},c=0;ne.debug("Starting DTS generation..."),ne.debug(`Using ${s.generationMode} declaration generation path`),ne.debug("Config:",i);let l=await Qf(i,()=>ba(i)),f=l.entryFiles,u=[...l.files],{resolver:d,reachability:h}=l;if(qu.set(i,new Set(u)),i.incremental){let x=l.getResolutionFingerprint();if(!i.isolatedDeclarations){let D=new Set(u),U=new Map;for(let k of u){let z=await yt(k);U.set(k,oo(z));for(let Q of vi(z,{includeImports:!0})){let ce=d(Q.specifier,k).resolved;if(ce&&!ce.split(/[/\\]/).includes("node_modules")&&!D.has(ce))D.add(ce),U.set(ce,oo(await yt(ce)))}}let j=[...U].sort(([k],[z])=>k.localeCompare(z));x=JSON.stringify([x,j])}if(o=new Ao(i,x),i.clearCache){if(ne.debug("Clearing build cache..."),!i.dryRun)o.clear()}else if(o.load()){let D=o.getStats();ne.debug(`Loaded build cache with ${D.entries} entries`)}else ne.debug("No existing build cache found, starting fresh");if(!i.dryRun)Ua(i.cwd)}if(o&&!i.dryRun){let x=o.prune(new Set(u),i.cwd);if(x>0)ne.debug(`Pruned ${x} deleted files from cache`)}if(ne.debug(`Found ${u.length} TypeScript files`),i.progress&&u.length>0){let x=i.parallel?"parallel":"sequential";ne.info(`Processing ${u.length} files (${x})...`)}let p=new Map,m=new Map,a=async(x,D,U="lf")=>{m.set(x,{content:D,lineEnding:U})},C=async(x,D)=>{let U;try{let j=qi(x,i),k=async(R)=>{if(!i.diff)return;try{let Ue=await yt(j),K=uu(Ue,R,jt(i.cwd,j));if(K)ne.info(`
269
+ ${K}`);else ne.debug(`[no changes] ${j}`)}catch{ne.info(`[new file] ${jt(i.cwd,j)}`)}},z=(R)=>{if(!i.validate)return 0;let Ue=fu(R,j);if(Ue.isValid)return ne.debug(`[validation] ${j} - OK`),0;ne.warn(`[validation] ${jt(i.cwd,j)} has ${Ue.errors.length} error(s):`);for(let K of Ue.errors){let ee=` Line ${K.line}:${K.column}`;if(K.code)ee+=` [${K.code}]`;if(ee+=` - ${K.message}`,ne.warn(ee),K.suggestion)ne.warn(` Suggestion: ${K.suggestion}`)}return Ue.errors.length},Q=(R)=>{ne.info(`[dry-run] Would generate: ${j}`),ne.debug("--- Content preview ---"),ne.debug(R.slice(0,500)+(R.length>500?`
270
+ ...`:"")),ne.debug("--- End preview ---")};if(o){let R=o.getCachedIfValid(x,i.cwd);if(R){if(i.bundle)p.set(x,R);await k(R);let Ue=z(R);if(i.dryRun)Q(R);else{if(i.declarationMap)U=D??await yt(x),await zu(j,x,R,U,i.cwd,a);await a(j,R,i.lineEnding)}return ne.debug(`[cached] ${jt(i.cwd,j)}`),{success:!0,file:x,declarationCount:0,importCount:0,exportCount:0,cached:!0,validationErrorCount:Ue}}}U=D??await yt(x);let{content:ce,declarationCount:ge,importCount:ve,exportCount:we}=await Dy(x,U,i,r,n,l.augmentationImports.get(x));if(i.bundle)p.set(x,ce);let be=ce;if(i.prettier||i.indentStyle||i.indentSize){let R=await xu(be,{usePrettier:i.prettier,builtIn:{indentSize:i.indentSize||2,useTabs:i.indentStyle==="tabs",normalizeWhitespace:!0,sortImports:!0,trailingNewline:!0}},j);be=R.content;for(let Ue of R.warnings??[])ne.warn(`[format] ${Ue}`)}if(i.declarationMap){let R=`${Hu(j)||"output.d.ts"}.map`;be=hu(be,R)}await k(be);let oe=z(be);if(i.dryRun)Q(be);else{if(i.declarationMap&&U)await zu(j,x,be,U,i.cwd,a);if(await a(j,be,i.lineEnding),o&&U)o.update(x,U,be,i.cwd);ne.debug(`Generated: ${j}`)}return{success:!0,file:x,declarationCount:ge,importCount:ve,exportCount:we,validationErrorCount:oe}}catch(j){let k=$u(j,x,U);if(i.plugins&&i.plugins.length>0)await r.runOnError(j instanceof Error?j:Error(String(j)),x,U||"");return{success:!1,file:x,declarationCount:0,importCount:0,exportCount:0,dtsError:k,validationErrorCount:0}}},b=i.parallel||i.parallel!==!1&&u.length>=10,v=Ha(i.concurrency,Oy?.()??8),T=new Map;if(b&&u.length>1){let x=u.map(async(D)=>{try{let U=await yt(D);return{file:D,source:U}}catch{return{file:D,source:null}}});for(let D of await Promise.all(x))if(D.source!==null)T.set(D.file,D.source)}let B=(x)=>{if(s.filesProcessed++,x.success){if(x.cached)c++;else s.filesGenerated++,s.declarationsFound+=x.declarationCount,s.importsProcessed+=x.importCount,s.exportsProcessed+=x.exportCount;if(i.validate){if(s.filesValidated++,x.validationErrorCount)s.validationErrors+=x.validationErrorCount}}else if(s.filesFailed++,x.dtsError){s.errors.push(x.dtsError);let D=Eu(x.dtsError);if(i.continueOnError)ne.warn(D);else throw ne.error(D),Error(x.dtsError.message)}};if(b)for(let x=0;x<u.length;x+=v){let D=u.slice(x,x+v),U=await Promise.all(D.map((j)=>C(j,T.get(j))));for(let j of U)B(j);if(i.progress){let j=Math.round(s.filesProcessed/u.length*100);ne.info(`[${s.filesProcessed}/${u.length}] ${j}%`)}}else for(let x of u){let D=await C(x);if(B(D),i.progress){let U=Math.round(s.filesProcessed/u.length*100),j=D.cached?"[cached]":"";ne.info(`[${s.filesProcessed}/${u.length}] ${U}% - ${jt(i.cwd,x)} ${j}`)}}if(!i.bundle){let x=[];if(h)for(let D of h.unresolved)x.push({from:D.from,specifier:D.specifier,reason:"missing"});if(i.autoIncludeReExports===!1&&u.length>0){let D=new Set(u);for(let U of u){let j;try{j=await yt(U)}catch{continue}for(let k of vi(j)){let z=d(k.specifier,U);if(!z.isRelative)continue;if(!z.resolved)x.push({from:U,specifier:k.specifier,reason:"missing"});else if(!/\.d\.(?:ts|mts|cts)$/.test(z.resolved)&&!D.has(z.resolved))x.push({from:U,specifier:k.specifier,reason:"not-emitted"})}}}if(x.length>0){let D=[];D.push(`Found ${x.length} re-export(s) pointing at siblings that won't be in the output:`);for(let j of x){let k=jt(i.cwd,j.from);if(j.reason==="missing")D.push(` ${k} \u2192 '${j.specifier}' (path not found on disk)`);else D.push(` ${k} \u2192 '${j.specifier}' (resolved but not in entrypoints; set autoIncludeReExports: true or add to entrypoints)`)}let U=D.join(`
271
+ `);if(i.failOnUnresolvedReExport)throw Error(U);ne.warn(U),ne.warn('Generated .d.ts files reference modules that were not emitted \u2014 consumers will see "has no exported member" errors.')}}if(i.bundle&&(s.filesGenerated>0||c>0)&&f.length>0)try{ne.debug("Bundling declarations...");let x=f.length===1&&!!i.bundleOutput;for(let D of f){let U=await mr([D],{includeImports:!0,resolveSpecifier:d}),j=new Set;for(let ce of U.reachable){if(ce.endsWith(".d.ts"))continue;if(ce.includes("node_modules"))continue;j.add(ce)}let k=u.filter((ce)=>j.has(ce));if(!k.includes(D))k.push(D);let z=yc(D,k,p,{cwd:i.cwd,keepComments:i.keepComments});for(let ce of new Set(z.warnings))ne.warn(`[bundle] ${ce}`);let Q=x?Py(i.cwd,i.outdir,i.bundleOutput):qi(D,i);if(i.dryRun)ne.info(`[dry-run] Would bundle ${z.files.length} files to: ${jt(i.cwd,Q)}`);else await a(Q,z.content,i.lineEnding),ne.debug(`Prepared ${z.files.length} bundled files for: ${jt(i.cwd,Q)}`);if(x)break}}catch(x){let D=x instanceof Error?x.message:String(x);throw ne.error(`Bundle failed: ${D}`),x}if(!i.dryRun)await vu(i,m);if(o&&!i.dryRun)o.save(),ne.debug("Saved build cache");if(s.durationMs=Date.now()-t,i.stats)if(i.outputFormat==="json")console.log(JSON.stringify(s,null,2));else{if(ne.info(`
272
+ --- Generation Statistics ---`),ne.info(`Files processed: ${s.filesProcessed}`),ne.info(`Files generated: ${s.filesGenerated}`),c>0)ne.info(`Files cached: ${c}`);if(s.filesFailed>0)ne.info(`Files failed: ${s.filesFailed}`);if(ne.info(`Declarations found: ${s.declarationsFound}`),ne.info(`Imports processed: ${s.importsProcessed}`),ne.info(`Exports processed: ${s.exportsProcessed}`),s.filesValidated>0){if(ne.info(`Files validated: ${s.filesValidated}`),s.validationErrors>0)ne.info(`Validation errors: ${s.validationErrors}`)}if(ne.info(`Duration: ${s.durationMs}ms`),s.errors.length>0){ne.info(`
273
+ Errors:`);for(let x of s.errors){let D=` - ${x.file}`;if(x.location)D+=`:${x.location.line}:${x.location.column}`;if(x.code)D+=` [${x.code}]`;if(D+=`: ${x.message}`,ne.info(D),x.suggestion)ne.info(` Suggestion: ${x.suggestion}`)}}ne.info(`-----------------------------
274
+ `)}if(i.plugins&&i.plugins.length>0)await r.runOnEnd(s);return ne.debug("DTS generation complete!"),s}async function My(e,t,i){let r=await ba(i),n=eu(t,i,r,qu.get(i));return mc(e,(o)=>n(o).emittedSpecifier)}async function Dy(e,t,i,r,n,o){let s=t;if(r)s=await r.runOnBeforeFile(e,t);let c=new Map;if(!i.isolatedDeclarations){let p=await ba(i);for(let m of vi(s,{includeImports:!0})){let a=p(m.specifier,e).resolved;if(a&&!a.split(/[/\\]/).includes("node_modules"))c.set(m.specifier,await yt(a))}}let l=c.size?Tu(s,c):void 0,f=dn(s,e,i.keepComments,i.isolatedDeclarations??!1,l);if(r)f=await r.runOnDeclarations(e,s,f);let u=0,d=0;for(let p=0;p<f.length;p++){let m=f[p];if(m.kind==="import")u++;if(m.kind==="export"||m.isExported)d++}let h=ju(f,{filePath:e,sourceCode:s,declarations:f,augmentationImports:o},i.keepComments,i.importOrder);if(h=await My(h,e,i),n)h=Uu(h,n,{filePath:e});if(i.normalizeOutput===!0||i.declarationOrder)h=Pu(h,{lineEnding:"lf",declarationOrder:i.declarationOrder,indent:{style:i.indentStyle??"spaces",size:i.indentSize??2}});if(r)h=await r.runOnAfterFile(e,s,h);return{content:h,declarationCount:f.length,importCount:u,exportCount:d}}var va,qu;var Ju=me(()=>{Qi();qa();fs();mn();wn();wc();Ka();Jf();ua();ha();bu();Su();Au();ku();Mu();Du();Gu();Ku();va=new WeakMap,qu=new WeakMap});var Yu=me(()=>{Ju()});import Qu from"process";import{dirname as Iy,relative as Xu,resolve as lo,sep as co}from"path";class ed{listeners=new Map;on(e,t){let i=this.listeners.get(e)||[];i.push(t),this.listeners.set(e,i)}async emit(e,t){let i={type:e,timestamp:Date.now(),data:t},r=this.listeners.get(e)||[];for(let n of r)await n(i)}}function td(e={}){let{onSuccess:t,onError:i,failOnError:r=!0,incremental:n=!1,cacheDir:o=".dtsx-cache",on:s,timeout:c=60000,continueOnError:l=!1,verbose:f=!1,...u}=e,d=new ed;if(s){for(let[h,p]of Object.entries(s))if(p)d.on(h,p)}return{name:"bun-plugin-dtsx",async setup(h){let p=Date.now();try{let m=Wy({...u,incremental:n,cacheDir:o},h);if(m.clean){let T=lo(m.cwd??Qu.cwd(),m.outdir??"./dist");if(Zu.has(T))m.clean=!1;else Zu.add(T)}if(await d.emit("start",{type:"start",files:m.entrypoints||[],config:m}),f){if(console.log("[bun-plugin-dtsx] Starting declaration generation..."),n)console.log("[bun-plugin-dtsx] Incremental mode enabled")}let C=await(async()=>new Promise((T,B)=>{let x=setTimeout(()=>{B(new Or(`Generation timed out after ${c}ms`,"TIMEOUT_ERROR",{timeout:c}))},c);$a(m).then((D)=>{clearTimeout(x),T(D)}).catch((D)=>{clearTimeout(x),B(D)})}))(),b=Date.now()-p,v=Math.max(0,C.filesProcessed-C.filesGenerated-C.filesFailed);if(await d.emit("complete",{type:"complete",stats:C,duration:b,fromCache:v}),f){if(console.log(`[bun-plugin-dtsx] Generation complete in ${b}ms`),v>0)console.log(`[bun-plugin-dtsx] ${v} files served from cache`)}if(t)await t(C)}catch(m){let a=Ny(m);if(await d.emit("error",{type:"error",error:a}),i)await i(a);else{if(console.error("[bun-plugin-dtsx] Error generating declarations:"),console.error(` Code: ${a.code}`),console.error(` Message: ${a.message}`),a.context)console.error(` Context: ${JSON.stringify(a.context)}`);if(f&&a.stack)console.error(` Stack: ${a.stack}`)}if(r&&!l)throw a}}}}function Ny(e){if(e instanceof Or)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 Or(e.message,t,{originalError:e.name},e)}return new Or(String(e),"GENERATION_ERROR")}function Fy(e){let t=e.map((r)=>Iy(r).split(co)),i=t[0];for(let r of t.slice(1)){let n=0;while(n<i.length&&n<r.length&&i[n]===r[n])n++;i=i.slice(0,n)}return i.join(co)||co}function Wy(e,t){let i=e.cwd||Qu.cwd(),r=t?.config?.entrypoints,n=e.outdir||e.build?.config.outdir||t?.config.outdir||"./dist",o=e.root||e.build?.config.root||t?.config.root;if(!o&&r?.length){let c=Fy(r.map((l)=>lo(i,l)));o=Xu(i,c)||"."}o=o||"./src";let s=e.entrypoints;if(!s)if(r?.length){let c=lo(i,o),l=[];for(let f of r){let u=lo(i,f);if(u===c||u.startsWith(c+co))l.push(Xu(c,u));else console.warn(`[bun-plugin-dtsx] Skipping entrypoint outside root "${o}": ${f}`)}s=l.length?l:["index.ts"]}else s=["index.ts"];return{...e,cwd:i,root:o,entrypoints:s,outdir:n,clean:e.clean??!0,tsconfigPath:e.tsconfigPath,moduleSpecifierMode:e.moduleSpecifierMode??((t?.config.target??e.build?.config.target)==="node"?"node":"preserve")}}var Or,Zu;var id=me(()=>{Yu();Or=class Or extends Error{code;context;cause;constructor(e,t,i,r){super(e);if(this.name="DtsxPluginError",this.code=t,this.context=i,this.cause=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,context:this.context,stack:this.stack}}};Zu=new Set});import{mkdir as Ly,stat as By}from"fs/promises";import{bold as Ea,dim as Sa,green as jy,italic as rd,log as Gy}from"@stacksjs/cli";import{path as bt}from"@stacksjs/path";import{glob as nd}from"@stacksjs/storage";function vo(e){let t=new Map;for(let s of e){if(t.has(s.name))throw Error(`duplicate package name: ${s.name}`);t.set(s.name,s)}let i=new Map,r=new Set,n=(s,c)=>{let l=i.get(s);if(l!==void 0)return l;if(r.has(s))throw Error(`dependency cycle: ${[...c,s].join(" -> ")}`);r.add(s);let f=t.get(s).dependencies.filter((d)=>d!==s&&t.has(d)),u=f.length?1+Math.max(...f.map((d)=>n(d,[...c,s]))):0;return r.delete(s),i.set(s,u),u},o=[];for(let s of[...e].sort((c,l)=>c.name.localeCompare(l.name)))(o[n(s.name,[])]||=[]).push(s);return o.filter(Boolean)}import{existsSync as gd,readdirSync as yd,readFileSync as La}from"fs";import{join as bo}from"path";function wd(e){return[...yd(e,{withFileTypes:!0}).filter((i)=>i.isDirectory()).map((i)=>bo(e,i.name)),e].filter((i)=>{let r=bo(i,"package.json");if(!gd(r))return!1;let n=JSON.parse(La(r,"utf8"));return!n.private&&!!n.scripts?.build})}async function Cd(e){let t=e.map((n)=>{let o=JSON.parse(La(bo(n,"package.json"),"utf8"));if(!o.name||!o.scripts?.build)throw Error(`Not a buildable workspace package: ${n}`);return{name:o.name,dir:n,dependencies:Object.keys(o.dependencies??{})}}),i=vo(t),r=[];for(let{name:n,dir:o,dependencies:s}of i.flat()){let c=r.filter((f)=>f.exitCode!==0&&s.includes(f.name)).map((f)=>f.name);if(c.length){console.error(`Cannot build ${o}: dependencies failed: ${c.join(", ")}`),r.push({name:n,dir:o,exitCode:null,blockedBy:c});continue}console.log(`Building ${o}`);let l=Bun.spawn([process.execPath,"run","build"],{cwd:o,stdout:"inherit",stderr:"inherit"});r.push({name:n,dir:o,exitCode:await l.exited,blockedBy:[]})}return r}async function _y(e){let t=await nd([bt.resolve(e,"dist","**/*.d.ts")],{absolute:!0}),i=new Bun.Transpiler({loader:"ts",target:"bun"});for(let r of t){let n=await Bun.file(r).text();try{i.transformSync(n)}catch(o){throw Error(`Invalid declaration generated at ${r}: ${o instanceof Error?o.message:String(o)}`)}}}async function Vy(e){let t=bt.resolve(e,"dist","index.js");if(!await Bun.file(t).exists())return;let i=Bun.spawnSync({cmd:[process.execPath,"-e",`try { await import(${JSON.stringify(t)}) } catch (error) { console.error(error); process.exit(1) }`],stdout:"ignore",stderr:"pipe",env:{...process.env,NODE_ENV:"test"}});if(i.exitCode===0)return;let r=new TextDecoder().decode(i.stderr??new Uint8Array),n=/SyntaxError|needs to refer to a top-level declared variable|does not provide an export named|Export named .* not found/i;if(n.test(r)){let o=r.split(`
275
+ `).find((s)=>n.test(s))??r.trim().split(`
255
276
  `)[0];throw Error(`Built package at ${t} cannot be imported: ${o}
256
- Fix the generated module at its source before publishing.`)}}async function GC(e){let r=Date.now()-e.startTime,n=e.pkgName??`@stacksjs/${ot.basename(e.dir)}`;if(e.result.errors&&e.result.errors.length>0)throw console.error("Build errors:",e.result.errors),Error(`Build failed with errors: ${JSON.stringify(e.result.errors)}`);else if(e.result.success!==void 0&&!e.result.success){let o=e.result.logs?.[0]||"Unknown build error";throw console.log(o),Error(`Build failed: ${o}`)}await Bun.write(ot.resolve(e.dir,"dist","tsconfig.json"),`${JSON.stringify({compilerOptions:{paths:{}}},null,2)}
257
- `),await Mp(e.dir),await Dp(e.dir);let i=await Yc([ot.resolve(e.dir,"dist","**/*")],{absolute:!0});for(let o of i){let s=await Rp(o),a;if(s.size<1048576)a=`${(s.size/1024).toFixed(2)}kb`;else a=`${(s.size/1024/1024).toFixed(2)}mb`;let c=ot.relative(e.dir,o).replace("dist/","");console.log(`${Yo(Zo(`[${a}]`))} ${Zo("dist/")}${c}`)}console.log(`${Yo(Zo(`[${r}ms]`))} Built ${qc(Yo(Pp(n)))}`)}async function jC(e){let t=e.pkgName??`@stacksjs/${ot.basename(e.dir)}`;if(e.styled===!1)console.log(`Building ${t}...`);else kp.info(`Building ${qc(t)}...`);return{startTime:Date.now()}}async function _C(e){await Promise.resolve().then(() => Jc());let r=ot.resolve(e.dir,"src"),n=ot.resolve(e.dir,"dist"),i=(await Array.fromAsync(new Bun.Glob("**/*.ts").scan({cwd:r}))).filter((s)=>!s.endsWith(".d.ts")).filter((s)=>!s.endsWith(".test.ts")&&!s.endsWith(".spec.ts")).filter((s)=>!s.split(/[\\/]/).some((a)=>a==="tests"||a==="__tests__"));await Bun.build({entrypoints:i.map((s)=>ot.resolve(r,s)),outdir:n,root:r,target:"bun",format:"esm",splitting:!1,external:e.external??Fp(),plugins:[zc({root:r,outdir:n})]});let o=new Bun.Transpiler({loader:"ts",target:"browser",minifyWhitespace:!0,define:{"process.env.NODE_ENV":"process.env.NODE_ENV"}});for(let s of i){let a=o.transformSync(await Bun.file(ot.resolve(r,s)).text());a=Ip(a);let c=ot.resolve(n,s.replace(/\.ts$/,".js"));await Op(ot.dirname(c),{recursive:!0}),await Bun.write(c,a)}}function Ip(e){return e.replace(/(['"])(\.\.?\/[^'"]+?)(?<!\.d)\.tsx?\1/g,"$1$2.js$1")}function Fp(e=[]){let t=[];try{let r=lf("fs"),n=JSON.parse(r.readFileSync(`${process.cwd()}/package.json`,"utf8"));t=[...Object.keys(n.dependencies??{}),...Object.keys(n.peerDependencies??{}),...Object.keys(n.optionalDependencies??{})]}catch{}return["@stacksjs/*",...t,...t.map((r)=>`${r}/*`),"bun-queue","ioredis","localtunnels","localtunnels/*","@craft-native/ts","ts-md","meilisearch","algoliasearch","@opensearch-project/opensearch","*.yaml","*.yml",...e]}export{hf as buildWorkspacePackages,ln as dependencyLayers,Fp as frameworkExternal,jC as intro,GC as outro,Ip as rewriteRelativeTsSpecifiers,_C as transpilePackage,Mp as validateDeclarations,Dp as validateRuntimeExports,uf as workspaceBuildTargets};
277
+ Fix the generated module at its source before publishing.`)}}async function Ob(e){let i=Date.now()-e.startTime,r=e.pkgName??`@stacksjs/${bt.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 o=e.result.logs?.[0]||"Unknown build error";throw console.log(o),Error(`Build failed: ${o}`)}await Bun.write(bt.resolve(e.dir,"dist","tsconfig.json"),`${JSON.stringify({compilerOptions:{paths:{}}},null,2)}
278
+ `),await _y(e.dir),await Vy(e.dir);let n=await nd([bt.resolve(e.dir,"dist","**/*")],{absolute:!0});for(let o of n){let s=await By(o),c;if(s.size<1048576)c=`${(s.size/1024).toFixed(2)}kb`;else c=`${(s.size/1024/1024).toFixed(2)}mb`;let l=bt.relative(e.dir,o).replace("dist/","");console.log(`${Ea(Sa(`[${c}]`))} ${Sa("dist/")}${l}`)}console.log(`${Ea(Sa(`[${i}ms]`))} Built ${rd(Ea(jy(r)))}`)}async function Rb(e){let t=e.pkgName??`@stacksjs/${bt.basename(e.dir)}`;if(e.styled===!1)console.log(`Building ${t}...`);else Gy.info(`Building ${rd(t)}...`);return{startTime:Date.now()}}async function Pb(e){await Promise.resolve().then(() => id());let i=bt.resolve(e.dir,"src"),r=bt.resolve(e.dir,"dist"),n=(await Array.fromAsync(new Bun.Glob("**/*.ts").scan({cwd:i}))).filter((s)=>!s.endsWith(".d.ts")).filter((s)=>!s.endsWith(".test.ts")&&!s.endsWith(".spec.ts")).filter((s)=>!s.split(/[\\/]/).some((c)=>c==="tests"||c==="__tests__"));await Bun.build({entrypoints:n.map((s)=>bt.resolve(i,s)),outdir:r,root:i,target:"bun",format:"esm",splitting:!1,external:e.external??Ky(),plugins:[td({root:i,outdir:r})]});let o=new Bun.Transpiler({loader:"ts",target:"browser",minifyWhitespace:!0,define:{"process.env.NODE_ENV":"process.env.NODE_ENV"}});for(let s of n){let c=o.transformSync(await Bun.file(bt.resolve(i,s)).text());c=Uy(c);let l=bt.resolve(r,s.replace(/\.ts$/,".js"));await Ly(bt.dirname(l),{recursive:!0}),await Bun.write(l,c)}}function Uy(e){return e.replace(/(['"])(\.\.?\/[^'"]+?)(?<!\.d)\.tsx?\1/g,"$1$2.js$1")}function Ky(e=[]){let t=[];try{let i=md("fs"),r=JSON.parse(i.readFileSync(`${process.cwd()}/package.json`,"utf8"));t=[...Object.keys(r.dependencies??{}),...Object.keys(r.peerDependencies??{}),...Object.keys(r.optionalDependencies??{})]}catch{}return["@stacksjs/*",...t,...t.map((i)=>`${i}/*`),"bun-queue","ioredis","localtunnels","localtunnels/*","@craft-native/ts","ts-md","meilisearch","algoliasearch","@opensearch-project/opensearch","*.yaml","*.yml",...e]}export{Cd as buildWorkspacePackages,vo as dependencyLayers,Ky as frameworkExternal,Rb as intro,Ob as outro,Uy as rewriteRelativeTsSpecifiers,Pb as transpilePackage,_y as validateDeclarations,Vy as validateRuntimeExports,wd as workspaceBuildTargets};