@stacksjs/build 0.75.450 → 0.75.452
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +209 -209
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,228 +1,185 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var de=(e,t,
|
|
3
|
-
`,
|
|
4
|
-
`,f+2);f=m===-1?e.length:m+1;continue}if(a===47&&e.charCodeAt(f+1)===42){let m=e.indexOf("*/",f+2);f=m===-1?e.length:m+2;continue}if(a===39||a===34){let m=a;f++;while(f<e.length){let y=e.charCodeAt(f++);if(y===92)f++;else if(y===m)break}u("literal");continue}if(a===96){
|
|
5
|
-
`;
|
|
6
|
-
`||u==="\r"?u:" ":u;continue}if(c===
|
|
7
|
-
`||e[
|
|
2
|
+
var de=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};var sf=import.meta.require;import{readFile as ff,stat as Lm,writeFile as uf}from"fs/promises";async function lo(e,t){if(Gr)return globalThis.Bun.write(e,t);let r=typeof t==="string"?t:t instanceof ArrayBuffer?Buffer.from(t):t;return await uf(e,r),typeof t==="string"?Buffer.byteLength(t):t.byteLength}async function Rt(e){if(Gr)return globalThis.Bun.file(e).text();return ff(e,"utf-8")}var Gr,Gm;var Br=de(()=>{Gr=typeof globalThis.Bun<"u",Gm=!Gr&&typeof process<"u"&&!!process.versions?.node});function jt(e){return co[e]>=co[_r]}function pf(){if(!df)return"";return`[${new Date().toISOString().slice(11,23)}] `}function mf(e,t){let r=pf();if(e||r)return[`${r}${e}`,...t];return t}function Kt(e,t,r){let n=mf(t,r);if(fo){fo(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 uo(e){return{debug:(...t)=>{if(jt("debug"))Kt("debug",e,t)},info:(...t)=>{if(jt("info"))Kt("info",e,t)},warn:(...t)=>{if(jt("warn"))Kt("warn",e,t)},error:(...t)=>{if(jt("error"))Kt("error",e,t)},setLevel:(t)=>{_r=t},getLevel:()=>_r,child:(t)=>{let r=e?`${e}:${t}`:`[${t}]`;return uo(r)},time:(t)=>{let r=performance.now();return()=>{let n=performance.now()-r;if(jt("debug"))Kt("debug",e,[`${t}: ${n.toFixed(2)}ms`])}},progress:(t)=>{if(jt("info"))if(typeof process<"u"&&process.stdout?.isTTY)process.stdout.write(`\r${e} ${t}`);else Kt("info",e,[t])}}}function cn(e){_r=e}var co,_r="info",hf="[dtsx]",df=!1,fo=null,q;var fn=de(()=>{co={debug:0,info:1,warn:2,error:3,silent:4};q=uo(hf)});function gt(e){return e>=65&&e<=90||e>=97&&e<=122||e===95||e===36||e>127}function Ve(e){return gt(e)||e>=48&&e<=57}function ho(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 s=e.lastIndexOf("/*",r-2);if(s===-1)return-1;r=s-1;continue}let n=e.lastIndexOf(`
|
|
3
|
+
`,r)+1,i=gf(e,n,r);if(i!==-1){r=i-1;continue}return r}}function gf(e,t,r){let n=0;for(let i=t;i<=r;i++){let s=e.charCodeAt(i);if(n){if(s===92){i++;continue}if(s===n)n=0;continue}if(s===39||s===34||s===96){n=s;continue}if(s===47&&i+1<=r&&e.charCodeAt(i+1)===47)return i}return-1}function po(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 mo(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 yf(e,t){let r=[],n=[],i=0,s=!1,o="",l="",c=!0,f=0,u=(a,m=!1)=>{l=o,o=a,c=m};while(f<=t){let a=e.charCodeAt(f);if(s){if(a===92){f+=2;continue}if(a===96)s=!1,u("literal");else if(a===36&&e.charCodeAt(f+1)===123)n.push(i++),s=!1,u("{",!0),f++;f++;continue}if(a===32||a===9||a===10||a===13){f++;continue}if(a===47&&e.charCodeAt(f+1)===47){let m=e.indexOf(`
|
|
4
|
+
`,f+2);f=m===-1?e.length:m+1;continue}if(a===47&&e.charCodeAt(f+1)===42){let m=e.indexOf("*/",f+2);f=m===-1?e.length:m+2;continue}if(a===39||a===34){let m=a;f++;while(f<e.length){let y=e.charCodeAt(f++);if(y===92)f++;else if(y===m)break}u("literal");continue}if(a===96){s=!0,f++;continue}if(gt(a)||a===35&>(e.charCodeAt(f+1))){let m=f++;while(Ve(e.charCodeAt(f)))f++;let y=e.slice(m,f);u(y,o!=="."&&mo(y));continue}if(a===40){let m=l!=="."&&(o==="if"||o==="while"||o==="for"||o==="with"||o==="switch"||o==="catch"||o==="await"&&l==="for");r.push(m),u("(",!0)}else if(a===41){let m=r.pop()??!1;if(f===t)return m;u(")",m)}else if(a===47&&c){f=pr(e,f),u("literal");continue}else{if(a===123)i++;else if(a===125){if(i--,n.at(-1)===i)n.pop(),s=!0}u(e[f],a===47||po(a))}f++}return!1}function Ur(e,t){let r=ho(e,t-1);if(r<0)return!0;let n=e.charCodeAt(r);if(n===41)return yf(e,r);if(po(n))return!0;if(Ve(n)){let i=r;while(i>=0&&Ve(e.charCodeAt(i)))i--;let s=e.charCodeAt(ho(e,i));if(s===46||s===35)return!1;return mo(e.slice(i+1,r+1))}return!1}function pr(e,t){let r=t,n=e.length;r++;let i=!1;while(r<n){let s=e.charCodeAt(r);if(s===92){r+=2;continue}if(i){if(s===93)i=!1;r++;continue}if(s===91){i=!0,r++;continue}if(s===47){r++;break}if(s===10||s===13)break;r++}while(r<n&&Ve(e.charCodeAt(r)))r++;return r}var un=()=>{};function go(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 s=r+1;while(s<e.length){while(s<e.length&&e.charCodeAt(s)<=32)s++;if(e.charCodeAt(s)===47&&e.charCodeAt(s+1)===47){s+=2;while(s<e.length&&e.charCodeAt(s)!==10&&e.charCodeAt(s)!==13)s++;continue}if(e.charCodeAt(s)===47&&e.charCodeAt(s+1)===42){s+=2;while(s+1<e.length&&!(e.charCodeAt(s)===42&&e.charCodeAt(s+1)===47))s++;s=Math.min(s+2,e.length);continue}break}let o=e.charCodeAt(s);if(o===93||o===125){r++;continue}}t+=e[r++]}return t}var yo=()=>{};import{readFileSync as Cf,statSync as wf}from"fs";import{readFile as $f}from"fs/promises";import{createRequire as vf}from"module";import{dirname as mr,isAbsolute as bf,join as hn,resolve as dn}from"path";function Zt(e){let t=[e];if(!e.endsWith(".json"))t.push(`${e}.json`);t.push(hn(e,"tsconfig.json"));for(let r of t)try{if(wf(r).isFile())return r}catch{}return null}function Ef(e,t){if(bf(e)||e.startsWith("."))return Zt(dn(mr(t),e));let r=vf(t),n=e.startsWith("@")?/^@[^/]+\/[^/]+/.exec(e)?.[0]:e.split("/")[0];if(n)for(let i of r.resolve.paths(n)??[]){let s=Zt(hn(i,n,"package.json"));if(!s)continue;let o=JSON.parse(Cf(s,"utf8"));if(e===n){if(o.tsconfig!==void 0){if(typeof o.tsconfig!=="string")throw Error(`Invalid tsconfig field in ${s}`);let c=Zt(dn(mr(s),o.tsconfig));if(!c)throw Error(`Cannot resolve tsconfig ${JSON.stringify(o.tsconfig)} from ${s}`);return c}let l=Zt(hn(mr(s),"tsconfig.json"));if(l)return l}break}for(let i of[`${e}/tsconfig.json`,e])try{let s=r.resolve(i),o=s.endsWith(".json")?Zt(s):null;if(o)return o}catch{}return null}async function gr(e,t={},r=new Set){let n=Zt(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),s=JSON.parse(go(await $f(n,"utf8"))),o=typeof s.extends==="string"?[s.extends]:s.extends??[];if(!Array.isArray(o)||o.some((f)=>typeof f!=="string"))throw Error(`Invalid tsconfig extends in ${n}`);let l={};for(let f of o){let u=Ef(f,n);if(!u)throw Error(`Cannot resolve tsconfig extends ${JSON.stringify(f)} from ${n}`);l={...l,...await gr(u,t,i)}}let c=s.compilerOptions??{};if(c.isolatedDeclarations!==void 0)l.isolatedDeclarations=c.isolatedDeclarations;if(c.baseUrl!==void 0){if(typeof c.baseUrl!=="string")throw Error(`Invalid baseUrl in ${n}`);l.baseUrl=dn(mr(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((a)=>typeof a!=="string"||a.split("*").length>2))throw Error(`Invalid path mapping ${JSON.stringify(f)} in ${n}`);l.paths=c.paths,l.pathsBasePath=mr(n)}return l}var pn=de(()=>{yo()});import{existsSync as gn,readFileSync as Co,realpathSync as yr,statSync as Sf}from"fs";import{builtinModules as Af}from"module";import{dirname as yn,extname as xf,isAbsolute as Cn,join as So,relative as Ao,resolve as Yt}from"path";function Vr(e){try{return Sf(e).isFile()}catch{return!1}}function Jt(e,t){let r=e.replace(/[?#].*$/,"");if(!(r.startsWith("./")||r.startsWith("../")||r==="."||r==="..")&&!Cn(r))return{resolved:null,isRelative:!1};let n=yn(t),i=Yt(n,r);if(Vr(i))return{resolved:i,isRelative:!0};let s=xf(i),o=Tf[s];if(o){let l=i.slice(0,-s.length);for(let c of o){let f=l+c;if(Vr(f))return{resolved:f,isRelative:!0}}}for(let l of wo){let c=i+l;if(Vr(c))return{resolved:c,isRelative:!0}}if(gn(i))for(let l of wo){let c=So(i,`index${l}`);if(Vr(c))return{resolved:c,isRelative:!0}}return{resolved:null,isRelative:!0}}function xo(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 To(e,t){if(Object.hasOwn(e,t))return e[t]!==null;let r=Object.keys(e).filter((n)=>n.includes("*")&&xo(n,t)).sort((n,i)=>i.indexOf("*")-n.indexOf("*")||i.length-n.length)[0];return r!==void 0&&e[r]!==null}function $o(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 To(n,r)}function mn(e,t){let r=Ao(e,t);return r!==".."&&!r.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!Cn(r)}async function Oo(e){let t=await gr(Yt(e.cwd,e.tsconfigPath||"tsconfig.json")),r=Object.entries(t?.paths??{});if(r.length===0)return Jt;let n=t?.baseUrl??t?.pathsBasePath??e.cwd,i=Yt(e.cwd,e.root),s=new Map,o=new Set([...Af,"bun"]),l=(f)=>{let u=yn(f),a=[];while(!0){if(s.has(u)){let w=s.get(u);for(let C of a)s.set(C,w);return w}a.push(u);let m=So(u,"package.json");if(gn(m)){let w={...JSON.parse(Co(m,"utf8")),directory:yr(u)};for(let C of a)s.set(C,w);return w}let y=yn(u);if(y===u)return;u=y}},c=(f,u)=>{if(f.startsWith(".")||Cn(f))return Jt(f,u);if(f.startsWith("node:")||f.startsWith("bun:")||o.has(f))return{resolved:null,isRelative:!1};let a=l(u),m=f.startsWith("@")?/^@[^/]+\/[^/]+/.exec(f)?.[0]:f.split("/")[0];if(a&&($o(a,f)||To(a.imports??{},f)||m&&[a.dependencies,a.devDependencies,a.peerDependencies,a.optionalDependencies].some((L)=>Object.hasOwn(L??{},m))))return{resolved:null,isRelative:!1};let y=r.filter(([L])=>xo(L,f)).sort(([L],[G])=>{if(!L.includes("*"))return-1;if(!G.includes("*"))return 1;return G.indexOf("*")-L.indexOf("*")})[0];if(!y)return{resolved:null,isRelative:!1};let[w,C]=y,x=w.indexOf("*"),k=x===-1?"":f.slice(x,f.length-(w.length-x-1));for(let L of C){let G=Yt(n,L.replace("*",k)),T=l(G);if(T&&$o(T,f)&&!T.private&&T.directory!==a?.directory)return{resolved:null,isRelative:!1};let D=Jt(G,u);if(!D.resolved)continue;let F=yr(D.resolved),N=e.outputStructure==="flat"||gn(i)&&mn(yr(i),F);if(!a||!mn(a.directory,F)||!N||l(F)?.directory!==a.directory||/\.d\.(?:ts|mts|cts)$/.test(F))throw Error(`Local alias ${JSON.stringify(f)} from ${u} resolves outside its emitted package source: ${F}`);return q.debug(`Resolved local declaration alias ${f} from ${u} to ${F}`),{resolved:e.outputStructure==="flat"?D.resolved:Yt(i,Ao(yr(i),F)),isRelative:!0,isAlias:!0,suffix:G.match(/[?#].*$/)?.[0]??""}}throw Error(`Cannot resolve local alias ${JSON.stringify(f)} from ${u} using ${e.tsconfigPath||"tsconfig.json"} (${JSON.stringify(w)})`)};return c.isPackageLocal=(f,u)=>{let a=l(f);return!!a&&l(u)?.directory===a.directory&&mn(a.directory,yr(u))},c.cacheKey=(f)=>{let u=f.map((m)=>({file:m,references:Hr(Co(m,"utf8"),{includeImports:!0}).map((y)=>({specifier:y.specifier,resolution:c(y.specifier,m)}))})),a=[...new Set(s.values())].filter((m)=>m!==void 0).sort((m,y)=>m.directory.localeCompare(y.directory));return JSON.stringify({root:i,compilerOptions:t,packages:a,edges:u})},c}function Ro(e,t=[]){let r=e.length,n="",i=0;while(i<r){let s=e.charCodeAt(i);if(s===34||s===39||s===96){let o=s,l=i;n+=e[i++];while(i<r){let c=e.charCodeAt(i),f=e[i++];if(n+=o===96&&c!==o?c===10||c===13?f:" ":f,c===92&&i<r){let u=e[i++];n+=o===96?u===`
|
|
6
|
+
`||u==="\r"?u:" ":u;continue}if(c===o)break}t.push({start:l,end:i});continue}if(s===47&&i+1<r){let o=e.charCodeAt(i+1);if(o===47){n+=" ",i+=2;while(i<r&&e.charCodeAt(i)!==10)n+=" ",i++;continue}if(o===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(Ur(e,i)){let l=pr(e,i);n+=e.slice(i,l).replace(/[^\r\n]/g," "),i=l;continue}}n+=e[i++]}return n}function Hr(e,t={}){let r=[],n=[],i=Ro(e,n),s=(l)=>n.some((c)=>l>c.start&&l<c.end);vo.lastIndex=0;let o;while((o=vo.exec(i))!==null){if(s(o.index))continue;let l=!!o[1],c=o[3],f=o[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:l})}if(t.includeImports){Eo.lastIndex=0;while((o=Eo.exec(i))!==null){if(s(o.index))continue;r.push({specifier:o[3],kind:"import",isTypeOnly:!!o[1]})}}if(t.includeImports){bo.lastIndex=0;while((o=bo.exec(i))!==null)if(!s(o.index))r.push({specifier:o[2],kind:"import",isTypeOnly:!1})}return r}function Po(e,t){let r=[],n=Ro(e,r),i=/\b(?:from\s*|import\s*(?:\(\s*)?)(['"])([^'"]+)\1/g,s=[],o;while((o=i.exec(n))!==null){if(r.some((u)=>o.index>u.start&&o.index<u.end))continue;let c=o.index+o[0].lastIndexOf(`${o[1]}${o[2]}${o[1]}`)+1,f=t(o[2]);if(f!==o[2])s.push({start:c,end:c+o[2].length,value:f})}let l=e;for(let c of s.reverse())l=l.slice(0,c.start)+c.value+l.slice(c.end);return l}async function wn(e,t={}){let r=new Set,n=new Map,i=[],s=[];for(let o of e){let l=Yt(o);if(!r.has(l))r.add(l),s.push(l)}while(s.length>0){let o=s.shift(),l;try{l=await Rt(o)}catch{continue}let c=Hr(l,t);n.set(o,c);for(let f of c){let u=(t.resolveSpecifier??Jt)(f.specifier,o);if(!u.isRelative)continue;if(u.resolved){if(!r.has(u.resolved))r.add(u.resolved),s.push(u.resolved)}else i.push({from:o,specifier:f.specifier,isTypeOnly:f.isTypeOnly})}}return{reachable:r,reExports:n,unresolved:i}}var wo,Tf,vo,bo,Eo;var $n=de(()=>{Br();fn();un();pn();wo=[".ts",".tsx",".mts",".cts",".vue",".stx",".js",".jsx",".mjs",".cjs",".d.ts",".d.mts",".d.cts"],Tf={".js":[".ts",".tsx",".d.ts"],".jsx":[".tsx",".ts",".d.ts"],".mjs":[".mts",".d.mts"],".cjs":[".cts",".d.cts"]};vo=/(?:^|[\n;{}])\s*export\s+(type\s+)?(?:\*(?:\s+as\s+\w+)?|\{[^}]*\})\s+from\s+(['"])([^'"]+)\2/g,bo=/\bimport\s*\(\s*(['"])([^'"]+)\1/g,Eo=/(?:^|[\n;{}])\s*import\s+(type\s+)?(?:[^'";]+?\s+from\s+)?(['"])([^'"]+)\2/g});import{relative as Nt}from"path";function Of(e){let t=[],r=[],n=0,i=0,s=[],o=!1,l=0,c=e.length,f=(u)=>{let a=e.slice(n,u).trim();if(n=u,!a)return;if(Rf(a)){r.push(a);return}t.push({text:a,comments:r}),r=[]};while(l<c){let u=e[l];if(o){if(u==="\\"){l+=2;continue}if(u==="`"){o=!1,l++;continue}if(u==="$"&&e[l+1]==="{"){s.push(i),i++,o=!1,l+=2;continue}l++;continue}if(u==="/"&&e[l+1]==="*"){let a=e.indexOf("*/",l+2);l=a===-1?c:a+2;continue}if(u==="/"&&e[l+1]==="/"){let a=e.indexOf(`
|
|
8
8
|
`,l);l=a===-1?c:a;continue}if(u==="'"||u==='"'){l++;while(l<c&&e[l]!==u&&e[l]!==`
|
|
9
|
-
`){if(e[l]==="\\")l++;l++}l++;continue}if(u==="`"){
|
|
10
|
-
`){let a=e[l+1];if(a!==void 0&&/[\w$@/]/.test(a))f(l+1);l++;continue}l++}return f(c),t}function Rf(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
|
|
11
|
-
`,t);t=
|
|
12
|
-
`).map((f)=>f.trim()).filter((f)=>f.startsWith("///"))),!1;return!0});let
|
|
13
|
-
`;while(n<
|
|
14
|
-
`,n),c=l===-1?
|
|
15
|
-
`){if(e[l]==="\\")l++;l++}
|
|
16
|
-
`||!/\s/.test(
|
|
17
|
-
export { ${
|
|
18
|
-
}`),
|
|
19
|
-
${
|
|
20
|
-
`)}`)}let he=
|
|
9
|
+
`){if(e[l]==="\\")l++;l++}l++;continue}if(u==="`"){o=!0,l++;continue}if(u==="("||u==="["||u==="{"){i++,l++;continue}if(u===")"||u==="]"||u==="}"){if(i--,s.length>0&&u==="}"&&i===s[s.length-1])s.pop(),o=!0;l++;continue}if(i===0&&u===";"){f(l+1),l++;continue}if(i===0&&u===`
|
|
10
|
+
`){let a=e[l+1];if(a!==void 0&&/[\w$@/]/.test(a))f(l+1);l++;continue}l++}return f(c),t}function Rf(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 vn(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 Pf(e){let t={named:[]},r=e.trim().replace(/^type\s+/,""),n=r.match(/\{([\s\S]*)\}/);if(n){for(let o of vn(n[1]))t.named.push({imported:o.local,local:o.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 s=r.replace(/,/g,"").trim();if(s&&Mo.test(s))t.defaultName=s;return t}function Mf(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,s)=>`${s.trimEnd()} ${t}`);if(/^(?:interface|type)\b/.test(r)||/^declare\b/.test(r))return r;return`declare ${r}`}function Df(e,t){let r={file:e,declarations:[],declared:new Set,imports:new Map,localExports:new Map,namedReExports:[],starReExports:[],namespaceReExports:[],verbatim:[],directives:[]},n=Of(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 s=i.text.replace(/;\s*$/,"").trim(),o=s.match(/^import\s+(type\s+)?([\s\S]+?)\s+from\s+(['"])([^'"]+)\3/);if(o){let c=Pf(o[2]),f=o[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(s)){r.verbatim.push(i);continue}if(o=s.match(/^export\s+(?:type\s+)?\*\s+as\s+([\w$]+)\s+from\s+(['"])([^'"]+)\2/),o){r.namespaceReExports.push({specifier:o[3],exported:o[1]});continue}if(o=s.match(/^export\s+(?:type\s+)?\*\s+from\s+(['"])([^'"]+)\1/),o){r.starReExports.push(o[2]);continue}if(o=s.match(/^export\s+(?:type\s+)?\{([\s\S]*)\}\s+from\s+(['"])([^'"]+)\2/),o){for(let c of vn(o[1]))r.namedReExports.push({specifier:o[3],imported:c.local,exported:c.exported});continue}if(o=s.match(/^export\s+(?:type\s+)?\{([\s\S]*)\}$/),o){for(let c of vn(o[1]))r.localExports.set(c.exported,c.local);continue}if(o=s.match(/^export\s+default\s+([\w$]+)$/),o&&Mo.test(o[1])){r.localExports.set("default",o[1]);continue}if(/^export\s+as\s+namespace\b/.test(s)||/^(?:export\s+)?declare\s+(?:global\b|module\s+['"])/.test(s)){r.verbatim.push(i);continue}let l=s.match(kf);if(l){let c=!!l[1],f=l[4]??(c?"_default":null);if(f){if(r.declared.add(f),/^export\s/.test(s))r.localExports.set(c?"default":f,f);r.declarations.push({statement:i,name:f,emit:Mf(i.text,f)});continue}}r.declarations.push({statement:i,name:null,emit:i.text})}return r}function ko(e,t){if(t.size===0)return e;let r="",n=0,i=e.length,s=`
|
|
13
|
+
`;while(n<i){let o=e[n];if(o==="/"&&e[n+1]==="*"){let l=e.indexOf("*/",n+2),c=l===-1?i:l+2;r+=e.slice(n,c),n=c;continue}if(o==="/"&&e[n+1]==="/"){let l=e.indexOf(`
|
|
14
|
+
`,n),c=l===-1?i:l;r+=e.slice(n,c),n=c;continue}if(o==="'"||o==='"'){let l=n+1;while(l<i&&e[l]!==o&&e[l]!==`
|
|
15
|
+
`){if(e[l]==="\\")l++;l++}r+=e.slice(n,l+1),n=l+1,s=o;continue}if(/[A-Z_$]/i.test(o)){let l=n+1;while(l<i&&/[\w$]/.test(e[l]))l++;let c=e.slice(n,l),f=t.get(c);if(f!==void 0&&s!=="."){let u=l;while(u<i&&(e[u]===" "||e[u]==="\t"))u++;let a=(e[u]===":"||e[u]==="?"&&e[u+1]===":")&&/[{;,(\n]/.test(s);r+=a?c:f}else r+=c;s="a",n=l;continue}if(r+=o,o===`
|
|
16
|
+
`||!/\s/.test(o))s=o;n++}return r}function Do(e,t,r,n){let i=[],s=new Map,o=[e,...t.filter((W)=>W!==e)];for(let W of o){let H=r.get(W);if(H===void 0){i.push(`No declarations were generated for ${Nt(n.cwd,W)}; it is left out of the bundle`);continue}s.set(W,Df(W,H))}let l=(W,H)=>{if(!W.startsWith(".")&&!W.startsWith("/"))return null;let J=Jt(W,H).resolved;return J&&s.has(J)?J:null},c=(W)=>W.startsWith(".")||W.startsWith("/"),f=new Set,u=(W)=>{let H=W;for(let J=1;f.has(H);J++)H=`${W}_${J}`;return f.add(H),H},a=new Map;for(let[W,H]of s){let J=new Map;for(let z of H.declared)J.set(z,u(z));a.set(W,J)}let m=new Map,y=(W,H,J)=>{let z=`${W}\x00${H}`,Y=m.get(z);if(!Y)Y=u(J),m.set(z,Y);return Y},w=new Map,C=new Map,x=new Set,k=(W,H,J)=>{let z=l(H,W.file);if(z){if(J==="*")return{kind:"namespace",file:z};let Y=G(z).get(J);if(!Y)i.push(`${Nt(n.cwd,W.file)}: '${J}' is not exported by '${H}'`);return Y??null}if(c(H))return i.push(`${Nt(n.cwd,W.file)}: '${H}' is not part of the bundle`),null;return J==="*"?{kind:"external-namespace",source:H}:{kind:"external",source:H,imported:J}},L=(W,H)=>{if(W.declared.has(H))return{kind:"local",name:a.get(W.file).get(H)};let J=W.imports.get(H);if(J)return k(W,J.specifier,J.imported);return i.push(`${Nt(n.cwd,W.file)}: cannot resolve exported name '${H}'`),null};function G(W){let H=w.get(W);if(H)return H;let J=new Map,z=s.get(W);if(!z||x.has(W))return J;x.add(W);let Y=new Set;for(let[te,oe]of z.localExports){let ne=L(z,oe);if(ne)J.set(te,ne)}for(let te of z.namedReExports){let oe=k(z,te.specifier,te.imported);if(oe)J.set(te.exported,oe)}for(let te of z.namespaceReExports){let oe=k(z,te.specifier,"*");if(oe)J.set(te.exported,oe)}for(let te of z.starReExports){let oe=l(te,W);if(oe){for(let[ne,qi]of G(oe))if(ne!=="default"&&!J.has(ne))J.set(ne,qi);for(let ne of C.get(oe)??[])Y.add(ne)}else if(c(te))i.push(`${Nt(n.cwd,W)}: '${te}' is not part of the bundle`);else Y.add(te)}return x.delete(W),w.set(W,J),C.set(W,Y),J}let T=new Map,D=[],F=(W,H)=>{switch(W.kind){case"local":return W.name;case"external":return y(W.source,W.imported,W.imported==="default"?H:W.imported);case"external-namespace":return y(W.source,"*",H);case"namespace":return N(W.file,H)}};function N(W,H){let J=T.get(W);if(J)return J;let z=u(H);T.set(W,z);let Y=[];for(let[te,oe]of G(W)){if(te==="default")continue;let ne=F(oe,te);Y.push(ne===te?te:`${ne} as ${te}`)}if(C.get(W)?.size)i.push(`${Nt(n.cwd,W)}: 'export * from' an external module cannot be expressed inside namespace '${z}'`);return D.push(`declare namespace ${z} {
|
|
17
|
+
export { ${Y.join(", ")} };
|
|
18
|
+
}`),z}let b=[],j=[],se=new Set;for(let[W,H]of s){for(let Y of H.directives)se.add(Y);let J=new Map;for(let[Y,te]of a.get(W))if(Y!==te)J.set(Y,te);for(let[Y,te]of H.imports){if(H.declared.has(Y))continue;let oe=k(H,te.specifier,te.imported);if(!oe)continue;let ne=F(oe,Y);if(ne!==Y)J.set(Y,ne)}let z=[];for(let Y of H.declarations){if(n.keepComments)z.push(...Y.statement.comments);let te=ko(Y.emit,J);if(!/[;}]$/.test(te))te+=";";z.push(te)}for(let Y of H.verbatim){if(n.keepComments)j.push(...Y.comments);j.push(ko(Y.text,J))}if(z.length>0)b.push(`// From: ${Nt(n.cwd,W)}
|
|
19
|
+
${z.join(`
|
|
20
|
+
`)}`)}let he=G(e),Z=[],ge=[];for(let[W,H]of he){if(H.kind==="external"){ge.push(`export { ${H.imported===W?W:`${H.imported} as ${W}`} } from '${H.source}';`);continue}if(H.kind==="external-namespace"){ge.push(`export * as ${W} from '${H.source}';`);continue}let J=F(H,W==="default"?"_default":W);Z.push(J===W?W:`${J} as ${W}`)}for(let W of C.get(e)??[])ge.push(`export * from '${W}';`);let De=new Map;for(let[W,H]of m){let[J,z]=W.split("\x00"),Y=De.get(J)??{named:[],defaults:[],namespaces:[]};if(De.set(J,Y),z==="*")Y.namespaces.push(H);else if(z==="default")Y.defaults.push(H);else Y.named.push(z===H?H:`${z} as ${H}`)}let ie=[];for(let[W,H]of[...De].sort(([J],[z])=>J.localeCompare(z))){for(let J of H.defaults)ie.push(`import ${J} from '${W}';`);for(let J of H.namespaces)ie.push(`import * as ${J} from '${W}';`);if(H.named.length>0)ie.push(`import { ${H.named.join(", ")} } from '${W}';`)}let ce=[];if(se.size>0)ce.push([...se].join(`
|
|
21
21
|
`));if(ce.push(`/**
|
|
22
22
|
* Bundled TypeScript declarations
|
|
23
|
-
* Generated from ${
|
|
24
|
-
*/`),
|
|
25
|
-
`));if(ce.push(...
|
|
26
|
-
`));if(
|
|
27
|
-
`));let ee=[];if(
|
|
23
|
+
* Generated from ${s.size} source files
|
|
24
|
+
*/`),ie.length>0)ce.push(ie.join(`
|
|
25
|
+
`));if(ce.push(...b),D.length>0)ce.push(D.join(`
|
|
26
|
+
`));if(j.length>0)ce.push(j.join(`
|
|
27
|
+
`));let ee=[];if(Z.length>0)ee.push(`export { ${Z.join(", ")} };`);if(ee.push(...ge),ee.length===0)ee.push("export {};");return ce.push(ee.join(`
|
|
28
28
|
`)),{content:`${ce.join(`
|
|
29
29
|
|
|
30
30
|
`)}
|
|
31
|
-
`,files:[...
|
|
31
|
+
`,files:[...s.keys()],exportCount:he.size,warnings:i}}var Mo,kf;var Io=de(()=>{$n();Mo=/^[A-Z_$][\w$]*$/i;kf=/^(?: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 Wo(e,t={}){let{lineEnding:r="lf",trailingNewline:n=!0,maxBlankLines:i=1,trimTrailingWhitespace:s=!0,normalizeIndentation:o=!0,indent:l={style:"spaces",size:2},declarationOrder:c,importGrouping:f,preserveComments:u=!0,insertFinalNewline:a=!0}=t,m=e;if(m=Nf(m,r),f?.enabled!==!1)m=_f(m,f||{});if(c)m=Uf(m,c);if(s)m=Wf(m);if(m=Lf(m,i),o)m=Bf(m,l);if(n||a)m=Gf(m);return m}function Nf(e,t){let r=e;if(e.indexOf("\r")!==-1){if(e.indexOf(`\r
|
|
32
|
+
`)!==-1)r=r.replace(/\r\n/g,`
|
|
33
|
+
`);if(r.indexOf("\r")!==-1)r=r.replace(/\r/g,`
|
|
34
|
+
`)}if(t==="crlf")r=r.replace(/\n/g,`\r
|
|
35
|
+
`);return r}function Wf(e){return e.split(`
|
|
36
|
+
`).map((t)=>t.replace(/[\t ]+$/,"")).join(`
|
|
37
|
+
`)}function Lf(e,t){let r=new RegExp(`\\n{${t+2},}`,"g");return e.replace(r,`
|
|
38
|
+
`.repeat(t+1))}function Gf(e){return`${e.replace(/\s+$/,"")}
|
|
39
|
+
`}function Bf(e,t){let{style:r="spaces",size:n=2}=t,i=r==="tabs"?"\t":" ".repeat(n),s=e.split(`
|
|
40
|
+
`),o=[];for(let l of s){let c=l.match(/^([\t ]*)(.*)$/);if(!c){o.push(l);continue}let[,f,u]=c;if(!u){o.push("");continue}let a=f.replace(/\t/g," "),m=Math.floor(a.length/2);o.push(i.repeat(m)+u)}return o.join(`
|
|
41
|
+
`)}function _f(e,t){let{groups:r=Ff,separateGroups:n=!0,alphabetize:i=!0}=t,s=e.split(`
|
|
42
|
+
`),o=[],l=[],c=-1;for(let w=0;w<s.length;w++){let C=s[w],x=Fo(C);if(x)o.push({line:C,source:x.source,group:x.group,isType:x.isType}),c=w;else if(o.length>0&&C.trim()==="")continue;else if(o.length>0||C.trim()!==""){if(o.length===0||w>c+1)l.push(C)}}if(o.length===0)return e;let f=new Map;for(let w of r)f.set(w,[]);for(let w of o)(f.get(w.group)||f.get("external")||[]).push(w);if(i)for(let[,w]of f)w.sort((C,x)=>{if(C.isType!==x.isType)return C.isType?1:-1;return C.source.localeCompare(x.source)});let u=[],a=null;for(let w of r){let C=f.get(w)||[];if(C.length===0)continue;if(n&&a!==null)u.push("");for(let x of C)u.push(x.line);a=w}let m=s.slice(0,s.findIndex((w)=>Fo(w)!==null)),y=l;while(y.length>0&&y[0].trim()==="")y.shift();return[...m,...u,"",...y].join(`
|
|
43
|
+
`)}function Fo(e){let t=e.trim(),r=t.match(/^import\s+(type\s+)?.*from\s+['"]([^'"]+)['"]/);if(!r){let s=t.match(/^import\s+['"]([^'"]+)['"]/);if(s)return{source:s[1],group:No(s[1]),isType:!1};return null}let n=!!r[1],i=r[2];return{source:i,group:n?"type":No(i),isType:n}}function No(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 Uf(e,t){let{kinds:r=If,alphabetize:n=!1,groupExports:i=!0}=t,s=e.split(`
|
|
44
|
+
`),o=[],l=[],c=[],f=null,u=0,a=!0,m=!1,y=[];for(let x=0;x<s.length;x++){let k=s[x],L=k.trim(),G=u,T=L.startsWith("///"),D=G===0&&!T&&(L.startsWith("//")||L.startsWith("/*"));if(m||D){if(y.push(k),!m&&L.startsWith("/*")&&!L.includes("*/"))m=!0;else if(m&&L.includes("*/"))m=!1;continue}if(G===0&&y.length>0&&L===""){y.push(k);continue}u+=(k.match(/\{/g)||[]).length,u-=(k.match(/\}/g)||[]).length;let F=Vf(L);if(a&&F&&F.kind!=="import"&&!L.startsWith("//")&&!L.startsWith("/*"))a=!1;if(a){if(y.length>0){if(F?.kind==="import"||!F)l.push(...y),y.length=0}l.push(k);continue}if(F&&u<=1){if(f)o.push(f);f={lines:y.length>0?[...y,k]:[k],kind:F.kind,name:F.name,isExport:F.isExport},y.length=0}else if(f)f.lines.push(k);else{if(L==="")continue;c.push(k)}}if(f)o.push(f);if(y.length>0)c.push(...y);o.sort((x,k)=>{if(i&&x.isExport!==k.isExport)return x.isExport?-1:1;let L=r.indexOf(x.kind),G=r.indexOf(k.kind),T=L>=0?L:r.length,D=G>=0?G:r.length;if(T!==D)return T-D;if(n)return x.name.localeCompare(k.name);return 0});let w=[...l],C=null;for(let x of o){if(C!==null&&x.kind!==C)w.push("");w.push(...x.lines),C=x.kind}if(c.length>0)w.push(""),w.push(...c);return w.join(`
|
|
45
|
+
`)}function Vf(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 If,Ff;var Lo=de(()=>{If=["import","type","interface","enum","class","function","variable","export","module","namespace","unknown"],Ff=["builtin","external","scoped","internal","parent","sibling","index","type"]});async function Hf(){if(jr!==null)return jr;try{return Pt=await import("prettier"),jr=!0,!0}catch{return jr=!1,!1}}async function jf(e,t){if(!Pt)return null;try{if(t&&Pt.resolveConfig){let r=await Pt.resolveConfig(t);if(r)return r}if(e&&Pt.resolveConfig){let r=await Pt.resolveConfig(e);if(r)return r}return null}catch{return null}}async function Kf(e,t){if(!Pt)throw Error("Prettier is not available");let r={...t,parser:t.parser||"typescript"};return Pt.format(e,r)}function Zf(e,t={}){let{indentSize:r=2,useTabs:n=!1,maxLineWidth:i=100,trailingNewline:s=!0,normalizeWhitespace:o=!0,sortImports:l=!0,groupImports:c=!0}=t,f=e,u=n?"\t":" ".repeat(r);if(f.indexOf(`\r
|
|
46
|
+
`)!==-1)f=f.replace(/\r\n/g,`
|
|
47
|
+
`);if(o){if(/[ \t]\n/.test(f)||/[ \t]$/.test(f))f=f.replace(/[ \t]+$/gm,"");if(f.indexOf(`
|
|
32
48
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
`;Fs(t,r)}}catch{}}var vn=3,Ki=".dtsx-cache",Wf="manifest.json";var Bs=de(()=>{En()});function Gs(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 js=()=>{};import Bf from"process";import{existsSync as _s,statSync as Vs}from"fs";import{existsSync as Gf,mkdirSync as gg,readdirSync as yg,readFileSync as jf,writeFileSync as Cg}from"fs";import{homedir as qt}from"os";import{dirname as Eg,resolve as nt}from"path";import xr from"process";import{existsSync as Us,statSync as Ks}from"fs";import{existsSync as Un,mkdirSync as _f,readdirSync as Vf,writeFileSync as Uf}from"fs";import{homedir as Yt}from"os";import{dirname as Hs,resolve as qe}from"path";import Ft from"process";import{join as Kf,relative as Hf,resolve as zs}from"path";import ur from"process";import{existsSync as Oa,mkdirSync as kg,readdirSync as Mg,writeFileSync as Dg}from"fs";import{homedir as xn}from"os";import{dirname as Fg,resolve as Je}from"path";import bi from"process";import{join as zf,relative as Jf,resolve as Js}from"path";import hr from"process";import{existsSync as Ra,mkdirSync as jg,readdirSync as _g,writeFileSync as Vg}from"fs";import{dirname as Kg,resolve as dr}from"path";import Kn from"process";import{Buffer as Rt}from"buffer";import{createCipheriv as qf,createDecipheriv as Yf,randomBytes as An}from"crypto";import{closeSync as Tn,createReadStream as qs,createWriteStream as Zf,existsSync as On,fsyncSync as Ys,openSync as Zs,writeFileSync as Xf}from"fs";import{access as Qf,constants as Xs,mkdir as eu,readdir as Hi,rename as Qs,stat as Zt,unlink as zi,writeFile as Rn}from"fs/promises";import{join as Xt}from"path";import Ve from"process";import{pipeline as tu}from"stream/promises";import{createGzip as ea}from"zlib";import Qt from"process";import wt from"process";import{Buffer as gt}from"buffer";import{createCipheriv as iu,createDecipheriv as ru,randomBytes as Pn}from"crypto";import{closeSync as kn,createReadStream as ta,createWriteStream as nu,existsSync as Ji,fsyncSync as ia,openSync as ra,writeFileSync as ou}from"fs";import{access as su,constants as na,mkdir as au,readdir as qi,rename as oa,stat as ei,unlink as Yi,writeFile as Mn}from"fs/promises";import{isAbsolute as lu,join as ti,resolve as cu}from"path";import ye from"process";import{pipeline as fu}from"stream/promises";import{createGzip as sa}from"zlib";import ii from"process";import bt from"process";import Zi from"process";import{existsSync as Xi}from"fs";import{resolve as Dn}from"path";import{existsSync as uu}from"fs";import{existsSync as hu,readdirSync as du}from"fs";import{extname as In,resolve as aa}from"path";import pu from"process";import{join as mu,relative as gu,resolve as la}from"path";import pr from"process";import{Buffer as yt}from"buffer";import{createCipheriv as yu,createDecipheriv as Cu,randomBytes as Nn}from"crypto";import{closeSync as Fn,createReadStream as ca,createWriteStream as wu,existsSync as Qi,fsyncSync as fa,openSync as ua,writeFileSync as bu}from"fs";import{access as Eu,constants as ha,mkdir as vu,readdir as er,rename as da,stat as ri,unlink as tr,writeFile as Ln}from"fs/promises";import{isAbsolute as Su,join as ni,resolve as $u}from"path";import Ce from"process";import{pipeline as xu}from"stream/promises";import{createGzip as pa}from"zlib";import oi from"process";import Et from"process";import ir from"process";import{existsSync as rr}from"fs";import{resolve as Wn}from"path";import{existsSync as Au}from"fs";class Pa{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],[,n])=>i.timestamp.getTime()-n.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,n){if(!this.options.enabled)return;let r=this.generateKey(e,i),o=n??this.options.ttl,s=this.estimateSize(t);this.cache.set(r,{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),n=this.cache.get(i);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(i),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!_s(e))return!0;return Vs(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,n){try{let r=_s(i)?Vs(i):null,o=r?r.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},i,n)}catch{this.set(e,t,i,n)}}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((n,r)=>n+r.size,0),i=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: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 n=i;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class ka{metrics=[];maxMetrics=1000;async track(e,t,i={}){let n=performance.now(),r=new Date;try{let o=await t(),s=performance.now()-n;return this.recordMetric({operation:e,duration:s,timestamp:r,...i}),o}catch(o){let s=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:r,...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((r)=>r.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let i=t.map((r)=>r.duration),n=i.reduce((r,o)=>r+o,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...i),maxDuration:Math.max(...i),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Ru(e,t){this[e]=Ou.bind(null,t)}class ro{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],[,n])=>i.timestamp.getTime()-n.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,n){if(!this.options.enabled)return;let r=this.generateKey(e,i),o=n??this.options.ttl,s=this.estimateSize(t);this.cache.set(r,{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),n=this.cache.get(i);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(i),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!Us(e))return!0;return Ks(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,n){try{let r=Us(i)?Ks(i):null,o=r?r.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},i,n)}catch{this.set(e,t,i,n)}}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((n,r)=>n+r.size,0),i=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: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 n=i;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class no{metrics=[];maxMetrics=1000;async track(e,t,i={}){let n=performance.now(),r=new Date;try{let o=await t(),s=performance.now()-n;return this.recordMetric({operation:e,duration:s,timestamp:r,...i}),o}catch(o){let s=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:r,...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((r)=>r.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let i=t.map((r)=>r.duration),n=i.reduce((r,o)=>r+o,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...i),maxDuration:Math.max(...i),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={}){let i=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return i?`${e}:${i}`:e}function Du(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Iu(e){return e.getStats().size*2}function oo(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Oe(t[0])&&"id"in t[0]&&t[0].id===3&&Oe(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Oe(t)&&Oe(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(Oe(e)&&"arr"in e&&Array.isArray(e.arr)&&Oe(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Oe(t[0])&&Oe(e[0])){let n=[...t];for(let r of e)if(Oe(r)&&"name"in r){if(!n.find((o)=>Oe(o)&&("name"in o)&&o.name===r.name))n.push(r)}else if(Oe(r)&&"path"in r){if(!n.find((o)=>Oe(o)&&("path"in o)&&o.path===r.path))n.push(r)}else if(!n.some((o)=>gr(o,r)))n.push(r);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let r of e)if(!n.includes(r))n.push(r);return n}return t}if(!Oe(t)||!Oe(e))return t;let i={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let r=t[n];if(r===null||r===void 0)continue;else if(Oe(r)&&Oe(i[n]))i[n]=oo(i[n],r);else if(Array.isArray(r)&&Array.isArray(i[n]))if(r.length>0&&i[n].length>0&&Oe(r[0])&&Oe(i[n][0])){let o=[...r];for(let s of i[n])if(Oe(s)&&"name"in s){if(!o.find((l)=>Oe(l)&&("name"in l)&&l.name===s.name))o.push(s)}else if(Oe(s)&&"path"in s){if(!o.find((l)=>Oe(l)&&("path"in l)&&l.path===s.path))o.push(s)}else if(!o.some((l)=>gr(l,s)))o.push(s);i[n]=o}else if(r.every((o)=>typeof o==="string")&&i[n].every((o)=>typeof o==="string")){let o=[...r];for(let s of i[n])if(!o.includes(s))o.push(s);i[n]=o}else i[n]=r;else i[n]=r}return i}function gr(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(!gr(e[i],t[i]))return!1;return!0}if(Oe(e)&&Oe(t)){let i=Object.keys(e),n=Object.keys(t);if(i.length!==n.length)return!1;for(let r of i){if(!Object.prototype.hasOwnProperty.call(t,r))return!1;if(!gr(e[r],t[r]))return!1}return!0}return!1}function Oe(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Nu(e,t){if(!Ra(e))return null;try{let i=await import(e),n=i.default||i;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return oo(t,n)}catch{return null}}catch{return null}}async function Fu({name:e="",cwd:t,defaultConfig:i}){let n=t||Kn.cwd(),r=[".ts",".js",".mjs",".cjs",".json"],o=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let s of o)for(let l of r){let c=dr(n,`${s}${l}`),f=await Nu(c,i);if(f!==null)return f}try{let s=dr(n,"package.json");if(Ra(s)){let l=(await import(s))[e];if(l&&typeof l==="object"&&!Array.isArray(l))try{return oo(i,l)}catch{}}}catch{}return i}function Lu(e,t={}){let i=hr.cwd();while(i.includes("storage"))i=Js(i,"..");let n=Js(i,e||"");if(t?.relative)return Jf(hr.cwd(),n);return n}async function Wu(){try{let e=await Fu({name:"clarity",defaultConfig:ar,cwd:hr.cwd(),endpoint:"",headers:{}});return{...ar,...e}}catch{return ar}}function Re(){if(wt.env.NODE_ENV==="test"||wt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Bu(){if(wt.env.NODE_ENV==="test"||wt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof wt<"u"){let e=wt.type;if(e==="renderer"||e==="worker")return!1;return!!(wt.versions&&(wt.versions.node||wt.versions.bun))}return!1}class Da{async format(e){let t=await Bu(),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:Qt.pid,hostname:t(),environment:Qt.env.NODE_ENV||"development",platform:Qt.platform,version:Qt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Qt.env.NODE_ENV||Qt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class yr{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={...zn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Da,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Ve.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let i={...t},n=t.timestamp!==void 0;if(n)delete i.timestamp;if(this.config={...this.config,...i,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let r=this.generateKeyId(),o=this.generateKey();this.currentKeyId=r,this.keys.set(r,o),this.encryptionKeys.set(r,{key:o,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...lr,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...lr};return{...lr,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:zn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},i={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==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 n,r=0,o=3,s=1000;while(r<o)try{try{try{await Qf(this.config.logDirectory,Xs.F_OK|Xs.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await eu(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 l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Rt.from(e);try{if(!On(this.currentLogFile))await Rn(this.currentLogFile,"",{mode:420});if(n=Zs(this.currentLogFile,"a",420),Xf(n,l,{flag:"a"}),Ys(n),n!==void 0)Tn(n),n=void 0;if((await Zt(this.currentLogFile)).size===0){if(await Rn(this.currentLogFile,l,{flag:"w",mode:420}),(await Zt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(r<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${r+1}/${o}:`,u);let a=s*2**r;await new Promise((m)=>setTimeout(m,a)),r++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(n!==void 0)try{Tn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(l){if(r===o-1){let f=l,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),l}r++;let c=s*2**(r-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let i=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}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 Xt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Xt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Xt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Re())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((n)=>{console.error("Error rotating keys:",n)})},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 n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,l])=>l.createdAt.getTime()-s.createdAt.getTime()),r=typeof e.maxKeys==="number"?e.maxKeys:1,o=Math.max(1,r);if(n.length>o)for(let[s]of n.slice(o))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return An(16).toString("hex")}generateKey(){return An(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),i=An(16),n=qf("aes-256-gcm",t,i),r=Rt.concat([n.update(e,"utf8"),n.final()]),o=n.getAuthTag();return{encrypted:Rt.concat([i,r,o]),iv:i}}async compressData(e){return new Promise((t,i)=>{let n=ea(),r=[];n.on("data",(o)=>r.push(o)),n.on("end",()=>t(Rt.from(Rt.concat(r)))),n.on("error",i),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(Re())return;let e=await Zt(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let i=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let r=await Hi(this.config.logDirectory),o=r.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,l=`${i}.${s}`;if(await Zt(i).catch(()=>null))try{if(await Qs(i,l),t.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await zi(l)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!r.some((c)=>c.endsWith(".log.1")))try{let c=`${i}.1`;await Rn(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let r=new Date().toISOString().replace(/[:.]/g,"-"),o=i.replace(/\.log$/,`-${r}.log`);if(await Zt(i).catch(()=>null))await Qs(i,o)}if(this.currentLogFile=n,t.maxFiles){let r=(await Hi(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of r.slice(t.maxFiles))await zi(Xt(this.config.logDirectory,o))}}}async compressLogFile(e,t){let i=qs(e),n=Zf(t),r=ea();await tu(i,r,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let i of this.logBuffer){let n=await this.formatter.format(i);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 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()})),On(this.currentLogFile))try{let e=Zs(this.currentLogFile,"r+");Ys(e),Tn(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Re()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Hi(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await zi(Xt(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?Se.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:i="",tag:n="",message:r,level:o,showTimestamp:s=!0}=e,l=(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(i)y.push(i.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)y.push(n.replace(/[[\]]/g,""));return y.push(r),y.join(" ")}let c=Ve.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${i} ${r}`;else if(o==="info"||o==="success")f=`${i} ${n} ${r}`;else f=`${i} ${n} ${Se.cyan(r)}`;if(!s)return f.trim();let u=l(f).trim().length,a=l(t).length,m=Math.max(1,c-2-u-a);return`${f.trim()}${" ".repeat(m)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let l=Number.parseInt(s,10);return l<t[0].length?String(t[0][l]):o});let i=/%([sdijfo%])/g,n=0,r=e.replace(i,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let l=t[n++];switch(s){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 o}});if(n<t.length)r+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return r}async log(e,t,...i){let n=new Date,r=this.formatConsoleTimestamp(n),o=this.formatFileTimestamp(n),s,l;if(t instanceof Error)s=t.message,l=t.stack;else s=this.formatMessage(t,i);if(this.fancy&&!Re()){let f=Va[e],u=this.options.showTags!==!1&&this.name?Se.gray(this.formatTag(this.name)):"",a;switch(e){case"debug":a=this.formatConsoleMessage({timestamp:r,icon:f,tag:u,message:Se.gray(s),level:e}),console.error(a);break;case"info":a=this.formatConsoleMessage({timestamp:r,icon:f,tag:u,message:s,level:e}),console.error(a);break;case"success":a=this.formatConsoleMessage({timestamp:r,icon:f,tag:u,message:Se.green(s),level:e}),console.error(a);break;case"warning":a=this.formatConsoleMessage({timestamp:r,icon:f,tag:u,message:s,level:e}),console.warn(a);break;case"error":if(a=this.formatConsoleMessage({timestamp:r,icon:f,tag:u,message:s,level:e}),console.error(a),l){let m=l.split(`
|
|
36
|
-
`);
|
|
49
|
+
|
|
50
|
+
`)!==-1)f=f.replace(/\n{3,}/g,`
|
|
51
|
+
|
|
52
|
+
`);f=Yf(f,u)}if(l||c)f=Jf(f,{sort:l,group:c});if(i>0)f=zf(f,i,u);if(s&&!f.endsWith(`
|
|
53
|
+
`))f+=`
|
|
54
|
+
`;return f}function Yf(e,t){let r=e.split(`
|
|
55
|
+
`),n=[];for(let i of r){let s=i.match(/^(\s*)(.*)$/);if(!s){n.push(i);continue}let[,o,l]=s;if(!l){n.push("");continue}let c=o.replace(/\t/g," ").length,f=Math.floor(c/2);n.push(t.repeat(f)+l)}return n.join(`
|
|
56
|
+
`)}function Jf(e,t){let r=e.split(`
|
|
57
|
+
`),n=[],i=[],s=!1,o=0;for(let c=0;c<r.length;c++){let f=r[c],u=f.match(/^(import\s+(?:type\s+)?.*from\s+['"])([^'"]+)(['"].*)$/);if(u){s=!0,o=c;let a=u[1];n.push({line:f,source:u[2],isType:a.startsWith("import type ")||a.startsWith("import type\t")})}else if(s&&f.trim()==="")continue;else{if(s)s=!1;i.push(f)}}if(n.length===0)return e;if(t.sort)n.sort((c,f)=>{if(c.isType!==f.isType)return c.isType?1:-1;return qf(c.source,f.source)});let l;if(t.group){let c=[],f=[],u=[],a=[],m=[];for(let y=0;y<n.length;y++){let w=n[y],C=w.source;if(C.charCodeAt(0)===46)m.push(w);else if(C.startsWith("node:"))c.push(w);else if(C.charCodeAt(0)===64)a.push(w);else if(C.includes("/"))u.push(w);else f.push(w)}l=[...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),...a.length>0&&(c.length>0||f.length>0||u.length>0)?[""]:[],...a.map((y)=>y.line),...m.length>0?[""]:[],...m.map((y)=>y.line)]}else l=n.map((c)=>c.line);return[...l,"",...i].join(`
|
|
58
|
+
`)}function qf(e,t){let r=e.startsWith("node:"),n=t.startsWith("node:");if(r!==n)return r?-1:1;let i=e.startsWith("."),s=t.startsWith(".");if(i!==s)return i?1:-1;return e.localeCompare(t)}function zf(e,t,r){let n=e.split(`
|
|
59
|
+
`),i=[];for(let s of n){if(s.length<=t){i.push(s);continue}if(s.trimStart().startsWith("import ")){i.push(s);continue}let o=s.match(/^(\s*)/)?.[1]||"",l=o+r,c=Qf(s,o,l);if(c){i.push(...c);continue}if(s.includes("{")&&s.includes("}")){let f=eu(s,t,o,l);i.push(...f);continue}if(s.includes(" | ")){let f=tu(s,t,o,l);i.push(...f);continue}i.push(s)}return i.join(`
|
|
60
|
+
`)}function Qf(e,t,r){let n=e.match(Xf);if(!n)return null;let[,i,s,o,l]=n,c=o.split(",").map((a)=>a.trim()).filter(Boolean);if(c.length<=1)return[e];let f=`${t}${i}${s??""} {`,u=l?`${t}} ${l};`:`${t}};`;return[f,...c.map((a)=>`${r}${a},`),u]}function eu(e,t,r,n){let i=e.match(/^(\s*)(.*?)(\{)(.+)(\}.*)$/);if(!i)return[e];let[,,s,o,l,c]=i,f=l.split(/;\s*|,\s*/).filter((u)=>u.trim());if(f.length<=1)return[e];return[`${r}${s}${o}`,...f.map((u)=>`${n}${u.trim()};`),`${r}${c.trim()}`]}function tu(e,t,r,n){let i=e.match(/^(\s*)(.*?=\s*)(.+)$/);if(!i)return[e];let[,,s,o]=i,l=o.split(/\s*\|\s*/).filter((c)=>c.trim());if(l.length<=2)return[e];return[`${r}${s}`,...l.map((c,f)=>`${n}${f>0?"| ":" "}${c.trim()}`)]}async function Go(e,t={},r){let n=[];if(t.usePrettier!==!1){if(await Hf())try{let i={...await jf(t.prettierConfigPath,r),...t.prettierOptions,parser:"typescript"};return{content:await Kf(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:Zf(e,t.builtIn),usedPrettier:!1,warnings:n.length>0?n:void 0}}var jr=null,Pt=null,Xf;var Bo=de(()=>{Xf=/^\s*(export|import)(\s+type)?\s*\{([^{}]*)\}\s*(from\s*(?:'[^']*'|"[^"]*")(?:\s*(?:with|assert)\s*\{[^{}]*\})?)?\s*;?\s*$/});import ru from"process";import{existsSync as _o,statSync as Uo}from"fs";import{existsSync as iu,mkdirSync as hg,readdirSync as dg,readFileSync as nu,writeFileSync as pg}from"fs";import{homedir as qt}from"os";import{dirname as yg,resolve as st}from"path";import Ai from"process";import{existsSync as Vo,statSync as Ho}from"fs";import{existsSync as _n,mkdirSync as su,readdirSync as ou,writeFileSync as au}from"fs";import{homedir as zt}from"os";import{dirname as jo,resolve as qe}from"path";import Wt from"process";import{join as lu,relative as cu,resolve as Ko}from"path";import ui from"process";import{existsSync as Ta,mkdirSync as Tg,readdirSync as Og,writeFileSync as Rg}from"fs";import{homedir as bn}from"os";import{dirname as Mg,resolve as Je}from"path";import wr from"process";import{join as fu,relative as uu,resolve as Zo}from"path";import hi from"process";import{existsSync as Oa,mkdirSync as Wg,readdirSync as Lg,writeFileSync as Gg}from"fs";import{dirname as _g,resolve as di}from"path";import Un from"process";import{Buffer as kt}from"buffer";import{createCipheriv as hu,createDecipheriv as du,randomBytes as En}from"crypto";import{closeSync as Sn,createReadStream as Yo,createWriteStream as pu,existsSync as An,fsyncSync as Jo,openSync as qo,writeFileSync as mu}from"fs";import{access as gu,constants as zo,mkdir as yu,readdir as Kr,rename as Xo,stat as Xt,unlink as Zr,writeFile as xn}from"fs/promises";import{join as Qt}from"path";import He from"process";import{pipeline as Cu}from"stream/promises";import{createGzip as Qo}from"zlib";import er from"process";import $t from"process";import{Buffer as yt}from"buffer";import{createCipheriv as wu,createDecipheriv as $u,randomBytes as Tn}from"crypto";import{closeSync as On,createReadStream as ea,createWriteStream as vu,existsSync as Yr,fsyncSync as ta,openSync as ra,writeFileSync as bu}from"fs";import{access as Eu,constants as ia,mkdir as Su,readdir as Jr,rename as na,stat as tr,unlink as qr,writeFile as Rn}from"fs/promises";import{isAbsolute as Au,join as rr,resolve as xu}from"path";import ye from"process";import{pipeline as Tu}from"stream/promises";import{createGzip as sa}from"zlib";import ir from"process";import vt from"process";import zr from"process";import{existsSync as Xr}from"fs";import{resolve as Pn}from"path";import{existsSync as Ou}from"fs";import{existsSync as Ru,readdirSync as Pu}from"fs";import{extname as kn,resolve as oa}from"path";import ku from"process";import{join as Mu,relative as Du,resolve as aa}from"path";import pi from"process";import{Buffer as Ct}from"buffer";import{createCipheriv as Iu,createDecipheriv as Fu,randomBytes as Mn}from"crypto";import{closeSync as Dn,createReadStream as la,createWriteStream as Nu,existsSync as Qr,fsyncSync as ca,openSync as fa,writeFileSync as Wu}from"fs";import{access as Lu,constants as ua,mkdir as Gu,readdir as ei,rename as ha,stat as nr,unlink as ti,writeFile as In}from"fs/promises";import{isAbsolute as Bu,join as sr,resolve as _u}from"path";import Ce from"process";import{pipeline as Uu}from"stream/promises";import{createGzip as da}from"zlib";import or from"process";import bt from"process";import ri from"process";import{existsSync as ii}from"fs";import{resolve as Fn}from"path";import{existsSync as Vu}from"fs";class Ra{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!_o(e))return!0;return Uo(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=_o(r)?Uo(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Pa{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),s}catch(s){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Ku(e,t){this[e]=ju.bind(null,t)}class es{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!Vo(e))return!0;return Ho(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=Vo(r)?Ho(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class ts{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),s}catch(s){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Ju(e,t={}){let r=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return r?`${e}:${r}`:e}function qu(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function zu(e){return e.getStats().size*2}function rs(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Oe(t[0])&&"id"in t[0]&&t[0].id===3&&Oe(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Oe(t)&&Oe(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(Oe(e)&&"arr"in e&&Array.isArray(e.arr)&&Oe(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Oe(t[0])&&Oe(e[0])){let n=[...t];for(let i of e)if(Oe(i)&&"name"in i){if(!n.find((s)=>Oe(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(Oe(i)&&"path"in i){if(!n.find((s)=>Oe(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((s)=>gi(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!Oe(t)||!Oe(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(Oe(i)&&Oe(r[n]))r[n]=rs(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&Oe(i[0])&&Oe(r[n][0])){let s=[...i];for(let o of r[n])if(Oe(o)&&"name"in o){if(!s.find((l)=>Oe(l)&&("name"in l)&&l.name===o.name))s.push(o)}else if(Oe(o)&&"path"in o){if(!s.find((l)=>Oe(l)&&("path"in l)&&l.path===o.path))s.push(o)}else if(!s.some((l)=>gi(l,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function gi(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(!gi(e[r],t[r]))return!1;return!0}if(Oe(e)&&Oe(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(!gi(e[i],t[i]))return!1}return!0}return!1}function Oe(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Xu(e,t){if(!Oa(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 rs(t,n)}catch{return null}}catch{return null}}async function Qu({name:e="",cwd:t,defaultConfig:r}){let n=t||Un.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let l of i){let c=di(n,`${o}${l}`),f=await Xu(c,r);if(f!==null)return f}try{let o=di(n,"package.json");if(Oa(o)){let l=(await import(o))[e];if(l&&typeof l==="object"&&!Array.isArray(l))try{return rs(r,l)}catch{}}}catch{}return r}function eh(e,t={}){let r=hi.cwd();while(r.includes("storage"))r=Zo(r,"..");let n=Zo(r,e||"");if(t?.relative)return uu(hi.cwd(),n);return n}async function th(){try{let e=await Qu({name:"clarity",defaultConfig:ai,cwd:hi.cwd(),endpoint:"",headers:{}});return{...ai,...e}}catch{return ai}}function Re(){if($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function rh(){if($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof $t<"u"){let e=$t.type;if(e==="renderer"||e==="worker")return!1;return!!($t.versions&&($t.versions.node||$t.versions.bun))}return!1}class Ma{async format(e){let t=await rh(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:er.pid,hostname:t(),environment:er.env.NODE_ENV||"development",platform:er.platform,version:er.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:er.env.NODE_ENV||er.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class yi{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...Hn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ma,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??He.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...li,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...li};return{...li,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Hn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let t=(async()=>{let n,i=0,s=3,o=1000;while(i<s)try{try{try{await gu(this.config.logDirectory,zo.F_OK|zo.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await yu(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 l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:kt.from(e);try{if(!An(this.currentLogFile))await xn(this.currentLogFile,"",{mode:420});if(n=qo(this.currentLogFile,"a",420),mu(n,l,{flag:"a"}),Jo(n),n!==void 0)Sn(n),n=void 0;if((await Xt(this.currentLogFile)).size===0){if(await xn(this.currentLogFile,l,{flag:"w",mode:420}),(await Xt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(i<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let a=o*2**i;await new Promise((m)=>setTimeout(m,a)),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{Sn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(l){if(i===s-1){let f=l,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),l}i++;let c=o*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Qt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Qt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Qt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Re())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,o],[,l])=>l.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,i);if(n.length>s)for(let[o]of n.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return En(16).toString("hex")}generateKey(){return En(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=En(16),n=hu("aes-256-gcm",t,r),i=kt.concat([n.update(e,"utf8"),n.final()]),s=n.getAuthTag();return{encrypted:kt.concat([r,i,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Qo(),i=[];n.on("data",(s)=>i.push(s)),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(Re())return;let e=await Xt(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Kr(this.config.logDirectory),s=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${r}.${o}`;if(await Xt(r).catch(()=>null))try{if(await Xo(r,l),t.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await Zr(l)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await xn(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await Xt(r).catch(()=>null))await Xo(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await Kr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await Zr(Qt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Yo(e),n=pu(t),i=Qo();await Cu(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()})),An(this.currentLogFile))try{let e=qo(this.currentLogFile,"r+");Jo(e),Sn(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(!Re()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Kr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Zr(Qt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?Ee.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,l=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(o)y.push(t);if(s==="warning")y.push("WARN");else if(s==="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=He.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${i}`;else if(s==="info"||s==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${Ee.cyan(i)}`;if(!o)return f.trim();let u=l(f).trim().length,a=l(t).length,m=Math.max(1,c-2-u-a);return`${f.trim()}${" ".repeat(m)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let l=Number.parseInt(o,10);return l<t[0].length?String(t[0][l]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let l=t[n++];switch(o){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}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,l;if(t instanceof Error)o=t.message,l=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!Re()){let f=Ua[e],u=this.options.showTags!==!1&&this.name?Ee.gray(this.formatTag(this.name)):"",a;switch(e){case"debug":a=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:Ee.gray(o),level:e}),console.error(a);break;case"info":a=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:o,level:e}),console.error(a);break;case"success":a=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:Ee.green(o),level:e}),console.error(a);break;case"warning":a=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:o,level:e}),console.warn(a);break;case"error":if(a=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:o,level:e}),console.error(a),l){let m=l.split(`
|
|
61
|
+
`);for(let y of m)if(y.trim()&&!y.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:Ee.gray(` ${y}`),level:e,showTimestamp:!1}))}break}}else if(!Re()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),l)console.error(l)}if(!this.shouldLog(e))return;let c=`${s} ${this.environment}.${e.toUpperCase()}: ${o}
|
|
37
62
|
`;if(l)c+=`${l}
|
|
38
|
-
`;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(e){let t=performance.now();if(this.fancy&&!Re()){let
|
|
39
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.fancy&&!Re()){let f=this.options.showTags!==!1&&this.name?
|
|
40
|
-
`),
|
|
41
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(
|
|
42
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(e,t=""){if(!this.enabled||!this.fancy||Re()||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
|
|
43
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Re()||!Ve.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(Re()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Hi(this.config.logDirectory),i=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let r=Xt(this.config.logDirectory,n);if(e.before)try{if((await Zt(r)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${r}:`,o);continue}i.push(r)}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 n of i)try{await zi(n),console.warn(`Deleted log file: ${n}`)}catch(r){console.error(`Failed to delete log file ${n}:`,r)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function sr(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 n=[...t];for(let r of e)if(we(r)&&"name"in r){if(!n.find((o)=>we(o)&&("name"in o)&&o.name===r.name))n.push(r)}else if(we(r)&&"path"in r){if(!n.find((o)=>we(o)&&("path"in o)&&o.path===r.path))n.push(r)}else if(!n.some((o)=>Cr(o,r)))n.push(r);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let r of e)if(!n.includes(r))n.push(r);return n}return t}if(!we(t)||!we(e))return t;let i={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let r=t[n];if(r===null||r===void 0)continue;else if(we(r)&&we(i[n]))i[n]=sr(i[n],r);else if(Array.isArray(r)&&Array.isArray(i[n]))if(r.length>0&&i[n].length>0&&we(r[0])&&we(i[n][0])){let o=[...r];for(let s of i[n])if(we(s)&&"name"in s){if(!o.find((l)=>we(l)&&("name"in l)&&l.name===s.name))o.push(s)}else if(we(s)&&"path"in s){if(!o.find((l)=>we(l)&&("path"in l)&&l.path===s.path))o.push(s)}else if(!o.some((l)=>Cr(l,s)))o.push(s);i[n]=o}else if(r.every((o)=>typeof o==="string")&&i[n].every((o)=>typeof o==="string")){let o=[...r];for(let s of i[n])if(!o.includes(s))o.push(s);i[n]=o}else i[n]=r;else i[n]=r}return i}function so(e,t,i="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return i==="replace"?t:sr(e,t);if(Array.isArray(e))return i==="replace"?t:sr(e,t);if(!we(t)||!we(e))return t;let n={...e};for(let r of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,r))continue;let o=t[r],s=n[r];if(o===null||o===void 0)continue;if(Array.isArray(o)||Array.isArray(s))if(i==="replace")n[r]=o;else n[r]=sr(s,o);else if(we(o)&&we(s))n[r]=so(s,o,i);else n[r]=o}return n}function Cr(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(!Cr(e[i],t[i]))return!1;return!0}if(we(e)&&we(t)){let i=Object.keys(e),n=Object.keys(t);if(i.length!==n.length)return!1;for(let r of i){if(!Object.prototype.hasOwnProperty.call(t,r))return!1;if(!Cr(e[r],t[r]))return!1}return!0}return!1}function we(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function nr(e,t,i="replace"){if(!Oa(e))return null;try{let n=await import(e),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return so(t,r,i)}catch{return null}}catch{return null}}function Gu(e,t,i=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),r={...t};function o(s,l=[]){let c={...s};for(let[f,u]of Object.entries(s)){let a=[...l,f],m=(C)=>C.replace(/([A-Z])/g,"_$1").toUpperCase(),y=`${n}_${a.map(m).join("_")}`,w=`${n}_${a.map((C)=>C.toUpperCase()).join("_")}`;if(i)Ke.info(`Checking environment variable ${y} for config ${e}.${a.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))c[f]=o(u,a);else{let C=bi.env[y]||bi.env[w];if(C!==void 0){if(i)Ke.info(`Using environment variable ${C?y:w} for config ${e}.${a.join(".")}`);if(typeof u==="number")c[f]=Number(C);else if(typeof u==="boolean")c[f]=C.toLowerCase()==="true";else if(Array.isArray(u))try{let A=JSON.parse(C);if(Array.isArray(A))c[f]=A;else c[f]=C.split(",").map((k)=>k.trim())}catch{c[f]=C.split(",").map((A)=>A.trim())}else c[f]=C}}}return c}return o(r)}async function ju({name:e="",alias:t,cwd:i,configDir:n,defaultConfig:r,verbose:o=!1,checkEnv:s=!0,arrayStrategy:l="replace"}){let c=s&&typeof r==="object"&&r!==null&&!Array.isArray(r)?Gu(e,r,o):r,f=i||bi.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(o)Ke.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${f}`);let a=[e,`.${e}`].filter(Boolean),m=[`${e}.config`,`.${e}.config`].filter(Boolean),y=t?[t,`.${t}`]:[],w=t?[`${t}.config`,`.${t}.config`]:[],C=Array.from(new Set([f,Je(f,"config"),Je(f,".config"),n?Je(f,n):void 0].filter(Boolean)));for(let A of C){if(o)Ke.info(`Searching for configuration in: ${A}`);let k=[Je(f,"config"),Je(f,".config")].concat(n?[Je(f,n)]:[]).includes(A)?[...a,...m,...y,...w]:[...m,...a,...w,...y];for(let W of k)for(let B of u){let T=Je(A,`${W}${B}`),D=await nr(T,c,l);if(D!==null){if(o)Ke.success(`Configuration loaded from: ${T}`);return D}}}if(e){let A=Je(xn(),".config",e),k=["config",`${e}.config`];if(t)k.push(`${t}.config`);if(o)Ke.info(`Checking user config directory: ${A}`);for(let W of k)for(let B of u){let T=Je(A,`${W}${B}`),D=await nr(T,c,l);if(D!==null){if(o)Ke.success(`Configuration loaded from user config directory: ${T}`);return D}}}if(e){let A=Je(xn(),".config"),k=[`.${e}.config`];if(t)k.push(`.${t}.config`);if(o)Ke.info(`Checking user config directory for dotfile configs: ${A}`);for(let W of k)for(let B of u){let T=Je(A,`${W}${B}`),D=await nr(T,c,l);if(D!==null){if(o)Ke.success(`Configuration loaded from user config directory dotfile: ${T}`);return D}}}if(e){let A=xn(),k=[`.${e}.config`,`.${e}`];if(t)k.push(`.${t}.config`),k.push(`.${t}`);if(o)Ke.info(`Checking user home directory for dotfile configs: ${A}`);for(let W of k)for(let B of u){let T=Je(A,`${W}${B}`),D=await nr(T,c,l);if(D!==null){if(o)Ke.success(`Configuration loaded from user home directory: ${T}`);return D}}}try{let A=Je(f,"package.json");if(Oa(A)){let k=await import(A),W=k[e];if(!W&&t){if(W=k[t],W&&o)Ke.success(`Using alias "${t}" configuration from package.json`)}if(W&&typeof W==="object"&&!Array.isArray(W))try{if(o)Ke.success(`Configuration loaded from package.json: ${W===k[e]?e:t}`);return so(c,W,l)}catch(B){if(o)Ke.warn("Failed to merge package.json config:",B)}}}catch(A){if(o)Ke.warn("Failed to load package.json:",A)}if(o)Ke.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function _u(e,t={}){let i=ur.cwd();while(i.includes("storage"))i=zs(i,"..");let n=zs(i,e||"");if(t?.relative)return Hf(ur.cwd(),n);return n}async function Vu(){try{let e=await ju({name:"clarity",alias:"logging",defaultConfig:cr,cwd:ur.cwd()});return{...cr,...e||{}}}catch{return cr}}function Fe(){if(bt.env.NODE_ENV==="test"||bt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Uu(){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 Ia{async format(e){let t=await Uu(),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:ii.pid,hostname:t(),environment:ii.env.NODE_ENV||"development",platform:ii.platform,version:ii.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ii.env.NODE_ENV||ii.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class wr{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 Ia,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 i={...t},n=t.timestamp!==void 0;if(n)delete i.timestamp;if(this.config={...this.config,...i,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let r=this.generateKeyId(),o=this.generateKey();this.currentKeyId=r,this.keys.set(r,o),this.encryptionKeys.set(r,{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{...fr,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...fr};return{...fr,...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(([,n])=>n!==void 0))};if(!i.level||!["debug","info","success","warning","error"].includes(i.level))i.level=t.level;return i}shouldWriteToFile(){return!Fe()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,r=0,o=3,s=1000;while(r<o)try{try{try{await su(this.config.logDirectory,na.F_OK|na.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 l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:gt.from(e);try{if(!Ji(this.currentLogFile))await Mn(this.currentLogFile,"",{mode:420});if(n=ra(this.currentLogFile,"a",420),ou(n,l,{flag:"a"}),ia(n),n!==void 0)kn(n),n=void 0;if((await ei(this.currentLogFile)).size===0){if(await Mn(this.currentLogFile,l,{flag:"w",mode:420}),(await ei(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(r<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${r+1}/${o}:`,u);let a=s*2**r;await new Promise((m)=>setTimeout(m,a)),r++;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{kn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(l){if(r===o-1){let f=l,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),l}r++;let c=s*2**(r-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let i=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}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 ti(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 ti(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ti(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Fe())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,i=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},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 n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,l])=>l.createdAt.getTime()-s.createdAt.getTime()),r=typeof e.maxKeys==="number"?e.maxKeys:1,o=Math.max(1,r);if(n.length>o)for(let[s]of n.slice(o))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return Pn(16).toString("hex")}generateKey(){return Pn(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=Pn(16),n=iu("aes-256-gcm",t,i),r=gt.isBuffer(e)?e:gt.from(e,"utf8"),o=n.update(r),s=n.final(),l=o.length+s.length,c=n.getAuthTag(),f=gt.allocUnsafe(16+l+16);return i.copy(f,0),o.copy(f,16),s.copy(f,16+o.length),c.copy(f,16+l),{encrypted:f,iv:i}}async compressData(e){return new Promise((t,i)=>{let n=sa(),r=[];n.on("data",(o)=>r.push(o)),n.on("end",()=>t(gt.from(gt.concat(r)))),n.on("error",i),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Fe())return;if(!this.shouldWriteToFile())return;let e=await ei(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,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let r=await qi(this.config.logDirectory),o=r.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,l=`${i}.${s}`;if(await ei(i).catch(()=>null))try{if(await oa(i,l),t.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await Yi(l)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!r.some((c)=>c.endsWith(".log.1")))try{let c=`${i}.1`;await Mn(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let r=new Date().toISOString().replace(/[:.]/g,"-"),o=i.replace(/\.log$/,`-${r}.log`);if(await ei(i).catch(()=>null))await oa(i,o)}if(this.currentLogFile=n,t.maxFiles){let r=(await qi(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of r.slice(t.maxFiles))await Yi(ti(this.config.logDirectory,o))}}}async compressLogFile(e,t){let i=ta(e),n=nu(t),r=sa();await fu(i,r,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let i of this.logBuffer){let n=await this.formatter.format(i);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()})),Ji(this.currentLogFile))try{let e=ra(this.currentLogFile,"r+");ia(e),kn(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Fe()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await qi(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Yi(ti(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()?fe.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Fe())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:i="",tag:n="",message:r,level:o,showTimestamp:s=!0}=e,l=(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(i)y.push(i.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)y.push(n.replace(/[[\]]/g,""));return y.push(r),y.join(" ")}let c=ye.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${i} ${r}`;else if(o==="info"||o==="success")f=`${i} ${n} ${r}`;else f=`${i} ${n} ${fe.cyan(r)}`;if(!s)return f.trim();let u=l(f).trim().length,a=l(t).length,m=Math.max(1,c-2-u-a);return`${f.trim()}${" ".repeat(m)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let l=Number.parseInt(s,10);return l<t[0].length?String(t[0][l]):o});let i=/%([sdijfo%])/g,n=0,r=e.replace(i,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let l=t[n++];switch(s){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 o}});if(n<t.length)r+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return r}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(i,n,r)=>{let o=fe.underline(fe.blue(n)),s=this.toAbsoluteFilePath(r);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(s)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${l}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${r}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),t=t.replace(/`([^`]+)`/g,(i,n)=>fe.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(i,n)=>fe.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(i,n)=>fe.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(i,n)=>fe.italic(n)),t=t.replace(/~([^~]+)~/g,(i,n)=>fe.strikethrough(n)),t}supportsHyperlinks(){if(Fe())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 i=ye.env.HOME||"";if(i)t=t.replace(/^~(?=$|\/)/,i)}if(lu(t)||t.startsWith("./")||t.startsWith("../"))t=cu(t);else return null;return Ji(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 n=new Date,r=this.formatConsoleTimestamp(n),o=this.formatFileTimestamp(n),s,l;if(t instanceof Error)s=t.message,l=t.stack;else s=this.formatMessage(t,i);let{consoleText:c,fileText:f}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let a=this.options.showIcons===!1?"":Ua[e],m=this.options.showTags!==!1&&this.name?fe.gray(this.formatTag(this.name)):"",y;switch(e){case"debug":y=this.formatConsoleMessage({timestamp:r,icon:a,tag:m,message:fe.gray(c),level:e}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:r,icon:a,tag:m,message:c,level:e}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:r,icon:a,tag:m,message:fe.green(c),level:e}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:r,icon:a,tag:m,message:c,level:e}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:r,icon:a,tag:m,message:c,level:e}),console.error(y),l){let w=l.split(`
|
|
44
|
-
`);for(let C of w)if(C.trim()&&!C.includes(
|
|
63
|
+
`;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(e){let t=performance.now();if(this.fancy&&!Re()){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),s=`${e} completed in ${i}ms`,o=new Date,l=this.formatConsoleTimestamp(o),c=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
|
|
64
|
+
`,c=c.replace(this.ANSI_PATTERN,""),this.fancy&&!Re()){let f=this.options.showTags!==!1&&this.name?Ee.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:Ee.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Re())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 yi(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(Re())throw Error("createReadStream is not supported in browser environments");if(!An(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Yo(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=kt.isBuffer(e)?e:kt.from(e,"base64"),i=n.slice(0,16),s=n.slice(-16),o=n.slice(16,-16),l=du("aes-256-gcm",r,i);return l.setAuthTag(s),kt.concat([l.update(o),l.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 Re()}isServerMode(){return!Re()}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&&!Re()){let s=e.split(`
|
|
65
|
+
`),o=Math.max(...s.map((u)=>u.length))+2,l=`\u250C${"\u2500".repeat(o)}\u2510`,c=`\u2514${"\u2500".repeat(o)}\u2518`,f=s.map((u)=>{let a=" ".repeat(o-u.length-2);return`\u2502 ${u}${a} \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(l)})),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(!Re())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let i=`${n} ${this.environment}.INFO: [BOX] ${e}
|
|
66
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(Re())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${Ee.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();He.stdin.removeListener("data",r);try{if(typeof He.stdin.setRawMode==="function")He.stdin.setRawMode(!1)}catch{}He.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof He.stdin.setRawMode==="function")He.stdin.setRawMode(!0)}catch{}He.stdin.resume(),He.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let i=/%([sdijfo%])/g,s=0;if(r=e.replace(i,(o,l)=>{if(l==="%")return"%";if(s>=t.length)return o;let c=t[s++];switch(l){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return o}}),s<t.length)r+=` ${t.slice(s).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`}if(this.fancy&&!Re()){let i=this.options.showTags!==!1&&this.name?Ee.gray(this.formatTag(this.name)):"",s=Ee.blue("\u25D0");console.error(`${s} ${i} ${Ee.cyan(r)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
67
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(e,t=""){if(!this.enabled||!this.fancy||Re()||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||Re())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,n)),i!==void 0)this.activeProgressBar.message=i;let s=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,s)},finish:(n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Re())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||Re())return;He.stdout.write(`${"\r".padEnd(He.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||Re()||!He.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=Ee.green("\u2501".repeat(n)),o=Ee.gray("\u2501".repeat(i)),l=`[${s}${o}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=t||r===100?Ee.green("\u2713"):Ee.blue("\u25B6"),a=this.options.showTags!==!1&&this.name?` ${Ee.gray(this.formatTag(this.name))}`:"",m=`\r${u}${a} ${l} ${c}${f}`,y=He.stdout.columns||80,w=" ".repeat(Math.max(0,y-m.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${m}${w}`,He.stdout.write(e.lastRenderedLine),t)He.stdout.write(`
|
|
68
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Re()||!He.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(Re()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Kr(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let i=Qt(this.config.logDirectory,n);if(e.before)try{if((await Xt(i)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${i}:`,s);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Zr(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 oi(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 n=[...t];for(let i of e)if(we(i)&&"name"in i){if(!n.find((s)=>we(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(we(i)&&"path"in i){if(!n.find((s)=>we(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((s)=>Ci(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!we(t)||!we(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(we(i)&&we(r[n]))r[n]=oi(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&we(i[0])&&we(r[n][0])){let s=[...i];for(let o of r[n])if(we(o)&&"name"in o){if(!s.find((l)=>we(l)&&("name"in l)&&l.name===o.name))s.push(o)}else if(we(o)&&"path"in o){if(!s.find((l)=>we(l)&&("path"in l)&&l.path===o.path))s.push(o)}else if(!s.some((l)=>Ci(l,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function is(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:oi(e,t);if(Array.isArray(e))return r==="replace"?t:oi(e,t);if(!we(t)||!we(e))return t;let n={...e};for(let i of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,i))continue;let s=t[i],o=n[i];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")n[i]=s;else n[i]=oi(o,s);else if(we(s)&&we(o))n[i]=is(o,s,r);else n[i]=s}return n}function Ci(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(!Ci(e[r],t[r]))return!1;return!0}if(we(e)&&we(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(!Ci(e[i],t[i]))return!1}return!0}return!1}function we(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function ni(e,t,r="replace"){if(!Ta(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 is(t,i,r)}catch{return null}}catch{return null}}function ih(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function s(o,l=[]){let c={...o};for(let[f,u]of Object.entries(o)){let a=[...l,f],m=(C)=>C.replace(/([A-Z])/g,"_$1").toUpperCase(),y=`${n}_${a.map(m).join("_")}`,w=`${n}_${a.map((C)=>C.toUpperCase()).join("_")}`;if(r)Ke.info(`Checking environment variable ${y} for config ${e}.${a.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))c[f]=s(u,a);else{let C=wr.env[y]||wr.env[w];if(C!==void 0){if(r)Ke.info(`Using environment variable ${C?y:w} for config ${e}.${a.join(".")}`);if(typeof u==="number")c[f]=Number(C);else if(typeof u==="boolean")c[f]=C.toLowerCase()==="true";else if(Array.isArray(u))try{let x=JSON.parse(C);if(Array.isArray(x))c[f]=x;else c[f]=C.split(",").map((k)=>k.trim())}catch{c[f]=C.split(",").map((x)=>x.trim())}else c[f]=C}}}return c}return s(i)}async function nh({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:s=!1,checkEnv:o=!0,arrayStrategy:l="replace"}){let c=o&&typeof i==="object"&&i!==null&&!Array.isArray(i)?ih(e,i,s):i,f=r||wr.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)Ke.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${f}`);let a=[e,`.${e}`].filter(Boolean),m=[`${e}.config`,`.${e}.config`].filter(Boolean),y=t?[t,`.${t}`]:[],w=t?[`${t}.config`,`.${t}.config`]:[],C=Array.from(new Set([f,Je(f,"config"),Je(f,".config"),n?Je(f,n):void 0].filter(Boolean)));for(let x of C){if(s)Ke.info(`Searching for configuration in: ${x}`);let k=[Je(f,"config"),Je(f,".config")].concat(n?[Je(f,n)]:[]).includes(x)?[...a,...m,...y,...w]:[...m,...a,...w,...y];for(let L of k)for(let G of u){let T=Je(x,`${L}${G}`),D=await ni(T,c,l);if(D!==null){if(s)Ke.success(`Configuration loaded from: ${T}`);return D}}}if(e){let x=Je(bn(),".config",e),k=["config",`${e}.config`];if(t)k.push(`${t}.config`);if(s)Ke.info(`Checking user config directory: ${x}`);for(let L of k)for(let G of u){let T=Je(x,`${L}${G}`),D=await ni(T,c,l);if(D!==null){if(s)Ke.success(`Configuration loaded from user config directory: ${T}`);return D}}}if(e){let x=Je(bn(),".config"),k=[`.${e}.config`];if(t)k.push(`.${t}.config`);if(s)Ke.info(`Checking user config directory for dotfile configs: ${x}`);for(let L of k)for(let G of u){let T=Je(x,`${L}${G}`),D=await ni(T,c,l);if(D!==null){if(s)Ke.success(`Configuration loaded from user config directory dotfile: ${T}`);return D}}}if(e){let x=bn(),k=[`.${e}.config`,`.${e}`];if(t)k.push(`.${t}.config`),k.push(`.${t}`);if(s)Ke.info(`Checking user home directory for dotfile configs: ${x}`);for(let L of k)for(let G of u){let T=Je(x,`${L}${G}`),D=await ni(T,c,l);if(D!==null){if(s)Ke.success(`Configuration loaded from user home directory: ${T}`);return D}}}try{let x=Je(f,"package.json");if(Ta(x)){let k=await import(x),L=k[e];if(!L&&t){if(L=k[t],L&&s)Ke.success(`Using alias "${t}" configuration from package.json`)}if(L&&typeof L==="object"&&!Array.isArray(L))try{if(s)Ke.success(`Configuration loaded from package.json: ${L===k[e]?e:t}`);return is(c,L,l)}catch(G){if(s)Ke.warn("Failed to merge package.json config:",G)}}}catch(x){if(s)Ke.warn("Failed to load package.json:",x)}if(s)Ke.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function sh(e,t={}){let r=ui.cwd();while(r.includes("storage"))r=Ko(r,"..");let n=Ko(r,e||"");if(t?.relative)return cu(ui.cwd(),n);return n}async function oh(){try{let e=await nh({name:"clarity",alias:"logging",defaultConfig:ci,cwd:ui.cwd()});return{...ci,...e||{}}}catch{return ci}}function Ne(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ah(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof vt<"u"){let e=vt.type;if(e==="renderer"||e==="worker")return!1;return!!(vt.versions&&(vt.versions.node||vt.versions.bun))}return!1}class Da{async format(e){let t=await ah(),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:ir.pid,hostname:t(),environment:ir.env.NODE_ENV||"development",platform:ir.platform,version:ir.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ir.env.NODE_ENV||ir.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class wi{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 Da,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??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},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...fi,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...fi};return{...fi,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:jn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Ne()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,i=0,s=3,o=1000;while(i<s)try{try{try{await Eu(this.config.logDirectory,ia.F_OK|ia.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Su(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 l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:yt.from(e);try{if(!Yr(this.currentLogFile))await Rn(this.currentLogFile,"",{mode:420});if(n=ra(this.currentLogFile,"a",420),bu(n,l,{flag:"a"}),ta(n),n!==void 0)On(n),n=void 0;if((await tr(this.currentLogFile)).size===0){if(await Rn(this.currentLogFile,l,{flag:"w",mode:420}),(await tr(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(i<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let a=o*2**i;await new Promise((m)=>setTimeout(m,a)),i++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(n!==void 0)try{On(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(l){if(i===s-1){let f=l,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),l}i++;let c=o*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return rr(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 rr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return rr(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(([,o],[,l])=>l.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,i);if(n.length>s)for(let[o]of n.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return Tn(16).toString("hex")}generateKey(){return Tn(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Tn(16),n=wu("aes-256-gcm",t,r),i=yt.isBuffer(e)?e:yt.from(e,"utf8"),s=n.update(i),o=n.final(),l=s.length+o.length,c=n.getAuthTag(),f=yt.allocUnsafe(16+l+16);return r.copy(f,0),s.copy(f,16),o.copy(f,16+s.length),c.copy(f,16+l),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=sa(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(yt.from(yt.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 tr(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Jr(this.config.logDirectory),s=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${r}.${o}`;if(await tr(r).catch(()=>null))try{if(await na(r,l),t.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await qr(l)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await Rn(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await tr(r).catch(()=>null))await na(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await Jr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await qr(rr(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=ea(e),n=vu(t),i=sa();await Tu(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()})),Yr(this.currentLogFile))try{let e=ra(this.currentLogFile,"r+");ta(e),On(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Ne()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Jr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await qr(rr(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()?fe.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Ne())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:s,showTimestamp:o=!0}=e,l=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(o)y.push(t);if(s==="warning")y.push("WARN");else if(s==="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(s==="warning"||s==="error")f=`${r} ${i}`;else if(s==="info"||s==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${fe.cyan(i)}`;if(!o)return f.trim();let u=l(f).trim().length,a=l(t).length,m=Math.max(1,c-2-u-a);return`${f.trim()}${" ".repeat(m)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let l=Number.parseInt(o,10);return l<t[0].length?String(t[0][l]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let l=t[n++];switch(o){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}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=fe.underline(fe.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(o)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${l}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>fe.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>fe.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>fe.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>fe.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>fe.strikethrough(n)),t}supportsHyperlinks(){if(Ne())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(Au(t)||t.startsWith("./")||t.startsWith("../"))t=xu(t);else return null;return Yr(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,l;if(t instanceof Error)o=t.message,l=t.stack;else o=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let a=this.options.showIcons===!1?"":Va[e],m=this.options.showTags!==!1&&this.name?fe.gray(this.formatTag(this.name)):"",y;switch(e){case"debug":y=this.formatConsoleMessage({timestamp:i,icon:a,tag:m,message:fe.gray(c),level:e}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:i,icon:a,tag:m,message:c,level:e}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:i,icon:a,tag:m,message:fe.green(c),level:e}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:i,icon:a,tag:m,message:c,level:e}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:i,icon:a,tag:m,message:c,level:e}),console.error(y),l){let w=l.split(`
|
|
69
|
+
`);for(let C of w)if(C.trim()&&!C.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:fe.gray(` ${C}`),level:e,showTimestamp:!1}))}break}}else if(!Ne()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),l)console.error(l)}if(!this.shouldLog(e))return;let u=`${s} ${this.environment}.${e.toUpperCase()}: ${f}
|
|
45
70
|
`;if(l)u+=`${l}
|
|
46
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let
|
|
47
|
-
`);if(this[
|
|
48
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?fe.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":fe.green("\u2713"),tag:f,message:`${
|
|
49
|
-
`),c=Math.max(...l.map((m)=>m.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,a=l.map((m)=>this.formatConsoleMessage({timestamp:
|
|
50
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
51
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
52
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||
|
|
71
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(i,s)=>{},finish:(i)=>{},interrupt:(i,s)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!Ne()&&ye.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(i,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,i),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!Ne()&&ye.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,s="info")=>{if(!Ne()&&ye.stdout.isTTY)ye.stdout.write(`
|
|
72
|
+
`);if(this[s==="warning"?"warn":s](i),this.activeProgressBar&&this.shouldStyleConsole()&&!Ne()&&ye.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?fe.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":fe.blue("\u25D0"),tag:r,message:`${fe.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,l=this.formatConsoleTimestamp(o),c=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
|
|
73
|
+
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?fe.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":fe.green("\u2713"),tag:f,message:`${s}${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 wi(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(!Yr(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=yt.isBuffer(e)?e:yt.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),l=$u("aes-256-gcm",r,i);l.setAuthTag(s);let c=l.update(o),f=l.final(),u=c.length+f.length,a=yt.allocUnsafe(u);return c.copy(a,0),f.copy(a,c.length),a.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:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let l=i.split(`
|
|
74
|
+
`),c=Math.max(...l.map((m)=>m.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,a=l.map((m)=>this.formatConsoleMessage({timestamp:r,message:fe.cyan(m),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:fe.cyan(f),showTimestamp:!1})),a.forEach((m)=>console.error(m)),console.error(this.formatConsoleMessage({timestamp:r,message:fe.cyan(u),showTimestamp:!1}))}else if(!Ne())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
|
|
75
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(Ne())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${fe.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 o=/%([sdijfo%])/g,l=0;if(r=e.replace(o,(c,f)=>{if(f==="%")return"%";if(l>=t.length)return c;let u=t[l++];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}}),l<t.length)r+=` ${t.slice(l).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?fe.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${fe.blue("\u25D0")} `;console.error(`${l}${o} ${fe.cyan(n)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
76
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}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,s=fe.green("\u2501".repeat(n)),o=fe.gray("\u2501".repeat(i)),l=`[${s}${o}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?fe.green("\u2713"):fe.blue("\u25B6"),a=this.options.showTags!==!1&&this.name?` ${fe.gray(this.formatTag(this.name))}`:"",m=`\r${u}${a} ${l} ${c}${f}`,y=ye.stdout.columns||80,w=" ".repeat(Math.max(0,y-m.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${m}${w}`,ye.stdout.write(e.lastRenderedLine),t)ye.stdout.write(`
|
|
77
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ne()||!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(Ne()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Jr(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let i=rr(this.config.logDirectory,n);if(e.before)try{if((await tr(i)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${i}:`,s);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await qr(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Ia(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let l=0;l<=r;l++)try{return await e()}catch(c){if(o=c instanceof Error?c:Error(String(c)),l===r||!i(o))break;if(n>0)await new Promise((f)=>setTimeout(f,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function Fa(e){return e instanceof et}function lh(e){return e instanceof $i}function ch(e){if(Fa(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 xi{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:l=!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),a={...t};return this.processObject(a,[],u,{useCamelCase:i,useBackwardCompatibility:s,customParsers:o,verbose:l,configName:e}),{config:a,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return br.track("applyEnvironmentVariables",f,{configName:e});return f()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],l=o.map((u)=>this.formatEnvKey(u,n.useCamelCase)),c=`${r}_${l.join("_")}`,f=n.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,n);else{let u=zr.env[c]||(f?zr.env[f]:void 0);if(u!==void 0){if(n.verbose){let a=zr.env[c]?c:f}try{e[i]=this.parseEnvironmentValue(u,typeof s,c,n.customParsers,n.configName)}catch(a){if(a instanceof vi)throw a;throw Mt.envVar(c,u,typeof s,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[s,o]of Object.entries(n))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw Mt.envVar(r,e,`${t} (via ${s.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(zr.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,s=n||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),i){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],l=`${r}_${o.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,n);else n.push({key:l,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
53
78
|
|
|
54
|
-
`;for(let n of e)
|
|
55
|
-
`,
|
|
56
|
-
`,
|
|
57
|
-
`,
|
|
79
|
+
`;for(let n of e)r+=`${n.key}
|
|
80
|
+
`,r+=` Type: ${n.type}
|
|
81
|
+
`,r+=` Description: ${n.description}
|
|
82
|
+
`,r+=` Example: ${n.example}
|
|
58
83
|
|
|
59
|
-
`;return
|
|
84
|
+
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
60
85
|
|
|
61
|
-
`;
|
|
62
|
-
`,
|
|
63
|
-
`;for(let n of e)
|
|
64
|
-
`;return i}}function zu(e,t){let i=ja("process");if(typeof i>"u"||!i.env)return t;let n=i.env[e];return n!==void 0?n:t}function La(e,t,i={}){return Wa(e,t,i,new WeakMap)}function Wa(e,t,i,n){let{arrayMergeMode:r="replace",skipNullish:o=!1,customMerger:s}=i;if(t===null||t===void 0)return o?e:t;if(s){let l=s(e,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(e))return Ba(e,t,r,n);if(!ot(t)||!ot(e))return t;return Zu(e,t,i,n)}function Ba(e,t,i,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(i){case"replace":return t;case"concat":return Ju(e,t);case"smart":return qu(e,t,n);default:return t}return t}function Ju(e,t){let i=[...t];for(let n of e)if(!i.some((r)=>Hn(r,n)))i.push(n);return i}function qu(e,t,i){if(t.length===0)return e;if(e.length===0)return t;if(ot(t[0])&&ot(e[0]))return Yu(e,t,i);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let r of e)if(!n.includes(r))n.push(r);return n}return t}function Yu(e,t,i){let n=[...t];for(let r of e){if(!ot(r)){n.push(r);continue}let o=["id","name","key","path","type"],s=!1;for(let l of o)if(l in r){if(n.find((c)=>ot(c)&&(l in c)&&c[l]===r[l])){s=!0;break}}if(!s)n.push(r)}return n}function Zu(e,t,i,n){let r=t;if(ot(r)&&n.has(r))return n.get(r);let o={...e};if(ot(r))n.set(r,o);for(let s in r){if(!Object.prototype.hasOwnProperty.call(r,s))continue;let l=r[s],c=o[s];if(i.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){o[s]=l;continue}if(ot(l)&&ot(c))o[s]=Wa(c,l,i,n);else if(Array.isArray(l)||Array.isArray(c))o[s]=Ba(c,l,i.arrayMergeMode||"smart",n);else o[s]=l}return o}function ao(e,t,i="replace"){return La(e,t,{arrayMergeMode:i==="replace"?"replace":"smart",skipNullish:!0})}function Hn(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(!Hn(e[i],t[i]))return!1;return!0}if(ot(e)&&ot(t)){let i=Object.keys(e),n=Object.keys(t);if(i.length!==n.length)return!1;for(let r of i){if(!Object.prototype.hasOwnProperty.call(t,r))return!1;if(!Hn(e[r],t[r]))return!1}return!0}return!1}function ot(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Tr{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,i={}){let{arrayStrategy:n="replace",useCache:r=!0,cacheTtl:o,trackPerformance:s=!0,verbose:l=!1}=i;if(r){let f=si.getWithFileCheck("file",e);if(f){if(l)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!Xi(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),a=u.default||u,m="default"in u,y=Object.keys(u).length>0;if(!m&&!y)throw new Ei(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof a!=="object"||a===null||Array.isArray(a))throw new Ei(e,Error("Configuration must export a valid object"),"unknown");let w={config:ao(t,a,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(r)si.setWithFileCheck("file",w,e,o);return w}catch(f){throw f instanceof Error?Pt.configLoad(e,f):Pt.configLoad(e,Error(String(f)))}};if(s)return Si.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,i={}){for(let n of e)try{let r=await this.loadFromPath(n,t,i);if(r)return r}catch(r){if(r instanceof Error&&r.name==="ConfigLoadError")throw r;if(i.verbose)console.warn(`Failed to load config from ${n}:`,r)}return null}generateConfigPaths(e,t,i){let n=this.generateNamePatterns(e,i),r=[];for(let o of n)for(let s of this.extensions)r.push(Dn(t,`${o}${s}`));return r}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 Na(async()=>Xi(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,i){let n=[];if(!Xi(e))return n;if(t||i){let r=this.generateNamePatterns(t||"",i);for(let o of r)for(let s of this.extensions){let l=Dn(e,`${o}${s}`);if(await this.checkFileAccess(l))n.push(l)}}else try{let{readdirSync:r}=await import("fs"),o=r(e);for(let s of o)if(this.looksLikeConfigFile(s)){let l=Dn(e,s);if(await this.checkFileAccess(l))n.push(l)}}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(!Xi(e))return t.push("Configuration file does not exist"),t;let i=await import(e),n=i.default||i;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:r}=await import("fs"),o=r(e,"utf8");JSON.parse(o)}catch(r){t.push(`Invalid JSON syntax: ${r}`)}}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(n)=>{try{let r=await this.loadFromPath(n,{},t);if(r)i.set(n,r.config)}catch(r){if(t.verbose)console.warn(`Failed to preload ${n}:`,r)}})),i}}class lo{async validateConfiguration(e,t,i={}){let{stopOnFirstError:n=!1,validateRequired:r=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:l=!0,verbose:c=!1}=i,f=async()=>{let u=[],a=[],m={stopOnFirstError:n,validateRequired:r,validateTypes:o,customRules:s,trackPerformance:l,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,m);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],m);else return this.validateWithJSONSchema(e,t,m)}catch(y){return u.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:u,warnings:a}}};if(l)return await Si.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,i){try{if(!uu(t))throw new vi(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),r=n.default||n;if(Array.isArray(r))return this.validateWithRules(e,r,i);else return this.validateWithJSONSchema(e,r,i)}catch(n){throw new vi(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,i){let n=[],r=[];return this.validateObjectAgainstSchema(e,t,"",n,r,i),{isValid:n.length===0,errors:n,warnings:r}}validateObjectAgainstSchema(e,t,i,n,r,o){if(o.validateTypes&&t.type){let s=Array.isArray(e)?"array":typeof e,l=Array.isArray(t.type)?t.type:[t.type];if(!l.includes(s)){if(n.push({path:i,message:`Expected type ${l.join(" or ")}, got ${s}`,expected:l.join(" or "),actual:s,rule:"type"}),o.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.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)n.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)n.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))n.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)n.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)n.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 l=i?`${i}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,l,n,r,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 l of t.required)if(!(l in s)){if(n.push({path:i?`${i}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[l,c]of Object.entries(t.properties))if(l in s){let f=i?`${i}.${l}`:l;if(this.validateObjectAgainstSchema(s[l],c,f,n,r,o),o.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(s))if(!l.has(c))r.push({path:i?`${i}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,i){let n=[],r=[];for(let o of t)try{let s=this.getValueByPath(e,o.path),l=this.validateWithRule(s,o,o.path);if(n.push(...l),i.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:r}}validateWithRule(e,t,i){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:i,message:t.message||`Property '${i}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let r=Array.isArray(e)?"array":typeof e;if(r!==t.type)n.push({path:i,message:t.message||`Expected type ${t.type}, got ${r}`,expected:t.type,actual:r,rule:"type"})}if(t.min!==void 0){let r=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(r<t.min)n.push({path:i,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:r,rule:"min"})}if(t.max!==void 0){let r=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(r>t.max)n.push({path:i,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:r,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.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))n.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 r=t.validator(e);if(r)n.push({path:i,message:t.message||r,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let i=t.split("."),n=e;for(let r of i)if(n&&typeof n==="object"&&r in n)n=n[r];else return;return n}generateRulesFromInterface(e){let t=[],i=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of i){let[,r,o,s]=n;t.push({path:r,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:Ha},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class co{fileLoader=new Tr;envProcessor=new Ar;validator=new lo;async loadConfig(e){let t=Date.now(),{cache:i,performance:n,schema:r,validate:o,...s}=e;try{if(i?.enabled){let c=this.checkCache(s.name||"",s);if(c)return c}let l;try{l=await this.loadConfigurationStrategies(s,!0,i)}catch(c){let f=s.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;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(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),a=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),m=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(m||u))throw c;if(a&&(!f||!m))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(!f)l={...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 l={...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(r||o)await this.validateConfiguration(l.config,r,o,s.name);if(i?.enabled&&l)this.cacheResult(s.name||"",l,i,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)ct.warn(`Slow configuration loading detected: ${c.duration}ms for ${s.name}`);l.metrics=c}return l}catch(l){let c=Date.now()-t;throw ct.error(`Configuration loading failed after ${c}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(e,t=!1,i){let{name:n="",alias:r,cwd:o,configDir:s,defaultConfig:l,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,a=o||Ft.cwd(),m=[],y=await this.loadLocalConfiguration(n,r,a,s,l,f,u,c,i);if(y)return m.push(...this.getLocalSearchPaths(n,r,a,s)),this.finalizeResult(y,m,c,n,u);let w=await this.loadHomeConfiguration(n,r,l,f,u,c);if(w)return m.push(...this.getHomeSearchPaths(n,r)),this.finalizeResult(w,m,c,n,u);let C=await this.loadPackageJsonConfiguration(n,r,a,l,f,u,c);if(C)return m.push(qe(a,"package.json")),this.finalizeResult(C,m,c,n,u);if(m.push(...this.getAllSearchPaths(n,r,a,s)),t)throw Pt.configNotFound(n,m,r);return{...await this.applyEnvironmentVariables(n,l,c,u),warnings:[`No configuration file found for "${n}"${r?` or alias "${r}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,i,n,r,o,s,l,c){let f=l?wi(e,r,s):r,u=this.getLocalDirectories(i,n);for(let a of u){if(s)ct.info(`Searching for configuration in: ${a}`);let m=this.fileLoader.generateConfigPaths(e,a,t),y=await this.fileLoader.tryLoadFromPaths(m,f,{arrayStrategy:o,verbose:s,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(y){if(s)ct.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(e,t,i,n,r,o){if(!e)return null;let s=o?wi(e,i,r):i,l=[qe(Yt(),".config",e),qe(Yt(),".config"),Yt()];for(let c of l){if(r)ct.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,s,{arrayStrategy:n,verbose:r});if(u){if(r)ct.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,i,n,r,o,s){let l=s?wi(e,n,o):n;try{let c=qe(i,"package.json");if(!Un(c))return null;let f=await import(c),u=f[e],a=e;if(!u&&t)u=f[t],a=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(o)ct.success(`Configuration loaded from package.json: ${a}`);return{config:ao(l,u,r),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(o)ct.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,i,n){if(!i||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:wi(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,i,n,r){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,i,n){let r=[];if(i){let o=i(e);if(o)r.push(...o)}if(t){let o=await this.validator.validateConfiguration(e,t);if(!o.isValid)r.push(...o.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(r.length>0)throw Pt.configValidation(n||"unknown",r,n)}checkCache(e,t){let i=this.generateCacheKey(e,t);return si.get(i)||null}cacheResult(e,t,i,n){let r=this.generateCacheKey(e,n);si.set(r,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,qe(e,"config"),qe(e,".config"),t?qe(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,i,n){let r=[];return r.push(...this.getLocalSearchPaths(e,t,i,n)),r.push(...this.getHomeSearchPaths(e,t)),r.push(qe(i,"package.json")),r}getLocalSearchPaths(e,t,i,n){let r=this.getLocalDirectories(i,n),o=[];for(let s of r)o.push(...this.fileLoader.generateConfigPaths(e,s,t));return o}getHomeSearchPaths(e,t){if(!e)return[];let i=[qe(Yt(),".config",e),qe(Yt(),".config"),Yt()],n=[];for(let r of i)n.push(...this.fileLoader.generateConfigPaths(e,r,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function ma(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 Xu(e){return vt.loadConfig({...e,__strictErrorHandling:!0})}async function Ga(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 n;if(i)n=await vt.loadConfig(e);else n=await vt.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let r=n instanceof Error?n.name:"UnknownError",o=n instanceof Error?n.message:String(n);if(!(r==="ConfigNotFoundError"||r==="ConfigLoadError"||r==="ConfigValidationError"||o.includes("config"))&&e.verbose)ct.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);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 vt.applyEnvironmentVariables(s.name||"",t,!0,s.verbose||!1))?.config??t;return t}}async function Qu(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await vt.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"&&ma(i)))return(await vt.applyEnvironmentVariables(e,{},!0,!1)).config;throw i}}try{return(await vt.loadConfig({...e,cwd:e.cwd||Ft.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&ma(t)))return(await vt.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function eh(e,t,i="replace"){let n=new Tr;try{let r=await n.loadFromPath(e,t,{arrayStrategy:i,useCache:!1,trackPerformance:!1});return r?r.config:null}catch{return null}}function wi(e,t,i=!1){let n=new Ar,r=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,l=[]){let c={...s};for(let[f,u]of Object.entries(s)){let a=[...l,f],m=[`${r}_${a.join("_").toUpperCase()}`,`${r}_${a.map((C)=>C.toUpperCase()).join("")}`,`${r}_${a.map((C)=>C.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,w;for(let C of m)if(y=Ft.env[C],y!==void 0){w=C;break}if(y!==void 0&&w)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(y.toLowerCase());else if(typeof u==="number"){let C=Number(y);if(!Number.isNaN(C))c[f]=C}else if(Array.isArray(u))try{c[f]=JSON.parse(y)}catch{c[f]=y.split(",").map((C)=>C.trim())}else c[f]=y;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=o(u,a)}return c}return o(t)}function th(e){let t=qe(Ft.cwd(),e.configDir),i=qe(Ft.cwd(),e.generatedDir),n=qe(i,"config-types.ts");if(!Un(Hs(n)))_f(Hs(n),{recursive:!0,mode:511});let r=Un(t)?Vf(t).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],o=`// Generated by bunfig v${Ph}
|
|
65
|
-
export type ConfigNames = ${
|
|
66
|
-
`;
|
|
67
|
-
${
|
|
86
|
+
`;r+=`| Variable | Type | Description | Example |
|
|
87
|
+
`,r+=`|----------|------|-------------|----------|
|
|
88
|
+
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
89
|
+
`;return r}}function fh(e,t){let r=Ba("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function Na(e,t,r={}){return Wa(e,t,r,new WeakMap)}function Wa(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let l=o(e,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(e))return La(e,t,i,n);if(!ot(t)||!ot(e))return t;return ph(e,t,r,n)}function La(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return uh(e,t);case"smart":return hh(e,t,n);default:return t}return t}function uh(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Vn(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(ot(t[0])&&ot(e[0]))return dh(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 dh(e,t,r){let n=[...t];for(let i of e){if(!ot(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let l of s)if(l in i){if(n.find((c)=>ot(c)&&(l in c)&&c[l]===i[l])){o=!0;break}}if(!o)n.push(i)}return n}function ph(e,t,r,n){let i=t;if(ot(i)&&n.has(i))return n.get(i);let s={...e};if(ot(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let l=i[o],c=s[o];if(r.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){s[o]=l;continue}if(ot(l)&&ot(c))s[o]=Wa(c,l,r,n);else if(Array.isArray(l)||Array.isArray(c))s[o]=La(c,l,r.arrayMergeMode||"smart",n);else s[o]=l}return s}function ns(e,t,r="replace"){return Na(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Vn(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Vn(e[r],t[r]))return!1;return!0}if(ot(e)&&ot(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Vn(e[i],t[i]))return!1}return!0}return!1}function ot(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Ti{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:o=!0,verbose:l=!1}=r;if(i){let f=ar.getWithFileCheck("file",e);if(f){if(l)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!Xr(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),a=u.default||u,m="default"in u,y=Object.keys(u).length>0;if(!m&&!y)throw new $r(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof a!=="object"||a===null||Array.isArray(a))throw new $r(e,Error("Configuration must export a valid object"),"unknown");let w={config:ns(t,a,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)ar.setWithFileCheck("file",w,e,s);return w}catch(f){throw f instanceof Error?Mt.configLoad(e,f):Mt.configLoad(e,Error(String(f)))}};if(o)return br.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(Pn(t,`${s}${o}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);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 Ia(async()=>Xr(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Xr(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let l=Pn(e,`${s}${o}`);if(await this.checkFileAccess(l))n.push(l)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let l=Pn(e,o);if(await this.checkFileAccess(l))n.push(l)}}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(!Xr(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class ss{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:l=!0,verbose:c=!1}=r,f=async()=>{let u=[],a=[],m={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:l,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,m);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],m);else return this.validateWithJSONSchema(e,t,m)}catch(y){return u.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:u,warnings:a}}};if(l)return await br.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!Ou(t))throw new vr(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 vr(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,l=Array.isArray(t.type)?t.type:[t.type];if(!l.includes(o)){if(n.push({path:r,message:`Expected type ${l.join(" or ")}, got ${o}`,expected:l.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let l=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,l,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let l of t.required)if(!(l in o)){if(n.push({path:r?`${r}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[l,c]of Object.entries(t.properties))if(l in o){let f=r?`${r}.${l}`:l;if(this.validateObjectAgainstSchema(o[l],c,f,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(o))if(!l.has(c))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),l=this.validateWithRule(o,s,s.path);if(n.push(...l),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,o]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:ja},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class os{fileLoader=new Ti;envProcessor=new xi;validator=new ss;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let c=this.checkCache(o.name||"",o);if(c)return c}let l;try{l=await this.loadConfigurationStrategies(o,!0,r)}catch(c){let f=o.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),a=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),m=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(m||u))throw c;if(a&&(!f||!m))l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(i||s)await this.validateConfiguration(l.config,i,s,o.name);if(r?.enabled&&l)this.cacheResult(o.name||"",l,r,o);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)ft.warn(`Slow configuration loading detected: ${c.duration}ms for ${o.name}`);l.metrics=c}return l}catch(l){let c=Date.now()-t;throw ft.error(`Configuration loading failed after ${c}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:l,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,a=s||Wt.cwd(),m=[],y=await this.loadLocalConfiguration(n,i,a,o,l,f,u,c,r);if(y)return m.push(...this.getLocalSearchPaths(n,i,a,o)),this.finalizeResult(y,m,c,n,u);let w=await this.loadHomeConfiguration(n,i,l,f,u,c);if(w)return m.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(w,m,c,n,u);let C=await this.loadPackageJsonConfiguration(n,i,a,l,f,u,c);if(C)return m.push(qe(a,"package.json")),this.finalizeResult(C,m,c,n,u);if(m.push(...this.getAllSearchPaths(n,i,a,o)),t)throw Mt.configNotFound(n,m,i);return{...await this.applyEnvironmentVariables(n,l,c,u),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,l,c){let f=l?Cr(e,i,o):i,u=this.getLocalDirectories(r,n);for(let a of u){if(o)ft.info(`Searching for configuration in: ${a}`);let m=this.fileLoader.generateConfigPaths(e,a,t),y=await this.fileLoader.tryLoadFromPaths(m,f,{arrayStrategy:s,verbose:o,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(y){if(o)ft.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?Cr(e,r,i):r,l=[qe(zt(),".config",e),qe(zt(),".config"),zt()];for(let c of l){if(i)ft.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,o,{arrayStrategy:n,verbose:i});if(u){if(i)ft.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let l=o?Cr(e,n,s):n;try{let c=qe(r,"package.json");if(!_n(c))return null;let f=await import(c),u=f[e],a=e;if(!u&&t)u=f[t],a=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)ft.success(`Configuration loaded from package.json: ${a}`);return{config:ns(l,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)ft.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Cr(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(i.length>0)throw Mt.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return ar.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);ar.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,qe(e,"config"),qe(e,".config"),t?qe(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(qe(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let o of i)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[qe(zt(),".config",e),qe(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 pa(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 mh(e){return Et.loadConfig({...e,__strictErrorHandling:!0})}async function Ga(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 Et.loadConfig(e);else n=await Et.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",s=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||s.includes("config"))&&e.verbose)ft.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let o=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await Et.applyEnvironmentVariables(o.name||"",t,!0,o.verbose||!1))?.config??t;return t}}async function gh(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await Et.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"&&pa(r)))return(await Et.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await Et.loadConfig({...e,cwd:e.cwd||Wt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&pa(t)))return(await Et.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function yh(e,t,r="replace"){let n=new Ti;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function Cr(e,t,r=!1){let n=new xi,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,l=[]){let c={...o};for(let[f,u]of Object.entries(o)){let a=[...l,f],m=[`${i}_${a.join("_").toUpperCase()}`,`${i}_${a.map((C)=>C.toUpperCase()).join("")}`,`${i}_${a.map((C)=>C.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,w;for(let C of m)if(y=Wt.env[C],y!==void 0){w=C;break}if(y!==void 0&&w)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(y.toLowerCase());else if(typeof u==="number"){let C=Number(y);if(!Number.isNaN(C))c[f]=C}else if(Array.isArray(u))try{c[f]=JSON.parse(y)}catch{c[f]=y.split(",").map((C)=>C.trim())}else c[f]=y;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,a)}return c}return s(t)}function Ch(e){let t=qe(Wt.cwd(),e.configDir),r=qe(Wt.cwd(),e.generatedDir),n=qe(r,"config-types.ts");if(!_n(jo(n)))su(jo(n),{recursive:!0,mode:511});let i=_n(t)?ou(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${Zh}
|
|
90
|
+
export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
|
|
91
|
+
`;au(n,s,{mode:438})}function wh(e){let t=null,r=null,n=()=>{if(!r)r=Ga(e).then((s)=>(t=s,s),(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)ft.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return o});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(s,o){if(t)return t[o];let l=i[o];return n(),l},has(s,o){return o in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(s,o){return Object.getOwnPropertyDescriptor(t||i,o)},set(s,o,l){if(!t)t={...i};return t[o]=l,!0}})}function $h(e){let t=oa(ku.cwd(),e?.configDir||"./config");function r(){if(!Ru(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=Pu(t).filter((c)=>i.has(kn(c))).map((c)=>({base:c.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:c})),l=new Map;for(let{base:c,file:f}of o){let u=kn(f).toLowerCase(),a=l.get(c);if(!a){l.set(c,f);continue}let m=kn(a).toLowerCase();if(s.indexOf(u)<s.indexOf(m))l.set(c,f)}return Array.from(l.entries()).map(([c,f])=>({base:c,file:f})).sort((c,f)=>c.base.localeCompare(f.base))}function n(){let i=r(),s=i.map((c)=>c.base),o=s.length?s.map((c)=>`'${c}'`).join(" | "):"string",l=i.length?`{
|
|
92
|
+
${i.map((c)=>{let f=oa(t,c.file).replace(/\\/g,"/");return` '${c.base}': typeof import('${f}').default`}).join(`,
|
|
68
93
|
`)}
|
|
69
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${
|
|
94
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${o}
|
|
70
95
|
export type ConfigByName = ${l}
|
|
71
96
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
72
97
|
export type ConfigOf = Config
|
|
73
|
-
`}return{name:"bunfig-plugin",setup(r){r.onResolve({filter:/^virtual:bunfig-types$/},(o)=>({path:o.path,namespace:"bunfig-virtual"})),r.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:n(),loader:"ts"}))}}}function Mh(e,t={}){let i=pr.cwd();while(i.includes("storage"))i=la(i,"..");let n=la(i,e||"");if(t?.relative)return gu(pr.cwd(),n);return n}function We(){if(Et.env.NODE_ENV==="test"||Et.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ih(){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 Ya{async format(e){let t=await Ih(),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:oi.pid,hostname:t(),environment:oi.env.NODE_ENV||"development",platform:oi.platform,version:oi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:oi.env.NODE_ENV||oi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Or{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={...vr},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ya,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Ce.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let i={...t},n=t.timestamp!==void 0;if(n)delete i.timestamp;if(this.config={...this.config,...i,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let r=this.generateKeyId(),o=this.generateKey();this.currentKeyId=r,this.keys.set(r,o),this.encryptionKeys.set(r,{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{...Vn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Vn};return{...Vn,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:vr.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(([,n])=>n!==void 0))};if(!i.level||!["debug","info","success","warning","error"].includes(i.level))i.level=t.level;return i}shouldWriteToFile(){return!We()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,r=0,o=3,s=1000;while(r<o)try{try{try{await Eu(this.config.logDirectory,ha.F_OK|ha.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await vu(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 l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:yt.from(e);try{if(!Qi(this.currentLogFile))await Ln(this.currentLogFile,"",{mode:420});if(n=ua(this.currentLogFile,"a",420),bu(n,l,{flag:"a"}),fa(n),n!==void 0)Fn(n),n=void 0;if((await ri(this.currentLogFile)).size===0){if(await Ln(this.currentLogFile,l,{flag:"w",mode:420}),(await ri(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(r<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${r+1}/${o}:`,u);let a=s*2**r;await new Promise((m)=>setTimeout(m,a)),r++;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{Fn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(l){if(r===o-1){let f=l,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),l}r++;let c=s*2**(r-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let i=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}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 ni(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 ni(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ni(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,i=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},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 n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,l])=>l.createdAt.getTime()-s.createdAt.getTime()),r=typeof e.maxKeys==="number"?e.maxKeys:1,o=Math.max(1,r);if(n.length>o)for(let[s]of n.slice(o))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return Nn(16).toString("hex")}generateKey(){return Nn(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=Nn(16),n=yu("aes-256-gcm",t,i),r=yt.isBuffer(e)?e:yt.from(e,"utf8"),o=n.update(r),s=n.final(),l=o.length+s.length,c=n.getAuthTag(),f=yt.allocUnsafe(16+l+16);return i.copy(f,0),o.copy(f,16),s.copy(f,16+o.length),c.copy(f,16+l),{encrypted:f,iv:i}}async compressData(e){return new Promise((t,i)=>{let n=pa(),r=[];n.on("data",(o)=>r.push(o)),n.on("end",()=>t(yt.from(yt.concat(r)))),n.on("error",i),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 ri(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,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let r=await er(this.config.logDirectory),o=r.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,l=`${i}.${s}`;if(await ri(i).catch(()=>null))try{if(await da(i,l),t.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await tr(l)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!r.some((c)=>c.endsWith(".log.1")))try{let c=`${i}.1`;await Ln(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let r=new Date().toISOString().replace(/[:.]/g,"-"),o=i.replace(/\.log$/,`-${r}.log`);if(await ri(i).catch(()=>null))await da(i,o)}if(this.currentLogFile=n,t.maxFiles){let r=(await er(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of r.slice(t.maxFiles))await tr(ni(this.config.logDirectory,o))}}}async compressLogFile(e,t){let i=ca(e),n=wu(t),r=pa();await xu(i,r,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let i of this.logBuffer){let n=await this.formatter.format(i);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()})),Qi(this.currentLogFile))try{let e=ua(this.currentLogFile,"r+");fa(e),Fn(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 er(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await tr(ni(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()?pe.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||We())return!1;let e=typeof Ce.env.NO_COLOR<"u",t=Ce.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof Ce.stderr<"u"&&Ce.stderr.isTTY||typeof Ce.stdout<"u"&&Ce.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:i="",tag:n="",message:r,level:o,showTimestamp:s=!0}=e,l=(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(i)y.push(i.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)y.push(n.replace(/[[\]]/g,""));return y.push(r),y.join(" ")}let c=Ce.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${i} ${r}`;else if(o==="info"||o==="success")f=`${i} ${n} ${r}`;else f=`${i} ${n} ${pe.cyan(r)}`;if(!s)return f.trim();let u=l(f).trim().length,a=l(t).length,m=Math.max(1,c-2-u-a);return`${f.trim()}${" ".repeat(m)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let l=Number.parseInt(s,10);return l<t[0].length?String(t[0][l]):o});let i=/%([sdijfo%])/g,n=0,r=e.replace(i,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let l=t[n++];switch(s){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 o}});if(n<t.length)r+=` ${t.slice(n).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return r}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(i,n,r)=>{let o=pe.underline(pe.blue(n)),s=this.toAbsoluteFilePath(r);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(s)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${l}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${r}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),t=t.replace(/`([^`]+)`/g,(i,n)=>pe.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(i,n)=>pe.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(i,n)=>pe.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(i,n)=>pe.italic(n)),t=t.replace(/~([^~]+)~/g,(i,n)=>pe.strikethrough(n)),t}supportsHyperlinks(){if(We())return!1;let e=Ce.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let i=Ce.env.HOME||"";if(i)t=t.replace(/^~(?=$|\/)/,i)}if(Su(t)||t.startsWith("./")||t.startsWith("../"))t=$u(t);else return null;return Qi(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 n=new Date,r=this.formatConsoleTimestamp(n),o=this.formatFileTimestamp(n),s,l;if(t instanceof Error)s=t.message,l=t.stack;else s=this.formatMessage(t,i);let{consoleText:c,fileText:f}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let a=this.options.showIcons===!1?"":Bh[e],m=this.options.showTags!==!1&&this.name?pe.gray(this.formatTag(this.name)):"",y;switch(e){case"debug":y=this.formatConsoleMessage({timestamp:r,icon:a,tag:m,message:pe.gray(c),level:e}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:r,icon:a,tag:m,message:c,level:e}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:r,icon:a,tag:m,message:pe.green(c),level:e}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:r,icon:a,tag:m,message:c,level:e}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:r,icon:a,tag:m,message:c,level:e}),console.error(y),l){let w=l.split(`
|
|
74
|
-
`);for(let C of w)if(C.trim()&&!C.includes(
|
|
98
|
+
`}return{name:"bunfig-plugin",setup(i){i.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:n(),loader:"ts"}))}}}function Jh(e,t={}){let r=pi.cwd();while(r.includes("storage"))r=aa(r,"..");let n=aa(r,e||"");if(t?.relative)return Du(pi.cwd(),n);return n}function Le(){if(bt.env.NODE_ENV==="test"||bt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function zh(){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 Ja{async format(e){let t=await zh(),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:or.pid,hostname:t(),environment:or.env.NODE_ENV||"development",platform:or.platform,version:or.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:or.env.NODE_ENV||or.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Oi{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={...bi},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ja,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Ce.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Bn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Bn};return{...Bn,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:bi.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!Le()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,i=0,s=3,o=1000;while(i<s)try{try{try{await Lu(this.config.logDirectory,ua.F_OK|ua.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Gu(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 l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Ct.from(e);try{if(!Qr(this.currentLogFile))await In(this.currentLogFile,"",{mode:420});if(n=fa(this.currentLogFile,"a",420),Wu(n,l,{flag:"a"}),ca(n),n!==void 0)Dn(n),n=void 0;if((await nr(this.currentLogFile)).size===0){if(await In(this.currentLogFile,l,{flag:"w",mode:420}),(await nr(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(i<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let a=o*2**i;await new Promise((m)=>setTimeout(m,a)),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(l){if(i===s-1){let f=l,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),l}i++;let c=o*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return 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(Le())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,o],[,l])=>l.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,i);if(n.length>s)for(let[o]of n.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return 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=Iu("aes-256-gcm",t,r),i=Ct.isBuffer(e)?e:Ct.from(e,"utf8"),s=n.update(i),o=n.final(),l=s.length+o.length,c=n.getAuthTag(),f=Ct.allocUnsafe(16+l+16);return r.copy(f,0),s.copy(f,16),o.copy(f,16+s.length),c.copy(f,16+l),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=da(),i=[];n.on("data",(s)=>i.push(s)),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(Le())return;if(!this.shouldWriteToFile())return;let e=await nr(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),s=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${r}.${o}`;if(await nr(r).catch(()=>null))try{if(await ha(r,l),t.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await ti(l)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await In(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await nr(r).catch(()=>null))await ha(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await ei(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await ti(sr(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=la(e),n=Nu(t),i=da();await Uu(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=fa(this.currentLogFile,"r+");ca(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(!Le()&&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(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()?pe.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Le())return!1;let e=typeof Ce.env.NO_COLOR<"u",t=Ce.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof Ce.stderr<"u"&&Ce.stderr.isTTY||typeof Ce.stdout<"u"&&Ce.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,l=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(o)y.push(t);if(s==="warning")y.push("WARN");else if(s==="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=Ce.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${i}`;else if(s==="info"||s==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${pe.cyan(i)}`;if(!o)return f.trim();let u=l(f).trim().length,a=l(t).length,m=Math.max(1,c-2-u-a);return`${f.trim()}${" ".repeat(m)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let l=Number.parseInt(o,10);return l<t[0].length?String(t[0][l]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let l=t[n++];switch(o){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}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=pe.underline(pe.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(o)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${l}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>pe.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>pe.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>pe.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>pe.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>pe.strikethrough(n)),t}supportsHyperlinks(){if(Le())return!1;let e=Ce.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=Ce.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Bu(t)||t.startsWith("./")||t.startsWith("../"))t=_u(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){if(!this.shouldLog(e))return;let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,l;if(t instanceof Error)o=t.message,l=t.stack;else o=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let a=this.options.showIcons===!1?"":rd[e],m=this.options.showTags!==!1&&this.name?pe.gray(this.formatTag(this.name)):"",y;switch(e){case"debug":y=this.formatConsoleMessage({timestamp:i,icon:a,tag:m,message:pe.gray(c),level:e}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:i,icon:a,tag:m,message:c,level:e}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:i,icon:a,tag:m,message:pe.green(c),level:e}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:i,icon:a,tag:m,message:c,level:e}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:i,icon:a,tag:m,message:c,level:e}),console.error(y),l){let w=l.split(`
|
|
99
|
+
`);for(let C of w)if(C.trim()&&!C.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:pe.gray(` ${C}`),level:e,showTimestamp:!1}))}break}}else if(!Le()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),l)console.error(l)}let u=`${s} ${this.environment}.${e.toUpperCase()}: ${f}
|
|
75
100
|
`;if(l)u+=`${l}
|
|
76
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let
|
|
77
|
-
`);if(this[
|
|
78
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?pe.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":pe.green("\u2713"),tag:f,message:`${
|
|
79
|
-
`),c=Math.max(...l.map((m)=>m.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,a=l.map((m)=>this.formatConsoleMessage({timestamp:
|
|
80
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
81
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
82
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||
|
|
101
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(i,s)=>{},finish:(i)=>{},interrupt:(i,s)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!Le()&&Ce.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(i,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,i),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!Le()&&Ce.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,s="info")=>{if(!Le()&&Ce.stdout.isTTY)Ce.stdout.write(`
|
|
102
|
+
`);if(this[s==="warning"?"warn":s](i),this.activeProgressBar&&this.shouldStyleConsole()&&!Le()&&Ce.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?pe.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":pe.blue("\u25D0"),tag:r,message:`${pe.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,l=this.formatConsoleTimestamp(o),c=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
|
|
103
|
+
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?pe.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":pe.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Le())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 Oi(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(Le())throw Error("createReadStream is not supported in browser environments");if(!Qr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return la(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),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),l=Fu("aes-256-gcm",r,i);l.setAuthTag(s);let c=l.update(o),f=l.final(),u=c.length+f.length,a=Ct.allocUnsafe(u);return c.copy(a,0),f.copy(a,c.length),a.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 Le()}isServerMode(){return!Le()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let l=i.split(`
|
|
104
|
+
`),c=Math.max(...l.map((m)=>m.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,a=l.map((m)=>this.formatConsoleMessage({timestamp:r,message:pe.cyan(m),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:pe.cyan(f),showTimestamp:!1})),a.forEach((m)=>console.error(m)),console.error(this.formatConsoleMessage({timestamp:r,message:pe.cyan(u),showTimestamp:!1}))}else if(!Le())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
|
|
105
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(Le())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${pe.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();Ce.stdin.removeListener("data",r);try{if(typeof Ce.stdin.setRawMode==="function")Ce.stdin.setRawMode(!1)}catch{}Ce.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof Ce.stdin.setRawMode==="function")Ce.stdin.setRawMode(!0)}catch{}Ce.stdin.resume(),Ce.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,l=0;if(r=e.replace(o,(c,f)=>{if(f==="%")return"%";if(l>=t.length)return c;let u=t[l++];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}}),l<t.length)r+=` ${t.slice(l).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?pe.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${pe.blue("\u25D0")} `;console.error(`${l}${o} ${pe.cyan(n)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
106
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!Ce.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=pe.green("\u2501".repeat(n)),o=pe.gray("\u2501".repeat(i)),l=`[${s}${o}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?pe.green("\u2713"):pe.blue("\u25B6"),a=this.options.showTags!==!1&&this.name?` ${pe.gray(this.formatTag(this.name))}`:"",m=`\r${u}${a} ${l} ${c}${f}`,y=Ce.stdout.columns||80,w=" ".repeat(Math.max(0,y-m.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${m}${w}`,Ce.stdout.write(e.lastRenderedLine),t)Ce.stdout.write(`
|
|
107
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Le()||!Ce.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Le()){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=sr(this.config.logDirectory,n);if(e.before)try{if((await nr(i)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${i}:`,s);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await 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 id(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let l=0;l<=r;l++)try{return await e()}catch(c){if(o=c instanceof Error?c:Error(String(c)),l===r||!i(o))break;if(n>0)await new Promise((f)=>setTimeout(f,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}class ls{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:l=!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),a={...t};return this.processObject(a,[],u,{useCamelCase:i,useBackwardCompatibility:s,customParsers:o,verbose:l,configName:e}),{config:a,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return Qn.track("applyEnvironmentVariables",f,{configName:e});return f()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],l=o.map((u)=>this.formatEnvKey(u,n.useCamelCase)),c=`${r}_${l.join("_")}`,f=n.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,n);else{let u=ri.env[c]||(f?ri.env[f]:void 0);if(u!==void 0){if(n.verbose){let a=ri.env[c]?c:f}try{e[i]=this.parseEnvironmentValue(u,typeof s,c,n.customParsers,n.configName)}catch(a){if(a instanceof as)throw a;throw lr.envVar(c,u,typeof s,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[s,o]of Object.entries(n))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw lr.envVar(r,e,`${t} (via ${s.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(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,s=n||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),i){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],l=`${r}_${o.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,n);else n.push({key:l,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
83
108
|
|
|
84
|
-
`;for(let n of e)
|
|
85
|
-
`,
|
|
86
|
-
`,
|
|
87
|
-
`,
|
|
109
|
+
`;for(let n of e)r+=`${n.key}
|
|
110
|
+
`,r+=` Type: ${n.type}
|
|
111
|
+
`,r+=` Description: ${n.description}
|
|
112
|
+
`,r+=` Example: ${n.example}
|
|
88
113
|
|
|
89
|
-
`;return
|
|
114
|
+
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
90
115
|
|
|
91
|
-
`;
|
|
92
|
-
`,
|
|
93
|
-
`;for(let n of e)
|
|
94
|
-
`;return i}}function jh(e,t,i={}){return ol(e,t,i,new WeakMap)}function ol(e,t,i,n){let{arrayMergeMode:r="replace",skipNullish:o=!1,customMerger:s}=i;if(t===null||t===void 0)return o?e:t;if(s){let l=s(e,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(e))return sl(e,t,r,n);if(!st(t)||!st(e))return t;return Kh(e,t,i,n)}function sl(e,t,i,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(i){case"replace":return t;case"concat":return _h(e,t);case"smart":return Vh(e,t,n);default:return t}return t}function _h(e,t){let i=[...t];for(let n of e)if(!i.some((r)=>to(r,n)))i.push(n);return i}function Vh(e,t,i){if(t.length===0)return e;if(e.length===0)return t;if(st(t[0])&&st(e[0]))return Uh(e,t,i);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let r of e)if(!n.includes(r))n.push(r);return n}return t}function Uh(e,t,i){let n=[...t];for(let r of e){if(!st(r)){n.push(r);continue}let o=["id","name","key","path","type"],s=!1;for(let l of o)if(l in r){if(n.find((c)=>st(c)&&(l in c)&&c[l]===r[l])){s=!0;break}}if(!s)n.push(r)}return n}function Kh(e,t,i,n){let r=t;if(st(r)&&n.has(r))return n.get(r);let o={...e};if(st(r))n.set(r,o);for(let s in r){if(!Object.prototype.hasOwnProperty.call(r,s))continue;let l=r[s],c=o[s];if(i.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){o[s]=l;continue}if(st(l)&&st(c))o[s]=ol(c,l,i,n);else if(Array.isArray(l)||Array.isArray(c))o[s]=sl(c,l,i.arrayMergeMode||"smart",n);else o[s]=l}return o}function al(e,t,i="replace"){return jh(e,t,{arrayMergeMode:i==="replace"?"replace":"smart",skipNullish:!0})}function to(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(!to(e[i],t[i]))return!1;return!0}if(st(e)&&st(t)){let i=Object.keys(e),n=Object.keys(t);if(i.length!==n.length)return!1;for(let r of i){if(!Object.prototype.hasOwnProperty.call(t,r))return!1;if(!to(e[r],t[r]))return!1}return!0}return!1}function st(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class ll{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,i={}){let{arrayStrategy:n="replace",useCache:r=!0,cacheTtl:o,trackPerformance:s=!0,verbose:l=!1}=i;if(r){let f=mr.getWithFileCheck("file",e);if(f){if(l)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!rr(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),a=u.default||u,m="default"in u,y=Object.keys(u).length>0;if(!m&&!y)throw new Sr(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof a!=="object"||a===null||Array.isArray(a))throw new Sr(e,Error("Configuration must export a valid object"),"unknown");let w={config:al(t,a,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(r)mr.setWithFileCheck("file",w,e,o);return w}catch(f){throw f instanceof Error?ai.configLoad(e,f):ai.configLoad(e,Error(String(f)))}};if(s)return io.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,i={}){for(let n of e)try{let r=await this.loadFromPath(n,t,i);if(r)return r}catch(r){if(r instanceof Error&&r.name==="ConfigLoadError")throw r;if(i.verbose)console.warn(`Failed to load config from ${n}:`,r)}return null}generateConfigPaths(e,t,i){let n=this.generateNamePatterns(e,i),r=[];for(let o of n)for(let s of this.extensions)r.push(Wn(t,`${o}${s}`));return r}generateNamePatterns(e,t){let i=[];if(i.push("config",".config"),e)i.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(i.push(o,`.${o}.config`,`${o}.config`,`.${o}`),e)i.push(`${e}.${o}.config`,`.${e}.${o}.config`)}let r=new Set;return i.filter((o)=>{if(!o||r.has(o))return!1;return r.add(o),!0})}checkFileAccess(e){return Gh(async()=>rr(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,i){let n=[];if(!rr(e))return n;if(t||i){let r=this.generateNamePatterns(t||"",i);for(let o of r)for(let s of this.extensions){let l=Wn(e,`${o}${s}`);if(await this.checkFileAccess(l))n.push(l)}}else try{let{readdirSync:r}=await import("fs"),o=r(e);for(let s of o)if(this.looksLikeConfigFile(s)){let l=Wn(e,s);if(await this.checkFileAccess(l))n.push(l)}}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(!rr(e))return t.push("Configuration file does not exist"),t;let i=await import(e),n=i.default||i;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:r}=await import("fs"),o=r(e,"utf8");JSON.parse(o)}catch(r){t.push(`Invalid JSON syntax: ${r}`)}}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(n)=>{try{let r=await this.loadFromPath(n,{},t);if(r)i.set(n,r.config)}catch(r){if(t.verbose)console.warn(`Failed to preload ${n}:`,r)}})),i}}class cl{async validateConfiguration(e,t,i={}){let{stopOnFirstError:n=!1,validateRequired:r=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:l=!0,verbose:c=!1}=i,f=async()=>{let u=[],a=[],m={stopOnFirstError:n,validateRequired:r,validateTypes:o,customRules:s,trackPerformance:l,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,m);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],m);else return this.validateWithJSONSchema(e,t,m)}catch(y){return u.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:u,warnings:a}}};if(l)return await io.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,i){try{if(!Au(t))throw new $r(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),r=n.default||n;if(Array.isArray(r))return this.validateWithRules(e,r,i);else return this.validateWithJSONSchema(e,r,i)}catch(n){throw new $r(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,i){let n=[],r=[];return this.validateObjectAgainstSchema(e,t,"",n,r,i),{isValid:n.length===0,errors:n,warnings:r}}validateObjectAgainstSchema(e,t,i,n,r,o){if(o.validateTypes&&t.type){let s=Array.isArray(e)?"array":typeof e,l=Array.isArray(t.type)?t.type:[t.type];if(!l.includes(s)){if(n.push({path:i,message:`Expected type ${l.join(" or ")}, got ${s}`,expected:l.join(" or "),actual:s,rule:"type"}),o.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.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)n.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)n.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))n.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)n.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)n.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 l=i?`${i}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,l,n,r,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 l of t.required)if(!(l in s)){if(n.push({path:i?`${i}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[l,c]of Object.entries(t.properties))if(l in s){let f=i?`${i}.${l}`:l;if(this.validateObjectAgainstSchema(s[l],c,f,n,r,o),o.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(s))if(!l.has(c))r.push({path:i?`${i}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,i){let n=[],r=[];for(let o of t)try{let s=this.getValueByPath(e,o.path),l=this.validateWithRule(s,o,o.path);if(n.push(...l),i.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:r}}validateWithRule(e,t,i){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:i,message:t.message||`Property '${i}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let r=Array.isArray(e)?"array":typeof e;if(r!==t.type)n.push({path:i,message:t.message||`Expected type ${t.type}, got ${r}`,expected:t.type,actual:r,rule:"type"})}if(t.min!==void 0){let r=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(r<t.min)n.push({path:i,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:r,rule:"min"})}if(t.max!==void 0){let r=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(r>t.max)n.push({path:i,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:r,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.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))n.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 r=t.validator(e);if(r)n.push({path:i,message:t.message||r,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let i=t.split("."),n=e;for(let r of i)if(n&&typeof n==="object"&&r in n)n=n[r];else return;return n}generateRulesFromInterface(e){let t=[],i=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of i){let[,r,o,s]=n;t.push({path:r,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:Hh},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function zh(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 fl{fileLoader=new ll;envProcessor=new uo;validator=new cl;async loadConfig(e){let t=Date.now(),{cache:i,performance:n,schema:r,validate:o,...s}=e;try{if(i?.enabled){let c=this.checkCache(s.name||"",s);if(c)return c}let l;try{l=await this.loadConfigurationStrategies(s,!0,i)}catch(c){let f=s.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;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(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),a=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),m=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(m||u))throw c;if(a&&(!f||!m))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(!f)l={...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 l={...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(r||o)await this.validateConfiguration(l.config,r,o,s.name);if(i?.enabled&&l)this.cacheResult(s.name||"",l,i,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)Ct.warn(`Slow configuration loading detected: ${c.duration}ms for ${s.name}`);l.metrics=c}return l}catch(l){if(l instanceof Error&&l.name==="ConfigNotFoundError")throw l;let c=Date.now()-t;throw Ct.error(`Configuration loading failed after ${c}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(e,t=!1,i){let{name:n="",alias:r,cwd:o,configDir:s,defaultConfig:l,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,a=o||xr.cwd(),m=[],y=await this.loadLocalConfiguration(n,r,a,s,l,f,u,c,i);if(y)return m.push(...this.getLocalSearchPaths(n,r,a,s)),this.finalizeResult(y,m,c,n,u);let w=await this.loadHomeConfiguration(n,r,l,f,u,c);if(w)return m.push(...this.getHomeSearchPaths(n,r)),this.finalizeResult(w,m,c,n,u);let C=await this.loadPackageJsonConfiguration(n,r,a,l,f,u,c);if(C)return m.push(nt(a,"package.json")),this.finalizeResult(C,m,c,n,u);if(m.push(...this.getAllSearchPaths(n,r,a,s)),t)throw ai.configNotFound(n,m,r);return{...await this.applyEnvironmentVariables(n,l,c,u),warnings:[`No configuration file found for "${n}"${zh(r)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,i,n,r,o,s,l,c){let f=l?or(e,r,s):r,u=this.getLocalDirectories(i,n);for(let a of u){if(s)Ct.info(`Searching for configuration in: ${a}`);let m=this.fileLoader.generateConfigPaths(e,a,t),y=await this.fileLoader.tryLoadFromPaths(m,f,{arrayStrategy:o,verbose:s,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(y){if(s)Ct.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(e,t,i,n,r,o){if(!e)return null;let s=o?or(e,i,r):i,l=[nt(qt(),".config",e),nt(qt(),".config"),qt()];for(let c of l){if(r)Ct.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,s,{arrayStrategy:n,verbose:r});if(u){if(r)Ct.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,i,n,r,o,s){let l=s?or(e,n,o):n;try{let c=nt(i,"package.json");if(!Gf(c))return null;let f={};try{f=JSON.parse(jf(c,"utf8"))}catch(m){if(o)Ct.warn("Failed to parse package.json:",[m instanceof Error?m:Error(String(m))]);return null}let u=f[e],a=e;if(!u&&t){let m=Array.isArray(t)?t:[t];for(let y of m){if(!y)continue;if(f[y]){u=f[y],a=y;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(o)Ct.success(`Configuration loaded from package.json: ${a}`);return{config:al(l,u,r),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(o)Ct.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,i,n){if(!i||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:or(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,i,n,r){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,i,n){let r=[];if(i){let o=i(e);if(o)r.push(...o)}if(t){let o=await this.validator.validateConfiguration(e,t);if(!o.isValid)r.push(...o.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(r.length>0)throw ai.configValidation(n||"unknown",r,n)}checkCache(e,t){let i=this.generateCacheKey(e,t);return mr.get(i)||null}cacheResult(e,t,i,n){let r=this.generateCacheKey(e,n);mr.set(r,t,void 0,i.ttl)}generateCacheKey(e,t){let i=[e];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;i.push(`alias:${n}`)}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,nt(e,"config"),nt(e,".config"),t?nt(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,i,n){let r=[];return r.push(...this.getLocalSearchPaths(e,t,i,n)),r.push(...this.getHomeSearchPaths(e,t)),r.push(nt(i,"package.json")),r}getLocalSearchPaths(e,t,i,n){let r=this.getLocalDirectories(i,n),o=[];for(let s of r)o.push(...this.fileLoader.generateConfigPaths(e,s,t));return o}getHomeSearchPaths(e,t){if(!e)return[];let i=[nt(qt(),".config",e),nt(qt(),".config"),qt()],n=[];for(let r of i)n.push(...this.fileLoader.generateConfigPaths(e,r,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function or(e,t,i=!1){let n=new uo,r=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,l=[]){let c={...s};for(let[f,u]of Object.entries(s)){let a=[...l,f],m=[`${r}_${a.join("_").toUpperCase()}`,`${r}_${a.map((C)=>C.toUpperCase()).join("")}`,`${r}_${a.map((C)=>C.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,w;for(let C of m)if(y=xr.env[C],y!==void 0){w=C;break}if(y!==void 0&&w)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(y.toLowerCase());else if(typeof u==="number"){let C=Number(y);if(!Number.isNaN(C))c[f]=C}else if(Array.isArray(u))try{c[f]=JSON.parse(y)}catch{c[f]=y.split(",").map((C)=>C.trim())}else c[f]=y;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=o(u,a)}return c}return o(t)}var mr,io,Tu,Ou=(e)=>e,Pu=(e,t)=>{for(var i in t)Tu(e,i,{get:t[i],enumerable:!0,configurable:!0,set:Ru.bind(t,i)})},ku=(e,t)=>()=>(e&&(t=e(e=0)),t),Ma,ja,si,Si,_a,nh,oh,ga,ar,zn,Ue,Se,sh,ya,ah,Ca,lh,ch,Bn,fh,wa,ba,Gn,uh,hh,dh,ph,lr,Va,mh,Ke,gh,yh,Ea,cr,Jn,Le,fe,Ch,va,wh,Sa,bh,Eh,jn,vh,$a,xa,Sh,_n,$h,xh,Ah,Th,Oh,fr,Ua,Rh,Ph="0.15.6",Qe,br,Ei,qn,Yn,Er,Zn,Xn,vi,Qn,eo,Pt,Ka,Ha,ct,vt,za,Ja,kh,Dh,qa,vr,Fy,Za,pe,Ly,Nh,Wy,Fh,By,Gy,Aa,jy,Lh,Wh,_y,Ta,Vy,Uy,Ky,Hy,zy,Vn,Bh,Jy,ft,Xa,Sr,Qa,el,fo,tl,il,$r,rl,nl,ai,Hh,Ct,qy,Yy,Zy,Jh,ul;var hl=de(()=>{mr=new Pa,io=new ka,Tu=Object.defineProperty;Ma={};Pu(Ma,{withErrorRecovery:()=>Na,tryLoadConfig:()=>eh,loadConfigWithResult:()=>Xu,loadConfig:()=>Ga,isRetryableError:()=>Hu,isConfigNotFoundError:()=>Ku,isBunfigError:()=>Fa,globalPerformanceMonitor:()=>Si,globalCache:()=>si,getEnvOrDefault:()=>zu,generateConfigTypes:()=>th,defaultGeneratedDir:()=>Ja,defaultConfigDir:()=>za,deepMergeWithArrayStrategy:()=>ao,deepMerge:()=>La,createLibraryConfig:()=>ih,config:()=>Qu,bunfigPlugin:()=>rh,applyEnvVarsToConfig:()=>wi,TypeGenerationError:()=>Xn,SchemaValidationError:()=>vi,PluginError:()=>eo,PerformanceMonitor:()=>no,FileSystemError:()=>Zn,ErrorFactory:()=>Pt,EnvVarError:()=>Er,EnvProcessor:()=>Ar,ConfigValidator:()=>lo,ConfigValidationError:()=>qn,ConfigNotFoundError:()=>br,ConfigMergeError:()=>Yn,ConfigLoader:()=>co,ConfigLoadError:()=>Ei,ConfigFileLoader:()=>Tr,ConfigCache:()=>ro,CacheUtils:()=>_a,BunfigError:()=>Qe,BrowserConfigError:()=>Qn,ArrayMergeStrategies:()=>Ka});kh=ku(async()=>{ja=import.meta.require,si=new ro,Si=new no,_a={createKey:Mu,isEquivalent:Du,estimateMemoryUsage:Iu},nh=dr(Kn.cwd(),"config"),oh=dr(Kn.cwd(),"src/generated"),ga=hr.env.CLARITY_LOG_DIR||zf(Lu(),"logs"),ar={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ga,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},zn=await Wu(),Ue={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"},Se=Ue,sh=Ue.red,ya=Ue.green,ah=Ue.yellow,Ca=Ue.blue,lh=Ue.magenta,ch=Ue.cyan,Bn=Ue.white,fh=Ue.gray,wa=Ue.bgRed,ba=Ue.bgYellow,Gn=Ue.bold,uh=Ue.dim,hh=Ue.italic,dh=Ue.underline,ph=Ue.reset,lr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Va={debug:"\uD83D\uDD0D",info:Ca("\u2139"),success:ya("\u2713"),warning:ba(Bn(Gn(" WARN "))),error:wa(Bn(Gn(" ERROR ")))},mh=new yr("stacks"),Ke=new yr("bunfig",{showTags:!0}),gh=Je(bi.cwd(),"config"),yh=Je(bi.cwd(),"src/generated"),Ea=ur.env.CLARITY_LOG_DIR||Kf(_u(),"logs"),cr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ea,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Jn=await Vu(),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"},fe=Le,Ch=Le.red,va=Le.green,wh=Le.yellow,Sa=Le.blue,bh=Le.magenta,Eh=Le.cyan,jn=Le.white,vh=Le.gray,$a=Le.bgRed,xa=Le.bgYellow,Sh=Le.bgGray,_n=Le.bold,$h=Le.dim,xh=Le.italic,Ah=Le.underline,Th=Le.strikethrough,Oh=Le.reset,fr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ua={debug:"\uD83D\uDD0D",info:Sa("\u2139"),success:va("\u2713"),warning:xa(jn(_n(" WARN "))),error:$a(jn(_n(" ERROR ")))},Rh=new wr("stacks"),Qe=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}`}},br=class extends Qe{code="CONFIG_NOT_FOUND";constructor(e,t,i){let n=i?` or alias "${i}"`:"";super(`Configuration "${e}"${n} not found`,{configName:e,alias:i,searchPaths:t,searchPathCount:t.length})}},Ei=class extends Qe{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}},qn=class extends Qe{code="CONFIG_VALIDATION_ERROR";constructor(e,t,i){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:i,validationErrors:t,errorCount:t.length})}},Yn=class extends Qe{code="CONFIG_MERGE_ERROR";constructor(e,t,i,n){super(`Failed to merge configuration from "${e}" with "${t}": ${i.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:i.name,originalMessage:i.message});this.cause=i}},Er=class extends Qe{code="ENV_VAR_ERROR";constructor(e,t,i,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${i}`,{envKey:e,envValue:t,expectedType:i,configName:n})}},Zn=class extends Qe{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}},Xn=class extends Qe{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}},vi=class extends Qe{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})}},Qn=class extends Qe{code="BROWSER_CONFIG_ERROR";constructor(e,t,i,n){super(`Failed to fetch configuration from "${e}": ${t} ${i}`,{endpoint:e,status:t,statusText:i,configName:n})}},eo=class extends Qe{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}},Pt={configNotFound(e,t,i){return new br(e,t,i)},configLoad(e,t,i){return new Ei(e,t,i)},configValidation(e,t,i){return new qn(e,t,i)},configMerge(e,t,i,n){return new Yn(e,t,i,n)},envVar(e,t,i,n){return new Er(e,t,i,n)},fileSystem(e,t,i){return new Zn(e,t,i)},typeGeneration(e,t,i){return new Xn(e,t,i)},schemaValidation(e,t,i){return new vi(e,t,i)},browserConfig(e,t,i,n){return new Qn(e,t,i,n)},plugin(e,t,i){return new eo(e,t,i)}},Ka={replace:"replace",concat:"concat",smart:"smart"},Ha=/^https?:\/\//,ct=new wr("bunfig",{showTags:!0}),vt=new co,za=qe(Ft.cwd(),"config"),Ja=qe(Ft.cwd(),"src/generated")});Dh=pr.env.CLARITY_LOG_DIR||mu(Mh(),"logs"),qa={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Dh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},vr={...qa},Fy=(async()=>{try{let{loadConfig:e}=await kh().then(()=>Ma),t=await e({name:"clarity",alias:"logging",defaultConfig:qa,cwd:pr.cwd()});if(t)Object.assign(vr,t)}catch{}return vr})();Za={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"},pe=Za,{red:Ly,green:Nh,yellow:Wy,blue:Fh,magenta:By,cyan:Gy,white:Aa,gray:jy,bgRed:Lh,bgYellow:Wh,bgGray:_y,bold:Ta,dim:Vy,italic:Uy,underline:Ky,strikethrough:Hy,reset:zy}=Za,Vn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Bh={debug:"\uD83D\uDD0D",info:Fh("\u2139"),success:Nh("\u2713"),warning:Wh(Aa(Ta(" WARN "))),error:Lh(Aa(Ta(" ERROR ")))};Jy=new Or("stacks");ft=class ft 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}`}};Xa=class Xa extends ft{code="CONFIG_NOT_FOUND";constructor(e,t,i){let n=i===void 0?[]:Array.isArray(i)?i.filter(Boolean):[i],r="";if(n.length===1)r=` or alias "${n[0]}"`;else if(n.length>1)r=` or aliases ${n.map((o)=>`"${o}"`).join(", ")}`;super(`Configuration "${e}"${r} not found`,{configName:e,alias:i,searchPaths:t,searchPathCount:t.length})}};Sr=class Sr extends ft{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}};Qa=class Qa extends ft{code="CONFIG_VALIDATION_ERROR";constructor(e,t,i){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:i,validationErrors:t,errorCount:t.length})}};el=class el extends ft{code="CONFIG_MERGE_ERROR";constructor(e,t,i,n){super(`Failed to merge configuration from "${e}" with "${t}": ${i.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:i.name,originalMessage:i.message});this.cause=i}};fo=class fo extends ft{code="ENV_VAR_ERROR";constructor(e,t,i,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${i}`,{envKey:e,envValue:t,expectedType:i,configName:n})}};tl=class tl extends ft{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}};il=class il extends ft{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}};$r=class $r extends ft{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})}};rl=class rl extends ft{code="BROWSER_CONFIG_ERROR";constructor(e,t,i,n){super(`Failed to fetch configuration from "${e}": ${t} ${i}`,{endpoint:e,status:t,statusText:i,configName:n})}};nl=class nl extends ft{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}};ai={configNotFound(e,t,i){return new Xa(e,t,i)},configLoad(e,t,i){return new Sr(e,t,i)},configValidation(e,t,i){return new Qa(e,t,i)},configMerge(e,t,i,n){return new el(e,t,i,n)},envVar(e,t,i,n){return new fo(e,t,i,n)},fileSystem(e,t,i){return new tl(e,t,i)},typeGeneration(e,t,i){return new il(e,t,i)},schemaValidation(e,t,i){return new $r(e,t,i)},browserConfig(e,t,i,n){return new rl(e,t,i,n)},plugin(e,t,i){return new nl(e,t,i)}};Hh=/^https?:\/\//;Ct=new Or("bunfig",{showTags:!0});qy=new fl;Yy=nt(xr.cwd(),"config"),Zy=nt(xr.cwd(),"src/generated"),Jh={cwd:Bf.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},ul=Jh});function dl(e,t,i){let n={file:t,message:"Unknown error",code:$i.UNKNOWN_ERROR};if(e instanceof Error){n.message=e.message,n.stack=e.stack;let r=e.message.match(/\((\d+),(\d+)\)/);if(r)n.location={line:Number.parseInt(r[1],10),column:Number.parseInt(r[2],10)};if(e.message.includes("Cannot find")||e.message.includes("not found"))n.code=$i.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=$i.SYNTAX_ERROR,n.suggestion="Check for syntax errors in your TypeScript code.";else if(e.message.includes("type")&&e.message.includes("cannot"))n.code=$i.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=$i.PARSE_ERROR,n.suggestion="The file contains invalid TypeScript syntax."}else if(typeof e==="string")n.message=e;return n}function pl(e,t){let i=[],n=e.file;if(e.location)n+=`:${e.location.line}:${e.location.column}`;if(e.code)n+=` [${e.code}]`;if(i.push(n),i.push(` Error: ${e.message}`),t&&e.location){i.push("");let r=t.split(`
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
`)
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
`)
|
|
104
|
-
|
|
105
|
-
`)
|
|
106
|
-
`)
|
|
107
|
-
|
|
108
|
-
`)
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
`)s
|
|
112
|
-
`)
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
`),i=null,n=Co(t);if(n.passthrough)return t;if(t=n.script,n.options){let C=Rr(n.options,"props");if(C)i=Mr(C)}let r=t,o=Cd(t),s=yd(r),l=s?.type??i??"{}",c=bo(r,null),f=Eo(r,null),u=Oi(r,"defineSlots")?.generic??null,a=s?.inlinedLocal;if(a)o=kr(o,a.name,a.declText);let m=`DefineComponent<${l}>`,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)m+=` & { ${y.join(", ")} }`;m=wo(m),o=wd(Pr(o,m));let w=["import type { DefineComponent } from '@stacksjs/stx'",`type __DtsxStxComponentType = ${m}`,"const __dtsx_component__: __DtsxStxComponentType = null as unknown as __DtsxStxComponentType","export default __dtsx_component__"];if(o.trim()!=="")w.push(o);return w.join(`
|
|
118
|
-
`)}var $l=de(()=>{vo()});function $t(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}
|
|
116
|
+
`;r+=`| Variable | Type | Description | Example |
|
|
117
|
+
`,r+=`|----------|------|-------------|----------|
|
|
118
|
+
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
119
|
+
`;return r}}function nd(e,t,r={}){return il(e,t,r,new WeakMap)}function il(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let l=o(e,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(e))return nl(e,t,i,n);if(!at(t)||!at(e))return t;return ld(e,t,r,n)}function nl(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 sd(e,t);case"smart":return od(e,t,n);default:return t}return t}function sd(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Xn(i,n)))r.push(n);return r}function od(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(at(t[0])&&at(e[0]))return ad(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 ad(e,t,r){let n=[...t];for(let i of e){if(!at(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let l of s)if(l in i){if(n.find((c)=>at(c)&&(l in c)&&c[l]===i[l])){o=!0;break}}if(!o)n.push(i)}return n}function ld(e,t,r,n){let i=t;if(at(i)&&n.has(i))return n.get(i);let s={...e};if(at(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let l=i[o],c=s[o];if(r.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){s[o]=l;continue}if(at(l)&&at(c))s[o]=il(c,l,r,n);else if(Array.isArray(l)||Array.isArray(c))s[o]=nl(c,l,r.arrayMergeMode||"smart",n);else s[o]=l}return s}function sl(e,t,r="replace"){return nd(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Xn(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Xn(e[r],t[r]))return!1;return!0}if(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(!Xn(e[i],t[i]))return!1}return!0}return!1}function at(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class ol{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:o=!0,verbose:l=!1}=r;if(i){let f=mi.getWithFileCheck("file",e);if(f){if(l)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),a=u.default||u,m="default"in u,y=Object.keys(u).length>0;if(!m&&!y)throw new Ei(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof a!=="object"||a===null||Array.isArray(a))throw new Ei(e,Error("Configuration must export a valid object"),"unknown");let w={config:sl(t,a,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)mi.setWithFileCheck("file",w,e,s);return w}catch(f){throw f instanceof Error?lr.configLoad(e,f):lr.configLoad(e,Error(String(f)))}};if(o)return Qn.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(Fn(t,`${s}${o}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let s of n){if(!s)continue;if(r.push(s,`.${s}.config`,`${s}.config`,`.${s}`),e)r.push(`${e}.${s}.config`,`.${e}.${s}.config`)}let i=new Set;return r.filter((s)=>{if(!s||i.has(s))return!1;return i.add(s),!0})}checkFileAccess(e){return id(async()=>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 s of i)for(let o of this.extensions){let l=Fn(e,`${s}${o}`);if(await this.checkFileAccess(l))n.push(l)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let l=Fn(e,o);if(await this.checkFileAccess(l))n.push(l)}}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"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class al{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:l=!0,verbose:c=!1}=r,f=async()=>{let u=[],a=[],m={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:l,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,m);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],m);else return this.validateWithJSONSchema(e,t,m)}catch(y){return u.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:u,warnings:a}}};if(l)return await Qn.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!Vu(t))throw new Si(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 Si(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,l=Array.isArray(t.type)?t.type:[t.type];if(!l.includes(o)){if(n.push({path:r,message:`Expected type ${l.join(" or ")}, got ${o}`,expected:l.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let l=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,l,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let l of t.required)if(!(l in o)){if(n.push({path:r?`${r}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[l,c]of Object.entries(t.properties))if(l in o){let f=r?`${r}.${l}`:l;if(this.validateObjectAgainstSchema(o[l],c,f,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(o))if(!l.has(c))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),l=this.validateWithRule(o,s,s.path);if(n.push(...l),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,o]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:cd},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function fd(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 ll{fileLoader=new ol;envProcessor=new ls;validator=new al;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let c=this.checkCache(o.name||"",o);if(c)return c}let l;try{l=await this.loadConfigurationStrategies(o,!0,r)}catch(c){let f=o.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),a=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),m=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(m||u))throw c;if(a&&(!f||!m))l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else l={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(i||s)await this.validateConfiguration(l.config,i,s,o.name);if(r?.enabled&&l)this.cacheResult(o.name||"",l,r,o);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)wt.warn(`Slow configuration loading detected: ${c.duration}ms for ${o.name}`);l.metrics=c}return l}catch(l){if(l instanceof Error&&l.name==="ConfigNotFoundError")throw l;let c=Date.now()-t;throw wt.error(`Configuration loading failed after ${c}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:l,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,a=s||Ai.cwd(),m=[],y=await this.loadLocalConfiguration(n,i,a,o,l,f,u,c,r);if(y)return m.push(...this.getLocalSearchPaths(n,i,a,o)),this.finalizeResult(y,m,c,n,u);let w=await this.loadHomeConfiguration(n,i,l,f,u,c);if(w)return m.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(w,m,c,n,u);let C=await this.loadPackageJsonConfiguration(n,i,a,l,f,u,c);if(C)return m.push(st(a,"package.json")),this.finalizeResult(C,m,c,n,u);if(m.push(...this.getAllSearchPaths(n,i,a,o)),t)throw lr.configNotFound(n,m,i);return{...await this.applyEnvironmentVariables(n,l,c,u),warnings:[`No configuration file found for "${n}"${fd(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,l,c){let f=l?si(e,i,o):i,u=this.getLocalDirectories(r,n);for(let a of u){if(o)wt.info(`Searching for configuration in: ${a}`);let m=this.fileLoader.generateConfigPaths(e,a,t),y=await this.fileLoader.tryLoadFromPaths(m,f,{arrayStrategy:s,verbose:o,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(y){if(o)wt.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?si(e,r,i):r,l=[st(qt(),".config",e),st(qt(),".config"),qt()];for(let c of l){if(i)wt.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,o,{arrayStrategy:n,verbose:i});if(u){if(i)wt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let l=o?si(e,n,s):n;try{let c=st(r,"package.json");if(!iu(c))return null;let f={};try{f=JSON.parse(nu(c,"utf8"))}catch(m){if(s)wt.warn("Failed to parse package.json:",[m instanceof Error?m:Error(String(m))]);return null}let u=f[e],a=e;if(!u&&t){let m=Array.isArray(t)?t:[t];for(let y of m){if(!y)continue;if(f[y]){u=f[y],a=y;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)wt.success(`Configuration loaded from package.json: ${a}`);return{config:sl(l,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)wt.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:si(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(i.length>0)throw lr.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return mi.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);mi.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),s=[];for(let o of i)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[st(qt(),".config",e),st(qt(),".config"),qt()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function si(e,t,r=!1){let n=new ls,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,l=[]){let c={...o};for(let[f,u]of Object.entries(o)){let a=[...l,f],m=[`${i}_${a.join("_").toUpperCase()}`,`${i}_${a.map((C)=>C.toUpperCase()).join("")}`,`${i}_${a.map((C)=>C.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,w;for(let C of m)if(y=Ai.env[C],y!==void 0){w=C;break}if(y!==void 0&&w)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(y.toLowerCase());else if(typeof u==="number"){let C=Number(y);if(!Number.isNaN(C))c[f]=C}else if(Array.isArray(u))try{c[f]=JSON.parse(y)}catch{c[f]=y.split(",").map((C)=>C.trim())}else c[f]=y;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,a)}return c}return s(t)}var mi,Qn,Hu,ju=(e)=>e,Zu=(e,t)=>{for(var r in t)Hu(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Ku.bind(t,r)})},Yu=(e,t)=>()=>(e&&(t=e(e=0)),t),ka,Ba,ar,br,_a,vh,bh,ma,ai,Hn,je,Ee,Eh,ga,Sh,ya,Ah,xh,Nn,Th,Ca,wa,Wn,Oh,Rh,Ph,kh,li,Ua,Mh,Ke,Dh,Ih,$a,ci,jn,We,fe,Fh,va,Nh,ba,Wh,Lh,Ln,Gh,Ea,Sa,Bh,Gn,_h,Uh,Vh,Hh,jh,fi,Va,Kh,Zh="0.15.6",et,$i,$r,Kn,Zn,vi,Yn,Jn,vr,qn,zn,Mt,Ha,ja,ft,Et,Ka,Za,Yh,qh,Ya,bi,My,Be,pe,Dy,Xh,Iy,Qh,Fy,Ny,Aa,Wy,ed,td,Ly,xa,Gy,By,_y,Uy,Vy,Bn,rd,Hy,ut,qa,Ei,za,Xa,as,Qa,el,Si,tl,rl,lr,cd,wt,jy,Ky,Zy,ud,cl;var fl=de(()=>{mi=new Ra,Qn=new Pa,Hu=Object.defineProperty;ka={};Zu(ka,{withErrorRecovery:()=>Ia,tryLoadConfig:()=>yh,loadConfigWithResult:()=>mh,loadConfig:()=>Ga,isRetryableError:()=>ch,isConfigNotFoundError:()=>lh,isBunfigError:()=>Fa,globalPerformanceMonitor:()=>br,globalCache:()=>ar,getEnvOrDefault:()=>fh,generateConfigTypes:()=>Ch,defaultGeneratedDir:()=>Za,defaultConfigDir:()=>Ka,deepMergeWithArrayStrategy:()=>ns,deepMerge:()=>Na,createLibraryConfig:()=>wh,config:()=>gh,bunfigPlugin:()=>$h,applyEnvVarsToConfig:()=>Cr,TypeGenerationError:()=>Jn,SchemaValidationError:()=>vr,PluginError:()=>zn,PerformanceMonitor:()=>ts,FileSystemError:()=>Yn,ErrorFactory:()=>Mt,EnvVarError:()=>vi,EnvProcessor:()=>xi,ConfigValidator:()=>ss,ConfigValidationError:()=>Kn,ConfigNotFoundError:()=>$i,ConfigMergeError:()=>Zn,ConfigLoader:()=>os,ConfigLoadError:()=>$r,ConfigFileLoader:()=>Ti,ConfigCache:()=>es,CacheUtils:()=>_a,BunfigError:()=>et,BrowserConfigError:()=>qn,ArrayMergeStrategies:()=>Ha});Yh=Yu(async()=>{Ba=import.meta.require,ar=new es,br=new ts,_a={createKey:Ju,isEquivalent:qu,estimateMemoryUsage:zu},vh=di(Un.cwd(),"config"),bh=di(Un.cwd(),"src/generated"),ma=hi.env.CLARITY_LOG_DIR||fu(eh(),"logs"),ai={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ma,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Hn=await th(),je={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=je,Eh=je.red,ga=je.green,Sh=je.yellow,ya=je.blue,Ah=je.magenta,xh=je.cyan,Nn=je.white,Th=je.gray,Ca=je.bgRed,wa=je.bgYellow,Wn=je.bold,Oh=je.dim,Rh=je.italic,Ph=je.underline,kh=je.reset,li={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ua={debug:"\uD83D\uDD0D",info:ya("\u2139"),success:ga("\u2713"),warning:wa(Nn(Wn(" WARN "))),error:Ca(Nn(Wn(" ERROR ")))},Mh=new yi("stacks"),Ke=new yi("bunfig",{showTags:!0}),Dh=Je(wr.cwd(),"config"),Ih=Je(wr.cwd(),"src/generated"),$a=ui.env.CLARITY_LOG_DIR||lu(sh(),"logs"),ci={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:$a,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},jn=await oh(),We={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},fe=We,Fh=We.red,va=We.green,Nh=We.yellow,ba=We.blue,Wh=We.magenta,Lh=We.cyan,Ln=We.white,Gh=We.gray,Ea=We.bgRed,Sa=We.bgYellow,Bh=We.bgGray,Gn=We.bold,_h=We.dim,Uh=We.italic,Vh=We.underline,Hh=We.strikethrough,jh=We.reset,fi={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Va={debug:"\uD83D\uDD0D",info:ba("\u2139"),success:va("\u2713"),warning:Sa(Ln(Gn(" WARN "))),error:Ea(Ln(Gn(" ERROR ")))},Kh=new wi("stacks"),et=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}`}},$i=class extends et{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 et{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},Kn=class extends et{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Zn=class extends et{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}},vi=class extends et{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})}},Yn=class extends et{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}},Jn=class extends et{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}},vr=class extends et{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}},qn=class extends et{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})}},zn=class extends et{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 $i(e,t,r)},configLoad(e,t,r){return new $r(e,t,r)},configValidation(e,t,r){return new Kn(e,t,r)},configMerge(e,t,r,n){return new Zn(e,t,r,n)},envVar(e,t,r,n){return new vi(e,t,r,n)},fileSystem(e,t,r){return new Yn(e,t,r)},typeGeneration(e,t,r){return new Jn(e,t,r)},schemaValidation(e,t,r){return new vr(e,t,r)},browserConfig(e,t,r,n){return new qn(e,t,r,n)},plugin(e,t,r){return new zn(e,t,r)}},Ha={replace:"replace",concat:"concat",smart:"smart"},ja=/^https?:\/\//,ft=new wi("bunfig",{showTags:!0}),Et=new os,Ka=qe(Wt.cwd(),"config"),Za=qe(Wt.cwd(),"src/generated")});qh=pi.env.CLARITY_LOG_DIR||Mu(Jh(),"logs"),Ya={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:qh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},bi={...Ya},My=(async()=>{try{let{loadConfig:e}=await Yh().then(()=>ka),t=await e({name:"clarity",alias:"logging",defaultConfig:Ya,cwd:pi.cwd()});if(t)Object.assign(bi,t)}catch{}return bi})();Be={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,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"},pe=Be,Dy=Be.red,Xh=Be.green,Iy=Be.yellow,Qh=Be.blue,Fy=Be.magenta,Ny=Be.cyan,Aa=Be.white,Wy=Be.gray,ed=Be.bgRed,td=Be.bgYellow,Ly=Be.bgGray,xa=Be.bold,Gy=Be.dim,By=Be.italic,_y=Be.underline,Uy=Be.strikethrough,Vy=Be.reset,Bn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},rd={debug:"\uD83D\uDD0D",info:Qh("\u2139"),success:Xh("\u2713"),warning:td(Aa(xa(" WARN "))),error:ed(Aa(xa(" ERROR ")))};Hy=new Oi("stacks");ut=class ut 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}`}};qa=class qa extends ut{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],i="";if(n.length===1)i=` or alias "${n[0]}"`;else if(n.length>1)i=` or aliases ${n.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}};Ei=class Ei extends ut{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}};za=class za extends ut{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};Xa=class Xa extends ut{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}};as=class as extends ut{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})}};Qa=class Qa extends ut{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}};el=class el extends ut{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}};Si=class Si extends ut{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})}};tl=class tl extends ut{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})}};rl=class rl extends ut{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}};lr={configNotFound(e,t,r){return new qa(e,t,r)},configLoad(e,t,r){return new Ei(e,t,r)},configValidation(e,t,r){return new za(e,t,r)},configMerge(e,t,r,n){return new Xa(e,t,r,n)},envVar(e,t,r,n){return new as(e,t,r,n)},fileSystem(e,t,r){return new Qa(e,t,r)},typeGeneration(e,t,r){return new el(e,t,r)},schemaValidation(e,t,r){return new Si(e,t,r)},browserConfig(e,t,r,n){return new tl(e,t,r,n)},plugin(e,t,r){return new rl(e,t,r)}};cd=/^https?:\/\//;wt=new Oi("bunfig",{showTags:!0});jy=new ll;Ky=st(Ai.cwd(),"config"),Zy=st(Ai.cwd(),"src/generated"),ud={cwd:ru.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},cl=ud});function Dt(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 hl(e){let t=[],r=[],n=[],i={")":"(","]":"[","}":"{"},s=0,o=0,l=-1;for(let f=0;f<e.length;f++){let u=e.charCodeAt(f),a=e.charCodeAt(f+1);if(l!==-1){if(u===42&&a===47)r.push({start:l,end:f+2}),l=-1,f++;continue}if(s){if(u===92)f++;else if(u===s)r.push({start:o,end:f+1}),s=0;continue}if(u===47&&a===42){l=f,f++;continue}if(u===47&&a===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){s=u,o=f;continue}let m=e[f];if(m==="("||m==="["||m==="{")n.push({char:m,offset:f});else if(i[m]){let y=n.pop();if(!y||y.char!==i[m])t.push({...Dt(e,f),message:`Unexpected closing delimiter ${m}`,code:"DTSX1004"})}}if(s)t.push({...Dt(e,o),message:"Unterminated string literal",code:"DTSX1002"});if(l!==-1)t.push({...Dt(e,l),message:"Unterminated block comment",code:"DTSX1003"});for(let f of n)t.push({...Dt(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 a of e.matchAll(f)){if(r.some((m)=>a.index>=m.start&&a.index<m.end))continue;t.push({...Dt(e,a.index),message:u,code:"DTSX1005"})}for(let f of e.matchAll(/\btype\s*(?=[{=])/g)){if(r.some((a)=>f.index>=a.start&&f.index<a.end))continue;let u=e.slice(0,f.index).trimEnd();if(u.endsWith("import")||u.endsWith("export"))continue;t.push({...Dt(e,f.index),message:"Declaration name expected",code:"DTSX1005"})}return t.push(...dd(e,r)),t.sort((f,u)=>f.line-u.line||f.column-u.column)}function dd(e,t){let r=[],n=(i)=>t.some((s)=>i>=s.start&&i<s.end);for(let i of e.matchAll(/\b(import|export)\s+(?:type\s+)?\{/g)){let s=i.index;if(n(s))continue;let o=s+i[0].length-1,l=-1;for(let u=o+1;u<e.length;u++){if(n(u))continue;let a=e[u];if(a==="{"){l=-2;break}if(a==="}"){l=u;break}}if(l<0)continue;let c=e.slice(o+1,l);if(!c.trim())continue;let f=o+1;for(let u of c.split(",")){let a=u.trim();if(a){let m=f+u.indexOf(a);if(a.includes(";"))r.push({...Dt(e,m),message:`Unexpected ';' in ${i[1]} clause \u2014 specifiers are separated by ','`,code:"DTSX1006"});else if(!hd.test(a))r.push({...Dt(e,m),message:`Invalid ${i[1]} specifier '${a}'`,code:"DTSX1006"})}f+=u.length+1}}return r}var ul,hd;var dl=de(()=>{ul=String.raw`(?:[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*|'[^']*'|"[^"]*")`,hd=new RegExp(`^(?:type\\s+)?${ul}(?:\\s+as\\s+${ul})?$`,"u")});var pl;var ml=de(()=>{pl=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 gl(e,t={strings:!0}){let r="",n=0;while(n<e.length){let i=e.slice(n,n+2);if(i==="//"){let o=e.indexOf(`
|
|
120
|
+
`,n),l=o===-1?e.length:o;r+=" ".repeat(l-n),n=l;continue}if(i==="/*"){let o=e.indexOf("*/",n+2),l=o===-1?e.length:o+2;for(let c=n;c<l;c++)r+=e[c]===`
|
|
121
|
+
`?`
|
|
122
|
+
`:" ";n=l;continue}let s=e[n];if(t.strings&&(s==='"'||s==="'"||s==="`")){let o=s;r+=" ",n++;while(n<e.length){if(e[n]==="\\"){r+=" ",n+=2;continue}if(e[n]===o){r+=" ",n++;break}r+=e[n]===`
|
|
123
|
+
`?`
|
|
124
|
+
`:" ",n++}continue}r+=s,n++}return r}function md(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 gd(e){let t=new Set;for(let r of e.matchAll(/\bimport\s+(?:type\s+)?([\s\S]*?)\s+from\s*['"`]/g)){let n=r[1],i=/\*\s*as\s+([A-Za-z_$][\w$]*)/.exec(n);if(i)t.add(i[1]);let s=n.split("{")[0].replace(/\*\s*as\s+[A-Za-z_$][\w$]*/,"");for(let l of s.split(",")){let c=l.trim();if(/^[A-Za-z_$][\w$]*$/.test(c))t.add(c)}let o=/\{([\s\S]*?)\}/.exec(n);if(o)for(let l of o[1].split(",")){let c=l.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 yd(e){let t=new Set,r=(i)=>{for(let s of i.split(",")){let o=s.trim().split(/\s+|=/)[0]?.trim();if(o&&/^[A-Za-z_$][\w$]*$/.test(o))t.add(o)}},n=/\b(?:type|interface|class|function)\s+[A-Za-z_$][\w$]*\s*<([^<>]*(?:<[^<>]*>[^<>]*)*)>/g;for(let i of e.matchAll(n))r(i[1]);for(let i of e.matchAll(/(?:\b[A-Za-z_$][\w$]*)?\s*<([^<>()]*)>\s*\(/g))r(i[1]);for(let i of e.matchAll(/\binfer\s+([A-Za-z_$][\w$]*)/g))t.add(i[1]);for(let i of e.matchAll(/\[\s*([A-Za-z_$][\w$]*)\s+in\b/g))t.add(i[1]);return t}function Cd(e){let t=new Map,r=(i)=>{let s=1;for(let o=0;o<i&&o<e.length;o++)if(e.charCodeAt(o)===10)s++;return s},n=(i,s,o)=>{for(let l of i.matchAll(/\b([A-Z][\w$]*)\b/g)){let c=l[1];if(t.has(c))continue;let f=i.slice(l.index+c.length);if(/^\s*\??:/.test(f))continue;t.set(c,{line:r(s),context:o.trim().slice(0,120)})}};for(let i of e.matchAll(/\btype\s+[A-Za-z_$][\w$]*\s*(?:<[^=]*?>)?\s*=([^;]*)/g))n(i[1],i.index+i[0].indexOf("="),i[0]);for(let i of e.matchAll(/\b(?:extends|implements)\s+([^{;]*)/g))n(i[1],i.index,i[0]);for(let i of e.matchAll(/:\s*([^;,){}\n=]+)/g))n(i[1],i.index,i[0]);for(let i of e.matchAll(/<([^<>()]*)>/g))n(i[1],i.index,i[0]);return t}function yl(e){let t=gl(e),r=gl(e,{strings:!1}),n=new Set([...md(t),...gd(r),...yd(t),...pl,...pd]),i=[];for(let[s,o]of Cd(t)){if(n.has(s))continue;if(new RegExp(`[\\w$]\\s*\\.\\s*${s}\\b`).test(t))continue;i.push({name:s,line:o.line,context:o.context})}return i.sort((s,o)=>s.line-o.line||s.name.localeCompare(o.name))}var pd;var Cl=de(()=>{ml();pd=new Set(["This","True","False","Null","Undefined","Void","Never","Any","Unknown","Object","Infinity","NaN"])});import{join as m0,resolve as wd}from"path";import $d from"process";function cs(){return`${String.fromCharCode(47,47,35)} sourceMappingURL=`}async function Ri(e,t,r="lf"){let n=t.replace(/\r\n/g,`
|
|
125
|
+
`);if(!n.endsWith(`
|
|
126
|
+
`))n+=`
|
|
127
|
+
`;if(r==="crlf")n=n.replace(/\n/g,`\r
|
|
128
|
+
`);await lo(e,n)}async function wl(e){try{let t=e?.cwd||$d.cwd();return(await gr(wd(t,e?.tsconfigPath||"tsconfig.json"),{allowCircular:!0}))?.isolatedDeclarations??!1}catch{return!1}}function $l(e,t){let r={isValid:!0,errors:[]};for(let n of hl(e))r.errors.push({line:n.line,column:n.column,message:n.message,code:n.code});for(let n of yl(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 vl(e,t,r){if(e===t)return"";let n=e.split(`
|
|
129
|
+
`),i=t.split(`
|
|
130
|
+
`),s=new Map,o=new Map;for(let u=0;u<n.length;u++)s.set(n[u],(s.get(n[u])??0)+1);for(let u=0;u<i.length;u++)o.set(i[u],(o.get(i[u])??0)+1);let l=[],c=[];for(let[u,a]of s){let m=a-(o.get(u)??0);for(let y=0;y<m;y++)l.push(u)}for(let[u,a]of o){let m=a-(s.get(u)??0);for(let y=0;y<m;y++)c.push(u)}if(l.length===0&&c.length===0)return"";let f=[`--- ${r}`,`+++ ${r}`];for(let u=0;u<l.length;u++)f.push(`- ${l[u]}`);for(let u=0;u<c.length;u++)f.push(`+ ${c[u]}`);return f.join(`
|
|
131
|
+
`)}function bl(e,t,r,n){let i=e.split(`
|
|
132
|
+
`),s=[];function o(a){let m="",y=a<0?-a<<1|1:a<<1;do{let w=y&31;if(y>>>=5,y>0)w|=32;m+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[w]}while(y>0);return m}let l=0,c=0,f=0,u=n.split(`
|
|
133
|
+
`).length;for(let a=0;a<i.length;a++){if(i[a].trim()===""){s.push("");continue}l=0;let m=Math.min(a,u-1),y=[],w=0-l,C=0,x=m-c,k=0-f;y.push(o(w)+o(C)+o(x)+o(k)),l=0,c=m,f=0,s.push(y.join(","))}return{version:3,file:t,sourceRoot:"",sources:[r],sourcesContent:[n],mappings:s.join(";")}}function El(e,t){return`${e}
|
|
134
|
+
${cs()}${t}
|
|
135
|
+
`}var Sl=de(()=>{dl();Cl();Br();pn()});function Al(e,t,r){let n={file:t,message:"Unknown error",code:Er.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=Er.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=Er.SYNTAX_ERROR,n.suggestion="Check for syntax errors in your TypeScript code.";else if(e.message.includes("type")&&e.message.includes("cannot"))n.code=Er.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=Er.PARSE_ERROR,n.suggestion="The file contains invalid TypeScript syntax."}else if(typeof e==="string")n.message=e;return n}function xl(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(`
|
|
136
|
+
`),s=e.location.line-1;if(s>=0&&s<i.length){let o=Math.max(0,s-1),l=Math.min(i.length-1,s+1);for(let c=o;c<=l;c++){let f=(c+1).toString().padStart(4," "),u=c===s?">":" ";if(r.push(` ${u} ${f} | ${i[c]}`),c===s&&e.location.column>0){let a=" ".repeat(10+e.location.column-1);r.push(` ${a}^`)}}}}if(e.suggestion)r.push(""),r.push(` Suggestion: ${e.suggestion}`);return r.join(`
|
|
137
|
+
`)}var Er;var Tl=de(()=>{Er={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 Ad(e){switch(e){case"strict":return bd;case"readonly":return Ed;case"simplified":return Sd;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 Rl{rules;compiled=[];cache=new Map;constructor(e={rules:[]}){if(this.rules=[],e.includeDefaults!==!1)this.rules.push(...vd);if(e.presets)for(let t of e.presets)this.rules.push(...Ad(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(xd,"\\$&"),r.global?"g":""):r.pattern;e[t]={rule:r,regex:n}}this.compiled=e}map(e,t={}){let r=!t.declarationName&&!t.declarationKind&&!t.filePath&&!t.isReturnType&&!t.isParameterType&&!t.isPropertyType?e:`${e}\x00${t.declarationName??""}\x00${t.declarationKind??""}\x00${t.filePath??""}\x00${t.isReturnType?"r":""}${t.isParameterType?"p":""}${t.isPropertyType?"P":""}`,n=this.cache.get(r);if(n!==void 0)return n;let i=e,s=null;for(let o=0;o<this.compiled.length;o++){let{rule:l,regex:c}=this.compiled[o];if(l.condition){if(!s)s={type:e,...t};if(!l.condition(s))continue}if(c.lastIndex=0,c.test(i)){if(c.lastIndex=0,i=i.replace(c,l.replacement),c.lastIndex=0,!l.global)break}}if(this.cache.size>=Ol){let o=Math.ceil(Ol*0.1),l=0;for(let c of this.cache.keys()){if(l++>=o)break;this.cache.delete(c)}}return this.cache.set(r,i),i}mapAll(e,t={}){return e.map((r)=>this.map(r,{...t,type:r}))}addRule(e){this.rules.push(e),this.rules.sort((t,r)=>(r.priority||0)-(t.priority||0)),this.recompile(),this.cache.clear()}removeRules(e){let t=this.rules.length;return this.rules=this.rules.filter((r)=>{let n=typeof r.pattern==="string"?r.pattern:r.pattern.source;if(e instanceof RegExp)e.lastIndex=0;return typeof e==="string"?n!==e:!e.test(n)}),this.recompile(),this.cache.clear(),t-this.rules.length}clearCache(){this.cache.clear()}getRules(){return this.rules}}function Pi(e={rules:[]}){return new Rl(e)}function Pl(e,t,r={}){return e.replace(/:\s*([^;,)\]}]+)/g,(n,i)=>`: ${t.map(i.trim(),r)}`)}var vd,bd,Ed,Sd,xd,Ol=2048,w0,$0;var kl=de(()=>{vd=[{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}],bd=[{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}],Ed=[{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}],Sd=[{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}];xd=/[.*+?^${}()|[\]\\]/g;w0=Pi({rules:[]}),$0=Pi({rules:[],presets:["strict"]})});function Sr(e){if(Td)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 Td;var fs=de(()=>{Td=typeof globalThis.Bun?.hash==="function"});import{existsSync as Ar,mkdirSync as Od,readFileSync as hs,renameSync as Rd,rmSync as Ml,statSync as Dl,writeFileSync as Il}from"fs";import{join as Fl,relative as ki,resolve as Pd}from"path";class ds{cacheDir;manifestPath;manifest=null;configHash;constructor(e,t){this.cacheDir=Pd(e.cwd,Mi),this.manifestPath=Fl(this.cacheDir,kd),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(Sr(JSON.stringify(r)))}hashString(e){return String(Sr(e))}load(){try{if(!Ar(this.manifestPath))return!1;let e=hs(this.manifestPath,"utf-8"),t=JSON.parse(e);if(t.version!==us)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:us,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};if(this.manifest.updatedAt=Date.now(),!Ar(this.cacheDir))Od(this.cacheDir,{recursive:!0});let e=`${this.manifestPath}.${process.pid}.tmp`;try{Il(e,JSON.stringify(this.manifest,null,2)),Rd(e,this.manifestPath)}finally{if(Ar(e))Ml(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=ki(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=Dl(e),{mtimeMs:s,ctimeMs:o}=i;if(i.size!==n.sourceSize)return null;if(s!==n.sourceMtime||o!==n.sourceCtime){let l=hs(e,"utf-8");if(this.hashString(l)!==n.sourceHash)return null;n.sourceMtime=s,n.sourceCtime=o}return n.dtsContent}catch{return null}}update(e,t,r,n){if(!this.manifest)this.manifest={version:us,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};let i=ki(n,e),s,o,l;try{let c=Dl(e);s=c.mtimeMs,o=c.ctimeMs,l=c.size}catch{s=Date.now(),o=s,l=Buffer.byteLength(t)}this.manifest.entries[i]={sourcePath:i,sourceHash:this.hashString(t),sourceMtime:s,sourceCtime:o,sourceSize:l,dtsContent:r,dtsHash:this.hashString(r),generatedAt:Date.now(),configHash:this.configHash}}remove(e,t){if(!this.manifest)return;let r=ki(t,e);delete this.manifest.entries[r]}clear(){this.manifest=null;try{if(Ar(this.manifestPath))Ml(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)=>ki(t,i)));for(let i of Object.keys(this.manifest.entries))if(!n.has(i))delete this.manifest.entries[i],r++;return r}}function Nl(e){let t=Fl(e,".gitignore");try{let r="";if(Ar(t))r=hs(t,"utf-8");if(!r.split(/\r?\n/).some((n)=>n.trim()===Mi||n.trim()===`${Mi}/`)){let n=r.trimEnd(),i=`${n}${n?`
|
|
138
|
+
|
|
139
|
+
`:""}# dtsx cache
|
|
140
|
+
${Mi}/
|
|
141
|
+
`;Il(t,i)}}catch{}}var us=3,Mi=".dtsx-cache",kd="manifest.json";var Wl=de(()=>{fs()});function At(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
142
|
`;return`${n.trim()}
|
|
120
|
-
`}let
|
|
121
|
-
`;
|
|
122
|
-
`}function
|
|
123
|
-
`)||
|
|
124
|
-
`;if(
|
|
125
|
-
`)||e.includes("\r"))return"string";return e}function
|
|
143
|
+
`}let r="";for(let n=0;n<e.length;n++){if(n>0)r+=`
|
|
144
|
+
`;r+=e[n].trim()}return`${r}
|
|
145
|
+
`}function vs(e){return e.replaceAll("*/","*\\/")}function ms(e){return Hl(e).replace(/\n[ \t]*(?=\n)/g,"")}function Hl(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 Es(){Wi=!0,ze=null}function Ss(){Wi=!1;let e=ze;return ze=null,e}function As(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 Md(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 ps(e,t){let r=0,n=0;while((n=e.indexOf(t,n))!==-1)r++,n+=t.length;return r}function Ll(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 Di(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&&Ll(t.charCodeAt(n)))n++;let i=t.slice(1,n),s=t.charCodeAt(n);if(s>32&&s!==62&&s!==47)return!1;if(t.endsWith("/>"))return!0;let o=t.lastIndexOf("</");if(o===-1)return!1;let l=o+2;while(l<t.length&&Ll(t.charCodeAt(l)))l++;return t.slice(o+2,l)===i&&t.charCodeAt(l)===62&&l===t.length-1}function Ii(e){let t=e.length,r=!1;for(let o=1;o<t;o++)if(e.charCodeAt(o)<=32&&e.charCodeAt(o-1)<=32){r=!0;break}if(!r)for(let o=0;o<t;o++){let l=e.charCodeAt(o);if(l===10||l===13||l===9){r=!0;break}}if(!r)return e;let n=[],i=-1,s=!1;for(let o=0;o<t;o++)if(e.charCodeAt(o)<=32){if(!s){if(i>=0)n.push(e.substring(i,o));n.push(" "),s=!0,i=-1}}else{if(s||i<0)i=o;s=!1}if(i>=0)n.push(e.substring(i));return n.join("")}function Ie(e,t=!1,r=!1,n=0){if(!e||typeof e!=="string")return"unknown";if(n>=bs)return"unknown";let i=e.trim();if(Di(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(`
|
|
146
|
+
`)||i.includes("\r"))return"string";return i}if(i.charCodeAt(0)===39||i.charCodeAt(0)===34){let o=Dd(i);if(o!==null){if(o==="string"||!t)return"string";return o}}if(As(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 Cs(i,t,n+1);if(i.startsWith("{")&&i.endsWith("}"))return jd(i,t,n+1);if(i.startsWith("class ")||i.startsWith("class{"))return Vd(i);if(i.startsWith("new "))return Ud(i);if(i.endsWith("as const")){let o=i.slice(0,-8).trim();if(o.startsWith("[")&&o.endsWith("]")){let l=o.slice(1,-1).trim();if(!l)return"readonly []";let c=Fi(l),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(o,!0,r,n+1)}if(Ni(i)!==-1||i.startsWith("function")||i.startsWith("async"))return Xl(i,r,n,t);if(i.startsWith("`")&&i.endsWith("`"))return _d(i,t);if(i.startsWith("Promise."))return Yl(i,t,n);if(i.startsWith("await "))return"unknown";if(i.charCodeAt(i.length-1)===110&&i.length>1&&Md(i)){if(t)return i;return"bigint"}if(i.startsWith("Symbol(")||i==="Symbol.for")return"symbol";let s=Jl(i);if(s!==null)return s;if(jl(i))return"boolean";if(Wd(i))return"number";return"unknown"}function Gl(e){let t=e.charCodeAt(0);if(t!==39&&t!==34)return!1;return It(e,0,t)===e.length}function Dd(e){if(Gl(e))return e;let t=Id(e);if(t.length<2)return null;let r=!1,n=!0,i="";for(let s of t){let o=s.trim();if(Gl(o))r=!0,i+=Fd(o);else n=!1}if(n)return Nd(i);if(r)return"string";return null}function Id(e){let t=[],r=0,n=0,i=0;while(i<e.length){let s=e.charCodeAt(i);if(s===39||s===34||s===96){i=It(e,i,s);continue}if(s===40||s===91||s===123)r++;else if(s===41||s===93||s===125)r--;else if(s===43&&r===0)t.push(e.slice(n,i)),n=i+1;i++}return t.push(e.slice(n)),t}function Fd(e){return e.slice(1,-1).replace(/\\(.)/g,(t,r)=>{if(r==="n")return`
|
|
147
|
+
`;if(r==="t")return"\t";if(r==="r")return"\r";if(r==="0")return"\x00";return r})}function Nd(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function Wd(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 jl(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 Ld(e,t=!1,r=0){return Ie(e,t,!0,r)}function fr(e,t=!1,r=""){let n=Kl(r),i=[],s=!1,o=0;while(o<e.length){let c=e.charCodeAt(o);if(c===34||c===39||c===96){o=It(e,o,c);continue}if(c===47&&e.charCodeAt(o+1)===47){o+=2;while(o<e.length&&e.charCodeAt(o)!==10&&e.charCodeAt(o)!==13)o++;continue}if(c===47&&e.charCodeAt(o+1)===42){let f=e.indexOf("*/",o+2);o=f===-1?e.length:f+2;continue}if(e.startsWith("function",o)&&gs(e,o,8)||e.startsWith("class",o)&&gs(e,o,5)){let f=Bd(e,o);if(f!==-1){o=ys(e,f);continue}}if(c===61&&e.charCodeAt(o+1)===62){let f=o+2;while(f<e.length&&e.charCodeAt(f)<=32)f++;if(e.charCodeAt(f)===123){o=ys(e,f);continue}}if(e.startsWith("return",o)&&(o===0||!St(e.charCodeAt(o-1)))&&!St(e.charCodeAt(o+6))){o+=6;let f=!1;while(o<e.length&&e.charCodeAt(o)<=32){let x=e.charCodeAt(o);if(x===10||x===13)f=!0;o++}if(f||o>=e.length||e.charCodeAt(o)===59||e.charCodeAt(o)===125){s=!0;continue}let u=o,a=0,m=0,y=0;while(o<e.length){let x=e.charCodeAt(o);if(x===34||x===39||x===96){o=It(e,o,x);continue}if(x===47&&e.charCodeAt(o+1)===47){if(a===0&&m===0&&y===0)break;while(o<e.length&&e.charCodeAt(o)!==10&&e.charCodeAt(o)!==13)o++;continue}if(x===47&&e.charCodeAt(o+1)===42){let k=e.indexOf("*/",o+2);o=k===-1?e.length:k+2;continue}if(x===40)a++;else if(x===41)a--;else if(x===91)m++;else if(x===93)m--;else if(x===123)y++;else if(x===125){if(y===0&&a===0&&m===0)break;y--}else if(x===59&&a===0&&m===0&&y===0)break;else if((x===10||x===13)&&a===0&&m===0&&y===0){let k=o+1;while(k<e.length&&e.charCodeAt(k)<=32)k++;if(e.startsWith("return",k)&&!St(e.charCodeAt(k+6)))break}o++}let w=e.slice(u,o).trim(),C=ms(Lt(w,n));if(!i.includes(C))i.push(C);continue}o++}if(s&&!i.includes("undefined"))i.push("undefined");let l=i.includes("unknown")?"unknown":i.length===0?"void":i.join(" | ");return t&&!l.startsWith("Promise<")?`Promise<${l}>`:l}function Kl(e){let t=new Map,r=e.startsWith("(")&&e.endsWith(")")?e.slice(1,-1):e,n=0,i=0,s=0;for(let o=0;o<=r.length;o++){let l=r.charCodeAt(o);if(l===40||l===91||l===123)i++;else if(l===41||l===93||l===125)i--;else if(l===60)s++;else if(l===62&&r.charCodeAt(o-1)!==61&&s>0)s--;if(o!==r.length&&(l!==44||i!==0||s!==0))continue;let c=r.slice(n,o).trim(),f=c.indexOf(":");if(f!==-1){let u=c.slice(0,f).trim().replace(/^\.\.\./,"").replace(/\?$/,""),a=c.slice(f+1).trim(),m=a.indexOf("=");if(m!==-1)a=a.slice(0,m).trim();if(Li(u)&&a)t.set(u,a)}n=o+1}return t}function Lt(e,t){let r=e.trim();while(Zl(r))r=r.slice(1,-1).trim();if(Di(r))return"JSX.Element";if(r.startsWith("await ")){let s=Lt(r.slice(6),t);return s.startsWith("Promise<")&&s.endsWith(">")?s.slice(8,-1):s}if(t.has(r))return t.get(r);if(r.startsWith("!"))return"boolean";if(r.startsWith("fetch("))return"Promise<Response>";let n=Gd(r);if(n){let s=Lt(n.whenTrue,t),o=Lt(n.whenFalse,t);return s===o?s:`${s} | ${o}`}if(jl(r))return"boolean";let i=0;for(let s=r.length-1;s>=0;s--){let o=r.charCodeAt(s);if(o===41||o===93||o===125)i++;else if(o===40||o===91||o===123)i--;else if(i===0&&(o===43||o===45||o===42||o===47||o===37)){let l=Lt(r.slice(0,s),t),c=Lt(r.slice(s+1),t);if(o===43&&(l==="string"||c==="string"))return"string";if(l==="number"&&c==="number")return"number";break}}return Ie(r,!1).replace(/\btypeof\s+[$A-Z_a-z][$\w]*/g,(s)=>{let o=s.slice(7);return t.get(o)??"unknown"})}function Zl(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 Gd(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 gs(e,t,r){return(t===0||!St(e.charCodeAt(t-1)))&&!St(e.charCodeAt(t+r))}function Bd(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 ys(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 s=e.indexOf("*/",n+2);n=s===-1?e.length:s+2;continue}if(i===123)r++;else if(i===125)r--;n++}return n}function 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=ys(e,n+1);continue}if(n++,i===r)break}return n}function _d(e,t){if(e.includes(".raw`")||e.includes("String.raw`"))return"string";if(!t||e.includes("${")||e.includes(`
|
|
148
|
+
`)||e.includes("\r"))return"string";return e}function Ud(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&&(St(e.charCodeAt(t))||e.charCodeAt(t)===46))t++;if(t===r)return"unknown";let i=e.slice(r,t);{let s=e.slice(t),o=s;if(s.startsWith("<")){let c=0,f=-1;for(let u=0;u<s.length;u++)if(s[u]==="<")c++;else if(s[u]===">"){if(c--,c===0){f=u;break}}if(f!==-1){let u=s.slice(0,f+1);o=s.slice(f+1);let a=o.indexOf("(");if(a!==-1){let m=0,y=-1;for(let w=a;w<o.length;w++)if(o[w]==="(")m++;else if(o[w]===")"){if(m--,m===0){y=w;break}}if(y!==-1){if(o.slice(y+1).trimStart().startsWith("."))return"unknown"}}return`${i}${u}`}}let l=o.indexOf("(");if(l!==-1){let c=0,f=-1;for(let u=l;u<o.length;u++)if(o[u]==="(")c++;else if(o[u]===")"){if(c--,c===0){f=u;break}}if(f!==-1){if(o.slice(f+1).trimStart().startsWith("."))return"unknown"}}switch(i){case"Date":return"Date";case"Map":return"Map<any, any>";case"Set":return"Set<any>";case"WeakMap":return"WeakMap<any, any>";case"WeakSet":return"WeakSet<any>";case"RegExp":return"RegExp";case"Error":return"Error";case"Array":return"any[]";case"Object":return"object";case"Function":return"Function";case"Promise":return"Promise<any>";default:return i}}return"unknown"}function Vd(e){return"{ new (...args: any[]): any }"}function Yl(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 s=e.slice(n+1,i).trim(),o=Fi(s),l=[];for(let c=0;c<o.length;c++){let f=o[c].trim();if(f.startsWith("Promise.resolve(")){let u=Yl(f,t,r+1),a=u.indexOf("<"),m=u.lastIndexOf(">");l.push(a!==-1&&m>a?u.slice(a+1,m):"unknown")}else l.push(Ie(f,t,!1,r+1))}return`Promise<[${l.join(", ")}]>`}return"Promise<unknown[]>"}return"Promise<unknown>"}function Cs(e,t,r=0){let n=e.slice(1,-1).trim();if(!n)return"never[]";if(r>=bs)return"unknown[]";let i=Fi(n),s=!1;for(let m=0;m<i.length;m++){let y=i[m],w=y.length;while(w>0&&y.charCodeAt(w-1)<=32)w--;if(w>=8&&y.slice(w-8,w)==="as const"){s=!0;break}}if(s){let m=[];for(let y=0;y<i.length;y++){let w=i[y].trim();if(w.endsWith("as const")){let C=w.slice(0,-8).trim();if(C.startsWith("[")&&C.endsWith("]")){let x=C.slice(1,-1).trim(),k=Fi(x),L=[];for(let G=0;G<k.length;G++)L.push(Ie(k[G].trim(),!0,!1,r+1));m.push(`readonly [${L.join(", ")}]`)}else m.push(Ie(C,!0,!1,r+1))}else if(w.startsWith("[")&&w.endsWith("]"))m.push(Cs(w,!0,r+1));else m.push(Ie(w,!0,!1,r+1))}return`readonly [
|
|
126
149
|
${m.join(` |
|
|
127
150
|
`)}
|
|
128
|
-
]`}let
|
|
129
|
-
`:"",
|
|
130
|
-
${
|
|
151
|
+
]`}let o=Wi&&!t,l=[],c=[];for(let m of i){let y=m.trim(),w=ze;if(ze=null,y.startsWith("...")){let C=y.slice(3).trim(),x=Ie(C,!1,!1,r+1);if(x.endsWith("[]"))l.push(x.slice(0,-2));else if(x.startsWith("readonly [")&&x.endsWith("]"))l.push(x.slice(10,-1));else if(cr(C))l.push(`(typeof ${C})[number]`);else l.push("unknown")}else if(y.startsWith("[")&&y.endsWith("]"))l.push(Cs(y,t,r+1));else l.push(Ld(y,t,r+1));if(o)c.push(ze);ze=w}if(o)if($s(e))ze=Ii(e);else{let m=[];for(let y=0;y<i.length;y++){let w=i[y].trim();if(w.endsWith("as const"))continue;if(ws(w)||w==="null"||w==="undefined")m.push(w);else if(w.startsWith("[")&&$s(w))m.push(Ii(w));else if(w.startsWith("{")){if(c[y])m.push(c[y])}else{let C=Ie(w,!1,!1,0);if(C!=="unknown")m.push(C)}}if(m.length>0)ze=`[${m.join(", ")}]`}if(t)return`readonly [${l.join(", ")}]`;let f=new Set,u=[],a=!0;for(let m of l){if(!f.has(m))f.add(m),u.push(m);if(a){if(!(As(m)||m==="true"||m==="false"||m.charCodeAt(0)===34&&m.charCodeAt(m.length-1)===34||m.charCodeAt(0)===39&&m.charCodeAt(m.length-1)===39))a=!1}}if(a&&l.length<=10)return`readonly [${l.join(", ")}]`;if(u.length===1)return`${u[0]}[]`;return`(${u.join(" | ")})[]`}function Fi(e){let t=[],r=0,n=0,i=!1,s=0;for(let l=0;l<e.length;l++){let c=e.charCodeAt(l);if(!i&&(c===34||c===39||c===96))i=!0,s=c;else if(i&&c===s&&(l===0||e.charCodeAt(l-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,l).trim();if(f)t.push(f);r=l+1;continue}}}let o=e.substring(r).trim();if(o)t.push(o);return t}function ws(e){if(As(e))return!0;if(e==="true"||e==="false")return!0;if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return!0;return!1}function Hd(e){return e==="number"||e==="string"||e==="boolean"}function $s(e){let t=!1,r=0,n=e.length;for(let i=0;i<n;i++){let s=e.charCodeAt(i);if(t){if(s===92){i++;continue}if(s===r)t=!1;continue}if(s===34||s===39||s===96){t=!0,r=s;continue}if(s===61&&i+1<n&&e.charCodeAt(i+1)===62)return!1;if(s>=97&&s<=122){let o=i;while(i<n&&(e.charCodeAt(i)>=97&&e.charCodeAt(i)<=122||e.charCodeAt(i)>=65&&e.charCodeAt(i)<=90||e.charCodeAt(i)>=48&&e.charCodeAt(i)<=57||e.charCodeAt(i)===95||e.charCodeAt(i)===36))i++;let l=e.slice(o,i);if(l==="new"||l==="async"||l==="await"||l==="function"||l==="yield"||l==="console"||l==="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 jd(e,t,r=0){let n=e.slice(1,-1).trim();if(!n)return"{}";if(r>=bs)return"Record<string, unknown>";let i=Jd(n),s=[],o=[],l=Wi&&!t,c=[];for(let[a,m]of i){let{comments:y,key:w}=zl(a),C=y?`${y}
|
|
152
|
+
`:"",x=w,k=!1;if(w==="..."){let b=m.trim(),j=cr(b)?`typeof ${b}`:Ie(b,t,!1,r+1);if(j!=="unknown")o.push(j);if(l&&(cr(b)||b.startsWith("{")))c.push(`...${Ii(b)}`);continue}let L=ze;ze=null;let G,T=m.trim();if(T===w&&Li(T))G=`typeof ${T}`;else if(Xd(T)){k=!0;let b=Qd(w);if(b){x=b.name;let j="";if(T.startsWith("async "))j="async ";if(T.charCodeAt(j.length)===42)j+="*";G=Ul(b.name,j+b.typeParams+T.slice(j.length))}else G=Ul(w,T)}else{if(G=Ie(m,t,!1,r+1),G==="unknown"&&cr(T))G=`typeof ${T}`;if(G.includes("=>")||G.includes("function")||G.includes("async"))G=Bl(G)}let D=ze;ze=L;let F=m.trim(),N=qd(w);if(N){let b=zd(N.kind,N.name,G);if(b){s.push(`${C}${b}`);continue}}if(!t&&Hd(G)&&ws(F))s.push(`${C}/** @defaultValue ${vs(F)} */
|
|
153
|
+
${x}: ${G}`);else s.push(`${C}${x}: ${G}`);if(l){let b=Hl(x);if(F.endsWith("as const"));else if(ws(F))c.push(`${b}: ${F}`);else if(F.startsWith("[")&&$s(F))c.push(`${b}: ${Ii(F)}`);else if(F.startsWith("{")){if(D)c.push(`${b}: ${D}`)}else if(k)c.push(`${b}: ${ms(Bl(G))}`);else if(!F.startsWith("[")&&(F.includes("=>")||F.startsWith("function")||F.startsWith("async"))){let j=Xl(F,!1,0,!0);c.push(`${b}: ${ms(j)}`)}}}if(l&&c.length>0){let a=r>0?(r-1)/2:0,m=`{ ${c.join(", ")} }`;if(m.length<=80)ze=m;else{let y=" ".repeat((a+1)*2),w=" ".repeat(a*2);ze=`{
|
|
131
154
|
${y}${c.join(`,
|
|
132
155
|
${y}`)}
|
|
133
|
-
${w}}`}}let f=
|
|
134
|
-
${
|
|
156
|
+
${w}}`}}let f=s.length>0?`{
|
|
157
|
+
${s.join(`;
|
|
135
158
|
`)}
|
|
136
|
-
}`:"{}";if(
|
|
137
|
-
`).map((f)=>
|
|
138
|
-
`),
|
|
139
|
-
`),key:e.slice(
|
|
140
|
-
`))
|
|
141
|
-
${n}`:n,n]);else if(n.startsWith("...")&&n.length>3)e.push(["...",n.slice(3).trim()])}function Wd(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 Bd(e,t,i){let n=i.trim();if(n.charCodeAt(0)!==40)return null;let r=tt(n,0,"(",")");if(r===-1)return null;let o=n.slice(1,r).trim(),s=n.slice(r+1).trimStart();if(!s.startsWith("=>"))return null;let l=s.slice(2).trim();if(e==="get")return`get ${t}(): ${l||"unknown"}`;return`set ${t}(${o})`}function Gd(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 n=0;n<t.length;n++){let r=t.charCodeAt(n);if(r===40)i++;else if(r===41){if(i--,i===0){let o=t.slice(n+1).trimStart();if(o.startsWith("{"))return!0;if(o.startsWith(":")){let s=No(o,1);if(s?.kind==="arrow")return!1;if(s?.kind==="body")return!0}return!1}}}return!1}function jd(e){let t=e.trimEnd();if(!t.endsWith(">"))return null;let i=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;i++}else if(s===60){if(i--,i===0){n=o;break}}}if(n===-1)return null;let r=t.slice(0,n).trimEnd();if(!r)return null;return{name:r,typeParams:t.slice(n)}}function Rl(e,t){let i=t.trimStart(),n=!1,r=!1;if(i.startsWith("async ")||i.startsWith("async\t"))n=!0,i=i.slice(5).trimStart();if(i.startsWith("*"))r=!0,i=i.slice(1).trimStart();let o="";if(i.charCodeAt(0)===60){let m=0,y=-1;for(let w=0;w<i.length;w++)if(i.charCodeAt(w)===60)m++;else if(i.charCodeAt(w)===62&&!(w>0&&i.charCodeAt(w-1)===61)){if(m--,m===0){y=w;break}}if(y!==-1)o=i.slice(0,y+1),i=i.slice(y+1).trimStart()}let s=i.indexOf("("),l=tt(i,s,"(",")");if(s===-1||l===-1)return"() => unknown";let c=i.slice(s,l+1),f="unknown",u=i.slice(l+1).trimStart();if(u.charCodeAt(0)===58){let m=u.slice(1),y=No(m,0);if(y)f=m.slice(0,y.index).trim();else f=m.trim()}if(f==="unknown"&&!r&&u.charCodeAt(0)===123){let m=tt(u,0,"{","}");if(m!==-1){let y=fi(u.slice(1,m),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&&r)f="AsyncGenerator<unknown, void, unknown>";else if(r)f="Generator<unknown, void, unknown>";else if(n)f="Promise<void>"}else if(n&&!f.startsWith("Promise<")&&!f.startsWith("AsyncGenerator<"))f=`Promise<${f}>`;let a=Wt(c);return`${o}${a} => ${f}`}function No(e,t){let i=0,n=0,r=0,o=0,s=!1,l=0;for(let c=t;c<e.length;c++){let f=e.charCodeAt(c);if(s){if(f===92)c++;else if(f===l)s=!1;continue}if(f===34||f===39||f===96){s=!0,l=f;continue}if(f===40)i++;else if(f===41&&i>0)i--;else if(f===91)n++;else if(f===93&&n>0)n--;else if(f===60)r++;else if(f===62&&r>0&&e.charCodeAt(c-1)!==61)r--;else if(f===125&&o>0)o--;else if(f===123){let u=i>0||n>0||r>0||o>0,a=e.slice(t,c).trimEnd(),m=a.charCodeAt(a.length-1),y=a.length===0||m===38||m===124||m===40||m===44||m===58||m===61||m===91;if(u||y)o++;else return{index:c,kind:"body"}}else if(f===61&&c+1<e.length&&e.charCodeAt(c+1)===62&&i===0&&n===0&&r===0&&o===0)return{index:c,kind:"arrow"}}return null}function tt(e,t,i,n){let r=0;for(let o=t;o<e.length;o++)if(e[o]===i)r++;else if(e[o]===n){if(n===">"&&o>0&&e[o-1]==="=")continue;if(r--,r===0)return o}return-1}function Lr(e){let t=0,i=0,n=!1,r="";for(let o=0;o<e.length-1;o++){let s=e[o],l=e[o+1],c=o>0?e[o-1]:"";if(!n&&(s==='"'||s==="'"||s==="`"))n=!0,r=s;else if(n&&s===r&&c!=="\\")n=!1;if(!n){if(s==="<"){let f=tt(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==="="&&l===">"&&t===0&&i===0)return o}}return-1}function Bl(e,t=!1,i=0,n=!0){let r=e.trim();if(r.length>200&&So(r,"=>")>2&&So(r,"<")>5&&!r.startsWith("function"))return t?"((...args: any[]) => any)":"(...args: any[]) => any";if(r.startsWith("async ")&&r.includes("=>")){let s=r.slice(5).trim(),l=Lr(s);if(l===-1)return t?"(() => Promise<unknown>)":"() => Promise<unknown>";let c=s.substring(0,l).trim(),f=s.substring(l+2).trim(),u=Pl(c),{params:a,returnType:m}=u;if(a=Wt(a),a==="()"||a==="")a="()";else if(!a.startsWith("("))a=`(${a})`;let y=m;if(y);else if(f.startsWith("{"))y=fi(f.slice(1,f.endsWith("}")?-1:void 0),!0,a);else y=Ie(f,n,!1,i+1);let w=`${a} => ${m||y.startsWith("Promise<")?y:`Promise<${y}>`}`;return t?`(${w})`:w}if(r.includes("=>")){let s="",l=r;if(r.startsWith("<")){let A=tt(r,0,"<",">");if(A!==-1)s=r.substring(0,A+1),l=r.substring(A+1).trim()}let c=Lr(l);if(c===-1)return t?"(() => unknown)":"() => unknown";let f=l.substring(0,c).trim(),u=l.substring(c+2).trim(),a=Pl(f),{params:m,returnType:y}=a;if(m=Wt(m),m==="()"||m==="")m="()";else if(!m.startsWith("("))m=`(${m})`;let w="unknown";if(y)w=y;else if(u.startsWith("{"))w=fi(u.slice(1,u.endsWith("}")?-1:void 0),!1,m);else if(Ir(u)||Il(u)&&Ir(u.slice(1,-1).trim()))w="JSX.Element";else if(u.includes("=>")){let A=u.trimStart(),k=A.indexOf("("),W=k!==-1?tt(A,k,"(",")"):-1,B=W!==-1?A.indexOf("=>",W):-1;if(k===0&&W!==-1&&B!==-1){let T=A.substring(k+1,W).trim(),D=Wt(T);if(s.includes("T")&&D.includes("T"))w=`(${D}) => T`;else w=`(${D}) => any`}else w="any"}else if(t)w="unknown";else w=Lt(u,Dl(m));let C=`${s}${m} => ${w}`;return t?`(${C})`:C}if(r.startsWith("function")){let s=8,l=r.length;while(s<l&&r.charCodeAt(s)<=32)s++;let c=!1;if(s<l&&r.charCodeAt(s)===42){c=!0,s++;while(s<l&&r.charCodeAt(s)<=32)s++}let f="";if(s<l&&r.charCodeAt(s)===60){let m=s,y=1;s++;while(s<l&&y>0){let w=r.charCodeAt(s);if(w===60)y++;else if(w===62&&r.charCodeAt(s-1)!==61)y--;s++}f=r.substring(m,s);while(s<l&&r.charCodeAt(s)<=32)s++}let u=r.indexOf("(",s);if(u!==-1){let m=1,y=u+1;while(y<l&&m>0){let B=r.charCodeAt(y);if(B===40)m++;else if(B===41)m--;y++}let w=r.substring(u+1,y-1).trim(),C=w?Wt(`(${w})`):"()";if(c){let B=r.substring(y).trim(),T=B.indexOf("Generator<");if(T!==-1){let N=T+10,F=B.indexOf(">",N);if(F!==-1){let E=B.substring(N,F),K=`${f}${C} => Generator<${E}>`;return t?`(${K})`:K}}let D=`${f}${C} => Generator<any, any, any>`;return t?`(${D})`:D}let A="unknown",k=r.substring(y).trimStart();if(k.charCodeAt(0)===58){let B=k.slice(1),T=No(B,0),D=(T?B.slice(0,T.index):B).trim();if(D)A=D}let W=`${f}${C} => ${A}`;return t?`(${W})`:W}let a="(...args: any[]) => unknown";return t?`(${a})`:a}if(r.includes("=>")&&r.includes("(")&&r.includes(")")){if(r.length>100||So(r,"=>")>2){let s="";if(r.charCodeAt(0)===60){let a=tt(r,0,"<",">");if(a!==-1)s=r.substring(0,a+1)}let l=r.indexOf("("),c=l!==-1?tt(r,l,"(",")"):-1,f=l!==-1&&c!==-1?r.substring(l,c+1):"(...args: any[])";f=Wt(f);let u=`${s}${f} => any`;return t?`(${u})`:u}return t?`(${r})`:r}let o="() => unknown";return t?`(${o})`:o}function Pl(e){let t=e.trim();if(!t.startsWith("("))return{params:t,returnType:""};let i=tt(t,0,"(",")");if(i===-1)return{params:t,returnType:""};let n=t.slice(i+1).trim();return{params:t.slice(0,i+1),returnType:n.startsWith(":")?n.slice(1).trim():""}}function Gl(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 Gr(e){let t=-1,i=0;for(let r=0;r<e.length;r++){let o=e.charCodeAt(r);if(o===34||o===39||o===96){r=kt(e,r,o)-1;continue}if(o===47&&e.charCodeAt(r+1)===47){while(r<e.length&&e.charCodeAt(r)!==10)r++;continue}if(o===47&&e.charCodeAt(r+1)===42){let s=e.indexOf("*/",r+2);r=s===-1?e.length:s+1;continue}if(o===47){let s=r-1;while(s>=0&&e.charCodeAt(s)<=32)s--;if(s<0||"([{:;,=!?&|+*-~>".includes(e[s])){let l=!1;for(r++;r<e.length;r++){let c=e.charCodeAt(r);if(c===92)r++;else if(c===91)l=!0;else if(c===93)l=!1;else if(c===47&&!l)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",r)&&xo(e,r,9)&&e[r-1]!==".")t=r}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 ko=20,Wr=!1,Ye=null;var Fo=()=>{};function je(e){return e===ke||e===Me||e===Ee||e===Te}function Ud(e){let t=!0;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);if(n===pt){if(t)return!1;t=!0}else if(t){if(!mt(n))return!1;t=!1}else if(!_e(n))return!1}return e.length>0&&!t}function _r(e,t,i){let n=t+1;while(n<e.length){let r=e.charCodeAt(n);if(r===it){n+=2;continue}if(n++,r===i)break}return n}function Kd(e){if(e==="any"||e==="object"||e==="unknown")return!0;if(e.startsWith("Record<")||e.startsWith("Array<"))return!0;return e.charCodeAt(0)===H&&e.includes("[")&&e.includes("]:")}function Vl(e,t,i=!0){return Kl(e,t,i,!0)}function Ul(e,t,i=!0){return Kl(e,t,i,!1)}function Kl(e,t,i,n){let r=e,o=i,s=n,l=r.length,c=[],f=new Map,u=new Set,a=0;if(a<l&&r.charCodeAt(a)===65279)a++;function m(d,p){if(d<p){let h=r.charCodeAt(d),g=r.charCodeAt(p-1);if(h!==ke&&h!==Me&&h!==Ee&&h!==Te&&g!==ke&&g!==Me&&g!==Ee&&g!==Te)return r.slice(d,p)}while(d<p&&je(r.charCodeAt(d)))d++;while(p>d&&je(r.charCodeAt(p-1)))p--;return r.slice(d,p)}let y=/[\r\n]/g;function w(d){return y.lastIndex=d,y.exec(r)?.index??l}function C(){if(a>=l)return;let d=r.charCodeAt(a);if(d!==ke&&d!==Me&&d!==Ee&&d!==Te&&d!==Q)return;while(a<l){let p=r.charCodeAt(a);if(p===ke||p===Me||p===Ee||p===Te){a++;continue}if(p===Q&&a+1<l){let h=r.charCodeAt(a+1);if(h===Q){a=w(a+2);continue}if(h===Ae){let g=r.indexOf("*/",a+2);a=g===-1?l:g+2;continue}}break}}function A(d){let p=d.length,h=0,g=p;for(let b=0;b<p;b++){let v=d.charCodeAt(b);if(h){if(v===it){b++;continue}if(v===h)h=0;continue}if(v===le||v===ue||v===Ne){h=v;continue}if(v===Q&&b+1<p){let O=d.charCodeAt(b+1);if(O===Q){g=b;while(g>0&&(d.charCodeAt(g-1)===ke||d.charCodeAt(g-1)===Me))g--;return d.slice(0,g)}if(O===Ae){let R=d.indexOf("*/",b+2);if(R!==-1){d=`${d.slice(0,b)} ${d.slice(R+2)}`,b--;continue}}}}g=p;while(g>0&&(d.charCodeAt(g-1)===ke||d.charCodeAt(g-1)===Me||d.charCodeAt(g-1)===Te))g--;return g<p?d.slice(0,g):d}function k(d){a++;let p=d===le?"'":'"';while(a<l){let h=r.indexOf(p,a);if(h===-1){a=l;return}let g=0,b=h-1;while(b>=0&&r.charCodeAt(b)===it)g++,b--;if(g%2===0){a=h+1;return}a=h+1}}function W(){a++;let d=[];while(a<l){let p=r.charCodeAt(a);if(d.length===0){if(p===it){a+=2;continue}if(p===Ne){a++;return}if(p===Vd&&a+1<l&&r.charCodeAt(a+1)===H){a+=2,d.push(0);continue}a++;continue}if(p===le||p===ue){k(p);continue}if(p===Ne){W();continue}if(p===Q&&a+1<l){let h=r.charCodeAt(a+1);if(h===Q){a=w(a+2);continue}if(h===Ae){let g=r.indexOf("*/",a+2);a=g===-1?l:g+2;continue}if(D()){N();continue}a++;continue}if(p===H){d[d.length-1]++,a++;continue}if(p===X){let h=d[d.length-1];if(h===0){d.pop(),a++;continue}d[d.length-1]=h-1,a++;continue}a++}}let B=!1;function T(){B=!1;let d=r.charCodeAt(a);if(d===le||d===ue)return k(d),!0;if(d===Ne)return W(),!0;if(d===Q&&a+1<l){let p=r.charCodeAt(a+1);if(p===Q)return a=w(a+2),!0;if(p===Ae){let h=r.indexOf("*/",a+2);return B=w(a+2)<(h===-1?l:h),a=h===-1?l:h+2,!0}if(D())return N(),!0}return!1}function D(){return ji(r,a)}function N(){a=di(r,a)}function F(){let d=a;while(a<l&&_e(r.charCodeAt(a)))a++;return r.slice(d,a)}function E(d){if(a+d.length>l)return!1;for(let p=0;p<d.length;p++)if(r.charCodeAt(a+p)!==d.charCodeAt(p))return!1;if(a+d.length<l&&_e(r.charCodeAt(a+d.length)))return!1;return!0}function K(d){let p=a+d;while(p<l){let h=r.charCodeAt(p);if(h===ke||h===Me||h===Ee||h===Te){p++;continue}return h!==pt&&h!==ve}return!1}function oe(){if(!B)return!1;let d=a;C();let p=a>=l||he()||r.charCodeAt(a)===X;return a=d,p}function he(){if(a>=l)return!1;switch(r.charCodeAt(a)){case 101:return E("export")||E("enum");case 105:return E("import")||E("interface");case 102:return E("function");case 99:return E("class")||E("const");case 116:return E("type");case 108:return E("let");case 118:return E("var");case 100:return E("declare")||E("default");case 109:return E("module");case 110:return E("namespace");case 97:return E("abstract")||E("async");default:return!1}}function z(){let d=r.charCodeAt(a);if(d!==Ee&&d!==Te)return!1;let p=a;if(a++,d===Te&&a<l&&r.charCodeAt(a)===Ee)a++;while(a<l){let g=r.charCodeAt(a);if(g===ke||g===Me||g===Te||g===Ee){a++;continue}if(g===Q&&a+1<l){let b=r.charCodeAt(a+1);if(b===Q){a=w(a+2);continue}if(b===Ae){let v=r.indexOf("*/",a+2);a=v===-1?l:v+2;continue}}break}let h=a>=l||he()||r.charCodeAt(a)===X;return a=p,h}function ge(d){let p=d-1;while(p>=0){let S=r.charCodeAt(p);if(S===ke||S===Me||S===Te||S===Ee){p--;continue}break}if(p<0)return!0;let h=r[p];if("+-*/%=<>&|^!~?:,.([{".includes(h))return!0;let g=p;while(g>0&&r.charCodeAt(g-1)!==Ee)g--;let b=r.slice(g,p+1),v=b.lastIndexOf("<");if(v!==-1&&/^<[A-Za-z]/.test(b.slice(v))&&!b.slice(v).includes(">"))return!0;let O=p;while(O>=0&&/[a-z]/i.test(r[O]))O--;let R=r.slice(O+1,p+1);return["as","in","of","new","typeof","keyof","extends","instanceof","satisfies","await","return","yield","void"].includes(R)}function De(){let d=r.charCodeAt(a);if(d!==Ee&&d!==Te)return!1;if(ge(a))return!1;let p=a;a++;while(a<l){let v=r.charCodeAt(a);if(v===ke||v===Me||v===Te||v===Ee){a++;continue}if(v===Q&&a+1<l){let O=r.charCodeAt(a+1);if(O===Q){a=w(a+2);continue}if(O===Ae){let R=r.indexOf("*/",a+2);a=R===-1?l:R+2;continue}}break}let h=a<l?r[a]:"",g=r.slice(a,a+2),b=h==="."||h==="?"||h===":"||h===")"||h==="]"||h==="}"||h===","||h==="+"||h==="-"||h==="*"||h==="/"||h==="%"||h==="<"||h===">"||h==="="||h==="&"||h==="|"||h==="^"||h==="`"||g==="=>"||E("as")||E("satisfies")||E("instanceof")||E("in");return a=p,!b}function re(){let d=r.charCodeAt(a);if(d!==Ee&&d!==Te)return!1;if(ge(a))return!1;let p=a;a++;while(a<l){let b=r.charCodeAt(a);if(b===ke||b===Me||b===Te||b===Ee){a++;continue}if(b===Q&&a+1<l){let v=r.charCodeAt(a+1);if(v===Q){a=w(a+2);continue}if(v===Ae){let O=r.indexOf("*/",a+2);a=O===-1?l:O+2;continue}}break}let h=a<l?r[a]:"",g=h==="|"||h==="&"||h==="["||h==="."||h==="?"||h===":"||h===">"||h===")"||h===","||E("extends");return a=p,!g}function ce(){let d=r.charCodeAt(a);if(d!==Ee&&d!==Te)return!1;let p=a;if(a++,d===Te&&a<l&&r.charCodeAt(a)===Ee)a++;while(a<l){let g=r.charCodeAt(a);if(g===ke||g===Me||g===Te||g===Ee){a++;continue}if(g===Q&&a+1<l&&r.charCodeAt(a+1)===Q){a=w(a+2);continue}break}if(a>=l)return a=p,!0;let h=r.charCodeAt(a);if(h===124||h===38||h===pt||h===jr||h===lt)return a=p,!1;if(E("extends")||E("keyof")||E("typeof")||E("infer")||E("is")||E("as")||E("in"))return a=p,!1;return a=p,!0}let ee=/[{}'"`\/]/g,L=/[()'"`\/]/g,U=/[[\]'"`\/]/g,q=/[<>'"`\/]/g;function Z(d,p){let h=1;a++;let g=d===H?ee:d===ae?L:d===xe?U:q;g.lastIndex=a;let b;while((b=g.exec(r))!==null){let v=b.index,O=r.charCodeAt(v);if(O===le||O===ue){a=v,k(O),g.lastIndex=a;continue}if(O===Ne){a=v,W(),g.lastIndex=a;continue}if(O===Q){if(a=v,T()){g.lastIndex=a;continue}g.lastIndex=v+1;continue}if(O===d)h++;else if(O===p){if(p===me&&v>0&&r.charCodeAt(v-1)===ve){g.lastIndex=v+1;continue}if(h--,h===0)return a=v+1,a}g.lastIndex=v+1}return a=l,a}function J(){return a>0&&r.charCodeAt(a-1)===ve}function te(){return a+1<l&&r.charCodeAt(a+1)===me}let se=/[<{};'"`\/\n\r()[\]]/g;function ne(d=!1){let p=0,h=0,g=0,b=0,v=r.charCodeAt(a)===H;se.lastIndex=a;let O;while((O=se.exec(r))!==null){let R=O.index,S=r.charCodeAt(R);if(S===le||S===ue){a=R,k(S),se.lastIndex=a;continue}if(S===Ne){a=R,W(),se.lastIndex=a;continue}if(S===Q){if(R>0&&r.charCodeAt(R-1)===be){se.lastIndex=R+1;continue}if(a=R,T()){if(p===0&&h===0&&g===0&&b===0&&oe())return;se.lastIndex=a;continue}se.lastIndex=R+1;continue}if(S===be){let x=es(R);if(x!==null)b=Math.max(0,b+x);se.lastIndex=R+1;continue}if(S===ae){h++,se.lastIndex=R+1;continue}if(S===$e){h--,se.lastIndex=R+1;continue}if(S===xe){g++,se.lastIndex=R+1;continue}if(S===Pe){g--,se.lastIndex=R+1;continue}if(S===H){p++,se.lastIndex=R+1;continue}if(S===X){let x=p>0;if(!x&&d&&h===0&&g===0&&b===0){a=R;return}if(x)p--;if((!x||v)&&p===0&&h===0&&g===0&&b===0){a=R+1;return}se.lastIndex=R+1;continue}if(S===ie&&p===0&&h===0&&g===0&&b===0){a=R+1;return}if((S===Ee||S===Te)&&p===0&&h===0&&g===0&&b===0){if(a=R,z())return}se.lastIndex=R+1}a=l}function qr(){a++;while(a<l&&(r.charCodeAt(a)===ke||r.charCodeAt(a)===Me))a++;let d=r.indexOf(`
|
|
142
|
-
|
|
143
|
-
`));continue}break}if(h.length===0)return;return h.reverse(),h}function qc(d){let p=d,h=!1;while(a<l){let S=r.charCodeAt(a);if(S===ie){a++;break}if(S===le||S===ue){k(S),h=!0;while(a<l&&(r.charCodeAt(a)===ke||r.charCodeAt(a)===Me))a++;if(a<l&&r.charCodeAt(a)===ie)a++;break}if(S===Ee&&h)break;a++}let g=m(p,a),b=g.charCodeAt(7)===116&&(g.startsWith("import type ")||g.startsWith("import type{")),v=!1;{let S=6;while(S<g.length&&(g.charCodeAt(S)===ke||g.charCodeAt(S)===Me))S++;if(S<g.length&&g.charCodeAt(S)===116&&g.startsWith("type",S)){S+=4;while(S<g.length&&(g.charCodeAt(S)===ke||g.charCodeAt(S)===Me))S++}if(S<g.length){let x=g.charCodeAt(S);v=x===le||x===ue}}let O="";{let S=g.indexOf("from ");if(S!==-1){let x=S+5;while(x<g.length&&(g.charCodeAt(x)===ke||g.charCodeAt(x)===Me))x++;if(x<g.length){let P=g.charCodeAt(x);if(P===le||P===ue){let j=g.indexOf(String.fromCharCode(P),x+1);if(j!==-1)O=g.slice(x+1,j)}}}else if(v){let x=6;while(x<g.length&&g.charCodeAt(x)!==le&&g.charCodeAt(x)!==ue)x++;if(x<g.length){let P=g.charCodeAt(x),j=g.indexOf(String.fromCharCode(P),x+1);if(j!==-1)O=g.slice(x+1,j)}}}let R=Xe(p);return{kind:"import",name:"",text:g,isExported:!1,isTypeOnly:b,isSideEffect:v,source:O,leadingComments:R,start:p,end:a}}function Yr(){let d=a;return Z(H,X),r.slice(d,a)}function Yo(d){let p=d.indexOf("(");if(p===-1)return d;let h=d.slice(p);if(h.indexOf("=")===-1)return d;let g=!1;for(let S=0;S<h.length;S++)if(h.charCodeAt(S)===61){let x=S>0?h.charCodeAt(S-1):0,P=S+1<h.length?h.charCodeAt(S+1):0;if(x!==61&&x!==33&&x!==60&&x!==62&&P!==61&&P!==62){g=!0;break}}if(!g)return d;let b=0,v=-1;for(let S=p;S<d.length;S++){let x=d.charCodeAt(S);if(x===40)b++;else if(x===41){if(b--,b===0){v=S;break}}}if(v===-1)return d;let O=d.slice(p,v+1),R=Gt(O);return d.slice(0,p)+R+d.slice(v+1)}function Zo(d){let p=d.indexOf("//")!==-1||d.indexOf("/*")!==-1,h=d.split(`
|
|
144
|
-
`),g=[],b=[],v=[],O=!1,R=1/0;for(let P=0;P<h.length;P++){let j=h[P];if(p){if(O){if(j.includes("*/"))O=!1;continue}let G=j.trim();if(G.length===0)continue;let I=G.charCodeAt(0);if(I===Q){let He=G.charCodeAt(1);if(He===Q)continue;if(He===Ae){if(!G.includes("*/"))O=!0;continue}}if(I===Ae)continue;let M=A(j);if(M.charCodeAt(M.length-1)===ie)M=M.slice(0,-1);M=Yo(M);let _=M.trim();if(!_)continue;g.push(M),b.push(_);let V=0;while(V<M.length&&je(M.charCodeAt(V)))V++;if(_!=="{"&&_!=="}"){if(V<R)R=V}v.push(V)}else{let G=j.length;while(G>0&&(j.charCodeAt(G-1)===ke||j.charCodeAt(G-1)===Me||j.charCodeAt(G-1)===Te))G--;if(G===0)continue;let I=G<j.length?j.slice(0,G):j;if(I.charCodeAt(I.length-1)===ie)I=I.slice(0,-1);I=Yo(I);let M=I.trim();if(!M)continue;g.push(I),b.push(M);let _=0;while(_<I.length&&je(I.charCodeAt(_)))_++;if(M!=="{"&&M!=="}"){if(_<R)R=_}v.push(_)}}if(g.length===0)return"{}";if(R===1/0||R<=2)return g.join(`
|
|
145
|
-
`);let S=R-2,x=Array(g.length);for(let P=0;P<g.length;P++){let j=b[P];if(j==="{"){x[P]=j;continue}let G=v[P];if(G>R)x[P]=g[P];else if(G===R&&(j.charCodeAt(0)===X||j.charCodeAt(0)===Pe||j.charCodeAt(0)===$e))x[P]=g[P];else{let I=Math.max(0,G-S);x[P]=" ".repeat(I)+j}}return x.join(`
|
|
146
|
-
`)}function ht(){if(a>=l||r.charCodeAt(a)!==be)return"";let d=a;Z(be,me);let p=r.slice(d,a);if(p.includes(`
|
|
147
|
-
`)){let h="",g=!1;for(let b=0;b<p.length;b++){let v=p.charCodeAt(b);if(v===32||v===9||v===10||v===13){if(!g&&h.length>0)h+=" ",g=!0}else h+=p[b],g=!1}if(h.charCodeAt(1)===32)h=`<${h.slice(2)}`;if(h.charCodeAt(h.length-2)===32)h=`${h.slice(0,-2)}>`;return h}return p}function xt(){if(a>=l||r.charCodeAt(a)!==ae)return"()";let d=a;return Z(ae,$e),r.slice(d,a)}function Fi(d){if(d.indexOf("/")===-1)return d;let p="",h=!1,g=0;for(let b=0;b<d.length;b++){let v=d.charCodeAt(b);if(h){if(p+=d[b],v===it&&b+1<d.length){p+=d[++b];continue}if(v===g)h=!1;continue}if(v===le||v===ue||v===Ne){h=!0,g=v,p+=d[b];continue}if(v===Q&&b+1<d.length){let O=d.charCodeAt(b+1);if(O===Ae){let R=d.indexOf("*/",b+2);b=R===-1?d.length:R+1,p+=" ";continue}if(O===Q){let R=d.indexOf(`
|
|
148
|
-
`,b+2);b=R===-1?d.length:R-1;continue}}p+=d[b]}return p.trim()}function Gt(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 S=0,x=0,P=0;for(let j=0;j<p.length;j++){let G=p.charCodeAt(j);if(G===ae||G===be||G===H)P++;else if(G===$e||G===me||G===X)P--;else if(P===0){if(G===lt)S++;else if(G===ut)x++}}if(S>=x+1){let j=!1;for(let G=0;G<Wo.length;G++){let I=Wo[G],M=p.indexOf(I);if(M!==-1){let _=M+I.length;if((M===0||!_e(p.charCodeAt(M-1)))&&(_>=p.length||!_e(p.charCodeAt(_)))){j=!0;break}}}if(!j)return d}}let h=[],g=0,b=0,v=!1,O=0;for(let S=0;S<=p.length;S++){if(S===p.length){h.push(Fi(p.slice(g).trim()));break}let x=p.charCodeAt(S);if(v){if(x===it){S++;continue}if(x===O)v=!1;continue}if(x===Q&&S+1<p.length){let P=p.charCodeAt(S+1);if(P===Ae){S+=2;while(S+1<p.length&&!(p.charCodeAt(S)===Ae&&p.charCodeAt(S+1)===Q))S++;S++;continue}if(P===Q){while(S<p.length&&p.charCodeAt(S)!==10)S++;continue}}if(x===le||x===ue||x===Ne){v=!0,O=x;continue}if(x===ae||x===H||x===xe||x===be)b++;else if(x===$e||x===X||x===Pe||x===me&&!(S>0&&p.charCodeAt(S-1)===ve))b--;else if(x===ut&&b===0)h.push(Fi(p.slice(g,S).trim())),g=S+1}let R=[];for(let S of h){if(!S)continue;let x=S.trim();if(x.startsWith("//")||x.startsWith("/*"))continue;let P=S;{let j=!1,G=0,I=0,M=0;for(let _=0;_<P.length-1;_++){let V=P.charCodeAt(_);if(V===Ee){M=_+1;continue}if(j){if(V===it){_++;continue}if(V===G)j=!1;continue}if(V===le||V===ue||V===Ne){j=!0,G=V;continue}if(V===H||V===xe||V===ae||V===be){I++;continue}if(V===X||V===Pe||V===$e||V===me){if(I>0)I--;continue}if(V===Q&&P.charCodeAt(_+1)===Q){if(I===0){P=P.slice(0,_).trimEnd();break}let He=P.indexOf(`
|
|
150
|
-
`,_);if(He===-1){P=P.slice(0,M).trimEnd();break}let ze=P.slice(0,M),Vt=P.slice(He+1);P=`${ze}${Vt}`,_=M-1}}}if(!P.trim())continue;R.push(Xo(P))}return`(${R.join(", ")})`}function Yc(d){if(!d.startsWith("{")&&!d.startsWith("["))return d;let p="",h=0,g=0,b=!1,v=0;while(h<d.length){let O=d.charCodeAt(h);if(b){if(O===it&&h+1<d.length){p+=d[h]+d[h+1],h+=2;continue}if(O===v)b=!1;p+=d[h],h++;continue}if(O===Q&&h+1<d.length){let R=d.charCodeAt(h+1);if(R===Ae){let S=h;h+=2;while(h+1<d.length&&!(d.charCodeAt(h)===Ae&&d.charCodeAt(h+1)===Q))h++;h=Math.min(h+2,d.length),p+=d.slice(S,h);continue}if(R===Q){let S=h;while(h<d.length&&d.charCodeAt(h)!==10)h++;p+=d.slice(S,h);continue}}if(O===le||O===ue||O===Ne){b=!0,v=O,p+=d[h],h++;continue}if(O===H||O===xe||O===ae)g++;else if(O===X||O===Pe||O===$e)g--;if(g>=1&&O===ve&&(h+1>=d.length||d.charCodeAt(h+1)!==ve&&d.charCodeAt(h+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);h++;let R=0;while(h<d.length){let S=d.charCodeAt(h);if(S===le||S===ue||S===Ne){let x=S;h++;while(h<d.length){if(d.charCodeAt(h)===it){h+=2;continue}if(d.charCodeAt(h)===x){h++;break}h++}continue}if(S===H||S===xe||S===ae)R++;else if(S===X||S===Pe||S===$e){if(R===0)break;R--}else if(S===ut&&R===0)break;h++}continue}if(g===1&&O===pt&&h+2<d.length&&d.charCodeAt(h+1)===pt&&d.charCodeAt(h+2)===pt){h+=3;continue}p+=d[h],h++}return p}function Xo(d){let p=d.trim(),h=p.startsWith("...");if(h)p=p.slice(3).trim();while(p.startsWith("@")){let M=1;while(M<p.length&&_e(p.charCodeAt(M)))M++;if(M<p.length&&p.charCodeAt(M)===ae){let _=1;M++;while(M<p.length&&_>0){if(p.charCodeAt(M)===ae)_++;else if(p.charCodeAt(M)===$e)_--;M++}}p=p.slice(M).trim()}let g=!0;while(g){g=!1;for(let M of Wo)if(p.startsWith(M)&&p.length>M.length&&!_e(p.charCodeAt(M.length))){let _=p.slice(M.length).trim();if(_.charCodeAt(0)===lt||_.charCodeAt(0)===jr&&_.length>1&&_.charCodeAt(1)===lt)break;p=_,g=!0;break}}let b=-1,v=-1,O=0,R=!1,S=0;for(let M=0;M<p.length;M++){let _=p.charCodeAt(M);if(R){if(_===it){M++;continue}if(_===S)R=!1;continue}if(_===Q&&M+1<p.length){let V=p.charCodeAt(M+1);if(V===Ae){M+=2;while(M+1<p.length&&!(p.charCodeAt(M)===Ae&&p.charCodeAt(M+1)===Q))M++;M++;continue}if(V===Q){while(M<p.length&&p.charCodeAt(M)!==10)M++;continue}}if(_===le||_===ue||_===Ne){R=!0,S=_;continue}if(_===ae||_===H||_===xe||_===be)O++;else if(_===$e||_===X||_===Pe||_===me&&!(M>0&&p.charCodeAt(M-1)===ve))O--;else if(O===0){if(_===lt&&b===-1)b=M;else if(_===ve&&v===-1&&(M===0||p.charCodeAt(M-1)!==ve)&&(M+1>=p.length||p.charCodeAt(M+1)!==ve&&p.charCodeAt(M+1)!==me))v=M}}let x,P,j=v!==-1;if(b!==-1&&(v===-1||b<v))if(x=p.slice(0,b).trim(),v!==-1)P=p.slice(b+1,v).trim();else P=p.slice(b+1).trim();else if(v!==-1)x=p.slice(0,v).trim(),P=Zr(p.slice(v+1).trim());else x=p,P="unknown";if(x=Yc(x),(x.startsWith("{")||x.startsWith("["))&&x.includes(`
|
|
152
|
-
`)){let M=x.replace(/\s*\n\s*/g," ").replace(/\s+/g," ");if(M.length<=40)x=M;else x=x.split(`
|
|
153
|
-
`).map((_)=>{let V=_.trim();if(!V)return"";if(V==="{"||V==="}"||V==="["||V==="]"||V.startsWith("}")||V.startsWith("]"))return V;return` ${V}`}).join(`
|
|
154
|
-
`)}let G=x.endsWith("?")||j;if(x.endsWith("?"))x=x.slice(0,-1).trim();let I=G&&!h?"?":"";if(h)return`...${x}: ${P}`;return`${x}${I}: ${P}`}function Qo(d){let p=0;if(p<d.length&&d.charCodeAt(p)===45)p++;if(p>=d.length)return!1;let h=d.charCodeAt(p);if(h<48||h>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 Zr(d){let p=d.trim();if(p==="true"||p==="false")return"boolean";if(Qo(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 Xr(d){let p=d.trim();if(p.endsWith("as const"))p=p.slice(0,-8).trim();if(p==="true"||p==="false")return p;if(Qo(p))return p;let h=Zc(p);if(h!==null)return h;return"unknown"}function Zc(d){if(d==="")return null;if(d.charCodeAt(0)===le||d.charCodeAt(0)===ue){if(_r(d,0,d.charCodeAt(0))===d.length)return d}let p=Xc(d,"+");if(p.length>1){let h=!1,g=!0,b=[];for(let v of p){let O=v.trim(),R=O.charCodeAt(0);if((R===le||R===ue)&&_r(O,0,R)===O.length)h=!0,b.push(Qc(O));else g=!1}if(g)return ef(b.join(""));if(h)return"string";return null}if(/^[\d\s()+*/%.\-]+$/.test(d)&&/\d/.test(d)&&/[+*/%\-\s]/.test(d))return"number";return null}function Xc(d,p){let h=[],g=0,b="",v=0;while(v<d.length){let O=d.charCodeAt(v);if(O===le||O===ue||O===Ne){let R=_r(d,v,O);b+=d.slice(v,R),v=R;continue}if(O===Q&&(d.charCodeAt(v+1)===Q||d.charCodeAt(v+1)===42)){if(d.charCodeAt(v+1)===Q){let x=d.indexOf(`
|
|
155
|
-
`,v+2),P=x===-1?d.length:x;b+=d.slice(v,P),v=P;continue}let R=d.indexOf("*/",v+2),S=R===-1?d.length:R+2;b+=d.slice(v,S),v=S;continue}if(O===ae||O===xe||O===H)g++;else if(O===$e||O===Pe||O===X)g--;if(d[v]===p&&g===0){h.push(b),b="",v++;continue}b+=d[v],v++}return h.push(b),h}function Qc(d){return d.slice(1,-1).replace(/\\(.)/g,(p,h)=>{if(h==="n")return`
|
|
156
|
-
`;if(h==="t")return"\t";if(h==="r")return"\r";if(h==="0")return"\x00";return h})}function ef(d){return`'${d.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function Li(d){if(d.endsWith("as const"))return null;let p=0,h=-1;for(let g=0;g<d.length;g++){let b=d.charCodeAt(g);if(b===le||b===ue||b===Ne)g=_r(d,g,b)-1;else if(b===123||b===91||b===40)p++;else if(b===125||b===93||b===41)p--;else if(p===0&&b===32&&g+4<=d.length&&d.substring(g,g+4)===" as ")h=g}if(h===-1)return null;return d.slice(h+4).trim()||null}function hi(){if(C(),a<l&&r.charCodeAt(a)===lt){a++,C();let d=a,p=0;while(a<l){if(T())continue;let h=r.charCodeAt(a);if(h===ae||h===xe||h===be)p++;else if(h===$e||h===Pe||h===me&&!J())p--;else if(h===H)if(p>0)p++;else{let g=m(d,a),b=(v)=>{let O=g.length-v.length;return O>=0&&g.endsWith(v)&&(O===0||!_e(g.charCodeAt(O-1)))};if(g.length===0||g.endsWith("|")||g.endsWith("&")||b("is")||b("extends"))p++;else break}else if(h===X){if(p===0)break;p--}else if(p===0&&h===ie)break;if(p===0&&ce())break;a++}return m(d,a)}return""}function At(d,p,h,g){a+=8,C();let b=a<l&&r.charCodeAt(a)===Ae;if(b)a++,C();let v=F();if(!v&&!g)return null;C();let O=ht();C();let R=xt();C();let S=hi(),x=S.length>0;if(!S)if(h&&b)S="AsyncGenerator<unknown, void, unknown>";else if(b)S="Generator<unknown, void, unknown>";else if(h)S="Promise<void>";else S="void";C();let P=!1;if(a<l&&r.charCodeAt(a)===H){P=!0;let M=a+1;if(Z(H,X),!x&&!b)S=fi(r.slice(M,a-1),h,R)}else if(a<l&&r.charCodeAt(a)===ie)a++;let j=Gt(R),G=`${p?g?"export default function ":"export declare function ":"declare function "}${v||(g?"":"default")}${O}${j}: ${S};`,I=Xe(d);if(P)u.add(c.length);return{kind:"function",name:v||"default",text:G,isExported:p,isDefault:g,isAsync:h,isGenerator:b,returnType:S,generics:O||void 0,leadingComments:I,start:d,end:a}}function It(d,p,h){a+=p.length,C();let g=[];do{if(C(),a>=l)break;let b=r.charCodeAt(a);if(b===H||b===xe)return ne(),g;let v=F();if(!v)return ne(),g;C();let O,R,S=!1;if(a<l&&r.charCodeAt(a)===lt){a++,C();let j=a,G=0;while(a<l){if(T()){if(G===0&&oe())break;continue}let I=r.charCodeAt(a);if(I===ae||I===H||I===xe||I===be)G++;else if(I===$e||I===X||I===Pe||I===me&&!J())G--;else if(G===0&&(I===ie||I===ut))break;else if(G===0&&I===ve&&!te())break;if(G===0&&(z()||re()))break;a++}O=m(j,a)}if(a<l&&r.charCodeAt(a)===ve)if(s&&O&&(!o||!Kd(O)))qr();else{a++,C();let j=a,G=0,I=0,M=0,_=!0;for(;;){a=j,G=0,I=0,M=0;while(a<l){if(T()){if(G===0&&I===0&&M===0&&oe())break;continue}let V=r.charCodeAt(a);if(V===ae||V===H||V===xe)G++;else if(V===$e||V===X||V===Pe)G--;else if(V===be&&G===0){let He=es(a);if(He!==null)M=Math.max(0,M+He);else if(_&&(a+1>=l||r.charCodeAt(a+1)!==ve))I++}else if(V===me&&G===0&&M===0&&!J()){if(I>0&&(a+1>=l||r.charCodeAt(a+1)!==ve))I--}else if(G===0&&I===0&&M===0&&(V===ie||V===ut))break;if(G===0&&I===0&&M===0&&(z()||De()))break;a++}if(I>0&&_){_=!1;continue}break}if(R=m(j,a),R.endsWith(" as const")||R==="const"){if(S=!0,!O){let V=R.endsWith(" as const")?R.slice(0,-9).trim():R,He=Xr(V);O=He!=="unknown"?He:void 0}}else if(!O){let V=Gr(R)??Li(R);if(V)O=V}}if(a<l){let j=r.charCodeAt(a);if(j===ut){a++;continue}if(j===ie)a++}let x=Xe(d),P=`${h?"export ":""}declare ${p} ${v}: ${O||"unknown"};`;g.push({kind:"variable",name:v,text:P,isExported:h,typeAnnotation:O,value:R,modifiers:S?[p,"const assertion"]:[p],leadingComments:x,start:d,end:a});break}while(a<l);return g}function es(d){if(r.charCodeAt(d)!==be||d+1>=l)return null;let p=r.charCodeAt(d+1);if(p===me)return 1;if(p===Q)return-1;if(!mt(p))return null;let h=d+2;while(h<l){let x=r.charCodeAt(h);if(!_e(x)&&x!==pt&&x!==58&&x!==45)break;h++}let g=r.slice(d+1,h),b=r.charCodeAt(h);if(b>32&&b!==me&&b!==Q)return null;let v=0,O=0,R=h;for(;R<l;R++){let x=r.charCodeAt(R);if(O!==0){if(x===it)R++;else if(x===O)O=0;continue}if(x===le||x===ue||x===Ne)O=x;else if(x===H)v++;else if(x===X&&v>0)v--;else if(x===me&&v===0)break}if(R>=l)return null;let S=R-1;while(S>d&&r.charCodeAt(S)<=32)S--;if(r.charCodeAt(S)===Q)return 0;return r.indexOf(`</${g}`,R+1)===-1?null:1}function Qr(d,p){a+=9,C();let h=F();C();let g=ht();C();let b="";if(E("extends")){a+=7,C();let x=a,P=0;while(a<l){if(T())continue;let j=r.charCodeAt(a);if(j===be)P++;else if(j===me&&!J())P--;else if(j===H&&P===0)break;a++}b=m(x,a)}C();let v=a<l&&r.charCodeAt(a)===H?Yr():"{}",O=Zo(v),R=`${p?"export ":""}declare interface ${h}${g}${b?` extends ${b}`:""} ${O}`,S=Xe(d);return{kind:"interface",name:h,text:R,isExported:p,extends:b||void 0,generics:g||void 0,leadingComments:S,start:d,end:a}}function en(d,p){a+=4,C();let h=F();C();let g=ht();if(C(),a<l&&r.charCodeAt(a)===ve)a++;C();let b=a,v=0;while(a<l){if(T())continue;let x=r.charCodeAt(a);if(x===ae||x===H||x===xe||x===be)v++;else if(x===$e||x===X||x===Pe||x===me&&!J())v--;else if(v===0&&x===ie)break;if(v===0&&(z()||re()))break;a++}let O=m(b,a);if(a<l&&r.charCodeAt(a)===ie)a++;let R=`${p?"export ":""}type ${h}${g} = ${O}`,S=Xe(d);return{kind:"type",name:h,text:R,isExported:p,generics:g||void 0,leadingComments:S,start:d,end:a}}function jt(d,p,h){a+=4,C();let g=F();C();let b=a;if(a<l&&r.charCodeAt(a)===H)Z(H,X);let v=m(d,a),O=Xe(d);return{kind:"enum",name:g,text:v,isExported:p,modifiers:h?["const"]:void 0,leadingComments:O,start:d,end:a}}function Tt(d,p,h,g=!1){a+=5,C();let b=F()||"AnonymousClass";C();let v=ht();C();let O="";if(E("extends")){a+=7,C();let j=a,G=0;while(a<l){if(T())continue;let I=r.charCodeAt(a);if(I===be)G++;else if(I===me&&!J())G--;else if(G===0&&(I===H||E("implements")))break;a++}O=m(j,a)}let R;if(E("implements")){a+=10,C();let j=a,G=0;while(a<l){if(T())continue;let M=r.charCodeAt(a);if(M===be)G++;else if(M===me&&!J())G--;else if(G===0&&M===H)break;a++}let I=m(j,a);if(I)R=I.split(",").map((M)=>M.trim())}C();let S=tn(),x=`${p?g?"export default ":"export declare ":"declare "}${h?"abstract ":""}class ${b}${v}${O?` extends ${O}`:""}${R&&R.length>0?` implements ${R.join(", ")}`:""} ${S}`,P=Xe(d);return{kind:"class",name:b,text:x,isExported:p,isDefault:g,extends:O||void 0,implements:R,generics:v||void 0,modifiers:h?["abstract"]:void 0,leadingComments:P,start:d,end:a}}function tn(){if(a>=l||r.charCodeAt(a)!==H)return"{}";a++;let d=[];while(a<l){if(C(),a>=l)break;if(r.charCodeAt(a)===X){a++;break}if(r.charCodeAt(a)===ie){a++;continue}if(E("static")&&nn("static")===H){a+=6,C(),Z(H,X);continue}let p=!1,h=!1,g=!1,b=!1,v=!1,O=!1,R=!1,S=!1,x=!0;while(x){C();let G=a,I=F();if(a=G,I){let M=nn(I);if(M===ae||M===be||M===jr||M===33||M===lt||M===ve||M===ie||M===X)break}if(E("private")){p=!0,a+=7;continue}if(E("protected")){h=!0,a+=9;continue}if(E("public")){a+=6;continue}if(E("static")){g=!0,a+=6;continue}if(E("abstract")){b=!0,a+=8;continue}if(E("readonly")){v=!0,a+=8;continue}if(E("override")){O=!0,a+=8;continue}if(E("accessor")){R=!0,a+=8;continue}if(E("async")){S=!0,a+=5;continue}if(E("declare")){a+=7;continue}break}if(C(),a>=l||r.charCodeAt(a)===X)break;if(r.charCodeAt(a)===Lo)p=!0;let P=p?[]:d,j=" ";if(h)j+="protected ";if(g)j+="static ";if(b)j+="abstract ";if(v)j+="readonly ";if(E("constructor")){a+=11,C();let G=xt();if(C(),rf(G,P),a<l&&r.charCodeAt(a)===H)Z(H,X);else if(a<l&&r.charCodeAt(a)===ie)a++;let I=Gt(G);P.push(` constructor${I};`)}else if(E("get"))if(a+=3,C(),a<l&&ts(r.charCodeAt(a))){let G=rn();if(G.startsWith("#")){if(C(),a<l&&r.charCodeAt(a)===ae)xt();if(C(),hi(),C(),a<l&&r.charCodeAt(a)===H)Z(H,X);else if(a<l&&r.charCodeAt(a)===ie)a++;continue}C(),xt(),C();let I=hi()||"unknown";if(C(),a<l&&r.charCodeAt(a)===H)Z(H,X);else if(a<l&&r.charCodeAt(a)===ie)a++;P.push(`${j}get ${G}(): ${I};`)}else rs("get",j,g,v,S,P);else if(E("set"))if(a+=3,C(),a<l&&ts(r.charCodeAt(a))){let G=rn();if(G.startsWith("#")){if(C(),a<l&&r.charCodeAt(a)===ae)xt();if(C(),a<l&&r.charCodeAt(a)===H)Z(H,X);else if(a<l&&r.charCodeAt(a)===ie)a++;continue}C();let I=xt();if(C(),a<l&&r.charCodeAt(a)===H)Z(H,X);else if(a<l&&r.charCodeAt(a)===ie)a++;let M=Gt(I);P.push(`${j}set ${G}${M};`)}else rs("set",j,g,v,S,P);else{let G=r.charCodeAt(a)===Ae;if(G)a++,C();let I=rn();if(!I){is();continue}ns(I,j,g,v,G,b,S,P)}}return`{
|
|
157
|
-
${d.join(`
|
|
158
|
-
`)}
|
|
159
|
-
}`}function ts(d){return mt(d)||d===xe||d===Lo||d===le||d===ue}function rn(){if(a>=l)return"";let d=r.charCodeAt(a);if(d===xe){let p=a;return Z(xe,Pe),r.slice(p,a)}if(d===Lo)return a++,`#${F()}`;if(d===le||d===ue){let p=a;return k(d),r.slice(p,a)}return F()}function nn(d){let p=a;a+=d.length,C();let h=a<l?r.charCodeAt(a):0;return a=p,h}function is(){let d=0;while(a<l){if(T())continue;let p=r.charCodeAt(a);if(p===H||p===ae)d++;else if(p===X||p===$e){if(d===0)return;d--}else if(p===ie&&d===0){a++;return}if(d===0&&ce())return;a++}}function rs(d,p,h,g,b,v){ns(d,p,h,g,!1,!1,b,v)}function ns(d,p,h,g,b,v,O,R){if(C(),a>=l)return;let S=r.charCodeAt(a),x=!1;if(S===jr)x=!0,a++,C();if(a<l&&r.charCodeAt(a)===33)a++,C();let P=a<l?r.charCodeAt(a):0;if(P===ae||P===be){let j=P===be?ht():"";C();let G=xt();C();let I=hi(),M=I.length>0;if(!I)if(O&&b)I="AsyncGenerator<unknown, void, unknown>";else if(b)I="Generator<unknown, void, unknown>";else if(O)I="Promise<void>";else I="void";if(C(),a<l&&r.charCodeAt(a)===H){let He=a+1;if(Z(H,X),!M&&!b)I=fi(r.slice(He,a-1),O,G)}else if(a<l&&r.charCodeAt(a)===ie)a++;let _=Gt(G),V=x?"?":"";R.push(`${p}${d}${V}${j}${_}: ${I};`)}else if(P===lt||P===ve||P===ie||P===X||P===Ee||P===Te){let j="";if(P===lt){a++,C();let M=a,_=0;while(a<l){if(T())continue;let V=r.charCodeAt(a);if(V===ae||V===H||V===xe||V===be)_++;else if(V===$e||V===X||V===Pe||V===me&&!J()){if(_===0)break;_--}else if(_===0&&(V===ie||V===ut))break;else if(_===0&&V===ve&&!te())break;if(_===0&&ce())break;a++}j=m(M,a)}let G="";if(a<l&&r.charCodeAt(a)===ve)if(s&&j){a++;let M=0;while(a<l){if(T())continue;let _=r.charCodeAt(a);if(_===ae||_===H||_===xe)M++;else if(_===$e||_===X||_===Pe){if(M===0&&_===X)break;M--}else if(M===0&&_===ie)break;if(M===0&&ce())break;a++}}else{a++,C();let M=a,_=0;while(a<l){if(T())continue;let V=r.charCodeAt(a);if(V===ae||V===H||V===xe)_++;else if(V===$e||V===X||V===Pe){if(_===0&&V===X)break;_--}else if(_===0&&V===ie)break;if(_===0&&ce())break;a++}G=m(M,a)}if(a<l&&r.charCodeAt(a)===ie)a++;if(!j)if(G){let M=Li(G);if(M)j=M;else j=G.endsWith("as const")||h&&g?Xr(G):Zr(G)}else j="unknown";let I=x?"?":"";R.push(`${p}${d}${I}: ${j};`)}else is()}function tf(d){let p=0;for(let h=0;h<d.length;h++){let g=d.charCodeAt(h);if(g===ae||g===H||g===xe||g===be)p++;else if(g===$e||g===X||g===Pe||g===me&&d.charCodeAt(h-1)!==ve)p--;else if(g===ve&&p===0&&d.charCodeAt(h+1)!==me&&d.charCodeAt(h+1)!==ve)return!0}return!1}function rf(d,p){let h=d.slice(1,-1).trim();if(!h)return;let g=[],b=0,v=0,O=!1,R=0;for(let S=0;S<=h.length;S++){if(S===h.length){g.push(Fi(h.slice(b).trim()));break}let x=h.charCodeAt(S);if(O){if(x===it){S++;continue}if(x===R)O=!1;continue}if(x===Q&&S+1<h.length){let P=h.charCodeAt(S+1);if(P===Ae){S+=2;while(S+1<h.length&&!(h.charCodeAt(S)===Ae&&h.charCodeAt(S+1)===Q))S++;S++;continue}if(P===Q){while(S<h.length&&h.charCodeAt(S)!==10)S++;continue}}if(x===le||x===ue||x===Ne){O=!0,R=x;continue}if(x===ae||x===H||x===xe||x===be)v++;else if(x===$e||x===X||x===Pe||x===me&&!(S>0&&h.charCodeAt(S-1)===ve))v--;else if(x===ut&&v===0)g.push(Fi(h.slice(b,S).trim())),b=S+1}for(let S of g){let x=S.startsWith("public ")||S.startsWith("public\t"),P=S.startsWith("protected ")||S.startsWith("protected\t"),j=S.startsWith("private ")||S.startsWith("private\t"),G=S.includes("readonly ");if(!x&&!P&&!j&&!G)continue;if(j)continue;let I=S,M=[];if(x){let ze=6;while(ze<I.length&&je(I.charCodeAt(ze)))ze++;I=I.slice(ze),M.push("public")}if(P){let ze=9;while(ze<I.length&&je(I.charCodeAt(ze)))ze++;I=I.slice(ze),M.push("protected")}if(G){let ze=I.indexOf("readonly ");if(ze!==-1){let Vt=ze+8;while(Vt<I.length&&je(I.charCodeAt(Vt)))Vt++;I=I.slice(0,ze)+I.slice(Vt)}M.push("readonly")}let _=M.length>0?`${M.join(" ")} `:"",V=Xo(I),He=I.search(/[?:=]/);if(He!==-1&&I.charCodeAt(He)!==63&&tf(I))V=V.replace(/^([\w$]+)\?:/,"$1:");p.push(` ${_}${V};`)}}function on(d=" "){if(a>=l||r.charCodeAt(a)!==H)return"{}";a++;let p=[];while(a<l){if(C(),a>=l)break;if(r.charCodeAt(a)===X){a++;break}if(r.charCodeAt(a)===ie){a++;continue}let h=!1;if(E("export"))h=!0,a+=6,C();if(E("declare"))a+=7,C();let g=h?"export ":"";if(E("function")||E("async")&&nf("async","function")){let b=!1;if(E("async"))b=!0,a+=5,C();if(a+=8,C(),a<l&&r.charCodeAt(a)===Ae)a++,C();let v=F();C();let O=ht();C();let R=xt();C();let S=hi();if(!S)S=b?"Promise<void>":"void";if(C(),a<l&&r.charCodeAt(a)===H)Z(H,X);else if(a<l&&r.charCodeAt(a)===ie)a++;let x=Gt(R);p.push(`${d}${g}function ${v}${O}${x}: ${S};`)}else if(E("const")||E("let")||E("var")){let b=E("const")?"const":E("let")?"let":"var";a+=b.length,C();let v=F();if(!v){ne(!0);continue}C();let O="";if(a<l&&r.charCodeAt(a)===lt){a++,C();let S=a,x=0;while(a<l){if(T())continue;let P=r.charCodeAt(a);if(P===ae||P===H||P===xe||P===be)x++;else if(P===X&&x===0)break;else if(P===$e||P===X||P===Pe||P===me&&!J())x--;else if(x===0&&(P===ie||P===ut))break;else if(x===0&&P===ve&&!te())break;if(x===0&&z())break;a++}O=m(S,a)}let R="";if(a<l&&r.charCodeAt(a)===ve){a++,C();let S=a,x=0;while(a<l){if(T())continue;let P=r.charCodeAt(a);if(P===ae||P===H||P===xe||P===be)x++;else if(P===X&&x===0)break;else if(P===$e||P===X||P===Pe||P===me&&!J())x--;else if(x===0&&(P===ie||P===ut))break;if(x===0&&z())break;a++}R=m(S,a)}if(a<l&&r.charCodeAt(a)===ie)a++;if(!O&&R){let S=Li(R);if(S)O=S;else if(b==="const")O=Xr(R);else O=Zr(R)}if(!O)O="unknown";p.push(`${d}${g}${b} ${v}: ${O};`)}else if(E("interface")){a+=9,C();let b=F();C();let v=ht();C();let O="";if(E("extends")){a+=7,C();let S=a,x=0;while(a<l){if(T())continue;let P=r.charCodeAt(a);if(P===be)x++;else if(P===me&&!J())x--;else if(P===H&&x===0)break;a++}O=m(S,a)}let R=Zo(Yr());p.push(`${d}${g}interface ${b}${v}${O?` extends ${O}`:""} ${R}`)}else if(E("type")){a+=4,C();let b=F();C();let v=ht();if(C(),a<l&&r.charCodeAt(a)===ve){a++,C();let O=a,R=0;while(a<l){if(T())continue;let x=r.charCodeAt(a);if(x===ae||x===H||x===xe||x===be)R++;else if(x===X&&R===0)break;else if(x===$e||x===X||x===Pe||x===me&&!J())R--;else if(R===0&&x===ie)break;if(R===0&&z())break;a++}let S=m(O,a);if(a<l&&r.charCodeAt(a)===ie)a++;p.push(`${d}${g}type ${b}${v} = ${S}`)}}else if(E("class")){a+=5,C();let b=F();C();let v=ht();C();let O=a,R=0;while(a<l){if(T())continue;let j=r.charCodeAt(a);if(j===be)R++;else if(j===me&&!J())R--;else if(j===H&&R===0)break;a++}let S=m(O,a),x=S?` ${S}`:"",P=tn();p.push(`${d}${g}class ${b}${v}${x} ${P}`)}else if(E("enum")){a+=4,C();let b=F();C();let v=Yr();p.push(`${d}${g}enum ${b} ${v}`)}else if(E("namespace")||E("module")){let b=E("namespace")?"namespace":"module";a+=b.length,C();let v=F();C();let O=on(d);p.push(`${d}${g}${b} ${v} ${O}`)}else if(E("abstract"))if(a+=8,C(),E("class")){a+=5,C();let b=F();C();let v=ht();C();let O=a,R=0;while(a<l){if(T())continue;let j=r.charCodeAt(a);if(j===be)R++;else if(j===me&&!J())R--;else if(j===H&&R===0)break;a++}let S=m(O,a),x=S?` ${S}`:"",P=tn();p.push(`${d}${g}abstract class ${b}${v}${x} ${P}`)}else ne(!0);else if(h&&E("default")){a+=7,C();let b=a;ne(!0);let v=m(b,a);if(v.charCodeAt(v.length-1)===ie)v=v.slice(0,-1);if(v)p.push(`${d}export default ${v};`)}else if(!h&&(r.charCodeAt(a)===le||r.charCodeAt(a)===ue||r.charCodeAt(a)===Ne))ne(!0);else ne(!0)}if(p.length===0)return"{}";return`{
|
|
160
|
-
${p.join(`
|
|
161
|
-
`)}
|
|
162
|
-
}`}function nf(d,p){let h=a+d.length;while(h<l&&je(r.charCodeAt(h)))h++;for(let g=0;g<p.length;g++)if(h+g>=l||r.charCodeAt(h+g)!==p.charCodeAt(g))return!1;return h+p.length>=l||!_e(r.charCodeAt(h+p.length))}function _t(d,p,h){a+=h.length,C();let g="",b=r.charCodeAt(a);if(b===le||b===ue){let x=a;k(b),g=r.slice(x,a)}else{g=F();while(a<l&&r.charCodeAt(a)===pt)a++,g+=`.${F()}`}C();let v=a<l&&r.charCodeAt(a)===H?on():"{}",O=`${p?"export ":""}declare ${h} ${g} ${v}`,R=Xe(d),S=g.startsWith("'")||g.startsWith('"');return{kind:"module",name:g,text:O,isExported:p,source:S?g.slice(1,-1):void 0,leadingComments:R,start:d,end:a}}function os(d,p){ne();let h=m(p,a);if(h.charCodeAt(h.length-1)===ie)h=h.slice(0,-1).trimEnd();if(!h)return;let g=mt(h.charCodeAt(0));for(let x=1;g&&x<h.length;x++)g=_e(h.charCodeAt(x));let b=Xe(d);if(g){c.push({kind:"export",name:"default",text:`export default ${h};`,isExported:!0,isTypeOnly:!1,leadingComments:b,start:d,end:a});return}let v="__dtsx_default_export__",O=1;while(r.includes(v))v=`__dtsx_default_export_${O++}__`;let R=Li(h)||Ie(h,!1),S=R==="unknown"&&Ud(h)?`typeof ${h}`:R;c.push({kind:"variable",name:v,text:`declare const ${v}: ${S};`,isExported:!1,typeAnnotation:S,modifiers:["const"],start:d,end:a}),c.push({kind:"export",name:"default",text:`export default ${v};`,isExported:!0,isTypeOnly:!1,leadingComments:b,start:d,end:a})}while(a<l){if(C(),a>=l)break;let d=a,p=r.charCodeAt(a);if(p===105&&E("import"))c.push(qc(d));else if(p===101&&E("export")){a+=6,C();let h=r.charCodeAt(a);if(h===100&&E("default")){a+=7,C();let g=a,b=r.charCodeAt(a);if(b===102&&E("function")){let v=At(d,!0,!1,!0);if(v)c.push(v)}else if(b===97&&E("async")&&nn("async")!==ie)if(a+=5,C(),E("function")){let v=At(d,!0,!0,!0);if(v)c.push(v)}else os(d,g);else if(b===99&&E("class")){let v=Tt(d,!0,!1,!0);c.push(v)}else if(b===97&&E("abstract")){if(a+=8,C(),E("class")){let v=Tt(d,!0,!0,!0);c.push(v)}}else os(d,g)}else if(h===116&&E("type")){let g=a;if(a+=4,C(),a<l&&r.charCodeAt(a)===H){Jo();let b=m(d,a),v=Xe(d);c.push({kind:"export",name:"",text:b,isExported:!0,isTypeOnly:!0,source:Ni(b),leadingComments:v,start:d,end:a})}else if(a<l&&r.charCodeAt(a)===Ae){qo();let b=m(d,a);c.push({kind:"export",name:"",text:b,isExported:!0,isTypeOnly:!0,source:Ni(b),start:d,end:a})}else{a=g;let b=en(d,!0);c.push(b)}}else if(h===105&&E("interface")){let g=Qr(d,!0);c.push(g)}else if(h===102&&E("function")){let g=At(d,!0,!1,!1);if(g)c.push(g)}else if(h===97&&E("async"))if(a+=5,C(),E("function")){let g=At(d,!0,!0,!1);if(g)c.push(g)}else ne();else if(h===99)if(E("class")){let g=Tt(d,!0,!1);c.push(g)}else if(E("const")){let g=a;if(a+=5,C(),E("enum")){a=g+5,C();let b=jt(d,!0,!0);c.push(b)}else{a=g;let b=It(d,"const",!0);for(let v=0;v<b.length;v++)c.push(b[v])}}else ne();else if(h===97&&E("abstract")){if(a+=8,C(),E("class")){let g=Tt(d,!0,!0);c.push(g)}}else if(h===108&&E("let")){let g=It(d,"let",!0);for(let b=0;b<g.length;b++)c.push(g[b])}else if(h===118&&E("var")){let g=It(d,"var",!0);for(let b=0;b<g.length;b++)c.push(g[b])}else if(h===101&&E("enum")){let g=jt(d,!0,!1);c.push(g)}else if(h===100&&E("declare"))a+=7,C(),ss(d,!0);else if(h===110&&E("namespace")&&K(9)){let g=_t(d,!0,"namespace");c.push(g)}else if(h===109&&E("module")&&K(6)){let g=_t(d,!0,"module");c.push(g)}else if(h===H){Jo();let g=m(d,a),b=g.includes("export type"),v=Xe(d);c.push({kind:"export",name:"",text:g,isExported:!0,isTypeOnly:b,source:Ni(g),leadingComments:v,start:d,end:a})}else if(h===Ae){qo();let g=m(d,a),b=Xe(d);c.push({kind:"export",name:"",text:g,isExported:!0,isTypeOnly:!1,source:Ni(g),leadingComments:b,start:d,end:a})}else{ne();let g=m(d,a);if(g)c.push({kind:"export",name:"",text:g,isExported:!0,start:d,end:a})}}else if(p===100&&E("declare"))a+=7,C(),ss(d,!1);else if(p===105&&E("interface")){let h=Qr(d,!1);f.set(h.name,h)}else if(p===116&&E("type")){let h=en(d,!1);f.set(h.name,h),c.push(h)}else if(p===102&&E("function")){let h=At(d,!1,!1,!1);if(h)f.set(h.name,h);else ne()}else if(p===97)if(E("async")){let h=a;if(a+=5,C(),E("function")){let g=At(d,!1,!0,!1);if(g)f.set(g.name,g);else a=h,ne()}else a=h,ne()}else if(E("abstract"))if(a+=8,C(),E("class")){let h=Tt(d,!1,!1);f.set(h.name,h),c.push(h)}else ne();else a++,ne();else if(p===99)if(E("class")){let h=Tt(d,!1,!1);f.set(h.name,h),c.push(h)}else if(E("const")){let h=a;if(a+=5,C(),E("enum")){a=h+5,C();let g=jt(d,!1,!0);f.set(g.name,g),c.push(g)}else{a=h;let g=It(d,"const",!1);for(let b=0;b<g.length;b++)f.set(g[b].name,g[b])}}else a++,ne();else if(p===101&&E("enum")){let h=jt(d,!1,!1);f.set(h.name,h),c.push(h)}else if(p===108&&E("let")||p===118&&E("var")){let h=E("let")?"let":"var",g=It(d,h,!1);for(let b=0;b<g.length;b++)f.set(g[b].name,g[b])}else if(p===109&&E("module")&&K(6)){let h=_t(d,!1,"module");c.push(h)}else if(p===110&&E("namespace")&&K(9)){let h=_t(d,!1,"namespace");c.push(h)}else{let h=r.charCodeAt(a);if(h===ie)a++;else if(h===le||h===ue){if(k(h),a<l&&r.charCodeAt(a)===ie)a++}else if(h===Ne){if(W(),a<l&&r.charCodeAt(a)===ie)a++}else if(h===_d){if(a++,F(),C(),a<l&&r.charCodeAt(a)===pt)a++,F(),C();if(a<l&&r.charCodeAt(a)===ae)Z(ae,$e)}else a++,ne()}}if(f.size>0)Hd(c,f);if(u.size>0){let d=new Map;for(let h of c)if(h.kind==="function")d.set(h.name,(d.get(h.name)||0)+1);let p=new Set;for(let[h,g]of d)if(g>1)p.add(h);if(p.size>0){let h=new Set;for(let g of p)for(let b=c.length-1;b>=0;b--)if(c[b].kind==="function"&&c[b].name===g&&u.has(b)){h.add(b);break}if(h.size>0){let g=[...h].sort((b,v)=>v-b);for(let b of g)c.splice(b,1)}}}return c;function ss(d,p){if(E("function")){let h=At(d,p,!1,!1);if(h)c.push(h)}else if(E("async")){if(a+=5,C(),E("function")){let h=At(d,p,!0,!1);if(h)c.push(h)}}else if(E("class")){let h=Tt(d,p,!1);c.push(h)}else if(E("abstract")){if(a+=8,C(),E("class")){let h=Tt(d,p,!0);c.push(h)}}else if(E("interface")){let h=Qr(d,p);c.push(h)}else if(E("type")){let h=en(d,p);c.push(h)}else if(E("enum")){let h=jt(d,p,!1);c.push(h)}else if(E("const")){let h=a;if(a+=5,C(),E("enum")){a=h+5,C();let g=jt(d,p,!0);c.push(g)}else if(p){a=h;let g=It(d,"const",!0);for(let b=0;b<g.length;b++)c.push(g[b])}else ne()}else if(E("let")||E("var"))if(p){let h=E("let")?"let":"var",g=It(d,h,!0);for(let b=0;b<g.length;b++)c.push(g[b])}else ne();else if(E("module")){let h=_t(d,p,"module");c.push(h)}else if(E("namespace")){let h=_t(d,p,"namespace");c.push(h)}else if(E("global")){a+=6,C();let h=`declare global ${a<l&&r.charCodeAt(a)===H?on():"{}"}`,g=Xe(d);c.push({kind:"module",name:"global",text:h,isExported:!1,leadingComments:g,start:d,end:a})}else ne()}}function jl(e,t){let i=0,n=e.length;while(i<n){let r=e.charCodeAt(i);if(r>=65&&r<=90||r>=97&&r<=122||r===95||r===36||r>127){let o=i;i++;while(i<n){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 _l(e,t){let i=0;while(i<e.length){let n=e.charCodeAt(i);if(n===le||n===ue||n===Ne){let u=n;i++;while(i<e.length)if(e.charCodeAt(i)===it)i+=2;else if(e.charCodeAt(i++)===u)break;continue}if(n===Q&&e.charCodeAt(i+1)===Q){i+=2;while(i<e.length&&e.charCodeAt(i)!==Ee&&e.charCodeAt(i)!==Te)i++;continue}if(n===Q&&e.charCodeAt(i+1)===Ae){let u=e.indexOf("*/",i+2);i=u===-1?e.length:u+2;continue}if(!mt(n)){i++;continue}let r=i++;while(i<e.length&&_e(e.charCodeAt(i)))i++;let o=r-1,s=i;while(o>=0&&je(e.charCodeAt(o)))o--;while(s<e.length&&je(e.charCodeAt(s)))s++;let l=o>=0?e.charCodeAt(o):0,c=s<e.length?e.charCodeAt(s):0,f=r>=3&&e.slice(r-3,r)==="...";if(c===lt||l===pt&&!f)continue;if(c===ae&&(l===H||l===ut))continue;t.add(e.slice(r,i))}}function Hd(e,t){let i=new Set,n=new Set;for(let s of e)n.add(s.name);let r=new Set,o=[];for(let s=0;s<e.length;s++){let l=e[s];if(l.kind!=="import"){if(o.push(l.text),jl(l.text,r),typeof l.value==="string")_l(l.value,r)}}for(;;){let s=[];for(let[f,u]of t){if(i.has(f))continue;if(r.has(f)){if(!n.has(f))s.push(u),n.add(f);i.add(f)}}if(s.length===0)break;s.sort((f,u)=>(f.start??1/0)-(u.start??1/0));let l=[],c=0;for(let f=0;f<e.length;f++){let u=e[f].start??1/0;while(c<s.length&&(s[c].start??1/0)<=u)l.push(s[c++]);l.push(e[f])}while(c<s.length)l.push(s[c++]);e.length=0;for(let f=0;f<l.length;f++)e.push(l[f]);for(let f of s)if(f.kind!=="import"){if(o.push(f.text),jl(f.text,r),typeof f.value==="string")_l(f.value,r)}}}var ke=32,Me=9,Ee=10,Te=13,Q=47,Ae=42,le=39,ue=34,Ne=96,it=92,H=123,X=125,ae=40,$e=41,xe=91,Pe=93,be=60,me=62,ie=59,lt=58,ve=61,ut=44,pt=46,jr=63,Lo=35,_d=64,Vd=36,Wo;var Hl=de(()=>{fn();Fo();Wo=["public","protected","private","readonly","override"]});function Jl(e,t,i=!0,n=!1){if(yl(t))e=bl(e);else if(vl(t))e=Sl(e);let r=yi(e),o=`${t}:${i?1:0}:${n?1:0}`,s=ui.get(o);if(s&&s.contentHash===r)return s.lastAccess=++zl,s.declarations;let l=n?Vl(e,t,i):Ul(e,t,i);if(ui.set(o,{declarations:l,contentHash:r,lastAccess:++zl}),ui.size>zd){let c=Math.max(1,Math.ceil(ui.size*0.1)),f=[];for(let[u,a]of ui)f.push([u,a.lastAccess]);f.sort((u,a)=>u[1]-a[1]);for(let u=0;u<c&&u<f.length;u++)ui.delete(f[u][0])}return l}var zd=100,zl=0,ui;var ql=de(()=>{vo();$l();Hl();En();ui=new Map});function Yl(e,t,i=!0,n=!1){return Jl(e,t,i,n)}var Zl=de(()=>{ql()});async function Jd(){if(Vr!==null)return Vr;try{return Mt=await import("prettier"),Vr=!0,!0}catch{return Vr=!1,!1}}async function qd(e,t){if(!Mt)return null;try{if(t&&Mt.resolveConfig){let i=await Mt.resolveConfig(t);if(i)return i}if(e&&Mt.resolveConfig){let i=await Mt.resolveConfig(e);if(i)return i}return null}catch{return null}}async function Yd(e,t){if(!Mt)throw Error("Prettier is not available");let i={...t,parser:t.parser||"typescript"};return Mt.format(e,i)}function Zd(e,t={}){let{indentSize:i=2,useTabs:n=!1,maxLineWidth:r=100,trailingNewline:o=!0,normalizeWhitespace:s=!0,sortImports:l=!0,groupImports:c=!0}=t,f=e,u=n?"\t":" ".repeat(i);if(f.indexOf(`\r
|
|
163
|
-
`)!==-1)f=f.replace(/\r\n/g,`
|
|
164
|
-
`);if(s){if(/[ \t]\n/.test(f)||/[ \t]$/.test(f))f=f.replace(/[ \t]+$/gm,"");if(f.indexOf(`
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
`)!==-1)f=f.replace(/\n{3,}/g,`
|
|
168
|
-
|
|
169
|
-
`);f=Xd(f,u)}if(l||c)f=Qd(f,{sort:l,group:c});if(r>0)f=tp(f,r,u);if(o&&!f.endsWith(`
|
|
170
|
-
`))f+=`
|
|
171
|
-
`;return f}function Xd(e,t){let i=e.split(`
|
|
172
|
-
`),n=[];for(let r of i){let o=r.match(/^(\s*)(.*)$/);if(!o){n.push(r);continue}let[,s,l]=o;if(!l){n.push("");continue}let c=s.replace(/\t/g," ").length,f=Math.floor(c/2);n.push(t.repeat(f)+l)}return n.join(`
|
|
173
|
-
`)}function Qd(e,t){let i=e.split(`
|
|
174
|
-
`),n=[],r=[],o=!1,s=0;for(let c=0;c<i.length;c++){let f=i[c],u=f.match(/^(import\s+(?:type\s+)?.*from\s+['"])([^'"]+)(['"].*)$/);if(u){o=!0,s=c;let a=u[1];n.push({line:f,source:u[2],isType:a.startsWith("import type ")||a.startsWith("import type\t")})}else if(o&&f.trim()==="")continue;else{if(o)o=!1;r.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 ep(c.source,f.source)});let l;if(t.group){let c=[],f=[],u=[],a=[],m=[];for(let y=0;y<n.length;y++){let w=n[y],C=w.source;if(C.charCodeAt(0)===46)m.push(w);else if(C.startsWith("node:"))c.push(w);else if(C.charCodeAt(0)===64)a.push(w);else if(C.includes("/"))u.push(w);else f.push(w)}l=[...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),...a.length>0&&(c.length>0||f.length>0||u.length>0)?[""]:[],...a.map((y)=>y.line),...m.length>0?[""]:[],...m.map((y)=>y.line)]}else l=n.map((c)=>c.line);return[...l,"",...r].join(`
|
|
175
|
-
`)}function ep(e,t){let i=e.startsWith("node:"),n=t.startsWith("node:");if(i!==n)return i?-1:1;let r=e.startsWith("."),o=t.startsWith(".");if(r!==o)return r?1:-1;return e.localeCompare(t)}function tp(e,t,i){let n=e.split(`
|
|
176
|
-
`),r=[];for(let o of n){if(o.length<=t){r.push(o);continue}if(o.trimStart().startsWith("import ")){r.push(o);continue}let s=o.match(/^(\s*)/)?.[1]||"",l=s+i,c=rp(o,s,l);if(c){r.push(...c);continue}if(o.includes("{")&&o.includes("}")){let f=np(o,t,s,l);r.push(...f);continue}if(o.includes(" | ")){let f=op(o,t,s,l);r.push(...f);continue}r.push(o)}return r.join(`
|
|
177
|
-
`)}function rp(e,t,i){let n=e.match(ip);if(!n)return null;let[,r,o,s,l]=n,c=s.split(",").map((a)=>a.trim()).filter(Boolean);if(c.length<=1)return[e];let f=`${t}${r}${o??""} {`,u=l?`${t}} ${l};`:`${t}};`;return[f,...c.map((a)=>`${i}${a},`),u]}function np(e,t,i,n){let r=e.match(/^(\s*)(.*?)(\{)(.+)(\}.*)$/);if(!r)return[e];let[,,o,s,l,c]=r,f=l.split(/;\s*|,\s*/).filter((u)=>u.trim());if(f.length<=1)return[e];return[`${i}${o}${s}`,...f.map((u)=>`${n}${u.trim()};`),`${i}${c.trim()}`]}function op(e,t,i,n){let r=e.match(/^(\s*)(.*?=\s*)(.+)$/);if(!r)return[e];let[,,o,s]=r,l=s.split(/\s*\|\s*/).filter((c)=>c.trim());if(l.length<=2)return[e];return[`${i}${o}`,...l.map((c,f)=>`${n}${f>0?"| ":" "}${c.trim()}`)]}async function Xl(e,t={},i){let n=[];if(t.usePrettier!==!1){if(await Jd())try{let r={...await qd(t.prettierConfigPath,i),...t.prettierOptions,parser:"typescript"};return{content:await Yd(e,r),usedPrettier:!0}}catch(r){n.push(`Prettier formatting failed: ${r}. Using built-in formatter.`)}else if(t.usePrettier===!0)n.push("Prettier requested but not available. Using built-in formatter.")}return{content:Zd(e,t.builtIn),usedPrettier:!1,warnings:n.length>0?n:void 0}}var Vr=null,Mt=null,ip;var Ql=de(()=>{ip=/^\s*(export|import)(\s+type)?\s*\{([^{}]*)\}\s*(from\s*(?:'[^']*'|"[^"]*")(?:\s*(?:with|assert)\s*\{[^{}]*\})?)?\s*;?\s*$/});class Ur{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 n=await i.onStart(t);if(n)t=n}return this.config=t,t}async runOnBeforeFile(e,t){let i=t;for(let n of this.plugins)if(n.onBeforeFile){let r={filePath:e,sourceCode:t,content:i,config:this.config,log:this.createLogger(n.name)},o=await n.onBeforeFile(r);if(typeof o==="string")i=o}return i}async runOnDeclarations(e,t,i){let n=i;for(let r of this.plugins)if(r.onDeclarations){let o={filePath:e,sourceCode:t,declarations:n,config:this.config,log:this.createLogger(r.name)},s=await r.onDeclarations(o);if(s)n=s}return n}async runOnAfterFile(e,t,i){let n=i;for(let r of this.plugins)if(r.onAfterFile){let o={filePath:e,sourceCode:t,content:n,config:this.config,log:this.createLogger(r.name)},s=await r.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,i){for(let n of this.plugins)if(n.onError){let r={filePath:t,sourceCode:i,config:this.config,log:this.createLogger(n.name)};await n.onError(e,r)}}}function sp(e){return e}var T0,O0;var ec=de(()=>{T0=new Ur;O0=sp({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 rc(e,t={}){let{lineEnding:i="lf",trailingNewline:n=!0,maxBlankLines:r=1,trimTrailingWhitespace:o=!0,normalizeIndentation:s=!0,indent:l={style:"spaces",size:2},declarationOrder:c,importGrouping:f,preserveComments:u=!0,insertFinalNewline:a=!0}=t,m=e;if(m=cp(m,i),f?.enabled!==!1)m=pp(m,f||{});if(c)m=mp(m,c);if(o)m=fp(m);if(m=up(m,r),s)m=dp(m,l);if(n||a)m=hp(m);return m}function cp(e,t){let i=e;if(e.indexOf("\r")!==-1){if(e.indexOf(`\r
|
|
178
|
-
`)!==-1)i=i.replace(/\r\n/g,`
|
|
179
|
-
`);if(i.indexOf("\r")!==-1)i=i.replace(/\r/g,`
|
|
180
|
-
`)}if(t==="crlf")i=i.replace(/\n/g,`\r
|
|
181
|
-
`);return i}function fp(e){return e.split(`
|
|
182
|
-
`).map((t)=>t.replace(/[\t ]+$/,"")).join(`
|
|
183
|
-
`)}function up(e,t){let i=new RegExp(`\\n{${t+2},}`,"g");return e.replace(i,`
|
|
184
|
-
`.repeat(t+1))}function hp(e){return`${e.replace(/\s+$/,"")}
|
|
185
|
-
`}function dp(e,t){let{style:i="spaces",size:n=2}=t,r=i==="tabs"?"\t":" ".repeat(n),o=e.split(`
|
|
186
|
-
`),s=[];for(let l of o){let c=l.match(/^([\t ]*)(.*)$/);if(!c){s.push(l);continue}let[,f,u]=c;if(!u){s.push("");continue}let a=f.replace(/\t/g," "),m=Math.floor(a.length/2);s.push(r.repeat(m)+u)}return s.join(`
|
|
187
|
-
`)}function pp(e,t){let{groups:i=lp,separateGroups:n=!0,alphabetize:r=!0}=t,o=e.split(`
|
|
188
|
-
`),s=[],l=[],c=-1;for(let w=0;w<o.length;w++){let C=o[w],A=tc(C);if(A)s.push({line:C,source:A.source,group:A.group,isType:A.isType}),c=w;else if(s.length>0&&C.trim()==="")continue;else if(s.length>0||C.trim()!==""){if(s.length===0||w>c+1)l.push(C)}}if(s.length===0)return e;let f=new Map;for(let w of i)f.set(w,[]);for(let w of s)(f.get(w.group)||f.get("external")||[]).push(w);if(r)for(let[,w]of f)w.sort((C,A)=>{if(C.isType!==A.isType)return C.isType?1:-1;return C.source.localeCompare(A.source)});let u=[],a=null;for(let w of i){let C=f.get(w)||[];if(C.length===0)continue;if(n&&a!==null)u.push("");for(let A of C)u.push(A.line);a=w}let m=o.slice(0,o.findIndex((w)=>tc(w)!==null)),y=l;while(y.length>0&&y[0].trim()==="")y.shift();return[...m,...u,"",...y].join(`
|
|
189
|
-
`)}function tc(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:ic(o[1]),isType:!1};return null}let n=!!i[1],r=i[2];return{source:r,group:n?"type":ic(r),isType:n}}function ic(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 mp(e,t){let{kinds:i=ap,alphabetize:n=!1,groupExports:r=!0}=t,o=e.split(`
|
|
190
|
-
`),s=[],l=[],c=[],f=null,u=0,a=!0,m=!1,y=[];for(let A=0;A<o.length;A++){let k=o[A],W=k.trim(),B=u,T=W.startsWith("///"),D=B===0&&!T&&(W.startsWith("//")||W.startsWith("/*"));if(m||D){if(y.push(k),!m&&W.startsWith("/*")&&!W.includes("*/"))m=!0;else if(m&&W.includes("*/"))m=!1;continue}if(B===0&&y.length>0&&W===""){y.push(k);continue}u+=(k.match(/\{/g)||[]).length,u-=(k.match(/\}/g)||[]).length;let N=gp(W);if(a&&N&&N.kind!=="import"&&!W.startsWith("//")&&!W.startsWith("/*"))a=!1;if(a){if(y.length>0){if(N?.kind==="import"||!N)l.push(...y),y.length=0}l.push(k);continue}if(N&&u<=1){if(f)s.push(f);f={lines:y.length>0?[...y,k]:[k],kind:N.kind,name:N.name,isExport:N.isExport},y.length=0}else if(f)f.lines.push(k);else{if(W==="")continue;c.push(k)}}if(f)s.push(f);if(y.length>0)c.push(...y);s.sort((A,k)=>{if(r&&A.isExport!==k.isExport)return A.isExport?-1:1;let W=i.indexOf(A.kind),B=i.indexOf(k.kind),T=W>=0?W:i.length,D=B>=0?B:i.length;if(T!==D)return T-D;if(n)return A.name.localeCompare(k.name);return 0});let w=[...l],C=null;for(let A of s){if(C!==null&&A.kind!==C)w.push("");w.push(...A.lines),C=A.kind}if(c.length>0)w.push(""),w.push(...c);return w.join(`
|
|
191
|
-
`)}function gp(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 ap,lp;var nc=de(()=>{ap=["import","type","interface","enum","class","function","variable","export","module","namespace","unknown"],lp=["builtin","external","scoped","internal","parent","sibling","index","type"]});function Ep(e){switch(e){case"strict":return Cp;case"readonly":return wp;case"simplified":return bp;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 sc{rules;compiled=[];cache=new Map;constructor(e={rules:[]}){if(this.rules=[],e.includeDefaults!==!1)this.rules.push(...yp);if(e.presets)for(let t of e.presets)this.rules.push(...Ep(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],n=typeof i.pattern==="string"?new RegExp(i.pattern.replace(vp,"\\$&"),i.global?"g":""):i.pattern;e[t]={rule:i,regex:n}}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":""}`,n=this.cache.get(i);if(n!==void 0)return n;let r=e,o=null;for(let s=0;s<this.compiled.length;s++){let{rule:l,regex:c}=this.compiled[s];if(l.condition){if(!o)o={type:e,...t};if(!l.condition(o))continue}if(c.lastIndex=0,c.test(r)){if(c.lastIndex=0,r=r.replace(c,l.replacement),c.lastIndex=0,!l.global)break}}if(this.cache.size>=oc){let s=Math.ceil(oc*0.1),l=0;for(let c of this.cache.keys()){if(l++>=s)break;this.cache.delete(c)}}return this.cache.set(i,r),r}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 n=typeof i.pattern==="string"?i.pattern:i.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 Kr(e={rules:[]}){return new sc(e)}function ac(e,t,i={}){return e.replace(/:\s*([^;,)\]}]+)/g,(n,r)=>`: ${t.map(r.trim(),i)}`)}var yp,Cp,wp,bp,vp,oc=2048,k0,M0;var lc=de(()=>{yp=[{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}],Cp=[{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}],wp=[{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}],bp=[{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}];vp=/[.*+?^${}()|[\]\\]/g;k0=Kr({rules:[]}),M0=Kr({rules:[],presets:["strict"]})});var cc;var fc=de(()=>{cc=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 uc(e,t={strings:!0}){let i="",n=0;while(n<e.length){let r=e.slice(n,n+2);if(r==="//"){let s=e.indexOf(`
|
|
192
|
-
`,n),l=s===-1?e.length:s;i+=" ".repeat(l-n),n=l;continue}if(r==="/*"){let s=e.indexOf("*/",n+2),l=s===-1?e.length:s+2;for(let c=n;c<l;c++)i+=e[c]===`
|
|
193
|
-
`?`
|
|
194
|
-
`:" ";n=l;continue}let o=e[n];if(t.strings&&(o==='"'||o==="'"||o==="`")){let s=o;i+=" ",n++;while(n<e.length){if(e[n]==="\\"){i+=" ",n+=2;continue}if(e[n]===s){i+=" ",n++;break}i+=e[n]===`
|
|
195
|
-
`?`
|
|
196
|
-
`:" ",n++}continue}i+=o,n++}return i}function $p(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 n of i)for(let r of e.matchAll(n))t.add(r[1]);return t}function xp(e){let t=new Set;for(let i of e.matchAll(/\bimport\s+(?:type\s+)?([\s\S]*?)\s+from\s*['"`]/g)){let n=i[1],r=/\*\s*as\s+([A-Za-z_$][\w$]*)/.exec(n);if(r)t.add(r[1]);let o=n.split("{")[0].replace(/\*\s*as\s+[A-Za-z_$][\w$]*/,"");for(let l of o.split(",")){let c=l.trim();if(/^[A-Za-z_$][\w$]*$/.test(c))t.add(c)}let s=/\{([\s\S]*?)\}/.exec(n);if(s)for(let l of s[1].split(",")){let c=l.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 i of e.matchAll(/\bimport\s*\(\s*['"`][^'"`]*['"`]\s*\)\s*\.\s*([A-Za-z_$][\w$]*)/g))t.add(i[1]);return t}function Ap(e){let t=new Set,i=(r)=>{for(let o of r.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 r of e.matchAll(n))i(r[1]);for(let r of e.matchAll(/(?:\b[A-Za-z_$][\w$]*)?\s*<([^<>()]*)>\s*\(/g))i(r[1]);for(let r of e.matchAll(/\binfer\s+([A-Za-z_$][\w$]*)/g))t.add(r[1]);for(let r of e.matchAll(/\[\s*([A-Za-z_$][\w$]*)\s+in\b/g))t.add(r[1]);return t}function Tp(e){let t=new Map,i=(r)=>{let o=1;for(let s=0;s<r&&s<e.length;s++)if(e.charCodeAt(s)===10)o++;return o},n=(r,o,s)=>{for(let l of r.matchAll(/\b([A-Z][\w$]*)\b/g)){let c=l[1];if(t.has(c))continue;let f=r.slice(l.index+c.length);if(/^\s*\??:/.test(f))continue;t.set(c,{line:i(o),context:s.trim().slice(0,120)})}};for(let r of e.matchAll(/\btype\s+[A-Za-z_$][\w$]*\s*(?:<[^=]*?>)?\s*=([^;]*)/g))n(r[1],r.index+r[0].indexOf("="),r[0]);for(let r of e.matchAll(/\b(?:extends|implements)\s+([^{;]*)/g))n(r[1],r.index,r[0]);for(let r of e.matchAll(/:\s*([^;,){}\n=]+)/g))n(r[1],r.index,r[0]);for(let r of e.matchAll(/<([^<>()]*)>/g))n(r[1],r.index,r[0]);return t}function hc(e){let t=uc(e),i=uc(e,{strings:!1}),n=new Set([...$p(t),...xp(i),...Ap(t),...cc,...Sp]),r=[];for(let[o,s]of Tp(t)){if(n.has(o))continue;if(new RegExp(`[\\w$]\\s*\\.\\s*${o}\\b`).test(t))continue;r.push({name:o,line:s.line,context:s.context})}return r.sort((o,s)=>o.line-s.line||o.name.localeCompare(s.name))}var Sp;var dc=de(()=>{fc();Sp=new Set(["This","True","False","Null","Undefined","Void","Never","Any","Unknown","Object","Infinity","NaN"])});function Dt(e,t){let i=1,n=1;for(let r=0;r<t;r++)if(e.charCodeAt(r)===10)i++,n=1;else n++;return{line:i,column:n}}function mc(e){let t=[],i=[],n=[],r={")":"(","]":"[","}":"{"},o=0,s=0,l=-1;for(let f=0;f<e.length;f++){let u=e.charCodeAt(f),a=e.charCodeAt(f+1);if(l!==-1){if(u===42&&a===47)i.push({start:l,end:f+2}),l=-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&&a===42){l=f,f++;continue}if(u===47&&a===47){let y=f;while(f<e.length&&e.charCodeAt(f)!==10)f++;i.push({start:y,end:f});continue}if(u===39||u===34||u===96){o=u,s=f;continue}let m=e[f];if(m==="("||m==="["||m==="{")n.push({char:m,offset:f});else if(r[m]){let y=n.pop();if(!y||y.char!==r[m])t.push({...Dt(e,f),message:`Unexpected closing delimiter ${m}`,code:"DTSX1004"})}}if(o)t.push({...Dt(e,s),message:"Unterminated string literal",code:"DTSX1002"});if(l!==-1)t.push({...Dt(e,l),message:"Unterminated block comment",code:"DTSX1003"});for(let f of n)t.push({...Dt(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 a of e.matchAll(f)){if(i.some((m)=>a.index>=m.start&&a.index<m.end))continue;t.push({...Dt(e,a.index),message:u,code:"DTSX1005"})}for(let f of e.matchAll(/\btype\s*(?=[{=])/g)){if(i.some((a)=>f.index>=a.start&&f.index<a.end))continue;let u=e.slice(0,f.index).trimEnd();if(u.endsWith("import")||u.endsWith("export"))continue;t.push({...Dt(e,f.index),message:"Declaration name expected",code:"DTSX1005"})}return t.push(...Rp(e,i)),t.sort((f,u)=>f.line-u.line||f.column-u.column)}function Rp(e,t){let i=[],n=(r)=>t.some((o)=>r>=o.start&&r<o.end);for(let r of e.matchAll(/\b(import|export)\s+(?:type\s+)?\{/g)){let o=r.index;if(n(o))continue;let s=o+r[0].length-1,l=-1;for(let u=s+1;u<e.length;u++){if(n(u))continue;let a=e[u];if(a==="{"){l=-2;break}if(a==="}"){l=u;break}}if(l<0)continue;let c=e.slice(s+1,l);if(!c.trim())continue;let f=s+1;for(let u of c.split(",")){let a=u.trim();if(a){let m=f+u.indexOf(a);if(a.includes(";"))i.push({...Dt(e,m),message:`Unexpected ';' in ${r[1]} clause \u2014 specifiers are separated by ','`,code:"DTSX1006"});else if(!Op.test(a))i.push({...Dt(e,m),message:`Invalid ${r[1]} specifier '${a}'`,code:"DTSX1006"})}f+=u.length+1}}return i}var pc,Op;var gc=de(()=>{pc=String.raw`(?:[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*|'[^']*'|"[^"]*")`,Op=new RegExp(`^(?:type\\s+)?${pc}(?:\\s+as\\s+${pc})?$`,"u")});import{join as V0,resolve as Pp}from"path";import kp from"process";function Bo(){return`${String.fromCharCode(47,47,35)} sourceMappingURL=`}async function Hr(e,t,i="lf"){let n=t.replace(/\r\n/g,`
|
|
197
|
-
`);if(!n.endsWith(`
|
|
198
|
-
`))n+=`
|
|
199
|
-
`;if(i==="crlf")n=n.replace(/\n/g,`\r
|
|
200
|
-
`);await ls(e,n)}async function yc(e){try{let t=e?.cwd||kp.cwd();return(await mi(Pp(t,e?.tsconfigPath||"tsconfig.json"),{allowCircular:!0}))?.isolatedDeclarations??!1}catch{return!1}}function Cc(e,t){let i={isValid:!0,errors:[]};for(let n of mc(e))i.errors.push({line:n.line,column:n.column,message:n.message,code:n.code});for(let n of hc(e))i.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 i.isValid=i.errors.length===0,i}function wc(e,t,i){if(e===t)return"";let n=e.split(`
|
|
201
|
-
`),r=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<r.length;u++)s.set(r[u],(s.get(r[u])??0)+1);let l=[],c=[];for(let[u,a]of o){let m=a-(s.get(u)??0);for(let y=0;y<m;y++)l.push(u)}for(let[u,a]of s){let m=a-(o.get(u)??0);for(let y=0;y<m;y++)c.push(u)}if(l.length===0&&c.length===0)return"";let f=[`--- ${i}`,`+++ ${i}`];for(let u=0;u<l.length;u++)f.push(`- ${l[u]}`);for(let u=0;u<c.length;u++)f.push(`+ ${c[u]}`);return f.join(`
|
|
203
|
-
`)}function bc(e,t,i,n){let r=e.split(`
|
|
204
|
-
`),o=[];function s(a){let m="",y=a<0?-a<<1|1:a<<1;do{let w=y&31;if(y>>>=5,y>0)w|=32;m+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[w]}while(y>0);return m}let l=0,c=0,f=0,u=n.split(`
|
|
205
|
-
`).length;for(let a=0;a<r.length;a++){if(r[a].trim()===""){o.push("");continue}l=0;let m=Math.min(a,u-1),y=[],w=0-l,C=0,A=m-c,k=0-f;y.push(s(w)+s(C)+s(A)+s(k)),l=0,c=m,f=0,o.push(y.join(","))}return{version:3,file:t,sourceRoot:"",sources:[i],sourcesContent:[n],mappings:o.join(";")}}function Ec(e,t){return`${e}
|
|
206
|
-
${Bo()}${t}
|
|
207
|
-
`}var vc=de(()=>{Bi();dn();dc();gc()});function Np(e){let t=[],i=0;for(let n=0;n<=e.length;n++)if(n===e.length||e[n]===`
|
|
208
|
-
`){let r=i,o=n;while(r<o&&(e[r]===" "||e[r]==="\t"||e[r]==="\r"))r++;while(o>r&&(e[o-1]===" "||e[o-1]==="\t"||e[o-1]==="\r"))o--;let s=e.slice(r,o);if(i=n+1,s.startsWith("///")){if(s.indexOf("<")===-1)continue;if(Mp.test(s)||Dp.test(s)||Ip.test(s))t.push(s)}else if(s===""||s.startsWith("//"))continue;else break}return t}function Fp(e){if(e.includes(`
|
|
159
|
+
}`:"{}";if(o.length===0)return f;let u=o[0];for(let a=1;a<o.length;a++)u=`Omit<${u}, keyof ${o[a]}> & ${o[a]}`;return s.length>0?`Omit<${u}, keyof ${f}> & ${f}`:u}function Li(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(!St(e.charCodeAt(r)))return!1;return!0}function cr(e){let t=e.split(".");return t.length>0&&t.every(Li)}function Kd(e){let t=!1,r="";for(let n=0;n<e.length;n++){let i=e[n];if(t){if(i==="\\")n++;else if(i===r)t=!1;continue}if(i==='"'||i==="'"||i==="`"){t=!0,r=i;continue}if(i==="(")return n;if(i==="<"){let s=tt(e,n,"<",">");if(s!==-1)n=s}}return-1}function Jl(e){if(e.length<3||!e.endsWith(")"))return null;let t=Kd(e);if(t===-1||tt(e,t,"(",")")!==e.length-1)return null;let r=e.slice(0,t).trim(),n=!1;if(r.endsWith("?."))n=!0,r=r.slice(0,-2).trim();let i=r,s=!1,o=r.indexOf("<");if(o!==-1){if(tt(r,o,"<",">")!==r.length-1)return null;i=r.slice(0,o).trim(),s=!0}if(!cr(i))return null;let l=e.slice(t+1,-1).trim(),c=Ni(l)!==-1||l.startsWith("function")||l.startsWith("async function"),f=cr(l),u=!c&&l.endsWith(")")&&Jl(l)!==null;if(!s&&!n&&!c&&!f&&!u)return null;let a=`ReturnType<typeof ${r}>`;return n?`${a} | undefined`:a}function Bl(e){let t=e.split(`
|
|
160
|
+
`).map((f)=>ql(f)).join(`
|
|
161
|
+
`),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(!St(f)&&!St(u))t=(t.slice(0,r)+t.slice(r+5)).trim()}let n=t.indexOf("(");if(n!==-1){let f=tt(t,n,"(",")");if(f!==-1){let u=t.slice(n,f+1),a=Gt(u);t=t.slice(0,n)+a+t.slice(f+1)}}let i=t.length,s="",o=[],l=!1,c=!1;for(let f=0;f<i;f++){let u=t.charCodeAt(f);if(u===123||u===40)o.push(u);else if(u===125||u===41)o.pop();if(u<=32){if(l=!0,u===10||u===13)c=!0;continue}if(l&&s.length>0){let a=(o.length>0?o[o.length-1]:0)===123;if(c&&a){let m=s.charCodeAt(s.length-1),y=m===59||m===44||m===123||u===125,w=s.length>=2&&s.charCodeAt(s.length-1)===47&&s.charCodeAt(s.length-2)===42;if(!y&&!w)s+="; ";else s+=" "}else s+=" "}l=!1,c=!1,s+=t[f]}return s.trim()}function St(e){return e>=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57||e===95||e===36}function Gt(e){let t=e.trim(),r,n=!1;if(t.startsWith("(")&&t.endsWith(")"))r=t.slice(1,-1),n=!0;else r=t;let i=r.trim();if(!i)return n?"()":"";let s=!1;{let w=0;for(let C=0;C<i.length;C++){let x=i.charCodeAt(C);if(x===40||x===60||x===91||x===123)w++;else if(x===41||x===93||x===125||x===62&&i.charCodeAt(C-1)!==61)w--;else if(w===0&&x===61){let k=C>0?i.charCodeAt(C-1):0,L=C+1<i.length?i.charCodeAt(C+1):0;if(k!==61&&k!==33&&k!==60&&k!==62&&L!==61&&L!==62){s=!0;break}}}}if(!s)return t;let o=[],l=[],c=0,f=0,u=!1,a=0;for(let w=0;w<=i.length;w++){if(w===i.length){o.push(i.slice(c));break}let C=i.charCodeAt(w);if(u){if(C===92){w++;continue}if(C===a)u=!1;continue}if(C===47&&w+1<i.length){let x=i.charCodeAt(w+1);if(x===42){w+=2;while(w+1<i.length&&!(i.charCodeAt(w)===42&&i.charCodeAt(w+1)===47))w++;w++;continue}if(x===47){while(w<i.length&&i.charCodeAt(w)!==10)w++;continue}}if(C===39||C===34||C===96){u=!0,a=C;continue}if(C===40||C===60||C===91||C===123)f++;else if(C===41||C===93||C===125||C===62&&i.charCodeAt(w-1)!==61)f--;else if(C===44&&f===0){o.push(i.slice(c,w));let x=",",k=w+1;while(k<i.length&&i.charCodeAt(k)<=32)x+=i[k],k++;l.push(x),c=k}}let m=[];for(let w of o){let C=w.trim();if(!C){m.push(w);continue}if(C.startsWith("//"))continue;let x=ql(C),k=w.slice(0,w.length-w.trimStart().length);m.push(k+Zd(x))}let y=m[0]||"";for(let w=1;w<m.length;w++)y+=(l[w-1]||", ")+m[w];return n?`(${y})`:y}function ql(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 Zd(e){if(e.startsWith("..."))return e;let t=-1,r=-1,n=0,i=!1,s=0;for(let l=0;l<e.length;l++){let c=e.charCodeAt(l);if(i){if(c===92){l++;continue}if(c===s)i=!1;continue}if(c===47&&l+1<e.length){let f=e.charCodeAt(l+1);if(f===42){l+=2;while(l+1<e.length&&!(e.charCodeAt(l)===42&&e.charCodeAt(l+1)===47))l++;l++;continue}if(f===47){while(l<e.length&&e.charCodeAt(l)!==10)l++;continue}}if(c===39||c===34||c===96){i=!0,s=c;continue}if(c===40||c===60||c===91||c===123)n++;else if(c===41||c===93||c===125||c===62&&e.charCodeAt(l-1)!==61)n--;else if(n===0){if(c===58&&t===-1)t=l;else if(c===61&&r===-1&&(l===0||e.charCodeAt(l-1)!==61)&&(l+1>=e.length||e.charCodeAt(l+1)!==61&&e.charCodeAt(l+1)!==62))r=l}}let o=r!==-1;if(t!==-1&&(r===-1||t<r)){let l=e.slice(0,t).trim(),c=r!==-1?e.slice(t+1,r).trim():e.slice(t+1).trim(),f=o&&!l.endsWith("?")?"?":"";return`${l}${f}: ${c}`}else if(r!==-1){let l=e.slice(0,r).trim(),c=!l.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`${l}${c}: ${u}`}return e}function Yd(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 zl(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(`
|
|
162
|
+
`),key:e.slice(r).trim()}}function Jd(e){let t=[],r="",n="",i=0,s=!1,o="",l=!0,c=!1,f=0,u=!1,a=!1,m=0,y=!1,w=!1;for(let C=0;C<e.length;C++){let x=e.charCodeAt(C),k=C>0?e.charCodeAt(C-1):0,L=C<e.length-1?e.charCodeAt(C+1):0;if(!s&&!c&&x===47&&L===47){r=r.replace(/[ \t]+$/,""),C+=2;while(C<e.length&&e.charCodeAt(C)!==10)C++;C--;continue}if(!s&&!c&&x===47&&L===42){c=!0,f=1,r+="/*",C++;continue}else if(c&&x===42&&L===47){if(f--,r+="*/",C++,f===0)c=!1;continue}else if(c&&x===47&&L===42){f++,r+="/*",C++;continue}let G=e[C];if(!s&&!c&&(x===34||x===39||x===96))s=!0,o=G,r+=G;else if(s&&G===o&&k!==92)s=!1,r+=G;else if(!s&&!c)if(x===40&&i===0&&l&&m===0){n=r.trim();let T=Yd(n),D=T>0?n.slice(0,T):"",F=n.slice(T),N="";if(F.startsWith("async ")||F.startsWith("async\t")||F.startsWith(`async
|
|
163
|
+
`))F=F.slice(6).trimStart(),N="async ";if(F.startsWith("*"))F=F.slice(1).trimStart(),N+="*";n=D+F,r=N+G,l=!1,y=!0,w=!1,i=1}else if(x===123||x===91||x===40){if(i++,r+=G,w&&x===123)w=!1}else if(x===125||x===93||x===41){if(i--,r+=G,x===41&&i===0&&!l&&!y)u=!0;if(y){if(x===41&&i===0&&!w)w=!0;else if(x===125&&i===0)y=!1,w=!1}}else if(x===58&&i===0&&l&&m===0)n=r.trim(),r="",l=!1;else if(x===58&&i===0&&u)a=!0,r+=G;else if(x===60&&a)m++,r+=G;else if(x===60&&l&&i===0)m++,r+=G;else if(x===62&&m>0&&k!==61)m--,r+=G;else if(x===61&&L===62&&a&&m===0)a=!1,u=!1,r+=G;else if(x===44&&i===0&&m===0&&!w){if(n&&r.trim()){let T=r.trim();t.push([n,T])}else if(l&&r.trim())_l(t,r.trim());r="",n="",l=!0,u=!1,a=!1,m=0}else r+=G;else r+=G}if(n&&r.trim()){let C=r.trim();t.push([n,C])}else if(l&&r.trim())_l(t,r.trim());return t}function _l(e,t){let{comments:r,key:n}=zl(t);if(Li(n))e.push([r?`${r}
|
|
164
|
+
${n}`:n,n]);else if(n.startsWith("...")&&n.length>3)e.push(["...",n.slice(3).trim()])}function qd(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 zd(e,t,r){let n=r.trim();if(n.charCodeAt(0)!==40)return null;let i=tt(n,0,"(",")");if(i===-1)return null;let s=n.slice(1,i).trim(),o=n.slice(i+1).trimStart();if(!o.startsWith("=>"))return null;let l=o.slice(2).trim();if(e==="get")return`get ${t}(): ${l||"unknown"}`;return`set ${t}(${s})`}function Xd(e){let t=e;if(t.startsWith("async ")||t.startsWith("async\t"))t=t.slice(5).trimStart();if(t.startsWith("*"))t=t.slice(1).trimStart();if(!t.startsWith("("))return!1;let r=0;for(let n=0;n<t.length;n++){let i=t.charCodeAt(n);if(i===40)r++;else if(i===41){if(r--,r===0){let s=t.slice(n+1).trimStart();if(s.startsWith("{"))return!0;if(s.startsWith(":")){let o=xs(s,1);if(o?.kind==="arrow")return!1;if(o?.kind==="body")return!0}return!1}}}return!1}function Qd(e){let t=e.trimEnd();if(!t.endsWith(">"))return null;let r=0,n=-1;for(let s=t.length-1;s>=0;s--){let o=t.charCodeAt(s);if(o===62){if(s>0&&t.charCodeAt(s-1)===61)continue;r++}else if(o===60){if(r--,r===0){n=s;break}}}if(n===-1)return null;let i=t.slice(0,n).trimEnd();if(!i)return null;return{name:i,typeParams:t.slice(n)}}function Ul(e,t){let r=t.trimStart(),n=!1,i=!1;if(r.startsWith("async ")||r.startsWith("async\t"))n=!0,r=r.slice(5).trimStart();if(r.startsWith("*"))i=!0,r=r.slice(1).trimStart();let s="";if(r.charCodeAt(0)===60){let m=0,y=-1;for(let w=0;w<r.length;w++)if(r.charCodeAt(w)===60)m++;else if(r.charCodeAt(w)===62&&!(w>0&&r.charCodeAt(w-1)===61)){if(m--,m===0){y=w;break}}if(y!==-1)s=r.slice(0,y+1),r=r.slice(y+1).trimStart()}let o=r.indexOf("("),l=tt(r,o,"(",")");if(o===-1||l===-1)return"() => unknown";let c=r.slice(o,l+1),f="unknown",u=r.slice(l+1).trimStart();if(u.charCodeAt(0)===58){let m=u.slice(1),y=xs(m,0);if(y)f=m.slice(0,y.index).trim();else f=m.trim()}if(f==="unknown"&&!i&&u.charCodeAt(0)===123){let m=tt(u,0,"{","}");if(m!==-1){let y=fr(u.slice(1,m),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 a=Gt(c);return`${s}${a} => ${f}`}function xs(e,t){let r=0,n=0,i=0,s=0,o=!1,l=0;for(let c=t;c<e.length;c++){let f=e.charCodeAt(c);if(o){if(f===92)c++;else if(f===l)o=!1;continue}if(f===34||f===39||f===96){o=!0,l=f;continue}if(f===40)r++;else if(f===41&&r>0)r--;else if(f===91)n++;else if(f===93&&n>0)n--;else if(f===60)i++;else if(f===62&&i>0&&e.charCodeAt(c-1)!==61)i--;else if(f===125&&s>0)s--;else if(f===123){let u=r>0||n>0||i>0||s>0,a=e.slice(t,c).trimEnd(),m=a.charCodeAt(a.length-1),y=a.length===0||m===38||m===124||m===40||m===44||m===58||m===61||m===91;if(u||y)s++;else return{index:c,kind:"body"}}else if(f===61&&c+1<e.length&&e.charCodeAt(c+1)===62&&r===0&&n===0&&i===0&&s===0)return{index:c,kind:"arrow"}}return null}function tt(e,t,r,n){let i=0;for(let s=t;s<e.length;s++)if(e[s]===r)i++;else if(e[s]===n){if(n===">"&&s>0&&e[s-1]==="=")continue;if(i--,i===0)return s}return-1}function Ni(e){let t=0,r=0,n=!1,i="";for(let s=0;s<e.length-1;s++){let o=e[s],l=e[s+1],c=s>0?e[s-1]:"";if(!n&&(o==='"'||o==="'"||o==="`"))n=!0,i=o;else if(n&&o===i&&c!=="\\")n=!1;if(!n){if(o==="<"){let f=tt(e,s,"<",">");if(f!==-1){s=f;continue}}if(o==="(")t++;else if(o===")")t--;else if(o==="[")r++;else if(o==="]")r--;if(o==="="&&l===">"&&t===0&&r===0)return s}}return-1}function Xl(e,t=!1,r=0,n=!0){let i=e.trim();if(i.length>200&&ps(i,"=>")>2&&ps(i,"<")>5&&!i.startsWith("function"))return t?"((...args: any[]) => any)":"(...args: any[]) => any";if(i.startsWith("async ")&&i.includes("=>")){let o=i.slice(5).trim(),l=Ni(o);if(l===-1)return t?"(() => Promise<unknown>)":"() => Promise<unknown>";let c=o.substring(0,l).trim(),f=o.substring(l+2).trim(),u=Vl(c),{params:a,returnType:m}=u;if(a=Gt(a),a==="()"||a==="")a="()";else if(!a.startsWith("("))a=`(${a})`;let y=m;if(y);else if(f.startsWith("{"))y=fr(f.slice(1,f.endsWith("}")?-1:void 0),!0,a);else y=Ie(f,n,!1,r+1);let w=`${a} => ${m||y.startsWith("Promise<")?y:`Promise<${y}>`}`;return t?`(${w})`:w}if(i.includes("=>")){let o="",l=i;if(i.startsWith("<")){let x=tt(i,0,"<",">");if(x!==-1)o=i.substring(0,x+1),l=i.substring(x+1).trim()}let c=Ni(l);if(c===-1)return t?"(() => unknown)":"() => unknown";let f=l.substring(0,c).trim(),u=l.substring(c+2).trim(),a=Vl(f),{params:m,returnType:y}=a;if(m=Gt(m),m==="()"||m==="")m="()";else if(!m.startsWith("("))m=`(${m})`;let w="unknown";if(y)w=y;else if(u.startsWith("{"))w=fr(u.slice(1,u.endsWith("}")?-1:void 0),!1,m);else if(Di(u)||Zl(u)&&Di(u.slice(1,-1).trim()))w="JSX.Element";else if(u.includes("=>")){let x=u.trimStart(),k=x.indexOf("("),L=k!==-1?tt(x,k,"(",")"):-1,G=L!==-1?x.indexOf("=>",L):-1;if(k===0&&L!==-1&&G!==-1){let T=x.substring(k+1,L).trim(),D=Gt(T);if(o.includes("T")&&D.includes("T"))w=`(${D}) => T`;else w=`(${D}) => any`}else w="any"}else if(t)w="unknown";else w=Lt(u,Kl(m));let C=`${o}${m} => ${w}`;return t?`(${C})`:C}if(i.startsWith("function")){let o=8,l=i.length;while(o<l&&i.charCodeAt(o)<=32)o++;let c=!1;if(o<l&&i.charCodeAt(o)===42){c=!0,o++;while(o<l&&i.charCodeAt(o)<=32)o++}let f="";if(o<l&&i.charCodeAt(o)===60){let m=o,y=1;o++;while(o<l&&y>0){let w=i.charCodeAt(o);if(w===60)y++;else if(w===62&&i.charCodeAt(o-1)!==61)y--;o++}f=i.substring(m,o);while(o<l&&i.charCodeAt(o)<=32)o++}let u=i.indexOf("(",o);if(u!==-1){let m=1,y=u+1;while(y<l&&m>0){let G=i.charCodeAt(y);if(G===40)m++;else if(G===41)m--;y++}let w=i.substring(u+1,y-1).trim(),C=w?Gt(`(${w})`):"()";if(c){let G=i.substring(y).trim(),T=G.indexOf("Generator<");if(T!==-1){let F=T+10,N=G.indexOf(">",F);if(N!==-1){let b=G.substring(F,N),j=`${f}${C} => Generator<${b}>`;return t?`(${j})`:j}}let D=`${f}${C} => Generator<any, any, any>`;return t?`(${D})`:D}let x="unknown",k=i.substring(y).trimStart();if(k.charCodeAt(0)===58){let G=k.slice(1),T=xs(G,0),D=(T?G.slice(0,T.index):G).trim();if(D)x=D}let L=`${f}${C} => ${x}`;return t?`(${L})`:L}let a="(...args: any[]) => unknown";return t?`(${a})`:a}if(i.includes("=>")&&i.includes("(")&&i.includes(")")){if(i.length>100||ps(i,"=>")>2){let o="";if(i.charCodeAt(0)===60){let a=tt(i,0,"<",">");if(a!==-1)o=i.substring(0,a+1)}let l=i.indexOf("("),c=l!==-1?tt(i,l,"(",")"):-1,f=l!==-1&&c!==-1?i.substring(l,c+1):"(...args: any[])";f=Gt(f);let u=`${o}${f} => any`;return t?`(${u})`:u}return t?`(${i})`:i}let s="() => unknown";return t?`(${s})`:s}function Vl(e){let t=e.trim();if(!t.startsWith("("))return{params:t,returnType:""};let r=tt(t,0,"(",")");if(r===-1)return{params:t,returnType:""};let n=t.slice(r+1).trim();return{params:t.slice(0,r+1),returnType:n.startsWith(":")?n.slice(1).trim():""}}function Ql(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 Gi(e){let t=-1,r=0;for(let i=0;i<e.length;i++){let s=e.charCodeAt(i);if(s===34||s===39||s===96){i=It(e,i,s)-1;continue}if(s===47&&e.charCodeAt(i+1)===47){while(i<e.length&&e.charCodeAt(i)!==10)i++;continue}if(s===47&&e.charCodeAt(i+1)===42){let o=e.indexOf("*/",i+2);i=o===-1?e.length:o+1;continue}if(s===47){let o=i-1;while(o>=0&&e.charCodeAt(o)<=32)o--;if(o<0||"([{:;,=!?&|+*-~>".includes(e[o])){let l=!1;for(i++;i<e.length;i++){let c=e.charCodeAt(i);if(c===92)i++;else if(c===91)l=!0;else if(c===93)l=!1;else if(c===47&&!l)break}continue}}if(s===40||s===91||s===123)r++;else if(s===41||s===93||s===125)r--;else if(r===0&&e.startsWith("satisfies",i)&&gs(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 bs=20,Wi=!1,ze=null;var Ts=()=>{};function ip(e){let t=[],r=0;for(let n=0;n<=e.length;n++)if(n===e.length||e[n]===`
|
|
165
|
+
`){let i=r,s=n;while(i<s&&(e[i]===" "||e[i]==="\t"||e[i]==="\r"))i++;while(s>i&&(e[s-1]===" "||e[s-1]==="\t"||e[s-1]==="\r"))s--;let o=e.slice(i,s);if(r=n+1,o.startsWith("///")){if(o.indexOf("<")===-1)continue;if(ep.test(o)||tp.test(o)||rp.test(o))t.push(o)}else if(o===""||o.startsWith("//"))continue;else break}return t}function np(e){if(e.includes(`
|
|
209
166
|
`))return`/**
|
|
210
167
|
* ${e}
|
|
211
168
|
*/
|
|
212
169
|
`;return`/** ${e} */
|
|
213
|
-
`}function
|
|
170
|
+
`}function sp(e){let t=e.indexOf("{");if(t===-1)return-1;let r=e.indexOf("<");if(r===-1||r>t)return t;let n=0,i=!1,s="";for(let o=0;o<e.length;o++){let l=e[o],c=o>0?e[o-1]:"";if(!i&&(l==='"'||l==="'"||l==="`"))i=!0,s=l;else if(i&&l===s&&c!=="\\")i=!1;if(!i){if(l==="<")n++;else if(l===">")n--;else if(l==="{"&&n===0)return o}}return-1}function op(e,t=!0){return At(e.leadingComments,t)+e.text}function ec(e,t=!0){let r=At(e.leadingComments,t);if(e.typeAnnotation&&!e.value)return r+e.text;let n="";if(e.isExported)n+="export ";n+="declare ";let i=e.modifiers?.[0]||"const";n+=`${i} `,n+=e.name;let{typeAnnotation:s,value:o}=e,l=!s&&o?Gi(o):null;if(l)s=l;else if(!s&&o&&o.trim().endsWith("as const"))s=Ie(o,!0);else if(!s&&o&&i==="const"){let f=o.trim(),u=f.startsWith("{")||f.startsWith("[");if(u)Es();s=Ie(o,!u)}else if(!s&&o)s=Ie(o,i==="const");if(!s)s="unknown";let c="";if(t&&o&&!e.typeAnnotation&&!o.trim().endsWith("as const")){let f=o.trim();if(i!=="const"){if((s==="string"||s==="number"||s==="boolean")&&f.length>0)c=`@defaultValue ${f}`}else if(f.startsWith("{")||f.startsWith("[")){let u=Ss();if(u)if(u.includes(`
|
|
214
171
|
`))c=`@defaultValue
|
|
215
172
|
* \`\`\`ts
|
|
216
173
|
${u.split(`
|
|
217
174
|
`).map((a)=>` * ${a}`).join(`
|
|
218
175
|
`)}
|
|
219
|
-
* \`\`\``;else c=`@defaultValue \`${u}\``}}else if(t&&
|
|
176
|
+
* \`\`\``;else c=`@defaultValue \`${u}\``}}else if(t&&o&&e.typeAnnotation&&Ql(e.typeAnnotation)){Es();let f=o.trim(),u=f.endsWith("as const")?f.slice(0,-8).trim():f;Ie(u,!1);let a=Ss();if(a)if(a.includes(`
|
|
220
177
|
`))c=`@defaultValue
|
|
221
178
|
* \`\`\`ts
|
|
222
179
|
${a.split(`
|
|
223
180
|
`).map((m)=>` * ${m}`).join(`
|
|
224
181
|
`)}
|
|
225
|
-
* \`\`\``;else c=`@defaultValue \`${a}\``}if(c=
|
|
182
|
+
* \`\`\``;else c=`@defaultValue \`${a}\``}if(c=vs(c),n+=`: ${s};`,c&&r&&r.includes("@defaultValue"))c="";if(c&&r){let f=r.trimEnd(),u=f.lastIndexOf("*/");if(u!==-1){let a=f.slice(0,u).trimEnd();if(a.startsWith("/** ")&&!a.includes(`
|
|
226
183
|
`))a=`/**
|
|
227
184
|
* ${a.slice(4)}`;return`${a}
|
|
228
185
|
* ${c}
|
|
@@ -231,28 +188,71 @@ ${a.split(`
|
|
|
231
188
|
* ${f.replace(/^\/\/\s*/,"")}
|
|
232
189
|
* ${c}
|
|
233
190
|
*/
|
|
234
|
-
${n}`}if(c)return`${
|
|
235
|
-
`;
|
|
236
|
-
`));for(let
|
|
237
|
-
`);if(
|
|
238
|
-
`;
|
|
239
|
-
`;
|
|
240
|
-
`;
|
|
241
|
-
`;
|
|
242
|
-
`;
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
`);
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
`).
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
191
|
+
${n}`}if(c)return`${np(c)}${n}`;return r+n}function ap(e,t=!0){let r=At(e.leadingComments,t),n=e.text;if(n.startsWith("export declare interface")||n.startsWith("declare interface"))return r+n;let i="";if(e.isExported)i+="export ";if(i+="declare interface ",i+=e.name,e.generics)i+=e.generics;if(e.extends)i+=` extends ${e.extends}`;let s=sp(e.text);if(s!==-1)i+=` ${e.text.slice(s)}`;else i+=" {}";return r+i}function lp(e,t=!0){let r=At(e.leadingComments,t);if(e.text.includes("{")&&e.text.includes("}")&&e.text.includes("from"))return r+e.text;let n="";if(e.isExported)n+="export ";if(!e.isExported&&!e.text.includes(" from "))n+="declare ";let i=e.text.indexOf("type ");if(i!==-1){let o=e.text.slice(i),l=o.length;while(l>0&&(o.charCodeAt(l-1)===59||o.charCodeAt(l-1)===32||o.charCodeAt(l-1)===10||o.charCodeAt(l-1)===13))l--;if(l<o.length)o=o.slice(0,l);n+=o}else{if(n+=`type ${e.name}`,e.generics)n+=e.generics;n+=" = any"}let s=n.trimEnd();if(!s.endsWith(";")&&!s.endsWith("}"))n+=";";return r+n}function cp(e,t=!0){return At(e.leadingComments,t)+e.text}function fp(e,t=!0){let r=At(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 up(e,t=!0){let r=At(e.leadingComments,t);if(e.text.startsWith("declare global"))return r+e.text;if(e.source||(e.name.startsWith('"')||e.name.startsWith("'")||e.name.startsWith("`"))){let s="declare module ";s+=e.name;let o=e.text.indexOf("{");if(o!==-1)s+=` ${e.text.slice(o)}`;else s+=" {}";return r+s}let n="";if(e.isExported)n+="export ";if(!e.modifiers?.includes("declare"))n+="declare ";n+="namespace ",n+=e.name;let i=e.text.indexOf("{");if(i!==-1)n+=` ${e.text.slice(i)}`;else n+=" {}";return r+n}function hp(e){let t=Bt.get(e);if(t)return Bt.delete(e),Bt.set(e,t),t;return null}function tc(e,t){if(Bt.set(e,t),Bt.size>200){let r=0;for(let n of Bt.keys()){if(r++>=20)break;Bt.delete(n)}}}function dp(e){let t=e.indexOf(" from ");if(t===-1)return null;let r=e.slice(t+6).trim(),n=r[0];if(n!=='"'&&n!=="'")return null;let i=r.indexOf(n,1);if(i===-1)return null;let s=r.slice(1,i),o=e.slice(0,t).trim(),l=o.startsWith("import type ");if(o.startsWith("import "))o=o.slice(7).trim();if(o.startsWith("type "))o=o.slice(5).trim();let c=null,f=[],u=!1,a=o.indexOf("{"),m=o.lastIndexOf("}");if(a!==-1&&m!==-1){let y=o.slice(0,a).trim();if(y.endsWith(","))c=y.slice(0,-1).trim()||null;let w=o.slice(a+1,m),C=0;for(let x=0;x<=w.length;x++)if(x===w.length||w.charCodeAt(x)===44){let k=C,L=x;while(k<L&&(w.charCodeAt(k)===32||w.charCodeAt(k)===9||w.charCodeAt(k)===10))k++;while(L>k&&(w.charCodeAt(L-1)===32||w.charCodeAt(L-1)===9||w.charCodeAt(L-1)===10))L--;if(k<L)f.push(w.slice(k,L));C=x+1}}else{let y=o.trim();if(y.startsWith("* as "))c=y.slice(5).trim()||null,u=!0;else c=y||null}return{defaultName:c,namedItems:f,source:s,isTypeOnly:l,isNamespace:u}}function pp(e){let t=hp(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 s=i.indexOf("{"),o=i.lastIndexOf("}");if(s!==-1&&o!==-1){let l=i.slice(0,s).trim();if(l.endsWith(",")){let f=l.slice(0,-1).trim();if(f)r.push(f)}else if(l&&!l.includes(","))r.push(l);let c=i.slice(s+1,o).split(",");for(let f=0;f<c.length;f++){let u=c[f].trim();if(!u)continue;if(u.startsWith("type "))u=u.slice(5).trim();let a=u.indexOf(" as ");if(a!==-1)u=u.slice(a+4).trim();if(u)r.push(u)}}else{let l=i.trim();if(l.startsWith("* as ")){let c=l.slice(5).trim();if(c)r.push(c)}else if(l)r.push(l)}return tc(e,r),r}function rc(e,t){throw Error(t||`Unexpected value: ${e}`)}function mp(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===95||e===36||e>127}function ic(e){let t=new Set,r=0,n=e.length;while(r<n){let i=e.charCodeAt(r);if(i>=65&&i<=90||i>=97&&i<=122||i===95||i===36||i>127){let s=r;r++;while(r<n&&mp(e.charCodeAt(r)))r++;t.add(e.substring(s,r))}else r++}return t}function ac(e,t,r=!0,n=["bun"]){let i="",s=t.sourceCode;if(s){let b=0;while(b<s.length&&(s.charCodeAt(b)===32||s.charCodeAt(b)===9||s.charCodeAt(b)===10||s.charCodeAt(b)===13))b++;if(b<s.length-2&&s.charCodeAt(b)===47&&s.charCodeAt(b+1)===47&&s.charCodeAt(b+2)===47){let j=ip(s);if(j.length>0)for(let se=0;se<j.length;se++){if(i)i+=`
|
|
192
|
+
`;i+=j[se]}}}let o=[],l=[],c=[],f=[],u=[],a=[],m=[],y=[],w=[];for(let b of e){let j=b.kind;switch(j){case"import":o.push(b);break;case"function":l.push(b);break;case"variable":c.push(b);break;case"interface":f.push(b);break;case"type":u.push(b);break;case"class":a.push(b);break;case"enum":m.push(b);break;case"module":y.push(b);break;case"export":w.push(b);break;case"namespace":y.push(b);break;case"unknown":break;default:rc(j,`Unhandled declaration kind: ${j}`)}}let C=new Set,x=[],k=[],L=[],G=new Set;for(let b of w){let j=At(b.leadingComments,r);if(b.text.startsWith("export default")){let se=b.text.endsWith(";")?b.text:`${b.text};`;L.push(j+se)}else{let se=b.text.trim();if(!se.endsWith(";"))se+=";";let he=se.match(gp);if(he){let ge=he[1],De=0;for(let ie=0;ie<=ge.length;ie++)if(ie===ge.length||ge.charCodeAt(ie)===44){let ce=De,ee=ie;while(ce<ee&&ge.charCodeAt(ce)<=32)ce++;while(ee>ce&&ge.charCodeAt(ee-1)<=32)ee--;if(ce<ee)C.add(ge.slice(ce,ee));De=ie+1}}let Z=j+se;if(!G.has(Z))if(G.add(Z),Z.includes("export type"))x.push(Z);else k.push(Z)}}let T=new Map;if(o.length>0)for(let b of o){let j=pp(b.text);for(let se of j)T.set(se,b)}let D=new Set;if(f.length>0){let b=[];for(let j of l)if(j.isExported)b.push(j.text);for(let j of a)b.push(j.text);for(let j of u)b.push(j.text);if(b.length>0){let j=ic(b.join(`
|
|
193
|
+
`));for(let se of f)if(j.has(se.name))D.add(se.name)}}let F=[];if(o.length>0){let b=new Set,j=[];for(let Z of l)if(Z.isExported)j.push(Z.text);for(let Z of c)if(j.push(Z.text),Z.typeAnnotation)j.push(Z.typeAnnotation);else if(Z.isExported&&Z.value)j.push(ec(Z,!1));for(let Z of f)if(Z.isExported||D.has(Z.name))j.push(Z.text);for(let Z of u)j.push(Z.text);for(let Z of a)j.push(Z.text);for(let Z of m)j.push(Z.text);for(let Z of y)j.push(Z.text);for(let Z of w)j.push(Z.text);let se=j.join(`
|
|
194
|
+
`);if(se&&T.size>0){let Z=ic(se);for(let ge of T.keys())if(Z.has(ge))b.add(ge)}for(let Z of C)if(T.has(Z))b.add(Z);for(let Z of o){if(Z.isSideEffect){let Y=Z.text.trim(),te=Y.endsWith(";")?Y:`${Y};`;F.push(te);continue}let ge=dp(Z.text);if(!ge)continue;let{defaultName:De,namedItems:ie,source:ce,isTypeOnly:ee,isNamespace:W}=ge,H=De?b.has(De):!1,J="",z=0;for(let Y=0;Y<ie.length;Y++){let te=ie[Y],oe=te.charCodeAt(0)===116&&te.startsWith("type ")?te.slice(5).trim():te.trim(),ne=oe.indexOf(" as ");if(ne!==-1)oe=oe.slice(ne+4).trim();if(b.has(oe)){if(z>0)J+=", ";J+=te,z++}}if(H||z>0){let Y=ee?"import type ":"import ";if(H&&De)if(W)Y+=`* as ${De}`;else Y+=z>0?`${De}, { ${J} }`:De;else if(z>0)Y+=`{ ${J} }`;Y+=` from '${ce}';`,F.push(Y)}}let he=n.length;if(F.length>1){if(nc!==n)nc=n,sc=n.map((ie)=>`from '${ie}`),oc=n.map((ie)=>`from "${ie}`);let Z=sc,ge=oc,De=new Map;for(let ie of F){let ce=he;for(let ee=0;ee<n.length;ee++)if(ie.includes(Z[ee])||ie.includes(ge[ee])){ce=ee;break}De.set(ie,ce)}F.sort((ie,ce)=>{let ee=De.get(ie),W=De.get(ce);return ee!==W?ee-W:ie.localeCompare(ce)})}}for(let b=0;b<F.length;b++){if(i)i+=`
|
|
195
|
+
`;i+=F[b]}for(let b=0;b<x.length;b++){if(i)i+=`
|
|
196
|
+
`;i+=x[b]}let N=[l,c,f,u,a,m,y];for(let b=0;b<N.length;b++){let j=N[b];for(let se=0;se<j.length;se++){let he=j[se],Z="",ge=he.kind;switch(ge){case"function":Z=op(he,r);break;case"variable":Z=ec(he,r);break;case"interface":Z=ap(he,r);break;case"type":Z=lp(he,r);break;case"class":Z=cp(he,r);break;case"enum":Z=fp(he,r);break;case"module":case"namespace":Z=up(he,r);break;case"import":case"export":case"unknown":break;default:rc(ge,`Unhandled declaration kind in processor: ${ge}`)}if(Z){if(i)i+=`
|
|
197
|
+
`;i+=Z}}}for(let b=0;b<k.length;b++){if(i)i+=`
|
|
198
|
+
`;i+=k[b]}for(let b=0;b<L.length;b++){if(i)i+=`
|
|
199
|
+
`;i+=L[b]}if(!i&&(o.length>0||w.length>0))return"export {};";return i}var ep,tp,rp,Bt,gp,nc=null,sc,oc;var lc=de(()=>{Ts();ep=/^\/\/\/\s*<reference\s+(?:path|types|lib|no-default-lib)\s*=\s*["'][^"']+["']\s*\/>/,tp=/^\/\/\/\s*<amd-module\s+name\s*=\s*["'][^"']+["']\s*\/>/,rp=/^\/\/\/\s*<amd-dependency\s+path\s*=\s*["'][^"']+["']/;Bt=new Map;gp=/export\s+(?:type\s+)?\{\s*([^}]+)\s*\}/,sc=[],oc=[]});function _e(e){return e===ke||e===Me||e===ve||e===Te}function wp(e){let t=!0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n===pt){if(t)return!1;t=!0}else if(t){if(!gt(n))return!1;t=!1}else if(!Ve(n))return!1}return e.length>0&&!t}function _i(e,t,r){let n=t+1;while(n<e.length){let i=e.charCodeAt(n);if(i===rt){n+=2;continue}if(n++,i===r)break}return n}function $p(e){if(e==="any"||e==="object"||e==="unknown")return!0;if(e.startsWith("Record<")||e.startsWith("Array<"))return!0;return e.charCodeAt(0)===K&&e.includes("[")&&e.includes("]:")}function uc(e,t,r=!0){return dc(e,t,r,!0)}function hc(e,t,r=!0){return dc(e,t,r,!1)}function dc(e,t,r,n){let i=e,s=r,o=n,l=i.length,c=[],f=new Map,u=new Set,a=0;if(a<l&&i.charCodeAt(a)===65279)a++;function m(d,p){if(d<p){let h=i.charCodeAt(d),g=i.charCodeAt(p-1);if(h!==ke&&h!==Me&&h!==ve&&h!==Te&&g!==ke&&g!==Me&&g!==ve&&g!==Te)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 y=/[\r\n]/g;function w(d){return y.lastIndex=d,y.exec(i)?.index??l}function C(){if(a>=l)return;let d=i.charCodeAt(a);if(d!==ke&&d!==Me&&d!==ve&&d!==Te&&d!==Q)return;while(a<l){let p=i.charCodeAt(a);if(p===ke||p===Me||p===ve||p===Te){a++;continue}if(p===Q&&a+1<l){let h=i.charCodeAt(a+1);if(h===Q){a=w(a+2);continue}if(h===xe){let g=i.indexOf("*/",a+2);a=g===-1?l:g+2;continue}}break}}function x(d){let p=d.length,h=0,g=p;for(let v=0;v<p;v++){let E=d.charCodeAt(v);if(h){if(E===rt){v++;continue}if(E===h)h=0;continue}if(E===le||E===ue||E===Fe){h=E;continue}if(E===Q&&v+1<p){let O=d.charCodeAt(v+1);if(O===Q){g=v;while(g>0&&(d.charCodeAt(g-1)===ke||d.charCodeAt(g-1)===Me))g--;return d.slice(0,g)}if(O===xe){let R=d.indexOf("*/",v+2);if(R!==-1){d=`${d.slice(0,v)} ${d.slice(R+2)}`,v--;continue}}}}g=p;while(g>0&&(d.charCodeAt(g-1)===ke||d.charCodeAt(g-1)===Me||d.charCodeAt(g-1)===Te))g--;return g<p?d.slice(0,g):d}function k(d){a++;let p=d===le?"'":'"';while(a<l){let h=i.indexOf(p,a);if(h===-1){a=l;return}let g=0,v=h-1;while(v>=0&&i.charCodeAt(v)===rt)g++,v--;if(g%2===0){a=h+1;return}a=h+1}}function L(){a++;let d=[];while(a<l){let p=i.charCodeAt(a);if(d.length===0){if(p===rt){a+=2;continue}if(p===Fe){a++;return}if(p===Cp&&a+1<l&&i.charCodeAt(a+1)===K){a+=2,d.push(0);continue}a++;continue}if(p===le||p===ue){k(p);continue}if(p===Fe){L();continue}if(p===Q&&a+1<l){let h=i.charCodeAt(a+1);if(h===Q){a=w(a+2);continue}if(h===xe){let g=i.indexOf("*/",a+2);a=g===-1?l:g+2;continue}if(D()){F();continue}a++;continue}if(p===K){d[d.length-1]++,a++;continue}if(p===X){let h=d[d.length-1];if(h===0){d.pop(),a++;continue}d[d.length-1]=h-1,a++;continue}a++}}let G=!1;function T(){G=!1;let d=i.charCodeAt(a);if(d===le||d===ue)return k(d),!0;if(d===Fe)return L(),!0;if(d===Q&&a+1<l){let p=i.charCodeAt(a+1);if(p===Q)return a=w(a+2),!0;if(p===xe){let h=i.indexOf("*/",a+2);return G=w(a+2)<(h===-1?l:h),a=h===-1?l:h+2,!0}if(D())return F(),!0}return!1}function D(){return Ur(i,a)}function F(){a=pr(i,a)}function N(){let d=a;while(a<l&&Ve(i.charCodeAt(a)))a++;return i.slice(d,a)}function b(d){if(a+d.length>l)return!1;for(let p=0;p<d.length;p++)if(i.charCodeAt(a+p)!==d.charCodeAt(p))return!1;if(a+d.length<l&&Ve(i.charCodeAt(a+d.length)))return!1;return!0}function j(d){let p=a+d;while(p<l){let h=i.charCodeAt(p);if(h===ke||h===Me||h===ve||h===Te){p++;continue}return h!==pt&&h!==be}return!1}function se(){if(!G)return!1;let d=a;C();let p=a>=l||he()||i.charCodeAt(a)===X;return a=d,p}function he(){if(a>=l)return!1;switch(i.charCodeAt(a)){case 101:return b("export")||b("enum");case 105:return b("import")||b("interface");case 102:return b("function");case 99:return b("class")||b("const");case 116:return b("type");case 108:return b("let");case 118:return b("var");case 100:return b("declare")||b("default");case 109:return b("module");case 110:return b("namespace");case 97:return b("abstract")||b("async");default:return!1}}function Z(){let d=i.charCodeAt(a);if(d!==ve&&d!==Te)return!1;let p=a;if(a++,d===Te&&a<l&&i.charCodeAt(a)===ve)a++;while(a<l){let g=i.charCodeAt(a);if(g===ke||g===Me||g===Te||g===ve){a++;continue}if(g===Q&&a+1<l){let v=i.charCodeAt(a+1);if(v===Q){a=w(a+2);continue}if(v===xe){let E=i.indexOf("*/",a+2);a=E===-1?l:E+2;continue}}break}let h=a>=l||he()||i.charCodeAt(a)===X;return a=p,h}function ge(d){let p=d-1;while(p>=0){let S=i.charCodeAt(p);if(S===ke||S===Me||S===Te||S===ve){p--;continue}break}if(p<0)return!0;let h=i[p];if("+-*/%=<>&|^!~?:,.([{".includes(h))return!0;let g=p;while(g>0&&i.charCodeAt(g-1)!==ve)g--;let v=i.slice(g,p+1),E=v.lastIndexOf("<");if(E!==-1&&/^<[A-Za-z]/.test(v.slice(E))&&!v.slice(E).includes(">"))return!0;let O=p;while(O>=0&&/[a-z]/i.test(i[O]))O--;let R=i.slice(O+1,p+1);return["as","in","of","new","typeof","keyof","extends","instanceof","satisfies","await","return","yield","void"].includes(R)}function De(){let d=i.charCodeAt(a);if(d!==ve&&d!==Te)return!1;if(ge(a))return!1;let p=a;a++;while(a<l){let E=i.charCodeAt(a);if(E===ke||E===Me||E===Te||E===ve){a++;continue}if(E===Q&&a+1<l){let O=i.charCodeAt(a+1);if(O===Q){a=w(a+2);continue}if(O===xe){let R=i.indexOf("*/",a+2);a=R===-1?l:R+2;continue}}break}let h=a<l?i[a]:"",g=i.slice(a,a+2),v=h==="."||h==="?"||h===":"||h===")"||h==="]"||h==="}"||h===","||h==="+"||h==="-"||h==="*"||h==="/"||h==="%"||h==="<"||h===">"||h==="="||h==="&"||h==="|"||h==="^"||h==="`"||g==="=>"||b("as")||b("satisfies")||b("instanceof")||b("in");return a=p,!v}function ie(){let d=i.charCodeAt(a);if(d!==ve&&d!==Te)return!1;if(ge(a))return!1;let p=a;a++;while(a<l){let v=i.charCodeAt(a);if(v===ke||v===Me||v===Te||v===ve){a++;continue}if(v===Q&&a+1<l){let E=i.charCodeAt(a+1);if(E===Q){a=w(a+2);continue}if(E===xe){let O=i.indexOf("*/",a+2);a=O===-1?l:O+2;continue}}break}let h=a<l?i[a]:"",g=h==="|"||h==="&"||h==="["||h==="."||h==="?"||h===":"||h===">"||h===")"||h===","||b("extends");return a=p,!g}function ce(){let d=i.charCodeAt(a);if(d!==ve&&d!==Te)return!1;let p=a;if(a++,d===Te&&a<l&&i.charCodeAt(a)===ve)a++;while(a<l){let g=i.charCodeAt(a);if(g===ke||g===Me||g===Te||g===ve){a++;continue}if(g===Q&&a+1<l&&i.charCodeAt(a+1)===Q){a=w(a+2);continue}break}if(a>=l)return a=p,!0;let h=i.charCodeAt(a);if(h===124||h===38||h===pt||h===Bi||h===lt)return a=p,!1;if(b("extends")||b("keyof")||b("typeof")||b("infer")||b("is")||b("as")||b("in"))return a=p,!1;return a=p,!0}let ee=/[{}'"`\/]/g,W=/[()'"`\/]/g,H=/[[\]'"`\/]/g,J=/[<>'"`\/]/g;function z(d,p){let h=1;a++;let g=d===K?ee:d===ae?W:d===Ae?H:J;g.lastIndex=a;let v;while((v=g.exec(i))!==null){let E=v.index,O=i.charCodeAt(E);if(O===le||O===ue){a=E,k(O),g.lastIndex=a;continue}if(O===Fe){a=E,L(),g.lastIndex=a;continue}if(O===Q){if(a=E,T()){g.lastIndex=a;continue}g.lastIndex=E+1;continue}if(O===d)h++;else if(O===p){if(p===me&&E>0&&i.charCodeAt(E-1)===be){g.lastIndex=E+1;continue}if(h--,h===0)return a=E+1,a}g.lastIndex=E+1}return a=l,a}function Y(){return a>0&&i.charCodeAt(a-1)===be}function te(){return a+1<l&&i.charCodeAt(a+1)===me}let oe=/[<{};'"`\/\n\r()[\]]/g;function ne(d=!1){let p=0,h=0,g=0,v=0,E=i.charCodeAt(a)===K;oe.lastIndex=a;let O;while((O=oe.exec(i))!==null){let R=O.index,S=i.charCodeAt(R);if(S===le||S===ue){a=R,k(S),oe.lastIndex=a;continue}if(S===Fe){a=R,L(),oe.lastIndex=a;continue}if(S===Q){if(R>0&&i.charCodeAt(R-1)===$e){oe.lastIndex=R+1;continue}if(a=R,T()){if(p===0&&h===0&&g===0&&v===0&&se())return;oe.lastIndex=a;continue}oe.lastIndex=R+1;continue}if(S===$e){let A=eo(R);if(A!==null)v=Math.max(0,v+A);oe.lastIndex=R+1;continue}if(S===ae){h++,oe.lastIndex=R+1;continue}if(S===Se){h--,oe.lastIndex=R+1;continue}if(S===Ae){g++,oe.lastIndex=R+1;continue}if(S===Pe){g--,oe.lastIndex=R+1;continue}if(S===K){p++,oe.lastIndex=R+1;continue}if(S===X){let A=p>0;if(!A&&d&&h===0&&g===0&&v===0){a=R;return}if(A)p--;if((!A||E)&&p===0&&h===0&&g===0&&v===0){a=R+1;return}oe.lastIndex=R+1;continue}if(S===re&&p===0&&h===0&&g===0&&v===0){a=R+1;return}if((S===ve||S===Te)&&p===0&&h===0&&g===0&&v===0){if(a=R,Z())return}oe.lastIndex=R+1}a=l}function qi(){a++;while(a<l&&(i.charCodeAt(a)===ke||i.charCodeAt(a)===Me))a++;let d=i.indexOf(`
|
|
200
|
+
`,a),p=d===-1?l:d,h=i.indexOf(";",a);if(h!==-1&&h<p){let g=h-1;while(g>=a&&(i.charCodeAt(g)===ke||i.charCodeAt(g)===Me))g--;let v=i.charCodeAt(a),E=i.charCodeAt(g);if(v===K&&E===X||v===Ae&&E===Pe||v===le&&E===le||v===ue&&E===ue||v===Fe&&E===Fe){a=h+1;return}}ne()}function Ys(){z(K,X);while(a<l&&_e(i.charCodeAt(a)))a++;if(b("from")){a+=4;while(a<l&&_e(i.charCodeAt(a)))a++;if(a<l){let d=i.charCodeAt(a);if(d===le||d===ue)k(d)}}while(a<l&&(i.charCodeAt(a)===ke||i.charCodeAt(a)===Me))a++;if(a<l&&i.charCodeAt(a)===re)a++}function Js(){a++;while(a<l&&_e(i.charCodeAt(a)))a++;if(b("as")){a+=2;while(a<l&&_e(i.charCodeAt(a)))a++;N();while(a<l&&_e(i.charCodeAt(a)))a++}if(b("from")){a+=4;while(a<l&&_e(i.charCodeAt(a)))a++;if(a<l){let d=i.charCodeAt(a);if(d===le||d===ue)k(d)}}while(a<l&&(i.charCodeAt(a)===ke||i.charCodeAt(a)===Me))a++;if(a<l&&i.charCodeAt(a)===re)a++}function Nr(d){let p=d.indexOf("from ");if(p===-1)return;let h=p+5;while(h<d.length&&(d.charCodeAt(h)===32||d.charCodeAt(h)===9))h++;if(h>=d.length)return;let g=d.charCodeAt(h);if(g!==39&&g!==34)return;let v=d.indexOf(d[h],h+1);if(v===-1)return;return d.slice(h+1,v)}function Qe(d){if(!s)return;let p=d-1;while(p>=0&&_e(i.charCodeAt(p)))p--;if(p<0)return;let h=[],g=!1;while(p>=0){if(p>=1&&i.charCodeAt(p)===Q&&i.charCodeAt(p-1)===xe){let O=i.lastIndexOf("/*",p-2);if(O>=0){h.push(i.slice(O,p+1)),g=!0,p=O-1;while(p>=0&&_e(i.charCodeAt(p)))p--;continue}break}let v=p;while(v>0&&i.charCodeAt(v-1)!==ve)v--;let E=m(v,p+1);if(E.startsWith("//")){if(g)break;let O=[E];p=v-1;while(p>=0&&(i.charCodeAt(p)===ve||i.charCodeAt(p)===Te))p--;while(p>=0){let R=p;while(R>0&&i.charCodeAt(R-1)!==ve)R--;let S=m(R,p+1);if(S.startsWith("//")){O.push(S),p=R-1;while(p>=0&&(i.charCodeAt(p)===ve||i.charCodeAt(p)===Te))p--}else if(S===""){p=R-1;while(p>=0&&(i.charCodeAt(p)===ve||i.charCodeAt(p)===Te))p--}else break}O.reverse(),h.push(O.join(`
|
|
201
|
+
`));continue}break}if(h.length===0)return;return h.reverse(),h}function Jc(d){let p=d,h=!1;while(a<l){let S=i.charCodeAt(a);if(S===re){a++;break}if(S===le||S===ue){k(S),h=!0;while(a<l&&(i.charCodeAt(a)===ke||i.charCodeAt(a)===Me))a++;if(a<l&&i.charCodeAt(a)===re)a++;break}if(S===ve&&h)break;a++}let g=m(p,a),v=g.charCodeAt(7)===116&&(g.startsWith("import type ")||g.startsWith("import type{")),E=!1;{let S=6;while(S<g.length&&(g.charCodeAt(S)===ke||g.charCodeAt(S)===Me))S++;if(S<g.length&&g.charCodeAt(S)===116&&g.startsWith("type",S)){S+=4;while(S<g.length&&(g.charCodeAt(S)===ke||g.charCodeAt(S)===Me))S++}if(S<g.length){let A=g.charCodeAt(S);E=A===le||A===ue}}let O="";{let S=g.indexOf("from ");if(S!==-1){let A=S+5;while(A<g.length&&(g.charCodeAt(A)===ke||g.charCodeAt(A)===Me))A++;if(A<g.length){let P=g.charCodeAt(A);if(P===le||P===ue){let _=g.indexOf(String.fromCharCode(P),A+1);if(_!==-1)O=g.slice(A+1,_)}}}else if(E){let A=6;while(A<g.length&&g.charCodeAt(A)!==le&&g.charCodeAt(A)!==ue)A++;if(A<g.length){let P=g.charCodeAt(A),_=g.indexOf(String.fromCharCode(P),A+1);if(_!==-1)O=g.slice(A+1,_)}}}let R=Qe(p);return{kind:"import",name:"",text:g,isExported:!1,isTypeOnly:v,isSideEffect:E,source:O,leadingComments:R,start:p,end:a}}function zi(){let d=a;return z(K,X),i.slice(d,a)}function qs(d){let p=d.indexOf("(");if(p===-1)return d;let h=d.slice(p);if(h.indexOf("=")===-1)return d;let g=!1;for(let S=0;S<h.length;S++)if(h.charCodeAt(S)===61){let A=S>0?h.charCodeAt(S-1):0,P=S+1<h.length?h.charCodeAt(S+1):0;if(A!==61&&A!==33&&A!==60&&A!==62&&P!==61&&P!==62){g=!0;break}}if(!g)return d;let v=0,E=-1;for(let S=p;S<d.length;S++){let A=d.charCodeAt(S);if(A===40)v++;else if(A===41){if(v--,v===0){E=S;break}}}if(E===-1)return d;let O=d.slice(p,E+1),R=_t(O);return d.slice(0,p)+R+d.slice(E+1)}function zs(d){let p=d.indexOf("//")!==-1||d.indexOf("/*")!==-1,h=d.split(`
|
|
202
|
+
`),g=[],v=[],E=[],O=!1,R=1/0;for(let P=0;P<h.length;P++){let _=h[P];if(p){if(O){if(_.includes("*/"))O=!1;continue}let B=_.trim();if(B.length===0)continue;let I=B.charCodeAt(0);if(I===Q){let Ze=B.charCodeAt(1);if(Ze===Q)continue;if(Ze===xe){if(!B.includes("*/"))O=!0;continue}}if(I===xe)continue;let M=x(_);if(M.charCodeAt(M.length-1)===re)M=M.slice(0,-1);M=qs(M);let U=M.trim();if(!U)continue;g.push(M),v.push(U);let V=0;while(V<M.length&&_e(M.charCodeAt(V)))V++;if(U!=="{"&&U!=="}"){if(V<R)R=V}E.push(V)}else{let B=_.length;while(B>0&&(_.charCodeAt(B-1)===ke||_.charCodeAt(B-1)===Me||_.charCodeAt(B-1)===Te))B--;if(B===0)continue;let I=B<_.length?_.slice(0,B):_;if(I.charCodeAt(I.length-1)===re)I=I.slice(0,-1);I=qs(I);let M=I.trim();if(!M)continue;g.push(I),v.push(M);let U=0;while(U<I.length&&_e(I.charCodeAt(U)))U++;if(M!=="{"&&M!=="}"){if(U<R)R=U}E.push(U)}}if(g.length===0)return"{}";if(R===1/0||R<=2)return g.join(`
|
|
203
|
+
`);let S=R-2,A=Array(g.length);for(let P=0;P<g.length;P++){let _=v[P];if(_==="{"){A[P]=_;continue}let B=E[P];if(B>R)A[P]=g[P];else if(B===R&&(_.charCodeAt(0)===X||_.charCodeAt(0)===Pe||_.charCodeAt(0)===Se))A[P]=g[P];else{let I=Math.max(0,B-S);A[P]=" ".repeat(I)+_}}return A.join(`
|
|
204
|
+
`)}function dt(){if(a>=l||i.charCodeAt(a)!==$e)return"";let d=a;z($e,me);let p=i.slice(d,a);if(p.includes(`
|
|
205
|
+
`)){let h="",g=!1;for(let v=0;v<p.length;v++){let E=p.charCodeAt(v);if(E===32||E===9||E===10||E===13){if(!g&&h.length>0)h+=" ",g=!0}else h+=p[v],g=!1}if(h.charCodeAt(1)===32)h=`<${h.slice(2)}`;if(h.charCodeAt(h.length-2)===32)h=`${h.slice(0,-2)}>`;return h}return p}function xt(){if(a>=l||i.charCodeAt(a)!==ae)return"()";let d=a;return z(ae,Se),i.slice(d,a)}function Wr(d){if(d.indexOf("/")===-1)return d;let p="",h=!1,g=0;for(let v=0;v<d.length;v++){let E=d.charCodeAt(v);if(h){if(p+=d[v],E===rt&&v+1<d.length){p+=d[++v];continue}if(E===g)h=!1;continue}if(E===le||E===ue||E===Fe){h=!0,g=E,p+=d[v];continue}if(E===Q&&v+1<d.length){let O=d.charCodeAt(v+1);if(O===xe){let R=d.indexOf("*/",v+2);v=R===-1?d.length:R+1,p+=" ";continue}if(O===Q){let R=d.indexOf(`
|
|
206
|
+
`,v+2);v=R===-1?d.length:R-1;continue}}p+=d[v]}return p.trim()}function _t(d){let p=d.slice(1,-1).trim();if(!p)return"()";if(d.indexOf(`
|
|
207
|
+
`)===-1&&p.indexOf(":")!==-1&&p.indexOf("{")===-1&&p.indexOf("[")===-1&&p.indexOf("=")===-1&&p.indexOf("@")===-1&&p.indexOf("...")===-1){let S=0,A=0,P=0;for(let _=0;_<p.length;_++){let B=p.charCodeAt(_);if(B===ae||B===$e||B===K)P++;else if(B===Se||B===me||B===X)P--;else if(P===0){if(B===lt)S++;else if(B===ht)A++}}if(S>=A+1){let _=!1;for(let B=0;B<Rs.length;B++){let I=Rs[B],M=p.indexOf(I);if(M!==-1){let U=M+I.length;if((M===0||!Ve(p.charCodeAt(M-1)))&&(U>=p.length||!Ve(p.charCodeAt(U)))){_=!0;break}}}if(!_)return d}}let h=[],g=0,v=0,E=!1,O=0;for(let S=0;S<=p.length;S++){if(S===p.length){h.push(Wr(p.slice(g).trim()));break}let A=p.charCodeAt(S);if(E){if(A===rt){S++;continue}if(A===O)E=!1;continue}if(A===Q&&S+1<p.length){let P=p.charCodeAt(S+1);if(P===xe){S+=2;while(S+1<p.length&&!(p.charCodeAt(S)===xe&&p.charCodeAt(S+1)===Q))S++;S++;continue}if(P===Q){while(S<p.length&&p.charCodeAt(S)!==10)S++;continue}}if(A===le||A===ue||A===Fe){E=!0,O=A;continue}if(A===ae||A===K||A===Ae||A===$e)v++;else if(A===Se||A===X||A===Pe||A===me&&!(S>0&&p.charCodeAt(S-1)===be))v--;else if(A===ht&&v===0)h.push(Wr(p.slice(g,S).trim())),g=S+1}let R=[];for(let S of h){if(!S)continue;let A=S.trim();if(A.startsWith("//")||A.startsWith("/*"))continue;let P=S;{let _=!1,B=0,I=0,M=0;for(let U=0;U<P.length-1;U++){let V=P.charCodeAt(U);if(V===ve){M=U+1;continue}if(_){if(V===rt){U++;continue}if(V===B)_=!1;continue}if(V===le||V===ue||V===Fe){_=!0,B=V;continue}if(V===K||V===Ae||V===ae||V===$e){I++;continue}if(V===X||V===Pe||V===Se||V===me){if(I>0)I--;continue}if(V===Q&&P.charCodeAt(U+1)===Q){if(I===0){P=P.slice(0,U).trimEnd();break}let Ze=P.indexOf(`
|
|
208
|
+
`,U);if(Ze===-1){P=P.slice(0,M).trimEnd();break}let Ye=P.slice(0,M),Ht=P.slice(Ze+1);P=`${Ye}${Ht}`,U=M-1}}}if(!P.trim())continue;R.push(Xs(P))}return`(${R.join(", ")})`}function qc(d){if(!d.startsWith("{")&&!d.startsWith("["))return d;let p="",h=0,g=0,v=!1,E=0;while(h<d.length){let O=d.charCodeAt(h);if(v){if(O===rt&&h+1<d.length){p+=d[h]+d[h+1],h+=2;continue}if(O===E)v=!1;p+=d[h],h++;continue}if(O===Q&&h+1<d.length){let R=d.charCodeAt(h+1);if(R===xe){let S=h;h+=2;while(h+1<d.length&&!(d.charCodeAt(h)===xe&&d.charCodeAt(h+1)===Q))h++;h=Math.min(h+2,d.length),p+=d.slice(S,h);continue}if(R===Q){let S=h;while(h<d.length&&d.charCodeAt(h)!==10)h++;p+=d.slice(S,h);continue}}if(O===le||O===ue||O===Fe){v=!0,E=O,p+=d[h],h++;continue}if(O===K||O===Ae||O===ae)g++;else if(O===X||O===Pe||O===Se)g--;if(g>=1&&O===be&&(h+1>=d.length||d.charCodeAt(h+1)!==be&&d.charCodeAt(h+1)!==me)){while(p.length>0&&(p[p.length-1]===" "||p[p.length-1]==="\t"||p[p.length-1]===`
|
|
209
|
+
`))p=p.slice(0,-1);h++;let R=0;while(h<d.length){let S=d.charCodeAt(h);if(S===le||S===ue||S===Fe){let A=S;h++;while(h<d.length){if(d.charCodeAt(h)===rt){h+=2;continue}if(d.charCodeAt(h)===A){h++;break}h++}continue}if(S===K||S===Ae||S===ae)R++;else if(S===X||S===Pe||S===Se){if(R===0)break;R--}else if(S===ht&&R===0)break;h++}continue}if(g===1&&O===pt&&h+2<d.length&&d.charCodeAt(h+1)===pt&&d.charCodeAt(h+2)===pt){h+=3;continue}p+=d[h],h++}return p}function Xs(d){let p=d.trim(),h=p.startsWith("...");if(h)p=p.slice(3).trim();while(p.startsWith("@")){let M=1;while(M<p.length&&Ve(p.charCodeAt(M)))M++;if(M<p.length&&p.charCodeAt(M)===ae){let U=1;M++;while(M<p.length&&U>0){if(p.charCodeAt(M)===ae)U++;else if(p.charCodeAt(M)===Se)U--;M++}}p=p.slice(M).trim()}let g=!0;while(g){g=!1;for(let M of Rs)if(p.startsWith(M)&&p.length>M.length&&!Ve(p.charCodeAt(M.length))){let U=p.slice(M.length).trim();if(U.charCodeAt(0)===lt||U.charCodeAt(0)===Bi&&U.length>1&&U.charCodeAt(1)===lt)break;p=U,g=!0;break}}let v=-1,E=-1,O=0,R=!1,S=0;for(let M=0;M<p.length;M++){let U=p.charCodeAt(M);if(R){if(U===rt){M++;continue}if(U===S)R=!1;continue}if(U===Q&&M+1<p.length){let V=p.charCodeAt(M+1);if(V===xe){M+=2;while(M+1<p.length&&!(p.charCodeAt(M)===xe&&p.charCodeAt(M+1)===Q))M++;M++;continue}if(V===Q){while(M<p.length&&p.charCodeAt(M)!==10)M++;continue}}if(U===le||U===ue||U===Fe){R=!0,S=U;continue}if(U===ae||U===K||U===Ae||U===$e)O++;else if(U===Se||U===X||U===Pe||U===me&&!(M>0&&p.charCodeAt(M-1)===be))O--;else if(O===0){if(U===lt&&v===-1)v=M;else if(U===be&&E===-1&&(M===0||p.charCodeAt(M-1)!==be)&&(M+1>=p.length||p.charCodeAt(M+1)!==be&&p.charCodeAt(M+1)!==me))E=M}}let A,P,_=E!==-1;if(v!==-1&&(E===-1||v<E))if(A=p.slice(0,v).trim(),E!==-1)P=p.slice(v+1,E).trim();else P=p.slice(v+1).trim();else if(E!==-1)A=p.slice(0,E).trim(),P=Xi(p.slice(E+1).trim());else A=p,P="unknown";if(A=qc(A),(A.startsWith("{")||A.startsWith("["))&&A.includes(`
|
|
210
|
+
`)){let M=A.replace(/\s*\n\s*/g," ").replace(/\s+/g," ");if(M.length<=40)A=M;else A=A.split(`
|
|
211
|
+
`).map((U)=>{let V=U.trim();if(!V)return"";if(V==="{"||V==="}"||V==="["||V==="]"||V.startsWith("}")||V.startsWith("]"))return V;return` ${V}`}).join(`
|
|
212
|
+
`)}let B=A.endsWith("?")||_;if(A.endsWith("?"))A=A.slice(0,-1).trim();let I=B&&!h?"?":"";if(h)return`...${A}: ${P}`;return`${A}${I}: ${P}`}function Qs(d){let p=0;if(p<d.length&&d.charCodeAt(p)===45)p++;if(p>=d.length)return!1;let h=d.charCodeAt(p);if(h<48||h>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 Xi(d){let p=d.trim();if(p==="true"||p==="false")return"boolean";if(Qs(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 Qi(d){let p=d.trim();if(p.endsWith("as const"))p=p.slice(0,-8).trim();if(p==="true"||p==="false")return p;if(Qs(p))return p;let h=zc(p);if(h!==null)return h;return"unknown"}function zc(d){if(d==="")return null;if(d.charCodeAt(0)===le||d.charCodeAt(0)===ue){if(_i(d,0,d.charCodeAt(0))===d.length)return d}let p=Xc(d,"+");if(p.length>1){let h=!1,g=!0,v=[];for(let E of p){let O=E.trim(),R=O.charCodeAt(0);if((R===le||R===ue)&&_i(O,0,R)===O.length)h=!0,v.push(Qc(O));else g=!1}if(g)return ef(v.join(""));if(h)return"string";return null}if(/^[\d\s()+*/%.\-]+$/.test(d)&&/\d/.test(d)&&/[+*/%\-\s]/.test(d))return"number";return null}function Xc(d,p){let h=[],g=0,v="",E=0;while(E<d.length){let O=d.charCodeAt(E);if(O===le||O===ue||O===Fe){let R=_i(d,E,O);v+=d.slice(E,R),E=R;continue}if(O===Q&&(d.charCodeAt(E+1)===Q||d.charCodeAt(E+1)===42)){if(d.charCodeAt(E+1)===Q){let A=d.indexOf(`
|
|
213
|
+
`,E+2),P=A===-1?d.length:A;v+=d.slice(E,P),E=P;continue}let R=d.indexOf("*/",E+2),S=R===-1?d.length:R+2;v+=d.slice(E,S),E=S;continue}if(O===ae||O===Ae||O===K)g++;else if(O===Se||O===Pe||O===X)g--;if(d[E]===p&&g===0){h.push(v),v="",E++;continue}v+=d[E],E++}return h.push(v),h}function Qc(d){return d.slice(1,-1).replace(/\\(.)/g,(p,h)=>{if(h==="n")return`
|
|
214
|
+
`;if(h==="t")return"\t";if(h==="r")return"\r";if(h==="0")return"\x00";return h})}function ef(d){return`'${d.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function Lr(d){if(d.endsWith("as const"))return null;let p=0,h=-1;for(let g=0;g<d.length;g++){let v=d.charCodeAt(g);if(v===le||v===ue||v===Fe)g=_i(d,g,v)-1;else if(v===123||v===91||v===40)p++;else if(v===125||v===93||v===41)p--;else if(p===0&&v===32&&g+4<=d.length&&d.substring(g,g+4)===" as ")h=g}if(h===-1)return null;return d.slice(h+4).trim()||null}function dr(){if(C(),a<l&&i.charCodeAt(a)===lt){a++,C();let d=a,p=0;while(a<l){if(T())continue;let h=i.charCodeAt(a);if(h===ae||h===Ae||h===$e)p++;else if(h===Se||h===Pe||h===me&&!Y())p--;else if(h===K)if(p>0)p++;else{let g=m(d,a),v=(E)=>{let O=g.length-E.length;return O>=0&&g.endsWith(E)&&(O===0||!Ve(g.charCodeAt(O-1)))};if(g.length===0||g.endsWith("|")||g.endsWith("&")||v("is")||v("extends"))p++;else break}else if(h===X){if(p===0)break;p--}else if(p===0&&h===re)break;if(p===0&&ce())break;a++}return m(d,a)}return""}function Tt(d,p,h,g){a+=8,C();let v=a<l&&i.charCodeAt(a)===xe;if(v)a++,C();let E=N();if(!E&&!g)return null;C();let O=dt();C();let R=xt();C();let S=dr(),A=S.length>0;if(!S)if(h&&v)S="AsyncGenerator<unknown, void, unknown>";else if(v)S="Generator<unknown, void, unknown>";else if(h)S="Promise<void>";else S="void";C();let P=!1;if(a<l&&i.charCodeAt(a)===K){P=!0;let M=a+1;if(z(K,X),!A&&!v)S=fr(i.slice(M,a-1),h,R)}else if(a<l&&i.charCodeAt(a)===re)a++;let _=_t(R),B=`${p?g?"export default function ":"export declare function ":"declare function "}${E||(g?"":"default")}${O}${_}: ${S};`,I=Qe(d);if(P)u.add(c.length);return{kind:"function",name:E||"default",text:B,isExported:p,isDefault:g,isAsync:h,isGenerator:v,returnType:S,generics:O||void 0,leadingComments:I,start:d,end:a}}function Ft(d,p,h){a+=p.length,C();let g=[];do{if(C(),a>=l)break;let v=i.charCodeAt(a);if(v===K||v===Ae)return ne(),g;let E=N();if(!E)return ne(),g;C();let O,R,S=!1;if(a<l&&i.charCodeAt(a)===lt){a++,C();let _=a,B=0;while(a<l){if(T()){if(B===0&&se())break;continue}let I=i.charCodeAt(a);if(I===ae||I===K||I===Ae||I===$e)B++;else if(I===Se||I===X||I===Pe||I===me&&!Y())B--;else if(B===0&&(I===re||I===ht))break;else if(B===0&&I===be&&!te())break;if(B===0&&(Z()||ie()))break;a++}O=m(_,a)}if(a<l&&i.charCodeAt(a)===be)if(o&&O&&(!s||!$p(O)))qi();else{a++,C();let _=a,B=0,I=0,M=0,U=!0;for(;;){a=_,B=0,I=0,M=0;while(a<l){if(T()){if(B===0&&I===0&&M===0&&se())break;continue}let V=i.charCodeAt(a);if(V===ae||V===K||V===Ae)B++;else if(V===Se||V===X||V===Pe)B--;else if(V===$e&&B===0){let Ze=eo(a);if(Ze!==null)M=Math.max(0,M+Ze);else if(U&&(a+1>=l||i.charCodeAt(a+1)!==be))I++}else if(V===me&&B===0&&M===0&&!Y()){if(I>0&&(a+1>=l||i.charCodeAt(a+1)!==be))I--}else if(B===0&&I===0&&M===0&&(V===re||V===ht))break;if(B===0&&I===0&&M===0&&(Z()||De()))break;a++}if(I>0&&U){U=!1;continue}break}if(R=m(_,a),R.endsWith(" as const")||R==="const"){if(S=!0,!O){let V=R.endsWith(" as const")?R.slice(0,-9).trim():R,Ze=Qi(V);O=Ze!=="unknown"?Ze:void 0}}else if(!O){let V=Gi(R)??Lr(R);if(V)O=V}}if(a<l){let _=i.charCodeAt(a);if(_===ht){a++;continue}if(_===re)a++}let A=Qe(d),P=`${h?"export ":""}declare ${p} ${E}: ${O||"unknown"};`;g.push({kind:"variable",name:E,text:P,isExported:h,typeAnnotation:O,value:R,modifiers:S?[p,"const assertion"]:[p],leadingComments:A,start:d,end:a});break}while(a<l);return g}function eo(d){if(i.charCodeAt(d)!==$e||d+1>=l)return null;let p=i.charCodeAt(d+1);if(p===me)return 1;if(p===Q)return-1;if(!gt(p))return null;let h=d+2;while(h<l){let A=i.charCodeAt(h);if(!Ve(A)&&A!==pt&&A!==58&&A!==45)break;h++}let g=i.slice(d+1,h),v=i.charCodeAt(h);if(v>32&&v!==me&&v!==Q)return null;let E=0,O=0,R=h;for(;R<l;R++){let A=i.charCodeAt(R);if(O!==0){if(A===rt)R++;else if(A===O)O=0;continue}if(A===le||A===ue||A===Fe)O=A;else if(A===K)E++;else if(A===X&&E>0)E--;else if(A===me&&E===0)break}if(R>=l)return null;let S=R-1;while(S>d&&i.charCodeAt(S)<=32)S--;if(i.charCodeAt(S)===Q)return 0;return i.indexOf(`</${g}`,R+1)===-1?null:1}function en(d,p){a+=9,C();let h=N();C();let g=dt();C();let v="";if(b("extends")){a+=7,C();let A=a,P=0;while(a<l){if(T())continue;let _=i.charCodeAt(a);if(_===$e)P++;else if(_===me&&!Y())P--;else if(_===K&&P===0)break;a++}v=m(A,a)}C();let E=a<l&&i.charCodeAt(a)===K?zi():"{}",O=zs(E),R=`${p?"export ":""}declare interface ${h}${g}${v?` extends ${v}`:""} ${O}`,S=Qe(d);return{kind:"interface",name:h,text:R,isExported:p,extends:v||void 0,generics:g||void 0,leadingComments:S,start:d,end:a}}function tn(d,p){a+=4,C();let h=N();C();let g=dt();if(C(),a<l&&i.charCodeAt(a)===be)a++;C();let v=a,E=0;while(a<l){if(T())continue;let A=i.charCodeAt(a);if(A===ae||A===K||A===Ae||A===$e)E++;else if(A===Se||A===X||A===Pe||A===me&&!Y())E--;else if(E===0&&A===re)break;if(E===0&&(Z()||ie()))break;a++}let O=m(v,a);if(a<l&&i.charCodeAt(a)===re)a++;let R=`${p?"export ":""}type ${h}${g} = ${O}`,S=Qe(d);return{kind:"type",name:h,text:R,isExported:p,generics:g||void 0,leadingComments:S,start:d,end:a}}function Ut(d,p,h){a+=4,C();let g=N();C();let v=a;if(a<l&&i.charCodeAt(a)===K)z(K,X);let E=m(d,a),O=Qe(d);return{kind:"enum",name:g,text:E,isExported:p,modifiers:h?["const"]:void 0,leadingComments:O,start:d,end:a}}function Ot(d,p,h,g=!1){a+=5,C();let v=N()||"AnonymousClass";C();let E=dt();C();let O="";if(b("extends")){a+=7,C();let _=a,B=0;while(a<l){if(T())continue;let I=i.charCodeAt(a);if(I===$e)B++;else if(I===me&&!Y())B--;else if(B===0&&(I===K||b("implements")))break;a++}O=m(_,a)}let R;if(b("implements")){a+=10,C();let _=a,B=0;while(a<l){if(T())continue;let M=i.charCodeAt(a);if(M===$e)B++;else if(M===me&&!Y())B--;else if(B===0&&M===K)break;a++}let I=m(_,a);if(I)R=I.split(",").map((M)=>M.trim())}C();let S=rn(),A=`${p?g?"export default ":"export declare ":"declare "}${h?"abstract ":""}class ${v}${E}${O?` extends ${O}`:""}${R&&R.length>0?` implements ${R.join(", ")}`:""} ${S}`,P=Qe(d);return{kind:"class",name:v,text:A,isExported:p,isDefault:g,extends:O||void 0,implements:R,generics:E||void 0,modifiers:h?["abstract"]:void 0,leadingComments:P,start:d,end:a}}function rn(){if(a>=l||i.charCodeAt(a)!==K)return"{}";a++;let d=[];while(a<l){if(C(),a>=l)break;if(i.charCodeAt(a)===X){a++;break}if(i.charCodeAt(a)===re){a++;continue}if(b("static")&&sn("static")===K){a+=6,C(),z(K,X);continue}let p=!1,h=!1,g=!1,v=!1,E=!1,O=!1,R=!1,S=!1,A=!0;while(A){C();let B=a,I=N();if(a=B,I){let M=sn(I);if(M===ae||M===$e||M===Bi||M===33||M===lt||M===be||M===re||M===X)break}if(b("private")){p=!0,a+=7;continue}if(b("protected")){h=!0,a+=9;continue}if(b("public")){a+=6;continue}if(b("static")){g=!0,a+=6;continue}if(b("abstract")){v=!0,a+=8;continue}if(b("readonly")){E=!0,a+=8;continue}if(b("override")){O=!0,a+=8;continue}if(b("accessor")){R=!0,a+=8;continue}if(b("async")){S=!0,a+=5;continue}if(b("declare")){a+=7;continue}break}if(C(),a>=l||i.charCodeAt(a)===X)break;if(i.charCodeAt(a)===Os)p=!0;let P=p?[]:d,_=" ";if(h)_+="protected ";if(g)_+="static ";if(v)_+="abstract ";if(E)_+="readonly ";if(b("constructor")){a+=11,C();let B=xt();if(C(),rf(B,P),a<l&&i.charCodeAt(a)===K)z(K,X);else if(a<l&&i.charCodeAt(a)===re)a++;let I=_t(B);P.push(` constructor${I};`)}else if(b("get"))if(a+=3,C(),a<l&&to(i.charCodeAt(a))){let B=nn();if(B.startsWith("#")){if(C(),a<l&&i.charCodeAt(a)===ae)xt();if(C(),dr(),C(),a<l&&i.charCodeAt(a)===K)z(K,X);else if(a<l&&i.charCodeAt(a)===re)a++;continue}C(),xt(),C();let I=dr()||"unknown";if(C(),a<l&&i.charCodeAt(a)===K)z(K,X);else if(a<l&&i.charCodeAt(a)===re)a++;P.push(`${_}get ${B}(): ${I};`)}else io("get",_,g,E,S,P);else if(b("set"))if(a+=3,C(),a<l&&to(i.charCodeAt(a))){let B=nn();if(B.startsWith("#")){if(C(),a<l&&i.charCodeAt(a)===ae)xt();if(C(),a<l&&i.charCodeAt(a)===K)z(K,X);else if(a<l&&i.charCodeAt(a)===re)a++;continue}C();let I=xt();if(C(),a<l&&i.charCodeAt(a)===K)z(K,X);else if(a<l&&i.charCodeAt(a)===re)a++;let M=_t(I);P.push(`${_}set ${B}${M};`)}else io("set",_,g,E,S,P);else{let B=i.charCodeAt(a)===xe;if(B)a++,C();let I=nn();if(!I){ro();continue}no(I,_,g,E,B,v,S,P)}}return`{
|
|
215
|
+
${d.join(`
|
|
216
|
+
`)}
|
|
217
|
+
}`}function to(d){return gt(d)||d===Ae||d===Os||d===le||d===ue}function nn(){if(a>=l)return"";let d=i.charCodeAt(a);if(d===Ae){let p=a;return z(Ae,Pe),i.slice(p,a)}if(d===Os)return a++,`#${N()}`;if(d===le||d===ue){let p=a;return k(d),i.slice(p,a)}return N()}function sn(d){let p=a;a+=d.length,C();let h=a<l?i.charCodeAt(a):0;return a=p,h}function ro(){let d=0;while(a<l){if(T())continue;let p=i.charCodeAt(a);if(p===K||p===ae)d++;else if(p===X||p===Se){if(d===0)return;d--}else if(p===re&&d===0){a++;return}if(d===0&&ce())return;a++}}function io(d,p,h,g,v,E){no(d,p,h,g,!1,!1,v,E)}function no(d,p,h,g,v,E,O,R){if(C(),a>=l)return;let S=i.charCodeAt(a),A=!1;if(S===Bi)A=!0,a++,C();if(a<l&&i.charCodeAt(a)===33)a++,C();let P=a<l?i.charCodeAt(a):0;if(P===ae||P===$e){let _=P===$e?dt():"";C();let B=xt();C();let I=dr(),M=I.length>0;if(!I)if(O&&v)I="AsyncGenerator<unknown, void, unknown>";else if(v)I="Generator<unknown, void, unknown>";else if(O)I="Promise<void>";else I="void";if(C(),a<l&&i.charCodeAt(a)===K){let Ze=a+1;if(z(K,X),!M&&!v)I=fr(i.slice(Ze,a-1),O,B)}else if(a<l&&i.charCodeAt(a)===re)a++;let U=_t(B),V=A?"?":"";R.push(`${p}${d}${V}${_}${U}: ${I};`)}else if(P===lt||P===be||P===re||P===X||P===ve||P===Te){let _="";if(P===lt){a++,C();let M=a,U=0;while(a<l){if(T())continue;let V=i.charCodeAt(a);if(V===ae||V===K||V===Ae||V===$e)U++;else if(V===Se||V===X||V===Pe||V===me&&!Y()){if(U===0)break;U--}else if(U===0&&(V===re||V===ht))break;else if(U===0&&V===be&&!te())break;if(U===0&&ce())break;a++}_=m(M,a)}let B="";if(a<l&&i.charCodeAt(a)===be)if(o&&_){a++;let M=0;while(a<l){if(T())continue;let U=i.charCodeAt(a);if(U===ae||U===K||U===Ae)M++;else if(U===Se||U===X||U===Pe){if(M===0&&U===X)break;M--}else if(M===0&&U===re)break;if(M===0&&ce())break;a++}}else{a++,C();let M=a,U=0;while(a<l){if(T())continue;let V=i.charCodeAt(a);if(V===ae||V===K||V===Ae)U++;else if(V===Se||V===X||V===Pe){if(U===0&&V===X)break;U--}else if(U===0&&V===re)break;if(U===0&&ce())break;a++}B=m(M,a)}if(a<l&&i.charCodeAt(a)===re)a++;if(!_)if(B){let M=Lr(B);if(M)_=M;else _=B.endsWith("as const")||h&&g?Qi(B):Xi(B)}else _="unknown";let I=A?"?":"";R.push(`${p}${d}${I}: ${_};`)}else ro()}function tf(d){let p=0;for(let h=0;h<d.length;h++){let g=d.charCodeAt(h);if(g===ae||g===K||g===Ae||g===$e)p++;else if(g===Se||g===X||g===Pe||g===me&&d.charCodeAt(h-1)!==be)p--;else if(g===be&&p===0&&d.charCodeAt(h+1)!==me&&d.charCodeAt(h+1)!==be)return!0}return!1}function rf(d,p){let h=d.slice(1,-1).trim();if(!h)return;let g=[],v=0,E=0,O=!1,R=0;for(let S=0;S<=h.length;S++){if(S===h.length){g.push(Wr(h.slice(v).trim()));break}let A=h.charCodeAt(S);if(O){if(A===rt){S++;continue}if(A===R)O=!1;continue}if(A===Q&&S+1<h.length){let P=h.charCodeAt(S+1);if(P===xe){S+=2;while(S+1<h.length&&!(h.charCodeAt(S)===xe&&h.charCodeAt(S+1)===Q))S++;S++;continue}if(P===Q){while(S<h.length&&h.charCodeAt(S)!==10)S++;continue}}if(A===le||A===ue||A===Fe){O=!0,R=A;continue}if(A===ae||A===K||A===Ae||A===$e)E++;else if(A===Se||A===X||A===Pe||A===me&&!(S>0&&h.charCodeAt(S-1)===be))E--;else if(A===ht&&E===0)g.push(Wr(h.slice(v,S).trim())),v=S+1}for(let S of g){let A=S.startsWith("public ")||S.startsWith("public\t"),P=S.startsWith("protected ")||S.startsWith("protected\t"),_=S.startsWith("private ")||S.startsWith("private\t"),B=S.includes("readonly ");if(!A&&!P&&!_&&!B)continue;if(_)continue;let I=S,M=[];if(A){let Ye=6;while(Ye<I.length&&_e(I.charCodeAt(Ye)))Ye++;I=I.slice(Ye),M.push("public")}if(P){let Ye=9;while(Ye<I.length&&_e(I.charCodeAt(Ye)))Ye++;I=I.slice(Ye),M.push("protected")}if(B){let Ye=I.indexOf("readonly ");if(Ye!==-1){let Ht=Ye+8;while(Ht<I.length&&_e(I.charCodeAt(Ht)))Ht++;I=I.slice(0,Ye)+I.slice(Ht)}M.push("readonly")}let U=M.length>0?`${M.join(" ")} `:"",V=Xs(I),Ze=I.search(/[?:=]/);if(Ze!==-1&&I.charCodeAt(Ze)!==63&&tf(I))V=V.replace(/^([\w$]+)\?:/,"$1:");p.push(` ${U}${V};`)}}function on(d=" "){if(a>=l||i.charCodeAt(a)!==K)return"{}";a++;let p=[];while(a<l){if(C(),a>=l)break;if(i.charCodeAt(a)===X){a++;break}if(i.charCodeAt(a)===re){a++;continue}let h=!1;if(b("export"))h=!0,a+=6,C();if(b("declare"))a+=7,C();let g=h?"export ":"";if(b("function")||b("async")&&nf("async","function")){let v=!1;if(b("async"))v=!0,a+=5,C();if(a+=8,C(),a<l&&i.charCodeAt(a)===xe)a++,C();let E=N();C();let O=dt();C();let R=xt();C();let S=dr();if(!S)S=v?"Promise<void>":"void";if(C(),a<l&&i.charCodeAt(a)===K)z(K,X);else if(a<l&&i.charCodeAt(a)===re)a++;let A=_t(R);p.push(`${d}${g}function ${E}${O}${A}: ${S};`)}else if(b("const")||b("let")||b("var")){let v=b("const")?"const":b("let")?"let":"var";a+=v.length,C();let E=N();if(!E){ne(!0);continue}C();let O="";if(a<l&&i.charCodeAt(a)===lt){a++,C();let S=a,A=0;while(a<l){if(T())continue;let P=i.charCodeAt(a);if(P===ae||P===K||P===Ae||P===$e)A++;else if(P===X&&A===0)break;else if(P===Se||P===X||P===Pe||P===me&&!Y())A--;else if(A===0&&(P===re||P===ht))break;else if(A===0&&P===be&&!te())break;if(A===0&&Z())break;a++}O=m(S,a)}let R="";if(a<l&&i.charCodeAt(a)===be){a++,C();let S=a,A=0;while(a<l){if(T())continue;let P=i.charCodeAt(a);if(P===ae||P===K||P===Ae||P===$e)A++;else if(P===X&&A===0)break;else if(P===Se||P===X||P===Pe||P===me&&!Y())A--;else if(A===0&&(P===re||P===ht))break;if(A===0&&Z())break;a++}R=m(S,a)}if(a<l&&i.charCodeAt(a)===re)a++;if(!O&&R){let S=Lr(R);if(S)O=S;else if(v==="const")O=Qi(R);else O=Xi(R)}if(!O)O="unknown";p.push(`${d}${g}${v} ${E}: ${O};`)}else if(b("interface")){a+=9,C();let v=N();C();let E=dt();C();let O="";if(b("extends")){a+=7,C();let S=a,A=0;while(a<l){if(T())continue;let P=i.charCodeAt(a);if(P===$e)A++;else if(P===me&&!Y())A--;else if(P===K&&A===0)break;a++}O=m(S,a)}let R=zs(zi());p.push(`${d}${g}interface ${v}${E}${O?` extends ${O}`:""} ${R}`)}else if(b("type")){a+=4,C();let v=N();C();let E=dt();if(C(),a<l&&i.charCodeAt(a)===be){a++,C();let O=a,R=0;while(a<l){if(T())continue;let A=i.charCodeAt(a);if(A===ae||A===K||A===Ae||A===$e)R++;else if(A===X&&R===0)break;else if(A===Se||A===X||A===Pe||A===me&&!Y())R--;else if(R===0&&A===re)break;if(R===0&&Z())break;a++}let S=m(O,a);if(a<l&&i.charCodeAt(a)===re)a++;p.push(`${d}${g}type ${v}${E} = ${S}`)}}else if(b("class")){a+=5,C();let v=N();C();let E=dt();C();let O=a,R=0;while(a<l){if(T())continue;let _=i.charCodeAt(a);if(_===$e)R++;else if(_===me&&!Y())R--;else if(_===K&&R===0)break;a++}let S=m(O,a),A=S?` ${S}`:"",P=rn();p.push(`${d}${g}class ${v}${E}${A} ${P}`)}else if(b("enum")){a+=4,C();let v=N();C();let E=zi();p.push(`${d}${g}enum ${v} ${E}`)}else if(b("namespace")||b("module")){let v=b("namespace")?"namespace":"module";a+=v.length,C();let E=N();C();let O=on(d);p.push(`${d}${g}${v} ${E} ${O}`)}else if(b("abstract"))if(a+=8,C(),b("class")){a+=5,C();let v=N();C();let E=dt();C();let O=a,R=0;while(a<l){if(T())continue;let _=i.charCodeAt(a);if(_===$e)R++;else if(_===me&&!Y())R--;else if(_===K&&R===0)break;a++}let S=m(O,a),A=S?` ${S}`:"",P=rn();p.push(`${d}${g}abstract class ${v}${E}${A} ${P}`)}else ne(!0);else if(h&&b("default")){a+=7,C();let v=a;ne(!0);let E=m(v,a);if(E.charCodeAt(E.length-1)===re)E=E.slice(0,-1);if(E)p.push(`${d}export default ${E};`)}else if(!h&&(i.charCodeAt(a)===le||i.charCodeAt(a)===ue||i.charCodeAt(a)===Fe))ne(!0);else ne(!0)}if(p.length===0)return"{}";return`{
|
|
218
|
+
${p.join(`
|
|
219
|
+
`)}
|
|
220
|
+
}`}function nf(d,p){let h=a+d.length;while(h<l&&_e(i.charCodeAt(h)))h++;for(let g=0;g<p.length;g++)if(h+g>=l||i.charCodeAt(h+g)!==p.charCodeAt(g))return!1;return h+p.length>=l||!Ve(i.charCodeAt(h+p.length))}function Vt(d,p,h){a+=h.length,C();let g="",v=i.charCodeAt(a);if(v===le||v===ue){let A=a;k(v),g=i.slice(A,a)}else{g=N();while(a<l&&i.charCodeAt(a)===pt)a++,g+=`.${N()}`}C();let E=a<l&&i.charCodeAt(a)===K?on():"{}",O=`${p?"export ":""}declare ${h} ${g} ${E}`,R=Qe(d),S=g.startsWith("'")||g.startsWith('"');return{kind:"module",name:g,text:O,isExported:p,source:S?g.slice(1,-1):void 0,leadingComments:R,start:d,end:a}}function so(d,p){ne();let h=m(p,a);if(h.charCodeAt(h.length-1)===re)h=h.slice(0,-1).trimEnd();if(!h)return;let g=gt(h.charCodeAt(0));for(let A=1;g&&A<h.length;A++)g=Ve(h.charCodeAt(A));let v=Qe(d);if(g){c.push({kind:"export",name:"default",text:`export default ${h};`,isExported:!0,isTypeOnly:!1,leadingComments:v,start:d,end:a});return}let E="__dtsx_default_export__",O=1;while(i.includes(E))E=`__dtsx_default_export_${O++}__`;let R=Lr(h)||Ie(h,!1),S=R==="unknown"&&wp(h)?`typeof ${h}`:R;c.push({kind:"variable",name:E,text:`declare const ${E}: ${S};`,isExported:!1,typeAnnotation:S,modifiers:["const"],start:d,end:a}),c.push({kind:"export",name:"default",text:`export default ${E};`,isExported:!0,isTypeOnly:!1,leadingComments:v,start:d,end:a})}while(a<l){if(C(),a>=l)break;let d=a,p=i.charCodeAt(a);if(p===105&&b("import"))c.push(Jc(d));else if(p===101&&b("export")){a+=6,C();let h=i.charCodeAt(a);if(h===100&&b("default")){a+=7,C();let g=a,v=i.charCodeAt(a);if(v===102&&b("function")){let E=Tt(d,!0,!1,!0);if(E)c.push(E)}else if(v===97&&b("async")&&sn("async")!==re)if(a+=5,C(),b("function")){let E=Tt(d,!0,!0,!0);if(E)c.push(E)}else so(d,g);else if(v===99&&b("class")){let E=Ot(d,!0,!1,!0);c.push(E)}else if(v===97&&b("abstract")){if(a+=8,C(),b("class")){let E=Ot(d,!0,!0,!0);c.push(E)}}else so(d,g)}else if(h===116&&b("type")){let g=a;if(a+=4,C(),a<l&&i.charCodeAt(a)===K){Ys();let v=m(d,a),E=Qe(d);c.push({kind:"export",name:"",text:v,isExported:!0,isTypeOnly:!0,source:Nr(v),leadingComments:E,start:d,end:a})}else if(a<l&&i.charCodeAt(a)===xe){Js();let v=m(d,a);c.push({kind:"export",name:"",text:v,isExported:!0,isTypeOnly:!0,source:Nr(v),start:d,end:a})}else{a=g;let v=tn(d,!0);c.push(v)}}else if(h===105&&b("interface")){let g=en(d,!0);c.push(g)}else if(h===102&&b("function")){let g=Tt(d,!0,!1,!1);if(g)c.push(g)}else if(h===97&&b("async"))if(a+=5,C(),b("function")){let g=Tt(d,!0,!0,!1);if(g)c.push(g)}else ne();else if(h===99)if(b("class")){let g=Ot(d,!0,!1);c.push(g)}else if(b("const")){let g=a;if(a+=5,C(),b("enum")){a=g+5,C();let v=Ut(d,!0,!0);c.push(v)}else{a=g;let v=Ft(d,"const",!0);for(let E=0;E<v.length;E++)c.push(v[E])}}else ne();else if(h===97&&b("abstract")){if(a+=8,C(),b("class")){let g=Ot(d,!0,!0);c.push(g)}}else if(h===108&&b("let")){let g=Ft(d,"let",!0);for(let v=0;v<g.length;v++)c.push(g[v])}else if(h===118&&b("var")){let g=Ft(d,"var",!0);for(let v=0;v<g.length;v++)c.push(g[v])}else if(h===101&&b("enum")){let g=Ut(d,!0,!1);c.push(g)}else if(h===100&&b("declare"))a+=7,C(),oo(d,!0);else if(h===110&&b("namespace")&&j(9)){let g=Vt(d,!0,"namespace");c.push(g)}else if(h===109&&b("module")&&j(6)){let g=Vt(d,!0,"module");c.push(g)}else if(h===K){Ys();let g=m(d,a),v=g.includes("export type"),E=Qe(d);c.push({kind:"export",name:"",text:g,isExported:!0,isTypeOnly:v,source:Nr(g),leadingComments:E,start:d,end:a})}else if(h===xe){Js();let g=m(d,a),v=Qe(d);c.push({kind:"export",name:"",text:g,isExported:!0,isTypeOnly:!1,source:Nr(g),leadingComments:v,start:d,end:a})}else{ne();let g=m(d,a);if(g)c.push({kind:"export",name:"",text:g,isExported:!0,start:d,end:a})}}else if(p===100&&b("declare"))a+=7,C(),oo(d,!1);else if(p===105&&b("interface")){let h=en(d,!1);f.set(h.name,h)}else if(p===116&&b("type")){let h=tn(d,!1);f.set(h.name,h),c.push(h)}else if(p===102&&b("function")){let h=Tt(d,!1,!1,!1);if(h)f.set(h.name,h);else ne()}else if(p===97)if(b("async")){let h=a;if(a+=5,C(),b("function")){let g=Tt(d,!1,!0,!1);if(g)f.set(g.name,g);else a=h,ne()}else a=h,ne()}else if(b("abstract"))if(a+=8,C(),b("class")){let h=Ot(d,!1,!1);f.set(h.name,h),c.push(h)}else ne();else a++,ne();else if(p===99)if(b("class")){let h=Ot(d,!1,!1);f.set(h.name,h),c.push(h)}else if(b("const")){let h=a;if(a+=5,C(),b("enum")){a=h+5,C();let g=Ut(d,!1,!0);f.set(g.name,g),c.push(g)}else{a=h;let g=Ft(d,"const",!1);for(let v=0;v<g.length;v++)f.set(g[v].name,g[v])}}else a++,ne();else if(p===101&&b("enum")){let h=Ut(d,!1,!1);f.set(h.name,h),c.push(h)}else if(p===108&&b("let")||p===118&&b("var")){let h=b("let")?"let":"var",g=Ft(d,h,!1);for(let v=0;v<g.length;v++)f.set(g[v].name,g[v])}else if(p===109&&b("module")&&j(6)){let h=Vt(d,!1,"module");c.push(h)}else if(p===110&&b("namespace")&&j(9)){let h=Vt(d,!1,"namespace");c.push(h)}else{let h=i.charCodeAt(a);if(h===re)a++;else if(h===le||h===ue){if(k(h),a<l&&i.charCodeAt(a)===re)a++}else if(h===Fe){if(L(),a<l&&i.charCodeAt(a)===re)a++}else if(h===yp){if(a++,N(),C(),a<l&&i.charCodeAt(a)===pt)a++,N(),C();if(a<l&&i.charCodeAt(a)===ae)z(ae,Se)}else a++,ne()}}if(f.size>0)vp(c,f);if(u.size>0){let d=new Map;for(let h of c)if(h.kind==="function")d.set(h.name,(d.get(h.name)||0)+1);let p=new Set;for(let[h,g]of d)if(g>1)p.add(h);if(p.size>0){let h=new Set;for(let g of p)for(let v=c.length-1;v>=0;v--)if(c[v].kind==="function"&&c[v].name===g&&u.has(v)){h.add(v);break}if(h.size>0){let g=[...h].sort((v,E)=>E-v);for(let v of g)c.splice(v,1)}}}return c;function oo(d,p){if(b("function")){let h=Tt(d,p,!1,!1);if(h)c.push(h)}else if(b("async")){if(a+=5,C(),b("function")){let h=Tt(d,p,!0,!1);if(h)c.push(h)}}else if(b("class")){let h=Ot(d,p,!1);c.push(h)}else if(b("abstract")){if(a+=8,C(),b("class")){let h=Ot(d,p,!0);c.push(h)}}else if(b("interface")){let h=en(d,p);c.push(h)}else if(b("type")){let h=tn(d,p);c.push(h)}else if(b("enum")){let h=Ut(d,p,!1);c.push(h)}else if(b("const")){let h=a;if(a+=5,C(),b("enum")){a=h+5,C();let g=Ut(d,p,!0);c.push(g)}else if(p){a=h;let g=Ft(d,"const",!0);for(let v=0;v<g.length;v++)c.push(g[v])}else ne()}else if(b("let")||b("var"))if(p){let h=b("let")?"let":"var",g=Ft(d,h,!0);for(let v=0;v<g.length;v++)c.push(g[v])}else ne();else if(b("module")){let h=Vt(d,p,"module");c.push(h)}else if(b("namespace")){let h=Vt(d,p,"namespace");c.push(h)}else if(b("global")){a+=6,C();let h=`declare global ${a<l&&i.charCodeAt(a)===K?on():"{}"}`,g=Qe(d);c.push({kind:"module",name:"global",text:h,isExported:!1,leadingComments:g,start:d,end:a})}else ne()}}function cc(e,t){let r=0,n=e.length;while(r<n){let i=e.charCodeAt(r);if(i>=65&&i<=90||i>=97&&i<=122||i===95||i===36||i>127){let s=r;r++;while(r<n){let o=e.charCodeAt(r);if(o>=65&&o<=90||o>=97&&o<=122||o>=48&&o<=57||o===95||o===36||o>127)r++;else break}t.add(e.substring(s,r))}else r++}}function fc(e,t){let r=0;while(r<e.length){let n=e.charCodeAt(r);if(n===le||n===ue||n===Fe){let u=n;r++;while(r<e.length)if(e.charCodeAt(r)===rt)r+=2;else if(e.charCodeAt(r++)===u)break;continue}if(n===Q&&e.charCodeAt(r+1)===Q){r+=2;while(r<e.length&&e.charCodeAt(r)!==ve&&e.charCodeAt(r)!==Te)r++;continue}if(n===Q&&e.charCodeAt(r+1)===xe){let u=e.indexOf("*/",r+2);r=u===-1?e.length:u+2;continue}if(!gt(n)){r++;continue}let i=r++;while(r<e.length&&Ve(e.charCodeAt(r)))r++;let s=i-1,o=r;while(s>=0&&_e(e.charCodeAt(s)))s--;while(o<e.length&&_e(e.charCodeAt(o)))o++;let l=s>=0?e.charCodeAt(s):0,c=o<e.length?e.charCodeAt(o):0,f=i>=3&&e.slice(i-3,i)==="...";if(c===lt||l===pt&&!f)continue;if(c===ae&&(l===K||l===ht))continue;t.add(e.slice(i,r))}}function vp(e,t){let r=new Set,n=new Set;for(let o of e)n.add(o.name);let i=new Set,s=[];for(let o=0;o<e.length;o++){let l=e[o];if(l.kind!=="import"){if(s.push(l.text),cc(l.text,i),typeof l.value==="string")fc(l.value,i)}}for(;;){let o=[];for(let[f,u]of t){if(r.has(f))continue;if(i.has(f)){if(!n.has(f))o.push(u),n.add(f);r.add(f)}}if(o.length===0)break;o.sort((f,u)=>(f.start??1/0)-(u.start??1/0));let l=[],c=0;for(let f=0;f<e.length;f++){let u=e[f].start??1/0;while(c<o.length&&(o[c].start??1/0)<=u)l.push(o[c++]);l.push(e[f])}while(c<o.length)l.push(o[c++]);e.length=0;for(let f=0;f<l.length;f++)e.push(l[f]);for(let f of o)if(f.kind!=="import"){if(s.push(f.text),cc(f.text,i),typeof f.value==="string")fc(f.value,i)}}}var ke=32,Me=9,ve=10,Te=13,Q=47,xe=42,le=39,ue=34,Fe=96,rt=92,K=123,X=125,ae=40,Se=41,Ae=91,Pe=93,$e=60,me=62,re=59,lt=58,be=61,ht=44,pt=46,Bi=63,Os=35,yp=64,Cp=36,Rs;var pc=de(()=>{Ts();un();Rs=["public","protected","private","readonly","override"]});function gc(e){return e.endsWith(".vue")}function bp(e){let t={script:null,scriptSetup:null},r=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,n;while((n=r.exec(e))!==null){let i=n[1]||"",s=/lang\s*=\s*["']([^"']+)["']/i.exec(i)?.[1]?.toLowerCase()??"js",o={content:n[2]??"",attrs:i,setup:/\bsetup\b/.test(i),lang:s};if(o.setup)t.scriptSetup=o;else t.script=o}return t}function 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 mt(e,t){if(e[t+1]==="/"){let r=e.indexOf(`
|
|
221
|
+
`,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 ks(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 mt(e,t);return t}function Ms(e){let t=e.split(""),r=0;while(r<e.length){let n=ks(e,r);if(n>r){for(let i=r;i<n;i++)if(t[i]!==`
|
|
222
|
+
`&&t[i]!=="\r")t[i]=" ";r=n;continue}r++}return t.join("")}function Ue(e,t,r,n){let i=0,s=t;while(s<e.length){let o=e[s];if(o==='"'||o==="'"){s=it(e,s);continue}if(o==="`"){s=ct(e,s);continue}if(o==="/"&&(e[s+1]==="/"||e[s+1]==="*")){s=mt(e,s);continue}if(o===r)i++;else if(o===n){if(i--,i===0)return s}s++}return-1}function Ds(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=mt(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 ur(e,t=","){let r=[],n=0,i="",s=0;while(s<e.length){let o=e[s];if(o==='"'||o==="'"){let l=it(e,s);i+=e.slice(s,l),s=l;continue}if(o==="`"){let l=ct(e,s);i+=e.slice(s,l),s=l;continue}if(o==="/"&&(e[s+1]==="/"||e[s+1]==="*")){s=mt(e,s);continue}if(o==="{"||o==="["||o==="("||o==="<")n++;else if(o==="}"||o==="]"||o===")"||o===">")n--;if(o===t&&n===0){r.push(i),i="",s++;continue}i+=o,s++}if(i.trim()!=="")r.push(i);return r}function Or(e){let t=e.trim();if(!t.startsWith("{"))return[];let r=Ue(t,0,"{","}");if(r===-1)return[];let n=t.slice(1,r),i=[];for(let s of ur(n)){let o=-1,l=0;for(let u=0;u<s.length;u++){let a=s[u];if(a==='"'||a==="'"){u=it(s,u)-1;continue}if(a==="`"){u=ct(s,u)-1;continue}if(a==="{"||a==="["||a==="("||a==="<")l++;else if(a==="}"||a==="]"||a===")"||a===">")l--;else if(a===":"&&l===0){o=u;break}}if(o!==-1){i.push({key:xr(s.slice(0,o).trim()),value:s.slice(o+1).trim(),isMethod:!1});continue}let c=/^([A-Za-z_$][\w$]*|['"][^'"]+['"])\s*\(/.exec(s.trim());if(c){i.push({key:xr(c[1]),value:s.trim(),isMethod:!0});continue}let f=s.trim();if(f)i.push({key:xr(f),value:"",isMethod:!1})}return i}function xr(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 r=new RegExp(`\\b${t}\\b`,"g"),n;while((n=r.exec(e))!==null){let i=n.index+n[0].length;while(i<e.length&&/\s/.test(e[i]))i++;let s=null;if(e[i]==="<"){let c=Ds(e,i);if(c===-1)return null;s=e.slice(i+1,c).trim(),i=c+1;while(i<e.length&&/\s/.test(e[i]))i++}if(e[i]!=="(")continue;let o=Ue(e,i,"(",")");if(o===-1)return null;let l=ur(e.slice(i+1,o));return{generic:s,arg:l.length>0?l[0].trim():null}}return null}function Ep(e,t){let r=yc(e,t);if(!r)return null;return r.kind==="interface"?e.slice(r.bodyStart,r.end):e.slice(r.bodyStart,r.end).trim()}function yc(e,t){let r=new RegExp(`\\binterface\\s+${t}\\b[^{]*\\{`,"m").exec(e);if(r){let i=r.index+r[0].length-1,s=Ue(e,i,"{","}");if(s!==-1)return{kind:"interface",start:r.index,end:s+1,bodyStart:i}}let n=new RegExp(`\\btype\\s+${t}\\b[^=]*=`,"m").exec(e);if(n){let i=n.index+n[0].length,s=0,o=i;while(i<e.length){let l=e[i];if(l==='"'||l==="'"){i=it(e,i);continue}if(l==="`"){i=ct(e,i);continue}if(l==="{"||l==="["||l==="("||l==="<")s++;else if(l==="}"||l==="]"||l===")"||l===">")s--;else if((l===";"||l===`
|
|
223
|
+
`)&&s===0)break;i++}return{kind:"type",start:n.index,end:i,bodyStart:o}}return null}function Sp(e){let t=e.search(/\bas\s+PropType\s*</);if(t===-1)return null;let r=e.indexOf("<",t),n=Ds(e,r);if(n===-1)return null;if(e.slice(n+1).trim()!=="")return null;return e.slice(r+1,n).trim()}function Ps(e){let t=e.trim(),r=Sp(t);if(r!==null)return{type:r,optional:!0};if(t==="null")return{type:"unknown",optional:!0};if(t.startsWith("[")){let n=Ue(t,0,"[","]");if(n!==-1){let i=ur(t.slice(1,n)).map((s)=>Ps(s).type).filter((s)=>s!=="unknown");return{type:i.length>0?[...new Set(i)].join(" | "):"unknown",optional:!0}}}if(t.startsWith("{")){let n=Or(t),i=n.find((c)=>c.key==="type"),s=n.find((c)=>c.key==="required"),o=i?Ps(i.value).type:"unknown",l=!(s&&s.value.trim()==="true");return{type:o,optional:l}}if(mc[t])return{type:mc[t],optional:!0};if(/^[A-Za-z_$][\w$.]*$/.test(t))return{type:t,optional:!0};return{type:"unknown",optional:!0}}function ji(e){let t=e.trim();if(t.startsWith("{")){let r=Or(t);if(r.length===0)return"{}";return`{ ${r.map((n)=>{if(n.isMethod||n.value==="")return`${Tr(n.key)}?: unknown`;let i=Ps(n.value);return`${Tr(n.key)}${i.optional?"?":""}: ${i.type}`}).join(", ")} }`}if(t.startsWith("[")){let r=Ue(t,0,"[","]");if(r===-1)return null;let n=ur(t.slice(1,r)).map((i)=>xr(i.trim())).filter((i)=>i!=="");if(n.length===0)return"{}";return`{ ${n.map((i)=>`${Tr(i)}?: unknown`).join(", ")} }`}return null}function Ap(e){let t=e.trim();if(!t.startsWith("["))return null;let r=Ue(t,0,"[","]");if(r===-1)return null;let n=ur(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(xr(i))).join(", ")}]`}function xp(e){let t=e.trim();if(!t.startsWith("{"))return null;let r=Or(t);if(r.length===0)return"{}";return`{ ${r.map((n)=>`${JSON.stringify(n.key)}: (...args: any[]) => void`).join(", ")} }`}function Cc(e){return Ap(e)??xp(e)}function Tp(e){let t=[],r=0,n="",i=0;while(i<e.length){let s=e[i];if(s==='"'||s==="'"){let o=it(e,i);n+=e.slice(i,o),i=o;continue}if(s==="`"){let o=ct(e,i);n+=e.slice(i,o),i=o;continue}if(s==="/"&&(e[i+1]==="/"||e[i+1]==="*")){let o=mt(e,i);n+=e.slice(i,o),i=o;continue}if(s==="="&&e[i+1]===">"){n+="=>",i+=2;continue}if(s==="{"||s==="["||s==="("||s==="<")r++;else if(s==="}"||s==="]"||s===")"||s===">")r--;if((s===";"||s===","||s===`
|
|
224
|
+
`)&&r===0){if(n.trim()!=="")t.push(n.trim());n="",i++;continue}n+=s,i++}if(n.trim()!=="")t.push(n.trim());return t}function Op(e){let t=e.trim();if(!t.startsWith("{"))return null;let r=Ue(t,0,"{","}");if(r===-1||t.slice(r+1).trim()!=="")return null;let n=Tp(t.slice(1,r));if(n.length===0)return"{}";let i=[];for(let s of n){let o=/^\(\s*\w+\s*:\s*/.exec(s);if(!o)return null;let l=o[0].length,c=s[l];if(c!=="'"&&c!=='"'&&c!=="`")return null;let f=it(s,l),u=s.slice(l+1,f-1),a=Ue(s,s.indexOf("(",0),"(",")");if(a===-1)return null;let m=s.slice(l,a),y=ur(m).slice(1),w=s.slice(a+1).trim();if(w.startsWith(":"))w=w.slice(1).trim();if(w==="")w="void";i.push(`${JSON.stringify(u)}: (${y.map((C)=>C.trim()).join(", ")}) => ${w}`)}return`{ ${i.join(", ")} }`}function Is(e){let t=e;for(let r of["defineProps","defineEmits","defineExpose","defineSlots","defineOptions"])t=Rp(t,r);return t}function Rp(e,t){let r=new RegExp(`\\b${t}\\b`,"g"),n=[],i=e,s;while((s=r.exec(e))!==null){let o=e.lastIndexOf(`
|
|
225
|
+
`,s.index)+1,l=e.slice(o,s.index),c=/^\s*(?:(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*(?::[^=]+)?=\s*)?(withDefaults\s*\(\s*)?$/.exec(l);if(!c)continue;let f=s.index+s[0].length;while(f<e.length&&/\s/.test(e[f]))f++;if(e[f]==="<"){let m=Ds(e,f);if(m===-1)continue;f=m+1;while(f<e.length&&/\s/.test(e[f]))f++}if(e[f]!=="(")continue;let u=Ue(e,f,"(",")");if(u===-1)continue;if(c[1]){let m=o+l.length-c[1].length,y=e.indexOf("(",m);if(y!==-1){let w=Ue(e,y,"(",")");if(w!==-1)u=w}}let a=u+1;while(a<e.length&&e[a]!==`
|
|
226
|
+
`&&/\s|;/.test(e[a]))a++;if(e[a]===`
|
|
227
|
+
`)a++;n.push([o,a])}for(let o=n.length-1;o>=0;o--)i=i.slice(0,n[o][0])+i.slice(n[o][1]);return i}function Fs(e){let t=Pp(e);if(t!==-1){let r=/^export\s+default\b/.exec(e.slice(t))?.[0];if(!r)return{options:null,script:e,passthrough:!1};let n=t+r.length;while(n<e.length&&/\s/.test(e[n]))n++;let i=-1,s=-1,o=-1;if(e[n]==="{")i=n,s=Ue(e,n,"{","}"),o=s;else if(e.startsWith("defineComponent",n)){let f=e.indexOf("(",n);if(f!==-1){let u=f+1;while(u<e.length&&/\s/.test(e[u]))u++;if(e[u]==="{")i=u,s=Ue(e,u,"{","}"),o=Ue(e,f,"(",")")}}if(i===-1||s===-1||o===-1)return{options:null,script:e,passthrough:!0};let l=o+1;if(e[l]===";")l++;let c=(e.slice(0,t)+e.slice(l)).trim();return{options:e.slice(i,s+1),script:c,passthrough:!1}}return{options:null,script:e,passthrough:!1}}function Pp(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=mt(e,r);continue}if(n==="{"||n==="["||n==="(")t++;else if(n==="}"||n==="]"||n===")")t=Math.max(0,t-1);else if(t===0&&e.startsWith("export",r)){let i=r===0?"":e[r-1],s=e[r+6]??"";if(!/[\w$]/.test(i)&&!/[\w$]/.test(s)){if(/^export\s+default\b/.exec(e.slice(r)))return r}}r++}return-1}function Ui(e,t){let r=Or(e).find((n)=>n.key===t);return r&&r.value!==""?r.value:null}function Vi(e,t){let r=Mp(e),n=e;for(let i=r.length-1;i>=0;i--){let s=r[i],o=n.slice(0,s.start)+n.slice(s.end);if(kp(o,s.name))continue;if(new RegExp(`\\btypeof\\s+${s.name}\\b`).test(t))continue;n=o}return n}function kp(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=mt(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 Mp(e){let t=[],r=Dp(e),n=/^[ \t]*(const|let|var|(?:async[ \t]+)?function)[ \t]+([A-Za-z_$][\w$]*)[ \t]*(?::[^=\n]+)?=?/gm,i;while((i=n.exec(e))!==null){let s=e.lastIndexOf(`
|
|
228
|
+
`,i.index)+1;if(!r.has(s))continue;if(/\bexport\b/.test(e.slice(s,i.index)))continue;let o=i[1],l=i[2],c=i.index+i[0].length,f=-1;if(o.endsWith("function")){let u=e.indexOf("(",c);if(u===-1)continue;let a=Ue(e,u,"(",")");if(a===-1)continue;c=a+1;while(c<e.length&&/\s/.test(e[c]))c++;if(e[c]===":")while(c<e.length&&e[c]!=="{"&&e[c]!==`
|
|
229
|
+
`)c++;while(c<e.length&&/\s/.test(e[c])&&e[c]!==`
|
|
230
|
+
`)c++;if(e[c]!=="{")continue;let m=Ue(e,c,"{","}");if(m===-1)continue;f=m+1}else{let u=0;while(c<e.length){let a=e[c];if(a==='"'||a==="'"){c=it(e,c);continue}if(a==="`"){c=ct(e,c);continue}if(a==="/"&&(e[c+1]==="/"||e[c+1]==="*")){c=mt(e,c);continue}if(a==="{"||a==="["||a==="(")u++;else if(a==="}"||a==="]"||a===")")u--;else if(a===";"&&u===0){f=c+1;break}else if(a===`
|
|
231
|
+
`&&u===0){f=c;break}c++}if(f===-1)f=e.length}if(e[f]===`
|
|
232
|
+
`)f++;t.push({name:l,start:i.index,end:f})}return t}function Dp(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=mt(e,n);continue}if(i==="{"||i==="["||i==="(")r++;else if(i==="}"||i==="]"||i===")")r=Math.max(0,r-1);if(i===`
|
|
233
|
+
`&&r===0)t.add(n+1);n++}return t}function Hi(e,t,r){let n=e.indexOf(r);if(n===-1)return e;let i=e.lastIndexOf(`
|
|
234
|
+
`,n)+1;if(/\bexport\b/.test(e.slice(i,n)))return e;let s=e.slice(0,n)+e.slice(n+r.length);if(new RegExp(`\\b${t}\\b`).test(s))return e;return s}function Ns(e){let t="",r=0,n=()=>{for(let s=t.length-1;s>=0;s--)if(!/\s/.test(t[s]))return t[s];return""},i=(s)=>{for(let o=s;o<e.length;o++)if(!/\s/.test(e[o]))return e[o];return""};while(r<e.length){let s=e[r];if(s==='"'||s==="'"){let o=it(e,r);t+=e.slice(r,o),r=o;continue}if(s==="`"){let o=ct(e,r);t+=e.slice(r,o),r=o;continue}if(s==="/"&&e[r+1]==="*"){let o=mt(e,r);t+=e.slice(r,o).replace(/\s*\n\s*/g," "),r=o;continue}if(s==="/"&&e[r+1]==="/"){let o=r+2;while(o<e.length&&e[o]!==`
|
|
235
|
+
`)o++;let l=e.slice(r+2,o).trim();if(l!==""&&!l.includes("*/"))t+=`/* ${l} */`;r=o;continue}if(s===`
|
|
236
|
+
`){let o=n(),l=i(r+1);if(o===""||l===""){r++;continue}let c=Ip(t);if(!c&&("{;,(<:=[".includes(o)||"}),]>;|&".includes(l))){if(!t.endsWith(" ")&&!t.endsWith(";"))t+=" "}else if(c){if(!t.endsWith(" "))t+=" "}else{if(t.endsWith(" "))t=t.slice(0,-1);t+="; "}r++;while(r<e.length&&(e[r]===" "||e[r]==="\t"))r++;continue}t+=s,r++}return t}function Ip(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 Ki(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=Rr(n,"defineProps");if(!i)continue;if(i.generic){let s=i.generic;if(s.startsWith("{"))return{type:s};if(/^[A-Za-z_$][\w$]*$/.test(s)){for(let o of r){let l=yc(o,s);if(!l)continue;let c=Ep(o,s);if(c===null)continue;return{type:c,inlinedLocal:{name:s,declText:o.slice(l.start,l.end)}}}return{type:s}}return{type:s}}if(i.arg){let s=ji(i.arg);if(s!==null)return{type:s}}}return null}function Ws(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=Rr(n,"defineEmits");if(!i)continue;if(i.generic)return Op(i.generic)??i.generic;if(i.arg){let s=Cc(i.arg);if(s!==null)return s}}return null}function Ls(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=Rr(n,"defineExpose");if(!i||!i.arg||!i.arg.startsWith("{"))continue;let s=Or(i.arg);if(s.length===0)return null;return`{ ${s.map((o)=>{if(o.value===""&&/^[A-Za-z_$][\w$]*$/.test(o.key))return`${Tr(o.key)}: typeof ${o.key}`;let l=o.isMethod||/=>|^\s*function\b/.test(o.value);return`${Tr(o.key)}: ${l?"(...args: any[]) => any":"unknown"}`}).join(", ")} }`}return null}function wc(e){let t=bp(e),r="",n=null,i=null;if(t.script){let x=Fs(t.script.content);if(x.passthrough)return t.scriptSetup?`${t.script.content}
|
|
237
|
+
${t.scriptSetup.content}`:t.script.content;if(r=x.script,x.options){let k=Ui(x.options,"props");if(k)n=ji(k);let L=Ui(x.options,"emits");if(L)i=Cc(L)}}let s=t.scriptSetup?.content??null,o=s!==null?Is(s):null,l=Ki(s,s!==null?null:r),c=l?.type??n??"{}",f=Ws(s,null)??i,u=Ls(s,null),a=l?.inlinedLocal;if(a){if(r=Hi(r,a.name,a.declText),o!==null)o=Hi(o,a.name,a.declText)}let m=[c,u??"{}"];if(f)m.push("{}","{}","{}","{}","{}",f);let y=Ns(`DefineComponent<${m.join(", ")}>`),w=[],C=Vi(r,y);if(C.trim()!=="")w.push(C);if(o&&o.trim()!==""){let x=Vi(o,y);if(x.trim()!=="")w.push(x)}return w.push("import type { DefineComponent } from 'vue'"),w.push(`type __DtsxComponentType = ${y}`),w.push("const __dtsx_component__: __DtsxComponentType = null as unknown as __DtsxComponentType"),w.push("export default __dtsx_component__"),w.join(`
|
|
238
|
+
`)}var mc;var Gs=de(()=>{mc={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 vc(e){return e.endsWith(".stx")}function Fp(e){let t=[],r=/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi,n;while((n=r.exec(e))!==null){let i=n[1]??"",s=/\blang\s*=\s*["']([^"']+)["']/i.exec(i)?.[1]?.toLowerCase()??(/\b(?:type\s*=\s*["'](?:text\/)?typescript["']|typescript)\b/i.test(i)?"ts":"js"),o=/\bserver\b/i.test(i)?"server":/\bclient\b/i.test(i)?"client":"universal";t.push({content:n[2]??"",kind:"script",attrs:i,context:o,lang:s,start:n.index})}return t}function Np(e){let t=[],r=/^[ \t]*@ts[ \t]*(?:\r?\n|$)/gm,n;while((n=r.exec(e))!==null){let i=r.lastIndex,s=/^[ \t]*@endts[ \t]*(?:\r?\n|$)/gm;s.lastIndex=i;let o=s.exec(e),l=o?.index??e.length;if(t.push({content:e.slice(i,l),kind:"ts",attrs:"",context:"universal",lang:"ts",start:n.index}),!o)break;r.lastIndex=s.lastIndex}return t}function Wp(e){return[...Fp(e),...Np(e)].sort((t,r)=>t.start-r.start)}function Lp(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 Gp(e){let t=/(?:\$?props)\s+as\s+/g,r;while((r=t.exec(e))!==null){let n=t.lastIndex;while(n<e.length&&/\s/.test(e[n]))n++;if(e[n]==="{"){let o=Ue(e,n,"{","}");if(o!==-1)return e.slice(n,o+1).trim();continue}let i=/^[A-Za-z_$][\w$]*/.exec(e.slice(n))?.[0];if(!i)continue;let s=n+i.length;while(s<e.length&&/\s/.test(e[s]))s++;if(e[s]==="<"){let o=Ue(e,s,"<",">");if(o!==-1)s=o+1}return e.slice(n,s).trim()}return null}function Bp(e){return/\b(?:const|let|var)\s+\$?props\s*:\s*([^=;\n]+)/.exec(e)?.[1]?.trim()??null}function _p(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 Up(e,t){if(!e||e==="unknown")return t;if(t==="unknown"||e===t)return e;return[...new Set([...e.split(" | "),...t.split(" | ")])].join(" | ")}function Vp(e){let t=Ms(e),r=new Map,n=/\$props(?:\.([A-Za-z_$][\w$]*)|\[\s*(['"])([^'"\n]+)\2\s*\])/g,i;while((i=n.exec(e))!==null){if(t.slice(i.index,i.index+6)!=="$props")continue;let s=i[1]??i[3],o=_p(e.slice(n.lastIndex));r.set(s,Up(r.get(s),o))}if(r.size===0)return null;return{type:`{ ${[...r].map(([s,o])=>`${/^[A-Za-z_$][\w$]*$/.test(s)?s:JSON.stringify(s)}?: ${o}`).join(", ")} }`}}function Hp(e){let t=Ki(e,null);if(t)return t;let r=Gp(e)??Bp(e);if(!r)return Vp(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 Ki(`${e}
|
|
239
|
+
defineProps<${r}>()`,null)}function jp(e){return Is(e)}function $c(e){let t=Ms(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 Kp(e){let t=[],r=0,n=0,i=0;while(i<e.length){let o=e[i],l=ks(e,i);if(l>i){i=l;continue}if(o==="{"||o==="["||o==="(")n++;else if(o==="}"||o==="]"||o===")")n=Math.max(0,n-1);if((o===";"||o===`
|
|
240
|
+
`)&&n===0){let c=i+1;if(!$c(e.slice(r,c)))t.push([r,c]);r=c}i++}if(r<e.length&&!$c(e.slice(r)))t.push([r,e.length]);let s=e;for(let o=t.length-1;o>=0;o--)s=s.slice(0,t[o][0])+s.slice(t[o][1]);return s}function bc(e){let t=Wp(e).filter(Lp).map((C)=>C.content).join(`
|
|
241
|
+
`),r=null,n=Fs(t);if(n.passthrough)return t;if(t=n.script,n.options){let C=Ui(n.options,"props");if(C)r=ji(C)}let i=t,s=jp(t),o=Hp(i),l=o?.type??r??"{}",c=Ws(i,null),f=Ls(i,null),u=Rr(i,"defineSlots")?.generic??null,a=o?.inlinedLocal;if(a)s=Hi(s,a.name,a.declText);let m=`DefineComponent<${l}>`,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)m+=` & { ${y.join(", ")} }`;m=Ns(m),s=Kp(Vi(s,m));let w=["import type { DefineComponent } from '@stacksjs/stx'",`type __DtsxStxComponentType = ${m}`,"const __dtsx_component__: __DtsxStxComponentType = null as unknown as __DtsxStxComponentType","export default __dtsx_component__"];if(s.trim()!=="")w.push(s);return w.join(`
|
|
242
|
+
`)}var Ec=de(()=>{Gs()});function Ac(e,t,r=!0,n=!1){if(gc(t))e=wc(e);else if(vc(t))e=bc(e);let i=Sr(e),s=`${t}:${r?1:0}:${n?1:0}`,o=hr.get(s);if(o&&o.contentHash===i)return o.lastAccess=++Sc,o.declarations;let l=n?uc(e,t,r):hc(e,t,r);if(hr.set(s,{declarations:l,contentHash:i,lastAccess:++Sc}),hr.size>Zp){let c=Math.max(1,Math.ceil(hr.size*0.1)),f=[];for(let[u,a]of hr)f.push([u,a.lastAccess]);f.sort((u,a)=>u[1]-a[1]);for(let u=0;u<c&&u<f.length;u++)hr.delete(f[u][0])}return l}var Zp=100,Sc=0,hr;var xc=de(()=>{pc();Ec();fs();Gs();hr=new Map});function Tc(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 Oc=()=>{};function Rc(e,t,r=!0,n=!1){return Ac(e,t,r,n)}var Pc=de(()=>{xc()});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)},s=await n.onBeforeFile(i);if(typeof s==="string")r=s}return r}async runOnDeclarations(e,t,r){let n=r;for(let i of this.plugins)if(i.onDeclarations){let s={filePath:e,sourceCode:t,declarations:n,config:this.config,log:this.createLogger(i.name)},o=await i.onDeclarations(s);if(o)n=o}return n}async runOnAfterFile(e,t,r){let n=r;for(let i of this.plugins)if(i.onAfterFile){let s={filePath:e,sourceCode:t,content:n,config:this.config,log:this.createLogger(i.name)},o=await i.onAfterFile(s);if(typeof o==="string")n=o}return n}async runOnEnd(e){for(let t of this.plugins)if(t.onEnd)await t.onEnd(e)}async runOnError(e,t,r){for(let n of this.plugins)if(n.onError){let i={filePath:t,sourceCode:r,config:this.config,log:this.createLogger(n.name)};await n.onError(e,i)}}}function Yp(e){return e}var j0,K0;var kc=de(()=>{j0=new Zi;K0=Yp({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})})});import{existsSync as Mc}from"fs";import{mkdir as Dc,readdir as Jp,realpath as qp,rm as zp}from"fs/promises";import{availableParallelism as Xp}from"os";import{basename as Hs,dirname as Yi,extname as Qp,isAbsolute as kr,parse as em,relative as Ge,resolve as Xe}from"path";function Wc(e){let t=Bs.get(e);if(!t)t=Oo(e),Bs.set(e,t),t.catch(()=>Bs.delete(e));return t}async function Ic(e,t,r,n,i,s=Ri){let o=Hs(e)||"output.d.ts",l=Ge(Yi(e),t),c=`${o}.map`,f=r.lastIndexOf(`
|
|
243
|
+
${cs()}`),u=f===-1?r:r.slice(0,f),a=bl(u,o,l,n),m=`${e}.map`;return await s(m,JSON.stringify(a)),q.debug(` Generated source map: ${Ge(i,m)}`),c}async function js(e){let t=Date.now(),r={...cl,...e};if(r.logLevel)cn(r.logLevel);else if(r.verbose)cn("debug");let n=new Zi;if(r.plugins&&r.plugins.length>0){for(let T of r.plugins)n.register(T),q.debug(`Registered plugin: ${T.name}`);r=await n.runOnStart(r)}if(await rm(r),r.isolatedDeclarations===void 0)r.isolatedDeclarations=await wl(r);let i=r.typeMappings?Pi(r.typeMappings):void 0,s=null,o={generationMode:r.isolatedDeclarations?"isolated":"semantic",filesProcessed:0,filesGenerated:0,filesFailed:0,filesValidated:0,validationErrors:0,declarationsFound:0,importsProcessed:0,exportsProcessed:0,durationMs:0,errors:[]},l=0;q.debug("Starting DTS generation..."),q.debug(`Using ${o.generationMode} declaration generation path`),q.debug("Config:",r);let c=await am(r);om(r,c);let f=c.slice(),u=await Wc(r),a=null;if(r.autoIncludeReExports!==!1&&f.length>0){a=await wn(f,{includeImports:!0,resolveSpecifier:u});let T=Xe(r.cwd,r.root),D=r.exclude||[],F=[];for(let N of a.reachable){if(f.includes(N))continue;if(!Vs(N))continue;if(N.endsWith(".d.ts"))continue;if(N.includes("node_modules"))continue;let b=r.outputStructure==="flat"&&c.some((j)=>u.isPackageLocal?.(j,N));if(!Mr(N,T)&&!b){q.warn(`Skipping auto-included source outside root: ${Ge(r.cwd,N)}`);continue}if(Us(N,D,T))continue;F.push(N)}if(F.length>0)f=[...f,...F],q.debug(`Auto-included ${F.length} file(s) reached via relative re-exports`)}if(lm(f,r),_s.set(r,new Set(f)),r.incremental){if(s=new ds(r,u.cacheKey?.(f)),r.clearCache){if(q.debug("Clearing build cache..."),!r.dryRun)s.clear()}else if(s.load()){let T=s.getStats();q.debug(`Loaded build cache with ${T.entries} entries`)}else q.debug("No existing build cache found, starting fresh");if(!r.dryRun)Nl(r.cwd)}if(s&&!r.dryRun){let T=s.prune(new Set(f),r.cwd);if(T>0)q.debug(`Pruned ${T} deleted files from cache`)}if(q.debug(`Found ${f.length} TypeScript files`),r.progress&&f.length>0){let T=r.parallel?"parallel":"sequential";q.info(`Processing ${f.length} files (${T})...`)}let m=new Map,y=new Map,w=async(T,D,F="lf")=>{y.set(T,{content:D,lineEnding:F})},C=async(T,D)=>{let F;try{let N=Dr(T,r),b=async(ee)=>{if(!r.diff)return;try{let W=await Rt(N),H=vl(W,ee,Ge(r.cwd,N));if(H)q.info(`
|
|
244
|
+
${H}`);else q.debug(`[no changes] ${N}`)}catch{q.info(`[new file] ${Ge(r.cwd,N)}`)}},j=(ee)=>{if(!r.validate)return 0;let W=$l(ee,N);if(W.isValid)return q.debug(`[validation] ${N} - OK`),0;q.warn(`[validation] ${Ge(r.cwd,N)} has ${W.errors.length} error(s):`);for(let H of W.errors){let J=` Line ${H.line}:${H.column}`;if(H.code)J+=` [${H.code}]`;if(J+=` - ${H.message}`,q.warn(J),H.suggestion)q.warn(` Suggestion: ${H.suggestion}`)}return W.errors.length},se=(ee)=>{q.info(`[dry-run] Would generate: ${N}`),q.debug("--- Content preview ---"),q.debug(ee.slice(0,500)+(ee.length>500?`
|
|
245
|
+
...`:"")),q.debug("--- End preview ---")};if(s){let ee=s.getCachedIfValid(T,r.cwd);if(ee){if(r.bundle)m.set(T,ee);await b(ee);let W=j(ee);if(r.dryRun)se(ee);else{if(r.declarationMap)F=D??await Rt(T),await Ic(N,T,ee,F,r.cwd,w);await w(N,ee,r.lineEnding)}return q.debug(`[cached] ${Ge(r.cwd,N)}`),{success:!0,file:T,declarationCount:0,importCount:0,exportCount:0,cached:!0,validationErrorCount:W}}}F=D??await Rt(T);let{content:he,declarationCount:Z,importCount:ge,exportCount:De}=await um(T,F,r,n,i);if(r.bundle)m.set(T,he);let ie=he;if(r.prettier||r.indentStyle||r.indentSize){let ee=await Go(ie,{usePrettier:r.prettier,builtIn:{indentSize:r.indentSize||2,useTabs:r.indentStyle==="tabs",normalizeWhitespace:!0,sortImports:!0,trailingNewline:!0}},N);ie=ee.content;for(let W of ee.warnings??[])q.warn(`[format] ${W}`)}if(r.declarationMap){let ee=`${Hs(N)||"output.d.ts"}.map`;ie=El(ie,ee)}await b(ie);let ce=j(ie);if(r.dryRun)se(ie);else{if(r.declarationMap&&F)await Ic(N,T,ie,F,r.cwd,w);if(await w(N,ie,r.lineEnding),s&&F)s.update(T,F,ie,r.cwd);q.debug(`Generated: ${N}`)}return{success:!0,file:T,declarationCount:Z,importCount:ge,exportCount:De,validationErrorCount:ce}}catch(N){let b=Al(N,T,F);if(r.plugins&&r.plugins.length>0)await n.runOnError(N instanceof Error?N:Error(String(N)),T,F||"");return{success:!1,file:T,declarationCount:0,importCount:0,exportCount:0,dtsError:b,validationErrorCount:0}}},x=r.parallel||r.parallel!==!1&&f.length>=10,k=Tc(r.concurrency,Xp?.()??8),L=new Map;if(x&&f.length>1){let T=f.map(async(D)=>{try{let F=await Rt(D);return{file:D,source:F}}catch{return{file:D,source:null}}});for(let D of await Promise.all(T))if(D.source!==null)L.set(D.file,D.source)}let G=(T)=>{if(o.filesProcessed++,T.success){if(T.cached)l++;else o.filesGenerated++,o.declarationsFound+=T.declarationCount,o.importsProcessed+=T.importCount,o.exportsProcessed+=T.exportCount;if(r.validate){if(o.filesValidated++,T.validationErrorCount)o.validationErrors+=T.validationErrorCount}}else if(o.filesFailed++,T.dtsError){o.errors.push(T.dtsError);let D=xl(T.dtsError);if(r.continueOnError)q.warn(D);else throw q.error(D),Error(T.dtsError.message)}};if(x)for(let T=0;T<f.length;T+=k){let D=f.slice(T,T+k),F=await Promise.all(D.map((N)=>C(N,L.get(N))));for(let N of F)G(N);if(r.progress){let N=Math.round(o.filesProcessed/f.length*100);q.info(`[${o.filesProcessed}/${f.length}] ${N}%`)}}else for(let T of f){let D=await C(T);if(G(D),r.progress){let F=Math.round(o.filesProcessed/f.length*100),N=D.cached?"[cached]":"";q.info(`[${o.filesProcessed}/${f.length}] ${F}% - ${Ge(r.cwd,T)} ${N}`)}}if(!r.dryRun){if(r.clean)await nm(r);for(let[T,D]of y)await Dc(Yi(T),{recursive:!0}),await Ri(T,D.content,D.lineEnding)}if(s&&!r.dryRun)s.save(),q.debug("Saved build cache");if(!r.bundle){let T=[];if(a)for(let D of a.unresolved)T.push({from:D.from,specifier:D.specifier,reason:"missing"});if(r.autoIncludeReExports===!1&&f.length>0){let D=new Set(f);for(let F of f){let N;try{N=await Rt(F)}catch{continue}for(let b of Hr(N)){let j=u(b.specifier,F);if(!j.isRelative)continue;if(!j.resolved)T.push({from:F,specifier:b.specifier,reason:"missing"});else if(!/\.d\.(?:ts|mts|cts)$/.test(j.resolved)&&!D.has(j.resolved))T.push({from:F,specifier:b.specifier,reason:"not-emitted"})}}}if(T.length>0){let D=[];D.push(`Found ${T.length} re-export(s) pointing at siblings that won't be in the output:`);for(let N of T){let b=Ge(r.cwd,N.from);if(N.reason==="missing")D.push(` ${b} \u2192 '${N.specifier}' (path not found on disk)`);else D.push(` ${b} \u2192 '${N.specifier}' (resolved but not in entrypoints; set autoIncludeReExports: true or add to entrypoints)`)}let F=D.join(`
|
|
246
|
+
`);if(r.failOnUnresolvedReExport)throw Error(F);q.warn(F),q.warn('Generated .d.ts files reference modules that were not emitted \u2014 consumers will see "has no exported member" errors.')}}if(r.bundle&&(o.filesGenerated>0||l>0)&&c.length>0)try{q.debug("Bundling declarations...");let T=c.length===1&&!!r.bundleOutput;for(let D of c){let F=await wn([D],{includeImports:!0,resolveSpecifier:u}),N=new Set;for(let he of F.reachable){if(he.endsWith(".d.ts"))continue;if(he.includes("node_modules"))continue;N.add(he)}let b=f.filter((he)=>N.has(he));if(!b.includes(D))b.push(D);let j=Do(D,b,m,{cwd:r.cwd,keepComments:r.keepComments});for(let he of new Set(j.warnings))q.warn(`[bundle] ${he}`);let se=T?Xe(r.cwd,r.outdir,r.bundleOutput):Dr(D,r);if(r.dryRun)q.info(`[dry-run] Would bundle ${j.files.length} files to: ${Ge(r.cwd,se)}`);else await Dc(Yi(se),{recursive:!0}),await Ri(se,j.content,r.lineEnding),q.info(`Bundled ${j.files.length} files to: ${Ge(r.cwd,se)}`);if(T)break}}catch(T){let D=T instanceof Error?T.message:String(T);q.error(`Bundle failed: ${D}`)}if(o.durationMs=Date.now()-t,r.stats)if(r.outputFormat==="json")console.log(JSON.stringify(o,null,2));else{if(q.info(`
|
|
247
|
+
--- Generation Statistics ---`),q.info(`Files processed: ${o.filesProcessed}`),q.info(`Files generated: ${o.filesGenerated}`),l>0)q.info(`Files cached: ${l}`);if(o.filesFailed>0)q.info(`Files failed: ${o.filesFailed}`);if(q.info(`Declarations found: ${o.declarationsFound}`),q.info(`Imports processed: ${o.importsProcessed}`),q.info(`Exports processed: ${o.exportsProcessed}`),o.filesValidated>0){if(q.info(`Files validated: ${o.filesValidated}`),o.validationErrors>0)q.info(`Validation errors: ${o.validationErrors}`)}if(q.info(`Duration: ${o.durationMs}ms`),o.errors.length>0){q.info(`
|
|
248
|
+
Errors:`);for(let T of o.errors){let D=` - ${T.file}`;if(T.location)D+=`:${T.location.line}:${T.location.column}`;if(T.code)D+=` [${T.code}]`;if(D+=`: ${T.message}`,q.info(D),T.suggestion)q.info(` Suggestion: ${T.suggestion}`)}}q.info(`-----------------------------
|
|
249
|
+
`)}if(r.plugins&&r.plugins.length>0)await n.runOnEnd(o);return q.debug("DTS generation complete!"),o}async function Fc(e){try{return await qp(e)}catch{return Xe(e)}}async function rm(e){let t=Xe(e.cwd,e.outdir);if(e.bundle&&e.bundleOutput){if(kr(e.bundleOutput))throw Error("bundleOutput must be relative to outdir");let i=Xe(t,e.bundleOutput);if(!Mr(i,t))throw Error("bundleOutput must stay within outdir")}if(!e.clean||e.dryRun)return;if(t===em(t).root)throw Error("Refusing to clean declarations from the filesystem root");let[r,n]=await Promise.all([Fc(t),Fc(Xe(e.cwd,e.root))]);if(Mr(n,r))throw Error("Refusing to clean an outdir that contains the source root")}function im(e){let t=Pr.get(e);if(!t){if(t=new Nc(e),Pr.set(e,t),Pr.size>tm){let r=Pr.keys().next().value;if(r!==void 0)Pr.delete(r)}}return t}async function nm(e){let t=Xe(e.cwd,e.outdir);async function r(n){let i;try{i=await Jp(n,{withFileTypes:!0})}catch{return}await Promise.all(i.map(async(s)=>{let o=Xe(n,s.name);if(s.isDirectory()){await r(o);return}if(s.name.endsWith(".d.ts")||s.name.endsWith(".d.mts")||s.name.endsWith(".d.cts")||s.name.endsWith(".d.ts.map")||s.name.endsWith(".d.mts.map")||s.name.endsWith(".d.cts.map"))await zp(o,{force:!0})}))}await r(t)}function Us(e,t,r){if(!t||t.length===0)return!1;let n=Ge(r,e);for(let i of t){let s=im(i);if(s.match(n)||s.match(e))return!0}return!1}function om(e,t){let r=Xe(e.cwd,e.root),n=` root: ${r}
|
|
250
|
+
entrypoints: ${e.entrypoints.map((s)=>JSON.stringify(s)).join(", ")||"(none)"}
|
|
251
|
+
`+(e.exclude?.length?` exclude: ${e.exclude.map((s)=>JSON.stringify(s)).join(", ")}
|
|
252
|
+
`:"")+"Entrypoints are resolved relative to --root. Pass several by repeating --entrypoints or separating them with commas.";if(t.length===0){if(e.entrypoints.filter((s)=>kr(s)&&Mc(s)&&!Mr(s,r)).length===e.entrypoints.length)return;throw Error(`No source files matched. Nothing was generated.
|
|
253
|
+
${n}`)}let i=e.entrypoints.filter((s)=>{if(sm.test(s))return!1;return!Mc(kr(s)?s:Xe(r,s))});if(i.length>0)throw Error(`Entrypoint${i.length>1?"s":""} not found: ${i.map((s)=>JSON.stringify(s)).join(", ")}
|
|
254
|
+
${n}`)}async function am(e){let t=[],r=Xe(e.cwd,e.root),n=e.exclude||[],i=[...e.entrypoints,...e.include??[]];for(let s of i)if(kr(s)&&Vs(s)){if(!s.includes("node_modules")){if(!Mr(s,r)&&e.outputStructure!=="flat")q.warn(`Skipping entrypoint outside root: ${Ge(e.cwd,s)}`);else if(!Us(s,n,r))t.push(s)}}else{let o=new Nc(s);for await(let l of o.scan({cwd:r,absolute:!0,onlyFiles:!0}))if(Vs(l)&&!l.includes("node_modules")){if(!Us(l,n,r))t.push(l)}}return[...new Set(t.map((s)=>Xe(s)))].sort()}function Mr(e,t){let r=Ge(t,e);return r!==".."&&!r.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!kr(r)}function lm(e,t){let r=new Map;for(let n of e){let i=Dr(n,t),s=r.get(i);if(s&&s!==n)throw Error(`Output path collision: ${Ge(t.cwd,s)} and ${Ge(t.cwd,n)} both emit ${Ge(t.cwd,i)}`);r.set(i,n)}}function Vs(e){return/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/.test(e)&&!/\.d\.(?:ts|mts|cts)$/.test(e)}function Dr(e,t){let r=Xe(t.cwd,t.root),n=Ge(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 Xe(t.cwd,t.outdir,n);else{let i=Hs(n);return Xe(t.cwd,t.outdir,i)}}function cm(e,t,r=""){let n=Ge(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 fm(e,t,r){let n=await Wc(r),i=Dr(t,r);return Po(e,(s)=>{let o=n(s,t);if(!o.isRelative||!o.resolved)return s;if(/\.d\.(?:ts|mts|cts)$/.test(o.resolved))return s;if(o.isAlias&&_s.has(r)&&!_s.get(r).has(o.resolved))throw Error(`Local alias ${JSON.stringify(s)} from ${t} targets a declaration excluded from this package build: ${o.resolved}`);let l=o.isAlias?o.suffix??"":s.match(/[?#].*$/)?.[0]??"",c=l?s.slice(0,-l.length):s,f=Qp(c),u=/^(?:\.js|\.jsx|\.mjs|\.cjs)$/.test(f)?f:"";return cm(i,Dr(o.resolved,r),u)+l})}async function um(e,t,r,n,i){let s=t;if(n)s=await n.runOnBeforeFile(e,t);let o=Rc(s,e,r.keepComments,r.isolatedDeclarations??!1);if(n)o=await n.runOnDeclarations(e,s,o);let l=0,c=0;for(let u=0;u<o.length;u++){let a=o[u];if(a.kind==="import")l++;if(a.kind==="export"||a.isExported)c++}let f=ac(o,{filePath:e,sourceCode:s,declarations:o},r.keepComments,r.importOrder);if(f=await fm(f,e,r),i)f=Pl(f,i,{filePath:e});if(r.normalizeOutput===!0||r.declarationOrder)f=Wo(f,{lineEnding:"lf",declarationOrder:r.declarationOrder,indent:{style:r.indentStyle??"spaces",size:r.indentSize??2}});if(n)f=await n.runOnAfterFile(e,s,f);return{content:f,declarationCount:o.length,importCount:l,exportCount:c}}var Nc,Bs,_s,tm=50,Pr,sm;var Lc=de(()=>{Io();$n();Lo();Bo();Sl();fl();Tl();kl();Wl();Br();fn();lc();Pc();Oc();kc();({Glob:Nc}=globalThis.Bun),Bs=new WeakMap,_s=new WeakMap;Pr=new Map;sm=/[*?[\]{}!]/});var Gc=de(()=>{Lc()});import{createHash as dm}from"crypto";import{existsSync as pm,readFileSync as mm,writeFileSync as gm}from"fs";import{dirname as ym,join as Cm,relative as Bc,resolve as Ir,sep as Ji}from"path";import Uc from"process";class Vc{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=Cm(e,"manifest.json"),this.manifest=this.loadManifest(t)}loadManifest(e){try{if(pm(this.manifestPath)){let t=JSON.parse(mm(this.manifestPath,"utf-8"));if(t.configHash===e&&t.version==="1.0")return t}}catch{}return{version:"1.0",configHash:e,entries:{}}}save(){try{let{mkdirSync:e}=hm("fs");e(this.cacheDir,{recursive:!0}),gm(this.manifestPath,JSON.stringify(this.manifest,null,2))}catch{}}getEntry(e){return this.manifest.entries[e]}setEntry(e,t){this.manifest.entries[e]=t}isValid(e,t){return this.getEntry(e)?.hash===t}clear(){this.manifest.entries={},this.save()}}function wm(e){let t={root:e.root,outdir:e.outdir,entrypoints:e.entrypoints,clean:e.clean,tsconfigPath:e.tsconfigPath};return dm("md5").update(JSON.stringify(t)).digest("hex")}function jc(e={}){let{onSuccess:t,onError:r,failOnError:n=!0,incremental:i=!1,cacheDir:s=".dtsx-cache",on:o,timeout:l=60000,continueOnError:c=!1,verbose:f=!1,...u}=e,a=new Vc;if(o){for(let[m,y]of Object.entries(o))if(y)a.on(m,y)}return{name:"bun-plugin-dtsx",async setup(m){let y=Date.now(),w=null,C=0;try{let x=bm(u,m),k=wm(x);if(x.clean){let D=Ir(x.cwd??Uc.cwd(),x.outdir??"./dist");if(_c.has(D))x.clean=!1;else _c.add(D)}if(i)w=new Hc(Ir(s),k);if(await a.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 G=await(async()=>new Promise((D,F)=>{let N=setTimeout(()=>{F(new Fr(`Generation timed out after ${l}ms`,"TIMEOUT_ERROR",{timeout:l}))},l);js(x).then((b)=>{clearTimeout(N),D(b)}).catch((b)=>{clearTimeout(N),F(b)})}))(),T=Date.now()-y;if(w)w.save();if(await a.emit("complete",{type:"complete",stats:G,duration:T,fromCache:C}),f){if(console.log(`[bun-plugin-dtsx] Generation complete in ${T}ms`),C>0)console.log(`[bun-plugin-dtsx] ${C} files served from cache`)}if(t)await t(G)}catch(x){let k=$m(x);if(await a.emit("error",{type:"error",error:k}),r)await r(k);else{if(console.error("[bun-plugin-dtsx] Error generating declarations:"),console.error(` Code: ${k.code}`),console.error(` Message: ${k.message}`),k.context)console.error(` Context: ${JSON.stringify(k.context)}`);if(f&&k.stack)console.error(` Stack: ${k.stack}`)}if(n&&!c)throw k}}}}function $m(e){if(e instanceof Fr)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 Fr(e.message,t,{originalError:e.name},e)}return new Fr(String(e),"GENERATION_ERROR")}function vm(e){let t=e.map((n)=>ym(n).split(Ji)),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(Ji)||Ji}function bm(e,t){let r=e.cwd||Uc.cwd(),n=t?.config?.entrypoints,i=e.outdir||e.build?.config.outdir||t?.config.outdir||"./dist",s=e.root||e.build?.config.root||t?.config.root;if(!s&&n?.length){let l=vm(n.map((c)=>Ir(r,c)));s=Bc(r,l)||"."}s=s||"./src";let o=e.entrypoints;if(!o)if(n?.length){let l=Ir(r,s),c=[];for(let f of n){let u=Ir(r,f);if(u===l||u.startsWith(l+Ji))c.push(Bc(l,u));else console.warn(`[bun-plugin-dtsx] Skipping entrypoint outside root "${s}": ${f}`)}o=c.length?c:["index.ts"]}else o=["index.ts"];return{...e,cwd:r,root:s,entrypoints:o,outdir:i,clean:e.clean??!0,tsconfigPath:e.tsconfigPath}}var hm,Fr,_c;var Kc=de(()=>{Gc();hm=import.meta.require;Fr=class Fr 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}}};_c=new Set});import{mkdir as Em,stat as Sm}from"fs/promises";import{bold as Ks,dim as Zs,green as Am,italic as Zc,log as xm}from"@stacksjs/cli";import{path as nt}from"@stacksjs/path";import{glob as Yc}from"@stacksjs/storage";function an(e){let t=new Map;for(let o of e){if(t.has(o.name))throw Error(`duplicate package name: ${o.name}`);t.set(o.name,o)}let r=new Map,n=new Set,i=(o,l)=>{let c=r.get(o);if(c!==void 0)return c;if(n.has(o))throw Error(`dependency cycle: ${[...l,o].join(" -> ")}`);n.add(o);let f=t.get(o).dependencies.filter((a)=>a!==o&&t.has(a)),u=f.length?1+Math.max(...f.map((a)=>i(a,[...l,o]))):0;return n.delete(o),r.set(o,u),u},s=[];for(let o of[...e].sort((l,c)=>l.name.localeCompare(c.name)))(s[i(o.name,[])]||=[]).push(o);return s.filter(Boolean)}import{existsSync as of,readdirSync as af,readFileSync as ao}from"fs";import{join as ln}from"path";function lf(e){return[...af(e,{withFileTypes:!0}).filter((r)=>r.isDirectory()).map((r)=>ln(e,r.name)),e].filter((r)=>{let n=ln(r,"package.json");if(!of(n))return!1;let i=JSON.parse(ao(n,"utf8"));return!i.private&&!!i.scripts?.build})}async function cf(e){let t=e.map((i)=>{let s=JSON.parse(ao(ln(i,"package.json"),"utf8"));if(!s.name||!s.scripts?.build)throw Error(`Not a buildable workspace package: ${i}`);return{name:s.name,dir:i,dependencies:Object.keys(s.dependencies??{})}}),r=an(t),n=[];for(let{name:i,dir:s,dependencies:o}of r.flat()){let l=n.filter((f)=>f.exitCode!==0&&o.includes(f.name)).map((f)=>f.name);if(l.length){console.error(`Cannot build ${s}: dependencies failed: ${l.join(", ")}`),n.push({name:i,dir:s,exitCode:null,blockedBy:l});continue}console.log(`Building ${s}`);let c=Bun.spawn([process.execPath,"run","build"],{cwd:s,stdout:"inherit",stderr:"inherit"});n.push({name:i,dir:s,exitCode:await c.exited,blockedBy:[]})}return n}async function Tm(e){let t=await Yc([nt.resolve(e,"dist","**/*.d.ts")],{absolute:!0}),r=new Bun.Transpiler({loader:"ts",target:"bun"});for(let n of t){let i=await Bun.file(n).text();try{r.transformSync(i)}catch(s){throw Error(`Invalid declaration generated at ${n}: ${s instanceof Error?s.message:String(s)}`)}}}async function Om(e){let t=nt.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 s=n.split(`
|
|
255
|
+
`).find((o)=>i.test(o))??n.trim().split(`
|
|
256
|
+
`)[0];throw Error(`Built package at ${t} cannot be imported: ${s}
|
|
257
|
+
Fix the generated module at its source before publishing.`)}}async function FC(e){let r=Date.now()-e.startTime,n=e.pkgName??`@stacksjs/${nt.basename(e.dir)}`;if(e.result.errors&&e.result.errors.length>0)throw console.error("Build errors:",e.result.errors),Error(`Build failed with errors: ${JSON.stringify(e.result.errors)}`);else if(e.result.success!==void 0&&!e.result.success){let s=e.result.logs?.[0]||"Unknown build error";throw console.log(s),Error(`Build failed: ${s}`)}await Bun.write(nt.resolve(e.dir,"dist","tsconfig.json"),`${JSON.stringify({compilerOptions:{paths:{}}},null,2)}
|
|
258
|
+
`),await Tm(e.dir),await Om(e.dir);let i=await Yc([nt.resolve(e.dir,"dist","**/*")],{absolute:!0});for(let s of i){let o=await Sm(s),l;if(o.size<1048576)l=`${(o.size/1024).toFixed(2)}kb`;else l=`${(o.size/1024/1024).toFixed(2)}mb`;let c=nt.relative(e.dir,s).replace("dist/","");console.log(`${Ks(Zs(`[${l}]`))} ${Zs("dist/")}${c}`)}console.log(`${Ks(Zs(`[${r}ms]`))} Built ${Zc(Ks(Am(n)))}`)}async function NC(e){let t=e.pkgName??`@stacksjs/${nt.basename(e.dir)}`;if(e.styled===!1)console.log(`Building ${t}...`);else xm.info(`Building ${Zc(t)}...`);return{startTime:Date.now()}}async function WC(e){await Promise.resolve().then(() => Kc());let r=nt.resolve(e.dir,"src"),n=nt.resolve(e.dir,"dist"),i=(await Array.fromAsync(new Bun.Glob("**/*.ts").scan({cwd:r}))).filter((o)=>!o.endsWith(".d.ts")).filter((o)=>!o.endsWith(".test.ts")&&!o.endsWith(".spec.ts")).filter((o)=>!o.split(/[\\/]/).some((l)=>l==="tests"||l==="__tests__"));await Bun.build({entrypoints:i.map((o)=>nt.resolve(r,o)),outdir:n,root:r,target:"bun",format:"esm",splitting:!1,external:e.external??Pm(),plugins:[jc({root:r,outdir:n})]});let s=new Bun.Transpiler({loader:"ts",target:"bun",minifyWhitespace:!0,define:{"process.env.NODE_ENV":"process.env.NODE_ENV"}});for(let o of i){let l=s.transformSync(await Bun.file(nt.resolve(r,o)).text());l=Rm(l);let c=nt.resolve(n,o.replace(/\.ts$/,".js"));await Em(nt.dirname(c),{recursive:!0}),await Bun.write(c,l)}}function Rm(e){return e.replace(/(['"])(\.\.?\/[^'"]+?)(?<!\.d)\.tsx?\1/g,"$1$2.js$1")}function Pm(e=[]){let t=[];try{let r=sf("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{cf as buildWorkspacePackages,an as dependencyLayers,Pm as frameworkExternal,NC as intro,FC as outro,Rm as rewriteRelativeTsSpecifiers,WC as transpilePackage,Tm as validateDeclarations,Om as validateRuntimeExports,lf as workspaceBuildTargets};
|