@stacksjs/build 0.75.40 → 0.75.42
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 +208 -186
- package/package.json +5 -5
package/dist/index.js
CHANGED
|
@@ -1,209 +1,231 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
`)
|
|
6
|
-
`)
|
|
7
|
-
`,
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
`,
|
|
11
|
-
`)
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
`)
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
`)
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
`)
|
|
23
|
-
`)
|
|
24
|
-
`)
|
|
25
|
-
|
|
26
|
-
`;if(r==="t")return"\t";if(r==="r")return"\r";if(r==="0")return"\x00";return r})}function Hc(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function Jc(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 qc(e){let t=0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n===34||n===39||n===96){r=Ot(e,r,n)-1;continue}if(n===40||n===91||n===123){t++;continue}if(n===41||n===93||n===125){t--;continue}if(t!==0)continue;if(e.startsWith("===",r)||e.startsWith("!==",r)||e.startsWith("==",r)||e.startsWith("!=",r)||e.startsWith(">=",r)||e.startsWith("<=",r))return!0;if((n===62||n===60)&&e.charCodeAt(r-1)!==61&&e.charCodeAt(r+1)!==61)return!0}return!1}function Yc(e,t=!1,r=0){return Te(e,t,!0,r)}function dr(e,t=!1,r=""){let n=Js(r),i=[],s=!1,o=0;while(o<e.length){let c=e.charCodeAt(o);if(c===34||c===39||c===96){o=Ot(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)&&Us(e,o,8)||e.startsWith("class",o)&&Us(e,o,5)){let f=Xc(e,o);if(f!==-1){o=Ks(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=Ks(e,f);continue}}if(e.startsWith("return",o)&&(o===0||!ht(e.charCodeAt(o-1)))&&!ht(e.charCodeAt(o+6))){o+=6;let f=!1;while(o<e.length&&e.charCodeAt(o)<=32){let w=e.charCodeAt(o);if(w===10||w===13)f=!0;o++}if(f||o>=e.length||e.charCodeAt(o)===59||e.charCodeAt(o)===125){s=!0;continue}let u=o,l=0,g=0,p=0;while(o<e.length){let w=e.charCodeAt(o);if(w===34||w===39||w===96){o=Ot(e,o,w);continue}if(w===47&&e.charCodeAt(o+1)===47)break;if(w===47&&e.charCodeAt(o+1)===42){let T=e.indexOf("*/",o+2);o=T===-1?e.length:T+2;continue}if(w===40)l++;else if(w===41)l--;else if(w===91)g++;else if(w===93)g--;else if(w===123)p++;else if(w===125){if(p===0&&l===0&&g===0)break;p--}else if(w===59&&l===0&&g===0&&p===0)break;else if((w===10||w===13)&&l===0&&g===0&&p===0){let T=o+1;while(T<e.length&&e.charCodeAt(T)<=32)T++;if(e.startsWith("return",T)&&!ht(e.charCodeAt(T+6)))break}o++}let v=e.slice(u,o).trim(),b=Rt(v,n);if(!i.includes(b))i.push(b);continue}o++}if(s&&!i.includes("undefined"))i.push("undefined");let a=i.includes("unknown")?"unknown":i.length===0?"void":i.join(" | ");return t&&!a.startsWith("Promise<")?`Promise<${a}>`:a}function Js(e){let t=new Map,r=e.startsWith("(")&&e.endsWith(")")?e.slice(1,-1):e,n=0,i=0,s=0;for(let o=0;o<=r.length;o++){let a=r.charCodeAt(o);if(a===40||a===91||a===123)i++;else if(a===41||a===93||a===125)i--;else if(a===60)s++;else if(a===62&&r.charCodeAt(o-1)!==61&&s>0)s--;if(o!==r.length&&(a!==44||i!==0||s!==0))continue;let c=r.slice(n,o).trim(),f=c.indexOf(":");if(f!==-1){let u=c.slice(0,f).trim().replace(/^\.\.\./,"").replace(/\?$/,""),l=c.slice(f+1).trim(),g=l.indexOf("=");if(g!==-1)l=l.slice(0,g).trim();if(mr(u)&&l)t.set(u,l)}n=o+1}return t}function Rt(e,t){let r=e.trim();while(qs(r))r=r.slice(1,-1).trim();if(Br(r))return"JSX.Element";if(r.startsWith("await ")){let s=Rt(r.slice(6),t);return s.startsWith("Promise<")&&s.endsWith(">")?s.slice(8,-1):s}if(t.has(r))return t.get(r);if(r.startsWith("!"))return"boolean";if(r.startsWith("fetch("))return"Promise<Response>";let n=Zc(r);if(n){let s=Rt(n.whenTrue,t),o=Rt(n.whenFalse,t);return s===o?s:`${s} | ${o}`}if(["===","!==","==","!=",">=","<="].some((s)=>r.includes(s))||r.includes(" > ")||r.includes(" < "))return"boolean";let i=0;for(let s=r.length-1;s>=0;s--){let o=r.charCodeAt(s);if(o===41||o===93||o===125)i++;else if(o===40||o===91||o===123)i--;else if(i===0&&(o===43||o===45||o===42||o===47||o===37)){let a=Rt(r.slice(0,s),t),c=Rt(r.slice(s+1),t);if(o===43&&(a==="string"||c==="string"))return"string";if(a==="number"&&c==="number")return"number";break}}return Te(r,!1).replace(/\btypeof\s+[$A-Z_a-z][$\w]*/g,(s)=>{let o=s.slice(7);return t.get(o)??"unknown"})}function qs(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 Zc(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 Us(e,t,r){return(t===0||!ht(e.charCodeAt(t-1)))&&!ht(e.charCodeAt(t+r))}function Xc(e,t){for(let r=t;r<e.length;r++){let n=e.charCodeAt(r);if(n===34||n===39||n===96){r=Ot(e,r,n)-1;continue}if(n===123)return r;if(n===59)return-1}return-1}function Ks(e,t){let r=1,n=t+1;while(n<e.length&&r>0){let i=e.charCodeAt(n);if(i===34||i===39||i===96){n=Ot(e,n,i);continue}if(i===47&&e.charCodeAt(n+1)===47){n+=2;while(n<e.length&&e.charCodeAt(n)!==10&&e.charCodeAt(n)!==13)n++;continue}if(i===47&&e.charCodeAt(n+1)===42){let s=e.indexOf("*/",n+2);n=s===-1?e.length:s+2;continue}if(i===123)r++;else if(i===125)r--;n++}return n}function Ot(e,t,r){let n=t+1;while(n<e.length){let i=e.charCodeAt(n);if(i===92){n+=2;continue}if(n++,i===r)break}return n}function Qc(e,t){if(e.includes(".raw`")||e.includes("String.raw`"))return"string";if(!t||e.includes("${")||e.includes(`
|
|
27
|
-
`)||e.includes("\r"))return"string";return e}function ef(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&&(ht(e.charCodeAt(t))||e.charCodeAt(t)===46))t++;if(t===r)return"unknown";let i=e.slice(r,t);{let s=e.slice(t),o=s;if(s.startsWith("<")){let c=0,f=-1;for(let u=0;u<s.length;u++)if(s[u]==="<")c++;else if(s[u]===">"){if(c--,c===0){f=u;break}}if(f!==-1){let u=s.slice(0,f+1);o=s.slice(f+1);let l=o.indexOf("(");if(l!==-1){let g=0,p=-1;for(let v=l;v<o.length;v++)if(o[v]==="(")g++;else if(o[v]===")"){if(g--,g===0){p=v;break}}if(p!==-1){if(o.slice(p+1).trimStart().startsWith("."))return"unknown"}}return`${i}${u}`}}let a=o.indexOf("(");if(a!==-1){let c=0,f=-1;for(let u=a;u<o.length;u++)if(o[u]==="(")c++;else if(o[u]===")"){if(c--,c===0){f=u;break}}if(f!==-1){if(o.slice(f+1).trimStart().startsWith("."))return"unknown"}}switch(i){case"Date":return"Date";case"Map":return"Map<any, any>";case"Set":return"Set<any>";case"WeakMap":return"WeakMap<any, any>";case"WeakSet":return"WeakSet<any>";case"RegExp":return"RegExp";case"Error":return"Error";case"Array":return"any[]";case"Object":return"object";case"Function":return"Function";case"Promise":return"Promise<any>";default:return i}}return"unknown"}function tf(e){return"{ new (...args: any[]): any }"}function Ys(e,t,r=0){if(e.startsWith("Promise.resolve(")){let n=e.indexOf(")",16);if(n!==-1){let i=e.slice(16,n).trim();if(i)return`Promise<${Te(i,t,!1,r+1)}>`}return"Promise<unknown>"}if(e.startsWith("Promise.reject("))return"Promise<never>";if(e.startsWith("Promise.all(")){let n=e.indexOf("[",12),i=e.lastIndexOf("]");if(n!==-1&&i>n){let s=e.slice(n+1,i).trim(),o=Gr(s),a=[];for(let c=0;c<o.length;c++){let f=o[c].trim();if(f.startsWith("Promise.resolve(")){let u=Ys(f,t,r+1),l=u.indexOf("<"),g=u.lastIndexOf(">");a.push(l!==-1&&g>l?u.slice(l+1,g):"unknown")}else a.push(Te(f,t,!1,r+1))}return`Promise<[${a.join(", ")}]>`}return"Promise<unknown[]>"}return"Promise<unknown>"}function cn(e,t,r=0){let n=e.slice(1,-1).trim();if(!n)return"never[]";if(r>=20)return"unknown[]";let i=Gr(n),s=!1;for(let g=0;g<i.length;g++){let p=i[g],v=p.length;while(v>0&&p.charCodeAt(v-1)<=32)v--;if(v>=8&&p.slice(v-8,v)==="as const"){s=!0;break}}if(s){let g=[];for(let p=0;p<i.length;p++){let v=i[p].trim();if(v.endsWith("as const")){let b=v.slice(0,-8).trim();if(b.startsWith("[")&&b.endsWith("]")){let w=b.slice(1,-1).trim(),T=Gr(w),k=[];for(let R=0;R<T.length;R++)k.push(Te(T[R].trim(),!0,!1,r+1));g.push(`readonly [${k.join(", ")}]`)}else g.push(Te(b,!0,!1,r+1))}else if(v.startsWith("[")&&v.endsWith("]"))g.push(cn(v,!0,r+1));else g.push(Te(v,!0,!1,r+1))}return`readonly [
|
|
28
|
-
${g.join(` |
|
|
29
|
-
`)}
|
|
30
|
-
]`}let o=_r&&!t,a=[],c=[];for(let g of i){let p=g.trim(),v=Ve;if(Ve=null,p.startsWith("...")){let b=p.slice(3).trim(),w=Te(b,!1,!1,r+1);if(w.endsWith("[]"))a.push(w.slice(0,-2));else if(w.startsWith("readonly [")&&w.endsWith("]"))a.push(w.slice(10,-1));else if(pr(b))a.push(`(typeof ${b})[number]`);else a.push("unknown")}else if(p.startsWith("[")&&p.endsWith("]"))a.push(cn(p,t,r+1));else a.push(Yc(p,t,r+1));if(o)c.push(Ve);Ve=v}if(o)if(un(e))Ve=hr(e);else{let g=[];for(let p=0;p<i.length;p++){let v=i[p].trim();if(v.endsWith("as const"))continue;if(fn(v)||v==="null"||v==="undefined")g.push(v);else if(v.startsWith("[")&&un(v))g.push(hr(v));else if(v.startsWith("{")){if(c[p])g.push(c[p])}else{let b=Te(v,!1,!1,0);if(b!=="unknown")g.push(b)}}if(g.length>0)Ve=`[${g.join(", ")}]`}if(t)return`readonly [${a.join(", ")}]`;let f=new Set,u=[],l=!0;for(let g of a){if(!f.has(g))f.add(g),u.push(g);if(l){if(!(mn(g)||g==="true"||g==="false"||g.charCodeAt(0)===34&&g.charCodeAt(g.length-1)===34||g.charCodeAt(0)===39&&g.charCodeAt(g.length-1)===39))l=!1}}if(l&&a.length<=10)return`readonly [${a.join(", ")}]`;if(u.length===1)return`${u[0]}[]`;return`(${u.join(" | ")})[]`}function Gr(e){let t=[],r=0,n=0,i=!1,s=0;for(let a=0;a<e.length;a++){let c=e.charCodeAt(a);if(!i&&(c===34||c===39||c===96))i=!0,s=c;else if(i&&c===s&&(a===0||e.charCodeAt(a-1)!==92))i=!1;if(!i){if(c===91||c===123||c===40)n++;else if(c===93||c===125||c===41)n--;else if(c===44&&n===0){let f=e.substring(r,a).trim();if(f)t.push(f);r=a+1;continue}}}let o=e.substring(r).trim();if(o)t.push(o);return t}function fn(e){if(mn(e))return!0;if(e==="true"||e==="false")return!0;if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return!0;return!1}function rf(e){return e==="number"||e==="string"||e==="boolean"}function un(e){let t=!1,r=0,n=e.length;for(let i=0;i<n;i++){let s=e.charCodeAt(i);if(t){if(s===92){i++;continue}if(s===r)t=!1;continue}if(s===34||s===39||s===96){t=!0,r=s;continue}if(s===61&&i+1<n&&e.charCodeAt(i+1)===62)return!1;if(s>=97&&s<=122){let o=i;while(i<n&&(e.charCodeAt(i)>=97&&e.charCodeAt(i)<=122||e.charCodeAt(i)>=65&&e.charCodeAt(i)<=90||e.charCodeAt(i)>=48&&e.charCodeAt(i)<=57||e.charCodeAt(i)===95||e.charCodeAt(i)===36))i++;let a=e.slice(o,i);if(a==="new"||a==="async"||a==="await"||a==="function"||a==="yield"||a==="console"||a==="process")return!1;let c=i;while(c<n&&e.charCodeAt(c)<=32)c++;if(c<n&&e.charCodeAt(c)===40)return!1;i--}}return!0}function nf(e,t,r=0){let n=e.slice(1,-1).trim();if(!n)return"{}";if(r>=20)return"Record<string, unknown>";let i=ff(n),s=[],o=[],a=_r&&!t,c=[];for(let[l,g]of i){let{comments:p,key:v}=cf(l),b=p?`${p}
|
|
31
|
-
`:"",w=v,T=!1;if(v==="..."){let F=g.trim(),U=pr(F)?`typeof ${F}`:Te(F,t,!1,r+1);if(U!=="unknown")o.push(U);if(a&&(pr(F)||F.startsWith("{")))c.push(`...${hr(F)}`);continue}let k=Ve;Ve=null;let R,I=g.trim();if(I===v&&mr(I))R=`typeof ${I}`;else if(df(I)){T=!0;let F=mf(v);if(F){w=F.name;let U="";if(I.startsWith("async "))U="async ";if(I.charCodeAt(U.length)===42)U+="*";R=zs(F.name,U+F.typeParams+I.slice(U.length))}else R=zs(v,I)}else if(R=Te(g,t,!1,r+1),R.includes("=>")||R.includes("function")||R.includes("async"))R=of(R);let _=Ve;Ve=k;let W=g.trim(),P=uf(v);if(P){let F=hf(P.kind,P.name,R);if(F){s.push(`${b}${F}`);continue}}if(!t&&rf(R)&&fn(W))s.push(`${b}/** @defaultValue ${W} */
|
|
32
|
-
${w}: ${R}`);else s.push(`${b}${w}: ${R}`);if(a){let F=_c(w);if(W.endsWith("as const"));else if(fn(W))c.push(`${F}: ${W}`);else if(W.startsWith("[")&&un(W))c.push(`${F}: ${hr(W)}`);else if(W.startsWith("{")){if(_)c.push(`${F}: ${_}`)}else if(T)c.push(`${F}: ${hr(R)}`);else if(!W.startsWith("[")&&(W.includes("=>")||W.startsWith("function")||W.startsWith("async"))){let U=eo(W,!1,0,!0);c.push(`${F}: ${U}`)}}}if(a&&c.length>0){let l=r>0?(r-1)/2:0,g=`{ ${c.join(", ")} }`;if(g.length<=80)Ve=g;else{let p=" ".repeat((l+1)*2),v=" ".repeat(l*2);Ve=`{
|
|
33
|
-
${p}${c.join(`,
|
|
34
|
-
${p}`)}
|
|
35
|
-
${v}}`}}let f=s.length>0?`{
|
|
36
|
-
${s.join(`;
|
|
37
|
-
`)}
|
|
38
|
-
}`:"{}";if(o.length===0)return f;let u=o[0];for(let l=1;l<o.length;l++)u=`Omit<${u}, keyof ${o[l]}> & ${o[l]}`;return s.length>0?`Omit<${u}, keyof ${f}> & ${f}`:u}function mr(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(!ht(e.charCodeAt(r)))return!1;return!0}function pr(e){let t=e.split(".");return t.length>0&&t.every(mr)}function sf(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=Qe(e,n,"<",">");if(s!==-1)n=s}}return-1}function Zs(e){if(e.length<3||!e.endsWith(")"))return null;let t=sf(e);if(t===-1||Qe(e,t,"(",")")!==e.length-1)return null;let r=e.slice(0,t).trim(),n=!1;if(r.endsWith("?."))n=!0,r=r.slice(0,-2).trim();let i=r,s=!1,o=r.indexOf("<");if(o!==-1){if(Qe(r,o,"<",">")!==r.length-1)return null;i=r.slice(0,o).trim(),s=!0}if(!pr(i))return null;let a=e.slice(t+1,-1).trim(),c=jr(a)!==-1||a.startsWith("function")||a.startsWith("async function"),f=pr(a),u=!c&&a.endsWith(")")&&Zs(a)!==null;if(!s&&!n&&!c&&!f&&!u)return null;let l=`ReturnType<typeof ${r}>`;return n?`${l} | undefined`:l}function of(e){let t=e.split(`
|
|
39
|
-
`).map((f)=>Xs(f)).join(`
|
|
40
|
-
`),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(!ht(f)&&!ht(u))t=(t.slice(0,r)+t.slice(r+5)).trim()}let n=t.indexOf("(");if(n!==-1){let f=Qe(t,n,"(",")");if(f!==-1){let u=t.slice(n,f+1),l=_t(u);t=t.slice(0,n)+l+t.slice(f+1)}}let i=t.length,s="",o=[],a=!1,c=!1;for(let f=0;f<i;f++){let u=t.charCodeAt(f);if(u===123||u===40)o.push(u);else if(u===125||u===41)o.pop();if(u<=32){if(a=!0,u===10||u===13)c=!0;continue}if(a&&s.length>0){let l=(o.length>0?o[o.length-1]:0)===123;if(c&&l){let g=s.charCodeAt(s.length-1),p=g===59||g===44||g===123||u===125,v=s.length>=2&&s.charCodeAt(s.length-1)===47&&s.charCodeAt(s.length-2)===42;if(!p&&!v)s+="; ";else s+=" "}else s+=" "}a=!1,c=!1,s+=t[f]}return s.trim()}function ht(e){return e>=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57||e===95||e===36}function _t(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 v=0;for(let b=0;b<i.length;b++){let w=i.charCodeAt(b);if(w===40||w===60||w===91||w===123)v++;else if(w===41||w===62||w===93||w===125)v--;else if(v===0&&w===61){let T=b>0?i.charCodeAt(b-1):0,k=b+1<i.length?i.charCodeAt(b+1):0;if(T!==61&&T!==33&&T!==60&&T!==62&&k!==61&&k!==62){s=!0;break}}}}if(!s)return t;let o=[],a=[],c=0,f=0,u=!1,l=0;for(let v=0;v<=i.length;v++){if(v===i.length){o.push(i.slice(c));break}let b=i.charCodeAt(v);if(u){if(b===92){v++;continue}if(b===l)u=!1;continue}if(b===47&&v+1<i.length){let w=i.charCodeAt(v+1);if(w===42){v+=2;while(v+1<i.length&&!(i.charCodeAt(v)===42&&i.charCodeAt(v+1)===47))v++;v++;continue}if(w===47){while(v<i.length&&i.charCodeAt(v)!==10)v++;continue}}if(b===39||b===34||b===96){u=!0,l=b;continue}if(b===40||b===60||b===91||b===123)f++;else if(b===41||b===62||b===93||b===125)f--;else if(b===44&&f===0){o.push(i.slice(c,v));let w=",",T=v+1;while(T<i.length&&i.charCodeAt(T)<=32)w+=i[T],T++;a.push(w),c=T}}let g=[];for(let v of o){let b=v.trim();if(!b){g.push(v);continue}if(b.startsWith("//"))continue;let w=Xs(b),T=v.slice(0,v.length-v.trimStart().length);g.push(T+af(w))}let p=g[0]||"";for(let v=1;v<g.length;v++)p+=(a[v-1]||", ")+g[v];return n?`(${p})`:p}function Xs(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 af(e){if(e.startsWith("..."))return e;let t=-1,r=-1,n=0,i=!1,s=0;for(let a=0;a<e.length;a++){let c=e.charCodeAt(a);if(i){if(c===92){a++;continue}if(c===s)i=!1;continue}if(c===47&&a+1<e.length){let f=e.charCodeAt(a+1);if(f===42){a+=2;while(a+1<e.length&&!(e.charCodeAt(a)===42&&e.charCodeAt(a+1)===47))a++;a++;continue}if(f===47){while(a<e.length&&e.charCodeAt(a)!==10)a++;continue}}if(c===39||c===34||c===96){i=!0,s=c;continue}if(c===40||c===60||c===91||c===123)n++;else if(c===41||c===62||c===93||c===125)n--;else if(n===0){if(c===58&&t===-1)t=a;else if(c===61&&r===-1&&(a===0||e.charCodeAt(a-1)!==61)&&(a+1>=e.length||e.charCodeAt(a+1)!==61&&e.charCodeAt(a+1)!==62))r=a}}let o=r!==-1;if(t!==-1&&(r===-1||t<r)){let a=e.slice(0,t).trim(),c=r!==-1?e.slice(t+1,r).trim():e.slice(t+1).trim(),f=o&&!a.endsWith("?")?"?":"";return`${a}${f}: ${c}`}else if(r!==-1){let a=e.slice(0,r).trim(),c=!a.endsWith("?")?"?":"",f=e.slice(r+1).trim(),u="unknown";if(f==="true"||f==="false")u="boolean";else if(/^-?\d+(\.\d+)?$/.test(f))u="number";else if(f.startsWith("'")&&f.endsWith("'")||f.startsWith('"')&&f.endsWith('"'))u="string";else if(f.startsWith("["))u="unknown[]";else if(f.startsWith("{"))u="Record<string, unknown>";return`${a}${c}: ${u}`}return e}function lf(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 cf(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(`
|
|
41
|
-
`),key:e.slice(r).trim()}}function ff(e){let t=[],r="",n="",i=0,s=!1,o="",a=!0,c=!1,f=0,u=!1,l=!1,g=0,p=!1,v=!1;for(let b=0;b<e.length;b++){let w=e.charCodeAt(b),T=b>0?e.charCodeAt(b-1):0,k=b<e.length-1?e.charCodeAt(b+1):0;if(!s&&!c&&w===47&&k===47){b+=2;while(b<e.length&&e.charCodeAt(b)!==10)b++;continue}if(!s&&!c&&w===47&&k===42){c=!0,f=1,r+="/*",b++;continue}else if(c&&w===42&&k===47){if(f--,r+="*/",b++,f===0)c=!1;continue}else if(c&&w===47&&k===42){f++,r+="/*",b++;continue}let R=e[b];if(!s&&(w===34||w===39||w===96))s=!0,o=R,r+=R;else if(s&&R===o&&T!==92)s=!1,r+=R;else if(!s&&!c)if(w===40&&i===0&&a&&g===0){n=r.trim();let I=lf(n),_=I>0?n.slice(0,I):"",W=n.slice(I),P="";if(W.startsWith("async ")||W.startsWith("async\t")||W.startsWith(`async
|
|
42
|
-
`))W=W.slice(6).trimStart(),P="async ";if(W.startsWith("*"))W=W.slice(1).trimStart(),P+="*";n=_+W,r=P+R,a=!1,p=!0,v=!1,i=1}else if(w===123||w===91||w===40){if(i++,r+=R,v&&w===123)v=!1}else if(w===125||w===93||w===41){if(i--,r+=R,w===41&&i===0&&!a&&!p)u=!0;if(p){if(w===41&&i===0&&!v)v=!0;else if(w===125&&i===0)p=!1,v=!1}}else if(w===58&&i===0&&a&&g===0)n=r.trim(),r="",a=!1;else if(w===58&&i===0&&u)l=!0,r+=R;else if(w===60&&l)g++,r+=R;else if(w===60&&a&&i===0)g++,r+=R;else if(w===62&&g>0&&T!==61)g--,r+=R;else if(w===61&&k===62&&l&&g===0)l=!1,u=!1,r+=R;else if(w===44&&i===0&&g===0&&!v){if(n&&r.trim()){let I=r.trim();t.push([n,I])}else if(a&&r.trim()){let I=r.trim();if(mr(I))t.push([I,I]);else if(I.startsWith("...")&&I.length>3)t.push(["...",I.slice(3).trim()])}r="",n="",a=!0,u=!1,l=!1,g=0}else r+=R;else r+=R}if(n&&r.trim()){let b=r.trim();t.push([n,b])}else if(a&&r.trim()){let b=r.trim();if(mr(b))t.push([b,b]);else if(b.startsWith("...")&&b.length>3)t.push(["...",b.slice(3).trim()])}return t}function uf(e){let t=e.trim();if(t.startsWith("get ")&&t.length>4){let r=t.slice(4).trim();if(r)return{kind:"get",name:r}}if(t.startsWith("set ")&&t.length>4){let r=t.slice(4).trim();if(r)return{kind:"set",name:r}}return null}function hf(e,t,r){let n=r.trim();if(n.charCodeAt(0)!==40)return null;let i=Qe(n,0,"(",")");if(i===-1)return null;let s=n.slice(1,i).trim(),o=n.slice(i+1).trimStart();if(!o.startsWith("=>"))return null;let a=o.slice(2).trim();if(e==="get")return`get ${t}(): ${a||"unknown"}`;return`set ${t}(${s})`}function df(e){let t=e;if(t.startsWith("async ")||t.startsWith("async\t"))t=t.slice(5).trimStart();if(t.startsWith("*"))t=t.slice(1).trimStart();if(!t.startsWith("("))return!1;let r=0;for(let n=0;n<t.length;n++){let i=t.charCodeAt(n);if(i===40)r++;else if(i===41){if(r--,r===0){let s=t.slice(n+1).trimStart();if(s.startsWith("{"))return!0;if(s.startsWith(":")){let o=Qs(s,1);if(o?.kind==="arrow")return!1;if(o?.kind==="body")return!0}return!1}}}return!1}function mf(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 zs(e,t){let r=t.trimStart(),n=!1,i=!1;if(r.startsWith("async ")||r.startsWith("async\t"))n=!0,r=r.slice(5).trimStart();if(r.startsWith("*"))i=!0,r=r.slice(1).trimStart();let s="";if(r.charCodeAt(0)===60){let g=0,p=-1;for(let v=0;v<r.length;v++)if(r.charCodeAt(v)===60)g++;else if(r.charCodeAt(v)===62&&!(v>0&&r.charCodeAt(v-1)===61)){if(g--,g===0){p=v;break}}if(p!==-1)s=r.slice(0,p+1),r=r.slice(p+1).trimStart()}let o=r.indexOf("("),a=Qe(r,o,"(",")");if(o===-1||a===-1)return"() => unknown";let c=r.slice(o,a+1),f="unknown",u=r.slice(a+1).trimStart();if(u.charCodeAt(0)===58){let g=u.slice(1),p=Qs(g,0);if(p)f=g.slice(0,p.index).trim();else f=g.trim()}if(f==="unknown"){if(n&&i)f="AsyncGenerator<unknown, void, unknown>";else if(i)f="Generator<unknown, void, unknown>";else if(n)f="Promise<void>"}else if(n&&!f.startsWith("Promise<")&&!f.startsWith("AsyncGenerator<"))f=`Promise<${f}>`;let l=_t(c);return`${s}${l} => ${f}`}function Qs(e,t){let r=0,n=0,i=0,s=0,o=!1,a=0;for(let c=t;c<e.length;c++){let f=e.charCodeAt(c);if(o){if(f===92)c++;else if(f===a)o=!1;continue}if(f===34||f===39||f===96){o=!0,a=f;continue}if(f===40)r++;else if(f===41&&r>0)r--;else if(f===91)n++;else if(f===93&&n>0)n--;else if(f===60)i++;else if(f===62&&i>0&&e.charCodeAt(c-1)!==61)i--;else if(f===125&&s>0)s--;else if(f===123){let u=r>0||n>0||i>0||s>0,l=e.slice(t,c).trimEnd(),g=l.charCodeAt(l.length-1),p=l.length===0||g===38||g===124||g===40||g===44||g===58||g===61||g===91;if(u||p)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 Qe(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 jr(e){let t=0,r=0,n=!1,i="";for(let s=0;s<e.length-1;s++){let o=e[s],a=e[s+1],c=s>0?e[s-1]:"";if(!n&&(o==='"'||o==="'"||o==="`"))n=!0,i=o;else if(n&&o===i&&c!=="\\")n=!1;if(!n){if(o==="<"){let f=Qe(e,s,"<",">");if(f!==-1){s=f;continue}}if(o==="(")t++;else if(o===")")t--;else if(o==="[")r++;else if(o==="]")r--;if(o==="="&&a===">"&&t===0&&r===0)return s}}return-1}function eo(e,t=!1,r=0,n=!0){let i=e.trim();if(i.length>200&&ln(i,"=>")>2&&ln(i,"<")>5&&!i.startsWith("function"))return t?"((...args: any[]) => any)":"(...args: any[]) => any";if(i.startsWith("async ")&&i.includes("=>")){let o=i.slice(5).trim(),a=jr(o);if(a===-1)return t?"(() => Promise<unknown>)":"() => Promise<unknown>";let c=o.substring(0,a).trim(),f=o.substring(a+2).trim(),u=Hs(c),{params:l,returnType:g}=u;if(l=_t(l),l==="()"||l==="")l="()";else if(!l.startsWith("("))l=`(${l})`;let p=g;if(p);else if(f.startsWith("{"))p=dr(f.slice(1,f.endsWith("}")?-1:void 0),!0,l);else p=Te(f,n,!1,r+1);let v=`${l} => ${g||p.startsWith("Promise<")?p:`Promise<${p}>`}`;return t?`(${v})`:v}if(i.includes("=>")){let o="",a=i;if(i.startsWith("<")){let w=Qe(i,0,"<",">");if(w!==-1)o=i.substring(0,w+1),a=i.substring(w+1).trim()}let c=jr(a);if(c===-1)return t?"(() => unknown)":"() => unknown";let f=a.substring(0,c).trim(),u=a.substring(c+2).trim(),l=Hs(f),{params:g,returnType:p}=l;if(g=_t(g),g==="()"||g==="")g="()";else if(!g.startsWith("("))g=`(${g})`;let v="unknown";if(p)v=p;else if(u.startsWith("{"))v=dr(u.slice(1,u.endsWith("}")?-1:void 0),!1,g);else if(Br(u)||qs(u)&&Br(u.slice(1,-1).trim()))v="JSX.Element";else if(u.includes("=>")){let w=u.trimStart(),T=w.indexOf("("),k=T!==-1?Qe(w,T,"(",")"):-1,R=k!==-1?w.indexOf("=>",k):-1;if(T===0&&k!==-1&&R!==-1){let I=w.substring(T+1,k).trim(),_=_t(I);if(o.includes("T")&&_.includes("T"))v=`(${_}) => T`;else v=`(${_}) => any`}else v="any"}else if(t)v="unknown";else v=Rt(u,Js(g));let b=`${o}${g} => ${v}`;return t?`(${b})`:b}if(i.startsWith("function")){let o=8,a=i.length;while(o<a&&i.charCodeAt(o)<=32)o++;let c=!1;if(o<a&&i.charCodeAt(o)===42){c=!0,o++;while(o<a&&i.charCodeAt(o)<=32)o++}let f="";if(o<a&&i.charCodeAt(o)===60){let g=o,p=1;o++;while(o<a&&p>0){let v=i.charCodeAt(o);if(v===60)p++;else if(v===62&&i.charCodeAt(o-1)!==61)p--;o++}f=i.substring(g,o);while(o<a&&i.charCodeAt(o)<=32)o++}let u=i.indexOf("(",o);if(u!==-1){let g=1,p=u+1;while(p<a&&g>0){let T=i.charCodeAt(p);if(T===40)g++;else if(T===41)g--;p++}let v=i.substring(u+1,p-1).trim(),b=v?`(${v})`:"()";if(c){let T=i.substring(p).trim(),k=T.indexOf("Generator<");if(k!==-1){let I=k+10,_=T.indexOf(">",I);if(_!==-1){let W=T.substring(I,_),P=`${f}${b} => Generator<${W}>`;return t?`(${P})`:P}}let R=`${f}${b} => Generator<any, any, any>`;return t?`(${R})`:R}let w=`${f}${b} => unknown`;return t?`(${w})`:w}let l="(...args: any[]) => unknown";return t?`(${l})`:l}if(i.includes("=>")&&i.includes("(")&&i.includes(")")){if(i.length>100||ln(i,"=>")>2){let o="";if(i.charCodeAt(0)===60){let l=Qe(i,0,"<",">");if(l!==-1)o=i.substring(0,l+1)}let a=i.indexOf("("),c=a!==-1?Qe(i,a,"(",")"):-1,f=a!==-1&&c!==-1?i.substring(a,c+1):"(...args: any[])";f=_t(f);let u=`${o}${f} => any`;return t?`(${u})`:u}return t?`(${i})`:i}let s="() => unknown";return t?`(${s})`:s}function Hs(e){let t=e.trim();if(!t.startsWith("("))return{params:t,returnType:""};let r=Qe(t,0,"(",")");if(r===-1)return{params:t,returnType:""};let n=t.slice(r+1).trim();return{params:t.slice(0,r+1),returnType:n.startsWith(":")?n.slice(1).trim():""}}function to(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 ro(e){let t=e.lastIndexOf(" satisfies ");if(t===-1)return null;let r=e.slice(t+11).trim();if(r.endsWith(";"))r=r.slice(0,-1).trim();return r||null}var _r=!1,Ve=null;var pn=()=>{};function Me(e){return e===Se||e===$e||e===oe||e===ye}function kt(e){return e>=65&&e<=90||e>=97&&e<=122||e===gf||e===so||e>127}function Ke(e){return kt(e)||e>=48&&e<=57}function yf(e){let t=!0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n===ft){if(t)return!1;t=!0}else if(t){if(!kt(n))return!1;t=!1}else if(!Ke(n))return!1}return e.length>0&&!t}function Kr(e,t,r){let n=t+1;while(n<e.length){let i=e.charCodeAt(n);if(i===Ue){n+=2;continue}if(n++,i===r)break}return n}function Cf(e){if(e==="any"||e==="object"||e==="unknown")return!0;if(e.startsWith("Record<")||e.startsWith("Array<"))return!0;return e.charCodeAt(0)===V&&e.includes("[")&&e.includes("]:")}function oo(e,t,r=!0){return lo(e,t,r,!0)}function ao(e,t,r=!0){return lo(e,t,r,!1)}function lo(e,t,r,n){let i=e,s=r,o=n,a=i.length,c=[],f=new Map,u=new Set,l=0;if(l<a&&i.charCodeAt(l)===65279)l++;function g(m,h){if(m<h){let d=i.charCodeAt(m),y=i.charCodeAt(h-1);if(d!==Se&&d!==$e&&d!==oe&&d!==ye&&y!==Se&&y!==$e&&y!==oe&&y!==ye)return i.slice(m,h)}while(m<h&&Me(i.charCodeAt(m)))m++;while(h>m&&Me(i.charCodeAt(h-1)))h--;return i.slice(m,h)}function p(){if(l>=a)return;let m=i.charCodeAt(l);if(m!==Se&&m!==$e&&m!==oe&&m!==ye&&m!==H)return;while(l<a){let h=i.charCodeAt(l);if(h===Se||h===$e||h===oe||h===ye){l++;continue}if(h===H&&l+1<a){let d=i.charCodeAt(l+1);if(d===H){let y=i.indexOf(`
|
|
43
|
-
`,l+2);l=y===-1?a:y+1;continue}if(d===ge){let y=i.indexOf("*/",l+2);l=y===-1?a:y+2;continue}}break}}function v(m){let h=m.length,d=0,y=h;for(let C=0;C<h;C++){let E=m.charCodeAt(C);if(d){if(E===Ue){C++;continue}if(E===d)d=0;continue}if(E===te||E===se||E===Ae){d=E;continue}if(E===H&&C+1<h){let x=m.charCodeAt(C+1);if(x===H){y=C;while(y>0&&(m.charCodeAt(y-1)===Se||m.charCodeAt(y-1)===$e))y--;return m.slice(0,y)}if(x===ge){let O=m.indexOf("*/",C+2);if(O!==-1){m=`${m.slice(0,C)} ${m.slice(O+2)}`,C--;continue}}}}y=h;while(y>0&&(m.charCodeAt(y-1)===Se||m.charCodeAt(y-1)===$e||m.charCodeAt(y-1)===ye))y--;return y<h?m.slice(0,y):m}function b(m){l++;let h=m===te?"'":'"';while(l<a){let d=i.indexOf(h,l);if(d===-1){l=a;return}let y=0,C=d-1;while(C>=0&&i.charCodeAt(C)===Ue)y++,C--;if(y%2===0){l=d+1;return}l=d+1}}function w(){l++;let m=[];while(l<a){let h=i.charCodeAt(l);if(m.length===0){if(h===Ue){l+=2;continue}if(h===Ae){l++;return}if(h===so&&l+1<a&&i.charCodeAt(l+1)===V){l+=2,m.push(0);continue}l++;continue}if(h===te||h===se){b(h);continue}if(h===Ae){w();continue}if(h===H&&l+1<a){let d=i.charCodeAt(l+1);if(d===H){let y=i.indexOf(`
|
|
44
|
-
`,l+2);l=y===-1?a:y+1;continue}if(d===ge){let y=i.indexOf("*/",l+2);l=y===-1?a:y+2;continue}if(I()){_();continue}l++;continue}if(h===V){m[m.length-1]++,l++;continue}if(h===J){let d=m[m.length-1];if(d===0){m.pop(),l++;continue}m[m.length-1]=d-1,l++;continue}l++}}function T(){let m=i.charCodeAt(l);if(m===te||m===se)return b(m),!0;if(m===Ae)return w(),!0;if(m===H&&l+1<a){let h=i.charCodeAt(l+1);if(h===H){let d=i.indexOf(`
|
|
45
|
-
`,l+2);return l=d===-1?a:d+1,!0}if(h===ge){let d=i.indexOf("*/",l+2);return l=d===-1?a:d+2,!0}if(I())return _(),!0}return!1}function k(m){let h=m;for(;;){while(h>=0&&(i.charCodeAt(h)===Se||i.charCodeAt(h)===$e||i.charCodeAt(h)===oe||i.charCodeAt(h)===ye))h--;if(h<0)return-1;if(i.charCodeAt(h)===H&&h>0&&i.charCodeAt(h-1)===ge){let C=i.lastIndexOf("/*",h-2);if(C===-1)return-1;h=C-1;continue}let d=i.lastIndexOf(`
|
|
46
|
-
`,h)+1,y=R(d,h);if(y!==-1){h=y-1;continue}return h}}function R(m,h){let d=0;for(let y=m;y<=h;y++){let C=i.charCodeAt(y);if(d){if(C===Ue){y++;continue}if(C===d)d=0;continue}if(C===te||C===se||C===Ae){d=C;continue}if(C===H&&y+1<=h&&i.charCodeAt(y+1)===H)return y}return-1}function I(){let m=k(l-1);if(m<0)return!0;let h=i.charCodeAt(m);if(h===Ce||h===Q||h===ue||h===33||h===38||h===124||h===Vr||h===et||h===tt||h===Y||h===V||h===J||h===94||h===126||h===43||h===45||h===ge||h===37||h===he||h===ne)return!0;if(Ke(h)){let d=m;while(d>=0&&Ke(i.charCodeAt(d)))d--;let y=i.slice(d+1,m+1);if(y==="return"||y==="typeof"||y==="void"||y==="delete"||y==="throw"||y==="new"||y==="in"||y==="of"||y==="case"||y==="instanceof"||y==="yield"||y==="await")return!0}return!1}function _(){l++;let m=!1;while(l<a){let h=i.charCodeAt(l);if(h===Ue){l+=2;continue}if(m){if(h===be)m=!1;l++;continue}if(h===ue){m=!0,l++;continue}if(h===H){l++;break}if(h===oe||h===ye)break;l++}while(l<a&&Ke(i.charCodeAt(l)))l++}function W(){let m=l;while(l<a&&Ke(i.charCodeAt(l)))l++;return i.slice(m,l)}function P(m){if(l+m.length>a)return!1;for(let h=0;h<m.length;h++)if(i.charCodeAt(l+h)!==m.charCodeAt(h))return!1;if(l+m.length<a&&Ke(i.charCodeAt(l+m.length)))return!1;return!0}function F(m){let h=l+m;while(h<a){let d=i.charCodeAt(h);if(d===Se||d===$e||d===oe||d===ye){h++;continue}return d!==ft&&d!==Ce}return!1}function U(){if(l>=a)return!1;switch(i.charCodeAt(l)){case 101:return P("export")||P("enum");case 105:return P("import")||P("interface");case 102:return P("function");case 99:return P("class")||P("const");case 116:return P("type");case 108:return P("let");case 118:return P("var");case 100:return P("declare")||P("default");case 109:return P("module");case 110:return P("namespace");case 97:return P("abstract")||P("async");default:return!1}}function q(){let m=i.charCodeAt(l);if(m!==oe&&m!==ye)return!1;let h=l;if(l++,m===ye&&l<a&&i.charCodeAt(l)===oe)l++;while(l<a){let y=i.charCodeAt(l);if(y===Se||y===$e||y===ye||y===oe){l++;continue}if(y===H&&l+1<a){let C=i.charCodeAt(l+1);if(C===H){let E=i.indexOf(`
|
|
47
|
-
`,l+2);l=E===-1?a:E+1;continue}if(C===ge){let E=i.indexOf("*/",l+2);l=E===-1?a:E+2;continue}}break}let d=l>=a||U()||i.charCodeAt(l)===J;return l=h,d}function le(m){let h=m-1;while(h>=0){let S=i.charCodeAt(h);if(S===Se||S===$e||S===ye||S===oe){h--;continue}break}if(h<0)return!0;let d=i[h];if("+-*/%=<>&|^!~?:,.([{".includes(d))return!0;let y=h;while(y>0&&i.charCodeAt(y-1)!==oe)y--;let C=i.slice(y,h+1),E=C.lastIndexOf("<");if(E!==-1&&/^<[A-Za-z]/.test(C.slice(E))&&!C.slice(E).includes(">"))return!0;let x=h;while(x>=0&&/[a-z]/i.test(i[x]))x--;let O=i.slice(x+1,h+1);return["as","in","of","new","typeof","keyof","extends","instanceof","satisfies","await","return","yield","void"].includes(O)}function z(){let m=i.charCodeAt(l);if(m!==oe&&m!==ye)return!1;if(le(l))return!1;let h=l;l++;while(l<a){let E=i.charCodeAt(l);if(E===Se||E===$e||E===ye||E===oe){l++;continue}if(E===H&&l+1<a){let x=i.charCodeAt(l+1);if(x===H){let O=i.indexOf(`
|
|
48
|
-
`,l+2);l=O===-1?a:O+1;continue}if(x===ge){let O=i.indexOf("*/",l+2);l=O===-1?a:O+2;continue}}break}let d=l<a?i[l]:"",y=i.slice(l,l+2),C=d==="."||d==="?"||d===":"||d===")"||d==="]"||d==="}"||d===","||d==="+"||d==="-"||d==="*"||d==="/"||d==="%"||d==="<"||d===">"||d==="="||d==="&"||d==="|"||d==="^"||d==="`"||y==="=>"||P("as")||P("satisfies")||P("instanceof")||P("in");return l=h,!C}function Z(){let m=i.charCodeAt(l);if(m!==oe&&m!==ye)return!1;if(le(l))return!1;let h=l;l++;while(l<a){let C=i.charCodeAt(l);if(C===Se||C===$e||C===ye||C===oe){l++;continue}if(C===H&&l+1<a){let E=i.charCodeAt(l+1);if(E===H){let x=i.indexOf(`
|
|
49
|
-
`,l+2);l=x===-1?a:x+1;continue}if(E===ge){let x=i.indexOf("*/",l+2);l=x===-1?a:x+2;continue}}break}let d=l<a?i[l]:"",y=d==="|"||d==="&"||d==="["||d==="."||d==="?"||d===":"||d===">"||d===")"||d===","||P("extends");return l=h,!y}function ie(){let m=i.charCodeAt(l);if(m!==oe&&m!==ye)return!1;let h=l;if(l++,m===ye&&l<a&&i.charCodeAt(l)===oe)l++;while(l<a){let y=i.charCodeAt(l);if(y===Se||y===$e||y===ye||y===oe){l++;continue}if(y===H&&l+1<a&&i.charCodeAt(l+1)===H){let C=i.indexOf(`
|
|
50
|
-
`,l+2);l=C===-1?a:C+1;continue}break}if(l>=a)return l=h,!0;let d=i.charCodeAt(l);if(d===124||d===38||d===ft||d===Vr||d===et)return l=h,!1;if(P("extends")||P("keyof")||P("typeof")||P("infer")||P("is")||P("as")||P("in"))return l=h,!1;return l=h,!0}let X=/[{}'"`\/]/g,Pe=/[()'"`\/]/g,Re=/[[\]'"`\/]/g,It=/[<>'"`\/]/g;function Oe(m,h){let d=1;l++;let y=m===V?X:m===Q?Pe:m===ue?Re:It;y.lastIndex=l;let C;while((C=y.exec(i))!==null){let E=C.index,x=i.charCodeAt(E);if(x===te||x===se){l=E,b(x),y.lastIndex=l;continue}if(x===Ae){l=E,w(),y.lastIndex=l;continue}if(x===H){if(l=E,T()){y.lastIndex=l;continue}y.lastIndex=E+1;continue}if(x===m)d++;else if(x===h){if(h===ne&&E>0&&i.charCodeAt(E-1)===Ce){y.lastIndex=E+1;continue}if(d--,d===0)return l=E+1,l}y.lastIndex=E+1}return l=a,l}function ke(){return l>0&&i.charCodeAt(l-1)===Ce}function ut(){return l+1<a&&i.charCodeAt(l+1)===ne}let ce=/[<{};'"`\/\n\r()[\]]/g;function ee(){let m=0,h=0,d=0,y=0,C=i.charCodeAt(l)===V;ce.lastIndex=l;let E;while((E=ce.exec(i))!==null){let x=E.index,O=i.charCodeAt(x);if(O===te||O===se){l=x,b(O),ce.lastIndex=l;continue}if(O===Ae){l=x,w(),ce.lastIndex=l;continue}if(O===H){if(x>0&&i.charCodeAt(x-1)===he){ce.lastIndex=x+1;continue}if(l=x,T()){ce.lastIndex=l;continue}ce.lastIndex=x+1;continue}if(O===he){let S=As(x);if(S!==null)y=Math.max(0,y+S);ce.lastIndex=x+1;continue}if(O===Q){h++,ce.lastIndex=x+1;continue}if(O===we){h--,ce.lastIndex=x+1;continue}if(O===ue){d++,ce.lastIndex=x+1;continue}if(O===be){d--,ce.lastIndex=x+1;continue}if(O===V){m++,ce.lastIndex=x+1;continue}if(O===J){let S=m>0;if(S)m--;if((!S||C)&&m===0&&h===0&&d===0&&y===0){l=x+1;return}ce.lastIndex=x+1;continue}if(O===Y&&m===0&&h===0&&d===0&&y===0){l=x+1;return}if((O===oe||O===ye)&&m===0&&h===0&&d===0&&y===0){if(l=x,q())return}ce.lastIndex=x+1}l=a}function Ft(){l++;while(l<a&&(i.charCodeAt(l)===Se||i.charCodeAt(l)===$e))l++;let m=i.indexOf(`
|
|
51
|
-
`,l),h=m===-1?a:m,d=i.indexOf(";",l);if(d!==-1&&d<h){let y=d-1;while(y>=l&&(i.charCodeAt(y)===Se||i.charCodeAt(y)===$e))y--;let C=i.charCodeAt(l),E=i.charCodeAt(y);if(C===V&&E===J||C===ue&&E===be||C===te&&E===te||C===se&&E===se||C===Ae&&E===Ae){l=d+1;return}}ee()}function sr(){Oe(V,J);while(l<a&&Me(i.charCodeAt(l)))l++;if(P("from")){l+=4;while(l<a&&Me(i.charCodeAt(l)))l++;if(l<a){let m=i.charCodeAt(l);if(m===te||m===se)b(m)}}while(l<a&&(i.charCodeAt(l)===Se||i.charCodeAt(l)===$e))l++;if(l<a&&i.charCodeAt(l)===Y)l++}function vs(){l++;while(l<a&&Me(i.charCodeAt(l)))l++;if(P("as")){l+=2;while(l<a&&Me(i.charCodeAt(l)))l++;W();while(l<a&&Me(i.charCodeAt(l)))l++}if(P("from")){l+=4;while(l<a&&Me(i.charCodeAt(l)))l++;if(l<a){let m=i.charCodeAt(l);if(m===te||m===se)b(m)}}while(l<a&&(i.charCodeAt(l)===Se||i.charCodeAt(l)===$e))l++;if(l<a&&i.charCodeAt(l)===Y)l++}function kr(m){let h=m.indexOf("from ");if(h===-1)return;let d=h+5;while(d<m.length&&(m.charCodeAt(d)===32||m.charCodeAt(d)===9))d++;if(d>=m.length)return;let y=m.charCodeAt(d);if(y!==39&&y!==34)return;let C=m.indexOf(m[d],d+1);if(C===-1)return;return m.slice(d+1,C)}function qe(m){if(!s)return;let h=m-1;while(h>=0&&Me(i.charCodeAt(h)))h--;if(h<0)return;let d=[],y=!1;while(h>=0){if(h>=1&&i.charCodeAt(h)===H&&i.charCodeAt(h-1)===ge){let x=i.lastIndexOf("/*",h-2);if(x>=0){d.push(i.slice(x,h+1)),y=!0,h=x-1;while(h>=0&&Me(i.charCodeAt(h)))h--;continue}break}let C=h;while(C>0&&i.charCodeAt(C-1)!==oe)C--;let E=g(C,h+1);if(E.startsWith("//")){if(y)break;let x=[E];h=C-1;while(h>=0&&(i.charCodeAt(h)===oe||i.charCodeAt(h)===ye))h--;while(h>=0){let O=h;while(O>0&&i.charCodeAt(O-1)!==oe)O--;let S=g(O,h+1);if(S.startsWith("//")){x.push(S),h=O-1;while(h>=0&&(i.charCodeAt(h)===oe||i.charCodeAt(h)===ye))h--}else if(S===""){h=O-1;while(h>=0&&(i.charCodeAt(h)===oe||i.charCodeAt(h)===ye))h--}else break}x.reverse(),d.push(x.join(`
|
|
52
|
-
`));continue}break}if(d.length===0)return;return d.reverse(),d}function oc(m){let h=m,d=!1;while(l<a){let S=i.charCodeAt(l);if(S===Y){l++;break}if(S===te||S===se){b(S),d=!0;while(l<a&&(i.charCodeAt(l)===Se||i.charCodeAt(l)===$e))l++;if(l<a&&i.charCodeAt(l)===Y)l++;break}if(S===oe&&d)break;l++}let y=g(h,l),C=y.charCodeAt(7)===116&&(y.startsWith("import type ")||y.startsWith("import type{")),E=!1;{let S=6;while(S<y.length&&(y.charCodeAt(S)===Se||y.charCodeAt(S)===$e))S++;if(S<y.length&&y.charCodeAt(S)===116&&y.startsWith("type",S)){S+=4;while(S<y.length&&(y.charCodeAt(S)===Se||y.charCodeAt(S)===$e))S++}if(S<y.length){let A=y.charCodeAt(S);E=A===te||A===se}}let x="";{let S=y.indexOf("from ");if(S!==-1){let A=S+5;while(A<y.length&&(y.charCodeAt(A)===Se||y.charCodeAt(A)===$e))A++;if(A<y.length){let M=y.charCodeAt(A);if(M===te||M===se){let N=y.indexOf(String.fromCharCode(M),A+1);if(N!==-1)x=y.slice(A+1,N)}}}else if(E){let A=6;while(A<y.length&&y.charCodeAt(A)!==te&&y.charCodeAt(A)!==se)A++;if(A<y.length){let M=y.charCodeAt(A),N=y.indexOf(String.fromCharCode(M),A+1);if(N!==-1)x=y.slice(A+1,N)}}}let O=qe(h);return{kind:"import",name:"",text:y,isExported:!1,isTypeOnly:C,isSideEffect:E,source:x,leadingComments:O,start:h,end:l}}function ji(){let m=l;return Oe(V,J),i.slice(m,l)}function Es(m){let h=m.indexOf("(");if(h===-1)return m;let d=m.slice(h);if(d.indexOf("=")===-1)return m;let y=!1;for(let S=0;S<d.length;S++)if(d.charCodeAt(S)===61){let A=S>0?d.charCodeAt(S-1):0,M=S+1<d.length?d.charCodeAt(S+1):0;if(A!==61&&A!==33&&A!==60&&A!==62&&M!==61&&M!==62){y=!0;break}}if(!y)return m;let C=0,E=-1;for(let S=h;S<m.length;S++){let A=m.charCodeAt(S);if(A===40)C++;else if(A===41){if(C--,C===0){E=S;break}}}if(E===-1)return m;let x=m.slice(h,E+1),O=Nt(x);return m.slice(0,h)+O+m.slice(E+1)}function bs(m){let h=m.indexOf("//")!==-1||m.indexOf("/*")!==-1,d=m.split(`
|
|
53
|
-
`),y=[],C=[],E=[],x=!1,O=1/0;for(let M=0;M<d.length;M++){let N=d[M];if(h){if(x){if(N.includes("*/"))x=!1;continue}let G=N.trim();if(G.length===0)continue;let L=G.charCodeAt(0);if(L===H){let je=G.charCodeAt(1);if(je===H)continue;if(je===ge){if(!G.includes("*/"))x=!0;continue}}if(L===ge)continue;let D=v(N);if(D.charCodeAt(D.length-1)===Y)D=D.slice(0,-1);D=Es(D);let B=D.trim();if(!B)continue;y.push(D),C.push(B);let j=0;while(j<D.length&&Me(D.charCodeAt(j)))j++;if(B!=="{"&&B!=="}"){if(j<O)O=j}E.push(j)}else{let G=N.length;while(G>0&&(N.charCodeAt(G-1)===Se||N.charCodeAt(G-1)===$e||N.charCodeAt(G-1)===ye))G--;if(G===0)continue;let L=G<N.length?N.slice(0,G):N;if(L.charCodeAt(L.length-1)===Y)L=L.slice(0,-1);L=Es(L);let D=L.trim();if(!D)continue;y.push(L),C.push(D);let B=0;while(B<L.length&&Me(L.charCodeAt(B)))B++;if(D!=="{"&&D!=="}"){if(B<O)O=B}E.push(B)}}if(y.length===0)return"{}";if(O===1/0||O<=2)return y.join(`
|
|
54
|
-
`);let S=O-2,A=Array(y.length);for(let M=0;M<y.length;M++){let N=C[M];if(N==="{"){A[M]=N;continue}let G=E[M];if(G>O)A[M]=y[M];else if(G===O&&(N.charCodeAt(0)===J||N.charCodeAt(0)===be||N.charCodeAt(0)===we))A[M]=y[M];else{let L=Math.max(0,G-S);A[M]=" ".repeat(L)+N}}return A.join(`
|
|
55
|
-
`)}function lt(){if(l>=a||i.charCodeAt(l)!==he)return"";let m=l;Oe(he,ne);let h=i.slice(m,l);if(h.includes(`
|
|
56
|
-
`)){let d="",y=!1;for(let C=0;C<h.length;C++){let E=h.charCodeAt(C);if(E===32||E===9||E===10||E===13){if(!y&&d.length>0)d+=" ",y=!0}else d+=h[C],y=!1}if(d.charCodeAt(1)===32)d=`<${d.slice(2)}`;if(d.charCodeAt(d.length-2)===32)d=`${d.slice(0,-2)}>`;return d}return h}function bt(){if(l>=a||i.charCodeAt(l)!==Q)return"()";let m=l;return Oe(Q,we),i.slice(m,l)}function Mr(m){if(m.indexOf("/")===-1)return m;let h="",d=!1,y=0;for(let C=0;C<m.length;C++){let E=m.charCodeAt(C);if(d){if(h+=m[C],E===Ue&&C+1<m.length){h+=m[++C];continue}if(E===y)d=!1;continue}if(E===te||E===se||E===Ae){d=!0,y=E,h+=m[C];continue}if(E===H&&C+1<m.length){let x=m.charCodeAt(C+1);if(x===ge){let O=m.indexOf("*/",C+2);C=O===-1?m.length:O+1,h+=" ";continue}if(x===H){let O=m.indexOf(`
|
|
57
|
-
`,C+2);C=O===-1?m.length:O-1;continue}}h+=m[C]}return h.trim()}function Nt(m){let h=m.slice(1,-1).trim();if(!h)return"()";if(m.indexOf(`
|
|
58
|
-
`)===-1&&h.indexOf(":")!==-1&&h.indexOf("{")===-1&&h.indexOf("[")===-1&&h.indexOf("=")===-1&&h.indexOf("@")===-1&&h.indexOf("...")===-1){let S=0,A=0,M=0;for(let N=0;N<h.length;N++){let G=h.charCodeAt(N);if(G===Q||G===he||G===V)M++;else if(G===we||G===ne||G===J)M--;else if(M===0){if(G===et)S++;else if(G===tt)A++}}if(S>=A+1){let N=!1;for(let G=0;G<gn.length;G++){let L=gn[G],D=h.indexOf(L);if(D!==-1){let B=D+L.length;if((D===0||!Ke(h.charCodeAt(D-1)))&&(B>=h.length||!Ke(h.charCodeAt(B)))){N=!0;break}}}if(!N)return m}}let d=[],y=0,C=0,E=!1,x=0;for(let S=0;S<=h.length;S++){if(S===h.length){d.push(Mr(h.slice(y).trim()));break}let A=h.charCodeAt(S);if(E){if(A===Ue){S++;continue}if(A===x)E=!1;continue}if(A===H&&S+1<h.length){let M=h.charCodeAt(S+1);if(M===ge){S+=2;while(S+1<h.length&&!(h.charCodeAt(S)===ge&&h.charCodeAt(S+1)===H))S++;S++;continue}if(M===H){while(S<h.length&&h.charCodeAt(S)!==10)S++;continue}}if(A===te||A===se||A===Ae){E=!0,x=A;continue}if(A===Q||A===V||A===ue||A===he)C++;else if(A===we||A===J||A===be||A===ne&&!(S>0&&h.charCodeAt(S-1)===Ce))C--;else if(A===tt&&C===0)d.push(Mr(h.slice(y,S).trim())),y=S+1}let O=[];for(let S of d){if(!S)continue;let A=S.trim();if(A.startsWith("//")||A.startsWith("/*"))continue;let M=S;{let N=!1,G=0,L=0,D=0;for(let B=0;B<M.length-1;B++){let j=M.charCodeAt(B);if(j===oe){D=B+1;continue}if(N){if(j===Ue){B++;continue}if(j===G)N=!1;continue}if(j===te||j===se||j===Ae){N=!0,G=j;continue}if(j===V||j===ue||j===Q||j===he){L++;continue}if(j===J||j===be||j===we||j===ne){if(L>0)L--;continue}if(j===H&&M.charCodeAt(B+1)===H){if(L===0){M=M.slice(0,B).trimEnd();break}let je=M.indexOf(`
|
|
59
|
-
`,B);if(je===-1){M=M.slice(0,D).trimEnd();break}let _e=M.slice(0,D),Gt=M.slice(je+1);M=`${_e}${Gt}`,B=D-1}}}if(!M.trim())continue;O.push(Ss(M))}return`(${O.join(", ")})`}function ac(m){if(!m.startsWith("{")&&!m.startsWith("["))return m;let h="",d=0,y=0,C=!1,E=0;while(d<m.length){let x=m.charCodeAt(d);if(C){if(x===Ue&&d+1<m.length){h+=m[d]+m[d+1],d+=2;continue}if(x===E)C=!1;h+=m[d],d++;continue}if(x===H&&d+1<m.length){let O=m.charCodeAt(d+1);if(O===ge){let S=d;d+=2;while(d+1<m.length&&!(m.charCodeAt(d)===ge&&m.charCodeAt(d+1)===H))d++;d=Math.min(d+2,m.length),h+=m.slice(S,d);continue}if(O===H){let S=d;while(d<m.length&&m.charCodeAt(d)!==10)d++;h+=m.slice(S,d);continue}}if(x===te||x===se||x===Ae){C=!0,E=x,h+=m[d],d++;continue}if(x===V||x===ue||x===Q)y++;else if(x===J||x===be||x===we)y--;if(y>=1&&x===Ce&&(d+1>=m.length||m.charCodeAt(d+1)!==Ce&&m.charCodeAt(d+1)!==ne)){while(h.length>0&&(h[h.length-1]===" "||h[h.length-1]==="\t"||h[h.length-1]===`
|
|
60
|
-
`))h=h.slice(0,-1);d++;let O=0;while(d<m.length){let S=m.charCodeAt(d);if(S===te||S===se||S===Ae){let A=S;d++;while(d<m.length){if(m.charCodeAt(d)===Ue){d+=2;continue}if(m.charCodeAt(d)===A){d++;break}d++}continue}if(S===V||S===ue||S===Q)O++;else if(S===J||S===be||S===we){if(O===0)break;O--}else if(S===tt&&O===0)break;d++}continue}if(y===1&&x===ft&&d+2<m.length&&m.charCodeAt(d+1)===ft&&m.charCodeAt(d+2)===ft){d+=3;continue}h+=m[d],d++}return h}function Ss(m){let h=m.trim(),d=h.startsWith("...");if(d)h=h.slice(3).trim();while(h.startsWith("@")){let D=1;while(D<h.length&&Ke(h.charCodeAt(D)))D++;if(D<h.length&&h.charCodeAt(D)===Q){let B=1;D++;while(D<h.length&&B>0){if(h.charCodeAt(D)===Q)B++;else if(h.charCodeAt(D)===we)B--;D++}}h=h.slice(D).trim()}let y=!0;while(y){y=!1;for(let D of gn)if(h.startsWith(D)&&h.length>D.length&&!Ke(h.charCodeAt(D.length))){let B=h.slice(D.length).trim();if(B.charCodeAt(0)===et||B.charCodeAt(0)===Vr&&B.length>1&&B.charCodeAt(1)===et)break;h=B,y=!0;break}}let C=-1,E=-1,x=0,O=!1,S=0;for(let D=0;D<h.length;D++){let B=h.charCodeAt(D);if(O){if(B===Ue){D++;continue}if(B===S)O=!1;continue}if(B===H&&D+1<h.length){let j=h.charCodeAt(D+1);if(j===ge){D+=2;while(D+1<h.length&&!(h.charCodeAt(D)===ge&&h.charCodeAt(D+1)===H))D++;D++;continue}if(j===H){while(D<h.length&&h.charCodeAt(D)!==10)D++;continue}}if(B===te||B===se||B===Ae){O=!0,S=B;continue}if(B===Q||B===V||B===ue||B===he)x++;else if(B===we||B===J||B===be||B===ne&&!(D>0&&h.charCodeAt(D-1)===Ce))x--;else if(x===0){if(B===et&&C===-1)C=D;else if(B===Ce&&E===-1&&(D===0||h.charCodeAt(D-1)!==Ce)&&(D+1>=h.length||h.charCodeAt(D+1)!==Ce&&h.charCodeAt(D+1)!==ne))E=D}}let A,M,N=E!==-1;if(C!==-1&&(E===-1||C<E))if(A=h.slice(0,C).trim(),E!==-1)M=h.slice(C+1,E).trim();else M=h.slice(C+1).trim();else if(E!==-1)A=h.slice(0,E).trim(),M=_i(h.slice(E+1).trim());else A=h,M="unknown";if(A=ac(A),(A.startsWith("{")||A.startsWith("["))&&A.includes(`
|
|
61
|
-
`)){let D=A.replace(/\s*\n\s*/g," ").replace(/\s+/g," ");if(D.length<=40)A=D;else A=A.split(`
|
|
62
|
-
`).map((B)=>{let j=B.trim();if(!j)return"";if(j==="{"||j==="}"||j==="["||j==="]"||j.startsWith("}")||j.startsWith("]"))return j;return` ${j}`}).join(`
|
|
63
|
-
`)}let G=A.endsWith("?")||N;if(A.endsWith("?"))A=A.slice(0,-1).trim();let L=G&&!d?"?":"";if(d)return`...${A}: ${M}`;return`${A}${L}: ${M}`}function $s(m){let h=0;if(h<m.length&&m.charCodeAt(h)===45)h++;if(h>=m.length)return!1;let d=m.charCodeAt(h);if(d<48||d>57)return!1;while(h<m.length&&m.charCodeAt(h)>=48&&m.charCodeAt(h)<=57)h++;if(h<m.length&&m.charCodeAt(h)===46){if(h++,h>=m.length||m.charCodeAt(h)<48||m.charCodeAt(h)>57)return!1;while(h<m.length&&m.charCodeAt(h)>=48&&m.charCodeAt(h)<=57)h++}return h===m.length}function _i(m){let h=m.trim();if(h==="true"||h==="false")return"boolean";if($s(h))return"number";if(h.startsWith("'")&&h.endsWith("'")||h.startsWith('"')&&h.endsWith('"'))return"string";if(h.startsWith("["))return"unknown[]";if(h.startsWith("{"))return"Record<string, unknown>";return"unknown"}function Vi(m){let h=m.trim();if(h.endsWith("as const"))h=h.slice(0,-8).trim();if(h==="true"||h==="false")return h;if($s(h))return h;let d=lc(h);if(d!==null)return d;return"unknown"}function lc(m){if(m==="")return null;if(m.charCodeAt(0)===te||m.charCodeAt(0)===se){if(Kr(m,0,m.charCodeAt(0))===m.length)return m}let h=cc(m,"+");if(h.length>1){let d=!1,y=!0,C=[];for(let E of h){let x=E.trim(),O=x.charCodeAt(0);if((O===te||O===se)&&Kr(x,0,O)===x.length)d=!0,C.push(fc(x));else y=!1}if(y)return uc(C.join(""));if(d)return"string";return null}if(/^[\d\s()+*/%.\-]+$/.test(m)&&/\d/.test(m)&&/[+*/%\-\s]/.test(m))return"number";return null}function cc(m,h){let d=[],y=0,C="",E=0;while(E<m.length){let x=m.charCodeAt(E);if(x===te||x===se||x===Ae){let O=Kr(m,E,x);C+=m.slice(E,O),E=O;continue}if(x===H&&(m.charCodeAt(E+1)===H||m.charCodeAt(E+1)===42)){if(m.charCodeAt(E+1)===H){let A=m.indexOf(`
|
|
64
|
-
`,E+2),M=A===-1?m.length:A;C+=m.slice(E,M),E=M;continue}let O=m.indexOf("*/",E+2),S=O===-1?m.length:O+2;C+=m.slice(E,S),E=S;continue}if(x===Q||x===ue||x===V)y++;else if(x===we||x===be||x===J)y--;if(m[E]===h&&y===0){d.push(C),C="",E++;continue}C+=m[E],E++}return d.push(C),d}function fc(m){return m.slice(1,-1).replace(/\\(.)/g,(h,d)=>{if(d==="n")return`
|
|
65
|
-
`;if(d==="t")return"\t";if(d==="r")return"\r";if(d==="0")return"\x00";return d})}function uc(m){return`'${m.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function Dr(m){if(m.endsWith("as const"))return null;let h=0,d=-1;for(let y=0;y<m.length;y++){let C=m.charCodeAt(y);if(C===te||C===se||C===Ae)y=Kr(m,y,C)-1;else if(C===123||C===91||C===40)h++;else if(C===125||C===93||C===41)h--;else if(h===0&&C===32&&y+4<=m.length&&m.substring(y,y+4)===" as ")d=y}if(d===-1)return null;return m.slice(d+4).trim()||null}function or(){if(p(),l<a&&i.charCodeAt(l)===et){l++,p();let m=l,h=0;while(l<a){if(T())continue;let d=i.charCodeAt(l);if(d===Q||d===ue||d===he)h++;else if(d===we||d===be||d===ne&&!ke())h--;else if(d===V)if(h>0)h++;else{let y=g(m,l),C=(E)=>{let x=y.length-E.length;return x>=0&&y.endsWith(E)&&(x===0||!Ke(y.charCodeAt(x-1)))};if(y.length===0||y.endsWith("|")||y.endsWith("&")||C("is")||C("extends"))h++;else break}else if(d===J){if(h===0)break;h--}else if(h===0&&d===Y)break;if(h===0&&ie())break;l++}return g(m,l)}return""}function St(m,h,d,y){l+=8,p();let C=l<a&&i.charCodeAt(l)===ge;if(C)l++,p();let E=W();if(!E&&!y)return null;p();let x=lt();p();let O=bt();p();let S=or(),A=S.length>0;if(!S)if(d&&C)S="AsyncGenerator<unknown, void, unknown>";else if(C)S="Generator<unknown, void, unknown>";else if(d)S="Promise<void>";else S="void";p();let M=!1;if(l<a&&i.charCodeAt(l)===V){M=!0;let D=l+1;if(Oe(V,J),!o&&!A&&!C)S=dr(i.slice(D,l-1),d,O)}else if(l<a&&i.charCodeAt(l)===Y)l++;let N=Nt(O),G=`${h?y?"export default function ":"export declare function ":"declare function "}${E||(y?"":"default")}${x}${N}: ${S};`,L=qe(m);if(M)u.add(c.length);return{kind:"function",name:E||"default",text:G,isExported:h,isDefault:y,isAsync:d,isGenerator:C,returnType:S,generics:x||void 0,leadingComments:L,start:m,end:l}}function Lt(m,h,d){l+=h.length,p();let y=[];do{if(p(),l>=a)break;let C=i.charCodeAt(l);if(C===V||C===ue)return ee(),y;let E=W();if(!E)return ee(),y;p();let x,O,S=!1;if(l<a&&i.charCodeAt(l)===et){l++,p();let N=l,G=0;while(l<a){if(T())continue;let L=i.charCodeAt(l);if(L===Q||L===V||L===ue||L===he)G++;else if(L===we||L===J||L===be||L===ne&&!ke())G--;else if(G===0&&(L===Y||L===tt))break;else if(G===0&&L===Ce&&!ut())break;if(G===0&&(q()||Z()))break;l++}x=g(N,l)}if(l<a&&i.charCodeAt(l)===Ce)if(o&&x&&(!s||!Cf(x)))Ft();else{l++,p();let N=l,G=0,L=0,D=0,B=!0;for(;;){l=N,G=0,L=0,D=0;while(l<a){if(T())continue;let j=i.charCodeAt(l);if(j===Q||j===V||j===ue)G++;else if(j===we||j===J||j===be)G--;else if(j===he&&G===0){let je=As(l);if(je!==null)D=Math.max(0,D+je);else if(B&&(l+1>=a||i.charCodeAt(l+1)!==Ce))L++}else if(j===ne&&G===0&&D===0&&!ke()){if(L>0&&(l+1>=a||i.charCodeAt(l+1)!==Ce))L--}else if(G===0&&L===0&&D===0&&(j===Y||j===tt))break;if(G===0&&L===0&&D===0&&(q()||z()))break;l++}if(L>0&&B){B=!1;continue}break}if(O=g(N,l),O.endsWith(" as const")||O==="const"){if(S=!0,!x){let j=O.endsWith(" as const")?O.slice(0,-9).trim():O,je=Vi(j);x=je!=="unknown"?je:void 0}}else if(!x){let j=Dr(O);if(j)x=j}}if(l<a){let N=i.charCodeAt(l);if(N===tt){l++;continue}if(N===Y)l++}let A=qe(m),M=`${d?"export ":""}declare ${h} ${E}: ${x||"unknown"};`;y.push({kind:"variable",name:E,text:M,isExported:d,typeAnnotation:x,value:O,modifiers:S?[h,"const assertion"]:[h],leadingComments:A,start:m,end:l});break}while(l<a);return y}function As(m){if(i.charCodeAt(m)!==he||m+1>=a)return null;let h=i.charCodeAt(m+1);if(h===ne)return 1;if(h===H)return-1;if(!kt(h))return null;let d=m+2;while(d<a){let A=i.charCodeAt(d);if(!Ke(A)&&A!==ft&&A!==58&&A!==45)break;d++}let y=i.slice(m+1,d),C=i.charCodeAt(d);if(C>32&&C!==ne&&C!==H)return null;let E=0,x=0,O=d;for(;O<a;O++){let A=i.charCodeAt(O);if(x!==0){if(A===Ue)O++;else if(A===x)x=0;continue}if(A===te||A===se||A===Ae)x=A;else if(A===V)E++;else if(A===J&&E>0)E--;else if(A===ne&&E===0)break}if(O>=a)return null;let S=O-1;while(S>m&&i.charCodeAt(S)<=32)S--;if(i.charCodeAt(S)===H)return 0;return i.indexOf(`</${y}`,O+1)===-1?null:1}function Ui(m,h){l+=9,p();let d=W();p();let y=lt();p();let C="";if(P("extends")){l+=7,p();let A=l,M=0;while(l<a){if(T())continue;let N=i.charCodeAt(l);if(N===he)M++;else if(N===ne&&!ke())M--;else if(N===V&&M===0)break;l++}C=g(A,l)}p();let E=l<a&&i.charCodeAt(l)===V?ji():"{}",x=bs(E),O=`${h?"export ":""}declare interface ${d}${y}${C?` extends ${C}`:""} ${x}`,S=qe(m);return{kind:"interface",name:d,text:O,isExported:h,extends:C||void 0,generics:y||void 0,leadingComments:S,start:m,end:l}}function Ki(m,h){l+=4,p();let d=W();p();let y=lt();if(p(),l<a&&i.charCodeAt(l)===Ce)l++;p();let C=l,E=0;while(l<a){if(T())continue;let A=i.charCodeAt(l);if(A===Q||A===V||A===ue||A===he)E++;else if(A===we||A===J||A===be||A===ne&&!ke())E--;else if(E===0&&A===Y)break;if(E===0&&(q()||Z()))break;l++}let x=g(C,l);if(l<a&&i.charCodeAt(l)===Y)l++;let O=`${h?"export ":""}type ${d}${y} = ${x}`,S=qe(m);return{kind:"type",name:d,text:O,isExported:h,generics:y||void 0,leadingComments:S,start:m,end:l}}function Wt(m,h,d){l+=4,p();let y=W();p();let C=l;if(l<a&&i.charCodeAt(l)===V)Oe(V,J);let E=g(m,l),x=qe(m);return{kind:"enum",name:y,text:E,isExported:h,modifiers:d?["const"]:void 0,leadingComments:x,start:m,end:l}}function $t(m,h,d,y=!1){l+=5,p();let C=W()||"AnonymousClass";p();let E=lt();p();let x="";if(P("extends")){l+=7,p();let N=l,G=0;while(l<a){if(T())continue;let L=i.charCodeAt(l);if(L===he)G++;else if(L===ne&&!ke())G--;else if(G===0&&(L===V||P("implements")))break;l++}x=g(N,l)}let O;if(P("implements")){l+=10,p();let N=l,G=0;while(l<a){if(T())continue;let D=i.charCodeAt(l);if(D===he)G++;else if(D===ne&&!ke())G--;else if(G===0&&D===V)break;l++}let L=g(N,l);if(L)O=L.split(",").map((D)=>D.trim())}p();let S=zi(),A=`${h?y?"export default ":"export declare ":"declare "}${d?"abstract ":""}class ${C}${E}${x?` extends ${x}`:""}${O&&O.length>0?` implements ${O.join(", ")}`:""} ${S}`,M=qe(m);return{kind:"class",name:C,text:A,isExported:h,isDefault:y,extends:x||void 0,implements:O,generics:E||void 0,modifiers:d?["abstract"]:void 0,leadingComments:M,start:m,end:l}}function zi(){if(l>=a||i.charCodeAt(l)!==V)return"{}";l++;let m=[];while(l<a){if(p(),l>=a)break;if(i.charCodeAt(l)===J){l++;break}if(i.charCodeAt(l)===Y){l++;continue}if(P("static")&&xs("static")===V){l+=6,p(),Oe(V,J);continue}let h=!1,d=!1,y=!1,C=!1,E=!1,x=!1,O=!1,S=!1,A=!0;while(A){if(p(),P("private")){h=!0,l+=7;continue}if(P("protected")){d=!0,l+=9;continue}if(P("public")){l+=6;continue}if(P("static")){y=!0,l+=6;continue}if(P("abstract")){C=!0,l+=8;continue}if(P("readonly")){E=!0,l+=8;continue}if(P("override")){x=!0,l+=8;continue}if(P("accessor")){O=!0,l+=8;continue}if(P("async")){S=!0,l+=5;continue}if(P("declare")){l+=7;continue}break}if(p(),l>=a||i.charCodeAt(l)===J)break;if(i.charCodeAt(l)===Ur)h=!0;if(h){Ji();continue}let M=" ";if(d)M+="protected ";if(y)M+="static ";if(C)M+="abstract ";if(E)M+="readonly ";if(P("constructor")){l+=11,p();let N=bt();if(p(),dc(N,m),l<a&&i.charCodeAt(l)===V)Oe(V,J);else if(l<a&&i.charCodeAt(l)===Y)l++;let G=Nt(N);m.push(` constructor${G};`)}else if(P("get"))if(l+=3,p(),l<a&&(kt(i.charCodeAt(l))||i.charCodeAt(l)===ue||i.charCodeAt(l)===Ur)){let N=Hi();if(N.startsWith("#")){if(p(),l<a&&i.charCodeAt(l)===Q)bt();if(p(),or(),p(),l<a&&i.charCodeAt(l)===V)Oe(V,J);else if(l<a&&i.charCodeAt(l)===Y)l++;continue}p(),bt(),p();let G=or()||"unknown";if(p(),l<a&&i.charCodeAt(l)===V)Oe(V,J);else if(l<a&&i.charCodeAt(l)===Y)l++;m.push(`${M}get ${N}(): ${G};`)}else Ts("get",M,y,E,S,m);else if(P("set"))if(l+=3,p(),l<a&&(kt(i.charCodeAt(l))||i.charCodeAt(l)===ue||i.charCodeAt(l)===Ur)){let N=Hi();if(N.startsWith("#")){if(p(),l<a&&i.charCodeAt(l)===Q)bt();if(p(),l<a&&i.charCodeAt(l)===V)Oe(V,J);else if(l<a&&i.charCodeAt(l)===Y)l++;continue}p();let G=bt();if(p(),l<a&&i.charCodeAt(l)===V)Oe(V,J);else if(l<a&&i.charCodeAt(l)===Y)l++;let L=Nt(G);m.push(`${M}set ${N}${L};`)}else Ts("set",M,y,E,S,m);else{let N=i.charCodeAt(l)===ge;if(N)l++,p();let G=Hi();if(!G){Ji();continue}Ps(G,M,y,E,N,C,S,m)}}return`{
|
|
66
|
-
${m.join(`
|
|
67
|
-
`)}
|
|
68
|
-
}`}function Hi(){if(l>=a)return"";let m=i.charCodeAt(l);if(m===ue){let h=l;return Oe(ue,be),i.slice(h,l)}if(m===Ur)return l++,`#${W()}`;return W()}function xs(m){let h=l+m.length;while(h<a&&Me(i.charCodeAt(h)))h++;return h<a?i.charCodeAt(h):0}function Ji(){let m=0;while(l<a){if(T())continue;let h=i.charCodeAt(l);if(h===V||h===Q)m++;else if(h===J||h===we){if(m===0)return;m--}else if(h===Y&&m===0){l++;return}if(m===0&&ie())return;l++}}function Ts(m,h,d,y,C,E){Ps(m,h,d,y,!1,!1,C,E)}function Ps(m,h,d,y,C,E,x,O){if(p(),l>=a)return;let S=i.charCodeAt(l),A=!1;if(S===Vr)A=!0,l++,p();if(l<a&&i.charCodeAt(l)===33)l++,p();let M=l<a?i.charCodeAt(l):0;if(M===Q||M===he){let N=M===he?lt():"";p();let G=bt();p();let L=or(),D=L.length>0;if(!L)if(x&&C)L="AsyncGenerator<unknown, void, unknown>";else if(C)L="Generator<unknown, void, unknown>";else if(x)L="Promise<void>";else L="void";if(p(),l<a&&i.charCodeAt(l)===V){let je=l+1;if(Oe(V,J),!o&&!D&&!C)L=dr(i.slice(je,l-1),x,G)}else if(l<a&&i.charCodeAt(l)===Y)l++;let B=Nt(G),j=A?"?":"";O.push(`${h}${m}${j}${N}${B}: ${L};`)}else if(M===et||M===Ce||M===Y||M===J||M===oe||M===ye){let N="";if(M===et){l++,p();let D=l,B=0;while(l<a){if(T())continue;let j=i.charCodeAt(l);if(j===Q||j===V||j===ue||j===he)B++;else if(j===we||j===J||j===be||j===ne&&!ke()){if(B===0)break;B--}else if(B===0&&(j===Y||j===tt))break;else if(B===0&&j===Ce&&!ut())break;if(B===0&&ie())break;l++}N=g(D,l)}let G="";if(l<a&&i.charCodeAt(l)===Ce)if(o&&N){l++;let D=0;while(l<a){if(T())continue;let B=i.charCodeAt(l);if(B===Q||B===V||B===ue)D++;else if(B===we||B===J||B===be){if(D===0&&B===J)break;D--}else if(D===0&&B===Y)break;if(D===0&&ie())break;l++}}else{l++,p();let D=l,B=0;while(l<a){if(T())continue;let j=i.charCodeAt(l);if(j===Q||j===V||j===ue)B++;else if(j===we||j===J||j===be){if(B===0&&j===J)break;B--}else if(B===0&&j===Y)break;if(B===0&&ie())break;l++}G=g(D,l)}if(l<a&&i.charCodeAt(l)===Y)l++;if(!N)if(G){let D=Dr(G);if(D)N=D;else N=G.endsWith("as const")||d&&y?Vi(G):_i(G)}else N="unknown";let L=A?"?":"";O.push(`${h}${m}${L}: ${N};`)}else Ji()}function hc(m){let h=0;for(let d=0;d<m.length;d++){let y=m.charCodeAt(d);if(y===Q||y===V||y===ue||y===he)h++;else if(y===we||y===J||y===be||y===ne&&m.charCodeAt(d-1)!==Ce)h--;else if(y===Ce&&h===0&&m.charCodeAt(d+1)!==ne&&m.charCodeAt(d+1)!==Ce)return!0}return!1}function dc(m,h){let d=m.slice(1,-1).trim();if(!d)return;let y=[],C=0,E=0,x=!1,O=0;for(let S=0;S<=d.length;S++){if(S===d.length){y.push(Mr(d.slice(C).trim()));break}let A=d.charCodeAt(S);if(x){if(A===Ue){S++;continue}if(A===O)x=!1;continue}if(A===H&&S+1<d.length){let M=d.charCodeAt(S+1);if(M===ge){S+=2;while(S+1<d.length&&!(d.charCodeAt(S)===ge&&d.charCodeAt(S+1)===H))S++;S++;continue}if(M===H){while(S<d.length&&d.charCodeAt(S)!==10)S++;continue}}if(A===te||A===se||A===Ae){x=!0,O=A;continue}if(A===Q||A===V||A===ue||A===he)E++;else if(A===we||A===J||A===be||A===ne&&!(S>0&&d.charCodeAt(S-1)===Ce))E--;else if(A===tt&&E===0)y.push(Mr(d.slice(C,S).trim())),C=S+1}for(let S of y){let A=S.startsWith("public ")||S.startsWith("public\t"),M=S.startsWith("protected ")||S.startsWith("protected\t"),N=S.startsWith("private ")||S.startsWith("private\t"),G=S.includes("readonly ");if(!A&&!M&&!N&&!G)continue;if(N)continue;let L=S,D=[];if(A){let _e=6;while(_e<L.length&&Me(L.charCodeAt(_e)))_e++;L=L.slice(_e),D.push("public")}if(M){let _e=9;while(_e<L.length&&Me(L.charCodeAt(_e)))_e++;L=L.slice(_e),D.push("protected")}if(G){let _e=L.indexOf("readonly ");if(_e!==-1){let Gt=_e+8;while(Gt<L.length&&Me(L.charCodeAt(Gt)))Gt++;L=L.slice(0,_e)+L.slice(Gt)}D.push("readonly")}let B=D.length>0?`${D.join(" ")} `:"",j=Ss(L),je=L.search(/[?:=]/);if(je!==-1&&L.charCodeAt(je)!==63&&hc(L))j=j.replace(/^([\w$]+)\?:/,"$1:");h.push(` ${B}${j};`)}}function qi(m=" "){if(l>=a||i.charCodeAt(l)!==V)return"{}";l++;let h=[];while(l<a){if(p(),l>=a)break;if(i.charCodeAt(l)===J){l++;break}if(i.charCodeAt(l)===Y){l++;continue}let d=!1;if(P("export"))d=!0,l+=6,p();if(P("declare"))l+=7,p();let y=d?"export ":"";if(P("function")||P("async")&&mc("async","function")){let C=!1;if(P("async"))C=!0,l+=5,p();if(l+=8,p(),l<a&&i.charCodeAt(l)===ge)l++,p();let E=W();p();let x=lt();p();let O=bt();p();let S=or();if(!S)S=C?"Promise<void>":"void";if(p(),l<a&&i.charCodeAt(l)===V)Oe(V,J);else if(l<a&&i.charCodeAt(l)===Y)l++;let A=Nt(O);h.push(`${m}${y}function ${E}${x}${A}: ${S};`)}else if(P("const")||P("let")||P("var")){let C=P("const")?"const":P("let")?"let":"var";l+=C.length,p();let E=W();if(!E){ee();continue}p();let x="";if(l<a&&i.charCodeAt(l)===et){l++,p();let S=l,A=0;while(l<a){if(T())continue;let M=i.charCodeAt(l);if(M===Q||M===V||M===ue||M===he)A++;else if(M===we||M===J||M===be||M===ne&&!ke())A--;else if(A===0&&(M===Y||M===tt))break;else if(A===0&&M===Ce&&!ut())break;if(A===0&&q())break;l++}x=g(S,l)}let O="";if(l<a&&i.charCodeAt(l)===Ce){l++,p();let S=l,A=0;while(l<a){if(T())continue;let M=i.charCodeAt(l);if(M===Q||M===V||M===ue||M===he)A++;else if(M===we||M===J||M===be||M===ne&&!ke())A--;else if(A===0&&(M===Y||M===tt))break;if(A===0&&q())break;l++}O=g(S,l)}if(l<a&&i.charCodeAt(l)===Y)l++;if(!x&&O){let S=Dr(O);if(S)x=S;else if(C==="const")x=Vi(O);else x=_i(O)}if(!x)x="unknown";h.push(`${m}${y}${C} ${E}: ${x};`)}else if(P("interface")){l+=9,p();let C=W();p();let E=lt();p();let x="";if(P("extends")){l+=7,p();let S=l,A=0;while(l<a){if(T())continue;let M=i.charCodeAt(l);if(M===he)A++;else if(M===ne&&!ke())A--;else if(M===V&&A===0)break;l++}x=g(S,l)}let O=bs(ji());h.push(`${m}${y}interface ${C}${E}${x?` extends ${x}`:""} ${O}`)}else if(P("type")){l+=4,p();let C=W();p();let E=lt();if(p(),l<a&&i.charCodeAt(l)===Ce){l++,p();let x=l,O=0;while(l<a){if(T())continue;let A=i.charCodeAt(l);if(A===Q||A===V||A===ue||A===he)O++;else if(A===we||A===J||A===be||A===ne&&!ke())O--;else if(O===0&&A===Y)break;if(O===0&&q())break;l++}let S=g(x,l);if(l<a&&i.charCodeAt(l)===Y)l++;h.push(`${m}${y}type ${C}${E} = ${S}`)}}else if(P("class")){l+=5,p();let C=W();p();let E=lt();p();let x=l,O=0;while(l<a){if(T())continue;let N=i.charCodeAt(l);if(N===he)O++;else if(N===ne&&!ke())O--;else if(N===V&&O===0)break;l++}let S=g(x,l),A=S?` ${S}`:"",M=zi();h.push(`${m}${y}class ${C}${E}${A} ${M}`)}else if(P("enum")){l+=4,p();let C=W();p();let E=ji();h.push(`${m}${y}enum ${C} ${E}`)}else if(P("namespace")||P("module")){let C=P("namespace")?"namespace":"module";l+=C.length,p();let E=W();p();let x=qi(m);h.push(`${m}${y}${C} ${E} ${x}`)}else if(P("abstract"))if(l+=8,p(),P("class")){l+=5,p();let C=W();p();let E=lt();p();let x=l,O=0;while(l<a){if(T())continue;let N=i.charCodeAt(l);if(N===he)O++;else if(N===ne&&!ke())O--;else if(N===V&&O===0)break;l++}let S=g(x,l),A=S?` ${S}`:"",M=zi();h.push(`${m}${y}abstract class ${C}${E}${A} ${M}`)}else ee();else if(d&&P("default")){l+=7,p();let C=l;ee();let E=g(C,l);if(E.charCodeAt(E.length-1)===Y)E=E.slice(0,-1);if(E)h.push(`${m}export default ${E};`)}else if(!d&&(i.charCodeAt(l)===te||i.charCodeAt(l)===se||i.charCodeAt(l)===Ae))ee();else ee()}if(h.length===0)return"{}";return`{
|
|
69
|
-
${h.join(`
|
|
2
|
+
var pe=(e,t,i)=>()=>{if(e)try{t=e(e=0)}catch(n){i=[n]}if(i)throw i[0];return t};var wc=import.meta.require;import{readFile as vc,stat as zm,writeFile as Ec}from"fs/promises";async function Io(e,t){if(Ni)return globalThis.Bun.write(e,t);let i=typeof t==="string"?t:t instanceof ArrayBuffer?Buffer.from(t):t;return await Ec(e,i),typeof t==="string"?Buffer.byteLength(t):t.byteLength}async function Tt(e){if(Ni)return globalThis.Bun.file(e).text();return vc(e,"utf-8")}var Ni,Jm;var Li=pe(()=>{Ni=typeof globalThis.Bun<"u",Jm=!Ni&&typeof process<"u"&&!!process.versions?.node});import{existsSync as bc,statSync as Sc}from"fs";import{dirname as $c,extname as Ac,isAbsolute as Zr,resolve as xc}from"path";function Wi(e){try{return Sc(e).isFile()}catch{return!1}}function Ut(e,t){let i=e.replace(/[?#].*$/,"");if(!(i.startsWith("./")||i.startsWith("../")||i==="."||i==="..")&&!Zr(i))return{resolved:null,isRelative:!1};let n=$c(t),r=Zr(i)?i:xc(n,i);if(Wi(r))return{resolved:r,isRelative:!0};let o=Ac(r),s=Tc[o];if(s){let a=r.slice(0,-o.length);for(let c of s){let f=a+c;if(Wi(f))return{resolved:f,isRelative:!0}}}for(let a of Fo){let c=r+a;if(Wi(c))return{resolved:c,isRelative:!0}}if(bc(r))for(let a of Fo){let c=`${r}/index${a}`;if(Wi(c))return{resolved:c,isRelative:!0}}return{resolved:null,isRelative:!0}}function Rc(e){let t=e.length,i="",n=0;while(n<t){let r=e.charCodeAt(n);if(r===34||r===39||r===96){let o=r;i+=e[n++];while(n<t){let s=e.charCodeAt(n),a=e[n++];if(i+=o===96&&s!==o?s===10||s===13?a:" ":a,s===92&&n<t){let c=e[n++];i+=o===96?c===`
|
|
3
|
+
`||c==="\r"?c:" ":c;continue}if(s===o)break}continue}if(r===47&&n+1<t){let o=e.charCodeAt(n+1);if(o===47){n+=2;while(n<t&&e.charCodeAt(n)!==10)n++;continue}if(o===42){n+=2;while(n+1<t&&!(e.charCodeAt(n)===42&&e.charCodeAt(n+1)===47))n++;n+=2;continue}}i+=e[n++]}return i}function Xr(e,t={}){let i=[],n=Rc(e);No.lastIndex=0;let r;while((r=No.exec(n))!==null){let o=!!r[1],s=r[3],a=r[0],c;if(a.includes("* as "))c="export-star-as";else if(a.includes("*"))c="export-star";else c="export-named";i.push({specifier:s,kind:c,isTypeOnly:o})}if(t.includeImports){Lo.lastIndex=0;while((r=Lo.exec(n))!==null)i.push({specifier:r[3],kind:"import",isTypeOnly:!!r[1]})}return i}async function Qr(e,t={}){let i=new Set,n=new Map,r=[],o=[];for(let s of e)if(!i.has(s))i.add(s),o.push(s);while(o.length>0){let s=o.shift(),a;try{a=await Tt(s)}catch{continue}let c=Xr(a,t);n.set(s,c);for(let f of c){if(!(f.specifier.startsWith(".")||Zr(f.specifier)))continue;let u=Ut(f.specifier,s);if(u.resolved){if(!i.has(u.resolved))i.add(u.resolved),o.push(u.resolved)}else r.push({from:s,specifier:f.specifier,isTypeOnly:f.isTypeOnly})}}return{reachable:i,reExports:n,unresolved:r}}var Fo,Tc,No,Lo;var en=pe(()=>{Li();Fo=[".ts",".tsx",".mts",".cts",".vue",".stx",".js",".jsx",".mjs",".cjs",".d.ts",".d.mts",".d.cts"],Tc={".js":[".ts",".tsx",".d.ts"],".jsx":[".tsx",".ts",".d.ts"],".mjs":[".mts",".d.mts"],".cjs":[".cts",".d.cts"]};No=/(?:^|[\n;{}])\s*export\s+(type\s+)?(?:\*(?:\s+as\s+\w+)?|\{[^}]*\})\s+from\s+(['"])([^'"]+)\2/g,Lo=/(?:^|[\n;{}])\s*import\s+(type\s+)?(?:[^'";\n]+\s+from\s+)?(['"])([^'"]+)\2/g});import{relative as Mt}from"path";function Pc(e){let t=[],i=[],n=0,r=0,o=[],s=!1,a=0,c=e.length,f=(u)=>{let l=e.slice(n,u).trim();if(n=u,!l)return;if(Oc(l)){i.push(l);return}t.push({text:l,comments:i}),i=[]};while(a<c){let u=e[a];if(s){if(u==="\\"){a+=2;continue}if(u==="`"){s=!1,a++;continue}if(u==="$"&&e[a+1]==="{"){o.push(r),r++,s=!1,a+=2;continue}a++;continue}if(u==="/"&&e[a+1]==="*"){let l=e.indexOf("*/",a+2);a=l===-1?c:l+2;continue}if(u==="/"&&e[a+1]==="/"){let l=e.indexOf(`
|
|
4
|
+
`,a);a=l===-1?c:l;continue}if(u==="'"||u==='"'){a++;while(a<c&&e[a]!==u&&e[a]!==`
|
|
5
|
+
`){if(e[a]==="\\")a++;a++}a++;continue}if(u==="`"){s=!0,a++;continue}if(u==="("||u==="["||u==="{"){r++,a++;continue}if(u===")"||u==="]"||u==="}"){if(r--,o.length>0&&u==="}"&&r===o[o.length-1])o.pop(),s=!0;a++;continue}if(r===0&&u===";"){f(a+1),a++;continue}if(r===0&&u===`
|
|
6
|
+
`){let l=e[a+1];if(l!==void 0&&/[\w$@/]/.test(l))f(a+1);a++;continue}a++}return f(c),t}function Oc(e){let t=0;while(t<e.length){while(t<e.length&&/\s/.test(e[t]))t++;if(t>=e.length)return!0;if(e.startsWith("//",t)){let i=e.indexOf(`
|
|
7
|
+
`,t);t=i===-1?e.length:i;continue}if(e.startsWith("/*",t)){let i=e.indexOf("*/",t+2);if(i===-1)return!0;t=i+2;continue}return!1}return!0}function tn(e){let t=[];for(let i of e.split(",")){let n=i.replace(/\/\*[\s\S]*?\*\//g,"").trim().replace(/^type\s+/,"");if(!n)continue;let r=n.match(/^([\w$]+)(?:\s+as\s+([\w$]+))?$/);if(!r)continue;t.push({local:r[1],exported:r[2]??r[1]})}return t}function kc(e){let t={named:[]},i=e.trim().replace(/^type\s+/,""),n=i.match(/\{([\s\S]*)\}/);if(n){for(let s of tn(n[1]))t.named.push({imported:s.local,local:s.exported});i=i.replace(n[0],"")}let r=i.match(/\*\s*as\s+([\w$]+)/);if(r)t.namespaceName=r[1],i=i.replace(r[0],"");let o=i.replace(/,/g,"").trim();if(o&&Bo.test(o))t.defaultName=o;return t}function Dc(e,t){let i=e.replace(/^export\s+/,""),n=/^default\s+/.test(i);if(i=i.replace(/^default\s+/,""),n)i=i.replace(/^((?:declare\s+)?(?:abstract\s+)?(?:class|function\s*\*?|async\s+function\s*\*?))\s*(?=[(<{])/,(r,o)=>`${o.trimEnd()} ${t}`);if(/^(?:interface|type)\b/.test(i)||/^declare\b/.test(i))return i;return`declare ${i}`}function Ic(e,t){let i={file:e,declarations:[],declared:new Set,imports:new Map,localExports:new Map,namedReExports:[],starReExports:[],namespaceReExports:[],verbatim:[],directives:[]},n=Pc(t);for(let r of n){r.comments=r.comments.filter((c)=>{if(/^\/\/\/\s*</.test(c))return i.directives.push(...c.split(`
|
|
8
|
+
`).map((f)=>f.trim()).filter((f)=>f.startsWith("///"))),!1;return!0});let o=r.text.replace(/;\s*$/,"").trim(),s=o.match(/^import\s+(type\s+)?([\s\S]+?)\s+from\s+(['"])([^'"]+)\3/);if(s){let c=kc(s[2]),f=s[4];if(c.defaultName)i.imports.set(c.defaultName,{specifier:f,imported:"default"});if(c.namespaceName)i.imports.set(c.namespaceName,{specifier:f,imported:"*"});for(let u of c.named)i.imports.set(u.local,{specifier:f,imported:u.imported});continue}if(/^import\s+['"]/.test(o)){i.verbatim.push(r);continue}if(s=o.match(/^export\s+(?:type\s+)?\*\s+as\s+([\w$]+)\s+from\s+(['"])([^'"]+)\2/),s){i.namespaceReExports.push({specifier:s[3],exported:s[1]});continue}if(s=o.match(/^export\s+(?:type\s+)?\*\s+from\s+(['"])([^'"]+)\1/),s){i.starReExports.push(s[2]);continue}if(s=o.match(/^export\s+(?:type\s+)?\{([\s\S]*)\}\s+from\s+(['"])([^'"]+)\2/),s){for(let c of tn(s[1]))i.namedReExports.push({specifier:s[3],imported:c.local,exported:c.exported});continue}if(s=o.match(/^export\s+(?:type\s+)?\{([\s\S]*)\}$/),s){for(let c of tn(s[1]))i.localExports.set(c.exported,c.local);continue}if(s=o.match(/^export\s+default\s+([\w$]+)$/),s&&Bo.test(s[1])){i.localExports.set("default",s[1]);continue}if(/^export\s+as\s+namespace\b/.test(o)||/^(?:export\s+)?declare\s+(?:global\b|module\s+['"])/.test(o)){i.verbatim.push(r);continue}let a=o.match(Mc);if(a){let c=!!a[1],f=a[4]??(c?"_default":null);if(f){if(i.declared.add(f),/^export\s/.test(o))i.localExports.set(c?"default":f,f);i.declarations.push({statement:r,name:f,emit:Dc(r.text,f)});continue}}i.declarations.push({statement:r,name:null,emit:r.text})}return i}function Wo(e,t){if(t.size===0)return e;let i="",n=0,r=e.length,o=`
|
|
9
|
+
`;while(n<r){let s=e[n];if(s==="/"&&e[n+1]==="*"){let a=e.indexOf("*/",n+2),c=a===-1?r:a+2;i+=e.slice(n,c),n=c;continue}if(s==="/"&&e[n+1]==="/"){let a=e.indexOf(`
|
|
10
|
+
`,n),c=a===-1?r:a;i+=e.slice(n,c),n=c;continue}if(s==="'"||s==='"'){let a=n+1;while(a<r&&e[a]!==s&&e[a]!==`
|
|
11
|
+
`){if(e[a]==="\\")a++;a++}i+=e.slice(n,a+1),n=a+1,o=s;continue}if(/[A-Z_$]/i.test(s)){let a=n+1;while(a<r&&/[\w$]/.test(e[a]))a++;let c=e.slice(n,a),f=t.get(c);if(f!==void 0&&o!=="."){let u=a;while(u<r&&(e[u]===" "||e[u]==="\t"))u++;let l=(e[u]===":"||e[u]==="?"&&e[u+1]===":")&&/[{;,(\n]/.test(o);i+=l?c:f}else i+=c;o="a",n=a;continue}if(i+=s,s===`
|
|
12
|
+
`||!/\s/.test(s))o=s;n++}return i}function Go(e,t,i,n){let r=[],o=new Map,s=[e,...t.filter((G)=>G!==e)];for(let G of s){let _=i.get(G);if(_===void 0){r.push(`No declarations were generated for ${Mt(n.cwd,G)}; it is left out of the bundle`);continue}o.set(G,Ic(G,_))}let a=(G,_)=>{if(!G.startsWith(".")&&!G.startsWith("/"))return null;let U=Ut(G,_).resolved;return U&&o.has(U)?U:null},c=(G)=>G.startsWith(".")||G.startsWith("/"),f=new Set,u=(G)=>{let _=G;for(let U=1;f.has(_);U++)_=`${G}_${U}`;return f.add(_),_},l=new Map;for(let[G,_]of o){let U=new Map;for(let ee of _.declared)U.set(ee,u(ee));l.set(G,U)}let y=new Map,p=(G,_,U)=>{let ee=`${G}\x00${_}`,z=y.get(ee);if(!z)z=u(U),y.set(ee,z);return z},w=new Map,S=new Map,x=new Set,E=(G,_,U)=>{let ee=a(_,G.file);if(ee){if(U==="*")return{kind:"namespace",file:ee};let z=I(ee).get(U);if(!z)r.push(`${Mt(n.cwd,G.file)}: '${U}' is not exported by '${_}'`);return z??null}if(c(_))return r.push(`${Mt(n.cwd,G.file)}: '${_}' is not part of the bundle`),null;return U==="*"?{kind:"external-namespace",source:_}:{kind:"external",source:_,imported:U}},k=(G,_)=>{if(G.declared.has(_))return{kind:"local",name:l.get(G.file).get(_)};let U=G.imports.get(_);if(U)return E(G,U.specifier,U.imported);return r.push(`${Mt(n.cwd,G.file)}: cannot resolve exported name '${_}'`),null};function I(G){let _=w.get(G);if(_)return _;let U=new Map,ee=o.get(G);if(!ee||x.has(G))return U;x.add(G);let z=new Set;for(let[q,Te]of ee.localExports){let Fe=k(ee,Te);if(Fe)U.set(q,Fe)}for(let q of ee.namedReExports){let Te=E(ee,q.specifier,q.imported);if(Te)U.set(q.exported,Te)}for(let q of ee.namespaceReExports){let Te=E(ee,q.specifier,"*");if(Te)U.set(q.exported,Te)}for(let q of ee.starReExports){let Te=a(q,G);if(Te){for(let[Fe,Mi]of I(Te))if(Fe!=="default"&&!U.has(Fe))U.set(Fe,Mi);for(let Fe of S.get(Te)??[])z.add(Fe)}else if(c(q))r.push(`${Mt(n.cwd,G)}: '${q}' is not part of the bundle`);else z.add(q)}return x.delete(G),w.set(G,U),S.set(G,z),U}let M=new Map,J=[],W=(G,_)=>{switch(G.kind){case"local":return G.name;case"external":return p(G.source,G.imported,G.imported==="default"?_:G.imported);case"external-namespace":return p(G.source,"*",_);case"namespace":return R(G.file,_)}};function R(G,_){let U=M.get(G);if(U)return U;let ee=u(_);M.set(G,ee);let z=[];for(let[q,Te]of I(G)){if(q==="default")continue;let Fe=W(Te,q);z.push(Fe===q?q:`${Fe} as ${q}`)}if(S.get(G)?.size)r.push(`${Mt(n.cwd,G)}: 'export * from' an external module cannot be expressed inside namespace '${ee}'`);return J.push(`declare namespace ${ee} {
|
|
13
|
+
export { ${z.join(", ")} };
|
|
14
|
+
}`),ee}let D=[],Y=[],ne=new Set;for(let[G,_]of o){for(let z of _.directives)ne.add(z);let U=new Map;for(let[z,q]of l.get(G))if(z!==q)U.set(z,q);for(let[z,q]of _.imports){if(_.declared.has(z))continue;let Te=E(_,q.specifier,q.imported);if(!Te)continue;let Fe=W(Te,z);if(Fe!==z)U.set(z,Fe)}let ee=[];for(let z of _.declarations){if(n.keepComments)ee.push(...z.statement.comments);let q=Wo(z.emit,U);if(!/[;}]$/.test(q))q+=";";ee.push(q)}for(let z of _.verbatim){if(n.keepComments)Y.push(...z.comments);Y.push(Wo(z.text,U))}if(ee.length>0)D.push(`// From: ${Mt(n.cwd,G)}
|
|
15
|
+
${ee.join(`
|
|
16
|
+
`)}`)}let De=I(e),K=[],me=[];for(let[G,_]of De){if(_.kind==="external"){me.push(`export { ${_.imported===G?G:`${_.imported} as ${G}`} } from '${_.source}';`);continue}if(_.kind==="external-namespace"){me.push(`export * as ${G} from '${_.source}';`);continue}let U=W(_,G==="default"?"_default":G);K.push(U===G?G:`${U} as ${G}`)}for(let G of S.get(e)??[])me.push(`export * from '${G}';`);let te=new Map;for(let[G,_]of y){let[U,ee]=G.split("\x00"),z=te.get(U)??{named:[],defaults:[],namespaces:[]};if(te.set(U,z),ee==="*")z.namespaces.push(_);else if(ee==="default")z.defaults.push(_);else z.named.push(ee===_?_:`${ee} as ${_}`)}let re=[];for(let[G,_]of[...te].sort(([U],[ee])=>U.localeCompare(ee))){for(let U of _.defaults)re.push(`import ${U} from '${G}';`);for(let U of _.namespaces)re.push(`import * as ${U} from '${G}';`);if(_.named.length>0)re.push(`import { ${_.named.join(", ")} } from '${G}';`)}let oe=[];if(ne.size>0)oe.push([...ne].join(`
|
|
17
|
+
`));if(oe.push(`/**
|
|
18
|
+
* Bundled TypeScript declarations
|
|
19
|
+
* Generated from ${o.size} source files
|
|
20
|
+
*/`),re.length>0)oe.push(re.join(`
|
|
21
|
+
`));if(oe.push(...D),J.length>0)oe.push(J.join(`
|
|
22
|
+
`));if(Y.length>0)oe.push(Y.join(`
|
|
23
|
+
`));let de=[];if(K.length>0)de.push(`export { ${K.join(", ")} };`);if(de.push(...me),de.length===0)de.push("export {};");return oe.push(de.join(`
|
|
24
|
+
`)),{content:`${oe.join(`
|
|
25
|
+
|
|
70
26
|
`)}
|
|
71
|
-
}`}function mc(m,h){let d=l+m.length;while(d<a&&Me(i.charCodeAt(d)))d++;for(let y=0;y<h.length;y++)if(d+y>=a||i.charCodeAt(d+y)!==h.charCodeAt(y))return!1;return d+h.length>=a||!Ke(i.charCodeAt(d+h.length))}function Bt(m,h,d){l+=d.length,p();let y="",C=i.charCodeAt(l);if(C===te||C===se){let A=l;b(C),y=i.slice(A,l)}else{y=W();while(l<a&&i.charCodeAt(l)===ft)l++,y+=`.${W()}`}p();let E=l<a&&i.charCodeAt(l)===V?qi():"{}",x=`${h?"export ":""}declare ${d} ${y} ${E}`,O=qe(m),S=y.startsWith("'")||y.startsWith('"');return{kind:"module",name:y,text:x,isExported:h,source:S?y.slice(1,-1):void 0,leadingComments:O,start:m,end:l}}function Rs(m,h){ee();let d=g(h,l);if(d.charCodeAt(d.length-1)===Y)d=d.slice(0,-1).trimEnd();if(!d)return;let y=kt(d.charCodeAt(0));for(let A=1;y&&A<d.length;A++)y=Ke(d.charCodeAt(A));let C=qe(m);if(y){c.push({kind:"export",name:"default",text:`export default ${d};`,isExported:!0,isTypeOnly:!1,leadingComments:C,start:m,end:l});return}let E="__dtsx_default_export__",x=1;while(i.includes(E))E=`__dtsx_default_export_${x++}__`;let O=Dr(d)||Te(d,!1),S=O==="unknown"&&yf(d)?`typeof ${d}`:O;c.push({kind:"variable",name:E,text:`declare const ${E}: ${S};`,isExported:!1,typeAnnotation:S,modifiers:["const"],start:m,end:l}),c.push({kind:"export",name:"default",text:`export default ${E};`,isExported:!0,isTypeOnly:!1,leadingComments:C,start:m,end:l})}while(l<a){if(p(),l>=a)break;let m=l,h=i.charCodeAt(l);if(h===105&&P("import"))c.push(oc(m));else if(h===101&&P("export")){l+=6,p();let d=i.charCodeAt(l);if(d===100&&P("default")){l+=7,p();let y=l,C=i.charCodeAt(l);if(C===102&&P("function")){let E=St(m,!0,!1,!0);if(E)c.push(E)}else if(C===97&&P("async")&&xs("async")!==Y)if(l+=5,p(),P("function")){let E=St(m,!0,!0,!0);if(E)c.push(E)}else Rs(m,y);else if(C===99&&P("class")){let E=$t(m,!0,!1,!0);c.push(E)}else if(C===97&&P("abstract")){if(l+=8,p(),P("class")){let E=$t(m,!0,!0,!0);c.push(E)}}else Rs(m,y)}else if(d===116&&P("type")){let y=l;if(l+=4,p(),l<a&&i.charCodeAt(l)===V){sr();let C=g(m,l),E=qe(m);c.push({kind:"export",name:"",text:C,isExported:!0,isTypeOnly:!0,source:kr(C),leadingComments:E,start:m,end:l})}else if(l<a&&i.charCodeAt(l)===ge){vs();let C=g(m,l);c.push({kind:"export",name:"",text:C,isExported:!0,isTypeOnly:!0,source:kr(C),start:m,end:l})}else{l=y;let C=Ki(m,!0);c.push(C)}}else if(d===105&&P("interface")){let y=Ui(m,!0);c.push(y)}else if(d===102&&P("function")){let y=St(m,!0,!1,!1);if(y)c.push(y)}else if(d===97&&P("async"))if(l+=5,p(),P("function")){let y=St(m,!0,!0,!1);if(y)c.push(y)}else ee();else if(d===99)if(P("class")){let y=$t(m,!0,!1);c.push(y)}else if(P("const")){let y=l;if(l+=5,p(),P("enum")){l=y+5,p();let C=Wt(m,!0,!0);c.push(C)}else{l=y;let C=Lt(m,"const",!0);for(let E=0;E<C.length;E++)c.push(C[E])}}else ee();else if(d===97&&P("abstract")){if(l+=8,p(),P("class")){let y=$t(m,!0,!0);c.push(y)}}else if(d===108&&P("let")){let y=Lt(m,"let",!0);for(let C=0;C<y.length;C++)c.push(y[C])}else if(d===118&&P("var")){let y=Lt(m,"var",!0);for(let C=0;C<y.length;C++)c.push(y[C])}else if(d===101&&P("enum")){let y=Wt(m,!0,!1);c.push(y)}else if(d===100&&P("declare"))l+=7,p(),Os(m,!0);else if(d===110&&P("namespace")&&F(9)){let y=Bt(m,!0,"namespace");c.push(y)}else if(d===109&&P("module")&&F(6)){let y=Bt(m,!0,"module");c.push(y)}else if(d===V){sr();let y=g(m,l),C=y.includes("export type"),E=qe(m);c.push({kind:"export",name:"",text:y,isExported:!0,isTypeOnly:C,source:kr(y),leadingComments:E,start:m,end:l})}else if(d===ge){vs();let y=g(m,l),C=qe(m);c.push({kind:"export",name:"",text:y,isExported:!0,isTypeOnly:!1,source:kr(y),leadingComments:C,start:m,end:l})}else{ee();let y=g(m,l);if(y)c.push({kind:"export",name:"",text:y,isExported:!0,start:m,end:l})}}else if(h===100&&P("declare"))l+=7,p(),Os(m,!1);else if(h===105&&P("interface")){let d=Ui(m,!1);f.set(d.name,d)}else if(h===116&&P("type")){let d=Ki(m,!1);f.set(d.name,d),c.push(d)}else if(h===102&&P("function")){let d=St(m,!1,!1,!1);if(d)f.set(d.name,d);else ee()}else if(h===97)if(P("async")){let d=l;if(l+=5,p(),P("function")){let y=St(m,!1,!0,!1);if(y)f.set(y.name,y);else l=d,ee()}else l=d,ee()}else if(P("abstract"))if(l+=8,p(),P("class")){let d=$t(m,!1,!1);f.set(d.name,d),c.push(d)}else ee();else l++,ee();else if(h===99)if(P("class")){let d=$t(m,!1,!1);f.set(d.name,d),c.push(d)}else if(P("const")){let d=l;if(l+=5,p(),P("enum")){l=d+5,p();let y=Wt(m,!1,!0);f.set(y.name,y),c.push(y)}else{l=d;let y=Lt(m,"const",!1);for(let C=0;C<y.length;C++)f.set(y[C].name,y[C])}}else l++,ee();else if(h===101&&P("enum")){let d=Wt(m,!1,!1);f.set(d.name,d),c.push(d)}else if(h===108&&P("let"))ee();else if(h===118&&P("var"))ee();else if(h===109&&P("module")&&F(6)){let d=Bt(m,!1,"module");c.push(d)}else if(h===110&&P("namespace")&&F(9)){let d=Bt(m,!1,"namespace");c.push(d)}else{let d=i.charCodeAt(l);if(d===Y)l++;else if(d===te||d===se){if(b(d),l<a&&i.charCodeAt(l)===Y)l++}else if(d===Ae){if(w(),l<a&&i.charCodeAt(l)===Y)l++}else if(d===pf){if(l++,W(),p(),l<a&&i.charCodeAt(l)===ft)l++,W(),p();if(l<a&&i.charCodeAt(l)===Q)Oe(Q,we)}else l++,ee()}}if(f.size>0)wf(c,f);if(u.size>0){let m=new Map;for(let d of c)if(d.kind==="function")m.set(d.name,(m.get(d.name)||0)+1);let h=new Set;for(let[d,y]of m)if(y>1)h.add(d);if(h.size>0){let d=new Set;for(let y of h)for(let C=c.length-1;C>=0;C--)if(c[C].kind==="function"&&c[C].name===y&&u.has(C)){d.add(C);break}if(d.size>0){let y=[...d].sort((C,E)=>E-C);for(let C of y)c.splice(C,1)}}}return c;function Os(m,h){if(P("function")){let d=St(m,h,!1,!1);if(d)c.push(d)}else if(P("async")){if(l+=5,p(),P("function")){let d=St(m,h,!0,!1);if(d)c.push(d)}}else if(P("class")){let d=$t(m,h,!1);c.push(d)}else if(P("abstract")){if(l+=8,p(),P("class")){let d=$t(m,h,!0);c.push(d)}}else if(P("interface")){let d=Ui(m,h);c.push(d)}else if(P("type")){let d=Ki(m,h);c.push(d)}else if(P("enum")){let d=Wt(m,h,!1);c.push(d)}else if(P("const")){let d=l;if(l+=5,p(),P("enum")){l=d+5,p();let y=Wt(m,h,!0);c.push(y)}else if(h){l=d;let y=Lt(m,"const",!0);for(let C=0;C<y.length;C++)c.push(y[C])}else ee()}else if(P("let")||P("var"))if(h){let d=P("let")?"let":"var",y=Lt(m,d,!0);for(let C=0;C<y.length;C++)c.push(y[C])}else ee();else if(P("module")){let d=Bt(m,h,"module");c.push(d)}else if(P("namespace")){let d=Bt(m,h,"namespace");c.push(d)}else if(P("global")){l+=6,p();let d=`declare global ${l<a&&i.charCodeAt(l)===V?qi():"{}"}`,y=qe(m);c.push({kind:"module",name:"global",text:d,isExported:!1,leadingComments:y,start:m,end:l})}else ee()}}function io(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 no(e,t){let r=0;while(r<e.length){let n=e.charCodeAt(r);if(n===te||n===se||n===Ae){let u=n;r++;while(r<e.length)if(e.charCodeAt(r)===Ue)r+=2;else if(e.charCodeAt(r++)===u)break;continue}if(n===H&&e.charCodeAt(r+1)===H){r+=2;while(r<e.length&&e.charCodeAt(r)!==oe&&e.charCodeAt(r)!==ye)r++;continue}if(n===H&&e.charCodeAt(r+1)===ge){let u=e.indexOf("*/",r+2);r=u===-1?e.length:u+2;continue}if(!kt(n)){r++;continue}let i=r++;while(r<e.length&&Ke(e.charCodeAt(r)))r++;let s=i-1,o=r;while(s>=0&&Me(e.charCodeAt(s)))s--;while(o<e.length&&Me(e.charCodeAt(o)))o++;let a=s>=0?e.charCodeAt(s):0,c=o<e.length?e.charCodeAt(o):0,f=i>=3&&e.slice(i-3,i)==="...";if(c===et||a===ft&&!f)continue;if(c===Q&&(a===V||a===tt))continue;t.add(e.slice(i,r))}}function wf(e,t){let r=new Set,n=new Set;for(let o of e)n.add(o.name);let i=new Set,s=[];for(let o=0;o<e.length;o++){let a=e[o];if(a.kind!=="import"){if(s.push(a.text),io(a.text,i),typeof a.value==="string")no(a.value,i)}}for(;;){let o=[];for(let[f,u]of t){if(r.has(f))continue;if(i.has(f)){if(!n.has(f))o.push(u),n.add(f);r.add(f)}}if(o.length===0)break;o.sort((f,u)=>(f.start??1/0)-(u.start??1/0));let a=[],c=0;for(let f=0;f<e.length;f++){let u=e[f].start??1/0;while(c<o.length&&(o[c].start??1/0)<=u)a.push(o[c++]);a.push(e[f])}while(c<o.length)a.push(o[c++]);e.length=0;for(let f=0;f<a.length;f++)e.push(a[f]);for(let f of o)if(f.kind!=="import"){if(s.push(f.text),io(f.text,i),typeof f.value==="string")no(f.value,i)}}}var Se=32,$e=9,oe=10,ye=13,H=47,ge=42,te=39,se=34,Ae=96,Ue=92,V=123,J=125,Q=40,we=41,ue=91,be=93,he=60,ne=62,Y=59,et=58,Ce=61,tt=44,ft=46,Vr=63,Ur=35,pf=64,so=36,gf=95,gn;var co=fe(()=>{pn();gn=["public","protected","private","readonly","override"]});function uo(e,t,r=!0,n=!1){if(Is(t))e=Ls(e);else if(Bs(t))e=Gs(e);let i=ar(e),s=`${t}:${r?1:0}:${n?1:0}`,o=Vt.get(s);if(o&&o.contentHash===i)return o.lastAccess=++fo,o.declarations;let a=n?oo(e,t,r):ao(e,t,r);if(Vt.set(s,{declarations:a,contentHash:i,lastAccess:++fo}),Vt.size>vf){let c=Math.max(1,Math.ceil(Vt.size*0.1)),f=[];for(let[u,l]of Vt)f.push([u,l.lastAccess]);f.sort((u,l)=>u[1]-l[1]);for(let u=0;u<c&&u<f.length;u++)Vt.delete(f[u][0])}return a}var vf=100,fo=0,Vt;var ho=fe(()=>{an();js();co();Yi();Vt=new Map});function zr(e,t,r=!0,n=!1){return uo(e,t,r,n)}var yn=fe(()=>{ho()});import{dirname as ip,relative as Ef,resolve as np}from"path";async function mo(e,t,r){let n=new Map,i=[],s=new Set,o=0,a=0,c=0,f=[];for(let k of e){let R=t.get(k);if(!R)continue;f.push({file:k,decls:zr(R,k,r.keepComments)})}for(let{file:k,decls:R}of f){o+=R.length;for(let I of R)if(I.kind==="import"){a++;let _=I.source||"";if(_.startsWith("."))continue;if(!n.has(_))n.set(_,{source:_,specifiers:new Map,isTypeOnly:I.isTypeOnly||!1,isSideEffect:I.isSideEffect||!1});let W=n.get(_);if(I.specifiers)for(let P of I.specifiers){let F=P.alias||P.name;if(!W.specifiers.has(F))W.specifiers.set(F,{name:P.name,alias:P.alias,isType:P.isType||!1})}if(!I.isTypeOnly)W.isTypeOnly=!1}else if(I.isExported||I.kind==="export"){if(c++,I.kind==="export"&&I.source&&(I.source.startsWith(".")||I.source.startsWith("/")))continue;if(I.name&&s.has(I.name))continue;if(I.name)s.add(I.name);i.push({declaration:I,file:k})}}let u=[];u.push("/**"),u.push(" * Bundled TypeScript declarations"),u.push(` * Generated from ${e.length} source files`),u.push(" */"),u.push("");let l=r.importOrder||["bun"],g=Array.from(n.values()),p=Array(g.length);for(let k=0;k<g.length;k++){let R=g[k].source,I=l.length;for(let _=0;_<l.length;_++)if(R.startsWith(l[_])){I=_;break}p[k]=I}let v=g.map((k,R)=>R);v.sort((k,R)=>{let I=p[k],_=p[R];if(I!==_)return I-_;return g[k].source.localeCompare(g[R].source)});let b=v.map((k)=>g[k]);for(let k of b)if(k.isSideEffect)u.push(`import '${k.source}';`);else if(k.specifiers.size>0){let R=Array.from(k.specifiers.values()).map((_)=>{let W=_.isType?"type ":"";return _.alias?`${W}${_.name} as ${_.alias}`:`${W}${_.name}`}),I=k.isTypeOnly?"type ":"";u.push(`import ${I}{ ${R.join(", ")} } from '${k.source}';`)}if(b.length>0)u.push("");let w=new Map;for(let{declaration:k,file:R}of i){if(!w.has(R))w.set(R,[]);w.get(R).push(k)}for(let[k,R]of w){let I=Ef(r.cwd,k);u.push(`// From: ${I}`);for(let _ of R){if(r.keepComments&&_.leadingComments)for(let W of _.leadingComments)u.push(W);u.push(po(_))}u.push("")}let T=u.join(`
|
|
72
|
-
`);return{content:T,files:e,declarationCount:o,importCount:a,exportCount:c,size:Buffer.byteLength(T,"utf8"),warnings:[]}}function po(e){if(e.text){let r=e.text.trim();if(e.isExported&&!r.startsWith("export"))r=`export ${r}`;if(!r.endsWith(";")&&!r.endsWith("}"))r+=";";return r}let t=[];if(e.isExported)t.push("export");if(e.isDefault)t.push("default");switch(e.kind){case"function":if(t.push("declare function"),t.push(e.name),e.generics)t.push(e.generics);if(t.push(`(${bf(e.parameters)})`),e.returnType)t.push(`: ${e.returnType}`);break;case"variable":if(t.push("declare const"),t.push(e.name),e.typeAnnotation)t.push(`: ${e.typeAnnotation}`);break;case"interface":if(t.push("interface"),t.push(e.name),e.generics)t.push(e.generics);if(e.extends)t.push(`extends ${e.extends}`);if(t.push("{"),e.members)for(let r of e.members)t.push(` ${r.name}${r.typeAnnotation?`: ${r.typeAnnotation}`:""};`);t.push("}");break;case"type":if(t.push("type"),t.push(e.name),e.generics)t.push(e.generics);t.push("="),t.push(e.typeAnnotation||"unknown");break;case"class":if(t.push("declare class"),t.push(e.name),e.generics)t.push(e.generics);if(e.extends)t.push(`extends ${e.extends}`);if(e.implements&&e.implements.length>0)t.push(`implements ${e.implements.join(", ")}`);if(t.push("{"),e.members)for(let r of e.members)t.push(` ${po(r)}`);t.push("}");break;case"enum":if(t.push("declare enum"),t.push(e.name),t.push("{"),e.members){let r=e.members.map((n)=>n.value!==void 0?`${n.name} = ${n.value}`:n.name);t.push(` ${r.join(`,
|
|
73
|
-
`)}`)}t.push("}");break;default:return e.text||""}return t.join(" ")}function bf(e){if(!e||e.length===0)return"";return e.map((t)=>{let r="";if(t.rest)r+="...";if(r+=t.name,t.optional)r+="?";if(t.type)r+=`: ${t.type}`;if(t.defaultValue)r+=` = ${t.defaultValue}`;return r}).join(", ")}var go=fe(()=>{yn()});import{existsSync as gr,mkdirSync as Sf,readFileSync as wn,renameSync as $f,rmSync as yo,statSync as Co,writeFileSync as wo}from"fs";import{join as vo,relative as Hr,resolve as Af}from"path";class vn{cacheDir;manifestPath;manifest=null;configHash;constructor(e){this.cacheDir=Af(e.cwd,Jr),this.manifestPath=vo(this.cacheDir,xf),this.configHash=this.hashConfig(e)}hashConfig(e){let t={keepComments:e.keepComments,importOrder:e.importOrder,outputStructure:e.outputStructure,isolatedDeclarations:e.isolatedDeclarations,declarationMap:e.declarationMap,indentStyle:e.indentStyle,indentSize:e.indentSize,prettier:e.prettier,typeMappings:e.typeMappings?{includeDefaults:e.typeMappings.includeDefaults,presets:e.typeMappings.presets,cacheKey:e.typeMappings.cacheKey,rules:e.typeMappings.rules.map((r)=>({pattern:typeof r.pattern==="string"?{kind:"string",value:r.pattern}:{kind:"regex",source:r.pattern.source,flags:r.pattern.flags},replacement:r.replacement,global:r.global,priority:r.priority,hasCondition:Boolean(r.condition)}))}:void 0,lineEnding:e.lineEnding,normalizeOutput:e.normalizeOutput,declarationOrder:e.declarationOrder,plugins:e.plugins?.map((r)=>({name:r.name,version:r.version,cacheKey:r.cacheKey}))};return String(ar(JSON.stringify(t)))}hashString(e){return String(ar(e))}load(){try{if(!gr(this.manifestPath))return!1;let e=wn(this.manifestPath,"utf-8"),t=JSON.parse(e);if(t.version!==Cn)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:Cn,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};if(this.manifest.updatedAt=Date.now(),!gr(this.cacheDir))Sf(this.cacheDir,{recursive:!0});let e=`${this.manifestPath}.${process.pid}.tmp`;try{wo(e,JSON.stringify(this.manifest,null,2)),$f(e,this.manifestPath)}finally{if(gr(e))yo(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=Hr(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=Co(e),{mtimeMs:s,ctimeMs:o}=i;if(i.size!==n.sourceSize)return null;if(s!==n.sourceMtime||o!==n.sourceCtime){let a=wn(e,"utf-8");if(this.hashString(a)!==n.sourceHash)return null;n.sourceMtime=s,n.sourceCtime=o}return n.dtsContent}catch{return null}}update(e,t,r,n){if(!this.manifest)this.manifest={version:Cn,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};let i=Hr(n,e),s,o,a;try{let c=Co(e);s=c.mtimeMs,o=c.ctimeMs,a=c.size}catch{s=Date.now(),o=s,a=Buffer.byteLength(t)}this.manifest.entries[i]={sourcePath:i,sourceHash:this.hashString(t),sourceMtime:s,sourceCtime:o,sourceSize:a,dtsContent:r,dtsHash:this.hashString(r),generatedAt:Date.now(),configHash:this.configHash}}remove(e,t){if(!this.manifest)return;let r=Hr(t,e);delete this.manifest.entries[r]}clear(){this.manifest=null;try{if(gr(this.manifestPath))yo(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)=>Hr(t,i)));for(let i of Object.keys(this.manifest.entries))if(!n.has(i))delete this.manifest.entries[i],r++;return r}}function Eo(e){let t=vo(e,".gitignore");try{let r="";if(gr(t))r=wn(t,"utf-8");if(!r.split(/\r?\n/).some((n)=>n.trim()===Jr||n.trim()===`${Jr}/`)){let n=r.trimEnd(),i=`${n}${n?`
|
|
27
|
+
`,files:[...o.keys()],exportCount:De.size,warnings:r}}var Bo,Mc;var jo=pe(()=>{en();Bo=/^[A-Z_$][\w$]*$/i;Mc=/^(?: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 ci(e){if(Fc)return Bun.hash(e);let t=0;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);t=(t<<5)-t+n,t=t&t}return t}var Fc;var rn=pe(()=>{Fc=typeof globalThis.Bun?.hash==="function"});import{existsSync as fi,mkdirSync as Nc,readFileSync as on,renameSync as Lc,rmSync as _o,statSync as Vo,writeFileSync as Uo}from"fs";import{join as Ko,relative as Bi,resolve as Wc}from"path";class sn{cacheDir;manifestPath;manifest=null;configHash;constructor(e){this.cacheDir=Wc(e.cwd,Gi),this.manifestPath=Ko(this.cacheDir,Bc),this.configHash=this.hashConfig(e)}hashConfig(e){let t={keepComments:e.keepComments,importOrder:e.importOrder,outputStructure:e.outputStructure,isolatedDeclarations:e.isolatedDeclarations,declarationMap:e.declarationMap,indentStyle:e.indentStyle,indentSize:e.indentSize,prettier:e.prettier,typeMappings:e.typeMappings?{includeDefaults:e.typeMappings.includeDefaults,presets:e.typeMappings.presets,cacheKey:e.typeMappings.cacheKey,rules:e.typeMappings.rules.map((i)=>({pattern:typeof i.pattern==="string"?{kind:"string",value:i.pattern}:{kind:"regex",source:i.pattern.source,flags:i.pattern.flags},replacement:i.replacement,global:i.global,priority:i.priority,hasCondition:Boolean(i.condition)}))}:void 0,lineEnding:e.lineEnding,normalizeOutput:e.normalizeOutput,declarationOrder:e.declarationOrder,plugins:e.plugins?.map((i)=>({name:i.name,version:i.version,cacheKey:i.cacheKey}))};return String(ci(JSON.stringify(t)))}hashString(e){return String(ci(e))}load(){try{if(!fi(this.manifestPath))return!1;let e=on(this.manifestPath,"utf-8"),t=JSON.parse(e);if(t.version!==nn)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:nn,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};if(this.manifest.updatedAt=Date.now(),!fi(this.cacheDir))Nc(this.cacheDir,{recursive:!0});let e=`${this.manifestPath}.${process.pid}.tmp`;try{Uo(e,JSON.stringify(this.manifest,null,2)),Lc(e,this.manifestPath)}finally{if(fi(e))_o(e,{force:!0})}}needsRegeneration(e,t){return this.getCachedIfValid(e,t)===null}getCached(e,t){return this.getCachedIfValid(e,t)}getCachedIfValid(e,t){if(!this.manifest)return null;let i=Bi(t,e),n=this.manifest.entries[i];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 r=Vo(e),{mtimeMs:o,ctimeMs:s}=r;if(r.size!==n.sourceSize)return null;if(o!==n.sourceMtime||s!==n.sourceCtime){let a=on(e,"utf-8");if(this.hashString(a)!==n.sourceHash)return null;n.sourceMtime=o,n.sourceCtime=s}return n.dtsContent}catch{return null}}update(e,t,i,n){if(!this.manifest)this.manifest={version:nn,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};let r=Bi(n,e),o,s,a;try{let c=Vo(e);o=c.mtimeMs,s=c.ctimeMs,a=c.size}catch{o=Date.now(),s=o,a=Buffer.byteLength(t)}this.manifest.entries[r]={sourcePath:r,sourceHash:this.hashString(t),sourceMtime:o,sourceCtime:s,sourceSize:a,dtsContent:i,dtsHash:this.hashString(i),generatedAt:Date.now(),configHash:this.configHash}}remove(e,t){if(!this.manifest)return;let i=Bi(t,e);delete this.manifest.entries[i]}clear(){this.manifest=null;try{if(fi(this.manifestPath))_o(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 i of Object.values(this.manifest.entries))t+=i.dtsContent.length;return{entries:e,size:t}}prune(e,t){if(!this.manifest)return 0;let i=0,n=new Set(Array.from(e).map((r)=>Bi(t,r)));for(let r of Object.keys(this.manifest.entries))if(!n.has(r))delete this.manifest.entries[r],i++;return i}}function Ho(e){let t=Ko(e,".gitignore");try{let i="";if(fi(t))i=on(t,"utf-8");if(!i.split(/\r?\n/).some((n)=>n.trim()===Gi||n.trim()===`${Gi}/`)){let n=i.trimEnd(),r=`${n}${n?`
|
|
74
28
|
|
|
75
29
|
`:""}# dtsx cache
|
|
76
|
-
${
|
|
77
|
-
`;wo(t,i)}}catch{}}var Cn=3,Jr=".dtsx-cache",xf="manifest.json";var bo=fe(()=>{Yi()});import{readFile as Tf,stat as up,writeFile as Pf}from"fs/promises";async function So(e,t){if(qr)return globalThis.Bun.write(e,t);let r=typeof t==="string"?t:t instanceof ArrayBuffer?Buffer.from(t):t;return await Pf(e,r),typeof t==="string"?Buffer.byteLength(t):t.byteLength}async function dt(e){if(qr)return globalThis.Bun.file(e).text();return Tf(e,"utf-8")}var qr,hp;var Yr=fe(()=>{qr=typeof globalThis.Bun<"u",hp=!qr&&typeof process<"u"&&!!process.versions?.node});function Ut(e){return $o[e]>=$o[Zr]}function kf(){if(!Of)return"";return`[${new Date().toISOString().slice(11,23)}] `}function Mf(e,t){let r=kf();if(e||r)return[`${r}${e}`,...t];return t}function Kt(e,t,r){let n=Mf(t,r);if(Ao){Ao(e,...n);return}switch(e){case"debug":console.debug(...n);break;case"info":console.log(...n);break;case"warn":console.warn(...n);break;case"error":console.error(...n);break}}function xo(e){return{debug:(...t)=>{if(Ut("debug"))Kt("debug",e,t)},info:(...t)=>{if(Ut("info"))Kt("info",e,t)},warn:(...t)=>{if(Ut("warn"))Kt("warn",e,t)},error:(...t)=>{if(Ut("error"))Kt("error",e,t)},setLevel:(t)=>{Zr=t},getLevel:()=>Zr,child:(t)=>{let r=e?`${e}:${t}`:`[${t}]`;return xo(r)},time:(t)=>{let r=performance.now();return()=>{let n=performance.now()-r;if(Ut("debug"))Kt("debug",e,[`${t}: ${n.toFixed(2)}ms`])}},progress:(t)=>{if(Ut("info"))if(typeof process<"u"&&process.stdout?.isTTY)process.stdout.write(`\r${e} ${t}`);else Kt("info",e,[t])}}}function En(e){Zr=e}var $o,Zr="info",Rf="[dtsx]",Of=!1,Ao=null,K;var To=fe(()=>{$o={debug:0,info:1,warn:2,error:3,silent:4};K=xo(Rf)});import Df from"process";import{existsSync as Po,statSync as Ro}from"fs";import{existsSync as If,mkdirSync as Cp,readdirSync as wp,readFileSync as Ff,writeFileSync as vp}from"fs";import{homedir as zt}from"os";import{dirname as Sp,resolve as rt}from"path";import ki from"process";import{existsSync as Oo,statSync as ko}from"fs";import{existsSync as jn,mkdirSync as Nf,readdirSync as Lf,writeFileSync as Wf}from"fs";import{homedir as Ht}from"os";import{dirname as Mo,resolve as He}from"path";import Mt from"process";import{join as Bf,relative as Gf,resolve as Do}from"path";import yi from"process";import{existsSync as ma,mkdirSync as Dp,readdirSync as Ip,writeFileSync as Fp}from"fs";import{homedir as bn}from"os";import{dirname as Wp,resolve as ze}from"path";import Cr from"process";import{join as jf,relative as _f,resolve as Io}from"path";import Ci from"process";import{existsSync as pa,mkdirSync as Vp,readdirSync as Up,writeFileSync as Kp}from"fs";import{dirname as Hp,resolve as wi}from"path";import _n from"process";import{Buffer as At}from"buffer";import{createCipheriv as Vf,createDecipheriv as Uf,randomBytes as Sn}from"crypto";import{closeSync as $n,createReadStream as Fo,createWriteStream as Kf,existsSync as An,fsyncSync as No,openSync as Lo,writeFileSync as zf}from"fs";import{access as Hf,constants as Wo,mkdir as Jf,readdir as Xr,rename as Bo,stat as Jt,unlink as Qr,writeFile as xn}from"fs/promises";import{join as qt}from"path";import We from"process";import{pipeline as qf}from"stream/promises";import{createGzip as Go}from"zlib";import Yt from"process";import yt from"process";import{Buffer as mt}from"buffer";import{createCipheriv as Yf,createDecipheriv as Zf,randomBytes as Tn}from"crypto";import{closeSync as Pn,createReadStream as jo,createWriteStream as Xf,existsSync as ei,fsyncSync as _o,openSync as Vo,writeFileSync as Qf}from"fs";import{access as eu,constants as Uo,mkdir as tu,readdir as ti,rename as Ko,stat as Zt,unlink as ri,writeFile as Rn}from"fs/promises";import{isAbsolute as ru,join as Xt,resolve as iu}from"path";import de from"process";import{pipeline as nu}from"stream/promises";import{createGzip as zo}from"zlib";import Qt from"process";import Ct from"process";import ii from"process";import{existsSync as ni}from"fs";import{resolve as On}from"path";import{existsSync as su}from"fs";import{existsSync as ou,readdirSync as au}from"fs";import{extname as kn,resolve as Ho}from"path";import lu from"process";import{join as cu,relative as fu,resolve as Jo}from"path";import vi from"process";import{Buffer as pt}from"buffer";import{createCipheriv as uu,createDecipheriv as hu,randomBytes as Mn}from"crypto";import{closeSync as Dn,createReadStream as qo,createWriteStream as du,existsSync as si,fsyncSync as Yo,openSync as Zo,writeFileSync as mu}from"fs";import{access as pu,constants as Xo,mkdir as gu,readdir as oi,rename as Qo,stat as er,unlink as ai,writeFile as In}from"fs/promises";import{isAbsolute as yu,join as tr,resolve as Cu}from"path";import me from"process";import{pipeline as wu}from"stream/promises";import{createGzip as ea}from"zlib";import rr from"process";import wt from"process";import li from"process";import{existsSync as ci}from"fs";import{resolve as Fn}from"path";import{existsSync as vu}from"fs";class ga{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(!Po(e))return!0;return Ro(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=Po(r)?Ro(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 ya{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 Su(e,t){this[e]=bu.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(!Oo(e))return!0;return ko(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=Oo(r)?ko(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 xu(e,t={}){let r=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return r?`${e}:${r}`:e}function Tu(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Pu(e){return e.getStats().size*2}function rs(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Ee(t[0])&&"id"in t[0]&&t[0].id===3&&Ee(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Ee(t)&&Ee(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(Ee(e)&&"arr"in e&&Array.isArray(e.arr)&&Ee(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Ee(t[0])&&Ee(e[0])){let n=[...t];for(let i of e)if(Ee(i)&&"name"in i){if(!n.find((s)=>Ee(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(Ee(i)&&"path"in i){if(!n.find((s)=>Ee(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((s)=>bi(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(!Ee(t)||!Ee(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(Ee(i)&&Ee(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&&Ee(i[0])&&Ee(r[n][0])){let s=[...i];for(let o of r[n])if(Ee(o)&&"name"in o){if(!s.find((a)=>Ee(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(Ee(o)&&"path"in o){if(!s.find((a)=>Ee(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((a)=>bi(a,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function bi(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!bi(e[r],t[r]))return!1;return!0}if(Ee(e)&&Ee(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!bi(e[i],t[i]))return!1}return!0}return!1}function Ee(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Ru(e,t){if(!pa(e))return null;try{let r=await import(e),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return rs(t,n)}catch{return null}}catch{return null}}async function Ou({name:e="",cwd:t,defaultConfig:r}){let n=t||_n.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let a of i){let c=wi(n,`${o}${a}`),f=await Ru(c,r);if(f!==null)return f}try{let o=wi(n,"package.json");if(pa(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return rs(r,a)}catch{}}}catch{}return r}function ku(e,t={}){let r=Ci.cwd();while(r.includes("storage"))r=Io(r,"..");let n=Io(r,e||"");if(t?.relative)return _f(Ci.cwd(),n);return n}async function Mu(){try{let e=await Ou({name:"clarity",defaultConfig:di,cwd:Ci.cwd(),endpoint:"",headers:{}});return{...di,...e}}catch{return di}}function xe(){if(yt.env.NODE_ENV==="test"||yt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Du(){if(yt.env.NODE_ENV==="test"||yt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof yt<"u"){let e=yt.type;if(e==="renderer"||e==="worker")return!1;return!!(yt.versions&&(yt.versions.node||yt.versions.bun))}return!1}class wa{async format(e){let t=await Du(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Yt.pid,hostname:t(),environment:Yt.env.NODE_ENV||"development",platform:Yt.platform,version:Yt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Yt.env.NODE_ENV||Yt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Si{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={...Un},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new wa,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??We.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...mi,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...mi};return{...mi,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Un.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 Hf(this.config.logDirectory,Wo.F_OK|Wo.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Jf(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:At.from(e);try{if(!An(this.currentLogFile))await xn(this.currentLogFile,"",{mode:420});if(n=Lo(this.currentLogFile,"a",420),zf(n,a,{flag:"a"}),No(n),n!==void 0)$n(n),n=void 0;if((await Jt(this.currentLogFile)).size===0){if(await xn(this.currentLogFile,a,{flag:"w",mode:420}),(await Jt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(i<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let l=o*2**i;await new Promise((g)=>setTimeout(g,l)),i++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(n!==void 0)try{$n(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===s-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}i++;let c=o*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return 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(xe())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,o],[,a])=>a.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,i);if(n.length>s)for(let[o]of n.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return Sn(16).toString("hex")}generateKey(){return Sn(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=Sn(16),n=Vf("aes-256-gcm",t,r),i=At.concat([n.update(e,"utf8"),n.final()]),s=n.getAuthTag();return{encrypted:At.concat([r,i,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Go(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(At.from(At.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(xe())return;let e=await Jt(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Xr(this.config.logDirectory),s=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${o}`;if(await Jt(r).catch(()=>null))try{if(await Bo(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await Qr(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await 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 Jt(r).catch(()=>null))await Bo(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await Xr(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(qt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Fo(e),n=Kf(t),i=Go();await qf(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=Lo(this.currentLogFile,"r+");No(e),$n(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(!xe()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Xr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Qr(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?ve.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,a=(p)=>p.replace(this.ANSI_PATTERN,"");if(!this.fancy){let p=[];if(o)p.push(t);if(s==="warning")p.push("WARN");else if(s==="error")p.push("ERROR");else if(r)p.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)p.push(n.replace(/[[\]]/g,""));return p.push(i),p.join(" ")}let c=We.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${i}`;else if(s==="info"||s==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${ve.cyan(i)}`;if(!o)return f.trim();let u=a(f).trim().length,l=a(t).length,g=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(g)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let a=Number.parseInt(o,10);return a<t[0].length?String(t[0][a]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let a=t[n++];switch(o){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,a;if(t instanceof Error)o=t.message,a=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!xe()){let f=Ra[e],u=this.options.showTags!==!1&&this.name?ve.gray(this.formatTag(this.name)):"",l;switch(e){case"debug":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:ve.gray(o),level:e}),console.error(l);break;case"info":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:o,level:e}),console.error(l);break;case"success":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:ve.green(o),level:e}),console.error(l);break;case"warning":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:o,level:e}),console.warn(l);break;case"error":if(l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:o,level:e}),console.error(l),a){let g=a.split(`
|
|
78
|
-
`);for(let p of
|
|
30
|
+
${Gi}/
|
|
31
|
+
`;Uo(t,r)}}catch{}}var nn=3,Gi=".dtsx-cache",Bc="manifest.json";var zo=pe(()=>{rn()});function Jo(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 qo=()=>{};function Kt(e){return Yo[e]>=Yo[ji]}function _c(){if(!jc)return"";return`[${new Date().toISOString().slice(11,23)}] `}function Vc(e,t){let i=_c();if(e||i)return[`${i}${e}`,...t];return t}function Ht(e,t,i){let n=Vc(t,i);if(Zo){Zo(e,...n);return}switch(e){case"debug":console.debug(...n);break;case"info":console.log(...n);break;case"warn":console.warn(...n);break;case"error":console.error(...n);break}}function Xo(e){return{debug:(...t)=>{if(Kt("debug"))Ht("debug",e,t)},info:(...t)=>{if(Kt("info"))Ht("info",e,t)},warn:(...t)=>{if(Kt("warn"))Ht("warn",e,t)},error:(...t)=>{if(Kt("error"))Ht("error",e,t)},setLevel:(t)=>{ji=t},getLevel:()=>ji,child:(t)=>{let i=e?`${e}:${t}`:`[${t}]`;return Xo(i)},time:(t)=>{let i=performance.now();return()=>{let n=performance.now()-i;if(Kt("debug"))Ht("debug",e,[`${t}: ${n.toFixed(2)}ms`])}},progress:(t)=>{if(Kt("info"))if(typeof process<"u"&&process.stdout?.isTTY)process.stdout.write(`\r${e} ${t}`);else Ht("info",e,[t])}}}function an(e){ji=e}var Yo,ji="info",Gc="[dtsx]",jc=!1,Zo=null,Z;var Qo=pe(()=>{Yo={debug:0,info:1,warn:2,error:3,silent:4};Z=Xo(Gc)});import Uc from"process";import{existsSync as es,statSync as ts}from"fs";import{existsSync as Kc,mkdirSync as dp,readdirSync as mp,readFileSync as Hc,writeFileSync as pp}from"fs";import{homedir as zt}from"os";import{dirname as Cp,resolve as it}from"path";import Er from"process";import{existsSync as is,statSync as rs}from"fs";import{existsSync as Tn,mkdirSync as zc,readdirSync as Jc,writeFileSync as qc}from"fs";import{homedir as Jt}from"os";import{dirname as ns,resolve as Je}from"path";import Dt from"process";import{join as Yc,relative as Zc,resolve as os}from"path";import ar from"process";import{existsSync as Gs,mkdirSync as Rp,readdirSync as Pp,writeFileSync as Op}from"fs";import{homedir as ln}from"os";import{dirname as Dp,resolve as ze}from"path";import hi from"process";import{join as Xc,relative as Qc,resolve as ss}from"path";import lr from"process";import{existsSync as js,mkdirSync as Wp,readdirSync as Bp,writeFileSync as Gp}from"fs";import{dirname as _p,resolve as cr}from"path";import Rn from"process";import{Buffer as Rt}from"buffer";import{createCipheriv as ef,createDecipheriv as tf,randomBytes as cn}from"crypto";import{closeSync as fn,createReadStream as as,createWriteStream as rf,existsSync as un,fsyncSync as ls,openSync as cs,writeFileSync as nf}from"fs";import{access as of,constants as fs,mkdir as sf,readdir as _i,rename as us,stat as qt,unlink as Vi,writeFile as hn}from"fs/promises";import{join as Yt}from"path";import _e from"process";import{pipeline as af}from"stream/promises";import{createGzip as hs}from"zlib";import Zt from"process";import Ct from"process";import{Buffer as pt}from"buffer";import{createCipheriv as lf,createDecipheriv as cf,randomBytes as dn}from"crypto";import{closeSync as mn,createReadStream as ds,createWriteStream as ff,existsSync as Ui,fsyncSync as ms,openSync as ps,writeFileSync as uf}from"fs";import{access as hf,constants as gs,mkdir as df,readdir as Ki,rename as ys,stat as Xt,unlink as Hi,writeFile as pn}from"fs/promises";import{isAbsolute as mf,join as Qt,resolve as pf}from"path";import ge from"process";import{pipeline as gf}from"stream/promises";import{createGzip as Cs}from"zlib";import ei from"process";import wt from"process";import zi from"process";import{existsSync as Ji}from"fs";import{resolve as gn}from"path";import{existsSync as yf}from"fs";import{existsSync as Cf,readdirSync as wf}from"fs";import{extname as yn,resolve as ws}from"path";import vf from"process";import{join as Ef,relative as bf,resolve as vs}from"path";import fr from"process";import{Buffer as gt}from"buffer";import{createCipheriv as Sf,createDecipheriv as $f,randomBytes as Cn}from"crypto";import{closeSync as wn,createReadStream as Es,createWriteStream as Af,existsSync as qi,fsyncSync as bs,openSync as Ss,writeFileSync as xf}from"fs";import{access as Tf,constants as $s,mkdir as Rf,readdir as Yi,rename as As,stat as ti,unlink as Zi,writeFile as vn}from"fs/promises";import{isAbsolute as Pf,join as ii,resolve as Of}from"path";import ye from"process";import{pipeline as kf}from"stream/promises";import{createGzip as xs}from"zlib";import ri from"process";import vt from"process";import Xi from"process";import{existsSync as Qi}from"fs";import{resolve as En}from"path";import{existsSync as Mf}from"fs";class _s{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(!es(e))return!0;return ts(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=es(i)?ts(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 Vs{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 Ff(e,t){this[e]=If.bind(null,t)}class Gn{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(!is(e))return!0;return rs(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=is(i)?rs(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 jn{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 Wf(e,t={}){let i=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return i?`${e}:${i}`:e}function Bf(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Gf(e){return e.getStats().size*2}function _n(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&xe(t[0])&&"id"in t[0]&&t[0].id===3&&xe(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(xe(t)&&xe(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(xe(e)&&"arr"in e&&Array.isArray(e.arr)&&xe(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&xe(t[0])&&xe(e[0])){let n=[...t];for(let r of e)if(xe(r)&&"name"in r){if(!n.find((o)=>xe(o)&&("name"in o)&&o.name===r.name))n.push(r)}else if(xe(r)&&"path"in r){if(!n.find((o)=>xe(o)&&("path"in o)&&o.path===r.path))n.push(r)}else if(!n.some((o)=>hr(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(!xe(t)||!xe(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(xe(r)&&xe(i[n]))i[n]=_n(i[n],r);else if(Array.isArray(r)&&Array.isArray(i[n]))if(r.length>0&&i[n].length>0&&xe(r[0])&&xe(i[n][0])){let o=[...r];for(let s of i[n])if(xe(s)&&"name"in s){if(!o.find((a)=>xe(a)&&("name"in a)&&a.name===s.name))o.push(s)}else if(xe(s)&&"path"in s){if(!o.find((a)=>xe(a)&&("path"in a)&&a.path===s.path))o.push(s)}else if(!o.some((a)=>hr(a,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 hr(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(!hr(e[i],t[i]))return!1;return!0}if(xe(e)&&xe(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(!hr(e[r],t[r]))return!1}return!0}return!1}function xe(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function jf(e,t){if(!js(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 _n(t,n)}catch{return null}}catch{return null}}async function _f({name:e="",cwd:t,defaultConfig:i}){let n=t||Rn.cwd(),r=[".ts",".js",".mjs",".cjs",".json"],o=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let s of o)for(let a of r){let c=cr(n,`${s}${a}`),f=await jf(c,i);if(f!==null)return f}try{let s=cr(n,"package.json");if(js(s)){let a=(await import(s))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return _n(i,a)}catch{}}}catch{}return i}function Vf(e,t={}){let i=lr.cwd();while(i.includes("storage"))i=ss(i,"..");let n=ss(i,e||"");if(t?.relative)return Qc(lr.cwd(),n);return n}async function Uf(){try{let e=await _f({name:"clarity",defaultConfig:rr,cwd:lr.cwd(),endpoint:"",headers:{}});return{...rr,...e}}catch{return rr}}function ke(){if(Ct.env.NODE_ENV==="test"||Ct.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Kf(){if(Ct.env.NODE_ENV==="test"||Ct.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Ct<"u"){let e=Ct.type;if(e==="renderer"||e==="worker")return!1;return!!(Ct.versions&&(Ct.versions.node||Ct.versions.bun))}return!1}class Ks{async format(e){let t=await Kf(),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:Zt.pid,hostname:t(),environment:Zt.env.NODE_ENV||"development",platform:Zt.platform,version:Zt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Zt.env.NODE_ENV||Zt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class dr{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={...On},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ks,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??_e.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{...nr,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...nr};return{...nr,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:On.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 of(this.config.logDirectory,fs.F_OK|fs.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await sf(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Rt.from(e);try{if(!un(this.currentLogFile))await hn(this.currentLogFile,"",{mode:420});if(n=cs(this.currentLogFile,"a",420),nf(n,a,{flag:"a"}),ls(n),n!==void 0)fn(n),n=void 0;if((await qt(this.currentLogFile)).size===0){if(await hn(this.currentLogFile,a,{flag:"w",mode:420}),(await qt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(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 l=s*2**r;await new Promise((y)=>setTimeout(y,l)),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(a){if(r===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}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 Yt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Yt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Yt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(ke())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],[,a])=>a.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 cn(16).toString("hex")}generateKey(){return cn(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=cn(16),n=ef("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=hs(),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(ke())return;let e=await qt(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let i=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let r=await _i(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,a=`${i}.${s}`;if(await qt(i).catch(()=>null))try{if(await us(i,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await Vi(a)}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 hn(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 qt(i).catch(()=>null))await us(i,o)}if(this.currentLogFile=n,t.maxFiles){let r=(await _i(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of r.slice(t.maxFiles))await Vi(Yt(this.config.logDirectory,o))}}}async compressLogFile(e,t){let i=as(e),n=rf(t),r=hs();await af(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()})),un(this.currentLogFile))try{let e=cs(this.currentLogFile,"r+");ls(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(!ke()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await _i(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Vi(Yt(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?$e.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:i="",tag:n="",message:r,level:o,showTimestamp:s=!0}=e,a=(p)=>p.replace(this.ANSI_PATTERN,"");if(!this.fancy){let p=[];if(s)p.push(t);if(o==="warning")p.push("WARN");else if(o==="error")p.push("ERROR");else if(i)p.push(i.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)p.push(n.replace(/[[\]]/g,""));return p.push(r),p.join(" ")}let c=_e.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} ${$e.cyan(r)}`;if(!s)return f.trim();let u=a(f).trim().length,l=a(t).length,y=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(y)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let a=Number.parseInt(s,10);return a<t[0].length?String(t[0][a]):o});let i=/%([sdijfo%])/g,n=0,r=e.replace(i,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let a=t[n++];switch(s){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return o}});if(n<t.length)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,a;if(t instanceof Error)s=t.message,a=t.stack;else s=this.formatMessage(t,i);if(this.fancy&&!ke()){let f=ta[e],u=this.options.showTags!==!1&&this.name?$e.gray(this.formatTag(this.name)):"",l;switch(e){case"debug":l=this.formatConsoleMessage({timestamp:r,icon:f,tag:u,message:$e.gray(s),level:e}),console.error(l);break;case"info":l=this.formatConsoleMessage({timestamp:r,icon:f,tag:u,message:s,level:e}),console.error(l);break;case"success":l=this.formatConsoleMessage({timestamp:r,icon:f,tag:u,message:$e.green(s),level:e}),console.error(l);break;case"warning":l=this.formatConsoleMessage({timestamp:r,icon:f,tag:u,message:s,level:e}),console.warn(l);break;case"error":if(l=this.formatConsoleMessage({timestamp:r,icon:f,tag:u,message:s,level:e}),console.error(l),a){let y=a.split(`
|
|
32
|
+
`);for(let p of y)if(p.trim()&&!p.includes(s))console.error(this.formatConsoleMessage({timestamp:r,message:$e.gray(` ${p}`),level:e,showTimestamp:!1}))}break}}else if(!ke()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${s}`),a)console.error(a)}if(!this.shouldLog(e))return;let c=`${o} ${this.environment}.${e.toUpperCase()}: ${s}
|
|
79
33
|
`;if(a)c+=`${a}
|
|
80
|
-
`;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(e){let t=performance.now();if(this.fancy&&!
|
|
81
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.fancy&&!
|
|
82
|
-
`),
|
|
83
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(
|
|
84
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(e,t=""){if(!this.enabled||!this.fancy||
|
|
85
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||xe()||!We.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(xe()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Xr(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 Jt(i)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${i}:`,s);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Qr(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function hi(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&pe(t[0])&&"id"in t[0]&&t[0].id===3&&pe(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(pe(t)&&pe(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(pe(e)&&"arr"in e&&Array.isArray(e.arr)&&pe(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&pe(t[0])&&pe(e[0])){let n=[...t];for(let i of e)if(pe(i)&&"name"in i){if(!n.find((s)=>pe(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(pe(i)&&"path"in i){if(!n.find((s)=>pe(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((s)=>$i(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(!pe(t)||!pe(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(pe(i)&&pe(r[n]))r[n]=hi(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&pe(i[0])&&pe(r[n][0])){let s=[...i];for(let o of r[n])if(pe(o)&&"name"in o){if(!s.find((a)=>pe(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(pe(o)&&"path"in o){if(!s.find((a)=>pe(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((a)=>$i(a,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function is(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:hi(e,t);if(Array.isArray(e))return r==="replace"?t:hi(e,t);if(!pe(t)||!pe(e))return t;let n={...e};for(let i of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,i))continue;let s=t[i],o=n[i];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")n[i]=s;else n[i]=hi(o,s);else if(pe(s)&&pe(o))n[i]=is(o,s,r);else n[i]=s}return n}function $i(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(!$i(e[r],t[r]))return!1;return!0}if(pe(e)&&pe(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(!$i(e[i],t[i]))return!1}return!0}return!1}function pe(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function fi(e,t,r="replace"){if(!ma(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 Iu(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function s(o,a=[]){let c={...o};for(let[f,u]of Object.entries(o)){let l=[...a,f],g=(b)=>b.replace(/([A-Z])/g,"_$1").toUpperCase(),p=`${n}_${l.map(g).join("_")}`,v=`${n}_${l.map((b)=>b.toUpperCase()).join("_")}`;if(r)Ge.info(`Checking environment variable ${p} for config ${e}.${l.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))c[f]=s(u,l);else{let b=Cr.env[p]||Cr.env[v];if(b!==void 0){if(r)Ge.info(`Using environment variable ${b?p:v} for config ${e}.${l.join(".")}`);if(typeof u==="number")c[f]=Number(b);else if(typeof u==="boolean")c[f]=b.toLowerCase()==="true";else if(Array.isArray(u))try{let w=JSON.parse(b);if(Array.isArray(w))c[f]=w;else c[f]=b.split(",").map((T)=>T.trim())}catch{c[f]=b.split(",").map((w)=>w.trim())}else c[f]=b}}}return c}return s(i)}async function Fu({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:s=!1,checkEnv:o=!0,arrayStrategy:a="replace"}){let c=o&&typeof i==="object"&&i!==null&&!Array.isArray(i)?Iu(e,i,s):i,f=r||Cr.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)Ge.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${f}`);let l=[e,`.${e}`].filter(Boolean),g=[`${e}.config`,`.${e}.config`].filter(Boolean),p=t?[t,`.${t}`]:[],v=t?[`${t}.config`,`.${t}.config`]:[],b=Array.from(new Set([f,ze(f,"config"),ze(f,".config"),n?ze(f,n):void 0].filter(Boolean)));for(let w of b){if(s)Ge.info(`Searching for configuration in: ${w}`);let T=[ze(f,"config"),ze(f,".config")].concat(n?[ze(f,n)]:[]).includes(w)?[...l,...g,...p,...v]:[...g,...l,...v,...p];for(let k of T)for(let R of u){let I=ze(w,`${k}${R}`),_=await fi(I,c,a);if(_!==null){if(s)Ge.success(`Configuration loaded from: ${I}`);return _}}}if(e){let w=ze(bn(),".config",e),T=["config",`${e}.config`];if(t)T.push(`${t}.config`);if(s)Ge.info(`Checking user config directory: ${w}`);for(let k of T)for(let R of u){let I=ze(w,`${k}${R}`),_=await fi(I,c,a);if(_!==null){if(s)Ge.success(`Configuration loaded from user config directory: ${I}`);return _}}}if(e){let w=ze(bn(),".config"),T=[`.${e}.config`];if(t)T.push(`.${t}.config`);if(s)Ge.info(`Checking user config directory for dotfile configs: ${w}`);for(let k of T)for(let R of u){let I=ze(w,`${k}${R}`),_=await fi(I,c,a);if(_!==null){if(s)Ge.success(`Configuration loaded from user config directory dotfile: ${I}`);return _}}}if(e){let w=bn(),T=[`.${e}.config`,`.${e}`];if(t)T.push(`.${t}.config`),T.push(`.${t}`);if(s)Ge.info(`Checking user home directory for dotfile configs: ${w}`);for(let k of T)for(let R of u){let I=ze(w,`${k}${R}`),_=await fi(I,c,a);if(_!==null){if(s)Ge.success(`Configuration loaded from user home directory: ${I}`);return _}}}try{let w=ze(f,"package.json");if(ma(w)){let T=await import(w),k=T[e];if(!k&&t){if(k=T[t],k&&s)Ge.success(`Using alias "${t}" configuration from package.json`)}if(k&&typeof k==="object"&&!Array.isArray(k))try{if(s)Ge.success(`Configuration loaded from package.json: ${k===T[e]?e:t}`);return is(c,k,a)}catch(R){if(s)Ge.warn("Failed to merge package.json config:",R)}}}catch(w){if(s)Ge.warn("Failed to load package.json:",w)}if(s)Ge.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function Nu(e,t={}){let r=yi.cwd();while(r.includes("storage"))r=Do(r,"..");let n=Do(r,e||"");if(t?.relative)return Gf(yi.cwd(),n);return n}async function Lu(){try{let e=await Fu({name:"clarity",alias:"logging",defaultConfig:pi,cwd:yi.cwd()});return{...pi,...e||{}}}catch{return pi}}function De(){if(Ct.env.NODE_ENV==="test"||Ct.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Wu(){if(Ct.env.NODE_ENV==="test"||Ct.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Ct<"u"){let e=Ct.type;if(e==="renderer"||e==="worker")return!1;return!!(Ct.versions&&(Ct.versions.node||Ct.versions.bun))}return!1}class va{async format(e){let t=await Wu(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Qt.pid,hostname:t(),environment:Qt.env.NODE_ENV||"development",platform:Qt.platform,version:Qt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Qt.env.NODE_ENV||Qt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ai{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...Kn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new va,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??de.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...gi,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...gi};return{...gi,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Kn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!De()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,i=0,s=3,o=1000;while(i<s)try{try{try{await eu(this.config.logDirectory,Uo.F_OK|Uo.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await tu(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:mt.from(e);try{if(!ei(this.currentLogFile))await Rn(this.currentLogFile,"",{mode:420});if(n=Vo(this.currentLogFile,"a",420),Qf(n,a,{flag:"a"}),_o(n),n!==void 0)Pn(n),n=void 0;if((await Zt(this.currentLogFile)).size===0){if(await Rn(this.currentLogFile,a,{flag:"w",mode:420}),(await Zt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(i<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let l=o*2**i;await new Promise((g)=>setTimeout(g,l)),i++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(n!==void 0)try{Pn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===s-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}i++;let c=o*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Xt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Xt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Xt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(De())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,o],[,a])=>a.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,i);if(n.length>s)for(let[o]of n.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return 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=Yf("aes-256-gcm",t,r),i=mt.isBuffer(e)?e:mt.from(e,"utf8"),s=n.update(i),o=n.final(),a=s.length+o.length,c=n.getAuthTag(),f=mt.allocUnsafe(16+a+16);return r.copy(f,0),s.copy(f,16),o.copy(f,16+s.length),c.copy(f,16+a),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=zo(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(mt.from(mt.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(De())return;if(!this.shouldWriteToFile())return;let e=await Zt(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await ti(this.config.logDirectory),s=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${o}`;if(await Zt(r).catch(()=>null))try{if(await Ko(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await ri(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await Rn(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await Zt(r).catch(()=>null))await Ko(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await ti(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await ri(Xt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=jo(e),n=Xf(t),i=zo();await nu(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),ei(this.currentLogFile))try{let e=Vo(this.currentLogFile,"r+");_o(e),Pn(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!De()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await ti(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await ri(Xt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?re.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||De())return!1;let e=typeof de.env.NO_COLOR<"u",t=de.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof de.stderr<"u"&&de.stderr.isTTY||typeof de.stdout<"u"&&de.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,a=(p)=>p.replace(this.ANSI_PATTERN,"");if(!this.fancy){let p=[];if(o)p.push(t);if(s==="warning")p.push("WARN");else if(s==="error")p.push("ERROR");else if(r)p.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)p.push(n.replace(/[[\]]/g,""));return p.push(i),p.join(" ")}let c=de.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${i}`;else if(s==="info"||s==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${re.cyan(i)}`;if(!o)return f.trim();let u=a(f).trim().length,l=a(t).length,g=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(g)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let a=Number.parseInt(o,10);return a<t[0].length?String(t[0][a]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let a=t[n++];switch(o){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=re.underline(re.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(o)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${a}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>re.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>re.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>re.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>re.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>re.strikethrough(n)),t}supportsHyperlinks(){if(De())return!1;let e=de.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=de.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(ru(t)||t.startsWith("./")||t.startsWith("../"))t=iu(t);else return null;return ei(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,a;if(t instanceof Error)o=t.message,a=t.stack;else o=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let l=this.options.showIcons===!1?"":Oa[e],g=this.options.showTags!==!1&&this.name?re.gray(this.formatTag(this.name)):"",p;switch(e){case"debug":p=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:re.gray(c),level:e}),console.error(p);break;case"info":p=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.warn(p);break;case"success":p=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:re.green(c),level:e}),console.error(p);break;case"warning":p=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.warn(p);break;case"error":if(p=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.error(p),a){let v=a.split(`
|
|
86
|
-
`);for(let
|
|
34
|
+
`;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(e){let t=performance.now();if(this.fancy&&!ke()){let i=this.options.showTags!==!1&&this.name?$e.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:$e.blue("\u25D0"),tag:i,message:`${$e.cyan(e)}...`}))}return async(i)=>{if(!this.enabled)return;let n=performance.now(),r=Math.round(n-t),o=`${e} completed in ${r}ms`,s=new Date,a=this.formatConsoleTimestamp(s),c=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(i)c+=` ${JSON.stringify(i)}`;if(c+=`
|
|
35
|
+
`,c=c.replace(this.ANSI_PATTERN,""),this.fancy&&!ke()){let f=this.options.showTags!==!1&&this.name?$e.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:$e.green("\u2713"),tag:f,message:`${o}${i?` ${JSON.stringify(i)}`:""}`}))}else if(!ke())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}`,i=new dr(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(i),i}createReadStream(){if(ke())throw Error("createReadStream is not supported in browser environments");if(!un(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return as(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let i=this.keys.get(this.currentKeyId);try{let n=Rt.isBuffer(e)?e:Rt.from(e,"base64"),r=n.slice(0,16),o=n.slice(-16),s=n.slice(16,-16),a=tf("aes-256-gcm",i,r);return a.setAuthTag(o),Rt.concat([a.update(s),a.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ke()}isServerMode(){return!ke()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,i=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!ke()){let o=e.split(`
|
|
36
|
+
`),s=Math.max(...o.map((u)=>u.length))+2,a=`\u250C${"\u2500".repeat(s)}\u2510`,c=`\u2514${"\u2500".repeat(s)}\u2518`,f=o.map((u)=>{let l=" ".repeat(s-u.length-2);return`\u2502 ${u}${l} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:i,message:$e.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:i,message:$e.cyan(a)})),f.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:i,message:$e.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:i,message:$e.cyan(c),showTimestamp:!1}))}else if(!ke())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let r=`${n} ${this.environment}.INFO: [BOX] ${e}
|
|
37
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(r)}async prompt(e){if(ke())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${$e.cyan("?")} ${e} (y/n) `);let i=(n)=>{let r=n.toString().trim().toLowerCase();_e.stdin.removeListener("data",i);try{if(typeof _e.stdin.setRawMode==="function")_e.stdin.setRawMode(!1)}catch{}_e.stdin.pause(),console.error(""),t(r==="y"||r==="yes")};try{if(typeof _e.stdin.setRawMode==="function")_e.stdin.setRawMode(!0)}catch{}_e.stdin.resume(),_e.stdin.once("data",i)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let i=e;if(t&&t.length>0){let r=/%([sdijfo%])/g,o=0;if(i=e.replace(r,(s,a)=>{if(a==="%")return"%";if(o>=t.length)return s;let c=t[o++];switch(a){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}}),o<t.length)i+=` ${t.slice(o).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`}if(this.fancy&&!ke()){let r=this.options.showTags!==!1&&this.name?$e.gray(this.formatTag(this.name)):"",o=$e.blue("\u25D0");console.error(`${o} ${r} ${$e.cyan(i)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
38
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(e,t=""){if(!this.enabled||!this.fancy||ke()||e<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let i=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:i,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(n,r)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||ke())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,n)),r!==void 0)this.activeProgressBar.message=r;let o=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,o)},finish:(n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||ke())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,r="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||ke())return;_e.stdout.write(`${"\r".padEnd(_e.stdout.columns||80)}\r`),this.log(r,n),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||ke()||!_e.stdout.isTTY)return;let i=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*i/100),r=e.barLength-n,o=$e.green("\u2501".repeat(n)),s=$e.gray("\u2501".repeat(r)),a=`[${o}${s}]`,c=`${i}%`.padStart(4),f=e.message?` ${e.message}`:"",u=t||i===100?$e.green("\u2713"):$e.blue("\u25B6"),l=this.options.showTags!==!1&&this.name?` ${$e.gray(this.formatTag(this.name))}`:"",y=`\r${u}${l} ${a} ${c}${f}`,p=_e.stdout.columns||80,w=" ".repeat(Math.max(0,p-y.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${y}${w}`,_e.stdout.write(e.lastRenderedLine),t)_e.stdout.write(`
|
|
39
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||ke()||!_e.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(ke()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await _i(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=Yt(this.config.logDirectory,n);if(e.before)try{if((await qt(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 Vi(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 ir(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Ce(t[0])&&"id"in t[0]&&t[0].id===3&&Ce(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Ce(t)&&Ce(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(Ce(e)&&"arr"in e&&Array.isArray(e.arr)&&Ce(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Ce(t[0])&&Ce(e[0])){let n=[...t];for(let r of e)if(Ce(r)&&"name"in r){if(!n.find((o)=>Ce(o)&&("name"in o)&&o.name===r.name))n.push(r)}else if(Ce(r)&&"path"in r){if(!n.find((o)=>Ce(o)&&("path"in o)&&o.path===r.path))n.push(r)}else if(!n.some((o)=>mr(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(!Ce(t)||!Ce(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(Ce(r)&&Ce(i[n]))i[n]=ir(i[n],r);else if(Array.isArray(r)&&Array.isArray(i[n]))if(r.length>0&&i[n].length>0&&Ce(r[0])&&Ce(i[n][0])){let o=[...r];for(let s of i[n])if(Ce(s)&&"name"in s){if(!o.find((a)=>Ce(a)&&("name"in a)&&a.name===s.name))o.push(s)}else if(Ce(s)&&"path"in s){if(!o.find((a)=>Ce(a)&&("path"in a)&&a.path===s.path))o.push(s)}else if(!o.some((a)=>mr(a,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 Vn(e,t,i="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return i==="replace"?t:ir(e,t);if(Array.isArray(e))return i==="replace"?t:ir(e,t);if(!Ce(t)||!Ce(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]=ir(s,o);else if(Ce(o)&&Ce(s))n[r]=Vn(s,o,i);else n[r]=o}return n}function mr(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(!mr(e[i],t[i]))return!1;return!0}if(Ce(e)&&Ce(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(!mr(e[r],t[r]))return!1}return!0}return!1}function Ce(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function er(e,t,i="replace"){if(!Gs(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 Vn(t,r,i)}catch{return null}}catch{return null}}function Hf(e,t,i=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),r={...t};function o(s,a=[]){let c={...s};for(let[f,u]of Object.entries(s)){let l=[...a,f],y=(S)=>S.replace(/([A-Z])/g,"_$1").toUpperCase(),p=`${n}_${l.map(y).join("_")}`,w=`${n}_${l.map((S)=>S.toUpperCase()).join("_")}`;if(i)Ue.info(`Checking environment variable ${p} for config ${e}.${l.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))c[f]=o(u,l);else{let S=hi.env[p]||hi.env[w];if(S!==void 0){if(i)Ue.info(`Using environment variable ${S?p:w} for config ${e}.${l.join(".")}`);if(typeof u==="number")c[f]=Number(S);else if(typeof u==="boolean")c[f]=S.toLowerCase()==="true";else if(Array.isArray(u))try{let x=JSON.parse(S);if(Array.isArray(x))c[f]=x;else c[f]=S.split(",").map((E)=>E.trim())}catch{c[f]=S.split(",").map((x)=>x.trim())}else c[f]=S}}}return c}return o(r)}async function zf({name:e="",alias:t,cwd:i,configDir:n,defaultConfig:r,verbose:o=!1,checkEnv:s=!0,arrayStrategy:a="replace"}){let c=s&&typeof r==="object"&&r!==null&&!Array.isArray(r)?Hf(e,r,o):r,f=i||hi.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(o)Ue.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${f}`);let l=[e,`.${e}`].filter(Boolean),y=[`${e}.config`,`.${e}.config`].filter(Boolean),p=t?[t,`.${t}`]:[],w=t?[`${t}.config`,`.${t}.config`]:[],S=Array.from(new Set([f,ze(f,"config"),ze(f,".config"),n?ze(f,n):void 0].filter(Boolean)));for(let x of S){if(o)Ue.info(`Searching for configuration in: ${x}`);let E=[ze(f,"config"),ze(f,".config")].concat(n?[ze(f,n)]:[]).includes(x)?[...l,...y,...p,...w]:[...y,...l,...w,...p];for(let k of E)for(let I of u){let M=ze(x,`${k}${I}`),J=await er(M,c,a);if(J!==null){if(o)Ue.success(`Configuration loaded from: ${M}`);return J}}}if(e){let x=ze(ln(),".config",e),E=["config",`${e}.config`];if(t)E.push(`${t}.config`);if(o)Ue.info(`Checking user config directory: ${x}`);for(let k of E)for(let I of u){let M=ze(x,`${k}${I}`),J=await er(M,c,a);if(J!==null){if(o)Ue.success(`Configuration loaded from user config directory: ${M}`);return J}}}if(e){let x=ze(ln(),".config"),E=[`.${e}.config`];if(t)E.push(`.${t}.config`);if(o)Ue.info(`Checking user config directory for dotfile configs: ${x}`);for(let k of E)for(let I of u){let M=ze(x,`${k}${I}`),J=await er(M,c,a);if(J!==null){if(o)Ue.success(`Configuration loaded from user config directory dotfile: ${M}`);return J}}}if(e){let x=ln(),E=[`.${e}.config`,`.${e}`];if(t)E.push(`.${t}.config`),E.push(`.${t}`);if(o)Ue.info(`Checking user home directory for dotfile configs: ${x}`);for(let k of E)for(let I of u){let M=ze(x,`${k}${I}`),J=await er(M,c,a);if(J!==null){if(o)Ue.success(`Configuration loaded from user home directory: ${M}`);return J}}}try{let x=ze(f,"package.json");if(Gs(x)){let E=await import(x),k=E[e];if(!k&&t){if(k=E[t],k&&o)Ue.success(`Using alias "${t}" configuration from package.json`)}if(k&&typeof k==="object"&&!Array.isArray(k))try{if(o)Ue.success(`Configuration loaded from package.json: ${k===E[e]?e:t}`);return Vn(c,k,a)}catch(I){if(o)Ue.warn("Failed to merge package.json config:",I)}}}catch(x){if(o)Ue.warn("Failed to load package.json:",x)}if(o)Ue.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function Jf(e,t={}){let i=ar.cwd();while(i.includes("storage"))i=os(i,"..");let n=os(i,e||"");if(t?.relative)return Zc(ar.cwd(),n);return n}async function qf(){try{let e=await zf({name:"clarity",alias:"logging",defaultConfig:or,cwd:ar.cwd()});return{...or,...e||{}}}catch{return or}}function Ne(){if(wt.env.NODE_ENV==="test"||wt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Yf(){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 Hs{async format(e){let t=await Yf(),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:ei.pid,hostname:t(),environment:ei.env.NODE_ENV||"development",platform:ei.platform,version:ei.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ei.env.NODE_ENV||ei.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class pr{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={...kn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Hs,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??ge.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let 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{...sr,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...sr};return{...sr,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:kn.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!Ne()&&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 hf(this.config.logDirectory,gs.F_OK|gs.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await df(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:pt.from(e);try{if(!Ui(this.currentLogFile))await pn(this.currentLogFile,"",{mode:420});if(n=ps(this.currentLogFile,"a",420),uf(n,a,{flag:"a"}),ms(n),n!==void 0)mn(n),n=void 0;if((await Xt(this.currentLogFile)).size===0){if(await pn(this.currentLogFile,a,{flag:"w",mode:420}),(await Xt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(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 l=s*2**r;await new Promise((y)=>setTimeout(y,l)),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{mn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(r===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}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 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(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,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],[,a])=>a.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 dn(16).toString("hex")}generateKey(){return dn(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=dn(16),n=lf("aes-256-gcm",t,i),r=pt.isBuffer(e)?e:pt.from(e,"utf8"),o=n.update(r),s=n.final(),a=o.length+s.length,c=n.getAuthTag(),f=pt.allocUnsafe(16+a+16);return i.copy(f,0),o.copy(f,16),s.copy(f,16+o.length),c.copy(f,16+a),{encrypted:f,iv:i}}async compressData(e){return new Promise((t,i)=>{let n=Cs(),r=[];n.on("data",(o)=>r.push(o)),n.on("end",()=>t(pt.from(pt.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(Ne())return;if(!this.shouldWriteToFile())return;let e=await Xt(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let i=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let r=await Ki(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,a=`${i}.${s}`;if(await Xt(i).catch(()=>null))try{if(await ys(i,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await Hi(a)}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 pn(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 Xt(i).catch(()=>null))await ys(i,o)}if(this.currentLogFile=n,t.maxFiles){let r=(await Ki(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of r.slice(t.maxFiles))await Hi(Qt(this.config.logDirectory,o))}}}async compressLogFile(e,t){let i=ds(e),n=ff(t),r=Cs();await gf(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()})),Ui(this.currentLogFile))try{let e=ps(this.currentLogFile,"r+");ms(e),mn(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Ne()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Ki(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Hi(Qt(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()?ae.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Ne())return!1;let e=typeof ge.env.NO_COLOR<"u",t=ge.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof ge.stderr<"u"&&ge.stderr.isTTY||typeof ge.stdout<"u"&&ge.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:i="",tag:n="",message:r,level:o,showTimestamp:s=!0}=e,a=(p)=>p.replace(this.ANSI_PATTERN,"");if(!this.fancy){let p=[];if(s)p.push(t);if(o==="warning")p.push("WARN");else if(o==="error")p.push("ERROR");else if(i)p.push(i.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)p.push(n.replace(/[[\]]/g,""));return p.push(r),p.join(" ")}let c=ge.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} ${ae.cyan(r)}`;if(!s)return f.trim();let u=a(f).trim().length,l=a(t).length,y=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(y)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let a=Number.parseInt(s,10);return a<t[0].length?String(t[0][a]):o});let i=/%([sdijfo%])/g,n=0,r=e.replace(i,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let a=t[n++];switch(s){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return o}});if(n<t.length)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=ae.underline(ae.blue(n)),s=this.toAbsoluteFilePath(r);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(s)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${a}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${r}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),t=t.replace(/`([^`]+)`/g,(i,n)=>ae.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(i,n)=>ae.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(i,n)=>ae.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(i,n)=>ae.italic(n)),t=t.replace(/~([^~]+)~/g,(i,n)=>ae.strikethrough(n)),t}supportsHyperlinks(){if(Ne())return!1;let e=ge.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let i=ge.env.HOME||"";if(i)t=t.replace(/^~(?=$|\/)/,i)}if(mf(t)||t.startsWith("./")||t.startsWith("../"))t=pf(t);else return null;return Ui(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,a;if(t instanceof Error)s=t.message,a=t.stack;else s=this.formatMessage(t,i);let{consoleText:c,fileText:f}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let l=this.options.showIcons===!1?"":ia[e],y=this.options.showTags!==!1&&this.name?ae.gray(this.formatTag(this.name)):"",p;switch(e){case"debug":p=this.formatConsoleMessage({timestamp:r,icon:l,tag:y,message:ae.gray(c),level:e}),console.error(p);break;case"info":p=this.formatConsoleMessage({timestamp:r,icon:l,tag:y,message:c,level:e}),console.warn(p);break;case"success":p=this.formatConsoleMessage({timestamp:r,icon:l,tag:y,message:ae.green(c),level:e}),console.error(p);break;case"warning":p=this.formatConsoleMessage({timestamp:r,icon:l,tag:y,message:c,level:e}),console.warn(p);break;case"error":if(p=this.formatConsoleMessage({timestamp:r,icon:l,tag:y,message:c,level:e}),console.error(p),a){let w=a.split(`
|
|
40
|
+
`);for(let S of w)if(S.trim()&&!S.includes(s))console.error(this.formatConsoleMessage({timestamp:r,message:ae.gray(` ${S}`),level:e,showTimestamp:!1}))}break}}else if(!Ne()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${s}`),a)console.error(a)}if(!this.shouldLog(e))return;let u=`${o} ${this.environment}.${e.toUpperCase()}: ${f}
|
|
87
41
|
`;if(a)u+=`${a}
|
|
88
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let
|
|
89
|
-
`);if(this[
|
|
90
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?
|
|
91
|
-
`),c=Math.max(...a.map((
|
|
92
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
93
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
94
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||
|
|
42
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let i={update:(r,o)=>{},finish:(r)=>{},interrupt:(r,o)=>{}};if(!this.enabled)return i;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!Ne()&&ge.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(r,o)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,r),this.activeProgressBar.total),o!==void 0)this.activeProgressBar.message=o;if(this.shouldStyleConsole()&&!Ne()&&ge.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(r)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,r)},interrupt:(r,o="info")=>{if(!Ne()&&ge.stdout.isTTY)ge.stdout.write(`
|
|
43
|
+
`);if(this[o==="warning"?"warn":o](r),this.activeProgressBar&&this.shouldStyleConsole()&&!Ne()&&ge.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let i=this.options.showTags!==!1&&this.name?ae.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":ae.blue("\u25D0"),tag:i,message:`${ae.cyan(e)}...`}))}return async(i)=>{if(!this.enabled)return;let n=performance.now(),r=Math.round(n-t),o=`${e} completed in ${r}ms`,s=new Date,a=this.formatConsoleTimestamp(s),c=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(i)c+=` ${JSON.stringify(i)}`;if(c+=`
|
|
44
|
+
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?ae.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":ae.green("\u2713"),tag:f,message:`${o}${i?` ${JSON.stringify(i)}`:""}`}))}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}`,i=new pr(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(i),i}createReadStream(){if(Ne())throw Error("createReadStream is not supported in browser environments");if(!Ui(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ds(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let i=this.keys.get(this.currentKeyId);try{let n=pt.isBuffer(e)?e:pt.from(e,"base64"),r=n.subarray(0,16),o=n.subarray(n.length-16),s=n.subarray(16,n.length-16),a=cf("aes-256-gcm",i,r);a.setAuthTag(o);let c=a.update(s),f=a.final(),u=c.length+f.length,l=pt.allocUnsafe(u);return c.copy(l,0),f.copy(l,c.length),l.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return 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,i=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:r,fileText:o}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let a=r.split(`
|
|
45
|
+
`),c=Math.max(...a.map((y)=>y.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,l=a.map((y)=>this.formatConsoleMessage({timestamp:i,message:ae.cyan(y),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:i,message:ae.cyan(f),showTimestamp:!1})),l.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:i,message:ae.cyan(u),showTimestamp:!1}))}else if(!Ne())console.error(`${n} ${this.environment}.INFO: [BOX] ${o}`);let s=`${n} ${this.environment}.INFO: [BOX] ${o}
|
|
46
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(e){if(Ne())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${ae.cyan("?")} ${e} (y/n) `);let i=(n)=>{let r=n.toString().trim().toLowerCase();ge.stdin.removeListener("data",i);try{if(typeof ge.stdin.setRawMode==="function")ge.stdin.setRawMode(!1)}catch{}ge.stdin.pause(),console.error(""),t(r==="y"||r==="yes")};try{if(typeof ge.stdin.setRawMode==="function")ge.stdin.setRawMode(!0)}catch{}ge.stdin.resume(),ge.stdin.once("data",i)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let i=e;if(t&&t.length>0){let s=/%([sdijfo%])/g,a=0;if(i=e.replace(s,(c,f)=>{if(f==="%")return"%";if(a>=t.length)return c;let u=t[a++];switch(f){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return c}}),a<t.length)i+=` ${t.slice(a).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}let{consoleText:n,fileText:r}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?ae.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${ae.blue("\u25D0")} `;console.error(`${a}${s} ${ae.cyan(n)}`)}let o=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
47
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!ge.stdout.isTTY)return;let i=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*i/100),r=e.barLength-n,o=ae.green("\u2501".repeat(n)),s=ae.gray("\u2501".repeat(r)),a=`[${o}${s}]`,c=`${i}%`.padStart(4),f=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||i===100?ae.green("\u2713"):ae.blue("\u25B6"),l=this.options.showTags!==!1&&this.name?` ${ae.gray(this.formatTag(this.name))}`:"",y=`\r${u}${l} ${a} ${c}${f}`,p=ge.stdout.columns||80,w=" ".repeat(Math.max(0,p-y.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${y}${w}`,ge.stdout.write(e.lastRenderedLine),t)ge.stdout.write(`
|
|
48
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ne()||!ge.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Ne()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ki(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=Qt(this.config.logDirectory,n);if(e.before)try{if((await Xt(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 Hi(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)}}}async function zs(e,t={}){let{maxRetries:i=3,retryDelay:n=1000,isRetryable:r=()=>!0,fallback:o}=t,s=Error("Unknown error occurred");for(let a=0;a<=i;a++)try{return await e()}catch(c){if(s=c instanceof Error?c:Error(String(c)),a===i||!r(s))break;if(n>0)await new Promise((f)=>setTimeout(f,n))}if(o!==void 0)return o;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}function Js(e){return e instanceof et}function Zf(e){return e instanceof gr}function Xf(e){if(Js(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 br{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,i={}){let{prefix:n,useCamelCase:r=!0,useBackwardCompatibility:o=!0,customParsers:s={},verbose:a=!1,trackPerformance:c=!0}=i,f=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),l={...t};return this.processObject(l,[],u,{useCamelCase:r,useBackwardCompatibility:o,customParsers:s,verbose:a,configName:e}),{config:l,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return pi.track("applyEnvironmentVariables",f,{configName:e});return f()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,i,n){for(let[r,o]of Object.entries(e)){let s=[...t,r],a=s.map((u)=>this.formatEnvKey(u,n.useCamelCase)),c=`${i}_${a.join("_")}`,f=n.useBackwardCompatibility?`${i}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.processObject(o,s,i,n);else{let u=zi.env[c]||(f?zi.env[f]:void 0);if(u!==void 0){if(n.verbose){let l=zi.env[c]?c:f}try{e[r]=this.parseEnvironmentValue(u,typeof o,c,n.customParsers,n.configName)}catch(l){if(l instanceof yr)throw l;throw Pt.envVar(c,u,typeof o,n.configName)}}}}}parseEnvironmentValue(e,t,i,n,r){for(let[o,s]of Object.entries(n))try{return s(e)}catch{continue}for(let o of this.defaultParsers)if(o.canParse(e,t))try{return o.parse(e)}catch{throw Pt.envVar(i,e,`${t} (via ${o.name} parser)`,r)}return e}getEnvironmentVariables(e){let t={},i=e.toUpperCase();for(let[n,r]of Object.entries(zi.env))if(n.startsWith(i)&&r!==void 0)t[n]=r;return t}validateEnvironmentVariable(e,t,i){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(i)try{this.parseEnvironmentValue(e,t,i,{})}catch(r){n.push(`Cannot parse value "${t}" as ${i}: ${r}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,i={}){let{prefix:n,format:r="text"}=i,o=n||this.generateEnvPrefix(e),s=[];switch(this.extractEnvVarInfo(t,[],o,s),r){case"markdown":return this.formatAsMarkdown(s,e);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,e)}}extractEnvVarInfo(e,t,i,n){for(let[r,o]of Object.entries(e)){let s=[...t,r],a=`${i}_${s.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.extractEnvVarInfo(o,s,i,n);else n.push({key:a,type:Array.isArray(o)?"array":typeof o,description:`Configuration for ${s.join(".")}`,example:this.generateExample(o)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let i=`Environment Variables for ${t}:
|
|
95
49
|
|
|
96
|
-
`;for(let n of e)
|
|
97
|
-
`,
|
|
98
|
-
`,
|
|
99
|
-
`,
|
|
50
|
+
`;for(let n of e)i+=`${n.key}
|
|
51
|
+
`,i+=` Type: ${n.type}
|
|
52
|
+
`,i+=` Description: ${n.description}
|
|
53
|
+
`,i+=` Example: ${n.example}
|
|
100
54
|
|
|
101
|
-
`;return
|
|
55
|
+
`;return i}formatAsMarkdown(e,t){let i=`# Environment Variables for ${t}
|
|
102
56
|
|
|
103
|
-
`;
|
|
104
|
-
`,
|
|
105
|
-
`;for(let n of e)
|
|
106
|
-
`;return r}}function ju(e,t){let r=Ta("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function Sa(e,t,r={}){return $a(e,t,r,new WeakMap)}function $a(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let a=o(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return Aa(e,t,i,n);if(!it(t)||!it(e))return t;return Ku(e,t,r,n)}function Aa(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 _u(e,t);case"smart":return Vu(e,t,n);default:return t}return t}function _u(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Vn(i,n)))r.push(n);return r}function Vu(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(it(t[0])&&it(e[0]))return Uu(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 Uu(e,t,r){let n=[...t];for(let i of e){if(!it(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let a of s)if(a in i){if(n.find((c)=>it(c)&&(a in c)&&c[a]===i[a])){o=!0;break}}if(!o)n.push(i)}return n}function Ku(e,t,r,n){let i=t;if(it(i)&&n.has(i))return n.get(i);let s={...e};if(it(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let a=i[o],c=s[o];if(r.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){s[o]=a;continue}if(it(a)&&it(c))s[o]=$a(c,a,r,n);else if(Array.isArray(a)||Array.isArray(c))s[o]=Aa(c,a,r.arrayMergeMode||"smart",n);else s[o]=a}return s}function ns(e,t,r="replace"){return Sa(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(it(e)&&it(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 it(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Di{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:o=!0,verbose:a=!1}=r;if(i){let f=ir.getWithFileCheck("file",e);if(f){if(a)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!ni(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,g="default"in u,p=Object.keys(u).length>0;if(!g&&!p)throw new wr(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new wr(e,Error("Configuration must export a valid object"),"unknown");let v={config:ns(t,l,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)ir.setWithFileCheck("file",v,e,s);return v}catch(f){throw f instanceof Error?xt.configLoad(e,f):xt.configLoad(e,Error(String(f)))}};if(o)return Er.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(On(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 Ea(async()=>ni(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!ni(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let a=On(e,`${s}${o}`);if(await this.checkFileAccess(a))n.push(a)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let a=On(e,o);if(await this.checkFileAccess(a))n.push(a)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!ni(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class ss{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:a=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],g={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,g);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],g);else return this.validateWithJSONSchema(e,t,g)}catch(p){return u.push({path:"",message:`Validation failed: ${p}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(a)return await Er.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!su(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,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(o)){if(n.push({path:r,message:`Expected type ${a.join(" or ")}, got ${o}`,expected:a.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let a=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,a,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let a of t.required)if(!(a in o)){if(n.push({path:r?`${r}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[a,c]of Object.entries(t.properties))if(a in o){let f=r?`${r}.${a}`:a;if(this.validateObjectAgainstSchema(o[a],c,f,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(o))if(!a.has(c))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),a=this.validateWithRule(o,s,s.path);if(n.push(...a),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,o]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Ma},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class os{fileLoader=new Di;envProcessor=new Mi;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 a;try{a=await this.loadConfigurationStrategies(o,!0,r)}catch(c){let f=o.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),l=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),g=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(g||u))throw c;if(l&&(!f||!g))a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(i||s)await this.validateConfiguration(a.config,i,s,o.name);if(r?.enabled&&a)this.cacheResult(o.name||"",a,r,o);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)ot.warn(`Slow configuration loading detected: ${c.duration}ms for ${o.name}`);a.metrics=c}return a}catch(a){let c=Date.now()-t;throw ot.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:a,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=s||Mt.cwd(),g=[],p=await this.loadLocalConfiguration(n,i,l,o,a,f,u,c,r);if(p)return g.push(...this.getLocalSearchPaths(n,i,l,o)),this.finalizeResult(p,g,c,n,u);let v=await this.loadHomeConfiguration(n,i,a,f,u,c);if(v)return g.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(v,g,c,n,u);let b=await this.loadPackageJsonConfiguration(n,i,l,a,f,u,c);if(b)return g.push(He(l,"package.json")),this.finalizeResult(b,g,c,n,u);if(g.push(...this.getAllSearchPaths(n,i,l,o)),t)throw xt.configNotFound(n,g,i);return{...await this.applyEnvironmentVariables(n,a,c,u),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,a,c){let f=a?yr(e,i,o):i,u=this.getLocalDirectories(r,n);for(let l of u){if(o)ot.info(`Searching for configuration in: ${l}`);let g=this.fileLoader.generateConfigPaths(e,l,t),p=await this.fileLoader.tryLoadFromPaths(g,f,{arrayStrategy:s,verbose:o,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(p){if(o)ot.success(`Configuration loaded from: ${p.source.path}`);return p}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?yr(e,r,i):r,a=[He(Ht(),".config",e),He(Ht(),".config"),Ht()];for(let c of a){if(i)ot.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)ot.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let a=o?yr(e,n,s):n;try{let c=He(r,"package.json");if(!jn(c))return null;let f=await import(c),u=f[e],l=e;if(!u&&t)u=f[t],l=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)ot.success(`Configuration loaded from package.json: ${l}`);return{config:ns(a,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)ot.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:yr(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(i.length>0)throw xt.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return ir.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);ir.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,He(e,"config"),He(e,".config"),t?He(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(He(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let o of i)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[He(Ht(),".config",e),He(Ht(),".config"),Ht()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function ta(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 zu(e){return vt.loadConfig({...e,__strictErrorHandling:!0})}async function xa(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await vt.loadConfig(e);else n=await vt.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)ot.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 vt.applyEnvironmentVariables(o.name||"",t,!0,o.verbose||!1))?.config??t;return t}}async function Hu(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(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&ta(r)))return(await vt.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await vt.loadConfig({...e,cwd:e.cwd||Mt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&ta(t)))return(await vt.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Ju(e,t,r="replace"){let n=new Di;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function yr(e,t,r=!1){let n=new Mi,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,a=[]){let c={...o};for(let[f,u]of Object.entries(o)){let l=[...a,f],g=[`${i}_${l.join("_").toUpperCase()}`,`${i}_${l.map((b)=>b.toUpperCase()).join("")}`,`${i}_${l.map((b)=>b.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],p,v;for(let b of g)if(p=Mt.env[b],p!==void 0){v=b;break}if(p!==void 0&&v)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(p.toLowerCase());else if(typeof u==="number"){let b=Number(p);if(!Number.isNaN(b))c[f]=b}else if(Array.isArray(u))try{c[f]=JSON.parse(p)}catch{c[f]=p.split(",").map((b)=>b.trim())}else c[f]=p;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,l)}return c}return s(t)}function qu(e){let t=He(Mt.cwd(),e.configDir),r=He(Mt.cwd(),e.generatedDir),n=He(r,"config-types.ts");if(!jn(Mo(n)))Nf(Mo(n),{recursive:!0,mode:511});let i=jn(t)?Lf(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${$h}
|
|
107
|
-
export type ConfigNames = ${
|
|
108
|
-
`;
|
|
109
|
-
${
|
|
57
|
+
`;i+=`| Variable | Type | Description | Example |
|
|
58
|
+
`,i+=`|----------|------|-------------|----------|
|
|
59
|
+
`;for(let n of e)i+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
60
|
+
`;return i}}function Qf(e,t){let i=Qs("process");if(typeof i>"u"||!i.env)return t;let n=i.env[e];return n!==void 0?n:t}function qs(e,t,i={}){return Ys(e,t,i,new WeakMap)}function Ys(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 a=s(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return Zs(e,t,r,n);if(!rt(t)||!rt(e))return t;return ru(e,t,i,n)}function Zs(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 eu(e,t);case"smart":return tu(e,t,n);default:return t}return t}function eu(e,t){let i=[...t];for(let n of e)if(!i.some((r)=>Pn(r,n)))i.push(n);return i}function tu(e,t,i){if(t.length===0)return e;if(e.length===0)return t;if(rt(t[0])&&rt(e[0]))return iu(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 iu(e,t,i){let n=[...t];for(let r of e){if(!rt(r)){n.push(r);continue}let o=["id","name","key","path","type"],s=!1;for(let a of o)if(a in r){if(n.find((c)=>rt(c)&&(a in c)&&c[a]===r[a])){s=!0;break}}if(!s)n.push(r)}return n}function ru(e,t,i,n){let r=t;if(rt(r)&&n.has(r))return n.get(r);let o={...e};if(rt(r))n.set(r,o);for(let s in r){if(!Object.prototype.hasOwnProperty.call(r,s))continue;let a=r[s],c=o[s];if(i.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){o[s]=a;continue}if(rt(a)&&rt(c))o[s]=Ys(c,a,i,n);else if(Array.isArray(a)||Array.isArray(c))o[s]=Zs(c,a,i.arrayMergeMode||"smart",n);else o[s]=a}return o}function Un(e,t,i="replace"){return qs(e,t,{arrayMergeMode:i==="replace"?"replace":"smart",skipNullish:!0})}function Pn(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(!Pn(e[i],t[i]))return!1;return!0}if(rt(e)&&rt(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(!Pn(e[r],t[r]))return!1}return!0}return!1}function rt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Sr{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:a=!1}=i;if(r){let f=ni.getWithFileCheck("file",e);if(f){if(a)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!Ji(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,y="default"in u,p=Object.keys(u).length>0;if(!y&&!p)throw new di(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new di(e,Error("Configuration must export a valid object"),"unknown");let w={config:Un(t,l,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(r)ni.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 pi.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(gn(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 zs(async()=>Ji(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,i){let n=[];if(!Ji(e))return n;if(t||i){let r=this.generateNamePatterns(t||"",i);for(let o of r)for(let s of this.extensions){let a=gn(e,`${o}${s}`);if(await this.checkFileAccess(a))n.push(a)}}else try{let{readdirSync:r}=await import("fs"),o=r(e);for(let s of o)if(this.looksLikeConfigFile(s)){let a=gn(e,s);if(await this.checkFileAccess(a))n.push(a)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!Ji(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 Kn{async validateConfiguration(e,t,i={}){let{stopOnFirstError:n=!1,validateRequired:r=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:a=!0,verbose:c=!1}=i,f=async()=>{let u=[],l=[],y={stopOnFirstError:n,validateRequired:r,validateTypes:o,customRules:s,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,y);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],y);else return this.validateWithJSONSchema(e,t,y)}catch(p){return u.push({path:"",message:`Validation failed: ${p}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(a)return await pi.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,i){try{if(!yf(t))throw new mi(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 mi(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,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(s)){if(n.push({path:i,message:`Expected type ${a.join(" or ")}, got ${s}`,expected:a.join(" or "),actual:s,rule:"type"}),o.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path: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 a=i?`${i}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,a,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 a of t.required)if(!(a in s)){if(n.push({path:i?`${i}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[a,c]of Object.entries(t.properties))if(a in s){let f=i?`${i}.${a}`:a;if(this.validateObjectAgainstSchema(s[a],c,f,n,r,o),o.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(s))if(!a.has(c))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),a=this.validateWithRule(s,o,o.path);if(n.push(...a),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:na},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Hn{fileLoader=new Sr;envProcessor=new br;validator=new Kn;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 a;try{a=await this.loadConfigurationStrategies(s,!0,i)}catch(c){let f=s.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),l=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),y=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(y||u))throw c;if(l&&(!f||!y))a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(r||o)await this.validateConfiguration(a.config,r,o,s.name);if(i?.enabled&&a)this.cacheResult(s.name||"",a,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)ft.warn(`Slow configuration loading detected: ${c.duration}ms for ${s.name}`);a.metrics=c}return a}catch(a){let c=Date.now()-t;throw ft.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,i){let{name:n="",alias:r,cwd:o,configDir:s,defaultConfig:a,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=o||Dt.cwd(),y=[],p=await this.loadLocalConfiguration(n,r,l,s,a,f,u,c,i);if(p)return y.push(...this.getLocalSearchPaths(n,r,l,s)),this.finalizeResult(p,y,c,n,u);let w=await this.loadHomeConfiguration(n,r,a,f,u,c);if(w)return y.push(...this.getHomeSearchPaths(n,r)),this.finalizeResult(w,y,c,n,u);let S=await this.loadPackageJsonConfiguration(n,r,l,a,f,u,c);if(S)return y.push(Je(l,"package.json")),this.finalizeResult(S,y,c,n,u);if(y.push(...this.getAllSearchPaths(n,r,l,s)),t)throw Pt.configNotFound(n,y,r);return{...await this.applyEnvironmentVariables(n,a,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,a,c){let f=a?ui(e,r,s):r,u=this.getLocalDirectories(i,n);for(let l of u){if(s)ft.info(`Searching for configuration in: ${l}`);let y=this.fileLoader.generateConfigPaths(e,l,t),p=await this.fileLoader.tryLoadFromPaths(y,f,{arrayStrategy:o,verbose:s,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(p){if(s)ft.success(`Configuration loaded from: ${p.source.path}`);return p}}return null}async loadHomeConfiguration(e,t,i,n,r,o){if(!e)return null;let s=o?ui(e,i,r):i,a=[Je(Jt(),".config",e),Je(Jt(),".config"),Jt()];for(let c of a){if(r)ft.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)ft.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,i,n,r,o,s){let a=s?ui(e,n,o):n;try{let c=Je(i,"package.json");if(!Tn(c))return null;let f=await import(c),u=f[e],l=e;if(!u&&t)u=f[t],l=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(o)ft.success(`Configuration loaded from package.json: ${l}`);return{config:Un(a,u,r),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(o)ft.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:ui(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 ni.get(i)||null}cacheResult(e,t,i,n){let r=this.generateCacheKey(e,n);ni.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,Je(e,"config"),Je(e,".config"),t?Je(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(Je(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=[Je(Jt(),".config",e),Je(Jt(),".config"),Jt()],n=[];for(let r of i)n.push(...this.fileLoader.generateConfigPaths(e,r,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function Ts(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 nu(e){return Et.loadConfig({...e,__strictErrorHandling:!0})}async function Xs(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 Et.loadConfig(e);else n=await Et.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)ft.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 Et.applyEnvironmentVariables(s.name||"",t,!0,s.verbose||!1))?.config??t;return t}}async function ou(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(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&Ts(i)))return(await Et.applyEnvironmentVariables(e,{},!0,!1)).config;throw i}}try{return(await Et.loadConfig({...e,cwd:e.cwd||Dt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Ts(t)))return(await Et.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function su(e,t,i="replace"){let n=new Sr;try{let r=await n.loadFromPath(e,t,{arrayStrategy:i,useCache:!1,trackPerformance:!1});return r?r.config:null}catch{return null}}function ui(e,t,i=!1){let n=new br,r=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,a=[]){let c={...s};for(let[f,u]of Object.entries(s)){let l=[...a,f],y=[`${r}_${l.join("_").toUpperCase()}`,`${r}_${l.map((S)=>S.toUpperCase()).join("")}`,`${r}_${l.map((S)=>S.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],p,w;for(let S of y)if(p=Dt.env[S],p!==void 0){w=S;break}if(p!==void 0&&w)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(p.toLowerCase());else if(typeof u==="number"){let S=Number(p);if(!Number.isNaN(S))c[f]=S}else if(Array.isArray(u))try{c[f]=JSON.parse(p)}catch{c[f]=p.split(",").map((S)=>S.trim())}else c[f]=p;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=o(u,l)}return c}return o(t)}function au(e){let t=Je(Dt.cwd(),e.configDir),i=Je(Dt.cwd(),e.generatedDir),n=Je(i,"config-types.ts");if(!Tn(ns(n)))zc(ns(n),{recursive:!0,mode:511});let r=Tn(t)?Jc(t).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],o=`// Generated by bunfig v${Nu}
|
|
61
|
+
export type ConfigNames = ${r.length?`'${r.join("' | '")}'`:"string"}
|
|
62
|
+
`;qc(n,o,{mode:438})}function lu(e){let t=null,i=null,n=()=>{if(!i)i=Xs(e).then((o)=>(t=o,o),(o)=>{let s="defaultConfig"in e?e.defaultConfig:{};if(t=s,"verbose"in e&&e.verbose)ft.warn("Config loading failed, using defaults:",[o instanceof Error?o:Error(String(o))]);return s});return i},r="defaultConfig"in e?e.defaultConfig:{};return t=r,n(),new Proxy({},{get(o,s){if(t)return t[s];let a=r[s];return n(),a},has(o,s){return s in(t||r)},ownKeys(){return Object.keys(t||r)},getOwnPropertyDescriptor(o,s){return Object.getOwnPropertyDescriptor(t||r,s)},set(o,s,a){if(!t)t={...r};return t[s]=a,!0}})}function cu(e){let t=ws(vf.cwd(),e?.configDir||"./config");function i(){if(!Cf(t))return[];let r=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),o=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=wf(t).filter((c)=>r.has(yn(c))).map((c)=>({base:c.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:c})),a=new Map;for(let{base:c,file:f}of s){let u=yn(f).toLowerCase(),l=a.get(c);if(!l){a.set(c,f);continue}let y=yn(l).toLowerCase();if(o.indexOf(u)<o.indexOf(y))a.set(c,f)}return Array.from(a.entries()).map(([c,f])=>({base:c,file:f})).sort((c,f)=>c.base.localeCompare(f.base))}function n(){let r=i(),o=r.map((c)=>c.base),s=o.length?o.map((c)=>`'${c}'`).join(" | "):"string",a=r.length?`{
|
|
63
|
+
${r.map((c)=>{let f=ws(t,c.file).replace(/\\/g,"/");return` '${c.base}': typeof import('${f}').default`}).join(`,
|
|
110
64
|
`)}
|
|
111
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${
|
|
65
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${s}
|
|
112
66
|
export type ConfigByName = ${a}
|
|
113
67
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
114
68
|
export type ConfigOf = Config
|
|
115
|
-
`}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 xh(e,t={}){let r=vi.cwd();while(r.includes("storage"))r=Jo(r,"..");let n=Jo(r,e||"");if(t?.relative)return fu(vi.cwd(),n);return n}function Fe(){if(wt.env.NODE_ENV==="test"||wt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ph(){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 Na{async format(e){let t=await Ph(),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:rr.pid,hostname:t(),environment:rr.env.NODE_ENV||"development",platform:rr.platform,version:rr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:rr.env.NODE_ENV||rr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ii{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={...Pi},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Na,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??me.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Gn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Gn};return{...Gn,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Pi.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Fe()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,i=0,s=3,o=1000;while(i<s)try{try{try{await pu(this.config.logDirectory,Xo.F_OK|Xo.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 a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:pt.from(e);try{if(!si(this.currentLogFile))await In(this.currentLogFile,"",{mode:420});if(n=Zo(this.currentLogFile,"a",420),mu(n,a,{flag:"a"}),Yo(n),n!==void 0)Dn(n),n=void 0;if((await er(this.currentLogFile)).size===0){if(await In(this.currentLogFile,a,{flag:"w",mode:420}),(await er(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(i<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let l=o*2**i;await new Promise((g)=>setTimeout(g,l)),i++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(n!==void 0)try{Dn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===s-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}i++;let c=o*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return tr(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 tr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return tr(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Fe())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,o],[,a])=>a.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,i);if(n.length>s)for(let[o]of n.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return 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=uu("aes-256-gcm",t,r),i=pt.isBuffer(e)?e:pt.from(e,"utf8"),s=n.update(i),o=n.final(),a=s.length+o.length,c=n.getAuthTag(),f=pt.allocUnsafe(16+a+16);return r.copy(f,0),s.copy(f,16),o.copy(f,16+s.length),c.copy(f,16+a),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=ea(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(pt.from(pt.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Fe())return;if(!this.shouldWriteToFile())return;let e=await er(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await oi(this.config.logDirectory),s=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${o}`;if(await er(r).catch(()=>null))try{if(await Qo(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await ai(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await 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 er(r).catch(()=>null))await Qo(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await oi(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await ai(tr(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=qo(e),n=du(t),i=ea();await wu(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),si(this.currentLogFile))try{let e=Zo(this.currentLogFile,"r+");Yo(e),Dn(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Fe()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await oi(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await ai(tr(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()?ae.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Fe())return!1;let e=typeof me.env.NO_COLOR<"u",t=me.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof me.stderr<"u"&&me.stderr.isTTY||typeof me.stdout<"u"&&me.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,a=(p)=>p.replace(this.ANSI_PATTERN,"");if(!this.fancy){let p=[];if(o)p.push(t);if(s==="warning")p.push("WARN");else if(s==="error")p.push("ERROR");else if(r)p.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)p.push(n.replace(/[[\]]/g,""));return p.push(i),p.join(" ")}let c=me.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} ${ae.cyan(i)}`;if(!o)return f.trim();let u=a(f).trim().length,l=a(t).length,g=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(g)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let a=Number.parseInt(o,10);return a<t[0].length?String(t[0][a]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let a=t[n++];switch(o){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=ae.underline(ae.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(o)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${a}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>ae.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>ae.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>ae.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>ae.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>ae.strikethrough(n)),t}supportsHyperlinks(){if(Fe())return!1;let e=me.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=me.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(yu(t)||t.startsWith("./")||t.startsWith("../"))t=Cu(t);else return null;return si(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,a;if(t instanceof Error)o=t.message,a=t.stack;else o=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let l=this.options.showIcons===!1?"":Dh[e],g=this.options.showTags!==!1&&this.name?ae.gray(this.formatTag(this.name)):"",p;switch(e){case"debug":p=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:ae.gray(c),level:e}),console.error(p);break;case"info":p=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.warn(p);break;case"success":p=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:ae.green(c),level:e}),console.error(p);break;case"warning":p=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.warn(p);break;case"error":if(p=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.error(p),a){let v=a.split(`
|
|
116
|
-
`);for(let
|
|
69
|
+
`}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 Wu(e,t={}){let i=fr.cwd();while(i.includes("storage"))i=vs(i,"..");let n=vs(i,e||"");if(t?.relative)return bf(fr.cwd(),n);return n}function We(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Gu(){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 la{async format(e){let t=await Gu(),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:ri.pid,hostname:t(),environment:ri.env.NODE_ENV||"development",platform:ri.platform,version:ri.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ri.env.NODE_ENV||ri.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class $r{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={...Cr},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new la,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,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{...xn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...xn};return{...xn,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Cr.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 Tf(this.config.logDirectory,$s.F_OK|$s.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Rf(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:gt.from(e);try{if(!qi(this.currentLogFile))await vn(this.currentLogFile,"",{mode:420});if(n=Ss(this.currentLogFile,"a",420),xf(n,a,{flag:"a"}),bs(n),n!==void 0)wn(n),n=void 0;if((await ti(this.currentLogFile)).size===0){if(await vn(this.currentLogFile,a,{flag:"w",mode:420}),(await ti(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 l=s*2**r;await new Promise((y)=>setTimeout(y,l)),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{wn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(r===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}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 ii(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 ii(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ii(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],[,a])=>a.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 Cn(16).toString("hex")}generateKey(){return Cn(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=Cn(16),n=Sf("aes-256-gcm",t,i),r=gt.isBuffer(e)?e:gt.from(e,"utf8"),o=n.update(r),s=n.final(),a=o.length+s.length,c=n.getAuthTag(),f=gt.allocUnsafe(16+a+16);return i.copy(f,0),o.copy(f,16),s.copy(f,16+o.length),c.copy(f,16+a),{encrypted:f,iv:i}}async compressData(e){return new Promise((t,i)=>{let n=xs(),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(We())return;if(!this.shouldWriteToFile())return;let e=await ti(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 Yi(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,a=`${i}.${s}`;if(await ti(i).catch(()=>null))try{if(await As(i,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await Zi(a)}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 vn(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 ti(i).catch(()=>null))await As(i,o)}if(this.currentLogFile=n,t.maxFiles){let r=(await Yi(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(ii(this.config.logDirectory,o))}}}async compressLogFile(e,t){let i=Es(e),n=Af(t),r=xs();await kf(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=Ss(this.currentLogFile,"r+");bs(e),wn(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!We()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Yi(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Zi(ii(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()?ce.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||We())return!1;let e=typeof ye.env.NO_COLOR<"u",t=ye.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof ye.stderr<"u"&&ye.stderr.isTTY||typeof ye.stdout<"u"&&ye.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:i="",tag:n="",message:r,level:o,showTimestamp:s=!0}=e,a=(p)=>p.replace(this.ANSI_PATTERN,"");if(!this.fancy){let p=[];if(s)p.push(t);if(o==="warning")p.push("WARN");else if(o==="error")p.push("ERROR");else if(i)p.push(i.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)p.push(n.replace(/[[\]]/g,""));return p.push(r),p.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} ${ce.cyan(r)}`;if(!s)return f.trim();let u=a(f).trim().length,l=a(t).length,y=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(y)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(o,s)=>{let a=Number.parseInt(s,10);return a<t[0].length?String(t[0][a]):o});let i=/%([sdijfo%])/g,n=0,r=e.replace(i,(o,s)=>{if(s==="%")return"%";if(n>=t.length)return o;let a=t[n++];switch(s){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return o}});if(n<t.length)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=ce.underline(ce.blue(n)),s=this.toAbsoluteFilePath(r);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(s)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${a}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${r}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),t=t.replace(/`([^`]+)`/g,(i,n)=>ce.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(i,n)=>ce.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(i,n)=>ce.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(i,n)=>ce.italic(n)),t=t.replace(/~([^~]+)~/g,(i,n)=>ce.strikethrough(n)),t}supportsHyperlinks(){if(We())return!1;let e=ye.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let i=ye.env.HOME||"";if(i)t=t.replace(/^~(?=$|\/)/,i)}if(Pf(t)||t.startsWith("./")||t.startsWith("../"))t=Of(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,a;if(t instanceof Error)s=t.message,a=t.stack;else s=this.formatMessage(t,i);let{consoleText:c,fileText:f}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let l=this.options.showIcons===!1?"":Ku[e],y=this.options.showTags!==!1&&this.name?ce.gray(this.formatTag(this.name)):"",p;switch(e){case"debug":p=this.formatConsoleMessage({timestamp:r,icon:l,tag:y,message:ce.gray(c),level:e}),console.error(p);break;case"info":p=this.formatConsoleMessage({timestamp:r,icon:l,tag:y,message:c,level:e}),console.warn(p);break;case"success":p=this.formatConsoleMessage({timestamp:r,icon:l,tag:y,message:ce.green(c),level:e}),console.error(p);break;case"warning":p=this.formatConsoleMessage({timestamp:r,icon:l,tag:y,message:c,level:e}),console.warn(p);break;case"error":if(p=this.formatConsoleMessage({timestamp:r,icon:l,tag:y,message:c,level:e}),console.error(p),a){let w=a.split(`
|
|
70
|
+
`);for(let S of w)if(S.trim()&&!S.includes(s))console.error(this.formatConsoleMessage({timestamp:r,message:ce.gray(` ${S}`),level:e,showTimestamp:!1}))}break}}else if(!We()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${s}`),a)console.error(a)}let u=`${o} ${this.environment}.${e.toUpperCase()}: ${f}
|
|
117
71
|
`;if(a)u+=`${a}
|
|
118
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let
|
|
119
|
-
`);if(this[
|
|
120
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?
|
|
121
|
-
`),c=Math.max(...a.map((
|
|
122
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
123
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
124
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||
|
|
72
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let i={update:(r,o)=>{},finish:(r)=>{},interrupt:(r,o)=>{}};if(!this.enabled)return i;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!We()&&ye.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(r,o)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,r),this.activeProgressBar.total),o!==void 0)this.activeProgressBar.message=o;if(this.shouldStyleConsole()&&!We()&&ye.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(r)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,r)},interrupt:(r,o="info")=>{if(!We()&&ye.stdout.isTTY)ye.stdout.write(`
|
|
73
|
+
`);if(this[o==="warning"?"warn":o](r),this.activeProgressBar&&this.shouldStyleConsole()&&!We()&&ye.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let i=this.options.showTags!==!1&&this.name?ce.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":ce.blue("\u25D0"),tag:i,message:`${ce.cyan(e)}...`}))}return async(i)=>{if(!this.enabled)return;let n=performance.now(),r=Math.round(n-t),o=`${e} completed in ${r}ms`,s=new Date,a=this.formatConsoleTimestamp(s),c=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(i)c+=` ${JSON.stringify(i)}`;if(c+=`
|
|
74
|
+
`,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?ce.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":ce.green("\u2713"),tag:f,message:`${o}${i?` ${JSON.stringify(i)}`:""}`}))}else if(!We())console.error(c.trim());if(this.shouldWriteToFile())await this.writeToFile(c)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,i=new $r(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(i),i}createReadStream(){if(We())throw Error("createReadStream is not supported in browser environments");if(!qi(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Es(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let i=this.keys.get(this.currentKeyId);try{let n=gt.isBuffer(e)?e:gt.from(e,"base64"),r=n.subarray(0,16),o=n.subarray(n.length-16),s=n.subarray(16,n.length-16),a=$f("aes-256-gcm",i,r);a.setAuthTag(o);let c=a.update(s),f=a.final(),u=c.length+f.length,l=gt.allocUnsafe(u);return c.copy(l,0),f.copy(l,c.length),l.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return We()}isServerMode(){return!We()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,i=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:r,fileText:o}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let a=r.split(`
|
|
75
|
+
`),c=Math.max(...a.map((y)=>y.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,l=a.map((y)=>this.formatConsoleMessage({timestamp:i,message:ce.cyan(y),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:i,message:ce.cyan(f),showTimestamp:!1})),l.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:i,message:ce.cyan(u),showTimestamp:!1}))}else if(!We())console.error(`${n} ${this.environment}.INFO: [BOX] ${o}`);let s=`${n} ${this.environment}.INFO: [BOX] ${o}
|
|
76
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(e){if(We())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${ce.cyan("?")} ${e} (y/n) `);let i=(n)=>{let r=n.toString().trim().toLowerCase();ye.stdin.removeListener("data",i);try{if(typeof ye.stdin.setRawMode==="function")ye.stdin.setRawMode(!1)}catch{}ye.stdin.pause(),console.error(""),t(r==="y"||r==="yes")};try{if(typeof ye.stdin.setRawMode==="function")ye.stdin.setRawMode(!0)}catch{}ye.stdin.resume(),ye.stdin.once("data",i)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let i=e;if(t&&t.length>0){let s=/%([sdijfo%])/g,a=0;if(i=e.replace(s,(c,f)=>{if(f==="%")return"%";if(a>=t.length)return c;let u=t[a++];switch(f){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return c}}),a<t.length)i+=` ${t.slice(a).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}let{consoleText:n,fileText:r}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?ce.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${ce.blue("\u25D0")} `;console.error(`${a}${s} ${ce.cyan(n)}`)}let o=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
77
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!ye.stdout.isTTY)return;let i=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*i/100),r=e.barLength-n,o=ce.green("\u2501".repeat(n)),s=ce.gray("\u2501".repeat(r)),a=`[${o}${s}]`,c=`${i}%`.padStart(4),f=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||i===100?ce.green("\u2713"):ce.blue("\u25B6"),l=this.options.showTags!==!1&&this.name?` ${ce.gray(this.formatTag(this.name))}`:"",y=`\r${u}${l} ${a} ${c}${f}`,p=ye.stdout.columns||80,w=" ".repeat(Math.max(0,p-y.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${y}${w}`,ye.stdout.write(e.lastRenderedLine),t)ye.stdout.write(`
|
|
78
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||We()||!ye.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(We()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Yi(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=ii(this.config.logDirectory,n);if(e.before)try{if((await ti(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)}}}async function Hu(e,t={}){let{maxRetries:i=3,retryDelay:n=1000,isRetryable:r=()=>!0,fallback:o}=t,s=Error("Unknown error occurred");for(let a=0;a<=i;a++)try{return await e()}catch(c){if(s=c instanceof Error?c:Error(String(c)),a===i||!r(s))break;if(n>0)await new Promise((f)=>setTimeout(f,n))}if(o!==void 0)return o;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}class Jn{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,i={}){let{prefix:n,useCamelCase:r=!0,useBackwardCompatibility:o=!0,customParsers:s={},verbose:a=!1,trackPerformance:c=!0}=i,f=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),l={...t};return this.processObject(l,[],u,{useCamelCase:r,useBackwardCompatibility:o,customParsers:s,verbose:a,configName:e}),{config:l,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return Bn.track("applyEnvironmentVariables",f,{configName:e});return f()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,i,n){for(let[r,o]of Object.entries(e)){let s=[...t,r],a=s.map((u)=>this.formatEnvKey(u,n.useCamelCase)),c=`${i}_${a.join("_")}`,f=n.useBackwardCompatibility?`${i}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.processObject(o,s,i,n);else{let u=Xi.env[c]||(f?Xi.env[f]:void 0);if(u!==void 0){if(n.verbose){let l=Xi.env[c]?c:f}try{e[r]=this.parseEnvironmentValue(u,typeof o,c,n.customParsers,n.configName)}catch(l){if(l instanceof zn)throw l;throw oi.envVar(c,u,typeof o,n.configName)}}}}}parseEnvironmentValue(e,t,i,n,r){for(let[o,s]of Object.entries(n))try{return s(e)}catch{continue}for(let o of this.defaultParsers)if(o.canParse(e,t))try{return o.parse(e)}catch{throw oi.envVar(i,e,`${t} (via ${o.name} parser)`,r)}return e}getEnvironmentVariables(e){let t={},i=e.toUpperCase();for(let[n,r]of Object.entries(Xi.env))if(n.startsWith(i)&&r!==void 0)t[n]=r;return t}validateEnvironmentVariable(e,t,i){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(i)try{this.parseEnvironmentValue(e,t,i,{})}catch(r){n.push(`Cannot parse value "${t}" as ${i}: ${r}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,i={}){let{prefix:n,format:r="text"}=i,o=n||this.generateEnvPrefix(e),s=[];switch(this.extractEnvVarInfo(t,[],o,s),r){case"markdown":return this.formatAsMarkdown(s,e);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,e)}}extractEnvVarInfo(e,t,i,n){for(let[r,o]of Object.entries(e)){let s=[...t,r],a=`${i}_${s.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.extractEnvVarInfo(o,s,i,n);else n.push({key:a,type:Array.isArray(o)?"array":typeof o,description:`Configuration for ${s.join(".")}`,example:this.generateExample(o)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let i=`Environment Variables for ${t}:
|
|
125
79
|
|
|
126
|
-
`;for(let n of e)
|
|
127
|
-
`,
|
|
128
|
-
`,
|
|
129
|
-
`,
|
|
80
|
+
`;for(let n of e)i+=`${n.key}
|
|
81
|
+
`,i+=` Type: ${n.type}
|
|
82
|
+
`,i+=` Description: ${n.description}
|
|
83
|
+
`,i+=` Example: ${n.example}
|
|
130
84
|
|
|
131
|
-
`;return
|
|
85
|
+
`;return i}formatAsMarkdown(e,t){let i=`# Environment Variables for ${t}
|
|
132
86
|
|
|
133
|
-
`;
|
|
134
|
-
`,
|
|
135
|
-
`;for(let n of e)
|
|
136
|
-
`;return r}}function Fh(e,t,r={}){return Ka(e,t,r,new WeakMap)}function Ka(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let a=o(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return za(e,t,i,n);if(!nt(t)||!nt(e))return t;return Bh(e,t,r,n)}function za(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 Nh(e,t);case"smart":return Lh(e,t,n);default:return t}return t}function Nh(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Xn(i,n)))r.push(n);return r}function Lh(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(nt(t[0])&&nt(e[0]))return Wh(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 Wh(e,t,r){let n=[...t];for(let i of e){if(!nt(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let a of s)if(a in i){if(n.find((c)=>nt(c)&&(a in c)&&c[a]===i[a])){o=!0;break}}if(!o)n.push(i)}return n}function Bh(e,t,r,n){let i=t;if(nt(i)&&n.has(i))return n.get(i);let s={...e};if(nt(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let a=i[o],c=s[o];if(r.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){s[o]=a;continue}if(nt(a)&&nt(c))s[o]=Ka(c,a,r,n);else if(Array.isArray(a)||Array.isArray(c))s[o]=za(c,a,r.arrayMergeMode||"smart",n);else s[o]=a}return s}function Ha(e,t,r="replace"){return Fh(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(nt(e)&&nt(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 nt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Ja{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:o=!0,verbose:a=!1}=r;if(i){let f=Ei.getWithFileCheck("file",e);if(f){if(a)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!ci(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,g="default"in u,p=Object.keys(u).length>0;if(!g&&!p)throw new Ri(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new Ri(e,Error("Configuration must export a valid object"),"unknown");let v={config:Ha(t,l,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)Ei.setWithFileCheck("file",v,e,s);return v}catch(f){throw f instanceof Error?nr.configLoad(e,f):nr.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 Ih(async()=>ci(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!ci(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let a=Fn(e,`${s}${o}`);if(await this.checkFileAccess(a))n.push(a)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let a=Fn(e,o);if(await this.checkFileAccess(a))n.push(a)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!ci(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class qa{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:a=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],g={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,g);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],g);else return this.validateWithJSONSchema(e,t,g)}catch(p){return u.push({path:"",message:`Validation failed: ${p}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(a)return await Qn.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!vu(t))throw new Oi(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 Oi(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(o)){if(n.push({path:r,message:`Expected type ${a.join(" or ")}, got ${o}`,expected:a.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let a=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,a,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let a of t.required)if(!(a in o)){if(n.push({path:r?`${r}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[a,c]of Object.entries(t.properties))if(a in o){let f=r?`${r}.${a}`:a;if(this.validateObjectAgainstSchema(o[a],c,f,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(o))if(!a.has(c))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),a=this.validateWithRule(o,s,s.path);if(n.push(...a),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,o]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Gh},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function jh(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 Ya{fileLoader=new Ja;envProcessor=new ls;validator=new qa;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let c=this.checkCache(o.name||"",o);if(c)return c}let a;try{a=await this.loadConfigurationStrategies(o,!0,r)}catch(c){let f=o.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),l=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),g=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(g||u))throw c;if(l&&(!f||!g))a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(i||s)await this.validateConfiguration(a.config,i,s,o.name);if(r?.enabled&&a)this.cacheResult(o.name||"",a,r,o);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)gt.warn(`Slow configuration loading detected: ${c.duration}ms for ${o.name}`);a.metrics=c}return a}catch(a){if(a instanceof Error&&a.name==="ConfigNotFoundError")throw a;let c=Date.now()-t;throw gt.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:a,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=s||ki.cwd(),g=[],p=await this.loadLocalConfiguration(n,i,l,o,a,f,u,c,r);if(p)return g.push(...this.getLocalSearchPaths(n,i,l,o)),this.finalizeResult(p,g,c,n,u);let v=await this.loadHomeConfiguration(n,i,a,f,u,c);if(v)return g.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(v,g,c,n,u);let b=await this.loadPackageJsonConfiguration(n,i,l,a,f,u,c);if(b)return g.push(rt(l,"package.json")),this.finalizeResult(b,g,c,n,u);if(g.push(...this.getAllSearchPaths(n,i,l,o)),t)throw nr.configNotFound(n,g,i);return{...await this.applyEnvironmentVariables(n,a,c,u),warnings:[`No configuration file found for "${n}"${jh(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,a,c){let f=a?ui(e,i,o):i,u=this.getLocalDirectories(r,n);for(let l of u){if(o)gt.info(`Searching for configuration in: ${l}`);let g=this.fileLoader.generateConfigPaths(e,l,t),p=await this.fileLoader.tryLoadFromPaths(g,f,{arrayStrategy:s,verbose:o,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(p){if(o)gt.success(`Configuration loaded from: ${p.source.path}`);return p}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?ui(e,r,i):r,a=[rt(zt(),".config",e),rt(zt(),".config"),zt()];for(let c of a){if(i)gt.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)gt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let a=o?ui(e,n,s):n;try{let c=rt(r,"package.json");if(!If(c))return null;let f={};try{f=JSON.parse(Ff(c,"utf8"))}catch(g){if(s)gt.warn("Failed to parse package.json:",[g instanceof Error?g:Error(String(g))]);return null}let u=f[e],l=e;if(!u&&t){let g=Array.isArray(t)?t:[t];for(let p of g){if(!p)continue;if(f[p]){u=f[p],l=p;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)gt.success(`Configuration loaded from package.json: ${l}`);return{config:Ha(a,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)gt.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:ui(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(i.length>0)throw nr.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Ei.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);Ei.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,rt(e,"config"),rt(e,".config"),t?rt(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(rt(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=[rt(zt(),".config",e),rt(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 ui(e,t,r=!1){let n=new ls,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,a=[]){let c={...o};for(let[f,u]of Object.entries(o)){let l=[...a,f],g=[`${i}_${l.join("_").toUpperCase()}`,`${i}_${l.map((b)=>b.toUpperCase()).join("")}`,`${i}_${l.map((b)=>b.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],p,v;for(let b of g)if(p=ki.env[b],p!==void 0){v=b;break}if(p!==void 0&&v)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(p.toLowerCase());else if(typeof u==="number"){let b=Number(p);if(!Number.isNaN(b))c[f]=b}else if(Array.isArray(u))try{c[f]=JSON.parse(p)}catch{c[f]=p.split(",").map((b)=>b.trim())}else c[f]=p;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,l)}return c}return s(t)}var Ei,Qn,Eu,bu=(e)=>e,$u=(e,t)=>{for(var r in t)Eu(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Su.bind(t,r)})},Au=(e,t)=>()=>(e&&(t=e(e=0)),t),Ca,Ta,ir,Er,Pa,Xu,Qu,ra,di,Un,Be,ve,eh,ia,th,na,rh,ih,Nn,nh,sa,oa,Ln,sh,oh,ah,lh,mi,Ra,ch,Ge,fh,uh,aa,pi,Kn,Ie,re,hh,la,dh,ca,mh,ph,Wn,gh,fa,ua,yh,Bn,Ch,wh,vh,Eh,bh,gi,Oa,Sh,$h="0.15.6",Ze,xi,wr,zn,Hn,Ti,Jn,qn,vr,Yn,Zn,xt,ka,Ma,ot,vt,Da,Ia,Ah,Th,Fa,Pi,Wg,La,ae,Bg,Rh,Gg,Oh,jg,_g,ha,Vg,kh,Mh,Ug,da,Kg,zg,Hg,Jg,qg,Gn,Dh,Yg,at,Wa,Ri,Ba,Ga,as,ja,_a,Oi,Va,Ua,nr,Gh,gt,Zg,Xg,Qg,_h,Za;var Xa=fe(()=>{Ei=new ga,Qn=new ya,Eu=Object.defineProperty;Ca={};$u(Ca,{withErrorRecovery:()=>Ea,tryLoadConfig:()=>Ju,loadConfigWithResult:()=>zu,loadConfig:()=>xa,isRetryableError:()=>Gu,isConfigNotFoundError:()=>Bu,isBunfigError:()=>ba,globalPerformanceMonitor:()=>Er,globalCache:()=>ir,getEnvOrDefault:()=>ju,generateConfigTypes:()=>qu,defaultGeneratedDir:()=>Ia,defaultConfigDir:()=>Da,deepMergeWithArrayStrategy:()=>ns,deepMerge:()=>Sa,createLibraryConfig:()=>Yu,config:()=>Hu,bunfigPlugin:()=>Zu,applyEnvVarsToConfig:()=>yr,TypeGenerationError:()=>qn,SchemaValidationError:()=>vr,PluginError:()=>Zn,PerformanceMonitor:()=>ts,FileSystemError:()=>Jn,ErrorFactory:()=>xt,EnvVarError:()=>Ti,EnvProcessor:()=>Mi,ConfigValidator:()=>ss,ConfigValidationError:()=>zn,ConfigNotFoundError:()=>xi,ConfigMergeError:()=>Hn,ConfigLoader:()=>os,ConfigLoadError:()=>wr,ConfigFileLoader:()=>Di,ConfigCache:()=>es,CacheUtils:()=>Pa,BunfigError:()=>Ze,BrowserConfigError:()=>Yn,ArrayMergeStrategies:()=>ka});Ah=Au(async()=>{Ta=import.meta.require,ir=new es,Er=new ts,Pa={createKey:xu,isEquivalent:Tu,estimateMemoryUsage:Pu},Xu=wi(_n.cwd(),"config"),Qu=wi(_n.cwd(),"src/generated"),ra=Ci.env.CLARITY_LOG_DIR||jf(ku(),"logs"),di={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ra,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Un=await Mu(),Be={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},ve=Be,eh=Be.red,ia=Be.green,th=Be.yellow,na=Be.blue,rh=Be.magenta,ih=Be.cyan,Nn=Be.white,nh=Be.gray,sa=Be.bgRed,oa=Be.bgYellow,Ln=Be.bold,sh=Be.dim,oh=Be.italic,ah=Be.underline,lh=Be.reset,mi={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ra={debug:"\uD83D\uDD0D",info:na("\u2139"),success:ia("\u2713"),warning:oa(Nn(Ln(" WARN "))),error:sa(Nn(Ln(" ERROR ")))},ch=new Si("stacks"),Ge=new Si("bunfig",{showTags:!0}),fh=ze(Cr.cwd(),"config"),uh=ze(Cr.cwd(),"src/generated"),aa=yi.env.CLARITY_LOG_DIR||Bf(Nu(),"logs"),pi={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:aa,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Kn=await Lu(),Ie={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},re=Ie,hh=Ie.red,la=Ie.green,dh=Ie.yellow,ca=Ie.blue,mh=Ie.magenta,ph=Ie.cyan,Wn=Ie.white,gh=Ie.gray,fa=Ie.bgRed,ua=Ie.bgYellow,yh=Ie.bgGray,Bn=Ie.bold,Ch=Ie.dim,wh=Ie.italic,vh=Ie.underline,Eh=Ie.strikethrough,bh=Ie.reset,gi={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Oa={debug:"\uD83D\uDD0D",info:ca("\u2139"),success:la("\u2713"),warning:ua(Wn(Bn(" WARN "))),error:fa(Wn(Bn(" ERROR ")))},Sh=new Ai("stacks"),Ze=class extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},xi=class extends Ze{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r?` or alias "${r}"`:"";super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},wr=class extends Ze{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},zn=class extends Ze{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Hn=class extends Ze{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Ti=class extends Ze{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}},Jn=class extends Ze{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},qn=class extends Ze{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},vr=class extends Ze{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Yn=class extends Ze{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}},Zn=class extends Ze{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},xt={configNotFound(e,t,r){return new xi(e,t,r)},configLoad(e,t,r){return new wr(e,t,r)},configValidation(e,t,r){return new zn(e,t,r)},configMerge(e,t,r,n){return new Hn(e,t,r,n)},envVar(e,t,r,n){return new Ti(e,t,r,n)},fileSystem(e,t,r){return new Jn(e,t,r)},typeGeneration(e,t,r){return new qn(e,t,r)},schemaValidation(e,t,r){return new vr(e,t,r)},browserConfig(e,t,r,n){return new Yn(e,t,r,n)},plugin(e,t,r){return new Zn(e,t,r)}},ka={replace:"replace",concat:"concat",smart:"smart"},Ma=/^https?:\/\//,ot=new Ai("bunfig",{showTags:!0}),vt=new os,Da=He(Mt.cwd(),"config"),Ia=He(Mt.cwd(),"src/generated")});Th=vi.env.CLARITY_LOG_DIR||cu(xh(),"logs"),Fa={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Th,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Pi={...Fa},Wg=(async()=>{try{let{loadConfig:e}=await Ah().then(()=>Ca),t=await e({name:"clarity",alias:"logging",defaultConfig:Fa,cwd:vi.cwd()});if(t)Object.assign(Pi,t)}catch{}return Pi})();La={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"},ae=La,{red:Bg,green:Rh,yellow:Gg,blue:Oh,magenta:jg,cyan:_g,white:ha,gray:Vg,bgRed:kh,bgYellow:Mh,bgGray:Ug,bold:da,dim:Kg,italic:zg,underline:Hg,strikethrough:Jg,reset:qg}=La,Gn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Dh={debug:"\uD83D\uDD0D",info:Oh("\u2139"),success:Rh("\u2713"),warning:Mh(ha(da(" WARN "))),error:kh(ha(da(" ERROR ")))};Yg=new Ii("stacks");at=class at 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}`}};Wa=class Wa extends at{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})}};Ri=class Ri extends at{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}};Ba=class Ba extends at{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};Ga=class Ga extends at{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 at{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})}};ja=class ja extends at{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}};_a=class _a extends at{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}};Oi=class Oi extends at{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})}};Va=class Va extends at{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})}};Ua=class Ua extends at{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}};nr={configNotFound(e,t,r){return new Wa(e,t,r)},configLoad(e,t,r){return new Ri(e,t,r)},configValidation(e,t,r){return new Ba(e,t,r)},configMerge(e,t,r,n){return new Ga(e,t,r,n)},envVar(e,t,r,n){return new as(e,t,r,n)},fileSystem(e,t,r){return new ja(e,t,r)},typeGeneration(e,t,r){return new _a(e,t,r)},schemaValidation(e,t,r){return new Oi(e,t,r)},browserConfig(e,t,r,n){return new Va(e,t,r,n)},plugin(e,t,r){return new Ua(e,t,r)}};Gh=/^https?:\/\//;gt=new Ii("bunfig",{showTags:!0});Zg=new Ya;Xg=rt(ki.cwd(),"config"),Qg=rt(ki.cwd(),"src/generated"),_h={cwd:Df.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},Za=_h});function Qa(e,t,r){let n={file:t,message:"Unknown error",code:br.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=br.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=br.SYNTAX_ERROR,n.suggestion="Check for syntax errors in your TypeScript code.";else if(e.message.includes("type")&&e.message.includes("cannot"))n.code=br.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=br.PARSE_ERROR,n.suggestion="The file contains invalid TypeScript syntax."}else if(typeof e==="string")n.message=e;return n}function el(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(`
|
|
137
|
-
`),
|
|
138
|
-
`)}var
|
|
87
|
+
`;i+=`| Variable | Type | Description | Example |
|
|
88
|
+
`,i+=`|----------|------|-------------|----------|
|
|
89
|
+
`;for(let n of e)i+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
90
|
+
`;return i}}function zu(e,t,i={}){return ya(e,t,i,new WeakMap)}function ya(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 a=s(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return Ca(e,t,r,n);if(!nt(t)||!nt(e))return t;return Zu(e,t,i,n)}function Ca(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)=>Wn(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(nt(t[0])&&nt(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(!nt(r)){n.push(r);continue}let o=["id","name","key","path","type"],s=!1;for(let a of o)if(a in r){if(n.find((c)=>nt(c)&&(a in c)&&c[a]===r[a])){s=!0;break}}if(!s)n.push(r)}return n}function Zu(e,t,i,n){let r=t;if(nt(r)&&n.has(r))return n.get(r);let o={...e};if(nt(r))n.set(r,o);for(let s in r){if(!Object.prototype.hasOwnProperty.call(r,s))continue;let a=r[s],c=o[s];if(i.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){o[s]=a;continue}if(nt(a)&&nt(c))o[s]=ya(c,a,i,n);else if(Array.isArray(a)||Array.isArray(c))o[s]=Ca(c,a,i.arrayMergeMode||"smart",n);else o[s]=a}return o}function wa(e,t,i="replace"){return zu(e,t,{arrayMergeMode:i==="replace"?"replace":"smart",skipNullish:!0})}function Wn(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(!Wn(e[i],t[i]))return!1;return!0}if(nt(e)&&nt(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(!Wn(e[r],t[r]))return!1}return!0}return!1}function nt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class va{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:a=!1}=i;if(r){let f=ur.getWithFileCheck("file",e);if(f){if(a)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!Qi(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,y="default"in u,p=Object.keys(u).length>0;if(!y&&!p)throw new wr(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new wr(e,Error("Configuration must export a valid object"),"unknown");let w={config:wa(t,l,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(r)ur.setWithFileCheck("file",w,e,o);return w}catch(f){throw f instanceof Error?oi.configLoad(e,f):oi.configLoad(e,Error(String(f)))}};if(s)return Bn.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(En(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 Hu(async()=>Qi(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,i){let n=[];if(!Qi(e))return n;if(t||i){let r=this.generateNamePatterns(t||"",i);for(let o of r)for(let s of this.extensions){let a=En(e,`${o}${s}`);if(await this.checkFileAccess(a))n.push(a)}}else try{let{readdirSync:r}=await import("fs"),o=r(e);for(let s of o)if(this.looksLikeConfigFile(s)){let a=En(e,s);if(await this.checkFileAccess(a))n.push(a)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!Qi(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 Ea{async validateConfiguration(e,t,i={}){let{stopOnFirstError:n=!1,validateRequired:r=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:a=!0,verbose:c=!1}=i,f=async()=>{let u=[],l=[],y={stopOnFirstError:n,validateRequired:r,validateTypes:o,customRules:s,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,y);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],y);else return this.validateWithJSONSchema(e,t,y)}catch(p){return u.push({path:"",message:`Validation failed: ${p}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(a)return await Bn.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,i){try{if(!Mf(t))throw new vr(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 vr(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,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(s)){if(n.push({path:i,message:`Expected type ${a.join(" or ")}, got ${s}`,expected:a.join(" or "),actual:s,rule:"type"}),o.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path: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 a=i?`${i}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,a,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 a of t.required)if(!(a in s)){if(n.push({path:i?`${i}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[a,c]of Object.entries(t.properties))if(a in s){let f=i?`${i}.${a}`:a;if(this.validateObjectAgainstSchema(s[a],c,f,n,r,o),o.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(s))if(!a.has(c))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),a=this.validateWithRule(s,o,o.path);if(n.push(...a),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:Xu},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function Qu(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 ba{fileLoader=new va;envProcessor=new Jn;validator=new Ea;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 a;try{a=await this.loadConfigurationStrategies(s,!0,i)}catch(c){let f=s.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),l=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),y=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(y||u))throw c;if(l&&(!f||!y))a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(r||o)await this.validateConfiguration(a.config,r,o,s.name);if(i?.enabled&&a)this.cacheResult(s.name||"",a,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)yt.warn(`Slow configuration loading detected: ${c.duration}ms for ${s.name}`);a.metrics=c}return a}catch(a){if(a instanceof Error&&a.name==="ConfigNotFoundError")throw a;let c=Date.now()-t;throw yt.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,i){let{name:n="",alias:r,cwd:o,configDir:s,defaultConfig:a,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=o||Er.cwd(),y=[],p=await this.loadLocalConfiguration(n,r,l,s,a,f,u,c,i);if(p)return y.push(...this.getLocalSearchPaths(n,r,l,s)),this.finalizeResult(p,y,c,n,u);let w=await this.loadHomeConfiguration(n,r,a,f,u,c);if(w)return y.push(...this.getHomeSearchPaths(n,r)),this.finalizeResult(w,y,c,n,u);let S=await this.loadPackageJsonConfiguration(n,r,l,a,f,u,c);if(S)return y.push(it(l,"package.json")),this.finalizeResult(S,y,c,n,u);if(y.push(...this.getAllSearchPaths(n,r,l,s)),t)throw oi.configNotFound(n,y,r);return{...await this.applyEnvironmentVariables(n,a,c,u),warnings:[`No configuration file found for "${n}"${Qu(r)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,i,n,r,o,s,a,c){let f=a?tr(e,r,s):r,u=this.getLocalDirectories(i,n);for(let l of u){if(s)yt.info(`Searching for configuration in: ${l}`);let y=this.fileLoader.generateConfigPaths(e,l,t),p=await this.fileLoader.tryLoadFromPaths(y,f,{arrayStrategy:o,verbose:s,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(p){if(s)yt.success(`Configuration loaded from: ${p.source.path}`);return p}}return null}async loadHomeConfiguration(e,t,i,n,r,o){if(!e)return null;let s=o?tr(e,i,r):i,a=[it(zt(),".config",e),it(zt(),".config"),zt()];for(let c of a){if(r)yt.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)yt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,i,n,r,o,s){let a=s?tr(e,n,o):n;try{let c=it(i,"package.json");if(!Kc(c))return null;let f={};try{f=JSON.parse(Hc(c,"utf8"))}catch(y){if(o)yt.warn("Failed to parse package.json:",[y instanceof Error?y:Error(String(y))]);return null}let u=f[e],l=e;if(!u&&t){let y=Array.isArray(t)?t:[t];for(let p of y){if(!p)continue;if(f[p]){u=f[p],l=p;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(o)yt.success(`Configuration loaded from package.json: ${l}`);return{config:wa(a,u,r),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(o)yt.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:tr(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 oi.configValidation(n||"unknown",r,n)}checkCache(e,t){let i=this.generateCacheKey(e,t);return ur.get(i)||null}cacheResult(e,t,i,n){let r=this.generateCacheKey(e,n);ur.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,it(e,"config"),it(e,".config"),t?it(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(it(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=[it(zt(),".config",e),it(zt(),".config"),zt()],n=[];for(let r of i)n.push(...this.fileLoader.generateConfigPaths(e,r,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function tr(e,t,i=!1){let n=new Jn,r=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,a=[]){let c={...s};for(let[f,u]of Object.entries(s)){let l=[...a,f],y=[`${r}_${l.join("_").toUpperCase()}`,`${r}_${l.map((S)=>S.toUpperCase()).join("")}`,`${r}_${l.map((S)=>S.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],p,w;for(let S of y)if(p=Er.env[S],p!==void 0){w=S;break}if(p!==void 0&&w)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(p.toLowerCase());else if(typeof u==="number"){let S=Number(p);if(!Number.isNaN(S))c[f]=S}else if(Array.isArray(u))try{c[f]=JSON.parse(p)}catch{c[f]=p.split(",").map((S)=>S.trim())}else c[f]=p;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=o(u,l)}return c}return o(t)}var ur,Bn,Df,If=(e)=>e,Nf=(e,t)=>{for(var i in t)Df(e,i,{get:t[i],enumerable:!0,configurable:!0,set:Ff.bind(t,i)})},Lf=(e,t)=>()=>(e&&(t=e(e=0)),t),Us,Qs,ni,pi,ea,fu,uu,Rs,rr,On,Ve,$e,hu,Ps,du,Os,mu,pu,bn,gu,ks,Ms,Sn,yu,Cu,wu,vu,nr,ta,Eu,Ue,bu,Su,Ds,or,kn,Le,ae,$u,Is,Au,Fs,xu,Tu,$n,Ru,Ns,Ls,Pu,An,Ou,ku,Mu,Du,Iu,sr,ia,Fu,Nu="0.15.6",et,gr,di,Mn,Dn,yr,In,Fn,mi,Nn,Ln,Pt,ra,na,ft,Et,oa,sa,Lu,Bu,aa,Cr,Dg,ca,ce,Ig,ju,Fg,_u,Ng,Lg,Ws,Wg,Vu,Uu,Bg,Bs,Gg,jg,_g,Vg,Ug,xn,Ku,Kg,ut,fa,wr,ua,ha,zn,da,ma,vr,pa,ga,oi,Xu,yt,Hg,zg,Jg,eh,Sa;var $a=pe(()=>{ur=new _s,Bn=new Vs,Df=Object.defineProperty;Us={};Nf(Us,{withErrorRecovery:()=>zs,tryLoadConfig:()=>su,loadConfigWithResult:()=>nu,loadConfig:()=>Xs,isRetryableError:()=>Xf,isConfigNotFoundError:()=>Zf,isBunfigError:()=>Js,globalPerformanceMonitor:()=>pi,globalCache:()=>ni,getEnvOrDefault:()=>Qf,generateConfigTypes:()=>au,defaultGeneratedDir:()=>sa,defaultConfigDir:()=>oa,deepMergeWithArrayStrategy:()=>Un,deepMerge:()=>qs,createLibraryConfig:()=>lu,config:()=>ou,bunfigPlugin:()=>cu,applyEnvVarsToConfig:()=>ui,TypeGenerationError:()=>Fn,SchemaValidationError:()=>mi,PluginError:()=>Ln,PerformanceMonitor:()=>jn,FileSystemError:()=>In,ErrorFactory:()=>Pt,EnvVarError:()=>yr,EnvProcessor:()=>br,ConfigValidator:()=>Kn,ConfigValidationError:()=>Mn,ConfigNotFoundError:()=>gr,ConfigMergeError:()=>Dn,ConfigLoader:()=>Hn,ConfigLoadError:()=>di,ConfigFileLoader:()=>Sr,ConfigCache:()=>Gn,CacheUtils:()=>ea,BunfigError:()=>et,BrowserConfigError:()=>Nn,ArrayMergeStrategies:()=>ra});Lu=Lf(async()=>{Qs=import.meta.require,ni=new Gn,pi=new jn,ea={createKey:Wf,isEquivalent:Bf,estimateMemoryUsage:Gf},fu=cr(Rn.cwd(),"config"),uu=cr(Rn.cwd(),"src/generated"),Rs=lr.env.CLARITY_LOG_DIR||Xc(Vf(),"logs"),rr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Rs,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},On=await Uf(),Ve={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},$e=Ve,hu=Ve.red,Ps=Ve.green,du=Ve.yellow,Os=Ve.blue,mu=Ve.magenta,pu=Ve.cyan,bn=Ve.white,gu=Ve.gray,ks=Ve.bgRed,Ms=Ve.bgYellow,Sn=Ve.bold,yu=Ve.dim,Cu=Ve.italic,wu=Ve.underline,vu=Ve.reset,nr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ta={debug:"\uD83D\uDD0D",info:Os("\u2139"),success:Ps("\u2713"),warning:Ms(bn(Sn(" WARN "))),error:ks(bn(Sn(" ERROR ")))},Eu=new dr("stacks"),Ue=new dr("bunfig",{showTags:!0}),bu=ze(hi.cwd(),"config"),Su=ze(hi.cwd(),"src/generated"),Ds=ar.env.CLARITY_LOG_DIR||Yc(Jf(),"logs"),or={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ds,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},kn=await qf(),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"},ae=Le,$u=Le.red,Is=Le.green,Au=Le.yellow,Fs=Le.blue,xu=Le.magenta,Tu=Le.cyan,$n=Le.white,Ru=Le.gray,Ns=Le.bgRed,Ls=Le.bgYellow,Pu=Le.bgGray,An=Le.bold,Ou=Le.dim,ku=Le.italic,Mu=Le.underline,Du=Le.strikethrough,Iu=Le.reset,sr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ia={debug:"\uD83D\uDD0D",info:Fs("\u2139"),success:Is("\u2713"),warning:Ls($n(An(" WARN "))),error:Ns($n(An(" ERROR ")))},Fu=new pr("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,i])=>`${t}: ${i}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},gr=class extends et{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})}},di=class extends et{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}},Mn=class extends et{code="CONFIG_VALIDATION_ERROR";constructor(e,t,i){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:i,validationErrors:t,errorCount:t.length})}},Dn=class extends et{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}},yr=class extends et{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})}},In=class extends et{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}},Fn=class extends et{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}},mi=class extends et{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})}},Nn=class extends et{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})}},Ln=class extends et{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 gr(e,t,i)},configLoad(e,t,i){return new di(e,t,i)},configValidation(e,t,i){return new Mn(e,t,i)},configMerge(e,t,i,n){return new Dn(e,t,i,n)},envVar(e,t,i,n){return new yr(e,t,i,n)},fileSystem(e,t,i){return new In(e,t,i)},typeGeneration(e,t,i){return new Fn(e,t,i)},schemaValidation(e,t,i){return new mi(e,t,i)},browserConfig(e,t,i,n){return new Nn(e,t,i,n)},plugin(e,t,i){return new Ln(e,t,i)}},ra={replace:"replace",concat:"concat",smart:"smart"},na=/^https?:\/\//,ft=new pr("bunfig",{showTags:!0}),Et=new Hn,oa=Je(Dt.cwd(),"config"),sa=Je(Dt.cwd(),"src/generated")});Bu=fr.env.CLARITY_LOG_DIR||Ef(Wu(),"logs"),aa={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Bu,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Cr={...aa},Dg=(async()=>{try{let{loadConfig:e}=await Lu().then(()=>Us),t=await e({name:"clarity",alias:"logging",defaultConfig:aa,cwd:fr.cwd()});if(t)Object.assign(Cr,t)}catch{}return Cr})();ca={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},ce=ca,{red:Ig,green:ju,yellow:Fg,blue:_u,magenta:Ng,cyan:Lg,white:Ws,gray:Wg,bgRed:Vu,bgYellow:Uu,bgGray:Bg,bold:Bs,dim:Gg,italic:jg,underline:_g,strikethrough:Vg,reset:Ug}=ca,xn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ku={debug:"\uD83D\uDD0D",info:_u("\u2139"),success:ju("\u2713"),warning:Uu(Ws(Bs(" WARN "))),error:Vu(Ws(Bs(" ERROR ")))};Kg=new $r("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,i])=>`${t}: ${i}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}};fa=class fa extends ut{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})}};wr=class wr extends ut{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}};ua=class ua extends ut{code="CONFIG_VALIDATION_ERROR";constructor(e,t,i){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:i,validationErrors:t,errorCount:t.length})}};ha=class ha extends ut{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}};zn=class zn extends ut{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})}};da=class da extends ut{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}};ma=class ma extends ut{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}};vr=class vr extends ut{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})}};pa=class pa extends ut{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})}};ga=class ga extends ut{code="PLUGIN_ERROR";constructor(e,t,i){super(`Plugin "${e}" failed during ${t}: ${i.message}`,{pluginName:e,operation:t,originalError:i.name,originalMessage:i.message});this.cause=i}};oi={configNotFound(e,t,i){return new fa(e,t,i)},configLoad(e,t,i){return new wr(e,t,i)},configValidation(e,t,i){return new ua(e,t,i)},configMerge(e,t,i,n){return new ha(e,t,i,n)},envVar(e,t,i,n){return new zn(e,t,i,n)},fileSystem(e,t,i){return new da(e,t,i)},typeGeneration(e,t,i){return new ma(e,t,i)},schemaValidation(e,t,i){return new vr(e,t,i)},browserConfig(e,t,i,n){return new pa(e,t,i,n)},plugin(e,t,i){return new ga(e,t,i)}};Xu=/^https?:\/\//;yt=new $r("bunfig",{showTags:!0});Hg=new ba;zg=it(Er.cwd(),"config"),Jg=it(Er.cwd(),"src/generated"),eh={cwd:Uc.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},Sa=eh});function Aa(e,t,i){let n={file:t,message:"Unknown error",code:gi.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=gi.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=gi.SYNTAX_ERROR,n.suggestion="Check for syntax errors in your TypeScript code.";else if(e.message.includes("type")&&e.message.includes("cannot"))n.code=gi.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=gi.PARSE_ERROR,n.suggestion="The file contains invalid TypeScript syntax."}else if(typeof e==="string")n.message=e;return n}function xa(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(`
|
|
91
|
+
`),o=e.location.line-1;if(o>=0&&o<r.length){let s=Math.max(0,o-1),a=Math.min(r.length-1,o+1);for(let c=s;c<=a;c++){let f=(c+1).toString().padStart(4," "),u=c===o?">":" ";if(i.push(` ${u} ${f} | ${r[c]}`),c===o&&e.location.column>0){let l=" ".repeat(10+e.location.column-1);i.push(` ${l}^`)}}}}if(e.suggestion)i.push(""),i.push(` Suggestion: ${e.suggestion}`);return i.join(`
|
|
92
|
+
`)}var gi;var Ta=pe(()=>{gi={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 Pa(e){return e.endsWith(".vue")}function th(e){let t={script:null,scriptSetup:null},i=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,n;while((n=i.exec(e))!==null){let r=n[1]||"",o=/lang\s*=\s*["']([^"']+)["']/i.exec(r)?.[1]?.toLowerCase()??"js",s={content:n[2]??"",attrs:r,setup:/\bsetup\b/.test(r),lang:o};if(s.setup)t.scriptSetup=s;else t.script=s}return t}function tt(e,t){let i=e[t];t++;while(t<e.length){let n=e[t];if(n==="\\"){t+=2;continue}if(n===i)return t+1;t++}return t}function ot(e,t){t++;let i=0;while(t<e.length){let n=e[t];if(n==="\\"){t+=2;continue}if(n==="`"&&i===0)return t+1;if(n==="$"&&e[t+1]==="{"){i++,t+=2;continue}if(n==="}"){if(i>0)i--;t++;continue}t++}return t}function dt(e,t){if(e[t+1]==="/"){let i=e.indexOf(`
|
|
93
|
+
`,t+2);return i===-1?e.length:i+1}if(e[t+1]==="*"){let i=e.indexOf("*/",t+2);return i===-1?e.length:i+2}return t+1}function Yn(e,t){let i=e[t];if(i==='"'||i==="'")return tt(e,t);if(i==="`")return ot(e,t);if(i==="/"&&(e[t+1]==="/"||e[t+1]==="*"))return dt(e,t);return t}function Zn(e){let t=e.split(""),i=0;while(i<e.length){let n=Yn(e,i);if(n>i){for(let r=i;r<n;r++)if(t[r]!==`
|
|
94
|
+
`&&t[r]!=="\r")t[r]=" ";i=n;continue}i++}return t.join("")}function je(e,t,i,n){let r=0,o=t;while(o<e.length){let s=e[o];if(s==='"'||s==="'"){o=tt(e,o);continue}if(s==="`"){o=ot(e,o);continue}if(s==="/"&&(e[o+1]==="/"||e[o+1]==="*")){o=dt(e,o);continue}if(s===i)r++;else if(s===n){if(r--,r===0)return o}o++}return-1}function Xn(e,t){let i=0,n=t;while(n<e.length){let r=e[n];if(r==='"'||r==="'"){n=tt(e,n);continue}if(r==="`"){n=ot(e,n);continue}if(r==="/"&&(e[n+1]==="/"||e[n+1]==="*")){n=dt(e,n);continue}if(r==="="&&e[n+1]===">"){n+=2;continue}if(r==="<")i++;else if(r===">"){if(i--,i===0)return n}n++}return-1}function si(e,t=","){let i=[],n=0,r="",o=0;while(o<e.length){let s=e[o];if(s==='"'||s==="'"){let a=tt(e,o);r+=e.slice(o,a),o=a;continue}if(s==="`"){let a=ot(e,o);r+=e.slice(o,a),o=a;continue}if(s==="/"&&(e[o+1]==="/"||e[o+1]==="*")){o=dt(e,o);continue}if(s==="{"||s==="["||s==="("||s==="<")n++;else if(s==="}"||s==="]"||s===")"||s===">")n--;if(s===t&&n===0){i.push(r),r="",o++;continue}r+=s,o++}if(r.trim()!=="")i.push(r);return i}function wi(e){let t=e.trim();if(!t.startsWith("{"))return[];let i=je(t,0,"{","}");if(i===-1)return[];let n=t.slice(1,i),r=[];for(let o of si(n)){let s=-1,a=0;for(let u=0;u<o.length;u++){let l=o[u];if(l==='"'||l==="'"){u=tt(o,u)-1;continue}if(l==="`"){u=ot(o,u)-1;continue}if(l==="{"||l==="["||l==="("||l==="<")a++;else if(l==="}"||l==="]"||l===")"||l===">")a--;else if(l===":"&&a===0){s=u;break}}if(s!==-1){r.push({key:yi(o.slice(0,s).trim()),value:o.slice(s+1).trim(),isMethod:!1});continue}let c=/^([A-Za-z_$][\w$]*|['"][^'"]+['"])\s*\(/.exec(o.trim());if(c){r.push({key:yi(c[1]),value:o.trim(),isMethod:!0});continue}let f=o.trim();if(f)r.push({key:yi(f),value:"",isMethod:!1})}return r}function yi(e){if(e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);return e}function Ci(e){return/^[A-Za-z_$][\w$]*$/.test(e)?e:JSON.stringify(e)}function vi(e,t){let i=new RegExp(`\\b${t}\\b`,"g"),n;while((n=i.exec(e))!==null){let r=n.index+n[0].length;while(r<e.length&&/\s/.test(e[r]))r++;let o=null;if(e[r]==="<"){let c=Xn(e,r);if(c===-1)return null;o=e.slice(r+1,c).trim(),r=c+1;while(r<e.length&&/\s/.test(e[r]))r++}if(e[r]!=="(")continue;let s=je(e,r,"(",")");if(s===-1)return null;let a=si(e.slice(r+1,s));return{generic:o,arg:a.length>0?a[0].trim():null}}return null}function ih(e,t){let i=Oa(e,t);if(!i)return null;return i.kind==="interface"?e.slice(i.bodyStart,i.end):e.slice(i.bodyStart,i.end).trim()}function Oa(e,t){let i=new RegExp(`\\binterface\\s+${t}\\b[^{]*\\{`,"m").exec(e);if(i){let r=i.index+i[0].length-1,o=je(e,r,"{","}");if(o!==-1)return{kind:"interface",start:i.index,end:o+1,bodyStart:r}}let n=new RegExp(`\\btype\\s+${t}\\b[^=]*=`,"m").exec(e);if(n){let r=n.index+n[0].length,o=0,s=r;while(r<e.length){let a=e[r];if(a==='"'||a==="'"){r=tt(e,r);continue}if(a==="`"){r=ot(e,r);continue}if(a==="{"||a==="["||a==="("||a==="<")o++;else if(a==="}"||a==="]"||a===")"||a===">")o--;else if((a===";"||a===`
|
|
95
|
+
`)&&o===0)break;r++}return{kind:"type",start:n.index,end:r,bodyStart:s}}return null}function rh(e){let t=e.search(/\bas\s+PropType\s*</);if(t===-1)return null;let i=e.indexOf("<",t),n=Xn(e,i);if(n===-1)return null;if(e.slice(n+1).trim()!=="")return null;return e.slice(i+1,n).trim()}function qn(e){let t=e.trim(),i=rh(t);if(i!==null)return{type:i,optional:!0};if(t==="null")return{type:"unknown",optional:!0};if(t.startsWith("[")){let n=je(t,0,"[","]");if(n!==-1){let r=si(t.slice(1,n)).map((o)=>qn(o).type).filter((o)=>o!=="unknown");return{type:r.length>0?[...new Set(r)].join(" | "):"unknown",optional:!0}}}if(t.startsWith("{")){let n=wi(t),r=n.find((c)=>c.key==="type"),o=n.find((c)=>c.key==="required"),s=r?qn(r.value).type:"unknown",a=!(o&&o.value.trim()==="true");return{type:s,optional:a}}if(Ra[t])return{type:Ra[t],optional:!0};if(/^[A-Za-z_$][\w$.]*$/.test(t))return{type:t,optional:!0};return{type:"unknown",optional:!0}}function Rr(e){let t=e.trim();if(t.startsWith("{")){let i=wi(t);if(i.length===0)return"{}";return`{ ${i.map((n)=>{if(n.isMethod||n.value==="")return`${Ci(n.key)}?: unknown`;let r=qn(n.value);return`${Ci(n.key)}${r.optional?"?":""}: ${r.type}`}).join(", ")} }`}if(t.startsWith("[")){let i=je(t,0,"[","]");if(i===-1)return null;let n=si(t.slice(1,i)).map((r)=>yi(r.trim())).filter((r)=>r!=="");if(n.length===0)return"{}";return`{ ${n.map((r)=>`${Ci(r)}?: unknown`).join(", ")} }`}return null}function nh(e){let t=e.trim();if(!t.startsWith("["))return null;let i=je(t,0,"[","]");if(i===-1)return null;let n=si(t.slice(1,i)).map((r)=>r.trim());if(n.length===0)return"{}";if(!n.every((r)=>r.startsWith("'")&&r.endsWith("'")||r.startsWith('"')&&r.endsWith('"')))return"string[]";return`[${n.map((r)=>JSON.stringify(yi(r))).join(", ")}]`}function oh(e){let t=e.trim();if(!t.startsWith("{"))return null;let i=wi(t);if(i.length===0)return"{}";return`{ ${i.map((n)=>`${JSON.stringify(n.key)}: (...args: any[]) => void`).join(", ")} }`}function ka(e){return nh(e)??oh(e)}function sh(e){let t=[],i=0,n="",r=0;while(r<e.length){let o=e[r];if(o==='"'||o==="'"){let s=tt(e,r);n+=e.slice(r,s),r=s;continue}if(o==="`"){let s=ot(e,r);n+=e.slice(r,s),r=s;continue}if(o==="/"&&(e[r+1]==="/"||e[r+1]==="*")){let s=dt(e,r);n+=e.slice(r,s),r=s;continue}if(o==="="&&e[r+1]===">"){n+="=>",r+=2;continue}if(o==="{"||o==="["||o==="("||o==="<")i++;else if(o==="}"||o==="]"||o===")"||o===">")i--;if((o===";"||o===","||o===`
|
|
96
|
+
`)&&i===0){if(n.trim()!=="")t.push(n.trim());n="",r++;continue}n+=o,r++}if(n.trim()!=="")t.push(n.trim());return t}function ah(e){let t=e.trim();if(!t.startsWith("{"))return null;let i=je(t,0,"{","}");if(i===-1||t.slice(i+1).trim()!=="")return null;let n=sh(t.slice(1,i));if(n.length===0)return"{}";let r=[];for(let o of n){let s=/^\(\s*\w+\s*:\s*/.exec(o);if(!s)return null;let a=s[0].length,c=o[a];if(c!=="'"&&c!=='"'&&c!=="`")return null;let f=tt(o,a),u=o.slice(a+1,f-1),l=je(o,o.indexOf("(",0),"(",")");if(l===-1)return null;let y=o.slice(a,l),p=si(y).slice(1),w=o.slice(l+1).trim();if(w.startsWith(":"))w=w.slice(1).trim();if(w==="")w="void";r.push(`${JSON.stringify(u)}: (${p.map((S)=>S.trim()).join(", ")}) => ${w}`)}return`{ ${r.join(", ")} }`}function Qn(e){let t=e;for(let i of["defineProps","defineEmits","defineExpose","defineSlots","defineOptions"])t=lh(t,i);return t}function lh(e,t){let i=new RegExp(`\\b${t}\\b`,"g"),n=[],r=e,o;while((o=i.exec(e))!==null){let s=e.lastIndexOf(`
|
|
97
|
+
`,o.index)+1,a=e.slice(s,o.index),c=/^\s*(?:(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*(?::[^=]+)?=\s*)?(withDefaults\s*\(\s*)?$/.exec(a);if(!c)continue;let f=o.index+o[0].length;while(f<e.length&&/\s/.test(e[f]))f++;if(e[f]==="<"){let y=Xn(e,f);if(y===-1)continue;f=y+1;while(f<e.length&&/\s/.test(e[f]))f++}if(e[f]!=="(")continue;let u=je(e,f,"(",")");if(u===-1)continue;if(c[1]){let y=s+a.length-c[1].length,p=e.indexOf("(",y);if(p!==-1){let w=je(e,p,"(",")");if(w!==-1)u=w}}let l=u+1;while(l<e.length&&e[l]!==`
|
|
98
|
+
`&&/\s|;/.test(e[l]))l++;if(e[l]===`
|
|
99
|
+
`)l++;n.push([s,l])}for(let s=n.length-1;s>=0;s--)r=r.slice(0,n[s][0])+r.slice(n[s][1]);return r}function eo(e){let t=ch(e);if(t!==-1){let i=/^export\s+default\b/.exec(e.slice(t))?.[0];if(!i)return{options:null,script:e,passthrough:!1};let n=t+i.length;while(n<e.length&&/\s/.test(e[n]))n++;let r=-1,o=-1,s=-1;if(e[n]==="{")r=n,o=je(e,n,"{","}"),s=o;else if(e.startsWith("defineComponent",n)){let f=e.indexOf("(",n);if(f!==-1){let u=f+1;while(u<e.length&&/\s/.test(e[u]))u++;if(e[u]==="{")r=u,o=je(e,u,"{","}"),s=je(e,f,"(",")")}}if(r===-1||o===-1||s===-1)return{options:null,script:e,passthrough:!0};let a=s+1;if(e[a]===";")a++;let c=(e.slice(0,t)+e.slice(a)).trim();return{options:e.slice(r,o+1),script:c,passthrough:!1}}return{options:null,script:e,passthrough:!1}}function ch(e){let t=0,i=0;while(i<e.length){let n=e[i];if(n==='"'||n==="'"){i=tt(e,i);continue}if(n==="`"){i=ot(e,i);continue}if(n==="/"&&(e[i+1]==="/"||e[i+1]==="*")){i=dt(e,i);continue}if(n==="{"||n==="["||n==="(")t++;else if(n==="}"||n==="]"||n===")")t=Math.max(0,t-1);else if(t===0&&e.startsWith("export",i)){let r=i===0?"":e[i-1],o=e[i+6]??"";if(!/[\w$]/.test(r)&&!/[\w$]/.test(o)){if(/^export\s+default\b/.exec(e.slice(i)))return i}}i++}return-1}function Ar(e,t){let i=wi(e).find((n)=>n.key===t);return i&&i.value!==""?i.value:null}function xr(e,t){let i=uh(e),n=e;for(let r=i.length-1;r>=0;r--){let o=i[r],s=n.slice(0,o.start)+n.slice(o.end);if(fh(s,o.name))continue;if(new RegExp(`\\btypeof\\s+${o.name}\\b`).test(t))continue;n=s}return n}function fh(e,t){let i=0;while(i<e.length){let n=e[i];if(n==='"'||n==="'"){i=tt(e,i);continue}if(n==="`"){i=ot(e,i);continue}if(n==="/"&&(e[i+1]==="/"||e[i+1]==="*")){i=dt(e,i);continue}if(/[A-Za-z_$]/.test(n)){let r=i+1;while(r<e.length&&/[\w$]/.test(e[r]))r++;if(e.slice(i,r)===t)return!0;i=r;continue}i++}return!1}function uh(e){let t=[],i=hh(e),n=/^[ \t]*(const|let|var|(?:async[ \t]+)?function)[ \t]+([A-Za-z_$][\w$]*)[ \t]*(?::[^=\n]+)?=?/gm,r;while((r=n.exec(e))!==null){let o=e.lastIndexOf(`
|
|
100
|
+
`,r.index)+1;if(!i.has(o))continue;if(/\bexport\b/.test(e.slice(o,r.index)))continue;let s=r[1],a=r[2],c=r.index+r[0].length,f=-1;if(s.endsWith("function")){let u=e.indexOf("(",c);if(u===-1)continue;let l=je(e,u,"(",")");if(l===-1)continue;c=l+1;while(c<e.length&&/\s/.test(e[c]))c++;if(e[c]===":")while(c<e.length&&e[c]!=="{"&&e[c]!==`
|
|
101
|
+
`)c++;while(c<e.length&&/\s/.test(e[c])&&e[c]!==`
|
|
102
|
+
`)c++;if(e[c]!=="{")continue;let y=je(e,c,"{","}");if(y===-1)continue;f=y+1}else{let u=0;while(c<e.length){let l=e[c];if(l==='"'||l==="'"){c=tt(e,c);continue}if(l==="`"){c=ot(e,c);continue}if(l==="/"&&(e[c+1]==="/"||e[c+1]==="*")){c=dt(e,c);continue}if(l==="{"||l==="["||l==="(")u++;else if(l==="}"||l==="]"||l===")")u--;else if(l===";"&&u===0){f=c+1;break}else if(l===`
|
|
103
|
+
`&&u===0){f=c;break}c++}if(f===-1)f=e.length}if(e[f]===`
|
|
104
|
+
`)f++;t.push({name:a,start:r.index,end:f})}return t}function hh(e){let t=new Set([0]),i=0,n=0;while(n<e.length){let r=e[n];if(r==='"'||r==="'"){n=tt(e,n);continue}if(r==="`"){n=ot(e,n);continue}if(r==="/"&&(e[n+1]==="/"||e[n+1]==="*")){n=dt(e,n);continue}if(r==="{"||r==="["||r==="(")i++;else if(r==="}"||r==="]"||r===")")i=Math.max(0,i-1);if(r===`
|
|
105
|
+
`&&i===0)t.add(n+1);n++}return t}function Tr(e,t,i){let n=e.indexOf(i);if(n===-1)return e;let r=e.lastIndexOf(`
|
|
106
|
+
`,n)+1;if(/\bexport\b/.test(e.slice(r,n)))return e;let o=e.slice(0,n)+e.slice(n+i.length);if(new RegExp(`\\b${t}\\b`).test(o))return e;return o}function to(e){let t="",i=0,n=()=>{for(let o=t.length-1;o>=0;o--)if(!/\s/.test(t[o]))return t[o];return""},r=(o)=>{for(let s=o;s<e.length;s++)if(!/\s/.test(e[s]))return e[s];return""};while(i<e.length){let o=e[i];if(o==='"'||o==="'"){let s=tt(e,i);t+=e.slice(i,s),i=s;continue}if(o==="`"){let s=ot(e,i);t+=e.slice(i,s),i=s;continue}if(o==="/"&&e[i+1]==="*"){let s=dt(e,i);t+=e.slice(i,s).replace(/\s*\n\s*/g," "),i=s;continue}if(o==="/"&&e[i+1]==="/"){let s=i+2;while(s<e.length&&e[s]!==`
|
|
107
|
+
`)s++;let a=e.slice(i+2,s).trim();if(a!==""&&!a.includes("*/"))t+=`/* ${a} */`;i=s;continue}if(o===`
|
|
108
|
+
`){let s=n(),a=r(i+1);if(s===""||a===""){i++;continue}let c=dh(t);if(!c&&("{;,(<:=[".includes(s)||"}),]>;|&".includes(a))){if(!t.endsWith(" ")&&!t.endsWith(";"))t+=" "}else if(c){if(!t.endsWith(" "))t+=" "}else{if(t.endsWith(" "))t=t.slice(0,-1);t+="; "}i++;while(i<e.length&&(e[i]===" "||e[i]==="\t"))i++;continue}t+=o,i++}return t}function dh(e){let t=e.length-1;while(t>=0&&/\s/.test(e[t]))t--;if(t<1||e[t]!=="/"||e[t-1]!=="*")return!1;let i=e.lastIndexOf("/*",t);if(i===-1)return!1;for(let n=i-1;n>=0;n--){let r=e[n];if(/\s/.test(r))continue;return"{;,(<:".includes(r)}return!0}function Pr(e,t){let i=[e,t].filter((n)=>n!==null);for(let n of i){let r=vi(n,"defineProps");if(!r)continue;if(r.generic){let o=r.generic;if(o.startsWith("{"))return{type:o};if(/^[A-Za-z_$][\w$]*$/.test(o)){for(let s of i){let a=Oa(s,o);if(!a)continue;let c=ih(s,o);if(c===null)continue;return{type:c,inlinedLocal:{name:o,declText:s.slice(a.start,a.end)}}}return{type:o}}return{type:o}}if(r.arg){let o=Rr(r.arg);if(o!==null)return{type:o}}}return null}function io(e,t){let i=[e,t].filter((n)=>n!==null);for(let n of i){let r=vi(n,"defineEmits");if(!r)continue;if(r.generic)return ah(r.generic)??r.generic;if(r.arg){let o=ka(r.arg);if(o!==null)return o}}return null}function ro(e,t){let i=[e,t].filter((n)=>n!==null);for(let n of i){let r=vi(n,"defineExpose");if(!r||!r.arg||!r.arg.startsWith("{"))continue;let o=wi(r.arg);if(o.length===0)return null;return`{ ${o.map((s)=>{if(s.value===""&&/^[A-Za-z_$][\w$]*$/.test(s.key))return`${Ci(s.key)}: typeof ${s.key}`;let a=s.isMethod||/=>|^\s*function\b/.test(s.value);return`${Ci(s.key)}: ${a?"(...args: any[]) => any":"unknown"}`}).join(", ")} }`}return null}function Ma(e){let t=th(e),i="",n=null,r=null;if(t.script){let x=eo(t.script.content);if(x.passthrough)return t.scriptSetup?`${t.script.content}
|
|
109
|
+
${t.scriptSetup.content}`:t.script.content;if(i=x.script,x.options){let E=Ar(x.options,"props");if(E)n=Rr(E);let k=Ar(x.options,"emits");if(k)r=ka(k)}}let o=t.scriptSetup?.content??null,s=o!==null?Qn(o):null,a=Pr(o,o!==null?null:i),c=a?.type??n??"{}",f=io(o,null)??r,u=ro(o,null),l=a?.inlinedLocal;if(l){if(i=Tr(i,l.name,l.declText),s!==null)s=Tr(s,l.name,l.declText)}let y=[c,u??"{}"];if(f)y.push("{}","{}","{}","{}","{}",f);let p=to(`DefineComponent<${y.join(", ")}>`),w=[],S=xr(i,p);if(S.trim()!=="")w.push(S);if(s&&s.trim()!==""){let x=xr(s,p);if(x.trim()!=="")w.push(x)}return w.push("import type { DefineComponent } from 'vue'"),w.push(`type __DtsxComponentType = ${p}`),w.push("const __dtsx_component__: __DtsxComponentType = null as unknown as __DtsxComponentType"),w.push("export default __dtsx_component__"),w.join(`
|
|
110
|
+
`)}var Ra;var no=pe(()=>{Ra={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 Ia(e){return e.endsWith(".stx")}function mh(e){let t=[],i=/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi,n;while((n=i.exec(e))!==null){let r=n[1]??"",o=/\blang\s*=\s*["']([^"']+)["']/i.exec(r)?.[1]?.toLowerCase()??(/\b(?:type\s*=\s*["'](?:text\/)?typescript["']|typescript)\b/i.test(r)?"ts":"js"),s=/\bserver\b/i.test(r)?"server":/\bclient\b/i.test(r)?"client":"universal";t.push({content:n[2]??"",kind:"script",attrs:r,context:s,lang:o,start:n.index})}return t}function ph(e){let t=[],i=/^[ \t]*@ts[ \t]*(?:\r?\n|$)/gm,n;while((n=i.exec(e))!==null){let r=i.lastIndex,o=/^[ \t]*@endts[ \t]*(?:\r?\n|$)/gm;o.lastIndex=r;let s=o.exec(e),a=s?.index??e.length;if(t.push({content:e.slice(r,a),kind:"ts",attrs:"",context:"universal",lang:"ts",start:n.index}),!s)break;i.lastIndex=o.lastIndex}return t}function gh(e){return[...mh(e),...ph(e)].sort((t,i)=>t.start-i.start)}function yh(e){if(e.kind==="ts"||e.context!=="universal"||e.lang==="ts")return!0;return/\b(?:defineProps|defineEmits|defineExpose|defineSlots)\b|\bexport\s|\b(?:interface|type)\s+[A-Za-z_$]/.test(e.content)}function Ch(e){let t=/(?:\$?props)\s+as\s+/g,i;while((i=t.exec(e))!==null){let n=t.lastIndex;while(n<e.length&&/\s/.test(e[n]))n++;if(e[n]==="{"){let s=je(e,n,"{","}");if(s!==-1)return e.slice(n,s+1).trim();continue}let r=/^[A-Za-z_$][\w$]*/.exec(e.slice(n))?.[0];if(!r)continue;let o=n+r.length;while(o<e.length&&/\s/.test(e[o]))o++;if(e[o]==="<"){let s=je(e,o,"<",">");if(s!==-1)o=s+1}return e.slice(n,o).trim()}return null}function wh(e){return/\b(?:const|let|var)\s+\$?props\s*:\s*([^=;\n]+)/.exec(e)?.[1]?.trim()??null}function vh(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 Eh(e,t){if(!e||e==="unknown")return t;if(t==="unknown"||e===t)return e;return[...new Set([...e.split(" | "),...t.split(" | ")])].join(" | ")}function bh(e){let t=Zn(e),i=new Map,n=/\$props(?:\.([A-Za-z_$][\w$]*)|\[\s*(['"])([^'"\n]+)\2\s*\])/g,r;while((r=n.exec(e))!==null){if(t.slice(r.index,r.index+6)!=="$props")continue;let o=r[1]??r[3],s=vh(e.slice(n.lastIndex));i.set(o,Eh(i.get(o),s))}if(i.size===0)return null;return{type:`{ ${[...i].map(([o,s])=>`${/^[A-Za-z_$][\w$]*$/.test(o)?o:JSON.stringify(o)}?: ${s}`).join(", ")} }`}}function Sh(e){let t=Pr(e,null);if(t)return t;let i=Ch(e)??wh(e);if(!i)return bh(e);if(/^[A-Za-z_$][\w$]*$/.test(i)){let n=i.replace(/[$]/g,"\\$&");if(new RegExp(`\\bexport\\s+(?:declare\\s+)?(?:interface|type)\\s+${n}\\b`).test(e))return{type:i}}return Pr(`${e}
|
|
111
|
+
defineProps<${i}>()`,null)}function $h(e){return Qn(e)}function Da(e){let t=Zn(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 Ah(e){let t=[],i=0,n=0,r=0;while(r<e.length){let s=e[r],a=Yn(e,r);if(a>r){r=a;continue}if(s==="{"||s==="["||s==="(")n++;else if(s==="}"||s==="]"||s===")")n=Math.max(0,n-1);if((s===";"||s===`
|
|
112
|
+
`)&&n===0){let c=r+1;if(!Da(e.slice(i,c)))t.push([i,c]);i=c}r++}if(i<e.length&&!Da(e.slice(i)))t.push([i,e.length]);let o=e;for(let s=t.length-1;s>=0;s--)o=o.slice(0,t[s][0])+o.slice(t[s][1]);return o}function Fa(e){let t=gh(e).filter(yh).map((S)=>S.content).join(`
|
|
113
|
+
`),i=null,n=eo(t);if(n.passthrough)return t;if(t=n.script,n.options){let S=Ar(n.options,"props");if(S)i=Rr(S)}let r=t,o=$h(t),s=Sh(r),a=s?.type??i??"{}",c=io(r,null),f=ro(r,null),u=vi(r,"defineSlots")?.generic??null,l=s?.inlinedLocal;if(l)o=Tr(o,l.name,l.declText);let y=`DefineComponent<${a}>`,p=[];if(c)p.push(`readonly __stxEmits?: ${c}`);if(u)p.push(`readonly __stxSlots?: ${u}`);if(f)p.push(`readonly __stxExposed?: ${f}`);if(p.length>0)y+=` & { ${p.join(", ")} }`;y=to(y),o=Ah(xr(o,y));let w=["import type { DefineComponent } from '@stacksjs/stx'",`type __DtsxStxComponentType = ${y}`,"const __dtsx_component__: __DtsxStxComponentType = null as unknown as __DtsxStxComponentType","export default __dtsx_component__"];if(o.trim()!=="")w.push(o);return w.join(`
|
|
114
|
+
`)}var Na=pe(()=>{no()});function xh(e){if(e.indexOf("/*")===-1)return e.trim();let t=[],i=0,n=0,r=e.length;while(n<r)if(e.charCodeAt(n)===47&&n+1<r&&e.charCodeAt(n+1)===42){if(n>i)t.push(e.substring(i,n));n+=2;while(n<r-1){if(e.charCodeAt(n)===42&&e.charCodeAt(n+1)===47){n+=2;break}n++}i=n}else n++;if(i<r)t.push(e.substring(i));return t.join("").trim()}function co(){Ir=!0,qe=null}function fo(){Ir=!1;let e=qe;return qe=null,e}function uo(e){let t=e.length;if(t===0)return!1;let i=0;if(e.charCodeAt(i)===45)i++;if(i>=t)return!1;let n=i;while(i<t&&e.charCodeAt(i)>=48&&e.charCodeAt(i)<=57)i++;if(i===n)return!1;if(i<t&&e.charCodeAt(i)===46){i++;let r=i;while(i<t&&e.charCodeAt(i)>=48&&e.charCodeAt(i)<=57)i++;if(i===r)return!1}return i===t}function Th(e){for(let t=0,i=e.length-1;t<i;t++){let n=e.charCodeAt(t);if(n<48||n>57)return!1}return!0}function oo(e,t){let i=0,n=0;while((n=e.indexOf(t,n))!==-1)i++,n+=t.length;return i}function La(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 Or(e){let t=e.trim();if(t.length<3||t.charCodeAt(0)!==60)return!1;if(t.startsWith("<>"))return t.endsWith("</>");let i=t.charCodeAt(1);if(!(i>=65&&i<=90||i>=97&&i<=122||i===36||i===95))return!1;let n=2;while(n<t.length&&La(t.charCodeAt(n)))n++;let r=t.slice(1,n),o=t.charCodeAt(n);if(o>32&&o!==62&&o!==47)return!1;if(t.endsWith("/>"))return!0;let s=t.lastIndexOf("</");if(s===-1)return!1;let a=s+2;while(a<t.length&&La(t.charCodeAt(a)))a++;return t.slice(s+2,a)===r&&t.charCodeAt(a)===62&&a===t.length-1}function kr(e){let t=e.length,i=!1;for(let s=1;s<t;s++)if(e.charCodeAt(s)<=32&&e.charCodeAt(s-1)<=32){i=!0;break}if(!i)for(let s=0;s<t;s++){let a=e.charCodeAt(s);if(a===10||a===13||a===9){i=!0;break}}if(!i)return e;let n=[],r=-1,o=!1;for(let s=0;s<t;s++)if(e.charCodeAt(s)<=32){if(!o){if(r>=0)n.push(e.substring(r,s));n.push(" "),o=!0,r=-1}}else{if(o||r<0)r=s;o=!1}if(r>=0)n.push(e.substring(r));return n.join("")}function Ie(e,t=!1,i=!1,n=0){if(!e||typeof e!=="string")return"unknown";if(n>=20)return"unknown";let r=e.trim();if(Or(r))return"JSX.Element";if(r.startsWith("BigInt("))return"bigint";if(r.startsWith("Symbol.for("))return"symbol";if(r.includes(".raw`")||r.includes("String.raw`"))return"string";if(r.startsWith("`")&&r.endsWith("`")){if(!t||r.includes("${")||r.includes(`
|
|
115
|
+
`)||r.includes("\r"))return"string";return r}if(r.charCodeAt(0)===39||r.charCodeAt(0)===34){let s=Rh(r);if(s!==null){if(s==="string"||!t)return"string";return s}}if(uo(r)){if(!t)return"number";return r}if(r==="true"||r==="false"){if(!t)return"boolean";return r}if(r==="null")return"null";if(r==="undefined")return"undefined";if(r.startsWith("[")&&r.endsWith("]"))return so(r,t,n+1);if(r.startsWith("{")&&r.endsWith("}"))return jh(r,t,n+1);if(r.startsWith("class ")||r.startsWith("class{"))return Bh(r);if(r.startsWith("new "))return Wh(r);if(r.endsWith("as const")){let s=r.slice(0,-8).trim();if(s.startsWith("[")&&s.endsWith("]")){let a=s.slice(1,-1).trim();if(!a)return"readonly []";let c=Mr(a),f=[];for(let u=0;u<c.length;u++)f.push(Ie(c[u].trim(),!0,!1,n+1));return`readonly [${f.join(", ")}]`}return Ie(s,!0,i,n+1)}if(Dr(r)!==-1||r.startsWith("function")||r.startsWith("async"))return qa(r,i,n,t);if(r.startsWith("`")&&r.endsWith("`"))return Lh(r,t);if(r.startsWith("Promise."))return Ha(r,t,n);if(r.startsWith("await "))return"unknown";if(r.charCodeAt(r.length-1)===110&&r.length>1&&Th(r)){if(t)return r;return"bigint"}if(r.startsWith("Symbol(")||r==="Symbol.for")return"symbol";let o=za(r);if(o!==null)return o;if(Dh(r))return"boolean";if(Mh(r))return"number";return"unknown"}function Wa(e){let t=e.charCodeAt(0);if(t!==39&&t!==34)return!1;return Nt(e,0,t)===e.length}function Rh(e){if(Wa(e))return e;let t=Ph(e);if(t.length<2)return null;let i=!1,n=!0,r="";for(let o of t){let s=o.trim();if(Wa(s))i=!0,r+=Oh(s);else n=!1}if(n)return kh(r);if(i)return"string";return null}function Ph(e){let t=[],i=0,n=0,r=0;while(r<e.length){let o=e.charCodeAt(r);if(o===39||o===34||o===96){r=Nt(e,r,o);continue}if(o===40||o===91||o===123)i++;else if(o===41||o===93||o===125)i--;else if(o===43&&i===0)t.push(e.slice(n,r)),n=r+1;r++}return t.push(e.slice(n)),t}function Oh(e){return e.slice(1,-1).replace(/\\(.)/g,(t,i)=>{if(i==="n")return`
|
|
116
|
+
`;if(i==="t")return"\t";if(i==="r")return"\r";if(i==="0")return"\x00";return i})}function kh(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function Mh(e){if(e==="")return!1;let t=!1,i=!1;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>=48&&r<=57){t=!0;continue}if(r===43||r===45||r===42||r===47||r===37){i=!0;continue}if(r===46||r===40||r===41||r<=32)continue;return!1}return t&&i}function Dh(e){let t=0;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);if(n===34||n===39||n===96){i=Nt(e,i,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("===",i)||e.startsWith("!==",i)||e.startsWith("==",i)||e.startsWith("!=",i)||e.startsWith(">=",i)||e.startsWith("<=",i))return!0;if((n===62||n===60)&&e.charCodeAt(i-1)!==61&&e.charCodeAt(i+1)!==61)return!0}return!1}function Ih(e,t=!1,i=0){return Ie(e,t,!0,i)}function Ei(e,t=!1,i=""){let n=Ua(i),r=[],o=!1,s=0;while(s<e.length){let c=e.charCodeAt(s);if(c===34||c===39||c===96){s=Nt(e,s,c);continue}if(c===47&&e.charCodeAt(s+1)===47){s+=2;while(s<e.length&&e.charCodeAt(s)!==10&&e.charCodeAt(s)!==13)s++;continue}if(c===47&&e.charCodeAt(s+1)===42){let f=e.indexOf("*/",s+2);s=f===-1?e.length:f+2;continue}if(e.startsWith("function",s)&&Ba(e,s,8)||e.startsWith("class",s)&&Ba(e,s,5)){let f=Nh(e,s);if(f!==-1){s=Ga(e,f);continue}}if(c===61&&e.charCodeAt(s+1)===62){let f=s+2;while(f<e.length&&e.charCodeAt(f)<=32)f++;if(e.charCodeAt(f)===123){s=Ga(e,f);continue}}if(e.startsWith("return",s)&&(s===0||!bt(e.charCodeAt(s-1)))&&!bt(e.charCodeAt(s+6))){s+=6;let f=!1;while(s<e.length&&e.charCodeAt(s)<=32){let x=e.charCodeAt(s);if(x===10||x===13)f=!0;s++}if(f||s>=e.length||e.charCodeAt(s)===59||e.charCodeAt(s)===125){o=!0;continue}let u=s,l=0,y=0,p=0;while(s<e.length){let x=e.charCodeAt(s);if(x===34||x===39||x===96){s=Nt(e,s,x);continue}if(x===47&&e.charCodeAt(s+1)===47)break;if(x===47&&e.charCodeAt(s+1)===42){let E=e.indexOf("*/",s+2);s=E===-1?e.length:E+2;continue}if(x===40)l++;else if(x===41)l--;else if(x===91)y++;else if(x===93)y--;else if(x===123)p++;else if(x===125){if(p===0&&l===0&&y===0)break;p--}else if(x===59&&l===0&&y===0&&p===0)break;else if((x===10||x===13)&&l===0&&y===0&&p===0){let E=s+1;while(E<e.length&&e.charCodeAt(E)<=32)E++;if(e.startsWith("return",E)&&!bt(e.charCodeAt(E+6)))break}s++}let w=e.slice(u,s).trim(),S=It(w,n);if(!r.includes(S))r.push(S);continue}s++}if(o&&!r.includes("undefined"))r.push("undefined");let a=r.includes("unknown")?"unknown":r.length===0?"void":r.join(" | ");return t&&!a.startsWith("Promise<")?`Promise<${a}>`:a}function Ua(e){let t=new Map,i=e.startsWith("(")&&e.endsWith(")")?e.slice(1,-1):e,n=0,r=0,o=0;for(let s=0;s<=i.length;s++){let a=i.charCodeAt(s);if(a===40||a===91||a===123)r++;else if(a===41||a===93||a===125)r--;else if(a===60)o++;else if(a===62&&i.charCodeAt(s-1)!==61&&o>0)o--;if(s!==i.length&&(a!==44||r!==0||o!==0))continue;let c=i.slice(n,s).trim(),f=c.indexOf(":");if(f!==-1){let u=c.slice(0,f).trim().replace(/^\.\.\./,"").replace(/\?$/,""),l=c.slice(f+1).trim(),y=l.indexOf("=");if(y!==-1)l=l.slice(0,y).trim();if(bi(u)&&l)t.set(u,l)}n=s+1}return t}function It(e,t){let i=e.trim();while(Ka(i))i=i.slice(1,-1).trim();if(Or(i))return"JSX.Element";if(i.startsWith("await ")){let o=It(i.slice(6),t);return o.startsWith("Promise<")&&o.endsWith(">")?o.slice(8,-1):o}if(t.has(i))return t.get(i);if(i.startsWith("!"))return"boolean";if(i.startsWith("fetch("))return"Promise<Response>";let n=Fh(i);if(n){let o=It(n.whenTrue,t),s=It(n.whenFalse,t);return o===s?o:`${o} | ${s}`}if(["===","!==","==","!=",">=","<="].some((o)=>i.includes(o))||i.includes(" > ")||i.includes(" < "))return"boolean";let r=0;for(let o=i.length-1;o>=0;o--){let s=i.charCodeAt(o);if(s===41||s===93||s===125)r++;else if(s===40||s===91||s===123)r--;else if(r===0&&(s===43||s===45||s===42||s===47||s===37)){let a=It(i.slice(0,o),t),c=It(i.slice(o+1),t);if(s===43&&(a==="string"||c==="string"))return"string";if(a==="number"&&c==="number")return"number";break}}return Ie(i,!1).replace(/\btypeof\s+[$A-Z_a-z][$\w]*/g,(o)=>{let s=o.slice(7);return t.get(s)??"unknown"})}function Ka(e){if(!e.startsWith("(")||!e.endsWith(")"))return!1;let t=0;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);if(n===40)t++;else if(n===41&&--t===0)return i===e.length-1}return!1}function Fh(e){let t=0,i=-1;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r===40||r===91||r===123)t++;else if(r===41||r===93||r===125)t--;else if(r===63&&t===0&&e.charCodeAt(n+1)!==63)i=n;else if(r===58&&t===0&&i!==-1)return{whenTrue:e.slice(i+1,n),whenFalse:e.slice(n+1)}}return null}function Ba(e,t,i){return(t===0||!bt(e.charCodeAt(t-1)))&&!bt(e.charCodeAt(t+i))}function Nh(e,t){for(let i=t;i<e.length;i++){let n=e.charCodeAt(i);if(n===34||n===39||n===96){i=Nt(e,i,n)-1;continue}if(n===123)return i;if(n===59)return-1}return-1}function Ga(e,t){let i=1,n=t+1;while(n<e.length&&i>0){let r=e.charCodeAt(n);if(r===34||r===39||r===96){n=Nt(e,n,r);continue}if(r===47&&e.charCodeAt(n+1)===47){n+=2;while(n<e.length&&e.charCodeAt(n)!==10&&e.charCodeAt(n)!==13)n++;continue}if(r===47&&e.charCodeAt(n+1)===42){let o=e.indexOf("*/",n+2);n=o===-1?e.length:o+2;continue}if(r===123)i++;else if(r===125)i--;n++}return n}function Nt(e,t,i){let n=t+1;while(n<e.length){let r=e.charCodeAt(n);if(r===92){n+=2;continue}if(n++,r===i)break}return n}function Lh(e,t){if(e.includes(".raw`")||e.includes("String.raw`"))return"string";if(!t||e.includes("${")||e.includes(`
|
|
117
|
+
`)||e.includes("\r"))return"string";return e}function Wh(e){let t=4;while(t<e.length&&e.charCodeAt(t)<=32)t++;let i=t,n=e.charCodeAt(t);if(n<65||n>90)return"unknown";while(t<e.length&&(bt(e.charCodeAt(t))||e.charCodeAt(t)===46))t++;if(t===i)return"unknown";let r=e.slice(i,t);{let o=e.slice(t),s=o;if(o.startsWith("<")){let c=0,f=-1;for(let u=0;u<o.length;u++)if(o[u]==="<")c++;else if(o[u]===">"){if(c--,c===0){f=u;break}}if(f!==-1){let u=o.slice(0,f+1);s=o.slice(f+1);let l=s.indexOf("(");if(l!==-1){let y=0,p=-1;for(let w=l;w<s.length;w++)if(s[w]==="(")y++;else if(s[w]===")"){if(y--,y===0){p=w;break}}if(p!==-1){if(s.slice(p+1).trimStart().startsWith("."))return"unknown"}}return`${r}${u}`}}let a=s.indexOf("(");if(a!==-1){let c=0,f=-1;for(let u=a;u<s.length;u++)if(s[u]==="(")c++;else if(s[u]===")"){if(c--,c===0){f=u;break}}if(f!==-1){if(s.slice(f+1).trimStart().startsWith("."))return"unknown"}}switch(r){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 r}}return"unknown"}function Bh(e){return"{ new (...args: any[]): any }"}function Ha(e,t,i=0){if(e.startsWith("Promise.resolve(")){let n=e.indexOf(")",16);if(n!==-1){let r=e.slice(16,n).trim();if(r)return`Promise<${Ie(r,t,!1,i+1)}>`}return"Promise<unknown>"}if(e.startsWith("Promise.reject("))return"Promise<never>";if(e.startsWith("Promise.all(")){let n=e.indexOf("[",12),r=e.lastIndexOf("]");if(n!==-1&&r>n){let o=e.slice(n+1,r).trim(),s=Mr(o),a=[];for(let c=0;c<s.length;c++){let f=s[c].trim();if(f.startsWith("Promise.resolve(")){let u=Ha(f,t,i+1),l=u.indexOf("<"),y=u.lastIndexOf(">");a.push(l!==-1&&y>l?u.slice(l+1,y):"unknown")}else a.push(Ie(f,t,!1,i+1))}return`Promise<[${a.join(", ")}]>`}return"Promise<unknown[]>"}return"Promise<unknown>"}function so(e,t,i=0){let n=e.slice(1,-1).trim();if(!n)return"never[]";if(i>=20)return"unknown[]";let r=Mr(n),o=!1;for(let y=0;y<r.length;y++){let p=r[y],w=p.length;while(w>0&&p.charCodeAt(w-1)<=32)w--;if(w>=8&&p.slice(w-8,w)==="as const"){o=!0;break}}if(o){let y=[];for(let p=0;p<r.length;p++){let w=r[p].trim();if(w.endsWith("as const")){let S=w.slice(0,-8).trim();if(S.startsWith("[")&&S.endsWith("]")){let x=S.slice(1,-1).trim(),E=Mr(x),k=[];for(let I=0;I<E.length;I++)k.push(Ie(E[I].trim(),!0,!1,i+1));y.push(`readonly [${k.join(", ")}]`)}else y.push(Ie(S,!0,!1,i+1))}else if(w.startsWith("[")&&w.endsWith("]"))y.push(so(w,!0,i+1));else y.push(Ie(w,!0,!1,i+1))}return`readonly [
|
|
118
|
+
${y.join(` |
|
|
119
|
+
`)}
|
|
120
|
+
]`}let s=Ir&&!t,a=[],c=[];for(let y of r){let p=y.trim(),w=qe;if(qe=null,p.startsWith("...")){let S=p.slice(3).trim(),x=Ie(S,!1,!1,i+1);if(x.endsWith("[]"))a.push(x.slice(0,-2));else if(x.startsWith("readonly [")&&x.endsWith("]"))a.push(x.slice(10,-1));else if(Si(S))a.push(`(typeof ${S})[number]`);else a.push("unknown")}else if(p.startsWith("[")&&p.endsWith("]"))a.push(so(p,t,i+1));else a.push(Ih(p,t,i+1));if(s)c.push(qe);qe=w}if(s)if(lo(e))qe=kr(e);else{let y=[];for(let p=0;p<r.length;p++){let w=r[p].trim();if(w.endsWith("as const"))continue;if(ao(w)||w==="null"||w==="undefined")y.push(w);else if(w.startsWith("[")&&lo(w))y.push(kr(w));else if(w.startsWith("{")){if(c[p])y.push(c[p])}else{let S=Ie(w,!1,!1,0);if(S!=="unknown")y.push(S)}}if(y.length>0)qe=`[${y.join(", ")}]`}if(t)return`readonly [${a.join(", ")}]`;let f=new Set,u=[],l=!0;for(let y of a){if(!f.has(y))f.add(y),u.push(y);if(l){if(!(uo(y)||y==="true"||y==="false"||y.charCodeAt(0)===34&&y.charCodeAt(y.length-1)===34||y.charCodeAt(0)===39&&y.charCodeAt(y.length-1)===39))l=!1}}if(l&&a.length<=10)return`readonly [${a.join(", ")}]`;if(u.length===1)return`${u[0]}[]`;return`(${u.join(" | ")})[]`}function Mr(e){let t=[],i=0,n=0,r=!1,o=0;for(let a=0;a<e.length;a++){let c=e.charCodeAt(a);if(!r&&(c===34||c===39||c===96))r=!0,o=c;else if(r&&c===o&&(a===0||e.charCodeAt(a-1)!==92))r=!1;if(!r){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(i,a).trim();if(f)t.push(f);i=a+1;continue}}}let s=e.substring(i).trim();if(s)t.push(s);return t}function ao(e){if(uo(e))return!0;if(e==="true"||e==="false")return!0;if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return!0;return!1}function Gh(e){return e==="number"||e==="string"||e==="boolean"}function lo(e){let t=!1,i=0,n=e.length;for(let r=0;r<n;r++){let o=e.charCodeAt(r);if(t){if(o===92){r++;continue}if(o===i)t=!1;continue}if(o===34||o===39||o===96){t=!0,i=o;continue}if(o===61&&r+1<n&&e.charCodeAt(r+1)===62)return!1;if(o>=97&&o<=122){let s=r;while(r<n&&(e.charCodeAt(r)>=97&&e.charCodeAt(r)<=122||e.charCodeAt(r)>=65&&e.charCodeAt(r)<=90||e.charCodeAt(r)>=48&&e.charCodeAt(r)<=57||e.charCodeAt(r)===95||e.charCodeAt(r)===36))r++;let a=e.slice(s,r);if(a==="new"||a==="async"||a==="await"||a==="function"||a==="yield"||a==="console"||a==="process")return!1;let c=r;while(c<n&&e.charCodeAt(c)<=32)c++;if(c<n&&e.charCodeAt(c)===40)return!1;r--}}return!0}function jh(e,t,i=0){let n=e.slice(1,-1).trim();if(!n)return"{}";if(i>=20)return"Record<string, unknown>";let r=Hh(n),o=[],s=[],a=Ir&&!t,c=[];for(let[l,y]of r){let{comments:p,key:w}=Kh(l),S=p?`${p}
|
|
121
|
+
`:"",x=w,E=!1;if(w==="..."){let D=y.trim(),Y=Si(D)?`typeof ${D}`:Ie(D,t,!1,i+1);if(Y!=="unknown")s.push(Y);if(a&&(Si(D)||D.startsWith("{")))c.push(`...${kr(D)}`);continue}let k=qe;qe=null;let I,M=y.trim();if(M===w&&bi(M))I=`typeof ${M}`;else if(qh(M)){E=!0;let D=Yh(w);if(D){x=D.name;let Y="";if(M.startsWith("async "))Y="async ";if(M.charCodeAt(Y.length)===42)Y+="*";I=_a(D.name,Y+D.typeParams+M.slice(Y.length))}else I=_a(w,M)}else if(I=Ie(y,t,!1,i+1),I.includes("=>")||I.includes("function")||I.includes("async"))I=ja(I);let J=qe;qe=k;let W=y.trim(),R=zh(w);if(R){let D=Jh(R.kind,R.name,I);if(D){o.push(`${S}${D}`);continue}}if(!t&&Gh(I)&&ao(W))o.push(`${S}/** @defaultValue ${W} */
|
|
122
|
+
${x}: ${I}`);else o.push(`${S}${x}: ${I}`);if(a){let D=xh(x);if(W.endsWith("as const"));else if(ao(W))c.push(`${D}: ${W}`);else if(W.startsWith("[")&&lo(W))c.push(`${D}: ${kr(W)}`);else if(W.startsWith("{")){if(J)c.push(`${D}: ${J}`)}else if(E)c.push(`${D}: ${ja(I)}`);else if(!W.startsWith("[")&&(W.includes("=>")||W.startsWith("function")||W.startsWith("async"))){let Y=qa(W,!1,0,!0);c.push(`${D}: ${Y}`)}}}if(a&&c.length>0){let l=i>0?(i-1)/2:0,y=`{ ${c.join(", ")} }`;if(y.length<=80)qe=y;else{let p=" ".repeat((l+1)*2),w=" ".repeat(l*2);qe=`{
|
|
123
|
+
${p}${c.join(`,
|
|
124
|
+
${p}`)}
|
|
125
|
+
${w}}`}}let f=o.length>0?`{
|
|
126
|
+
${o.join(`;
|
|
127
|
+
`)}
|
|
128
|
+
}`:"{}";if(s.length===0)return f;let u=s[0];for(let l=1;l<s.length;l++)u=`Omit<${u}, keyof ${s[l]}> & ${s[l]}`;return o.length>0?`Omit<${u}, keyof ${f}> & ${f}`:u}function bi(e){if(!e)return!1;let t=e.charCodeAt(0);if(!(t>=65&&t<=90||t>=97&&t<=122||t===95||t===36||t>127))return!1;for(let i=1;i<e.length;i++)if(!bt(e.charCodeAt(i)))return!1;return!0}function Si(e){let t=e.split(".");return t.length>0&&t.every(bi)}function _h(e){let t=!1,i="";for(let n=0;n<e.length;n++){let r=e[n];if(t){if(r==="\\")n++;else if(r===i)t=!1;continue}if(r==='"'||r==="'"||r==="`"){t=!0,i=r;continue}if(r==="(")return n;if(r==="<"){let o=st(e,n,"<",">");if(o!==-1)n=o}}return-1}function za(e){if(e.length<3||!e.endsWith(")"))return null;let t=_h(e);if(t===-1||st(e,t,"(",")")!==e.length-1)return null;let i=e.slice(0,t).trim(),n=!1;if(i.endsWith("?."))n=!0,i=i.slice(0,-2).trim();let r=i,o=!1,s=i.indexOf("<");if(s!==-1){if(st(i,s,"<",">")!==i.length-1)return null;r=i.slice(0,s).trim(),o=!0}if(!Si(r))return null;let a=e.slice(t+1,-1).trim(),c=Dr(a)!==-1||a.startsWith("function")||a.startsWith("async function"),f=Si(a),u=!c&&a.endsWith(")")&&za(a)!==null;if(!o&&!n&&!c&&!f&&!u)return null;let l=`ReturnType<typeof ${i}>`;return n?`${l} | undefined`:l}function ja(e){let t=e.split(`
|
|
129
|
+
`).map((f)=>Ja(f)).join(`
|
|
130
|
+
`),i=t.indexOf("async");if(i!==-1){let f=i>0?t.charCodeAt(i-1):32,u=i+5<t.length?t.charCodeAt(i+5):32;if(!bt(f)&&!bt(u))t=(t.slice(0,i)+t.slice(i+5)).trim()}let n=t.indexOf("(");if(n!==-1){let f=st(t,n,"(",")");if(f!==-1){let u=t.slice(n,f+1),l=Ft(u);t=t.slice(0,n)+l+t.slice(f+1)}}let r=t.length,o="",s=[],a=!1,c=!1;for(let f=0;f<r;f++){let u=t.charCodeAt(f);if(u===123||u===40)s.push(u);else if(u===125||u===41)s.pop();if(u<=32){if(a=!0,u===10||u===13)c=!0;continue}if(a&&o.length>0){let l=(s.length>0?s[s.length-1]:0)===123;if(c&&l){let y=o.charCodeAt(o.length-1),p=y===59||y===44||y===123||u===125,w=o.length>=2&&o.charCodeAt(o.length-1)===47&&o.charCodeAt(o.length-2)===42;if(!p&&!w)o+="; ";else o+=" "}else o+=" "}a=!1,c=!1,o+=t[f]}return o.trim()}function bt(e){return e>=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57||e===95||e===36}function Ft(e){let t=e.trim(),i,n=!1;if(t.startsWith("(")&&t.endsWith(")"))i=t.slice(1,-1),n=!0;else i=t;let r=i.trim();if(!r)return n?"()":"";let o=!1;{let w=0;for(let S=0;S<r.length;S++){let x=r.charCodeAt(S);if(x===40||x===60||x===91||x===123)w++;else if(x===41||x===93||x===125||x===62&&r.charCodeAt(S-1)!==61)w--;else if(w===0&&x===61){let E=S>0?r.charCodeAt(S-1):0,k=S+1<r.length?r.charCodeAt(S+1):0;if(E!==61&&E!==33&&E!==60&&E!==62&&k!==61&&k!==62){o=!0;break}}}}if(!o)return t;let s=[],a=[],c=0,f=0,u=!1,l=0;for(let w=0;w<=r.length;w++){if(w===r.length){s.push(r.slice(c));break}let S=r.charCodeAt(w);if(u){if(S===92){w++;continue}if(S===l)u=!1;continue}if(S===47&&w+1<r.length){let x=r.charCodeAt(w+1);if(x===42){w+=2;while(w+1<r.length&&!(r.charCodeAt(w)===42&&r.charCodeAt(w+1)===47))w++;w++;continue}if(x===47){while(w<r.length&&r.charCodeAt(w)!==10)w++;continue}}if(S===39||S===34||S===96){u=!0,l=S;continue}if(S===40||S===60||S===91||S===123)f++;else if(S===41||S===93||S===125||S===62&&r.charCodeAt(w-1)!==61)f--;else if(S===44&&f===0){s.push(r.slice(c,w));let x=",",E=w+1;while(E<r.length&&r.charCodeAt(E)<=32)x+=r[E],E++;a.push(x),c=E}}let y=[];for(let w of s){let S=w.trim();if(!S){y.push(w);continue}if(S.startsWith("//"))continue;let x=Ja(S),E=w.slice(0,w.length-w.trimStart().length);y.push(E+Vh(x))}let p=y[0]||"";for(let w=1;w<y.length;w++)p+=(a[w-1]||", ")+y[w];return n?`(${p})`:p}function Ja(e){let t=!1,i=0;for(let n=0;n<e.length-1;n++){let r=e.charCodeAt(n);if(t){if(r===92){n++;continue}if(r===i)t=!1;continue}if(r===39||r===34||r===96){t=!0,i=r;continue}if(r===47&&e.charCodeAt(n+1)===47)return e.slice(0,n).trimEnd()}return e}function Vh(e){if(e.startsWith("..."))return e;let t=-1,i=-1,n=0,r=!1,o=0;for(let a=0;a<e.length;a++){let c=e.charCodeAt(a);if(r){if(c===92){a++;continue}if(c===o)r=!1;continue}if(c===47&&a+1<e.length){let f=e.charCodeAt(a+1);if(f===42){a+=2;while(a+1<e.length&&!(e.charCodeAt(a)===42&&e.charCodeAt(a+1)===47))a++;a++;continue}if(f===47){while(a<e.length&&e.charCodeAt(a)!==10)a++;continue}}if(c===39||c===34||c===96){r=!0,o=c;continue}if(c===40||c===60||c===91||c===123)n++;else if(c===41||c===93||c===125||c===62&&e.charCodeAt(a-1)!==61)n--;else if(n===0){if(c===58&&t===-1)t=a;else if(c===61&&i===-1&&(a===0||e.charCodeAt(a-1)!==61)&&(a+1>=e.length||e.charCodeAt(a+1)!==61&&e.charCodeAt(a+1)!==62))i=a}}let s=i!==-1;if(t!==-1&&(i===-1||t<i)){let a=e.slice(0,t).trim(),c=i!==-1?e.slice(t+1,i).trim():e.slice(t+1).trim(),f=s&&!a.endsWith("?")?"?":"";return`${a}${f}: ${c}`}else if(i!==-1){let a=e.slice(0,i).trim(),c=!a.endsWith("?")?"?":"",f=e.slice(i+1).trim(),u="unknown";if(f==="true"||f==="false")u="boolean";else if(/^-?\d+(\.\d+)?$/.test(f))u="number";else if(f.startsWith("'")&&f.endsWith("'")||f.startsWith('"')&&f.endsWith('"'))u="string";else if(f.startsWith("["))u="unknown[]";else if(f.startsWith("{"))u="Record<string, unknown>";return`${a}${c}: ${u}`}return e}function Uh(e){let t=0,i=e.length;while(t<i){while(t<i&&(e.charCodeAt(t)===32||e.charCodeAt(t)===9||e.charCodeAt(t)===10||e.charCodeAt(t)===13))t++;if(t+1<i&&e.charCodeAt(t)===47&&e.charCodeAt(t+1)===42){t+=2;while(t+1<i&&!(e.charCodeAt(t)===42&&e.charCodeAt(t+1)===47))t++;t+=2;continue}break}return t}function Kh(e){let t=[],i=0,n=e.length;while(i<n){while(i<n&&e.charCodeAt(i)<=32)i++;if(i+1>=n||e.charCodeAt(i)!==47||e.charCodeAt(i+1)!==42)break;let r=i;i+=2;while(i+1<n&&!(e.charCodeAt(i)===42&&e.charCodeAt(i+1)===47))i++;i=Math.min(i+2,n),t.push(e.slice(r,i).trim())}return{comments:t.join(`
|
|
131
|
+
`),key:e.slice(i).trim()}}function Hh(e){let t=[],i="",n="",r=0,o=!1,s="",a=!0,c=!1,f=0,u=!1,l=!1,y=0,p=!1,w=!1;for(let S=0;S<e.length;S++){let x=e.charCodeAt(S),E=S>0?e.charCodeAt(S-1):0,k=S<e.length-1?e.charCodeAt(S+1):0;if(!o&&!c&&x===47&&k===47){S+=2;while(S<e.length&&e.charCodeAt(S)!==10)S++;continue}if(!o&&!c&&x===47&&k===42){c=!0,f=1,i+="/*",S++;continue}else if(c&&x===42&&k===47){if(f--,i+="*/",S++,f===0)c=!1;continue}else if(c&&x===47&&k===42){f++,i+="/*",S++;continue}let I=e[S];if(!o&&(x===34||x===39||x===96))o=!0,s=I,i+=I;else if(o&&I===s&&E!==92)o=!1,i+=I;else if(!o&&!c)if(x===40&&r===0&&a&&y===0){n=i.trim();let M=Uh(n),J=M>0?n.slice(0,M):"",W=n.slice(M),R="";if(W.startsWith("async ")||W.startsWith("async\t")||W.startsWith(`async
|
|
132
|
+
`))W=W.slice(6).trimStart(),R="async ";if(W.startsWith("*"))W=W.slice(1).trimStart(),R+="*";n=J+W,i=R+I,a=!1,p=!0,w=!1,r=1}else if(x===123||x===91||x===40){if(r++,i+=I,w&&x===123)w=!1}else if(x===125||x===93||x===41){if(r--,i+=I,x===41&&r===0&&!a&&!p)u=!0;if(p){if(x===41&&r===0&&!w)w=!0;else if(x===125&&r===0)p=!1,w=!1}}else if(x===58&&r===0&&a&&y===0)n=i.trim(),i="",a=!1;else if(x===58&&r===0&&u)l=!0,i+=I;else if(x===60&&l)y++,i+=I;else if(x===60&&a&&r===0)y++,i+=I;else if(x===62&&y>0&&E!==61)y--,i+=I;else if(x===61&&k===62&&l&&y===0)l=!1,u=!1,i+=I;else if(x===44&&r===0&&y===0&&!w){if(n&&i.trim()){let M=i.trim();t.push([n,M])}else if(a&&i.trim()){let M=i.trim();if(bi(M))t.push([M,M]);else if(M.startsWith("...")&&M.length>3)t.push(["...",M.slice(3).trim()])}i="",n="",a=!0,u=!1,l=!1,y=0}else i+=I;else i+=I}if(n&&i.trim()){let S=i.trim();t.push([n,S])}else if(a&&i.trim()){let S=i.trim();if(bi(S))t.push([S,S]);else if(S.startsWith("...")&&S.length>3)t.push(["...",S.slice(3).trim()])}return t}function zh(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 Jh(e,t,i){let n=i.trim();if(n.charCodeAt(0)!==40)return null;let r=st(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 a=s.slice(2).trim();if(e==="get")return`get ${t}(): ${a||"unknown"}`;return`set ${t}(${o})`}function qh(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=ho(o,1);if(s?.kind==="arrow")return!1;if(s?.kind==="body")return!0}return!1}}}return!1}function Yh(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 _a(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 y=0,p=-1;for(let w=0;w<i.length;w++)if(i.charCodeAt(w)===60)y++;else if(i.charCodeAt(w)===62&&!(w>0&&i.charCodeAt(w-1)===61)){if(y--,y===0){p=w;break}}if(p!==-1)o=i.slice(0,p+1),i=i.slice(p+1).trimStart()}let s=i.indexOf("("),a=st(i,s,"(",")");if(s===-1||a===-1)return"() => unknown";let c=i.slice(s,a+1),f="unknown",u=i.slice(a+1).trimStart();if(u.charCodeAt(0)===58){let y=u.slice(1),p=ho(y,0);if(p)f=y.slice(0,p.index).trim();else f=y.trim()}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 l=Ft(c);return`${o}${l} => ${f}`}function ho(e,t){let i=0,n=0,r=0,o=0,s=!1,a=0;for(let c=t;c<e.length;c++){let f=e.charCodeAt(c);if(s){if(f===92)c++;else if(f===a)s=!1;continue}if(f===34||f===39||f===96){s=!0,a=f;continue}if(f===40)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,l=e.slice(t,c).trimEnd(),y=l.charCodeAt(l.length-1),p=l.length===0||y===38||y===124||y===40||y===44||y===58||y===61||y===91;if(u||p)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 st(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 Dr(e){let t=0,i=0,n=!1,r="";for(let o=0;o<e.length-1;o++){let s=e[o],a=e[o+1],c=o>0?e[o-1]:"";if(!n&&(s==='"'||s==="'"||s==="`"))n=!0,r=s;else if(n&&s===r&&c!=="\\")n=!1;if(!n){if(s==="<"){let f=st(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==="="&&a===">"&&t===0&&i===0)return o}}return-1}function qa(e,t=!1,i=0,n=!0){let r=e.trim();if(r.length>200&&oo(r,"=>")>2&&oo(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(),a=Dr(s);if(a===-1)return t?"(() => Promise<unknown>)":"() => Promise<unknown>";let c=s.substring(0,a).trim(),f=s.substring(a+2).trim(),u=Va(c),{params:l,returnType:y}=u;if(l=Ft(l),l==="()"||l==="")l="()";else if(!l.startsWith("("))l=`(${l})`;let p=y;if(p);else if(f.startsWith("{"))p=Ei(f.slice(1,f.endsWith("}")?-1:void 0),!0,l);else p=Ie(f,n,!1,i+1);let w=`${l} => ${y||p.startsWith("Promise<")?p:`Promise<${p}>`}`;return t?`(${w})`:w}if(r.includes("=>")){let s="",a=r;if(r.startsWith("<")){let x=st(r,0,"<",">");if(x!==-1)s=r.substring(0,x+1),a=r.substring(x+1).trim()}let c=Dr(a);if(c===-1)return t?"(() => unknown)":"() => unknown";let f=a.substring(0,c).trim(),u=a.substring(c+2).trim(),l=Va(f),{params:y,returnType:p}=l;if(y=Ft(y),y==="()"||y==="")y="()";else if(!y.startsWith("("))y=`(${y})`;let w="unknown";if(p)w=p;else if(u.startsWith("{"))w=Ei(u.slice(1,u.endsWith("}")?-1:void 0),!1,y);else if(Or(u)||Ka(u)&&Or(u.slice(1,-1).trim()))w="JSX.Element";else if(u.includes("=>")){let x=u.trimStart(),E=x.indexOf("("),k=E!==-1?st(x,E,"(",")"):-1,I=k!==-1?x.indexOf("=>",k):-1;if(E===0&&k!==-1&&I!==-1){let M=x.substring(E+1,k).trim(),J=Ft(M);if(s.includes("T")&&J.includes("T"))w=`(${J}) => T`;else w=`(${J}) => any`}else w="any"}else if(t)w="unknown";else w=It(u,Ua(y));let S=`${s}${y} => ${w}`;return t?`(${S})`:S}if(r.startsWith("function")){let s=8,a=r.length;while(s<a&&r.charCodeAt(s)<=32)s++;let c=!1;if(s<a&&r.charCodeAt(s)===42){c=!0,s++;while(s<a&&r.charCodeAt(s)<=32)s++}let f="";if(s<a&&r.charCodeAt(s)===60){let y=s,p=1;s++;while(s<a&&p>0){let w=r.charCodeAt(s);if(w===60)p++;else if(w===62&&r.charCodeAt(s-1)!==61)p--;s++}f=r.substring(y,s);while(s<a&&r.charCodeAt(s)<=32)s++}let u=r.indexOf("(",s);if(u!==-1){let y=1,p=u+1;while(p<a&&y>0){let I=r.charCodeAt(p);if(I===40)y++;else if(I===41)y--;p++}let w=r.substring(u+1,p-1).trim(),S=w?Ft(`(${w})`):"()";if(c){let I=r.substring(p).trim(),M=I.indexOf("Generator<");if(M!==-1){let W=M+10,R=I.indexOf(">",W);if(R!==-1){let D=I.substring(W,R),Y=`${f}${S} => Generator<${D}>`;return t?`(${Y})`:Y}}let J=`${f}${S} => Generator<any, any, any>`;return t?`(${J})`:J}let x="unknown",E=r.substring(p).trimStart();if(E.charCodeAt(0)===58){let I=E.slice(1),M=ho(I,0),J=(M?I.slice(0,M.index):I).trim();if(J)x=J}let k=`${f}${S} => ${x}`;return t?`(${k})`:k}let l="(...args: any[]) => unknown";return t?`(${l})`:l}if(r.includes("=>")&&r.includes("(")&&r.includes(")")){if(r.length>100||oo(r,"=>")>2){let s="";if(r.charCodeAt(0)===60){let l=st(r,0,"<",">");if(l!==-1)s=r.substring(0,l+1)}let a=r.indexOf("("),c=a!==-1?st(r,a,"(",")"):-1,f=a!==-1&&c!==-1?r.substring(a,c+1):"(...args: any[])";f=Ft(f);let u=`${s}${f} => any`;return t?`(${u})`:u}return t?`(${r})`:r}let o="() => unknown";return t?`(${o})`:o}function Va(e){let t=e.trim();if(!t.startsWith("("))return{params:t,returnType:""};let i=st(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 Ya(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 Za(e){let t=e.lastIndexOf(" satisfies ");if(t===-1)return null;let i=e.slice(t+11).trim();if(i.endsWith(";"))i=i.slice(0,-1).trim();return i||null}var Ir=!1,qe=null;var mo=()=>{};function Be(e){return e===Pe||e===Oe||e===he||e===be}function Lt(e){return e>=65&&e<=90||e>=97&&e<=122||e===Xh||e===el||e>127}function Ze(e){return Lt(e)||e>=48&&e<=57}function Qh(e){let t=!0;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);if(n===mt){if(t)return!1;t=!0}else if(t){if(!Lt(n))return!1;t=!1}else if(!Ze(n))return!1}return e.length>0&&!t}function Lr(e,t,i){let n=t+1;while(n<e.length){let r=e.charCodeAt(n);if(r===Ye){n+=2;continue}if(n++,r===i)break}return n}function ed(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 tl(e,t,i=!0){return rl(e,t,i,!0)}function il(e,t,i=!0){return rl(e,t,i,!1)}function rl(e,t,i,n){let r=e,o=i,s=n,a=r.length,c=[],f=new Map,u=new Set,l=0;if(l<a&&r.charCodeAt(l)===65279)l++;function y(m,h){if(m<h){let d=r.charCodeAt(m),g=r.charCodeAt(h-1);if(d!==Pe&&d!==Oe&&d!==he&&d!==be&&g!==Pe&&g!==Oe&&g!==he&&g!==be)return r.slice(m,h)}while(m<h&&Be(r.charCodeAt(m)))m++;while(h>m&&Be(r.charCodeAt(h-1)))h--;return r.slice(m,h)}function p(){if(l>=a)return;let m=r.charCodeAt(l);if(m!==Pe&&m!==Oe&&m!==he&&m!==be&&m!==X)return;while(l<a){let h=r.charCodeAt(l);if(h===Pe||h===Oe||h===he||h===be){l++;continue}if(h===X&&l+1<a){let d=r.charCodeAt(l+1);if(d===X){let g=r.indexOf(`
|
|
133
|
+
`,l+2);l=g===-1?a:g+1;continue}if(d===Ee){let g=r.indexOf("*/",l+2);l=g===-1?a:g+2;continue}}break}}function w(m){let h=m.length,d=0,g=h;for(let C=0;C<h;C++){let v=m.charCodeAt(C);if(d){if(v===Ye){C++;continue}if(v===d)d=0;continue}if(v===le||v===ue||v===Me){d=v;continue}if(v===X&&C+1<h){let T=m.charCodeAt(C+1);if(T===X){g=C;while(g>0&&(m.charCodeAt(g-1)===Pe||m.charCodeAt(g-1)===Oe))g--;return m.slice(0,g)}if(T===Ee){let P=m.indexOf("*/",C+2);if(P!==-1){m=`${m.slice(0,C)} ${m.slice(P+2)}`,C--;continue}}}}g=h;while(g>0&&(m.charCodeAt(g-1)===Pe||m.charCodeAt(g-1)===Oe||m.charCodeAt(g-1)===be))g--;return g<h?m.slice(0,g):m}function S(m){l++;let h=m===le?"'":'"';while(l<a){let d=r.indexOf(h,l);if(d===-1){l=a;return}let g=0,C=d-1;while(C>=0&&r.charCodeAt(C)===Ye)g++,C--;if(g%2===0){l=d+1;return}l=d+1}}function x(){l++;let m=[];while(l<a){let h=r.charCodeAt(l);if(m.length===0){if(h===Ye){l+=2;continue}if(h===Me){l++;return}if(h===el&&l+1<a&&r.charCodeAt(l+1)===H){l+=2,m.push(0);continue}l++;continue}if(h===le||h===ue){S(h);continue}if(h===Me){x();continue}if(h===X&&l+1<a){let d=r.charCodeAt(l+1);if(d===X){let g=r.indexOf(`
|
|
134
|
+
`,l+2);l=g===-1?a:g+1;continue}if(d===Ee){let g=r.indexOf("*/",l+2);l=g===-1?a:g+2;continue}if(M()){J();continue}l++;continue}if(h===H){m[m.length-1]++,l++;continue}if(h===Q){let d=m[m.length-1];if(d===0){m.pop(),l++;continue}m[m.length-1]=d-1,l++;continue}l++}}function E(){let m=r.charCodeAt(l);if(m===le||m===ue)return S(m),!0;if(m===Me)return x(),!0;if(m===X&&l+1<a){let h=r.charCodeAt(l+1);if(h===X){let d=r.indexOf(`
|
|
135
|
+
`,l+2);return l=d===-1?a:d+1,!0}if(h===Ee){let d=r.indexOf("*/",l+2);return l=d===-1?a:d+2,!0}if(M())return J(),!0}return!1}function k(m){let h=m;for(;;){while(h>=0&&(r.charCodeAt(h)===Pe||r.charCodeAt(h)===Oe||r.charCodeAt(h)===he||r.charCodeAt(h)===be))h--;if(h<0)return-1;if(r.charCodeAt(h)===X&&h>0&&r.charCodeAt(h-1)===Ee){let C=r.lastIndexOf("/*",h-2);if(C===-1)return-1;h=C-1;continue}let d=r.lastIndexOf(`
|
|
136
|
+
`,h)+1,g=I(d,h);if(g!==-1){h=g-1;continue}return h}}function I(m,h){let d=0;for(let g=m;g<=h;g++){let C=r.charCodeAt(g);if(d){if(C===Ye){g++;continue}if(C===d)d=0;continue}if(C===le||C===ue||C===Me){d=C;continue}if(C===X&&g+1<=h&&r.charCodeAt(g+1)===X)return g}return-1}function M(){let m=k(l-1);if(m<0)return!0;let h=r.charCodeAt(m);if(h===Se||h===se||h===we||h===33||h===38||h===124||h===Fr||h===at||h===lt||h===ie||h===H||h===Q||h===94||h===126||h===43||h===45||h===Ee||h===37||h===ve||h===fe)return!0;if(Ze(h)){let d=m;while(d>=0&&Ze(r.charCodeAt(d)))d--;let g=r.slice(d+1,m+1);if(g==="return"||g==="typeof"||g==="void"||g==="delete"||g==="throw"||g==="new"||g==="in"||g==="of"||g==="case"||g==="instanceof"||g==="yield"||g==="await")return!0}return!1}function J(){l++;let m=!1;while(l<a){let h=r.charCodeAt(l);if(h===Ye){l+=2;continue}if(m){if(h===Re)m=!1;l++;continue}if(h===we){m=!0,l++;continue}if(h===X){l++;break}if(h===he||h===be)break;l++}while(l<a&&Ze(r.charCodeAt(l)))l++}function W(){let m=l;while(l<a&&Ze(r.charCodeAt(l)))l++;return r.slice(m,l)}function R(m){if(l+m.length>a)return!1;for(let h=0;h<m.length;h++)if(r.charCodeAt(l+h)!==m.charCodeAt(h))return!1;if(l+m.length<a&&Ze(r.charCodeAt(l+m.length)))return!1;return!0}function D(m){let h=l+m;while(h<a){let d=r.charCodeAt(h);if(d===Pe||d===Oe||d===he||d===be){h++;continue}return d!==mt&&d!==Se}return!1}function Y(){if(l>=a)return!1;switch(r.charCodeAt(l)){case 101:return R("export")||R("enum");case 105:return R("import")||R("interface");case 102:return R("function");case 99:return R("class")||R("const");case 116:return R("type");case 108:return R("let");case 118:return R("var");case 100:return R("declare")||R("default");case 109:return R("module");case 110:return R("namespace");case 97:return R("abstract")||R("async");default:return!1}}function ne(){let m=r.charCodeAt(l);if(m!==he&&m!==be)return!1;let h=l;if(l++,m===be&&l<a&&r.charCodeAt(l)===he)l++;while(l<a){let g=r.charCodeAt(l);if(g===Pe||g===Oe||g===be||g===he){l++;continue}if(g===X&&l+1<a){let C=r.charCodeAt(l+1);if(C===X){let v=r.indexOf(`
|
|
137
|
+
`,l+2);l=v===-1?a:v+1;continue}if(C===Ee){let v=r.indexOf("*/",l+2);l=v===-1?a:v+2;continue}}break}let d=l>=a||Y()||r.charCodeAt(l)===Q;return l=h,d}function De(m){let h=m-1;while(h>=0){let b=r.charCodeAt(h);if(b===Pe||b===Oe||b===be||b===he){h--;continue}break}if(h<0)return!0;let d=r[h];if("+-*/%=<>&|^!~?:,.([{".includes(d))return!0;let g=h;while(g>0&&r.charCodeAt(g-1)!==he)g--;let C=r.slice(g,h+1),v=C.lastIndexOf("<");if(v!==-1&&/^<[A-Za-z]/.test(C.slice(v))&&!C.slice(v).includes(">"))return!0;let T=h;while(T>=0&&/[a-z]/i.test(r[T]))T--;let P=r.slice(T+1,h+1);return["as","in","of","new","typeof","keyof","extends","instanceof","satisfies","await","return","yield","void"].includes(P)}function K(){let m=r.charCodeAt(l);if(m!==he&&m!==be)return!1;if(De(l))return!1;let h=l;l++;while(l<a){let v=r.charCodeAt(l);if(v===Pe||v===Oe||v===be||v===he){l++;continue}if(v===X&&l+1<a){let T=r.charCodeAt(l+1);if(T===X){let P=r.indexOf(`
|
|
138
|
+
`,l+2);l=P===-1?a:P+1;continue}if(T===Ee){let P=r.indexOf("*/",l+2);l=P===-1?a:P+2;continue}}break}let d=l<a?r[l]:"",g=r.slice(l,l+2),C=d==="."||d==="?"||d===":"||d===")"||d==="]"||d==="}"||d===","||d==="+"||d==="-"||d==="*"||d==="/"||d==="%"||d==="<"||d===">"||d==="="||d==="&"||d==="|"||d==="^"||d==="`"||g==="=>"||R("as")||R("satisfies")||R("instanceof")||R("in");return l=h,!C}function me(){let m=r.charCodeAt(l);if(m!==he&&m!==be)return!1;if(De(l))return!1;let h=l;l++;while(l<a){let C=r.charCodeAt(l);if(C===Pe||C===Oe||C===be||C===he){l++;continue}if(C===X&&l+1<a){let v=r.charCodeAt(l+1);if(v===X){let T=r.indexOf(`
|
|
139
|
+
`,l+2);l=T===-1?a:T+1;continue}if(v===Ee){let T=r.indexOf("*/",l+2);l=T===-1?a:T+2;continue}}break}let d=l<a?r[l]:"",g=d==="|"||d==="&"||d==="["||d==="."||d==="?"||d===":"||d===">"||d===")"||d===","||R("extends");return l=h,!g}function te(){let m=r.charCodeAt(l);if(m!==he&&m!==be)return!1;let h=l;if(l++,m===be&&l<a&&r.charCodeAt(l)===he)l++;while(l<a){let g=r.charCodeAt(l);if(g===Pe||g===Oe||g===be||g===he){l++;continue}if(g===X&&l+1<a&&r.charCodeAt(l+1)===X){let C=r.indexOf(`
|
|
140
|
+
`,l+2);l=C===-1?a:C+1;continue}break}if(l>=a)return l=h,!0;let d=r.charCodeAt(l);if(d===124||d===38||d===mt||d===Fr||d===at)return l=h,!1;if(R("extends")||R("keyof")||R("typeof")||R("infer")||R("is")||R("as")||R("in"))return l=h,!1;return l=h,!0}let re=/[{}'"`\/]/g,oe=/[()'"`\/]/g,de=/[[\]'"`\/]/g,G=/[<>'"`\/]/g;function _(m,h){let d=1;l++;let g=m===H?re:m===se?oe:m===we?de:G;g.lastIndex=l;let C;while((C=g.exec(r))!==null){let v=C.index,T=r.charCodeAt(v);if(T===le||T===ue){l=v,S(T),g.lastIndex=l;continue}if(T===Me){l=v,x(),g.lastIndex=l;continue}if(T===X){if(l=v,E()){g.lastIndex=l;continue}g.lastIndex=v+1;continue}if(T===m)d++;else if(T===h){if(h===fe&&v>0&&r.charCodeAt(v-1)===Se){g.lastIndex=v+1;continue}if(d--,d===0)return l=v+1,l}g.lastIndex=v+1}return l=a,l}function U(){return l>0&&r.charCodeAt(l-1)===Se}function ee(){return l+1<a&&r.charCodeAt(l+1)===fe}let z=/[<{};'"`\/\n\r()[\]]/g;function q(m=!1){let h=0,d=0,g=0,C=0,v=r.charCodeAt(l)===H;z.lastIndex=l;let T;while((T=z.exec(r))!==null){let P=T.index,b=r.charCodeAt(P);if(b===le||b===ue){l=P,S(b),z.lastIndex=l;continue}if(b===Me){l=P,x(),z.lastIndex=l;continue}if(b===X){if(P>0&&r.charCodeAt(P-1)===ve){z.lastIndex=P+1;continue}if(l=P,E()){z.lastIndex=l;continue}z.lastIndex=P+1;continue}if(b===ve){let A=Ro(P);if(A!==null)C=Math.max(0,C+A);z.lastIndex=P+1;continue}if(b===se){d++,z.lastIndex=P+1;continue}if(b===Ae){d--,z.lastIndex=P+1;continue}if(b===we){g++,z.lastIndex=P+1;continue}if(b===Re){g--,z.lastIndex=P+1;continue}if(b===H){h++,z.lastIndex=P+1;continue}if(b===Q){let A=h>0;if(!A&&m&&d===0&&g===0&&C===0){l=P;return}if(A)h--;if((!A||v)&&h===0&&d===0&&g===0&&C===0){l=P+1;return}z.lastIndex=P+1;continue}if(b===ie&&h===0&&d===0&&g===0&&C===0){l=P+1;return}if((b===he||b===be)&&h===0&&d===0&&g===0&&C===0){if(l=P,ne())return}z.lastIndex=P+1}l=a}function Te(){l++;while(l<a&&(r.charCodeAt(l)===Pe||r.charCodeAt(l)===Oe))l++;let m=r.indexOf(`
|
|
141
|
+
`,l),h=m===-1?a:m,d=r.indexOf(";",l);if(d!==-1&&d<h){let g=d-1;while(g>=l&&(r.charCodeAt(g)===Pe||r.charCodeAt(g)===Oe))g--;let C=r.charCodeAt(l),v=r.charCodeAt(g);if(C===H&&v===Q||C===we&&v===Re||C===le&&v===le||C===ue&&v===ue||C===Me&&v===Me){l=d+1;return}}q()}function Fe(){_(H,Q);while(l<a&&Be(r.charCodeAt(l)))l++;if(R("from")){l+=4;while(l<a&&Be(r.charCodeAt(l)))l++;if(l<a){let m=r.charCodeAt(l);if(m===le||m===ue)S(m)}}while(l<a&&(r.charCodeAt(l)===Pe||r.charCodeAt(l)===Oe))l++;if(l<a&&r.charCodeAt(l)===ie)l++}function Mi(){l++;while(l<a&&Be(r.charCodeAt(l)))l++;if(R("as")){l+=2;while(l<a&&Be(r.charCodeAt(l)))l++;W();while(l<a&&Be(r.charCodeAt(l)))l++}if(R("from")){l+=4;while(l<a&&Be(r.charCodeAt(l)))l++;if(l<a){let m=r.charCodeAt(l);if(m===le||m===ue)S(m)}}while(l<a&&(r.charCodeAt(l)===Pe||r.charCodeAt(l)===Oe))l++;if(l<a&&r.charCodeAt(l)===ie)l++}function Di(m){let h=m.indexOf("from ");if(h===-1)return;let d=h+5;while(d<m.length&&(m.charCodeAt(d)===32||m.charCodeAt(d)===9))d++;if(d>=m.length)return;let g=m.charCodeAt(d);if(g!==39&&g!==34)return;let C=m.indexOf(m[d],d+1);if(C===-1)return;return m.slice(d+1,C)}function Qe(m){if(!o)return;let h=m-1;while(h>=0&&Be(r.charCodeAt(h)))h--;if(h<0)return;let d=[],g=!1;while(h>=0){if(h>=1&&r.charCodeAt(h)===X&&r.charCodeAt(h-1)===Ee){let T=r.lastIndexOf("/*",h-2);if(T>=0){d.push(r.slice(T,h+1)),g=!0,h=T-1;while(h>=0&&Be(r.charCodeAt(h)))h--;continue}break}let C=h;while(C>0&&r.charCodeAt(C-1)!==he)C--;let v=y(C,h+1);if(v.startsWith("//")){if(g)break;let T=[v];h=C-1;while(h>=0&&(r.charCodeAt(h)===he||r.charCodeAt(h)===be))h--;while(h>=0){let P=h;while(P>0&&r.charCodeAt(P-1)!==he)P--;let b=y(P,h+1);if(b.startsWith("//")){T.push(b),h=P-1;while(h>=0&&(r.charCodeAt(h)===he||r.charCodeAt(h)===be))h--}else if(b===""){h=P-1;while(h>=0&&(r.charCodeAt(h)===he||r.charCodeAt(h)===be))h--}else break}T.reverse(),d.push(T.join(`
|
|
142
|
+
`));continue}break}if(d.length===0)return;return d.reverse(),d}function fc(m){let h=m,d=!1;while(l<a){let b=r.charCodeAt(l);if(b===ie){l++;break}if(b===le||b===ue){S(b),d=!0;while(l<a&&(r.charCodeAt(l)===Pe||r.charCodeAt(l)===Oe))l++;if(l<a&&r.charCodeAt(l)===ie)l++;break}if(b===he&&d)break;l++}let g=y(h,l),C=g.charCodeAt(7)===116&&(g.startsWith("import type ")||g.startsWith("import type{")),v=!1;{let b=6;while(b<g.length&&(g.charCodeAt(b)===Pe||g.charCodeAt(b)===Oe))b++;if(b<g.length&&g.charCodeAt(b)===116&&g.startsWith("type",b)){b+=4;while(b<g.length&&(g.charCodeAt(b)===Pe||g.charCodeAt(b)===Oe))b++}if(b<g.length){let A=g.charCodeAt(b);v=A===le||A===ue}}let T="";{let b=g.indexOf("from ");if(b!==-1){let A=b+5;while(A<g.length&&(g.charCodeAt(A)===Pe||g.charCodeAt(A)===Oe))A++;if(A<g.length){let O=g.charCodeAt(A);if(O===le||O===ue){let N=g.indexOf(String.fromCharCode(O),A+1);if(N!==-1)T=g.slice(A+1,N)}}}else if(v){let A=6;while(A<g.length&&g.charCodeAt(A)!==le&&g.charCodeAt(A)!==ue)A++;if(A<g.length){let O=g.charCodeAt(A),N=g.indexOf(String.fromCharCode(O),A+1);if(N!==-1)T=g.slice(A+1,N)}}}let P=Qe(h);return{kind:"import",name:"",text:g,isExported:!1,isTypeOnly:C,isSideEffect:v,source:T,leadingComments:P,start:h,end:l}}function _r(){let m=l;return _(H,Q),r.slice(m,l)}function $o(m){let h=m.indexOf("(");if(h===-1)return m;let d=m.slice(h);if(d.indexOf("=")===-1)return m;let g=!1;for(let b=0;b<d.length;b++)if(d.charCodeAt(b)===61){let A=b>0?d.charCodeAt(b-1):0,O=b+1<d.length?d.charCodeAt(b+1):0;if(A!==61&&A!==33&&A!==60&&A!==62&&O!==61&&O!==62){g=!0;break}}if(!g)return m;let C=0,v=-1;for(let b=h;b<m.length;b++){let A=m.charCodeAt(b);if(A===40)C++;else if(A===41){if(C--,C===0){v=b;break}}}if(v===-1)return m;let T=m.slice(h,v+1),P=Bt(T);return m.slice(0,h)+P+m.slice(v+1)}function Ao(m){let h=m.indexOf("//")!==-1||m.indexOf("/*")!==-1,d=m.split(`
|
|
143
|
+
`),g=[],C=[],v=[],T=!1,P=1/0;for(let O=0;O<d.length;O++){let N=d[O];if(h){if(T){if(N.includes("*/"))T=!1;continue}let j=N.trim();if(j.length===0)continue;let L=j.charCodeAt(0);if(L===X){let Ke=j.charCodeAt(1);if(Ke===X)continue;if(Ke===Ee){if(!j.includes("*/"))T=!0;continue}}if(L===Ee)continue;let F=w(N);if(F.charCodeAt(F.length-1)===ie)F=F.slice(0,-1);F=$o(F);let B=F.trim();if(!B)continue;g.push(F),C.push(B);let V=0;while(V<F.length&&Be(F.charCodeAt(V)))V++;if(B!=="{"&&B!=="}"){if(V<P)P=V}v.push(V)}else{let j=N.length;while(j>0&&(N.charCodeAt(j-1)===Pe||N.charCodeAt(j-1)===Oe||N.charCodeAt(j-1)===be))j--;if(j===0)continue;let L=j<N.length?N.slice(0,j):N;if(L.charCodeAt(L.length-1)===ie)L=L.slice(0,-1);L=$o(L);let F=L.trim();if(!F)continue;g.push(L),C.push(F);let B=0;while(B<L.length&&Be(L.charCodeAt(B)))B++;if(F!=="{"&&F!=="}"){if(B<P)P=B}v.push(B)}}if(g.length===0)return"{}";if(P===1/0||P<=2)return g.join(`
|
|
144
|
+
`);let b=P-2,A=Array(g.length);for(let O=0;O<g.length;O++){let N=C[O];if(N==="{"){A[O]=N;continue}let j=v[O];if(j>P)A[O]=g[O];else if(j===P&&(N.charCodeAt(0)===Q||N.charCodeAt(0)===Re||N.charCodeAt(0)===Ae))A[O]=g[O];else{let L=Math.max(0,j-b);A[O]=" ".repeat(L)+N}}return A.join(`
|
|
145
|
+
`)}function ht(){if(l>=a||r.charCodeAt(l)!==ve)return"";let m=l;_(ve,fe);let h=r.slice(m,l);if(h.includes(`
|
|
146
|
+
`)){let d="",g=!1;for(let C=0;C<h.length;C++){let v=h.charCodeAt(C);if(v===32||v===9||v===10||v===13){if(!g&&d.length>0)d+=" ",g=!0}else d+=h[C],g=!1}if(d.charCodeAt(1)===32)d=`<${d.slice(2)}`;if(d.charCodeAt(d.length-2)===32)d=`${d.slice(0,-2)}>`;return d}return h}function $t(){if(l>=a||r.charCodeAt(l)!==se)return"()";let m=l;return _(se,Ae),r.slice(m,l)}function Ii(m){if(m.indexOf("/")===-1)return m;let h="",d=!1,g=0;for(let C=0;C<m.length;C++){let v=m.charCodeAt(C);if(d){if(h+=m[C],v===Ye&&C+1<m.length){h+=m[++C];continue}if(v===g)d=!1;continue}if(v===le||v===ue||v===Me){d=!0,g=v,h+=m[C];continue}if(v===X&&C+1<m.length){let T=m.charCodeAt(C+1);if(T===Ee){let P=m.indexOf("*/",C+2);C=P===-1?m.length:P+1,h+=" ";continue}if(T===X){let P=m.indexOf(`
|
|
147
|
+
`,C+2);C=P===-1?m.length:P-1;continue}}h+=m[C]}return h.trim()}function Bt(m){let h=m.slice(1,-1).trim();if(!h)return"()";if(m.indexOf(`
|
|
148
|
+
`)===-1&&h.indexOf(":")!==-1&&h.indexOf("{")===-1&&h.indexOf("[")===-1&&h.indexOf("=")===-1&&h.indexOf("@")===-1&&h.indexOf("...")===-1){let b=0,A=0,O=0;for(let N=0;N<h.length;N++){let j=h.charCodeAt(N);if(j===se||j===ve||j===H)O++;else if(j===Ae||j===fe||j===Q)O--;else if(O===0){if(j===at)b++;else if(j===lt)A++}}if(b>=A+1){let N=!1;for(let j=0;j<po.length;j++){let L=po[j],F=h.indexOf(L);if(F!==-1){let B=F+L.length;if((F===0||!Ze(h.charCodeAt(F-1)))&&(B>=h.length||!Ze(h.charCodeAt(B)))){N=!0;break}}}if(!N)return m}}let d=[],g=0,C=0,v=!1,T=0;for(let b=0;b<=h.length;b++){if(b===h.length){d.push(Ii(h.slice(g).trim()));break}let A=h.charCodeAt(b);if(v){if(A===Ye){b++;continue}if(A===T)v=!1;continue}if(A===X&&b+1<h.length){let O=h.charCodeAt(b+1);if(O===Ee){b+=2;while(b+1<h.length&&!(h.charCodeAt(b)===Ee&&h.charCodeAt(b+1)===X))b++;b++;continue}if(O===X){while(b<h.length&&h.charCodeAt(b)!==10)b++;continue}}if(A===le||A===ue||A===Me){v=!0,T=A;continue}if(A===se||A===H||A===we||A===ve)C++;else if(A===Ae||A===Q||A===Re||A===fe&&!(b>0&&h.charCodeAt(b-1)===Se))C--;else if(A===lt&&C===0)d.push(Ii(h.slice(g,b).trim())),g=b+1}let P=[];for(let b of d){if(!b)continue;let A=b.trim();if(A.startsWith("//")||A.startsWith("/*"))continue;let O=b;{let N=!1,j=0,L=0,F=0;for(let B=0;B<O.length-1;B++){let V=O.charCodeAt(B);if(V===he){F=B+1;continue}if(N){if(V===Ye){B++;continue}if(V===j)N=!1;continue}if(V===le||V===ue||V===Me){N=!0,j=V;continue}if(V===H||V===we||V===se||V===ve){L++;continue}if(V===Q||V===Re||V===Ae||V===fe){if(L>0)L--;continue}if(V===X&&O.charCodeAt(B+1)===X){if(L===0){O=O.slice(0,B).trimEnd();break}let Ke=O.indexOf(`
|
|
149
|
+
`,B);if(Ke===-1){O=O.slice(0,F).trimEnd();break}let He=O.slice(0,F),Vt=O.slice(Ke+1);O=`${He}${Vt}`,B=F-1}}}if(!O.trim())continue;P.push(xo(O))}return`(${P.join(", ")})`}function uc(m){if(!m.startsWith("{")&&!m.startsWith("["))return m;let h="",d=0,g=0,C=!1,v=0;while(d<m.length){let T=m.charCodeAt(d);if(C){if(T===Ye&&d+1<m.length){h+=m[d]+m[d+1],d+=2;continue}if(T===v)C=!1;h+=m[d],d++;continue}if(T===X&&d+1<m.length){let P=m.charCodeAt(d+1);if(P===Ee){let b=d;d+=2;while(d+1<m.length&&!(m.charCodeAt(d)===Ee&&m.charCodeAt(d+1)===X))d++;d=Math.min(d+2,m.length),h+=m.slice(b,d);continue}if(P===X){let b=d;while(d<m.length&&m.charCodeAt(d)!==10)d++;h+=m.slice(b,d);continue}}if(T===le||T===ue||T===Me){C=!0,v=T,h+=m[d],d++;continue}if(T===H||T===we||T===se)g++;else if(T===Q||T===Re||T===Ae)g--;if(g>=1&&T===Se&&(d+1>=m.length||m.charCodeAt(d+1)!==Se&&m.charCodeAt(d+1)!==fe)){while(h.length>0&&(h[h.length-1]===" "||h[h.length-1]==="\t"||h[h.length-1]===`
|
|
150
|
+
`))h=h.slice(0,-1);d++;let P=0;while(d<m.length){let b=m.charCodeAt(d);if(b===le||b===ue||b===Me){let A=b;d++;while(d<m.length){if(m.charCodeAt(d)===Ye){d+=2;continue}if(m.charCodeAt(d)===A){d++;break}d++}continue}if(b===H||b===we||b===se)P++;else if(b===Q||b===Re||b===Ae){if(P===0)break;P--}else if(b===lt&&P===0)break;d++}continue}if(g===1&&T===mt&&d+2<m.length&&m.charCodeAt(d+1)===mt&&m.charCodeAt(d+2)===mt){d+=3;continue}h+=m[d],d++}return h}function xo(m){let h=m.trim(),d=h.startsWith("...");if(d)h=h.slice(3).trim();while(h.startsWith("@")){let F=1;while(F<h.length&&Ze(h.charCodeAt(F)))F++;if(F<h.length&&h.charCodeAt(F)===se){let B=1;F++;while(F<h.length&&B>0){if(h.charCodeAt(F)===se)B++;else if(h.charCodeAt(F)===Ae)B--;F++}}h=h.slice(F).trim()}let g=!0;while(g){g=!1;for(let F of po)if(h.startsWith(F)&&h.length>F.length&&!Ze(h.charCodeAt(F.length))){let B=h.slice(F.length).trim();if(B.charCodeAt(0)===at||B.charCodeAt(0)===Fr&&B.length>1&&B.charCodeAt(1)===at)break;h=B,g=!0;break}}let C=-1,v=-1,T=0,P=!1,b=0;for(let F=0;F<h.length;F++){let B=h.charCodeAt(F);if(P){if(B===Ye){F++;continue}if(B===b)P=!1;continue}if(B===X&&F+1<h.length){let V=h.charCodeAt(F+1);if(V===Ee){F+=2;while(F+1<h.length&&!(h.charCodeAt(F)===Ee&&h.charCodeAt(F+1)===X))F++;F++;continue}if(V===X){while(F<h.length&&h.charCodeAt(F)!==10)F++;continue}}if(B===le||B===ue||B===Me){P=!0,b=B;continue}if(B===se||B===H||B===we||B===ve)T++;else if(B===Ae||B===Q||B===Re||B===fe&&!(F>0&&h.charCodeAt(F-1)===Se))T--;else if(T===0){if(B===at&&C===-1)C=F;else if(B===Se&&v===-1&&(F===0||h.charCodeAt(F-1)!==Se)&&(F+1>=h.length||h.charCodeAt(F+1)!==Se&&h.charCodeAt(F+1)!==fe))v=F}}let A,O,N=v!==-1;if(C!==-1&&(v===-1||C<v))if(A=h.slice(0,C).trim(),v!==-1)O=h.slice(C+1,v).trim();else O=h.slice(C+1).trim();else if(v!==-1)A=h.slice(0,v).trim(),O=Vr(h.slice(v+1).trim());else A=h,O="unknown";if(A=uc(A),(A.startsWith("{")||A.startsWith("["))&&A.includes(`
|
|
151
|
+
`)){let F=A.replace(/\s*\n\s*/g," ").replace(/\s+/g," ");if(F.length<=40)A=F;else A=A.split(`
|
|
152
|
+
`).map((B)=>{let V=B.trim();if(!V)return"";if(V==="{"||V==="}"||V==="["||V==="]"||V.startsWith("}")||V.startsWith("]"))return V;return` ${V}`}).join(`
|
|
153
|
+
`)}let j=A.endsWith("?")||N;if(A.endsWith("?"))A=A.slice(0,-1).trim();let L=j&&!d?"?":"";if(d)return`...${A}: ${O}`;return`${A}${L}: ${O}`}function To(m){let h=0;if(h<m.length&&m.charCodeAt(h)===45)h++;if(h>=m.length)return!1;let d=m.charCodeAt(h);if(d<48||d>57)return!1;while(h<m.length&&m.charCodeAt(h)>=48&&m.charCodeAt(h)<=57)h++;if(h<m.length&&m.charCodeAt(h)===46){if(h++,h>=m.length||m.charCodeAt(h)<48||m.charCodeAt(h)>57)return!1;while(h<m.length&&m.charCodeAt(h)>=48&&m.charCodeAt(h)<=57)h++}return h===m.length}function Vr(m){let h=m.trim();if(h==="true"||h==="false")return"boolean";if(To(h))return"number";if(h.startsWith("'")&&h.endsWith("'")||h.startsWith('"')&&h.endsWith('"'))return"string";if(h.startsWith("["))return"unknown[]";if(h.startsWith("{"))return"Record<string, unknown>";return"unknown"}function Ur(m){let h=m.trim();if(h.endsWith("as const"))h=h.slice(0,-8).trim();if(h==="true"||h==="false")return h;if(To(h))return h;let d=hc(h);if(d!==null)return d;return"unknown"}function hc(m){if(m==="")return null;if(m.charCodeAt(0)===le||m.charCodeAt(0)===ue){if(Lr(m,0,m.charCodeAt(0))===m.length)return m}let h=dc(m,"+");if(h.length>1){let d=!1,g=!0,C=[];for(let v of h){let T=v.trim(),P=T.charCodeAt(0);if((P===le||P===ue)&&Lr(T,0,P)===T.length)d=!0,C.push(mc(T));else g=!1}if(g)return pc(C.join(""));if(d)return"string";return null}if(/^[\d\s()+*/%.\-]+$/.test(m)&&/\d/.test(m)&&/[+*/%\-\s]/.test(m))return"number";return null}function dc(m,h){let d=[],g=0,C="",v=0;while(v<m.length){let T=m.charCodeAt(v);if(T===le||T===ue||T===Me){let P=Lr(m,v,T);C+=m.slice(v,P),v=P;continue}if(T===X&&(m.charCodeAt(v+1)===X||m.charCodeAt(v+1)===42)){if(m.charCodeAt(v+1)===X){let A=m.indexOf(`
|
|
154
|
+
`,v+2),O=A===-1?m.length:A;C+=m.slice(v,O),v=O;continue}let P=m.indexOf("*/",v+2),b=P===-1?m.length:P+2;C+=m.slice(v,b),v=b;continue}if(T===se||T===we||T===H)g++;else if(T===Ae||T===Re||T===Q)g--;if(m[v]===h&&g===0){d.push(C),C="",v++;continue}C+=m[v],v++}return d.push(C),d}function mc(m){return m.slice(1,-1).replace(/\\(.)/g,(h,d)=>{if(d==="n")return`
|
|
155
|
+
`;if(d==="t")return"\t";if(d==="r")return"\r";if(d==="0")return"\x00";return d})}function pc(m){return`'${m.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function Fi(m){if(m.endsWith("as const"))return null;let h=0,d=-1;for(let g=0;g<m.length;g++){let C=m.charCodeAt(g);if(C===le||C===ue||C===Me)g=Lr(m,g,C)-1;else if(C===123||C===91||C===40)h++;else if(C===125||C===93||C===41)h--;else if(h===0&&C===32&&g+4<=m.length&&m.substring(g,g+4)===" as ")d=g}if(d===-1)return null;return m.slice(d+4).trim()||null}function li(){if(p(),l<a&&r.charCodeAt(l)===at){l++,p();let m=l,h=0;while(l<a){if(E())continue;let d=r.charCodeAt(l);if(d===se||d===we||d===ve)h++;else if(d===Ae||d===Re||d===fe&&!U())h--;else if(d===H)if(h>0)h++;else{let g=y(m,l),C=(v)=>{let T=g.length-v.length;return T>=0&&g.endsWith(v)&&(T===0||!Ze(g.charCodeAt(T-1)))};if(g.length===0||g.endsWith("|")||g.endsWith("&")||C("is")||C("extends"))h++;else break}else if(d===Q){if(h===0)break;h--}else if(h===0&&d===ie)break;if(h===0&&te())break;l++}return y(m,l)}return""}function At(m,h,d,g){l+=8,p();let C=l<a&&r.charCodeAt(l)===Ee;if(C)l++,p();let v=W();if(!v&&!g)return null;p();let T=ht();p();let P=$t();p();let b=li(),A=b.length>0;if(!b)if(d&&C)b="AsyncGenerator<unknown, void, unknown>";else if(C)b="Generator<unknown, void, unknown>";else if(d)b="Promise<void>";else b="void";p();let O=!1;if(l<a&&r.charCodeAt(l)===H){O=!0;let F=l+1;if(_(H,Q),!s&&!A&&!C)b=Ei(r.slice(F,l-1),d,P)}else if(l<a&&r.charCodeAt(l)===ie)l++;let N=Bt(P),j=`${h?g?"export default function ":"export declare function ":"declare function "}${v||(g?"":"default")}${T}${N}: ${b};`,L=Qe(m);if(O)u.add(c.length);return{kind:"function",name:v||"default",text:j,isExported:h,isDefault:g,isAsync:d,isGenerator:C,returnType:b,generics:T||void 0,leadingComments:L,start:m,end:l}}function Gt(m,h,d){l+=h.length,p();let g=[];do{if(p(),l>=a)break;let C=r.charCodeAt(l);if(C===H||C===we)return q(),g;let v=W();if(!v)return q(),g;p();let T,P,b=!1;if(l<a&&r.charCodeAt(l)===at){l++,p();let N=l,j=0;while(l<a){if(E())continue;let L=r.charCodeAt(l);if(L===se||L===H||L===we||L===ve)j++;else if(L===Ae||L===Q||L===Re||L===fe&&!U())j--;else if(j===0&&(L===ie||L===lt))break;else if(j===0&&L===Se&&!ee())break;if(j===0&&(ne()||me()))break;l++}T=y(N,l)}if(l<a&&r.charCodeAt(l)===Se)if(s&&T&&(!o||!ed(T)))Te();else{l++,p();let N=l,j=0,L=0,F=0,B=!0;for(;;){l=N,j=0,L=0,F=0;while(l<a){if(E())continue;let V=r.charCodeAt(l);if(V===se||V===H||V===we)j++;else if(V===Ae||V===Q||V===Re)j--;else if(V===ve&&j===0){let Ke=Ro(l);if(Ke!==null)F=Math.max(0,F+Ke);else if(B&&(l+1>=a||r.charCodeAt(l+1)!==Se))L++}else if(V===fe&&j===0&&F===0&&!U()){if(L>0&&(l+1>=a||r.charCodeAt(l+1)!==Se))L--}else if(j===0&&L===0&&F===0&&(V===ie||V===lt))break;if(j===0&&L===0&&F===0&&(ne()||K()))break;l++}if(L>0&&B){B=!1;continue}break}if(P=y(N,l),P.endsWith(" as const")||P==="const"){if(b=!0,!T){let V=P.endsWith(" as const")?P.slice(0,-9).trim():P,Ke=Ur(V);T=Ke!=="unknown"?Ke:void 0}}else if(!T){let V=Fi(P);if(V)T=V}}if(l<a){let N=r.charCodeAt(l);if(N===lt){l++;continue}if(N===ie)l++}let A=Qe(m),O=`${d?"export ":""}declare ${h} ${v}: ${T||"unknown"};`;g.push({kind:"variable",name:v,text:O,isExported:d,typeAnnotation:T,value:P,modifiers:b?[h,"const assertion"]:[h],leadingComments:A,start:m,end:l});break}while(l<a);return g}function Ro(m){if(r.charCodeAt(m)!==ve||m+1>=a)return null;let h=r.charCodeAt(m+1);if(h===fe)return 1;if(h===X)return-1;if(!Lt(h))return null;let d=m+2;while(d<a){let A=r.charCodeAt(d);if(!Ze(A)&&A!==mt&&A!==58&&A!==45)break;d++}let g=r.slice(m+1,d),C=r.charCodeAt(d);if(C>32&&C!==fe&&C!==X)return null;let v=0,T=0,P=d;for(;P<a;P++){let A=r.charCodeAt(P);if(T!==0){if(A===Ye)P++;else if(A===T)T=0;continue}if(A===le||A===ue||A===Me)T=A;else if(A===H)v++;else if(A===Q&&v>0)v--;else if(A===fe&&v===0)break}if(P>=a)return null;let b=P-1;while(b>m&&r.charCodeAt(b)<=32)b--;if(r.charCodeAt(b)===X)return 0;return r.indexOf(`</${g}`,P+1)===-1?null:1}function Kr(m,h){l+=9,p();let d=W();p();let g=ht();p();let C="";if(R("extends")){l+=7,p();let A=l,O=0;while(l<a){if(E())continue;let N=r.charCodeAt(l);if(N===ve)O++;else if(N===fe&&!U())O--;else if(N===H&&O===0)break;l++}C=y(A,l)}p();let v=l<a&&r.charCodeAt(l)===H?_r():"{}",T=Ao(v),P=`${h?"export ":""}declare interface ${d}${g}${C?` extends ${C}`:""} ${T}`,b=Qe(m);return{kind:"interface",name:d,text:P,isExported:h,extends:C||void 0,generics:g||void 0,leadingComments:b,start:m,end:l}}function Hr(m,h){l+=4,p();let d=W();p();let g=ht();if(p(),l<a&&r.charCodeAt(l)===Se)l++;p();let C=l,v=0;while(l<a){if(E())continue;let A=r.charCodeAt(l);if(A===se||A===H||A===we||A===ve)v++;else if(A===Ae||A===Q||A===Re||A===fe&&!U())v--;else if(v===0&&A===ie)break;if(v===0&&(ne()||me()))break;l++}let T=y(C,l);if(l<a&&r.charCodeAt(l)===ie)l++;let P=`${h?"export ":""}type ${d}${g} = ${T}`,b=Qe(m);return{kind:"type",name:d,text:P,isExported:h,generics:g||void 0,leadingComments:b,start:m,end:l}}function jt(m,h,d){l+=4,p();let g=W();p();let C=l;if(l<a&&r.charCodeAt(l)===H)_(H,Q);let v=y(m,l),T=Qe(m);return{kind:"enum",name:g,text:v,isExported:h,modifiers:d?["const"]:void 0,leadingComments:T,start:m,end:l}}function xt(m,h,d,g=!1){l+=5,p();let C=W()||"AnonymousClass";p();let v=ht();p();let T="";if(R("extends")){l+=7,p();let N=l,j=0;while(l<a){if(E())continue;let L=r.charCodeAt(l);if(L===ve)j++;else if(L===fe&&!U())j--;else if(j===0&&(L===H||R("implements")))break;l++}T=y(N,l)}let P;if(R("implements")){l+=10,p();let N=l,j=0;while(l<a){if(E())continue;let F=r.charCodeAt(l);if(F===ve)j++;else if(F===fe&&!U())j--;else if(j===0&&F===H)break;l++}let L=y(N,l);if(L)P=L.split(",").map((F)=>F.trim())}p();let b=zr(),A=`${h?g?"export default ":"export declare ":"declare "}${d?"abstract ":""}class ${C}${v}${T?` extends ${T}`:""}${P&&P.length>0?` implements ${P.join(", ")}`:""} ${b}`,O=Qe(m);return{kind:"class",name:C,text:A,isExported:h,isDefault:g,extends:T||void 0,implements:P,generics:v||void 0,modifiers:d?["abstract"]:void 0,leadingComments:O,start:m,end:l}}function zr(){if(l>=a||r.charCodeAt(l)!==H)return"{}";l++;let m=[];while(l<a){if(p(),l>=a)break;if(r.charCodeAt(l)===Q){l++;break}if(r.charCodeAt(l)===ie){l++;continue}if(R("static")&&Po("static")===H){l+=6,p(),_(H,Q);continue}let h=!1,d=!1,g=!1,C=!1,v=!1,T=!1,P=!1,b=!1,A=!0;while(A){if(p(),R("private")){h=!0,l+=7;continue}if(R("protected")){d=!0,l+=9;continue}if(R("public")){l+=6;continue}if(R("static")){g=!0,l+=6;continue}if(R("abstract")){C=!0,l+=8;continue}if(R("readonly")){v=!0,l+=8;continue}if(R("override")){T=!0,l+=8;continue}if(R("accessor")){P=!0,l+=8;continue}if(R("async")){b=!0,l+=5;continue}if(R("declare")){l+=7;continue}break}if(p(),l>=a||r.charCodeAt(l)===Q)break;if(r.charCodeAt(l)===Nr)h=!0;if(h){qr();continue}let O=" ";if(d)O+="protected ";if(g)O+="static ";if(C)O+="abstract ";if(v)O+="readonly ";if(R("constructor")){l+=11,p();let N=$t();if(p(),yc(N,m),l<a&&r.charCodeAt(l)===H)_(H,Q);else if(l<a&&r.charCodeAt(l)===ie)l++;let j=Bt(N);m.push(` constructor${j};`)}else if(R("get"))if(l+=3,p(),l<a&&(Lt(r.charCodeAt(l))||r.charCodeAt(l)===we||r.charCodeAt(l)===Nr)){let N=Jr();if(N.startsWith("#")){if(p(),l<a&&r.charCodeAt(l)===se)$t();if(p(),li(),p(),l<a&&r.charCodeAt(l)===H)_(H,Q);else if(l<a&&r.charCodeAt(l)===ie)l++;continue}p(),$t(),p();let j=li()||"unknown";if(p(),l<a&&r.charCodeAt(l)===H)_(H,Q);else if(l<a&&r.charCodeAt(l)===ie)l++;m.push(`${O}get ${N}(): ${j};`)}else Oo("get",O,g,v,b,m);else if(R("set"))if(l+=3,p(),l<a&&(Lt(r.charCodeAt(l))||r.charCodeAt(l)===we||r.charCodeAt(l)===Nr)){let N=Jr();if(N.startsWith("#")){if(p(),l<a&&r.charCodeAt(l)===se)$t();if(p(),l<a&&r.charCodeAt(l)===H)_(H,Q);else if(l<a&&r.charCodeAt(l)===ie)l++;continue}p();let j=$t();if(p(),l<a&&r.charCodeAt(l)===H)_(H,Q);else if(l<a&&r.charCodeAt(l)===ie)l++;let L=Bt(j);m.push(`${O}set ${N}${L};`)}else Oo("set",O,g,v,b,m);else{let N=r.charCodeAt(l)===Ee;if(N)l++,p();let j=Jr();if(!j){qr();continue}ko(j,O,g,v,N,C,b,m)}}return`{
|
|
156
|
+
${m.join(`
|
|
157
|
+
`)}
|
|
158
|
+
}`}function Jr(){if(l>=a)return"";let m=r.charCodeAt(l);if(m===we){let h=l;return _(we,Re),r.slice(h,l)}if(m===Nr)return l++,`#${W()}`;return W()}function Po(m){let h=l+m.length;while(h<a&&Be(r.charCodeAt(h)))h++;return h<a?r.charCodeAt(h):0}function qr(){let m=0;while(l<a){if(E())continue;let h=r.charCodeAt(l);if(h===H||h===se)m++;else if(h===Q||h===Ae){if(m===0)return;m--}else if(h===ie&&m===0){l++;return}if(m===0&&te())return;l++}}function Oo(m,h,d,g,C,v){ko(m,h,d,g,!1,!1,C,v)}function ko(m,h,d,g,C,v,T,P){if(p(),l>=a)return;let b=r.charCodeAt(l),A=!1;if(b===Fr)A=!0,l++,p();if(l<a&&r.charCodeAt(l)===33)l++,p();let O=l<a?r.charCodeAt(l):0;if(O===se||O===ve){let N=O===ve?ht():"";p();let j=$t();p();let L=li(),F=L.length>0;if(!L)if(T&&C)L="AsyncGenerator<unknown, void, unknown>";else if(C)L="Generator<unknown, void, unknown>";else if(T)L="Promise<void>";else L="void";if(p(),l<a&&r.charCodeAt(l)===H){let Ke=l+1;if(_(H,Q),!s&&!F&&!C)L=Ei(r.slice(Ke,l-1),T,j)}else if(l<a&&r.charCodeAt(l)===ie)l++;let B=Bt(j),V=A?"?":"";P.push(`${h}${m}${V}${N}${B}: ${L};`)}else if(O===at||O===Se||O===ie||O===Q||O===he||O===be){let N="";if(O===at){l++,p();let F=l,B=0;while(l<a){if(E())continue;let V=r.charCodeAt(l);if(V===se||V===H||V===we||V===ve)B++;else if(V===Ae||V===Q||V===Re||V===fe&&!U()){if(B===0)break;B--}else if(B===0&&(V===ie||V===lt))break;else if(B===0&&V===Se&&!ee())break;if(B===0&&te())break;l++}N=y(F,l)}let j="";if(l<a&&r.charCodeAt(l)===Se)if(s&&N){l++;let F=0;while(l<a){if(E())continue;let B=r.charCodeAt(l);if(B===se||B===H||B===we)F++;else if(B===Ae||B===Q||B===Re){if(F===0&&B===Q)break;F--}else if(F===0&&B===ie)break;if(F===0&&te())break;l++}}else{l++,p();let F=l,B=0;while(l<a){if(E())continue;let V=r.charCodeAt(l);if(V===se||V===H||V===we)B++;else if(V===Ae||V===Q||V===Re){if(B===0&&V===Q)break;B--}else if(B===0&&V===ie)break;if(B===0&&te())break;l++}j=y(F,l)}if(l<a&&r.charCodeAt(l)===ie)l++;if(!N)if(j){let F=Fi(j);if(F)N=F;else N=j.endsWith("as const")||d&&g?Ur(j):Vr(j)}else N="unknown";let L=A?"?":"";P.push(`${h}${m}${L}: ${N};`)}else qr()}function gc(m){let h=0;for(let d=0;d<m.length;d++){let g=m.charCodeAt(d);if(g===se||g===H||g===we||g===ve)h++;else if(g===Ae||g===Q||g===Re||g===fe&&m.charCodeAt(d-1)!==Se)h--;else if(g===Se&&h===0&&m.charCodeAt(d+1)!==fe&&m.charCodeAt(d+1)!==Se)return!0}return!1}function yc(m,h){let d=m.slice(1,-1).trim();if(!d)return;let g=[],C=0,v=0,T=!1,P=0;for(let b=0;b<=d.length;b++){if(b===d.length){g.push(Ii(d.slice(C).trim()));break}let A=d.charCodeAt(b);if(T){if(A===Ye){b++;continue}if(A===P)T=!1;continue}if(A===X&&b+1<d.length){let O=d.charCodeAt(b+1);if(O===Ee){b+=2;while(b+1<d.length&&!(d.charCodeAt(b)===Ee&&d.charCodeAt(b+1)===X))b++;b++;continue}if(O===X){while(b<d.length&&d.charCodeAt(b)!==10)b++;continue}}if(A===le||A===ue||A===Me){T=!0,P=A;continue}if(A===se||A===H||A===we||A===ve)v++;else if(A===Ae||A===Q||A===Re||A===fe&&!(b>0&&d.charCodeAt(b-1)===Se))v--;else if(A===lt&&v===0)g.push(Ii(d.slice(C,b).trim())),C=b+1}for(let b of g){let A=b.startsWith("public ")||b.startsWith("public\t"),O=b.startsWith("protected ")||b.startsWith("protected\t"),N=b.startsWith("private ")||b.startsWith("private\t"),j=b.includes("readonly ");if(!A&&!O&&!N&&!j)continue;if(N)continue;let L=b,F=[];if(A){let He=6;while(He<L.length&&Be(L.charCodeAt(He)))He++;L=L.slice(He),F.push("public")}if(O){let He=9;while(He<L.length&&Be(L.charCodeAt(He)))He++;L=L.slice(He),F.push("protected")}if(j){let He=L.indexOf("readonly ");if(He!==-1){let Vt=He+8;while(Vt<L.length&&Be(L.charCodeAt(Vt)))Vt++;L=L.slice(0,He)+L.slice(Vt)}F.push("readonly")}let B=F.length>0?`${F.join(" ")} `:"",V=xo(L),Ke=L.search(/[?:=]/);if(Ke!==-1&&L.charCodeAt(Ke)!==63&&gc(L))V=V.replace(/^([\w$]+)\?:/,"$1:");h.push(` ${B}${V};`)}}function Yr(m=" "){if(l>=a||r.charCodeAt(l)!==H)return"{}";l++;let h=[];while(l<a){if(p(),l>=a)break;if(r.charCodeAt(l)===Q){l++;break}if(r.charCodeAt(l)===ie){l++;continue}let d=!1;if(R("export"))d=!0,l+=6,p();if(R("declare"))l+=7,p();let g=d?"export ":"";if(R("function")||R("async")&&Cc("async","function")){let C=!1;if(R("async"))C=!0,l+=5,p();if(l+=8,p(),l<a&&r.charCodeAt(l)===Ee)l++,p();let v=W();p();let T=ht();p();let P=$t();p();let b=li();if(!b)b=C?"Promise<void>":"void";if(p(),l<a&&r.charCodeAt(l)===H)_(H,Q);else if(l<a&&r.charCodeAt(l)===ie)l++;let A=Bt(P);h.push(`${m}${g}function ${v}${T}${A}: ${b};`)}else if(R("const")||R("let")||R("var")){let C=R("const")?"const":R("let")?"let":"var";l+=C.length,p();let v=W();if(!v){q(!0);continue}p();let T="";if(l<a&&r.charCodeAt(l)===at){l++,p();let b=l,A=0;while(l<a){if(E())continue;let O=r.charCodeAt(l);if(O===se||O===H||O===we||O===ve)A++;else if(O===Q&&A===0)break;else if(O===Ae||O===Q||O===Re||O===fe&&!U())A--;else if(A===0&&(O===ie||O===lt))break;else if(A===0&&O===Se&&!ee())break;if(A===0&&ne())break;l++}T=y(b,l)}let P="";if(l<a&&r.charCodeAt(l)===Se){l++,p();let b=l,A=0;while(l<a){if(E())continue;let O=r.charCodeAt(l);if(O===se||O===H||O===we||O===ve)A++;else if(O===Q&&A===0)break;else if(O===Ae||O===Q||O===Re||O===fe&&!U())A--;else if(A===0&&(O===ie||O===lt))break;if(A===0&&ne())break;l++}P=y(b,l)}if(l<a&&r.charCodeAt(l)===ie)l++;if(!T&&P){let b=Fi(P);if(b)T=b;else if(C==="const")T=Ur(P);else T=Vr(P)}if(!T)T="unknown";h.push(`${m}${g}${C} ${v}: ${T};`)}else if(R("interface")){l+=9,p();let C=W();p();let v=ht();p();let T="";if(R("extends")){l+=7,p();let b=l,A=0;while(l<a){if(E())continue;let O=r.charCodeAt(l);if(O===ve)A++;else if(O===fe&&!U())A--;else if(O===H&&A===0)break;l++}T=y(b,l)}let P=Ao(_r());h.push(`${m}${g}interface ${C}${v}${T?` extends ${T}`:""} ${P}`)}else if(R("type")){l+=4,p();let C=W();p();let v=ht();if(p(),l<a&&r.charCodeAt(l)===Se){l++,p();let T=l,P=0;while(l<a){if(E())continue;let A=r.charCodeAt(l);if(A===se||A===H||A===we||A===ve)P++;else if(A===Q&&P===0)break;else if(A===Ae||A===Q||A===Re||A===fe&&!U())P--;else if(P===0&&A===ie)break;if(P===0&&ne())break;l++}let b=y(T,l);if(l<a&&r.charCodeAt(l)===ie)l++;h.push(`${m}${g}type ${C}${v} = ${b}`)}}else if(R("class")){l+=5,p();let C=W();p();let v=ht();p();let T=l,P=0;while(l<a){if(E())continue;let N=r.charCodeAt(l);if(N===ve)P++;else if(N===fe&&!U())P--;else if(N===H&&P===0)break;l++}let b=y(T,l),A=b?` ${b}`:"",O=zr();h.push(`${m}${g}class ${C}${v}${A} ${O}`)}else if(R("enum")){l+=4,p();let C=W();p();let v=_r();h.push(`${m}${g}enum ${C} ${v}`)}else if(R("namespace")||R("module")){let C=R("namespace")?"namespace":"module";l+=C.length,p();let v=W();p();let T=Yr(m);h.push(`${m}${g}${C} ${v} ${T}`)}else if(R("abstract"))if(l+=8,p(),R("class")){l+=5,p();let C=W();p();let v=ht();p();let T=l,P=0;while(l<a){if(E())continue;let N=r.charCodeAt(l);if(N===ve)P++;else if(N===fe&&!U())P--;else if(N===H&&P===0)break;l++}let b=y(T,l),A=b?` ${b}`:"",O=zr();h.push(`${m}${g}abstract class ${C}${v}${A} ${O}`)}else q(!0);else if(d&&R("default")){l+=7,p();let C=l;q(!0);let v=y(C,l);if(v.charCodeAt(v.length-1)===ie)v=v.slice(0,-1);if(v)h.push(`${m}export default ${v};`)}else if(!d&&(r.charCodeAt(l)===le||r.charCodeAt(l)===ue||r.charCodeAt(l)===Me))q(!0);else q(!0)}if(h.length===0)return"{}";return`{
|
|
159
|
+
${h.join(`
|
|
160
|
+
`)}
|
|
161
|
+
}`}function Cc(m,h){let d=l+m.length;while(d<a&&Be(r.charCodeAt(d)))d++;for(let g=0;g<h.length;g++)if(d+g>=a||r.charCodeAt(d+g)!==h.charCodeAt(g))return!1;return d+h.length>=a||!Ze(r.charCodeAt(d+h.length))}function _t(m,h,d){l+=d.length,p();let g="",C=r.charCodeAt(l);if(C===le||C===ue){let A=l;S(C),g=r.slice(A,l)}else{g=W();while(l<a&&r.charCodeAt(l)===mt)l++,g+=`.${W()}`}p();let v=l<a&&r.charCodeAt(l)===H?Yr():"{}",T=`${h?"export ":""}declare ${d} ${g} ${v}`,P=Qe(m),b=g.startsWith("'")||g.startsWith('"');return{kind:"module",name:g,text:T,isExported:h,source:b?g.slice(1,-1):void 0,leadingComments:P,start:m,end:l}}function Mo(m,h){q();let d=y(h,l);if(d.charCodeAt(d.length-1)===ie)d=d.slice(0,-1).trimEnd();if(!d)return;let g=Lt(d.charCodeAt(0));for(let A=1;g&&A<d.length;A++)g=Ze(d.charCodeAt(A));let C=Qe(m);if(g){c.push({kind:"export",name:"default",text:`export default ${d};`,isExported:!0,isTypeOnly:!1,leadingComments:C,start:m,end:l});return}let v="__dtsx_default_export__",T=1;while(r.includes(v))v=`__dtsx_default_export_${T++}__`;let P=Fi(d)||Ie(d,!1),b=P==="unknown"&&Qh(d)?`typeof ${d}`:P;c.push({kind:"variable",name:v,text:`declare const ${v}: ${b};`,isExported:!1,typeAnnotation:b,modifiers:["const"],start:m,end:l}),c.push({kind:"export",name:"default",text:`export default ${v};`,isExported:!0,isTypeOnly:!1,leadingComments:C,start:m,end:l})}while(l<a){if(p(),l>=a)break;let m=l,h=r.charCodeAt(l);if(h===105&&R("import"))c.push(fc(m));else if(h===101&&R("export")){l+=6,p();let d=r.charCodeAt(l);if(d===100&&R("default")){l+=7,p();let g=l,C=r.charCodeAt(l);if(C===102&&R("function")){let v=At(m,!0,!1,!0);if(v)c.push(v)}else if(C===97&&R("async")&&Po("async")!==ie)if(l+=5,p(),R("function")){let v=At(m,!0,!0,!0);if(v)c.push(v)}else Mo(m,g);else if(C===99&&R("class")){let v=xt(m,!0,!1,!0);c.push(v)}else if(C===97&&R("abstract")){if(l+=8,p(),R("class")){let v=xt(m,!0,!0,!0);c.push(v)}}else Mo(m,g)}else if(d===116&&R("type")){let g=l;if(l+=4,p(),l<a&&r.charCodeAt(l)===H){Fe();let C=y(m,l),v=Qe(m);c.push({kind:"export",name:"",text:C,isExported:!0,isTypeOnly:!0,source:Di(C),leadingComments:v,start:m,end:l})}else if(l<a&&r.charCodeAt(l)===Ee){Mi();let C=y(m,l);c.push({kind:"export",name:"",text:C,isExported:!0,isTypeOnly:!0,source:Di(C),start:m,end:l})}else{l=g;let C=Hr(m,!0);c.push(C)}}else if(d===105&&R("interface")){let g=Kr(m,!0);c.push(g)}else if(d===102&&R("function")){let g=At(m,!0,!1,!1);if(g)c.push(g)}else if(d===97&&R("async"))if(l+=5,p(),R("function")){let g=At(m,!0,!0,!1);if(g)c.push(g)}else q();else if(d===99)if(R("class")){let g=xt(m,!0,!1);c.push(g)}else if(R("const")){let g=l;if(l+=5,p(),R("enum")){l=g+5,p();let C=jt(m,!0,!0);c.push(C)}else{l=g;let C=Gt(m,"const",!0);for(let v=0;v<C.length;v++)c.push(C[v])}}else q();else if(d===97&&R("abstract")){if(l+=8,p(),R("class")){let g=xt(m,!0,!0);c.push(g)}}else if(d===108&&R("let")){let g=Gt(m,"let",!0);for(let C=0;C<g.length;C++)c.push(g[C])}else if(d===118&&R("var")){let g=Gt(m,"var",!0);for(let C=0;C<g.length;C++)c.push(g[C])}else if(d===101&&R("enum")){let g=jt(m,!0,!1);c.push(g)}else if(d===100&&R("declare"))l+=7,p(),Do(m,!0);else if(d===110&&R("namespace")&&D(9)){let g=_t(m,!0,"namespace");c.push(g)}else if(d===109&&R("module")&&D(6)){let g=_t(m,!0,"module");c.push(g)}else if(d===H){Fe();let g=y(m,l),C=g.includes("export type"),v=Qe(m);c.push({kind:"export",name:"",text:g,isExported:!0,isTypeOnly:C,source:Di(g),leadingComments:v,start:m,end:l})}else if(d===Ee){Mi();let g=y(m,l),C=Qe(m);c.push({kind:"export",name:"",text:g,isExported:!0,isTypeOnly:!1,source:Di(g),leadingComments:C,start:m,end:l})}else{q();let g=y(m,l);if(g)c.push({kind:"export",name:"",text:g,isExported:!0,start:m,end:l})}}else if(h===100&&R("declare"))l+=7,p(),Do(m,!1);else if(h===105&&R("interface")){let d=Kr(m,!1);f.set(d.name,d)}else if(h===116&&R("type")){let d=Hr(m,!1);f.set(d.name,d),c.push(d)}else if(h===102&&R("function")){let d=At(m,!1,!1,!1);if(d)f.set(d.name,d);else q()}else if(h===97)if(R("async")){let d=l;if(l+=5,p(),R("function")){let g=At(m,!1,!0,!1);if(g)f.set(g.name,g);else l=d,q()}else l=d,q()}else if(R("abstract"))if(l+=8,p(),R("class")){let d=xt(m,!1,!1);f.set(d.name,d),c.push(d)}else q();else l++,q();else if(h===99)if(R("class")){let d=xt(m,!1,!1);f.set(d.name,d),c.push(d)}else if(R("const")){let d=l;if(l+=5,p(),R("enum")){l=d+5,p();let g=jt(m,!1,!0);f.set(g.name,g),c.push(g)}else{l=d;let g=Gt(m,"const",!1);for(let C=0;C<g.length;C++)f.set(g[C].name,g[C])}}else l++,q();else if(h===101&&R("enum")){let d=jt(m,!1,!1);f.set(d.name,d),c.push(d)}else if(h===108&&R("let"))q();else if(h===118&&R("var"))q();else if(h===109&&R("module")&&D(6)){let d=_t(m,!1,"module");c.push(d)}else if(h===110&&R("namespace")&&D(9)){let d=_t(m,!1,"namespace");c.push(d)}else{let d=r.charCodeAt(l);if(d===ie)l++;else if(d===le||d===ue){if(S(d),l<a&&r.charCodeAt(l)===ie)l++}else if(d===Me){if(x(),l<a&&r.charCodeAt(l)===ie)l++}else if(d===Zh){if(l++,W(),p(),l<a&&r.charCodeAt(l)===mt)l++,W(),p();if(l<a&&r.charCodeAt(l)===se)_(se,Ae)}else l++,q()}}if(f.size>0)td(c,f);if(u.size>0){let m=new Map;for(let d of c)if(d.kind==="function")m.set(d.name,(m.get(d.name)||0)+1);let h=new Set;for(let[d,g]of m)if(g>1)h.add(d);if(h.size>0){let d=new Set;for(let g of h)for(let C=c.length-1;C>=0;C--)if(c[C].kind==="function"&&c[C].name===g&&u.has(C)){d.add(C);break}if(d.size>0){let g=[...d].sort((C,v)=>v-C);for(let C of g)c.splice(C,1)}}}return c;function Do(m,h){if(R("function")){let d=At(m,h,!1,!1);if(d)c.push(d)}else if(R("async")){if(l+=5,p(),R("function")){let d=At(m,h,!0,!1);if(d)c.push(d)}}else if(R("class")){let d=xt(m,h,!1);c.push(d)}else if(R("abstract")){if(l+=8,p(),R("class")){let d=xt(m,h,!0);c.push(d)}}else if(R("interface")){let d=Kr(m,h);c.push(d)}else if(R("type")){let d=Hr(m,h);c.push(d)}else if(R("enum")){let d=jt(m,h,!1);c.push(d)}else if(R("const")){let d=l;if(l+=5,p(),R("enum")){l=d+5,p();let g=jt(m,h,!0);c.push(g)}else if(h){l=d;let g=Gt(m,"const",!0);for(let C=0;C<g.length;C++)c.push(g[C])}else q()}else if(R("let")||R("var"))if(h){let d=R("let")?"let":"var",g=Gt(m,d,!0);for(let C=0;C<g.length;C++)c.push(g[C])}else q();else if(R("module")){let d=_t(m,h,"module");c.push(d)}else if(R("namespace")){let d=_t(m,h,"namespace");c.push(d)}else if(R("global")){l+=6,p();let d=`declare global ${l<a&&r.charCodeAt(l)===H?Yr():"{}"}`,g=Qe(m);c.push({kind:"module",name:"global",text:d,isExported:!1,leadingComments:g,start:m,end:l})}else q()}}function Xa(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 Qa(e,t){let i=0;while(i<e.length){let n=e.charCodeAt(i);if(n===le||n===ue||n===Me){let u=n;i++;while(i<e.length)if(e.charCodeAt(i)===Ye)i+=2;else if(e.charCodeAt(i++)===u)break;continue}if(n===X&&e.charCodeAt(i+1)===X){i+=2;while(i<e.length&&e.charCodeAt(i)!==he&&e.charCodeAt(i)!==be)i++;continue}if(n===X&&e.charCodeAt(i+1)===Ee){let u=e.indexOf("*/",i+2);i=u===-1?e.length:u+2;continue}if(!Lt(n)){i++;continue}let r=i++;while(i<e.length&&Ze(e.charCodeAt(i)))i++;let o=r-1,s=i;while(o>=0&&Be(e.charCodeAt(o)))o--;while(s<e.length&&Be(e.charCodeAt(s)))s++;let a=o>=0?e.charCodeAt(o):0,c=s<e.length?e.charCodeAt(s):0,f=r>=3&&e.slice(r-3,r)==="...";if(c===at||a===mt&&!f)continue;if(c===se&&(a===H||a===lt))continue;t.add(e.slice(r,i))}}function td(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 a=e[s];if(a.kind!=="import"){if(o.push(a.text),Xa(a.text,r),typeof a.value==="string")Qa(a.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 a=[],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)a.push(s[c++]);a.push(e[f])}while(c<s.length)a.push(s[c++]);e.length=0;for(let f=0;f<a.length;f++)e.push(a[f]);for(let f of s)if(f.kind!=="import"){if(o.push(f.text),Xa(f.text,r),typeof f.value==="string")Qa(f.value,r)}}}var Pe=32,Oe=9,he=10,be=13,X=47,Ee=42,le=39,ue=34,Me=96,Ye=92,H=123,Q=125,se=40,Ae=41,we=91,Re=93,ve=60,fe=62,ie=59,at=58,Se=61,lt=44,mt=46,Fr=63,Nr=35,Zh=64,el=36,Xh=95,po;var nl=pe(()=>{mo();po=["public","protected","private","readonly","override"]});function sl(e,t,i=!0,n=!1){if(Pa(t))e=Ma(e);else if(Ia(t))e=Fa(e);let r=ci(e),o=`${t}:${i?1:0}:${n?1:0}`,s=ai.get(o);if(s&&s.contentHash===r)return s.lastAccess=++ol,s.declarations;let a=n?tl(e,t,i):il(e,t,i);if(ai.set(o,{declarations:a,contentHash:r,lastAccess:++ol}),ai.size>id){let c=Math.max(1,Math.ceil(ai.size*0.1)),f=[];for(let[u,l]of ai)f.push([u,l.lastAccess]);f.sort((u,l)=>u[1]-l[1]);for(let u=0;u<c&&u<f.length;u++)ai.delete(f[u][0])}return a}var id=100,ol=0,ai;var al=pe(()=>{no();Na();nl();rn();ai=new Map});function ll(e,t,i=!0,n=!1){return sl(e,t,i,n)}var cl=pe(()=>{al()});async function rd(){if(Wr!==null)return Wr;try{return Ot=await import("prettier"),Wr=!0,!0}catch{return Wr=!1,!1}}async function nd(e,t){if(!Ot)return null;try{if(t&&Ot.resolveConfig){let i=await Ot.resolveConfig(t);if(i)return i}if(e&&Ot.resolveConfig){let i=await Ot.resolveConfig(e);if(i)return i}return null}catch{return null}}async function od(e,t){if(!Ot)throw Error("Prettier is not available");let i={...t,parser:t.parser||"typescript"};return Ot.format(e,i)}function sd(e,t={}){let{indentSize:i=2,useTabs:n=!1,maxLineWidth:r=100,trailingNewline:o=!0,normalizeWhitespace:s=!0,sortImports:a=!0,groupImports:c=!0}=t,f=e,u=n?"\t":" ".repeat(i);if(f.indexOf(`\r
|
|
139
162
|
`)!==-1)f=f.replace(/\r\n/g,`
|
|
140
|
-
`);if(
|
|
163
|
+
`);if(s){if(/[ \t]\n/.test(f)||/[ \t]$/.test(f))f=f.replace(/[ \t]+$/gm,"");if(f.indexOf(`
|
|
141
164
|
|
|
142
165
|
|
|
143
166
|
`)!==-1)f=f.replace(/\n{3,}/g,`
|
|
144
167
|
|
|
145
|
-
`);f=
|
|
168
|
+
`);f=ad(f,u)}if(a||c)f=ld(f,{sort:a,group:c});if(r>0)f=fd(f,r,u);if(o&&!f.endsWith(`
|
|
146
169
|
`))f+=`
|
|
147
|
-
`;return f}function
|
|
148
|
-
`),n=[];for(let
|
|
149
|
-
`)}function
|
|
150
|
-
`),n=[],
|
|
151
|
-
`)}function
|
|
152
|
-
`),
|
|
153
|
-
`)}function
|
|
154
|
-
|
|
155
|
-
`)!==-1)
|
|
156
|
-
`)
|
|
157
|
-
`)}
|
|
158
|
-
`);return r}function hd(e){return e.split(`
|
|
170
|
+
`;return f}function ad(e,t){let i=e.split(`
|
|
171
|
+
`),n=[];for(let r of i){let o=r.match(/^(\s*)(.*)$/);if(!o){n.push(r);continue}let[,s,a]=o;if(!a){n.push("");continue}let c=s.replace(/\t/g," ").length,f=Math.floor(c/2);n.push(t.repeat(f)+a)}return n.join(`
|
|
172
|
+
`)}function ld(e,t){let i=e.split(`
|
|
173
|
+
`),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 l=u[1];n.push({line:f,source:u[2],isType:l.startsWith("import type ")||l.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 cd(c.source,f.source)});let a;if(t.group){let c=[],f=[],u=[],l=[],y=[];for(let p=0;p<n.length;p++){let w=n[p],S=w.source;if(S.charCodeAt(0)===46)y.push(w);else if(S.startsWith("node:"))c.push(w);else if(S.charCodeAt(0)===64)l.push(w);else if(S.includes("/"))u.push(w);else f.push(w)}a=[...c.map((p)=>p.line),...c.length>0&&f.length>0?[""]:[],...f.map((p)=>p.line),...(c.length>0||f.length>0)&&u.length>0?[""]:[],...u.map((p)=>p.line),...l.length>0&&(c.length>0||f.length>0||u.length>0)?[""]:[],...l.map((p)=>p.line),...y.length>0?[""]:[],...y.map((p)=>p.line)]}else a=n.map((c)=>c.line);return[...a,"",...r].join(`
|
|
174
|
+
`)}function cd(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 fd(e,t,i){let n=e.split(`
|
|
175
|
+
`),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]||"",a=s+i,c=hd(o,s,a);if(c){r.push(...c);continue}if(o.includes("{")&&o.includes("}")){let f=dd(o,t,s,a);r.push(...f);continue}if(o.includes(" | ")){let f=md(o,t,s,a);r.push(...f);continue}r.push(o)}return r.join(`
|
|
176
|
+
`)}function hd(e,t,i){let n=e.match(ud);if(!n)return null;let[,r,o,s,a]=n,c=s.split(",").map((l)=>l.trim()).filter(Boolean);if(c.length<=1)return[e];let f=`${t}${r}${o??""} {`,u=a?`${t}} ${a};`:`${t}};`;return[f,...c.map((l)=>`${i}${l},`),u]}function dd(e,t,i,n){let r=e.match(/^(\s*)(.*?)(\{)(.+)(\}.*)$/);if(!r)return[e];let[,,o,s,a,c]=r,f=a.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 md(e,t,i,n){let r=e.match(/^(\s*)(.*?=\s*)(.+)$/);if(!r)return[e];let[,,o,s]=r,a=s.split(/\s*\|\s*/).filter((c)=>c.trim());if(a.length<=2)return[e];return[`${i}${o}`,...a.map((c,f)=>`${n}${f>0?"| ":" "}${c.trim()}`)]}async function fl(e,t={},i){let n=[];if(t.usePrettier!==!1){if(await rd())try{let r={...await nd(t.prettierConfigPath,i),...t.prettierOptions,parser:"typescript"};return{content:await od(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:sd(e,t.builtIn),usedPrettier:!1,warnings:n.length>0?n:void 0}}var Wr=null,Ot=null,ud;var ul=pe(()=>{ud=/^\s*(export|import)(\s+type)?\s*\{([^{}]*)\}\s*(from\s*(?:'[^']*'|"[^"]*")(?:\s*(?:with|assert)\s*\{[^{}]*\})?)?\s*;?\s*$/});class Br{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 pd(e){return e}var Sy,$y;var hl=pe(()=>{Sy=new Br;$y=pd({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 pl(e,t={}){let{lineEnding:i="lf",trailingNewline:n=!0,maxBlankLines:r=1,trimTrailingWhitespace:o=!0,normalizeIndentation:s=!0,indent:a={style:"spaces",size:2},declarationOrder:c,importGrouping:f,preserveComments:u=!0,insertFinalNewline:l=!0}=t,y=e;if(y=Cd(y,i),f?.enabled!==!1)y=Sd(y,f||{});if(c)y=$d(y,c);if(o)y=wd(y);if(y=vd(y,r),s)y=bd(y,a);if(n||l)y=Ed(y);return y}function Cd(e,t){let i=e;if(e.indexOf("\r")!==-1){if(e.indexOf(`\r
|
|
177
|
+
`)!==-1)i=i.replace(/\r\n/g,`
|
|
178
|
+
`);if(i.indexOf("\r")!==-1)i=i.replace(/\r/g,`
|
|
179
|
+
`)}if(t==="crlf")i=i.replace(/\n/g,`\r
|
|
180
|
+
`);return i}function wd(e){return e.split(`
|
|
159
181
|
`).map((t)=>t.replace(/[\t ]+$/,"")).join(`
|
|
160
|
-
`)}function
|
|
161
|
-
`.repeat(t+1))}function
|
|
162
|
-
`}function
|
|
163
|
-
`),
|
|
164
|
-
`)}function
|
|
165
|
-
`),
|
|
166
|
-
`)}function
|
|
167
|
-
`),
|
|
168
|
-
`)}function Cd(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 cd,fd;var hl=fe(()=>{cd=["import","type","interface","enum","class","function","variable","export","module","namespace","unknown"],fd=["builtin","external","scoped","internal","parent","sibling","index","type"]});function Sd(e){switch(e){case"strict":return vd;case"readonly":return Ed;case"simplified":return bd;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 ml{rules;compiled=[];cache=new Map;constructor(e={rules:[]}){if(this.rules=[],e.includeDefaults!==!1)this.rules.push(...wd);if(e.presets)for(let t of e.presets)this.rules.push(...Sd(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($d,"\\$&"),r.global?"g":""):r.pattern;e[t]={rule:r,regex:n}}this.compiled=e}map(e,t={}){let r=!t.declarationName&&!t.declarationKind&&!t.filePath&&!t.isReturnType&&!t.isParameterType&&!t.isPropertyType?e:`${e}\x00${t.declarationName??""}\x00${t.declarationKind??""}\x00${t.filePath??""}\x00${t.isReturnType?"r":""}${t.isParameterType?"p":""}${t.isPropertyType?"P":""}`,n=this.cache.get(r);if(n!==void 0)return n;let i=e,s=null;for(let o=0;o<this.compiled.length;o++){let{rule:a,regex:c}=this.compiled[o];if(a.condition){if(!s)s={type:e,...t};if(!a.condition(s))continue}if(c.lastIndex=0,c.test(i)){if(c.lastIndex=0,i=i.replace(c,a.replacement),c.lastIndex=0,!a.global)break}}if(this.cache.size>=dl){let o=Math.ceil(dl*0.1),a=0;for(let c of this.cache.keys()){if(a++>=o)break;this.cache.delete(c)}}return this.cache.set(r,i),i}mapAll(e,t={}){return e.map((r)=>this.map(r,{...t,type:r}))}addRule(e){this.rules.push(e),this.rules.sort((t,r)=>(r.priority||0)-(t.priority||0)),this.recompile(),this.cache.clear()}removeRules(e){let t=this.rules.length;return this.rules=this.rules.filter((r)=>{let n=typeof r.pattern==="string"?r.pattern:r.pattern.source;if(e instanceof RegExp)e.lastIndex=0;return typeof e==="string"?n!==e:!e.test(n)}),this.recompile(),this.cache.clear(),t-this.rules.length}clearCache(){this.cache.clear()}getRules(){return this.rules}}function Bi(e={rules:[]}){return new ml(e)}function pl(e,t,r={}){return e.replace(/:\s*([^;,)\]}]+)/g,(n,i)=>`: ${t.map(i.trim(),r)}`)}var wd,vd,Ed,bd,$d,dl=2048,by,Sy;var gl=fe(()=>{wd=[{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}],vd=[{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}],bd=[{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}];$d=/[.*+?^${}()|[\]\\]/g;by=Bi({rules:[]}),Sy=Bi({rules:[],presets:["strict"]})});var yl;var Cl=fe(()=>{yl=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 wl(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(`
|
|
169
|
-
`,n),a=
|
|
182
|
+
`)}function vd(e,t){let i=new RegExp(`\\n{${t+2},}`,"g");return e.replace(i,`
|
|
183
|
+
`.repeat(t+1))}function Ed(e){return`${e.replace(/\s+$/,"")}
|
|
184
|
+
`}function bd(e,t){let{style:i="spaces",size:n=2}=t,r=i==="tabs"?"\t":" ".repeat(n),o=e.split(`
|
|
185
|
+
`),s=[];for(let a of o){let c=a.match(/^([\t ]*)(.*)$/);if(!c){s.push(a);continue}let[,f,u]=c;if(!u){s.push("");continue}let l=f.replace(/\t/g," "),y=Math.floor(l.length/2);s.push(r.repeat(y)+u)}return s.join(`
|
|
186
|
+
`)}function Sd(e,t){let{groups:i=yd,separateGroups:n=!0,alphabetize:r=!0}=t,o=e.split(`
|
|
187
|
+
`),s=[],a=[],c=-1;for(let w=0;w<o.length;w++){let S=o[w],x=dl(S);if(x)s.push({line:S,source:x.source,group:x.group,isType:x.isType}),c=w;else if(s.length>0&&S.trim()==="")continue;else if(s.length>0||S.trim()!==""){if(s.length===0||w>c+1)a.push(S)}}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((S,x)=>{if(S.isType!==x.isType)return S.isType?1:-1;return S.source.localeCompare(x.source)});let u=[],l=null;for(let w of i){let S=f.get(w)||[];if(S.length===0)continue;if(n&&l!==null)u.push("");for(let x of S)u.push(x.line);l=w}let y=o.slice(0,o.findIndex((w)=>dl(w)!==null)),p=a;while(p.length>0&&p[0].trim()==="")p.shift();return[...y,...u,"",...p].join(`
|
|
188
|
+
`)}function dl(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:ml(o[1]),isType:!1};return null}let n=!!i[1],r=i[2];return{source:r,group:n?"type":ml(r),isType:n}}function ml(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 $d(e,t){let{kinds:i=gd,alphabetize:n=!1,groupExports:r=!0}=t,o=e.split(`
|
|
189
|
+
`),s=[],a=[],c=[],f=null,u=0,l=!0,y=!1,p=[];for(let x=0;x<o.length;x++){let E=o[x],k=E.trim(),I=u,M=k.startsWith("///"),J=I===0&&!M&&(k.startsWith("//")||k.startsWith("/*"));if(y||J){if(p.push(E),!y&&k.startsWith("/*")&&!k.includes("*/"))y=!0;else if(y&&k.includes("*/"))y=!1;continue}if(I===0&&p.length>0&&k===""){p.push(E);continue}u+=(E.match(/\{/g)||[]).length,u-=(E.match(/\}/g)||[]).length;let W=Ad(k);if(l&&W&&W.kind!=="import"&&!k.startsWith("//")&&!k.startsWith("/*"))l=!1;if(l){if(p.length>0){if(W?.kind==="import"||!W)a.push(...p),p.length=0}a.push(E);continue}if(W&&u<=1){if(f)s.push(f);f={lines:p.length>0?[...p,E]:[E],kind:W.kind,name:W.name,isExport:W.isExport},p.length=0}else if(f)f.lines.push(E);else{if(k==="")continue;c.push(E)}}if(f)s.push(f);if(p.length>0)c.push(...p);s.sort((x,E)=>{if(r&&x.isExport!==E.isExport)return x.isExport?-1:1;let k=i.indexOf(x.kind),I=i.indexOf(E.kind),M=k>=0?k:i.length,J=I>=0?I:i.length;if(M!==J)return M-J;if(n)return x.name.localeCompare(E.name);return 0});let w=[...a],S=null;for(let x of s){if(S!==null&&x.kind!==S)w.push("");w.push(...x.lines),S=x.kind}if(c.length>0)w.push(""),w.push(...c);return w.join(`
|
|
190
|
+
`)}function Ad(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 gd,yd;var gl=pe(()=>{gd=["import","type","interface","enum","class","function","variable","export","module","namespace","unknown"],yd=["builtin","external","scoped","internal","parent","sibling","index","type"]});function Od(e){switch(e){case"strict":return Td;case"readonly":return Rd;case"simplified":return Pd;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 Cl{rules;compiled=[];cache=new Map;constructor(e={rules:[]}){if(this.rules=[],e.includeDefaults!==!1)this.rules.push(...xd);if(e.presets)for(let t of e.presets)this.rules.push(...Od(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(kd,"\\$&"),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:a,regex:c}=this.compiled[s];if(a.condition){if(!o)o={type:e,...t};if(!a.condition(o))continue}if(c.lastIndex=0,c.test(r)){if(c.lastIndex=0,r=r.replace(c,a.replacement),c.lastIndex=0,!a.global)break}}if(this.cache.size>=yl){let s=Math.ceil(yl*0.1),a=0;for(let c of this.cache.keys()){if(a++>=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 Gr(e={rules:[]}){return new Cl(e)}function wl(e,t,i={}){return e.replace(/:\s*([^;,)\]}]+)/g,(n,r)=>`: ${t.map(r.trim(),i)}`)}var xd,Td,Rd,Pd,kd,yl=2048,Ty,Ry;var vl=pe(()=>{xd=[{pattern:/^Promise<void>$/,replacement:"Promise<void>",priority:-1},{pattern:/^Record<string,\s*any>$/,replacement:"Record<string, unknown>",priority:0},{pattern:/^Array<([^<>]+)>$/,replacement:"$1[]",priority:0}],Td=[{pattern:/\bany\b/,replacement:"unknown",global:!0,priority:10},{pattern:/^object$/,replacement:"Record<string, unknown>",priority:10},{pattern:/^Function$/,replacement:"(...args: unknown[]) => unknown",priority:10}],Rd=[{pattern:/^(\w+)\[\]$/,replacement:"readonly $1[]",priority:5},{pattern:/^Array<(.+)>$/,replacement:"ReadonlyArray<$1>",priority:5},{pattern:/^Map<(.+),\s*(.+)>$/,replacement:"ReadonlyMap<$1, $2>",priority:5},{pattern:/^Set<(.+)>$/,replacement:"ReadonlySet<$1>",priority:5}],Pd=[{pattern:/^Partial<Partial<(.+)>>$/,replacement:"Partial<$1>",priority:5},{pattern:/^Required<Required<(.+)>>$/,replacement:"Required<$1>",priority:5},{pattern:/^Pick<Omit<(.+),\s*(.+)>,\s*(.+)>$/,replacement:"Pick<$1, $3>",priority:5}];kd=/[.*+?^${}()|[\]\\]/g;Ty=Gr({rules:[]}),Ry=Gr({rules:[],presets:["strict"]})});var El;var bl=pe(()=>{El=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 Sl(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(`
|
|
191
|
+
`,n),a=s===-1?e.length:s;i+=" ".repeat(a-n),n=a;continue}if(r==="/*"){let s=e.indexOf("*/",n+2),a=s===-1?e.length:s+2;for(let c=n;c<a;c++)i+=e[c]===`
|
|
170
192
|
`?`
|
|
171
|
-
`:" ";n=a;continue}let
|
|
193
|
+
`:" ";n=a;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]===`
|
|
172
194
|
`?`
|
|
173
|
-
`:" ",n++}continue}
|
|
195
|
+
`:" ",n++}continue}i+=o,n++}return i}function Dd(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 Id(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 a of o.split(",")){let c=a.trim();if(/^[A-Za-z_$][\w$]*$/.test(c))t.add(c)}let s=/\{([\s\S]*?)\}/.exec(n);if(s)for(let a of s[1].split(",")){let c=a.trim().replace(/^type\s+/,"");if(!c)continue;let f=/\bas\s+([A-Za-z_$][\w$]*)$/.exec(c);t.add(f?f[1]:c.split(/\s+/)[0])}}for(let i of e.matchAll(/\bimport\s*\(\s*['"`][^'"`]*['"`]\s*\)\s*\.\s*([A-Za-z_$][\w$]*)/g))t.add(i[1]);return t}function Fd(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 Nd(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 a of r.matchAll(/\b([A-Z][\w$]*)\b/g)){let c=a[1];if(t.has(c))continue;let f=r.slice(a.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 $l(e){let t=Sl(e),i=Sl(e,{strings:!1}),n=new Set([...Dd(t),...Id(i),...Fd(t),...El,...Md]),r=[];for(let[o,s]of Nd(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 Md;var Al=pe(()=>{bl();Md=new Set(["This","True","False","Null","Undefined","Void","Never","Any","Unknown","Object","Infinity","NaN"])});function kt(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 Tl(e){let t=[],i=[],n=[],r={")":"(","]":"[","}":"{"},o=0,s=0,a=-1;for(let f=0;f<e.length;f++){let u=e.charCodeAt(f),l=e.charCodeAt(f+1);if(a!==-1){if(u===42&&l===47)i.push({start:a,end:f+2}),a=-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&&l===42){a=f,f++;continue}if(u===47&&l===47){let p=f;while(f<e.length&&e.charCodeAt(f)!==10)f++;i.push({start:p,end:f});continue}if(u===39||u===34||u===96){o=u,s=f;continue}let y=e[f];if(y==="("||y==="["||y==="{")n.push({char:y,offset:f});else if(r[y]){let p=n.pop();if(!p||p.char!==r[y])t.push({...kt(e,f),message:`Unexpected closing delimiter ${y}`,code:"DTSX1004"})}}if(o)t.push({...kt(e,s),message:"Unterminated string literal",code:"DTSX1002"});if(a!==-1)t.push({...kt(e,a),message:"Unterminated block comment",code:"DTSX1003"});for(let f of n)t.push({...kt(e,f.offset),message:`Unclosed delimiter ${f.char}`,code:"DTSX1001"});let c=[[/\b(?:interface|class|enum)\s*(?=[{=])/g,"Declaration name expected"],[/\bfunction\s*(?=\()/g,"Function name expected"],[/\(\s*:/g,"Parameter name expected"]];for(let[f,u]of c)for(let l of e.matchAll(f)){if(i.some((y)=>l.index>=y.start&&l.index<y.end))continue;t.push({...kt(e,l.index),message:u,code:"DTSX1005"})}for(let f of e.matchAll(/\btype\s*(?=[{=])/g)){if(i.some((l)=>f.index>=l.start&&f.index<l.end))continue;let u=e.slice(0,f.index).trimEnd();if(u.endsWith("import")||u.endsWith("export"))continue;t.push({...kt(e,f.index),message:"Declaration name expected",code:"DTSX1005"})}return t.push(...Wd(e,i)),t.sort((f,u)=>f.line-u.line||f.column-u.column)}function Wd(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,a=-1;for(let u=s+1;u<e.length;u++){if(n(u))continue;let l=e[u];if(l==="{"){a=-2;break}if(l==="}"){a=u;break}}if(a<0)continue;let c=e.slice(s+1,a);if(!c.trim())continue;let f=s+1;for(let u of c.split(",")){let l=u.trim();if(l){let y=f+u.indexOf(l);if(l.includes(";"))i.push({...kt(e,y),message:`Unexpected ';' in ${r[1]} clause \u2014 specifiers are separated by ','`,code:"DTSX1006"});else if(!Ld.test(l))i.push({...kt(e,y),message:`Invalid ${r[1]} specifier '${l}'`,code:"DTSX1006"})}f+=u.length+1}}return i}var xl,Ld;var Rl=pe(()=>{xl=String.raw`(?:[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*|'[^']*'|"[^"]*")`,Ld=new RegExp(`^(?:type\\s+)?${xl}(?:\\s+as\\s+${xl})?$`,"u")});import{statSync as Bd}from"fs";import{readFile as Gd,readdir as By}from"fs/promises";import{createRequire as jd}from"module";import{dirname as _d,isAbsolute as Pl,join as Vd,resolve as Ol}from"path";import Ud from"process";function yo(){return`${String.fromCharCode(47,47,35)} sourceMappingURL=`}async function $i(e,t,i="lf"){let n=t.replace(/\r\n/g,`
|
|
174
196
|
`);if(!n.endsWith(`
|
|
175
197
|
`))n+=`
|
|
176
|
-
`;if(
|
|
177
|
-
`);await
|
|
178
|
-
`;
|
|
179
|
-
`),
|
|
180
|
-
`),
|
|
181
|
-
`)}function
|
|
182
|
-
`),
|
|
183
|
-
`).length;for(let l=0;l<
|
|
184
|
-
${
|
|
185
|
-
`}var
|
|
198
|
+
`;if(i==="crlf")n=n.replace(/\n/g,`\r
|
|
199
|
+
`);await Io(e,n)}function Kd(e){let t="",i=0,n=0;while(i<e.length){let r=e.charCodeAt(i);if(n){if(t+=e[i],r===92&&i+1<e.length){t+=e[i+1],i+=2;continue}if(r===n)n=0;i++;continue}if(r===34){n=r,t+=e[i++];continue}if(r===47&&e.charCodeAt(i+1)===47){i+=2;while(i<e.length&&e.charCodeAt(i)!==10)i++;continue}if(r===47&&e.charCodeAt(i+1)===42){i+=2;while(i+1<e.length&&!(e.charCodeAt(i)===42&&e.charCodeAt(i+1)===47)){if(e.charCodeAt(i)===10)t+=`
|
|
200
|
+
`;i++}i=Math.min(i+2,e.length);continue}if(r===44){let o=i+1;while(o<e.length){while(o<e.length&&e.charCodeAt(o)<=32)o++;if(e.charCodeAt(o)===47&&e.charCodeAt(o+1)===47){o+=2;while(o<e.length&&e.charCodeAt(o)!==10)o++;continue}if(e.charCodeAt(o)===47&&e.charCodeAt(o+1)===42){o+=2;while(o+1<e.length&&!(e.charCodeAt(o)===42&&e.charCodeAt(o+1)===47))o++;o=Math.min(o+2,e.length);continue}break}let s=e.charCodeAt(o);if(s===93||s===125){i++;continue}}t+=e[i++]}return t}function go(e){let t=[e];if(!e.endsWith(".json"))t.push(`${e}.json`);t.push(Vd(e,"tsconfig.json"));for(let i of t)try{if(Bd(i).isFile())return i}catch{}return null}function Hd(e,t){if(Pl(e)||e.startsWith("."))return go(Ol(_d(t),e));let i=jd(t);for(let n of[e,`${e}/tsconfig.json`])try{let r=go(i.resolve(n));if(r)return r}catch{}return null}async function kl(e,t){let i=go(e);if(!i||t.has(i))return;t.add(i);let n=await Gd(i,"utf8"),r=JSON.parse(Kd(n)),o=typeof r.extends==="string"?[r.extends]:r.extends??[],s;for(let a of o){let c=Hd(a,i);if(!c)continue;let f=await kl(c,t);if(f!==void 0)s=f}return r.compilerOptions?.isolatedDeclarations??s}async function Ml(e){try{let t=e?.cwd||Ud.cwd(),i=e?.tsconfigPath||"tsconfig.json",n=Pl(i)?i:Ol(t,i);return await kl(n,new Set)??!1}catch{return!1}}function Dl(e,t){let i={isValid:!0,errors:[]};for(let n of Tl(e))i.errors.push({line:n.line,column:n.column,message:n.message,code:n.code});for(let n of $l(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 Il(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 a=[],c=[];for(let[u,l]of o){let y=l-(s.get(u)??0);for(let p=0;p<y;p++)a.push(u)}for(let[u,l]of s){let y=l-(o.get(u)??0);for(let p=0;p<y;p++)c.push(u)}if(a.length===0&&c.length===0)return"";let f=[`--- ${i}`,`+++ ${i}`];for(let u=0;u<a.length;u++)f.push(`- ${a[u]}`);for(let u=0;u<c.length;u++)f.push(`+ ${c[u]}`);return f.join(`
|
|
203
|
+
`)}function Fl(e,t,i,n){let r=e.split(`
|
|
204
|
+
`),o=[];function s(l){let y="",p=l<0?-l<<1|1:l<<1;do{let w=p&31;if(p>>>=5,p>0)w|=32;y+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[w]}while(p>0);return y}let a=0,c=0,f=0,u=n.split(`
|
|
205
|
+
`).length;for(let l=0;l<r.length;l++){if(r[l].trim()===""){o.push("");continue}a=0;let y=Math.min(l,u-1),p=[],w=0-a,S=0,x=y-c,E=0-f;p.push(s(w)+s(S)+s(x)+s(E)),a=0,c=y,f=0,o.push(p.join(","))}return{version:3,file:t,sourceRoot:"",sources:[i],sourcesContent:[n],mappings:o.join(";")}}function Nl(e,t){return`${e}
|
|
206
|
+
${yo()}${t}
|
|
207
|
+
`}var Ll=pe(()=>{Li();Al();Rl()});function St(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}
|
|
186
208
|
`;return`${n.trim()}
|
|
187
|
-
`}let
|
|
188
|
-
`;
|
|
189
|
-
`}var
|
|
209
|
+
`}let i="";for(let n=0;n<e.length;n++){if(n>0)i+=`
|
|
210
|
+
`;i+=e[n].trim()}return`${i}
|
|
211
|
+
`}var Wl=()=>{};function zd(e){if(e.includes(`
|
|
190
212
|
`))return`/**
|
|
191
213
|
* ${e}
|
|
192
214
|
*/
|
|
193
215
|
`;return`/** ${e} */
|
|
194
|
-
`}function
|
|
216
|
+
`}function Jd(e){let t=e.indexOf("{");if(t===-1)return-1;let i=e.indexOf("<");if(i===-1||i>t)return t;let n=0,r=!1,o="";for(let s=0;s<e.length;s++){let a=e[s],c=s>0?e[s-1]:"";if(!r&&(a==='"'||a==="'"||a==="`"))r=!0,o=a;else if(r&&a===o&&c!=="\\")r=!1;if(!r){if(a==="<")n++;else if(a===">")n--;else if(a==="{"&&n===0)return s}}return-1}function qd(e,t=!0){return St(e.leadingComments,t)+e.text}function Bl(e,t=!0){let i=St(e.leadingComments,t);if(e.typeAnnotation&&!e.value)return i+e.text;let n="";if(e.isExported)n+="export ";n+="declare ";let r=e.modifiers?.[0]||"const";n+=`${r} `,n+=e.name;let{typeAnnotation:o,value:s}=e;if(s&&s.includes(" satisfies ")){let c=Za(s);if(c)o=c}else if(!o&&s&&s.trim().endsWith("as const"))o=Ie(s,!0);else if(!o&&s&&r==="const"){let c=s.trim(),f=c.startsWith("{")||c.startsWith("[");if(f)co();o=Ie(s,!f)}else if(!o&&s)o=Ie(s,r==="const");if(!o)o="unknown";let a="";if(t&&s&&!e.typeAnnotation&&!s.trim().endsWith("as const")){let c=s.trim();if(r!=="const"){if((o==="string"||o==="number"||o==="boolean")&&c.length>0)a=`@defaultValue ${c}`}else if(c.startsWith("{")||c.startsWith("[")){let f=fo();if(f)if(f.includes(`
|
|
195
217
|
`))a=`@defaultValue
|
|
196
218
|
* \`\`\`ts
|
|
197
219
|
${f.split(`
|
|
198
220
|
`).map((u)=>` * ${u}`).join(`
|
|
199
221
|
`)}
|
|
200
|
-
* \`\`\``;else a=`@defaultValue \`${f}\``}}else if(t&&
|
|
222
|
+
* \`\`\``;else a=`@defaultValue \`${f}\``}}else if(t&&s&&e.typeAnnotation&&Ya(e.typeAnnotation)){co();let c=s.trim(),f=c.endsWith("as const")?c.slice(0,-8).trim():c;Ie(f,!1);let u=fo();if(u)if(u.includes(`
|
|
201
223
|
`))a=`@defaultValue
|
|
202
224
|
* \`\`\`ts
|
|
203
225
|
${u.split(`
|
|
204
226
|
`).map((l)=>` * ${l}`).join(`
|
|
205
227
|
`)}
|
|
206
|
-
* \`\`\``;else a=`@defaultValue \`${u}\``}if(n+=`: ${
|
|
228
|
+
* \`\`\``;else a=`@defaultValue \`${u}\``}if(n+=`: ${o};`,a&&i&&i.includes("@defaultValue"))a="";if(a&&i){let c=i.trimEnd(),f=c.lastIndexOf("*/");if(f!==-1){let u=c.slice(0,f).trimEnd();if(u.startsWith("/** ")&&!u.includes(`
|
|
207
229
|
`))u=`/**
|
|
208
230
|
* ${u.slice(4)}`;return`${u}
|
|
209
231
|
* ${a}
|
|
@@ -212,27 +234,27 @@ ${u.split(`
|
|
|
212
234
|
* ${c.replace(/^\/\/\s*/,"")}
|
|
213
235
|
* ${a}
|
|
214
236
|
*/
|
|
215
|
-
${n}`}if(a)return`${
|
|
216
|
-
`){let i
|
|
217
|
-
`;
|
|
218
|
-
`));for(let
|
|
219
|
-
`);if(
|
|
220
|
-
`;
|
|
221
|
-
`;
|
|
222
|
-
`;
|
|
223
|
-
`;
|
|
224
|
-
`;
|
|
225
|
-
${
|
|
226
|
-
${
|
|
227
|
-
...`:"")),
|
|
228
|
-
`);if(
|
|
229
|
-
--- Generation Statistics ---`),
|
|
230
|
-
Errors:`);for(let
|
|
231
|
-
`)}if(
|
|
232
|
-
entrypoints: ${e.entrypoints.map((
|
|
233
|
-
`+(e.exclude?.length?` exclude: ${e.exclude.map((
|
|
234
|
-
`:"")+"Entrypoints are resolved relative to --root. Pass several by repeating --entrypoints or separating them with commas.";if(t.length===0){if(e.entrypoints.filter((
|
|
235
|
-
${n}`)}let
|
|
236
|
-
${n}`)}async function
|
|
237
|
+
${n}`}if(a)return`${zd(a)}${n}`;return i+n}function Yd(e,t=!0){let i=St(e.leadingComments,t),n=e.text;if(n.startsWith("export declare interface")||n.startsWith("declare interface"))return i+n;let r="";if(e.isExported)r+="export ";if(r+="declare interface ",r+=e.name,e.generics)r+=e.generics;if(e.extends)r+=` extends ${e.extends}`;let o=Jd(e.text);if(o!==-1)r+=` ${e.text.slice(o)}`;else r+=" {}";return i+r}function Zd(e,t=!0){let i=St(e.leadingComments,t);if(e.text.includes("{")&&e.text.includes("}")&&e.text.includes("from"))return i+e.text;let n="";if(e.isExported)n+="export ";if(!e.isExported&&!e.text.includes(" from "))n+="declare ";let r=e.text.indexOf("type ");if(r!==-1){let s=e.text.slice(r),a=s.length;while(a>0&&(s.charCodeAt(a-1)===59||s.charCodeAt(a-1)===32||s.charCodeAt(a-1)===10||s.charCodeAt(a-1)===13))a--;if(a<s.length)s=s.slice(0,a);n+=s}else{if(n+=`type ${e.name}`,e.generics)n+=e.generics;n+=" = any"}let o=n.trimEnd();if(!o.endsWith(";")&&!o.endsWith("}"))n+=";";return i+n}function Xd(e,t=!0){return St(e.leadingComments,t)+e.text}function Qd(e,t=!0){let i=St(e.leadingComments,t),n="";if(e.isExported)n+="export ";if(n+="declare ",e.modifiers?.includes("const"))n+="const ";n+="enum ",n+=e.name;let r=e.text.indexOf("{");if(r!==-1)n+=` ${e.text.slice(r)}`;else n+=" {}";return i+n}function em(e,t=!0){let i=St(e.leadingComments,t);if(e.text.startsWith("declare global"))return i+e.text;if(e.source||(e.name.startsWith('"')||e.name.startsWith("'")||e.name.startsWith("`"))){let o="declare module ";o+=e.name;let s=e.text.indexOf("{");if(s!==-1)o+=` ${e.text.slice(s)}`;else o+=" {}";return i+o}let n="";if(e.isExported)n+="export ";if(!e.modifiers?.includes("declare"))n+="declare ";n+="namespace ",n+=e.name;let r=e.text.indexOf("{");if(r!==-1)n+=` ${e.text.slice(r)}`;else n+=" {}";return i+n}function tm(e){let t=Wt.get(e);if(t)return Wt.delete(e),Wt.set(e,t),t;return null}function Gl(e,t){if(Wt.set(e,t),Wt.size>200){let i=0;for(let n of Wt.keys()){if(i++>=20)break;Wt.delete(n)}}}function im(e){let t=e.indexOf(" from ");if(t===-1)return null;let i=e.slice(t+6).trim(),n=i[0];if(n!=='"'&&n!=="'")return null;let r=i.indexOf(n,1);if(r===-1)return null;let o=i.slice(1,r),s=e.slice(0,t).trim(),a=s.startsWith("import type ");if(s.startsWith("import "))s=s.slice(7).trim();if(s.startsWith("type "))s=s.slice(5).trim();let c=null,f=[],u=!1,l=s.indexOf("{"),y=s.lastIndexOf("}");if(l!==-1&&y!==-1){let p=s.slice(0,l).trim();if(p.endsWith(","))c=p.slice(0,-1).trim()||null;let w=s.slice(l+1,y),S=0;for(let x=0;x<=w.length;x++)if(x===w.length||w.charCodeAt(x)===44){let E=S,k=x;while(E<k&&(w.charCodeAt(E)===32||w.charCodeAt(E)===9||w.charCodeAt(E)===10))E++;while(k>E&&(w.charCodeAt(k-1)===32||w.charCodeAt(k-1)===9||w.charCodeAt(k-1)===10))k--;if(E<k)f.push(w.slice(E,k));S=x+1}}else{let p=s.trim();if(p.startsWith("* as "))c=p.slice(5).trim()||null,u=!0;else c=p||null}return{defaultName:c,namedItems:f,source:o,isTypeOnly:a,isNamespace:u}}function rm(e){let t=tm(e);if(t)return t;let i=[],n=e.indexOf(" from ");if(n===-1)return Gl(e,i),i;let r=e.slice(0,n).trim();if(r.startsWith("import "))r=r.slice(7).trim();if(r.startsWith("type "))r=r.slice(5).trim();let o=r.indexOf("{"),s=r.lastIndexOf("}");if(o!==-1&&s!==-1){let a=r.slice(0,o).trim();if(a.endsWith(",")){let f=a.slice(0,-1).trim();if(f)i.push(f)}else if(a&&!a.includes(","))i.push(a);let c=r.slice(o+1,s).split(",");for(let f=0;f<c.length;f++){let u=c[f].trim();if(!u)continue;if(u.startsWith("type "))u=u.slice(5).trim();let l=u.indexOf(" as ");if(l!==-1)u=u.slice(l+4).trim();if(u)i.push(u)}}else{let a=r.trim();if(a.startsWith("* as ")){let c=a.slice(5).trim();if(c)i.push(c)}else if(a)i.push(a)}return Gl(e,i),i}function am(e){let t=[],i=0;for(let n=0;n<=e.length;n++)if(n===e.length||e[n]===`
|
|
238
|
+
`){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(nm.test(s)||om.test(s)||sm.test(s))t.push(s)}else if(s===""||s.startsWith("//"))continue;else break}return t}function jl(e,t){throw Error(t||`Unexpected value: ${e}`)}function lm(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===95||e===36||e>127}function _l(e){let t=new Set,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&&lm(e.charCodeAt(i)))i++;t.add(e.substring(o,i))}else i++}return t}function Hl(e,t,i=!0,n=["bun"]){let r="",o=t.sourceCode;if(o){let D=0;while(D<o.length&&(o.charCodeAt(D)===32||o.charCodeAt(D)===9||o.charCodeAt(D)===10||o.charCodeAt(D)===13))D++;if(D<o.length-2&&o.charCodeAt(D)===47&&o.charCodeAt(D+1)===47&&o.charCodeAt(D+2)===47){let Y=am(o);if(Y.length>0)for(let ne=0;ne<Y.length;ne++){if(r)r+=`
|
|
239
|
+
`;r+=Y[ne]}}}let s=[],a=[],c=[],f=[],u=[],l=[],y=[],p=[],w=[];for(let D of e){let Y=D.kind;switch(Y){case"import":s.push(D);break;case"function":a.push(D);break;case"variable":c.push(D);break;case"interface":f.push(D);break;case"type":u.push(D);break;case"class":l.push(D);break;case"enum":y.push(D);break;case"module":p.push(D);break;case"export":w.push(D);break;case"namespace":p.push(D);break;case"unknown":break;default:jl(Y,`Unhandled declaration kind: ${Y}`)}}let S=new Set,x=[],E=[],k=[],I=new Set;for(let D of w){let Y=St(D.leadingComments,i);if(D.text.startsWith("export default")){let ne=D.text.endsWith(";")?D.text:`${D.text};`;k.push(Y+ne)}else{let ne=D.text.trim();if(!ne.endsWith(";"))ne+=";";let De=ne.match(cm);if(De){let me=De[1],te=0;for(let re=0;re<=me.length;re++)if(re===me.length||me.charCodeAt(re)===44){let oe=te,de=re;while(oe<de&&me.charCodeAt(oe)<=32)oe++;while(de>oe&&me.charCodeAt(de-1)<=32)de--;if(oe<de)S.add(me.slice(oe,de));te=re+1}}let K=Y+ne;if(!I.has(K))if(I.add(K),K.includes("export type"))x.push(K);else E.push(K)}}let M=new Map;if(s.length>0)for(let D of s){let Y=rm(D.text);for(let ne of Y)M.set(ne,D)}let J=new Set;if(f.length>0){let D=[];for(let Y of a)if(Y.isExported)D.push(Y.text);for(let Y of l)D.push(Y.text);for(let Y of u)D.push(Y.text);if(D.length>0){let Y=_l(D.join(`
|
|
240
|
+
`));for(let ne of f)if(Y.has(ne.name))J.add(ne.name)}}let W=[];if(s.length>0){let D=new Set,Y=[];for(let K of a)if(K.isExported)Y.push(K.text);for(let K of c)if(Y.push(K.text),K.typeAnnotation)Y.push(K.typeAnnotation);else if(K.isExported&&K.value)Y.push(Bl(K,!1));for(let K of f)if(K.isExported||J.has(K.name))Y.push(K.text);for(let K of u)Y.push(K.text);for(let K of l)Y.push(K.text);for(let K of y)Y.push(K.text);for(let K of p)Y.push(K.text);for(let K of w)Y.push(K.text);let ne=Y.join(`
|
|
241
|
+
`);if(ne&&M.size>0){let K=_l(ne);for(let me of M.keys())if(K.has(me))D.add(me)}for(let K of S)if(M.has(K))D.add(K);for(let K of s){if(K.isSideEffect){let z=K.text.trim(),q=z.endsWith(";")?z:`${z};`;W.push(q);continue}let me=im(K.text);if(!me)continue;let{defaultName:te,namedItems:re,source:oe,isTypeOnly:de,isNamespace:G}=me,_=te?D.has(te):!1,U="",ee=0;for(let z=0;z<re.length;z++){let q=re[z],Te=q.charCodeAt(0)===116&&q.startsWith("type ")?q.slice(5).trim():q.trim(),Fe=Te.indexOf(" as ");if(Fe!==-1)Te=Te.slice(Fe+4).trim();if(D.has(Te)){if(ee>0)U+=", ";U+=q,ee++}}if(_||ee>0){let z=de?"import type ":"import ";if(_&&te)if(G)z+=`* as ${te}`;else z+=ee>0?`${te}, { ${U} }`:te;else if(ee>0)z+=`{ ${U} }`;z+=` from '${oe}';`,W.push(z)}}let De=n.length;if(W.length>1){if(Vl!==n)Vl=n,Ul=n.map((re)=>`from '${re}`),Kl=n.map((re)=>`from "${re}`);let K=Ul,me=Kl,te=new Map;for(let re of W){let oe=De;for(let de=0;de<n.length;de++)if(re.includes(K[de])||re.includes(me[de])){oe=de;break}te.set(re,oe)}W.sort((re,oe)=>{let de=te.get(re),G=te.get(oe);return de!==G?de-G:re.localeCompare(oe)})}}for(let D=0;D<W.length;D++){if(r)r+=`
|
|
242
|
+
`;r+=W[D]}for(let D=0;D<x.length;D++){if(r)r+=`
|
|
243
|
+
`;r+=x[D]}let R=[a,c,f,u,l,y,p];for(let D=0;D<R.length;D++){let Y=R[D];for(let ne=0;ne<Y.length;ne++){let De=Y[ne],K="",me=De.kind;switch(me){case"function":K=qd(De,i);break;case"variable":K=Bl(De,i);break;case"interface":K=Yd(De,i);break;case"type":K=Zd(De,i);break;case"class":K=Xd(De,i);break;case"enum":K=Qd(De,i);break;case"module":case"namespace":K=em(De,i);break;case"import":case"export":case"unknown":break;default:jl(me,`Unhandled declaration kind in processor: ${me}`)}if(K){if(r)r+=`
|
|
244
|
+
`;r+=K}}}for(let D=0;D<E.length;D++){if(r)r+=`
|
|
245
|
+
`;r+=E[D]}for(let D=0;D<k.length;D++){if(r)r+=`
|
|
246
|
+
`;r+=k[D]}if(!r&&(s.length>0||w.length>0))return"export {};";return r}var Wt,nm,om,sm,cm,Vl=null,Ul,Kl;var zl=pe(()=>{Wl();mo();Wt=new Map;nm=/^\/\/\/\s*<reference\s+(?:path|types|lib|no-default-lib)\s*=\s*["'][^"']+["']\s*\/>/,om=/^\/\/\/\s*<amd-module\s+name\s*=\s*["'][^"']+["']\s*\/>/,sm=/^\/\/\/\s*<amd-dependency\s+path\s*=\s*["'][^"']+["']/;cm=/export\s+(?:type\s+)?\{\s*([^}]+)\s*\}/,Ul=[],Kl=[]});import{existsSync as Jl}from"fs";import{mkdir as Co,readdir as fm,realpath as um,rm as hm}from"fs/promises";import{availableParallelism as dm}from"os";import{basename as Xl,dirname as xi,extname as mm,isAbsolute as Ti,parse as pm,relative as Ge,resolve as Xe}from"path";async function ql(e,t,i,n,r){let o=Xl(e)||"output.d.ts",s=Ge(xi(e),t),a=`${o}.map`,c=i.lastIndexOf(`
|
|
247
|
+
${yo()}`),f=c===-1?i:i.slice(0,c),u=Fl(f,o,s,n),l=`${e}.map`;return await $i(l,JSON.stringify(u)),Z.debug(` Generated source map: ${Ge(r,l)}`),a}async function Eo(e){let t=Date.now(),i={...Sa,...e};if(i.logLevel)an(i.logLevel);else if(i.verbose)an("debug");let n=new Br;if(i.plugins&&i.plugins.length>0){for(let E of i.plugins)n.register(E),Z.debug(`Registered plugin: ${E.name}`);i=await n.runOnStart(i)}if(await ym(i),i.isolatedDeclarations===void 0)i.isolatedDeclarations=await Ml(i);let r=i.typeMappings?Gr(i.typeMappings):void 0,o=null;if(i.incremental){if(o=new sn(i),i.clearCache){if(Z.debug("Clearing build cache..."),!i.dryRun)o.clear()}else if(o.load()){let E=o.getStats();Z.debug(`Loaded build cache with ${E.entries} entries`)}else Z.debug("No existing build cache found, starting fresh");if(!i.dryRun)Ho(i.cwd)}let s={generationMode:i.isolatedDeclarations?"isolated":"semantic",filesProcessed:0,filesGenerated:0,filesFailed:0,filesValidated:0,validationErrors:0,declarationsFound:0,importsProcessed:0,exportsProcessed:0,durationMs:0,errors:[]},a=0;if(Z.debug("Starting DTS generation..."),Z.debug(`Using ${s.generationMode} declaration generation path`),Z.debug("Config:",i),i.clean&&!i.dryRun)await wm(i);let c=await bm(i);Em(i,c);let f=c.slice(),u=null;if(i.autoIncludeReExports!==!1&&f.length>0){u=await Qr(f,{includeImports:!0});let E=Xe(i.cwd,i.root),k=i.exclude||[],I=[];for(let M of u.reachable){if(f.includes(M))continue;if(!vo(M))continue;if(M.endsWith(".d.ts"))continue;if(M.includes("node_modules"))continue;if(!Ri(M,E)){Z.warn(`Skipping auto-included source outside root: ${Ge(i.cwd,M)}`);continue}if(wo(M,k,E))continue;I.push(M)}if(I.length>0)f=[...f,...I],Z.debug(`Auto-included ${I.length} file(s) reached via relative re-exports`)}if(Sm(f,i),o&&!i.dryRun){let E=o.prune(new Set(f),i.cwd);if(E>0)Z.debug(`Pruned ${E} deleted files from cache`)}if(Z.debug(`Found ${f.length} TypeScript files`),i.progress&&f.length>0){let E=i.parallel?"parallel":"sequential";Z.info(`Processing ${f.length} files (${E})...`)}let l=new Map,y=async(E,k)=>{let I;try{let M=Pi(E,i),J=async(te)=>{if(!i.diff)return;try{let re=await Tt(M),oe=Il(re,te,Ge(i.cwd,M));if(oe)Z.info(`
|
|
248
|
+
${oe}`);else Z.debug(`[no changes] ${M}`)}catch{Z.info(`[new file] ${Ge(i.cwd,M)}`)}},W=(te)=>{if(!i.validate)return 0;let re=Dl(te,M);if(re.isValid)return Z.debug(`[validation] ${M} - OK`),0;Z.warn(`[validation] ${Ge(i.cwd,M)} has ${re.errors.length} error(s):`);for(let oe of re.errors){let de=` Line ${oe.line}:${oe.column}`;if(oe.code)de+=` [${oe.code}]`;if(de+=` - ${oe.message}`,Z.warn(de),oe.suggestion)Z.warn(` Suggestion: ${oe.suggestion}`)}return re.errors.length},R=(te)=>{Z.info(`[dry-run] Would generate: ${M}`),Z.debug("--- Content preview ---"),Z.debug(te.slice(0,500)+(te.length>500?`
|
|
249
|
+
...`:"")),Z.debug("--- End preview ---")};if(o){let te=o.getCachedIfValid(E,i.cwd);if(te){if(i.bundle)l.set(E,te);await J(te);let re=W(te);if(i.dryRun)R(te);else{if(await Co(xi(M),{recursive:!0}),i.declarationMap)I=k??await Tt(E),await ql(M,E,te,I,i.cwd);await $i(M,te,i.lineEnding)}return Z.debug(`[cached] ${Ge(i.cwd,M)}`),{success:!0,file:E,declarationCount:0,importCount:0,exportCount:0,cached:!0,validationErrorCount:re}}}I=k??await Tt(E);let{content:D,declarationCount:Y,importCount:ne,exportCount:De}=await xm(E,I,i,n,r);if(i.bundle)l.set(E,D);let K=D;if(i.prettier||i.indentStyle||i.indentSize){let te=await fl(K,{usePrettier:i.prettier,builtIn:{indentSize:i.indentSize||2,useTabs:i.indentStyle==="tabs",normalizeWhitespace:!0,sortImports:!0,trailingNewline:!0}},M);K=te.content;for(let re of te.warnings??[])Z.warn(`[format] ${re}`)}if(i.declarationMap){let te=`${Xl(M)||"output.d.ts"}.map`;K=Nl(K,te)}await J(K);let me=W(K);if(i.dryRun)R(K);else{if(await Co(xi(M),{recursive:!0}),i.declarationMap&&I)await ql(M,E,K,I,i.cwd);if(await $i(M,K,i.lineEnding),o&&I)o.update(E,I,K,i.cwd);Z.debug(`Generated: ${M}`)}return{success:!0,file:E,declarationCount:Y,importCount:ne,exportCount:De,validationErrorCount:me}}catch(M){let J=Aa(M,E,I);if(i.plugins&&i.plugins.length>0)await n.runOnError(M instanceof Error?M:Error(String(M)),E,I||"");return{success:!1,file:E,declarationCount:0,importCount:0,exportCount:0,dtsError:J,validationErrorCount:0}}},p=i.parallel||i.parallel!==!1&&f.length>=10,w=Jo(i.concurrency,dm?.()??8),S=new Map;if(p&&f.length>1){let E=f.map(async(k)=>{try{let I=await Tt(k);return{file:k,source:I}}catch{return{file:k,source:null}}});for(let k of await Promise.all(E))if(k.source!==null)S.set(k.file,k.source)}let x=(E)=>{if(s.filesProcessed++,E.success){if(E.cached)a++;else s.filesGenerated++,s.declarationsFound+=E.declarationCount,s.importsProcessed+=E.importCount,s.exportsProcessed+=E.exportCount;if(i.validate){if(s.filesValidated++,E.validationErrorCount)s.validationErrors+=E.validationErrorCount}}else if(s.filesFailed++,E.dtsError){s.errors.push(E.dtsError);let k=xa(E.dtsError);if(i.continueOnError)Z.warn(k);else throw Z.error(k),Error(E.dtsError.message)}};if(p)for(let E=0;E<f.length;E+=w){let k=f.slice(E,E+w),I=await Promise.all(k.map((M)=>y(M,S.get(M))));for(let M of I)x(M);if(i.progress){let M=Math.round(s.filesProcessed/f.length*100);Z.info(`[${s.filesProcessed}/${f.length}] ${M}%`)}}else for(let E of f){let k=await y(E);if(x(k),i.progress){let I=Math.round(s.filesProcessed/f.length*100),M=k.cached?"[cached]":"";Z.info(`[${s.filesProcessed}/${f.length}] ${I}% - ${Ge(i.cwd,E)} ${M}`)}}if(o&&!i.dryRun)o.save(),Z.debug("Saved build cache");if(!i.bundle){let E=[];if(u)for(let k of u.unresolved)E.push({from:k.from,specifier:k.specifier,reason:"missing"});if(i.autoIncludeReExports===!1&&f.length>0){let k=new Set(f);for(let I of f){let M;try{M=await Tt(I)}catch{continue}for(let J of Xr(M)){if(!J.specifier.startsWith("."))continue;let W=Ut(J.specifier,I);if(!W.resolved)E.push({from:I,specifier:J.specifier,reason:"missing"});else if(!/\.d\.(?:ts|mts|cts)$/.test(W.resolved)&&!k.has(W.resolved))E.push({from:I,specifier:J.specifier,reason:"not-emitted"})}}}if(E.length>0){let k=[];k.push(`Found ${E.length} re-export(s) pointing at siblings that won't be in the output:`);for(let M of E){let J=Ge(i.cwd,M.from);if(M.reason==="missing")k.push(` ${J} \u2192 '${M.specifier}' (path not found on disk)`);else k.push(` ${J} \u2192 '${M.specifier}' (resolved but not in entrypoints; set autoIncludeReExports: true or add to entrypoints)`)}let I=k.join(`
|
|
250
|
+
`);if(i.failOnUnresolvedReExport)throw Error(I);Z.warn(I),Z.warn('Generated .d.ts files reference modules that were not emitted \u2014 consumers will see "has no exported member" errors.')}}if(i.bundle&&(s.filesGenerated>0||a>0)&&c.length>0)try{Z.debug("Bundling declarations...");let E=c.length===1&&!!i.bundleOutput;for(let k of c){let I=await Qr([k],{includeImports:!0}),M=new Set;for(let D of I.reachable){if(D.endsWith(".d.ts"))continue;if(D.includes("node_modules"))continue;M.add(D)}let J=f.filter((D)=>M.has(D));if(!J.includes(k))J.push(k);let W=Go(k,J,l,{cwd:i.cwd,keepComments:i.keepComments});for(let D of new Set(W.warnings))Z.warn(`[bundle] ${D}`);let R=E?Xe(i.cwd,i.outdir,i.bundleOutput):Pi(k,i);if(i.dryRun)Z.info(`[dry-run] Would bundle ${W.files.length} files to: ${Ge(i.cwd,R)}`);else await Co(xi(R),{recursive:!0}),await $i(R,W.content,i.lineEnding),Z.info(`Bundled ${W.files.length} files to: ${Ge(i.cwd,R)}`);if(E)break}}catch(E){let k=E instanceof Error?E.message:String(E);Z.error(`Bundle failed: ${k}`)}if(s.durationMs=Date.now()-t,i.stats)if(i.outputFormat==="json")console.log(JSON.stringify(s,null,2));else{if(Z.info(`
|
|
251
|
+
--- Generation Statistics ---`),Z.info(`Files processed: ${s.filesProcessed}`),Z.info(`Files generated: ${s.filesGenerated}`),a>0)Z.info(`Files cached: ${a}`);if(s.filesFailed>0)Z.info(`Files failed: ${s.filesFailed}`);if(Z.info(`Declarations found: ${s.declarationsFound}`),Z.info(`Imports processed: ${s.importsProcessed}`),Z.info(`Exports processed: ${s.exportsProcessed}`),s.filesValidated>0){if(Z.info(`Files validated: ${s.filesValidated}`),s.validationErrors>0)Z.info(`Validation errors: ${s.validationErrors}`)}if(Z.info(`Duration: ${s.durationMs}ms`),s.errors.length>0){Z.info(`
|
|
252
|
+
Errors:`);for(let E of s.errors){let k=` - ${E.file}`;if(E.location)k+=`:${E.location.line}:${E.location.column}`;if(E.code)k+=` [${E.code}]`;if(k+=`: ${E.message}`,Z.info(k),E.suggestion)Z.info(` Suggestion: ${E.suggestion}`)}}Z.info(`-----------------------------
|
|
253
|
+
`)}if(i.plugins&&i.plugins.length>0)await n.runOnEnd(s);return Z.debug("DTS generation complete!"),s}async function Yl(e){try{return await um(e)}catch{return Xe(e)}}async function ym(e){let t=Xe(e.cwd,e.outdir);if(e.bundle&&e.bundleOutput){if(Ti(e.bundleOutput))throw Error("bundleOutput must be relative to outdir");let r=Xe(t,e.bundleOutput);if(!Ri(r,t))throw Error("bundleOutput must stay within outdir")}if(!e.clean||e.dryRun)return;if(t===pm(t).root)throw Error("Refusing to clean declarations from the filesystem root");let[i,n]=await Promise.all([Yl(t),Yl(Xe(e.cwd,e.root))]);if(Ri(n,i))throw Error("Refusing to clean an outdir that contains the source root")}function Cm(e){let t=Ai.get(e);if(!t){if(t=new Zl(e),Ai.set(e,t),Ai.size>gm){let i=Ai.keys().next().value;if(i!==void 0)Ai.delete(i)}}return t}async function wm(e){let t=Xe(e.cwd,e.outdir);async function i(n){let r;try{r=await fm(n,{withFileTypes:!0})}catch{return}await Promise.all(r.map(async(o)=>{let s=Xe(n,o.name);if(o.isDirectory()){await i(s);return}if(o.name.endsWith(".d.ts")||o.name.endsWith(".d.mts")||o.name.endsWith(".d.cts")||o.name.endsWith(".d.ts.map")||o.name.endsWith(".d.mts.map")||o.name.endsWith(".d.cts.map"))await hm(s,{force:!0})}))}await i(t)}function wo(e,t,i){if(!t||t.length===0)return!1;let n=Ge(i,e);for(let r of t){let o=Cm(r);if(o.match(n)||o.match(e))return!0}return!1}function Em(e,t){let i=Xe(e.cwd,e.root),n=` root: ${i}
|
|
254
|
+
entrypoints: ${e.entrypoints.map((o)=>JSON.stringify(o)).join(", ")||"(none)"}
|
|
255
|
+
`+(e.exclude?.length?` exclude: ${e.exclude.map((o)=>JSON.stringify(o)).join(", ")}
|
|
256
|
+
`:"")+"Entrypoints are resolved relative to --root. Pass several by repeating --entrypoints or separating them with commas.";if(t.length===0){if(e.entrypoints.filter((o)=>Ti(o)&&Jl(o)&&!Ri(o,i)).length===e.entrypoints.length)return;throw Error(`No source files matched. Nothing was generated.
|
|
257
|
+
${n}`)}let r=e.entrypoints.filter((o)=>{if(vm.test(o))return!1;return!Jl(Ti(o)?o:Xe(i,o))});if(r.length>0)throw Error(`Entrypoint${r.length>1?"s":""} not found: ${r.map((o)=>JSON.stringify(o)).join(", ")}
|
|
258
|
+
${n}`)}async function bm(e){let t=[],i=Xe(e.cwd,e.root),n=e.exclude||[],r=[...e.entrypoints,...e.include??[]];for(let o of r)if(Ti(o)&&vo(o)){if(!o.includes("node_modules")){if(!Ri(o,i)&&e.outputStructure!=="flat")Z.warn(`Skipping entrypoint outside root: ${Ge(e.cwd,o)}`);else if(!wo(o,n,i))t.push(o)}}else{let s=new Zl(o);for await(let a of s.scan({cwd:i,absolute:!0,onlyFiles:!0}))if(vo(a)&&!a.includes("node_modules")){if(!wo(a,n,i))t.push(a)}}return[...new Set(t)].sort()}function Ri(e,t){let i=Ge(t,e);return i!==".."&&!i.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!Ti(i)}function Sm(e,t){let i=new Map;for(let n of e){let r=Pi(n,t),o=i.get(r);if(o&&o!==n)throw Error(`Output path collision: ${Ge(t.cwd,o)} and ${Ge(t.cwd,n)} both emit ${Ge(t.cwd,r)}`);i.set(r,n)}}function vo(e){return/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/.test(e)&&!/\.d\.(?:ts|mts|cts)$/.test(e)}function Pi(e,t){let i=Xe(t.cwd,t.root),n=Ge(i,e).replace(/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/,(r)=>{if(r===".mts"||r===".mjs")return".d.mts";if(r===".cts"||r===".cjs")return".d.cts";return".d.ts"});if(t.outputStructure==="mirror")return Xe(t.cwd,t.outdir,n);else{let r=n.split("/").pop();return Xe(t.cwd,t.outdir,r)}}function $m(e,t,i=""){let n=Ge(xi(e),t).replace(/\\/g,"/");if(n=n.replace(/\.d\.mts$/,"").replace(/\.d\.cts$/,"").replace(/\.d\.ts$/,""),i)n+=i;if(!n.startsWith("."))n=`./${n}`;return n}function Am(e,t,i){let n=Pi(t,i),r=(o)=>{let s=Ut(o,t);if(!s.isRelative||!s.resolved)return o;if(/\.d\.(?:ts|mts|cts)$/.test(s.resolved))return o;let a=o.match(/[?#].*$/)?.[0]??"",c=a?o.slice(0,-a.length):o,f=mm(c),u=/^(?:\.js|\.jsx|\.mjs|\.cjs)$/.test(f)?f:"";return $m(n,Pi(s.resolved,i),u)+a};return e.replace(/\b(from\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(o,s,a,c)=>`${s}${a}${r(c)}${a}`).replace(/\b(import\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(o,s,a,c)=>`${s}${a}${r(c)}${a}`).replace(/\b(import\s*\(\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(o,s,a,c)=>`${s}${a}${r(c)}${a}`)}async function xm(e,t,i,n,r){let o=t;if(n)o=await n.runOnBeforeFile(e,t);let s=ll(o,e,i.keepComments,i.isolatedDeclarations??!1);if(n)s=await n.runOnDeclarations(e,o,s);let a=0,c=0;for(let u=0;u<s.length;u++){let l=s[u];if(l.kind==="import")a++;if(l.kind==="export"||l.isExported)c++}let f=Hl(s,{filePath:e,sourceCode:o,declarations:s},i.keepComments,i.importOrder);if(f=Am(f,e,i),r)f=wl(f,r,{filePath:e});if(i.normalizeOutput===!0||i.declarationOrder)f=pl(f,{lineEnding:"lf",declarationOrder:i.declarationOrder,indent:{style:i.indentStyle??"spaces",size:i.indentSize??2}});if(n)f=await n.runOnAfterFile(e,o,f);return{content:f,declarationCount:s.length,importCount:a,exportCount:c}}var Zl,gm=50,Ai,vm;var Ql=pe(()=>{Li();en();jo();zo();qo();$a();Qo();Ta();cl();ul();hl();gl();vl();Ll();zl();({Glob:Zl}=globalThis.Bun);Ai=new Map;vm=/[*?[\]{}!]/});var ec=pe(()=>{Ql()});import{createHash as Rm}from"crypto";import{existsSync as Pm,readFileSync as Om,writeFileSync as km}from"fs";import{dirname as Mm,join as Dm,relative as tc,resolve as Oi,sep as jr}from"path";import rc from"process";class nc{listeners=new Map;on(e,t){let i=this.listeners.get(e)||[];i.push(t),this.listeners.set(e,i)}async emit(e,t){let i={type:e,timestamp:Date.now(),data:t},n=this.listeners.get(e)||[];for(let r of n)await r(i)}}class oc{manifest;cacheDir;manifestPath;constructor(e,t){this.cacheDir=e,this.manifestPath=Dm(e,"manifest.json"),this.manifest=this.loadManifest(t)}loadManifest(e){try{if(Pm(this.manifestPath)){let t=JSON.parse(Om(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}=Tm("fs");e(this.cacheDir,{recursive:!0}),km(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 Im(e){let t={root:e.root,outdir:e.outdir,entrypoints:e.entrypoints,clean:e.clean,tsconfigPath:e.tsconfigPath};return Rm("md5").update(JSON.stringify(t)).digest("hex")}function sc(e={}){let{onSuccess:t,onError:i,failOnError:n=!0,incremental:r=!1,cacheDir:o=".dtsx-cache",on:s,timeout:a=60000,continueOnError:c=!1,verbose:f=!1,...u}=e,l=new nc;if(s){for(let[y,p]of Object.entries(s))if(p)l.on(y,p)}return{name:"bun-plugin-dtsx",async setup(y){let p=Date.now(),w=null,S=0;try{let x=Lm(u,y),E=Im(x);if(x.clean){let J=Oi(x.cwd??rc.cwd(),x.outdir??"./dist");if(ic.has(J))x.clean=!1;else ic.add(J)}if(r)w=new oc(Oi(o),E);if(await l.emit("start",{type:"start",files:x.entrypoints||[],config:x}),f){if(console.log("[bun-plugin-dtsx] Starting declaration generation..."),r)console.log("[bun-plugin-dtsx] Incremental mode enabled")}let I=await(async()=>new Promise((J,W)=>{let R=setTimeout(()=>{W(new ki(`Generation timed out after ${a}ms`,"TIMEOUT_ERROR",{timeout:a}))},a);Eo(x).then((D)=>{clearTimeout(R),J(D)}).catch((D)=>{clearTimeout(R),W(D)})}))(),M=Date.now()-p;if(w)w.save();if(await l.emit("complete",{type:"complete",stats:I,duration:M,fromCache:S}),f){if(console.log(`[bun-plugin-dtsx] Generation complete in ${M}ms`),S>0)console.log(`[bun-plugin-dtsx] ${S} files served from cache`)}if(t)await t(I)}catch(x){let E=Fm(x);if(await l.emit("error",{type:"error",error:E}),i)await i(E);else{if(console.error("[bun-plugin-dtsx] Error generating declarations:"),console.error(` Code: ${E.code}`),console.error(` Message: ${E.message}`),E.context)console.error(` Context: ${JSON.stringify(E.context)}`);if(f&&E.stack)console.error(` Stack: ${E.stack}`)}if(n&&!c)throw E}}}}function Fm(e){if(e instanceof ki)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 ki(e.message,t,{originalError:e.name},e)}return new ki(String(e),"GENERATION_ERROR")}function Nm(e){let t=e.map((n)=>Mm(n).split(jr)),i=t[0];for(let n of t.slice(1)){let r=0;while(r<i.length&&r<n.length&&i[r]===n[r])r++;i=i.slice(0,r)}return i.join(jr)||jr}function Lm(e,t){let i=e.cwd||rc.cwd(),n=t?.config?.entrypoints,r=e.outdir||e.build?.config.outdir||t?.config.outdir||"./dist",o=e.root||e.build?.config.root||t?.config.root;if(!o&&n?.length){let a=Nm(n.map((c)=>Oi(i,c)));o=tc(i,a)||"."}o=o||"./src";let s=e.entrypoints;if(!s)if(n?.length){let a=Oi(i,o),c=[];for(let f of n){let u=Oi(i,f);if(u===a||u.startsWith(a+jr))c.push(tc(a,u));else console.warn(`[bun-plugin-dtsx] Skipping entrypoint outside root "${o}": ${f}`)}s=c.length?c:["index.ts"]}else s=["index.ts"];return{...e,cwd:i,root:o,entrypoints:s,outdir:r,clean:e.clean??!0,tsconfigPath:e.tsconfigPath}}var Tm,ki,ic;var ac=pe(()=>{ec();Tm=import.meta.require;ki=class ki extends Error{code;context;cause;constructor(e,t,i,n){super(e);if(this.name="DtsxPluginError",this.code=t,this.context=i,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}}};ic=new Set});import{mkdir as Wm,stat as Bm}from"fs/promises";import{bold as bo,dim as So,green as Gm,italic as lc,log as jm}from"@stacksjs/cli";import{path as ct}from"@stacksjs/path";import{glob as cc}from"@stacksjs/storage";async function _m(e){let t=await cc([ct.resolve(e,"dist","**/*.d.ts")],{absolute:!0}),i=new Bun.Transpiler({loader:"ts",target:"bun"});for(let n of t){let r=await Bun.file(n).text();try{i.transformSync(r)}catch(o){throw Error(`Invalid declaration generated at ${n}: ${o instanceof Error?o.message:String(o)}`)}}}async function Vm(e){let t=ct.resolve(e,"dist","index.js");if(!await Bun.file(t).exists())return;let i=Bun.spawnSync({cmd:[process.execPath,"-e",`await import(${JSON.stringify(t)})`],stdout:"ignore",stderr:"pipe",env:{...process.env,NODE_ENV:"test"}});if(i.exitCode===0)return;let n=new TextDecoder().decode(i.stderr??new Uint8Array);if(/needs to refer to a top-level declared variable|does not provide an export named|Export named .* not found/i.test(n))throw Error(`Built package at ${t} cannot be imported: ${n.trim().split(`
|
|
237
259
|
`)[0]}
|
|
238
|
-
This is the minified-barrel failure. Build with \`transpilePackage\` instead of a minifying \`Bun.build\`.`)}async function
|
|
260
|
+
This is the minified-barrel failure. Build with \`transpilePackage\` instead of a minifying \`Bun.build\`.`)}async function F0(e){let i=Date.now()-e.startTime,n=e.pkgName??`@stacksjs/${ct.basename(e.dir)}`;if(e.result.errors&&e.result.errors.length>0)throw console.error("Build errors:",e.result.errors),Error(`Build failed with errors: ${JSON.stringify(e.result.errors)}`);else if(e.result.success!==void 0&&!e.result.success){let o=e.result.logs?.[0]||"Unknown build error";throw console.log(o),Error(`Build failed: ${o}`)}await _m(e.dir),await Vm(e.dir);let r=await cc([ct.resolve(e.dir,"dist","**/*")],{absolute:!0});for(let o of r){let s=await Bm(o),a;if(s.size<1048576)a=`${(s.size/1024).toFixed(2)}kb`;else a=`${(s.size/1024/1024).toFixed(2)}mb`;let c=ct.relative(e.dir,o).replace("dist/","");console.log(`${bo(So(`[${a}]`))} ${So("dist/")}${c}`)}console.log(`${bo(So(`[${i}ms]`))} Built ${lc(bo(Gm(n)))}`)}async function N0(e){let t=e.pkgName??`@stacksjs/${ct.basename(e.dir)}`;if(e.styled===!1)console.log(`Building ${t}...`);else jm.info(`Building ${lc(t)}...`);return{startTime:Date.now()}}async function L0(e){await Promise.resolve().then(() => ac());let i=ct.resolve(e.dir,"src"),n=ct.resolve(e.dir,"dist"),r=(await Array.fromAsync(new Bun.Glob("**/*.ts").scan({cwd:i}))).filter((s)=>!s.endsWith(".d.ts")).filter((s)=>!s.endsWith(".test.ts")&&!s.endsWith(".spec.ts"));await Bun.build({entrypoints:r.map((s)=>ct.resolve(i,s)),outdir:n,root:i,target:"bun",format:"esm",splitting:!1,external:e.external??Um(),plugins:[sc({root:i,outdir:n})]});let o=new Bun.Transpiler({loader:"ts",target:"bun",minifyWhitespace:!0});for(let s of r){let a=o.transformSync(await Bun.file(ct.resolve(i,s)).text());a=a.replace(/(['"])(\.\.?\/[^'"]+?)\.tsx?\1/g,"$1$2.js$1");let c=ct.resolve(n,s.replace(/\.ts$/,".js"));await Wm(ct.dirname(c),{recursive:!0}),await Bun.write(c,a)}}function Um(e=[]){let t=[];try{let i=wc("fs"),n=JSON.parse(i.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((i)=>`${i}/*`),"bun-queue","ioredis","localtunnels","localtunnels/*","@craft-native/ts","ts-md","meilisearch","algoliasearch","@opensearch-project/opensearch","*.yaml","*.yml",...e]}export{Um as frameworkExternal,N0 as intro,F0 as outro,L0 as transpilePackage,_m as validateDeclarations,Vm as validateRuntimeExports};
|