@stacksjs/build 0.74.47 → 0.74.48
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 +62 -62
- package/package.json +5 -5
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var ce=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};var dc=import.meta.require;function
|
|
2
|
+
var ce=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};var dc=import.meta.require;function Rs(e,t){let r=Number.isFinite(t)?Math.max(1,Math.floor(t)):1;if(e===void 0||!Number.isFinite(e))return r;return Math.max(1,Math.floor(e))}var Os=()=>{};function or(e){if(mc)return Bun.hash(e);let t=0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);t=(t<<5)-t+n,t=t&t}return t}var mc;var Ji=ce(()=>{mc=typeof globalThis.Bun?.hash==="function"});function Ms(e){return e.endsWith(".vue")}function pc(e){let t={script:null,scriptSetup:null},r=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,n;while((n=r.exec(e))!==null){let i=n[1]||"",s=/lang\s*=\s*["']([^"']+)["']/i.exec(i)?.[1]?.toLowerCase()??"js",o={content:n[2]??"",attrs:i,setup:/\bsetup\b/.test(i),lang:s};if(o.setup)t.scriptSetup=o;else t.script=o}return t}function qe(e,t){let r=e[t];t++;while(t<e.length){let n=e[t];if(n==="\\"){t+=2;continue}if(n===r)return t+1;t++}return t}function Ze(e,t){t++;let r=0;while(t<e.length){let n=e[t];if(n==="\\"){t+=2;continue}if(n==="`"&&r===0)return t+1;if(n==="$"&&e[t+1]==="{"){r++,t+=2;continue}if(n==="}"){if(r>0)r--;t++;continue}t++}return t}function lt(e,t){if(e[t+1]==="/"){let r=e.indexOf(`
|
|
3
3
|
`,t+2);return r===-1?e.length:r+1}if(e[t+1]==="*"){let r=e.indexOf("*/",t+2);return r===-1?e.length:r+2}return t+1}function Yi(e,t){let r=e[t];if(r==='"'||r==="'")return qe(e,t);if(r==="`")return Ze(e,t);if(r==="/"&&(e[t+1]==="/"||e[t+1]==="*"))return lt(e,t);return t}function Zi(e){let t=e.split(""),r=0;while(r<e.length){let n=Yi(e,r);if(n>r){for(let i=r;i<n;i++)if(t[i]!==`
|
|
4
4
|
`&&t[i]!=="\r")t[i]=" ";r=n;continue}r++}return t.join("")}function We(e,t,r,n){let i=0,s=t;while(s<e.length){let o=e[s];if(o==='"'||o==="'"){s=qe(e,s);continue}if(o==="`"){s=Ze(e,s);continue}if(o==="/"&&(e[s+1]==="/"||e[s+1]==="*")){s=lt(e,s);continue}if(o===r)i++;else if(o===n){if(i--,i===0)return s}s++}return-1}function Xi(e,t){let r=0,n=t;while(n<e.length){let i=e[n];if(i==='"'||i==="'"){n=qe(e,n);continue}if(i==="`"){n=Ze(e,n);continue}if(i==="/"&&(e[n+1]==="/"||e[n+1]==="*")){n=lt(e,n);continue}if(i==="="&&e[n+1]===">"){n+=2;continue}if(i==="<")r++;else if(i===">"){if(r--,r===0)return n}n++}return-1}function Gt(e,t=","){let r=[],n=0,i="",s=0;while(s<e.length){let o=e[s];if(o==='"'||o==="'"){let a=qe(e,s);i+=e.slice(s,a),s=a;continue}if(o==="`"){let a=Ze(e,s);i+=e.slice(s,a),s=a;continue}if(o==="/"&&(e[s+1]==="/"||e[s+1]==="*")){s=lt(e,s);continue}if(o==="{"||o==="["||o==="("||o==="<")n++;else if(o==="}"||o==="]"||o===")"||o===">")n--;if(o===t&&n===0){r.push(i),i="",s++;continue}i+=o,s++}if(i.trim()!=="")r.push(i);return r}function cr(e){let t=e.trim();if(!t.startsWith("{"))return[];let r=We(t,0,"{","}");if(r===-1)return[];let n=t.slice(1,r),i=[];for(let s of Gt(n)){let o=-1,a=0;for(let u=0;u<s.length;u++){let l=s[u];if(l==='"'||l==="'"){u=qe(s,u)-1;continue}if(l==="`"){u=Ze(s,u)-1;continue}if(l==="{"||l==="["||l==="("||l==="<")a++;else if(l==="}"||l==="]"||l===")"||l===">")a--;else if(l===":"&&a===0){o=u;break}}if(o!==-1){i.push({key:ar(s.slice(0,o).trim()),value:s.slice(o+1).trim(),isMethod:!1});continue}let c=/^([A-Za-z_$][\w$]*|['"][^'"]+['"])\s*\(/.exec(s.trim());if(c){i.push({key:ar(c[1]),value:s.trim(),isMethod:!0});continue}let f=s.trim();if(f)i.push({key:ar(f),value:"",isMethod:!1})}return i}function ar(e){if(e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);return e}function lr(e){return/^[A-Za-z_$][\w$]*$/.test(e)?e:JSON.stringify(e)}function fr(e,t){let r=new RegExp(`\\b${t}\\b`,"g"),n;while((n=r.exec(e))!==null){let i=n.index+n[0].length;while(i<e.length&&/\s/.test(e[i]))i++;let s=null;if(e[i]==="<"){let c=Xi(e,i);if(c===-1)return null;s=e.slice(i+1,c).trim(),i=c+1;while(i<e.length&&/\s/.test(e[i]))i++}if(e[i]!=="(")continue;let o=We(e,i,"(",")");if(o===-1)return null;let a=Gt(e.slice(i+1,o));return{generic:s,arg:a.length>0?a[0].trim():null}}return null}function gc(e,t){let r=Ds(e,t);if(!r)return null;return r.kind==="interface"?e.slice(r.bodyStart,r.end):e.slice(r.bodyStart,r.end).trim()}function Ds(e,t){let r=new RegExp(`\\binterface\\s+${t}\\b[^{]*\\{`,"m").exec(e);if(r){let i=r.index+r[0].length-1,s=We(e,i,"{","}");if(s!==-1)return{kind:"interface",start:r.index,end:s+1,bodyStart:i}}let n=new RegExp(`\\btype\\s+${t}\\b[^=]*=`,"m").exec(e);if(n){let i=n.index+n[0].length,s=0,o=i;while(i<e.length){let a=e[i];if(a==='"'||a==="'"){i=qe(e,i);continue}if(a==="`"){i=Ze(e,i);continue}if(a==="{"||a==="["||a==="("||a==="<")s++;else if(a==="}"||a==="]"||a===")"||a===">")s--;else if((a===";"||a===`
|
|
5
5
|
`)&&s===0)break;i++}return{kind:"type",start:n.index,end:i,bodyStart:o}}return null}function yc(e){let t=e.search(/\bas\s+PropType\s*</);if(t===-1)return null;let r=e.indexOf("<",t),n=Xi(e,r);if(n===-1)return null;if(e.slice(n+1).trim()!=="")return null;return e.slice(r+1,n).trim()}function qi(e){let t=e.trim(),r=yc(t);if(r!==null)return{type:r,optional:!0};if(t==="null")return{type:"unknown",optional:!0};if(t.startsWith("[")){let n=We(t,0,"[","]");if(n!==-1){let i=Gt(t.slice(1,n)).map((s)=>qi(s).type).filter((s)=>s!=="unknown");return{type:i.length>0?[...new Set(i)].join(" | "):"unknown",optional:!0}}}if(t.startsWith("{")){let n=cr(t),i=n.find((c)=>c.key==="type"),s=n.find((c)=>c.key==="required"),o=i?qi(i.value).type:"unknown",a=!(s&&s.value.trim()==="true");return{type:o,optional:a}}if(ks[t])return{type:ks[t],optional:!0};if(/^[A-Za-z_$][\w$.]*$/.test(t))return{type:t,optional:!0};return{type:"unknown",optional:!0}}function Fr(e){let t=e.trim();if(t.startsWith("{")){let r=cr(t);if(r.length===0)return"{}";return`{ ${r.map((n)=>{if(n.isMethod||n.value==="")return`${lr(n.key)}?: unknown`;let i=qi(n.value);return`${lr(n.key)}${i.optional?"?":""}: ${i.type}`}).join(", ")} }`}if(t.startsWith("[")){let r=We(t,0,"[","]");if(r===-1)return null;let n=Gt(t.slice(1,r)).map((i)=>ar(i.trim())).filter((i)=>i!=="");if(n.length===0)return"{}";return`{ ${n.map((i)=>`${lr(i)}?: unknown`).join(", ")} }`}return null}function Cc(e){let t=e.trim();if(!t.startsWith("["))return null;let r=We(t,0,"[","]");if(r===-1)return null;let n=Gt(t.slice(1,r)).map((i)=>i.trim());if(n.length===0)return"{}";if(!n.every((i)=>i.startsWith("'")&&i.endsWith("'")||i.startsWith('"')&&i.endsWith('"')))return"string[]";return`[${n.map((i)=>JSON.stringify(ar(i))).join(", ")}]`}function wc(e){let t=e.trim();if(!t.startsWith("{"))return null;let r=cr(t);if(r.length===0)return"{}";return`{ ${r.map((n)=>`${JSON.stringify(n.key)}: (...args: any[]) => void`).join(", ")} }`}function Is(e){return Cc(e)??wc(e)}function vc(e){let t=[],r=0,n="",i=0;while(i<e.length){let s=e[i];if(s==='"'||s==="'"){let o=qe(e,i);n+=e.slice(i,o),i=o;continue}if(s==="`"){let o=Ze(e,i);n+=e.slice(i,o),i=o;continue}if(s==="/"&&(e[i+1]==="/"||e[i+1]==="*")){let o=lt(e,i);n+=e.slice(i,o),i=o;continue}if(s==="="&&e[i+1]===">"){n+="=>",i+=2;continue}if(s==="{"||s==="["||s==="("||s==="<")r++;else if(s==="}"||s==="]"||s===")"||s===">")r--;if((s===";"||s===","||s===`
|
|
@@ -17,19 +17,19 @@ var ce=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};
|
|
|
17
17
|
`)o++;let a=e.slice(r+2,o).trim();if(a!==""&&!a.includes("*/"))t+=`/* ${a} */`;r=o;continue}if(s===`
|
|
18
18
|
`){let o=n(),a=i(r+1);if(o===""||a===""){r++;continue}let c=Tc(t);if(!c&&("{;,(<:=[".includes(o)||"}),]>;|&".includes(a))){if(!t.endsWith(" ")&&!t.endsWith(";"))t+=" "}else if(c){if(!t.endsWith(" "))t+=" "}else{if(t.endsWith(" "))t=t.slice(0,-1);t+="; "}r++;while(r<e.length&&(e[r]===" "||e[r]==="\t"))r++;continue}t+=s,r++}return t}function Tc(e){let t=e.length-1;while(t>=0&&/\s/.test(e[t]))t--;if(t<1||e[t]!=="/"||e[t-1]!=="*")return!1;let r=e.lastIndexOf("/*",t);if(r===-1)return!1;for(let n=r-1;n>=0;n--){let i=e[n];if(/\s/.test(i))continue;return"{;,(<:".includes(i)}return!0}function Nr(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=fr(n,"defineProps");if(!i)continue;if(i.generic){let s=i.generic;if(s.startsWith("{"))return{type:s};if(/^[A-Za-z_$][\w$]*$/.test(s)){for(let o of r){let a=Ds(o,s);if(!a)continue;let c=gc(o,s);if(c===null)continue;return{type:c,inlinedLocal:{name:s,declText:o.slice(a.start,a.end)}}}return{type:s}}return{type:s}}if(i.arg){let s=Fr(i.arg);if(s!==null)return{type:s}}}return null}function rn(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=fr(n,"defineEmits");if(!i)continue;if(i.generic)return Ec(i.generic)??i.generic;if(i.arg){let s=Is(i.arg);if(s!==null)return s}}return null}function nn(e,t){let r=[e,t].filter((n)=>n!==null);for(let n of r){let i=fr(n,"defineExpose");if(!i||!i.arg||!i.arg.startsWith("{"))continue;let s=cr(i.arg);if(s.length===0)return null;return`{ ${s.map((o)=>{if(o.value===""&&/^[A-Za-z_$][\w$]*$/.test(o.key))return`${lr(o.key)}: typeof ${o.key}`;let a=o.isMethod||/=>|^\s*function\b/.test(o.value);return`${lr(o.key)}: ${a?"(...args: any[]) => any":"unknown"}`}).join(", ")} }`}return null}function Fs(e){let t=pc(e),r="",n=null,i=null;if(t.script){let C=en(t.script.content);if(C.passthrough)return t.scriptSetup?`${t.script.content}
|
|
19
19
|
${t.scriptSetup.content}`:t.script.content;if(r=C.script,C.options){let T=Mr(C.options,"props");if(T)n=Fr(T);let k=Mr(C.options,"emits");if(k)i=Is(k)}}let s=t.scriptSetup?.content??null,o=s!==null?Qi(s):null,a=Nr(s,s!==null?null:r),c=a?.type??n??"{}",f=rn(s,null)??i,u=nn(s,null),l=a?.inlinedLocal;if(l){if(r=Ir(r,l.name,l.declText),o!==null)o=Ir(o,l.name,l.declText)}let g=[c,u??"{}"];if(f)g.push("{}","{}","{}","{}","{}",f);let d=tn(`DefineComponent<${g.join(", ")}>`),v=[],b=Dr(r,d);if(b.trim()!=="")v.push(b);if(o&&o.trim()!==""){let C=Dr(o,d);if(C.trim()!=="")v.push(C)}return v.push("import type { DefineComponent } from 'vue'"),v.push(`type __DtsxComponentType = ${d}`),v.push("const __dtsx_component__: __DtsxComponentType = null as unknown as __DtsxComponentType"),v.push("export default __dtsx_component__"),v.join(`
|
|
20
|
-
`)}var ks;var sn=ce(()=>{ks={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 Ls(e){return e.endsWith(".stx")}function
|
|
20
|
+
`)}var ks;var sn=ce(()=>{ks={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 Ls(e){return e.endsWith(".stx")}function Pc(e){let t=[],r=/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi,n;while((n=r.exec(e))!==null){let i=n[1]??"",s=/\blang\s*=\s*["']([^"']+)["']/i.exec(i)?.[1]?.toLowerCase()??(/\b(?:type\s*=\s*["'](?:text\/)?typescript["']|typescript)\b/i.test(i)?"ts":"js"),o=/\bserver\b/i.test(i)?"server":/\bclient\b/i.test(i)?"client":"universal";t.push({content:n[2]??"",kind:"script",attrs:i,context:o,lang:s,start:n.index})}return t}function Rc(e){let t=[],r=/^[ \t]*@ts[ \t]*(?:\r?\n|$)/gm,n;while((n=r.exec(e))!==null){let i=r.lastIndex,s=/^[ \t]*@endts[ \t]*(?:\r?\n|$)/gm;s.lastIndex=i;let o=s.exec(e),a=o?.index??e.length;if(t.push({content:e.slice(i,a),kind:"ts",attrs:"",context:"universal",lang:"ts",start:n.index}),!o)break;r.lastIndex=s.lastIndex}return t}function Oc(e){return[...Pc(e),...Rc(e)].sort((t,r)=>t.start-r.start)}function kc(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 Mc(e){let t=/(?:\$?props)\s+as\s+/g,r;while((r=t.exec(e))!==null){let n=t.lastIndex;while(n<e.length&&/\s/.test(e[n]))n++;if(e[n]==="{"){let o=We(e,n,"{","}");if(o!==-1)return e.slice(n,o+1).trim();continue}let i=/^[A-Za-z_$][\w$]*/.exec(e.slice(n))?.[0];if(!i)continue;let s=n+i.length;while(s<e.length&&/\s/.test(e[s]))s++;if(e[s]==="<"){let o=We(e,s,"<",">");if(o!==-1)s=o+1}return e.slice(n,s).trim()}return null}function Dc(e){return/\b(?:const|let|var)\s+\$?props\s*:\s*([^=;\n]+)/.exec(e)?.[1]?.trim()??null}function Ic(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 Fc(e,t){if(!e||e==="unknown")return t;if(t==="unknown"||e===t)return e;return[...new Set([...e.split(" | "),...t.split(" | ")])].join(" | ")}function Nc(e){let t=Zi(e),r=new Map,n=/\$props(?:\.([A-Za-z_$][\w$]*)|\[\s*(['"])([^'"\n]+)\2\s*\])/g,i;while((i=n.exec(e))!==null){if(t.slice(i.index,i.index+6)!=="$props")continue;let s=i[1]??i[3],o=Ic(e.slice(n.lastIndex));r.set(s,Fc(r.get(s),o))}if(r.size===0)return null;return{type:`{ ${[...r].map(([s,o])=>`${/^[A-Za-z_$][\w$]*$/.test(s)?s:JSON.stringify(s)}?: ${o}`).join(", ")} }`}}function Lc(e){let t=Nr(e,null);if(t)return t;let r=Mc(e)??Dc(e);if(!r)return Nc(e);if(/^[A-Za-z_$][\w$]*$/.test(r)){let n=r.replace(/[$]/g,"\\$&");if(new RegExp(`\\bexport\\s+(?:declare\\s+)?(?:interface|type)\\s+${n}\\b`).test(e))return{type:r}}return Nr(`${e}
|
|
21
21
|
defineProps<${r}>()`,null)}function Wc(e){return Qi(e)}function Ns(e){let t=Zi(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 Bc(e){let t=[],r=0,n=0,i=0;while(i<e.length){let o=e[i],a=Yi(e,i);if(a>i){i=a;continue}if(o==="{"||o==="["||o==="(")n++;else if(o==="}"||o==="]"||o===")")n=Math.max(0,n-1);if((o===";"||o===`
|
|
22
|
-
`)&&n===0){let c=i+1;if(!Ns(e.slice(r,c)))t.push([r,c]);r=c}i++}if(r<e.length&&!Ns(e.slice(r)))t.push([r,e.length]);let s=e;for(let o=t.length-1;o>=0;o--)s=s.slice(0,t[o][0])+s.slice(t[o][1]);return s}function Ws(e){let t=
|
|
22
|
+
`)&&n===0){let c=i+1;if(!Ns(e.slice(r,c)))t.push([r,c]);r=c}i++}if(r<e.length&&!Ns(e.slice(r)))t.push([r,e.length]);let s=e;for(let o=t.length-1;o>=0;o--)s=s.slice(0,t[o][0])+s.slice(t[o][1]);return s}function Ws(e){let t=Oc(e).filter(kc).map((b)=>b.content).join(`
|
|
23
23
|
`),r=null,n=en(t);if(n.passthrough)return t;if(t=n.script,n.options){let b=Mr(n.options,"props");if(b)r=Fr(b)}let i=t,s=Wc(t),o=Lc(i),a=o?.type??r??"{}",c=rn(i,null),f=nn(i,null),u=fr(i,"defineSlots")?.generic??null,l=o?.inlinedLocal;if(l)s=Ir(s,l.name,l.declText);let g=`DefineComponent<${a}>`,d=[];if(c)d.push(`readonly __stxEmits?: ${c}`);if(u)d.push(`readonly __stxSlots?: ${u}`);if(f)d.push(`readonly __stxExposed?: ${f}`);if(d.length>0)g+=` & { ${d.join(", ")} }`;g=tn(g),s=Bc(Dr(s,g));let v=["import type { DefineComponent } from '@stacksjs/stx'",`type __DtsxStxComponentType = ${g}`,"const __dtsx_component__: __DtsxStxComponentType = null as unknown as __DtsxStxComponentType","export default __dtsx_component__"];if(s.trim()!=="")v.push(s);return v.join(`
|
|
24
24
|
`)}var Bs=ce(()=>{sn()});function Gc(e){if(e.indexOf("/*")===-1)return e.trim();let t=[],r=0,n=0,i=e.length;while(n<i)if(e.charCodeAt(n)===47&&n+1<i&&e.charCodeAt(n+1)===42){if(n>r)t.push(e.substring(r,n));n+=2;while(n<i-1){if(e.charCodeAt(n)===42&&e.charCodeAt(n+1)===47){n+=2;break}n++}r=n}else n++;if(r<i)t.push(e.substring(r));return t.join("").trim()}function fn(){Gr=!0,_e=null}function un(){Gr=!1;let e=_e;return _e=null,e}function hn(e){let t=e.length;if(t===0)return!1;let r=0;if(e.charCodeAt(r)===45)r++;if(r>=t)return!1;let n=r;while(r<t&&e.charCodeAt(r)>=48&&e.charCodeAt(r)<=57)r++;if(r===n)return!1;if(r<t&&e.charCodeAt(r)===46){r++;let i=r;while(r<t&&e.charCodeAt(r)>=48&&e.charCodeAt(r)<=57)r++;if(r===i)return!1}return r===t}function jc(e){for(let t=0,r=e.length-1;t<r;t++){let n=e.charCodeAt(t);if(n<48||n>57)return!1}return!0}function on(e,t){let r=0,n=0;while((n=e.indexOf(t,n))!==-1)r++,n+=t.length;return r}function Gs(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 Lr(e){let t=e.trim();if(t.length<3||t.charCodeAt(0)!==60)return!1;if(t.startsWith("<>"))return t.endsWith("</>");let r=t.charCodeAt(1);if(!(r>=65&&r<=90||r>=97&&r<=122||r===36||r===95))return!1;let n=2;while(n<t.length&&Gs(t.charCodeAt(n)))n++;let i=t.slice(1,n),s=t.charCodeAt(n);if(s>32&&s!==62&&s!==47)return!1;if(t.endsWith("/>"))return!0;let o=t.lastIndexOf("</");if(o===-1)return!1;let a=o+2;while(a<t.length&&Gs(t.charCodeAt(a)))a++;return t.slice(o+2,a)===i&&t.charCodeAt(a)===62&&a===t.length-1}function ur(e){let t=e.length,r=!1;for(let o=1;o<t;o++)if(e.charCodeAt(o)<=32&&e.charCodeAt(o-1)<=32){r=!0;break}if(!r)for(let o=0;o<t;o++){let a=e.charCodeAt(o);if(a===10||a===13||a===9){r=!0;break}}if(!r)return e;let n=[],i=-1,s=!1;for(let o=0;o<t;o++)if(e.charCodeAt(o)<=32){if(!s){if(i>=0)n.push(e.substring(i,o));n.push(" "),s=!0,i=-1}}else{if(s||i<0)i=o;s=!1}if(i>=0)n.push(e.substring(i));return n.join("")}function Te(e,t=!1,r=!1,n=0){if(!e||typeof e!=="string")return"unknown";if(n>=20)return"unknown";let i=e.trim();if(Lr(i))return"JSX.Element";if(i.startsWith("BigInt("))return"bigint";if(i.startsWith("Symbol.for("))return"symbol";if(i.includes(".raw`")||i.includes("String.raw`"))return"string";if(i.startsWith("`")&&i.endsWith("`")){if(!t||i.includes("${")||i.includes(`
|
|
25
|
-
`)||i.includes("\r"))return"string";return i}if(i.charCodeAt(0)===39||i.charCodeAt(0)===34){let o=_c(i);if(o!==null){if(o==="string"||!t)return"string";return o}}if(hn(i)){if(!t)return"number";return i}if(i==="true"||i==="false"){if(!t)return"boolean";return i}if(i==="null")return"null";if(i==="undefined")return"undefined";if(i.startsWith("[")&&i.endsWith("]"))return an(i,t,n+1);if(i.startsWith("{")&&i.endsWith("}"))return tf(i,t,n+1);if(i.startsWith("class ")||i.startsWith("class{"))return Qc(i);if(i.startsWith("new "))return Xc(i);if(i.endsWith("as const")){let o=i.slice(0,-8).trim();if(o.startsWith("[")&&o.endsWith("]")){let a=o.slice(1,-1).trim();if(!a)return"readonly []";let c=Wr(a),f=[];for(let u=0;u<c.length;u++)f.push(Te(c[u].trim(),!0,!1,n+1));return`readonly [${f.join(", ")}]`}return Te(o,!0,r,n+1)}if(Br(i)!==-1||i.startsWith("function")||i.startsWith("async"))return Xs(i,r,n,t);if(i.startsWith("`")&&i.endsWith("`"))return Zc(i,t);if(i.startsWith("Promise."))return Js(i,t,n);if(i.startsWith("await "))return"unknown";if(i.charCodeAt(i.length-1)===110&&i.length>1&&jc(i)){if(t)return i;return"bigint"}if(i.startsWith("Symbol(")||i==="Symbol.for")return"symbol";let s=qs(i);if(s!==null)return s;if(zc(i))return"boolean";if(Hc(i))return"number";return"unknown"}function js(e){let t=e.charCodeAt(0);if(t!==39&&t!==34)return!1;return
|
|
26
|
-
`;if(r==="t")return"\t";if(r==="r")return"\r";if(r==="0")return"\x00";return r})}function Kc(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function Hc(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 zc(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=
|
|
27
|
-
`)||e.includes("\r"))return"string";return e}function Xc(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&&(ut(e.charCodeAt(t))||e.charCodeAt(t)===46))t++;if(t===r)return"unknown";let i=e.slice(r,t);{let s=e.slice(t),o=s;if(s.startsWith("<")){let c=0,f=-1;for(let u=0;u<s.length;u++)if(s[u]==="<")c++;else if(s[u]===">"){if(c--,c===0){f=u;break}}if(f!==-1){let u=s.slice(0,f+1);o=s.slice(f+1);let l=o.indexOf("(");if(l!==-1){let g=0,d=-1;for(let v=l;v<o.length;v++)if(o[v]==="(")g++;else if(o[v]===")"){if(g--,g===0){d=v;break}}if(d!==-1){if(o.slice(d+1).trimStart().startsWith("."))return"unknown"}}return`${i}${u}`}}let a=o.indexOf("(");if(a!==-1){let c=0,f=-1;for(let u=a;u<o.length;u++)if(o[u]==="(")c++;else if(o[u]===")"){if(c--,c===0){f=u;break}}if(f!==-1){if(o.slice(f+1).trimStart().startsWith("."))return"unknown"}}switch(i){case"Date":return"Date";case"Map":return"Map<any, any>";case"Set":return"Set<any>";case"WeakMap":return"WeakMap<any, any>";case"WeakSet":return"WeakSet<any>";case"RegExp":return"RegExp";case"Error":return"Error";case"Array":return"any[]";case"Object":return"object";case"Function":return"Function";case"Promise":return"Promise<any>";default:return i}}return"unknown"}function Qc(e){return"{ new (...args: any[]): any }"}function Js(e,t,r=0){if(e.startsWith("Promise.resolve(")){let n=e.indexOf(")",16);if(n!==-1){let i=e.slice(16,n).trim();if(i)return`Promise<${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=Wr(s),a=[];for(let c=0;c<o.length;c++){let f=o[c].trim();if(f.startsWith("Promise.resolve(")){let u=Js(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 an(e,t,r=0){let n=e.slice(1,-1).trim();if(!n)return"never[]";if(r>=20)return"unknown[]";let i=Wr(n),s=!1;for(let g=0;g<i.length;g++){let d=i[g],v=d.length;while(v>0&&d.charCodeAt(v-1)<=32)v--;if(v>=8&&d.slice(v-8,v)==="as const"){s=!0;break}}if(s){let g=[];for(let d=0;d<i.length;d++){let v=i[d].trim();if(v.endsWith("as const")){let b=v.slice(0,-8).trim();if(b.startsWith("[")&&b.endsWith("]")){let C=b.slice(1,-1).trim(),T=Wr(C),k=[];for(let
|
|
25
|
+
`)||i.includes("\r"))return"string";return i}if(i.charCodeAt(0)===39||i.charCodeAt(0)===34){let o=_c(i);if(o!==null){if(o==="string"||!t)return"string";return o}}if(hn(i)){if(!t)return"number";return i}if(i==="true"||i==="false"){if(!t)return"boolean";return i}if(i==="null")return"null";if(i==="undefined")return"undefined";if(i.startsWith("[")&&i.endsWith("]"))return an(i,t,n+1);if(i.startsWith("{")&&i.endsWith("}"))return tf(i,t,n+1);if(i.startsWith("class ")||i.startsWith("class{"))return Qc(i);if(i.startsWith("new "))return Xc(i);if(i.endsWith("as const")){let o=i.slice(0,-8).trim();if(o.startsWith("[")&&o.endsWith("]")){let a=o.slice(1,-1).trim();if(!a)return"readonly []";let c=Wr(a),f=[];for(let u=0;u<c.length;u++)f.push(Te(c[u].trim(),!0,!1,n+1));return`readonly [${f.join(", ")}]`}return Te(o,!0,r,n+1)}if(Br(i)!==-1||i.startsWith("function")||i.startsWith("async"))return Xs(i,r,n,t);if(i.startsWith("`")&&i.endsWith("`"))return Zc(i,t);if(i.startsWith("Promise."))return Js(i,t,n);if(i.startsWith("await "))return"unknown";if(i.charCodeAt(i.length-1)===110&&i.length>1&&jc(i)){if(t)return i;return"bigint"}if(i.startsWith("Symbol(")||i==="Symbol.for")return"symbol";let s=qs(i);if(s!==null)return s;if(zc(i))return"boolean";if(Hc(i))return"number";return"unknown"}function js(e){let t=e.charCodeAt(0);if(t!==39&&t!==34)return!1;return Rt(e,0,t)===e.length}function _c(e){if(js(e))return e;let t=Vc(e);if(t.length<2)return null;let r=!1,n=!0,i="";for(let s of t){let o=s.trim();if(js(o))r=!0,i+=Uc(o);else n=!1}if(n)return Kc(i);if(r)return"string";return null}function Vc(e){let t=[],r=0,n=0,i=0;while(i<e.length){let s=e.charCodeAt(i);if(s===39||s===34||s===96){i=Rt(e,i,s);continue}if(s===40||s===91||s===123)r++;else if(s===41||s===93||s===125)r--;else if(s===43&&r===0)t.push(e.slice(n,i)),n=i+1;i++}return t.push(e.slice(n)),t}function Uc(e){return e.slice(1,-1).replace(/\\(.)/g,(t,r)=>{if(r==="n")return`
|
|
26
|
+
`;if(r==="t")return"\t";if(r==="r")return"\r";if(r==="0")return"\x00";return r})}function Kc(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function Hc(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 zc(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=Rt(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 Jc(e,t=!1,r=0){return Te(e,t,!0,r)}function hr(e,t=!1,r=""){let n=Hs(r),i=[],s=!1,o=0;while(o<e.length){let c=e.charCodeAt(o);if(c===34||c===39||c===96){o=Rt(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)&&_s(e,o,8)||e.startsWith("class",o)&&_s(e,o,5)){let f=Yc(e,o);if(f!==-1){o=Vs(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=Vs(e,f);continue}}if(e.startsWith("return",o)&&(o===0||!ut(e.charCodeAt(o-1)))&&!ut(e.charCodeAt(o+6))){o+=6;let f=!1;while(o<e.length&&e.charCodeAt(o)<=32){let C=e.charCodeAt(o);if(C===10||C===13)f=!0;o++}if(f||o>=e.length||e.charCodeAt(o)===59||e.charCodeAt(o)===125){s=!0;continue}let u=o,l=0,g=0,d=0;while(o<e.length){let C=e.charCodeAt(o);if(C===34||C===39||C===96){o=Rt(e,o,C);continue}if(C===47&&e.charCodeAt(o+1)===47)break;if(C===47&&e.charCodeAt(o+1)===42){let T=e.indexOf("*/",o+2);o=T===-1?e.length:T+2;continue}if(C===40)l++;else if(C===41)l--;else if(C===91)g++;else if(C===93)g--;else if(C===123)d++;else if(C===125){if(d===0&&l===0&&g===0)break;d--}else if(C===59&&l===0&&g===0&&d===0)break;else if((C===10||C===13)&&l===0&&g===0&&d===0){let T=o+1;while(T<e.length&&e.charCodeAt(T)<=32)T++;if(e.startsWith("return",T)&&!ut(e.charCodeAt(T+6)))break}o++}let v=e.slice(u,o).trim(),b=Pt(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 Hs(e){let t=new Map,r=e.startsWith("(")&&e.endsWith(")")?e.slice(1,-1):e,n=0,i=0,s=0;for(let o=0;o<=r.length;o++){let a=r.charCodeAt(o);if(a===40||a===91||a===123)i++;else if(a===41||a===93||a===125)i--;else if(a===60)s++;else if(a===62&&r.charCodeAt(o-1)!==61&&s>0)s--;if(o!==r.length&&(a!==44||i!==0||s!==0))continue;let 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(dr(u)&&l)t.set(u,l)}n=o+1}return t}function Pt(e,t){let r=e.trim();while(zs(r))r=r.slice(1,-1).trim();if(Lr(r))return"JSX.Element";if(r.startsWith("await ")){let s=Pt(r.slice(6),t);return s.startsWith("Promise<")&&s.endsWith(">")?s.slice(8,-1):s}if(t.has(r))return t.get(r);if(r.startsWith("!"))return"boolean";if(r.startsWith("fetch("))return"Promise<Response>";let n=qc(r);if(n){let s=Pt(n.whenTrue,t),o=Pt(n.whenFalse,t);return s===o?s:`${s} | ${o}`}if(["===","!==","==","!=",">=","<="].some((s)=>r.includes(s))||r.includes(" > ")||r.includes(" < "))return"boolean";let i=0;for(let s=r.length-1;s>=0;s--){let o=r.charCodeAt(s);if(o===41||o===93||o===125)i++;else if(o===40||o===91||o===123)i--;else if(i===0&&(o===43||o===45||o===42||o===47||o===37)){let a=Pt(r.slice(0,s),t),c=Pt(r.slice(s+1),t);if(o===43&&(a==="string"||c==="string"))return"string";if(a==="number"&&c==="number")return"number";break}}return Te(r,!1).replace(/\btypeof\s+[$A-Z_a-z][$\w]*/g,(s)=>{let o=s.slice(7);return t.get(o)??"unknown"})}function zs(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 qc(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 _s(e,t,r){return(t===0||!ut(e.charCodeAt(t-1)))&&!ut(e.charCodeAt(t+r))}function Yc(e,t){for(let r=t;r<e.length;r++){let n=e.charCodeAt(r);if(n===34||n===39||n===96){r=Rt(e,r,n)-1;continue}if(n===123)return r;if(n===59)return-1}return-1}function Vs(e,t){let r=1,n=t+1;while(n<e.length&&r>0){let i=e.charCodeAt(n);if(i===34||i===39||i===96){n=Rt(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 Rt(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 Zc(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 Xc(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&&(ut(e.charCodeAt(t))||e.charCodeAt(t)===46))t++;if(t===r)return"unknown";let i=e.slice(r,t);{let s=e.slice(t),o=s;if(s.startsWith("<")){let c=0,f=-1;for(let u=0;u<s.length;u++)if(s[u]==="<")c++;else if(s[u]===">"){if(c--,c===0){f=u;break}}if(f!==-1){let u=s.slice(0,f+1);o=s.slice(f+1);let l=o.indexOf("(");if(l!==-1){let g=0,d=-1;for(let v=l;v<o.length;v++)if(o[v]==="(")g++;else if(o[v]===")"){if(g--,g===0){d=v;break}}if(d!==-1){if(o.slice(d+1).trimStart().startsWith("."))return"unknown"}}return`${i}${u}`}}let a=o.indexOf("(");if(a!==-1){let c=0,f=-1;for(let u=a;u<o.length;u++)if(o[u]==="(")c++;else if(o[u]===")"){if(c--,c===0){f=u;break}}if(f!==-1){if(o.slice(f+1).trimStart().startsWith("."))return"unknown"}}switch(i){case"Date":return"Date";case"Map":return"Map<any, any>";case"Set":return"Set<any>";case"WeakMap":return"WeakMap<any, any>";case"WeakSet":return"WeakSet<any>";case"RegExp":return"RegExp";case"Error":return"Error";case"Array":return"any[]";case"Object":return"object";case"Function":return"Function";case"Promise":return"Promise<any>";default:return i}}return"unknown"}function Qc(e){return"{ new (...args: any[]): any }"}function Js(e,t,r=0){if(e.startsWith("Promise.resolve(")){let n=e.indexOf(")",16);if(n!==-1){let i=e.slice(16,n).trim();if(i)return`Promise<${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=Wr(s),a=[];for(let c=0;c<o.length;c++){let f=o[c].trim();if(f.startsWith("Promise.resolve(")){let u=Js(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 an(e,t,r=0){let n=e.slice(1,-1).trim();if(!n)return"never[]";if(r>=20)return"unknown[]";let i=Wr(n),s=!1;for(let g=0;g<i.length;g++){let d=i[g],v=d.length;while(v>0&&d.charCodeAt(v-1)<=32)v--;if(v>=8&&d.slice(v-8,v)==="as const"){s=!0;break}}if(s){let g=[];for(let d=0;d<i.length;d++){let v=i[d].trim();if(v.endsWith("as const")){let b=v.slice(0,-8).trim();if(b.startsWith("[")&&b.endsWith("]")){let C=b.slice(1,-1).trim(),T=Wr(C),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(an(v,!0,r+1));else g.push(Te(v,!0,!1,r+1))}return`readonly [
|
|
28
28
|
${g.join(` |
|
|
29
29
|
`)}
|
|
30
30
|
]`}let o=Gr&&!t,a=[],c=[];for(let g of i){let d=g.trim(),v=_e;if(_e=null,d.startsWith("...")){let b=d.slice(3).trim(),C=Te(b,!1,!1,r+1);if(C.endsWith("[]"))a.push(C.slice(0,-2));else if(C.startsWith("readonly [")&&C.endsWith("]"))a.push(C.slice(10,-1));else if(mr(b))a.push(`(typeof ${b})[number]`);else a.push("unknown")}else if(d.startsWith("[")&&d.endsWith("]"))a.push(an(d,t,r+1));else a.push(Jc(d,t,r+1));if(o)c.push(_e);_e=v}if(o)if(cn(e))_e=ur(e);else{let g=[];for(let d=0;d<i.length;d++){let v=i[d].trim();if(v.endsWith("as const"))continue;if(ln(v)||v==="null"||v==="undefined")g.push(v);else if(v.startsWith("[")&&cn(v))g.push(ur(v));else if(v.startsWith("{")){if(c[d])g.push(c[d])}else{let b=Te(v,!1,!1,0);if(b!=="unknown")g.push(b)}}if(g.length>0)_e=`[${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(!(hn(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 Wr(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 ln(e){if(hn(e))return!0;if(e==="true"||e==="false")return!0;if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return!0;return!1}function ef(e){return e==="number"||e==="string"||e==="boolean"}function cn(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 tf(e,t,r=0){let n=e.slice(1,-1).trim();if(!n)return"{}";if(r>=20)return"Record<string, unknown>";let i=lf(n),s=[],o=[],a=Gr&&!t,c=[];for(let[l,g]of i){let{comments:d,key:v}=af(l),b=d?`${d}
|
|
31
|
-
`:"",C=v,T=!1;if(v==="..."){let F=g.trim(),U=mr(F)?`typeof ${F}`:Te(F,t,!1,r+1);if(U!=="unknown")o.push(U);if(a&&(mr(F)||F.startsWith("{")))c.push(`...${ur(F)}`);continue}let k=_e;_e=null;let
|
|
32
|
-
${C}: ${
|
|
31
|
+
`:"",C=v,T=!1;if(v==="..."){let F=g.trim(),U=mr(F)?`typeof ${F}`:Te(F,t,!1,r+1);if(U!=="unknown")o.push(U);if(a&&(mr(F)||F.startsWith("{")))c.push(`...${ur(F)}`);continue}let k=_e;_e=null;let R,I=g.trim();if(I===v&&dr(I))R=`typeof ${I}`;else if(uf(I)){T=!0;let F=hf(v);if(F){C=F.name;let U="";if(I.startsWith("async "))U="async ";if(I.charCodeAt(U.length)===42)U+="*";R=Us(F.name,U+F.typeParams+I.slice(U.length))}else R=Us(v,I)}else if(R=Te(g,t,!1,r+1),R.includes("=>")||R.includes("function")||R.includes("async"))R=nf(R);let _=_e;_e=k;let L=g.trim(),P=cf(v);if(P){let F=ff(P.kind,P.name,R);if(F){s.push(`${b}${F}`);continue}}if(!t&&ef(R)&&ln(L))s.push(`${b}/** @defaultValue ${L} */
|
|
32
|
+
${C}: ${R}`);else s.push(`${b}${C}: ${R}`);if(a){let F=Gc(C);if(L.endsWith("as const"));else if(ln(L))c.push(`${F}: ${L}`);else if(L.startsWith("[")&&cn(L))c.push(`${F}: ${ur(L)}`);else if(L.startsWith("{")){if(_)c.push(`${F}: ${_}`)}else if(T)c.push(`${F}: ${ur(R)}`);else if(!L.startsWith("[")&&(L.includes("=>")||L.startsWith("function")||L.startsWith("async"))){let U=Xs(L,!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)_e=g;else{let d=" ".repeat((l+1)*2),v=" ".repeat(l*2);_e=`{
|
|
33
33
|
${d}${c.join(`,
|
|
34
34
|
${d}`)}
|
|
35
35
|
${v}}`}}let f=s.length>0?`{
|
|
@@ -38,50 +38,50 @@ ${v}}`}}let f=s.length>0?`{
|
|
|
38
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 dr(e){if(!e)return!1;let t=e.charCodeAt(0);if(!(t>=65&&t<=90||t>=97&&t<=122||t===95||t===36||t>127))return!1;for(let r=1;r<e.length;r++)if(!ut(e.charCodeAt(r)))return!1;return!0}function mr(e){let t=e.split(".");return t.length>0&&t.every(dr)}function rf(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=Xe(e,n,"<",">");if(s!==-1)n=s}}return-1}function qs(e){if(e.length<3||!e.endsWith(")"))return null;let t=rf(e);if(t===-1||Xe(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(Xe(r,o,"<",">")!==r.length-1)return null;i=r.slice(0,o).trim(),s=!0}if(!mr(i))return null;let a=e.slice(t+1,-1).trim(),c=Br(a)!==-1||a.startsWith("function")||a.startsWith("async function"),f=mr(a),u=!c&&a.endsWith(")")&&qs(a)!==null;if(!s&&!n&&!c&&!f&&!u)return null;let l=`ReturnType<typeof ${r}>`;return n?`${l} | undefined`:l}function nf(e){let t=e.split(`
|
|
39
39
|
`).map((f)=>Ys(f)).join(`
|
|
40
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(!ut(f)&&!ut(u))t=(t.slice(0,r)+t.slice(r+5)).trim()}let n=t.indexOf("(");if(n!==-1){let f=Xe(t,n,"(",")");if(f!==-1){let u=t.slice(n,f+1),l=jt(u);t=t.slice(0,n)+l+t.slice(f+1)}}let i=t.length,s="",o=[],a=!1,c=!1;for(let f=0;f<i;f++){let u=t.charCodeAt(f);if(u===123||u===40)o.push(u);else if(u===125||u===41)o.pop();if(u<=32){if(a=!0,u===10||u===13)c=!0;continue}if(a&&s.length>0){let l=(o.length>0?o[o.length-1]:0)===123;if(c&&l){let g=s.charCodeAt(s.length-1),d=g===59||g===44||g===123||u===125,v=s.length>=2&&s.charCodeAt(s.length-1)===47&&s.charCodeAt(s.length-2)===42;if(!d&&!v)s+="; ";else s+=" "}else s+=" "}a=!1,c=!1,s+=t[f]}return s.trim()}function ut(e){return e>=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57||e===95||e===36}function jt(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 C=i.charCodeAt(b);if(C===40||C===60||C===91||C===123)v++;else if(C===41||C===62||C===93||C===125)v--;else if(v===0&&C===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 C=i.charCodeAt(v+1);if(C===42){v+=2;while(v+1<i.length&&!(i.charCodeAt(v)===42&&i.charCodeAt(v+1)===47))v++;v++;continue}if(C===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 C=",",T=v+1;while(T<i.length&&i.charCodeAt(T)<=32)C+=i[T],T++;a.push(C),c=T}}let g=[];for(let v of o){let b=v.trim();if(!b){g.push(v);continue}if(b.startsWith("//"))continue;let C=Ys(b),T=v.slice(0,v.length-v.trimStart().length);g.push(T+sf(C))}let d=g[0]||"";for(let v=1;v<g.length;v++)d+=(a[v-1]||", ")+g[v];return n?`(${d})`:d}function Ys(e){let t=!1,r=0;for(let n=0;n<e.length-1;n++){let i=e.charCodeAt(n);if(t){if(i===92){n++;continue}if(i===r)t=!1;continue}if(i===39||i===34||i===96){t=!0,r=i;continue}if(i===47&&e.charCodeAt(n+1)===47)return e.slice(0,n).trimEnd()}return e}function sf(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 of(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 af(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 lf(e){let t=[],r="",n="",i=0,s=!1,o="",a=!0,c=!1,f=0,u=!1,l=!1,g=0,d=!1,v=!1;for(let b=0;b<e.length;b++){let C=e.charCodeAt(b),T=b>0?e.charCodeAt(b-1):0,k=b<e.length-1?e.charCodeAt(b+1):0;if(!s&&!c&&C===47&&k===47){b+=2;while(b<e.length&&e.charCodeAt(b)!==10)b++;continue}if(!s&&!c&&C===47&&k===42){c=!0,f=1,r+="/*",b++;continue}else if(c&&C===42&&k===47){if(f--,r+="*/",b++,f===0)c=!1;continue}else if(c&&C===47&&k===42){f++,r+="/*",b++;continue}let
|
|
42
|
-
`))
|
|
43
|
-
`,l+2);l=y===-1?a:y+1;continue}if(m===
|
|
44
|
-
`,l+2);l=y===-1?a:y+1;continue}if(m===
|
|
45
|
-
`,l+2);return l=m===-1?a:m+1,!0}if(h===
|
|
46
|
-
`,h)+1,y=
|
|
47
|
-
`,l+2);l=E===-1?a:E+1;continue}if(w===
|
|
48
|
-
`,l+2);l=
|
|
49
|
-
`,l+2);l=x===-1?a:x+1;continue}if(E===
|
|
50
|
-
`,l+2);l=w===-1?a:w+1;continue}break}if(l>=a)return l=h,!0;let m=i.charCodeAt(l);if(m===124||m===38||m===ct||m===jr||m===Qe)return l=h,!1;if(
|
|
51
|
-
`,l),h=p===-1?a:p,m=i.indexOf(";",l);if(m!==-1&&m<h){let y=m-1;while(y>=l&&(i.charCodeAt(y)===
|
|
52
|
-
`));continue}break}if(m.length===0)return;return m.reverse(),m}function nc(p){let h=p,m=!1;while(l<a){let S=i.charCodeAt(l);if(S===Y){l++;break}if(S===ie||S===le){b(S),m=!0;while(l<a&&(i.charCodeAt(l)===
|
|
53
|
-
`),y=[],w=[],E=[],x=!1,
|
|
54
|
-
`);let S=
|
|
55
|
-
`)}function at(){if(l>=a||i.charCodeAt(l)!==
|
|
56
|
-
`)){let m="",y=!1;for(let w=0;w<h.length;w++){let E=h.charCodeAt(w);if(E===32||E===9||E===10||E===13){if(!y&&m.length>0)m+=" ",y=!0}else m+=h[w],y=!1}if(m.charCodeAt(1)===32)m=`<${m.slice(2)}`;if(m.charCodeAt(m.length-2)===32)m=`${m.slice(0,-2)}>`;return m}return h}function Et(){if(l>=a||i.charCodeAt(l)!==ee)return"()";let p=l;return ke(ee,
|
|
57
|
-
`)===-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
|
|
58
|
-
`,
|
|
59
|
-
`))h=h.slice(0,-1);m++;let
|
|
41
|
+
`),key:e.slice(r).trim()}}function lf(e){let t=[],r="",n="",i=0,s=!1,o="",a=!0,c=!1,f=0,u=!1,l=!1,g=0,d=!1,v=!1;for(let b=0;b<e.length;b++){let C=e.charCodeAt(b),T=b>0?e.charCodeAt(b-1):0,k=b<e.length-1?e.charCodeAt(b+1):0;if(!s&&!c&&C===47&&k===47){b+=2;while(b<e.length&&e.charCodeAt(b)!==10)b++;continue}if(!s&&!c&&C===47&&k===42){c=!0,f=1,r+="/*",b++;continue}else if(c&&C===42&&k===47){if(f--,r+="*/",b++,f===0)c=!1;continue}else if(c&&C===47&&k===42){f++,r+="/*",b++;continue}let R=e[b];if(!s&&(C===34||C===39||C===96))s=!0,o=R,r+=R;else if(s&&R===o&&T!==92)s=!1,r+=R;else if(!s&&!c)if(C===40&&i===0&&a&&g===0){n=r.trim();let I=of(n),_=I>0?n.slice(0,I):"",L=n.slice(I),P="";if(L.startsWith("async ")||L.startsWith("async\t")||L.startsWith(`async
|
|
42
|
+
`))L=L.slice(6).trimStart(),P="async ";if(L.startsWith("*"))L=L.slice(1).trimStart(),P+="*";n=_+L,r=P+R,a=!1,d=!0,v=!1,i=1}else if(C===123||C===91||C===40){if(i++,r+=R,v&&C===123)v=!1}else if(C===125||C===93||C===41){if(i--,r+=R,C===41&&i===0&&!a&&!d)u=!0;if(d){if(C===41&&i===0&&!v)v=!0;else if(C===125&&i===0)d=!1,v=!1}}else if(C===58&&i===0&&a&&g===0)n=r.trim(),r="",a=!1;else if(C===58&&i===0&&u)l=!0,r+=R;else if(C===60&&l)g++,r+=R;else if(C===60&&a&&i===0)g++,r+=R;else if(C===62&&g>0&&T!==61)g--,r+=R;else if(C===61&&k===62&&l&&g===0)l=!1,u=!1,r+=R;else if(C===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(dr(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(dr(b))t.push([b,b]);else if(b.startsWith("...")&&b.length>3)t.push(["...",b.slice(3).trim()])}return t}function cf(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 ff(e,t,r){let n=r.trim();if(n.charCodeAt(0)!==40)return null;let i=Xe(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 uf(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=Zs(s,1);if(o?.kind==="arrow")return!1;if(o?.kind==="body")return!0}return!1}}}return!1}function hf(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 Us(e,t){let r=t.trimStart(),n=!1,i=!1;if(r.startsWith("async ")||r.startsWith("async\t"))n=!0,r=r.slice(5).trimStart();if(r.startsWith("*"))i=!0,r=r.slice(1).trimStart();let s="";if(r.charCodeAt(0)===60){let g=0,d=-1;for(let 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){d=v;break}}if(d!==-1)s=r.slice(0,d+1),r=r.slice(d+1).trimStart()}let o=r.indexOf("("),a=Xe(r,o,"(",")");if(o===-1||a===-1)return"() => unknown";let c=r.slice(o,a+1),f="unknown",u=r.slice(a+1).trimStart();if(u.charCodeAt(0)===58){let g=u.slice(1),d=Zs(g,0);if(d)f=g.slice(0,d.index).trim();else f=g.trim()}if(f==="unknown"){if(n&&i)f="AsyncGenerator<unknown, void, unknown>";else if(i)f="Generator<unknown, void, unknown>";else if(n)f="Promise<void>"}else if(n&&!f.startsWith("Promise<")&&!f.startsWith("AsyncGenerator<"))f=`Promise<${f}>`;let l=jt(c);return`${s}${l} => ${f}`}function Zs(e,t){let r=0,n=0,i=0,s=0,o=!1,a=0;for(let c=t;c<e.length;c++){let f=e.charCodeAt(c);if(o){if(f===92)c++;else if(f===a)o=!1;continue}if(f===34||f===39||f===96){o=!0,a=f;continue}if(f===40)r++;else if(f===41&&r>0)r--;else if(f===91)n++;else if(f===93&&n>0)n--;else if(f===60)i++;else if(f===62&&i>0&&e.charCodeAt(c-1)!==61)i--;else if(f===125&&s>0)s--;else if(f===123){let u=r>0||n>0||i>0||s>0,l=e.slice(t,c).trimEnd(),g=l.charCodeAt(l.length-1),d=l.length===0||g===38||g===124||g===40||g===44||g===58||g===61||g===91;if(u||d)s++;else return{index:c,kind:"body"}}else if(f===61&&c+1<e.length&&e.charCodeAt(c+1)===62&&r===0&&n===0&&i===0&&s===0)return{index:c,kind:"arrow"}}return null}function Xe(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 Br(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=Xe(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 Xs(e,t=!1,r=0,n=!0){let i=e.trim();if(i.length>200&&on(i,"=>")>2&&on(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=Br(o);if(a===-1)return t?"(() => Promise<unknown>)":"() => Promise<unknown>";let c=o.substring(0,a).trim(),f=o.substring(a+2).trim(),u=Ks(c),{params:l,returnType:g}=u;if(l=jt(l),l==="()"||l==="")l="()";else if(!l.startsWith("("))l=`(${l})`;let d=g;if(d);else if(f.startsWith("{"))d=hr(f.slice(1,f.endsWith("}")?-1:void 0),!0,l);else d=Te(f,n,!1,r+1);let v=`${l} => ${g||d.startsWith("Promise<")?d:`Promise<${d}>`}`;return t?`(${v})`:v}if(i.includes("=>")){let o="",a=i;if(i.startsWith("<")){let C=Xe(i,0,"<",">");if(C!==-1)o=i.substring(0,C+1),a=i.substring(C+1).trim()}let c=Br(a);if(c===-1)return t?"(() => unknown)":"() => unknown";let f=a.substring(0,c).trim(),u=a.substring(c+2).trim(),l=Ks(f),{params:g,returnType:d}=l;if(g=jt(g),g==="()"||g==="")g="()";else if(!g.startsWith("("))g=`(${g})`;let v="unknown";if(d)v=d;else if(u.startsWith("{"))v=hr(u.slice(1,u.endsWith("}")?-1:void 0),!1,g);else if(Lr(u)||zs(u)&&Lr(u.slice(1,-1).trim()))v="JSX.Element";else if(u.includes("=>")){let C=u.trimStart(),T=C.indexOf("("),k=T!==-1?Xe(C,T,"(",")"):-1,R=k!==-1?C.indexOf("=>",k):-1;if(T===0&&k!==-1&&R!==-1){let I=C.substring(T+1,k).trim(),_=jt(I);if(o.includes("T")&&_.includes("T"))v=`(${_}) => T`;else v=`(${_}) => any`}else v="any"}else if(t)v="unknown";else v=Pt(u,Hs(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,d=1;o++;while(o<a&&d>0){let v=i.charCodeAt(o);if(v===60)d++;else if(v===62&&i.charCodeAt(o-1)!==61)d--;o++}f=i.substring(g,o);while(o<a&&i.charCodeAt(o)<=32)o++}let u=i.indexOf("(",o);if(u!==-1){let g=1,d=u+1;while(d<a&&g>0){let T=i.charCodeAt(d);if(T===40)g++;else if(T===41)g--;d++}let v=i.substring(u+1,d-1).trim(),b=v?`(${v})`:"()";if(c){let T=i.substring(d).trim(),k=T.indexOf("Generator<");if(k!==-1){let I=k+10,_=T.indexOf(">",I);if(_!==-1){let L=T.substring(I,_),P=`${f}${b} => Generator<${L}>`;return t?`(${P})`:P}}let R=`${f}${b} => Generator<any, any, any>`;return t?`(${R})`:R}let C=`${f}${b} => unknown`;return t?`(${C})`:C}let l="(...args: any[]) => unknown";return t?`(${l})`:l}if(i.includes("=>")&&i.includes("(")&&i.includes(")")){if(i.length>100||on(i,"=>")>2){let o="";if(i.charCodeAt(0)===60){let l=Xe(i,0,"<",">");if(l!==-1)o=i.substring(0,l+1)}let a=i.indexOf("("),c=a!==-1?Xe(i,a,"(",")"):-1,f=a!==-1&&c!==-1?i.substring(a,c+1):"(...args: any[])";f=jt(f);let u=`${o}${f} => any`;return t?`(${u})`:u}return t?`(${i})`:i}let s="() => unknown";return t?`(${s})`:s}function Ks(e){let t=e.trim();if(!t.startsWith("("))return{params:t,returnType:""};let r=Xe(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 Qs(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 eo(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 Gr=!1,_e=null;var dn=()=>{};function De(e){return e===Se||e===Ae||e===ne||e===ye}function Ot(e){return e>=65&&e<=90||e>=97&&e<=122||e===mf||e===io||e>127}function Ve(e){return Ot(e)||e>=48&&e<=57}function pf(e){let t=!0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n===ct){if(t)return!1;t=!0}else if(t){if(!Ot(n))return!1;t=!1}else if(!Ve(n))return!1}return e.length>0&&!t}function Vr(e,t,r){let n=t+1;while(n<e.length){let i=e.charCodeAt(n);if(i===He){n+=2;continue}if(n++,i===r)break}return n}function gf(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 no(e,t,r=!0){return oo(e,t,r,!0)}function so(e,t,r=!0){return oo(e,t,r,!1)}function oo(e,t,r,n){let i=e,s=r,o=n,a=i.length,c=[],f=new Map,u=new Set,l=0;if(l<a&&i.charCodeAt(l)===65279)l++;function g(p,h){if(p<h){let m=i.charCodeAt(p),y=i.charCodeAt(h-1);if(m!==Se&&m!==Ae&&m!==ne&&m!==ye&&y!==Se&&y!==Ae&&y!==ne&&y!==ye)return i.slice(p,h)}while(p<h&&De(i.charCodeAt(p)))p++;while(h>p&&De(i.charCodeAt(h-1)))h--;return i.slice(p,h)}function d(){if(l>=a)return;let p=i.charCodeAt(l);if(p!==Se&&p!==Ae&&p!==ne&&p!==ye&&p!==z)return;while(l<a){let h=i.charCodeAt(l);if(h===Se||h===Ae||h===ne||h===ye){l++;continue}if(h===z&&l+1<a){let m=i.charCodeAt(l+1);if(m===z){let y=i.indexOf(`
|
|
43
|
+
`,l+2);l=y===-1?a:y+1;continue}if(m===ve){let y=i.indexOf("*/",l+2);l=y===-1?a:y+2;continue}}break}}function v(p){let h=p.length,m=0,y=h;for(let w=0;w<h;w++){let E=p.charCodeAt(w);if(m){if(E===He){w++;continue}if(E===m)m=0;continue}if(E===ie||E===le||E===Pe){m=E;continue}if(E===z&&w+1<h){let x=p.charCodeAt(w+1);if(x===z){y=w;while(y>0&&(p.charCodeAt(y-1)===Se||p.charCodeAt(y-1)===Ae))y--;return p.slice(0,y)}if(x===ve){let O=p.indexOf("*/",w+2);if(O!==-1){p=`${p.slice(0,w)} ${p.slice(O+2)}`,w--;continue}}}}y=h;while(y>0&&(p.charCodeAt(y-1)===Se||p.charCodeAt(y-1)===Ae||p.charCodeAt(y-1)===ye))y--;return y<h?p.slice(0,y):p}function b(p){l++;let h=p===ie?"'":'"';while(l<a){let m=i.indexOf(h,l);if(m===-1){l=a;return}let y=0,w=m-1;while(w>=0&&i.charCodeAt(w)===He)y++,w--;if(y%2===0){l=m+1;return}l=m+1}}function C(){l++;let p=[];while(l<a){let h=i.charCodeAt(l);if(p.length===0){if(h===He){l+=2;continue}if(h===Pe){l++;return}if(h===io&&l+1<a&&i.charCodeAt(l+1)===V){l+=2,p.push(0);continue}l++;continue}if(h===ie||h===le){b(h);continue}if(h===Pe){C();continue}if(h===z&&l+1<a){let m=i.charCodeAt(l+1);if(m===z){let y=i.indexOf(`
|
|
44
|
+
`,l+2);l=y===-1?a:y+1;continue}if(m===ve){let y=i.indexOf("*/",l+2);l=y===-1?a:y+2;continue}if(I()){_();continue}l++;continue}if(h===V){p[p.length-1]++,l++;continue}if(h===J){let m=p[p.length-1];if(m===0){p.pop(),l++;continue}p[p.length-1]=m-1,l++;continue}l++}}function T(){let p=i.charCodeAt(l);if(p===ie||p===le)return b(p),!0;if(p===Pe)return C(),!0;if(p===z&&l+1<a){let h=i.charCodeAt(l+1);if(h===z){let m=i.indexOf(`
|
|
45
|
+
`,l+2);return l=m===-1?a:m+1,!0}if(h===ve){let m=i.indexOf("*/",l+2);return l=m===-1?a:m+2,!0}if(I())return _(),!0}return!1}function k(p){let h=p;for(;;){while(h>=0&&(i.charCodeAt(h)===Se||i.charCodeAt(h)===Ae||i.charCodeAt(h)===ne||i.charCodeAt(h)===ye))h--;if(h<0)return-1;if(i.charCodeAt(h)===z&&h>0&&i.charCodeAt(h-1)===ve){let w=i.lastIndexOf("/*",h-2);if(w===-1)return-1;h=w-1;continue}let m=i.lastIndexOf(`
|
|
46
|
+
`,h)+1,y=R(m,h);if(y!==-1){h=y-1;continue}return h}}function R(p,h){let m=0;for(let y=p;y<=h;y++){let w=i.charCodeAt(y);if(m){if(w===He){y++;continue}if(w===m)m=0;continue}if(w===ie||w===le||w===Pe){m=w;continue}if(w===z&&y+1<=h&&i.charCodeAt(y+1)===z)return y}return-1}function I(){let p=k(l-1);if(p<0)return!0;let h=i.charCodeAt(p);if(h===be||h===ee||h===pe||h===33||h===38||h===124||h===jr||h===Qe||h===et||h===Y||h===V||h===J||h===94||h===126||h===43||h===45||h===ve||h===37||h===ge||h===fe)return!0;if(Ve(h)){let m=p;while(m>=0&&Ve(i.charCodeAt(m)))m--;let y=i.slice(m+1,p+1);if(y==="return"||y==="typeof"||y==="void"||y==="delete"||y==="throw"||y==="new"||y==="in"||y==="of"||y==="case"||y==="instanceof"||y==="yield"||y==="await")return!0}return!1}function _(){l++;let p=!1;while(l<a){let h=i.charCodeAt(l);if(h===He){l+=2;continue}if(p){if(h===$e)p=!1;l++;continue}if(h===pe){p=!0,l++;continue}if(h===z){l++;break}if(h===ne||h===ye)break;l++}while(l<a&&Ve(i.charCodeAt(l)))l++}function L(){let p=l;while(l<a&&Ve(i.charCodeAt(l)))l++;return i.slice(p,l)}function P(p){if(l+p.length>a)return!1;for(let h=0;h<p.length;h++)if(i.charCodeAt(l+h)!==p.charCodeAt(h))return!1;if(l+p.length<a&&Ve(i.charCodeAt(l+p.length)))return!1;return!0}function F(p){let h=l+p;while(h<a){let m=i.charCodeAt(h);if(m===Se||m===Ae||m===ne||m===ye){h++;continue}return m!==ct&&m!==be}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 p=i.charCodeAt(l);if(p!==ne&&p!==ye)return!1;let h=l;if(l++,p===ye&&l<a&&i.charCodeAt(l)===ne)l++;while(l<a){let y=i.charCodeAt(l);if(y===Se||y===Ae||y===ye||y===ne){l++;continue}if(y===z&&l+1<a){let w=i.charCodeAt(l+1);if(w===z){let E=i.indexOf(`
|
|
47
|
+
`,l+2);l=E===-1?a:E+1;continue}if(w===ve){let E=i.indexOf("*/",l+2);l=E===-1?a:E+2;continue}}break}let m=l>=a||U()||i.charCodeAt(l)===J;return l=h,m}function oe(p){let h=p-1;while(h>=0){let S=i.charCodeAt(h);if(S===Se||S===Ae||S===ye||S===ne){h--;continue}break}if(h<0)return!0;let m=i[h];if("+-*/%=<>&|^!~?:,.([{".includes(m))return!0;let y=h;while(y>0&&i.charCodeAt(y-1)!==ne)y--;let w=i.slice(y,h+1),E=w.lastIndexOf("<");if(E!==-1&&/^<[A-Za-z]/.test(w.slice(E))&&!w.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 H(){let p=i.charCodeAt(l);if(p!==ne&&p!==ye)return!1;if(oe(l))return!1;let h=l;l++;while(l<a){let E=i.charCodeAt(l);if(E===Se||E===Ae||E===ye||E===ne){l++;continue}if(E===z&&l+1<a){let x=i.charCodeAt(l+1);if(x===z){let O=i.indexOf(`
|
|
48
|
+
`,l+2);l=O===-1?a:O+1;continue}if(x===ve){let O=i.indexOf("*/",l+2);l=O===-1?a:O+2;continue}}break}let m=l<a?i[l]:"",y=i.slice(l,l+2),w=m==="."||m==="?"||m===":"||m===")"||m==="]"||m==="}"||m===","||m==="+"||m==="-"||m==="*"||m==="/"||m==="%"||m==="<"||m===">"||m==="="||m==="&"||m==="|"||m==="^"||m==="`"||y==="=>"||P("as")||P("satisfies")||P("instanceof")||P("in");return l=h,!w}function Z(){let p=i.charCodeAt(l);if(p!==ne&&p!==ye)return!1;if(oe(l))return!1;let h=l;l++;while(l<a){let w=i.charCodeAt(l);if(w===Se||w===Ae||w===ye||w===ne){l++;continue}if(w===z&&l+1<a){let E=i.charCodeAt(l+1);if(E===z){let x=i.indexOf(`
|
|
49
|
+
`,l+2);l=x===-1?a:x+1;continue}if(E===ve){let x=i.indexOf("*/",l+2);l=x===-1?a:x+2;continue}}break}let m=l<a?i[l]:"",y=m==="|"||m==="&"||m==="["||m==="."||m==="?"||m===":"||m===">"||m===")"||m===","||P("extends");return l=h,!y}function re(){let p=i.charCodeAt(l);if(p!==ne&&p!==ye)return!1;let h=l;if(l++,p===ye&&l<a&&i.charCodeAt(l)===ne)l++;while(l<a){let y=i.charCodeAt(l);if(y===Se||y===Ae||y===ye||y===ne){l++;continue}if(y===z&&l+1<a&&i.charCodeAt(l+1)===z){let w=i.indexOf(`
|
|
50
|
+
`,l+2);l=w===-1?a:w+1;continue}break}if(l>=a)return l=h,!0;let m=i.charCodeAt(l);if(m===124||m===38||m===ct||m===jr||m===Qe)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,Re=/[()'"`\/]/g,Oe=/[[\]'"`\/]/g,Dt=/[<>'"`\/]/g;function ke(p,h){let m=1;l++;let y=p===V?X:p===ee?Re:p===pe?Oe:Dt;y.lastIndex=l;let w;while((w=y.exec(i))!==null){let E=w.index,x=i.charCodeAt(E);if(x===ie||x===le){l=E,b(x),y.lastIndex=l;continue}if(x===Pe){l=E,C(),y.lastIndex=l;continue}if(x===z){if(l=E,T()){y.lastIndex=l;continue}y.lastIndex=E+1;continue}if(x===p)m++;else if(x===h){if(h===fe&&E>0&&i.charCodeAt(E-1)===be){y.lastIndex=E+1;continue}if(m--,m===0)return l=E+1,l}y.lastIndex=E+1}return l=a,l}function Me(){return l>0&&i.charCodeAt(l-1)===be}function ft(){return l+1<a&&i.charCodeAt(l+1)===fe}let ae=/[<{};'"`\/\n\r()[\]]/g;function Q(){let p=0,h=0,m=0,y=0,w=i.charCodeAt(l)===V;ae.lastIndex=l;let E;while((E=ae.exec(i))!==null){let x=E.index,O=i.charCodeAt(x);if(O===ie||O===le){l=x,b(O),ae.lastIndex=l;continue}if(O===Pe){l=x,C(),ae.lastIndex=l;continue}if(O===z){if(x>0&&i.charCodeAt(x-1)===ge){ae.lastIndex=x+1;continue}if(l=x,T()){ae.lastIndex=l;continue}ae.lastIndex=x+1;continue}if(O===ge){let S=Ss(x);if(S!==null)y=Math.max(0,y+S);ae.lastIndex=x+1;continue}if(O===ee){h++,ae.lastIndex=x+1;continue}if(O===we){h--,ae.lastIndex=x+1;continue}if(O===pe){m++,ae.lastIndex=x+1;continue}if(O===$e){m--,ae.lastIndex=x+1;continue}if(O===V){p++,ae.lastIndex=x+1;continue}if(O===J){let S=p>0;if(S)p--;if((!S||w)&&p===0&&h===0&&m===0&&y===0){l=x+1;return}ae.lastIndex=x+1;continue}if(O===Y&&p===0&&h===0&&m===0&&y===0){l=x+1;return}if((O===ne||O===ye)&&p===0&&h===0&&m===0&&y===0){if(l=x,q())return}ae.lastIndex=x+1}l=a}function It(){l++;while(l<a&&(i.charCodeAt(l)===Se||i.charCodeAt(l)===Ae))l++;let p=i.indexOf(`
|
|
51
|
+
`,l),h=p===-1?a:p,m=i.indexOf(";",l);if(m!==-1&&m<h){let y=m-1;while(y>=l&&(i.charCodeAt(y)===Se||i.charCodeAt(y)===Ae))y--;let w=i.charCodeAt(l),E=i.charCodeAt(y);if(w===V&&E===J||w===pe&&E===$e||w===ie&&E===ie||w===le&&E===le||w===Pe&&E===Pe){l=m+1;return}}Q()}function nr(){ke(V,J);while(l<a&&De(i.charCodeAt(l)))l++;if(P("from")){l+=4;while(l<a&&De(i.charCodeAt(l)))l++;if(l<a){let p=i.charCodeAt(l);if(p===ie||p===le)b(p)}}while(l<a&&(i.charCodeAt(l)===Se||i.charCodeAt(l)===Ae))l++;if(l<a&&i.charCodeAt(l)===Y)l++}function Cs(){l++;while(l<a&&De(i.charCodeAt(l)))l++;if(P("as")){l+=2;while(l<a&&De(i.charCodeAt(l)))l++;L();while(l<a&&De(i.charCodeAt(l)))l++}if(P("from")){l+=4;while(l<a&&De(i.charCodeAt(l)))l++;if(l<a){let p=i.charCodeAt(l);if(p===ie||p===le)b(p)}}while(l<a&&(i.charCodeAt(l)===Se||i.charCodeAt(l)===Ae))l++;if(l<a&&i.charCodeAt(l)===Y)l++}function Or(p){let h=p.indexOf("from ");if(h===-1)return;let m=h+5;while(m<p.length&&(p.charCodeAt(m)===32||p.charCodeAt(m)===9))m++;if(m>=p.length)return;let y=p.charCodeAt(m);if(y!==39&&y!==34)return;let w=p.indexOf(p[m],m+1);if(w===-1)return;return p.slice(m+1,w)}function Je(p){if(!s)return;let h=p-1;while(h>=0&&De(i.charCodeAt(h)))h--;if(h<0)return;let m=[],y=!1;while(h>=0){if(h>=1&&i.charCodeAt(h)===z&&i.charCodeAt(h-1)===ve){let x=i.lastIndexOf("/*",h-2);if(x>=0){m.push(i.slice(x,h+1)),y=!0,h=x-1;while(h>=0&&De(i.charCodeAt(h)))h--;continue}break}let w=h;while(w>0&&i.charCodeAt(w-1)!==ne)w--;let E=g(w,h+1);if(E.startsWith("//")){if(y)break;let x=[E];h=w-1;while(h>=0&&(i.charCodeAt(h)===ne||i.charCodeAt(h)===ye))h--;while(h>=0){let O=h;while(O>0&&i.charCodeAt(O-1)!==ne)O--;let S=g(O,h+1);if(S.startsWith("//")){x.push(S),h=O-1;while(h>=0&&(i.charCodeAt(h)===ne||i.charCodeAt(h)===ye))h--}else if(S===""){h=O-1;while(h>=0&&(i.charCodeAt(h)===ne||i.charCodeAt(h)===ye))h--}else break}x.reverse(),m.push(x.join(`
|
|
52
|
+
`));continue}break}if(m.length===0)return;return m.reverse(),m}function nc(p){let h=p,m=!1;while(l<a){let S=i.charCodeAt(l);if(S===Y){l++;break}if(S===ie||S===le){b(S),m=!0;while(l<a&&(i.charCodeAt(l)===Se||i.charCodeAt(l)===Ae))l++;if(l<a&&i.charCodeAt(l)===Y)l++;break}if(S===ne&&m)break;l++}let y=g(h,l),w=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)===Ae))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)===Ae))S++}if(S<y.length){let A=y.charCodeAt(S);E=A===ie||A===le}}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)===Ae))A++;if(A<y.length){let M=y.charCodeAt(A);if(M===ie||M===le){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)!==ie&&y.charCodeAt(A)!==le)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=Je(h);return{kind:"import",name:"",text:y,isExported:!1,isTypeOnly:w,isSideEffect:E,source:x,leadingComments:O,start:h,end:l}}function Bi(){let p=l;return ke(V,J),i.slice(p,l)}function ws(p){let h=p.indexOf("(");if(h===-1)return p;let m=p.slice(h);if(m.indexOf("=")===-1)return p;let y=!1;for(let S=0;S<m.length;S++)if(m.charCodeAt(S)===61){let A=S>0?m.charCodeAt(S-1):0,M=S+1<m.length?m.charCodeAt(S+1):0;if(A!==61&&A!==33&&A!==60&&A!==62&&M!==61&&M!==62){y=!0;break}}if(!y)return p;let w=0,E=-1;for(let S=h;S<p.length;S++){let A=p.charCodeAt(S);if(A===40)w++;else if(A===41){if(w--,w===0){E=S;break}}}if(E===-1)return p;let x=p.slice(h,E+1),O=Ft(x);return p.slice(0,h)+O+p.slice(E+1)}function vs(p){let h=p.indexOf("//")!==-1||p.indexOf("/*")!==-1,m=p.split(`
|
|
53
|
+
`),y=[],w=[],E=[],x=!1,O=1/0;for(let M=0;M<m.length;M++){let N=m[M];if(h){if(x){if(N.includes("*/"))x=!1;continue}let G=N.trim();if(G.length===0)continue;let B=G.charCodeAt(0);if(B===z){let me=G.charCodeAt(1);if(me===z)continue;if(me===ve){if(!G.includes("*/"))x=!0;continue}}if(B===ve)continue;let D=v(N);if(D.charCodeAt(D.length-1)===Y)D=D.slice(0,-1);D=ws(D);let W=D.trim();if(!W)continue;y.push(D),w.push(W);let j=0;while(j<D.length&&De(D.charCodeAt(j)))j++;if(W!=="{"&&W!=="}"){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)===Ae||N.charCodeAt(G-1)===ye))G--;if(G===0)continue;let B=G<N.length?N.slice(0,G):N;if(B.charCodeAt(B.length-1)===Y)B=B.slice(0,-1);B=ws(B);let D=B.trim();if(!D)continue;y.push(B),w.push(D);let W=0;while(W<B.length&&De(B.charCodeAt(W)))W++;if(D!=="{"&&D!=="}"){if(W<O)O=W}E.push(W)}}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=w[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)===$e||N.charCodeAt(0)===we))A[M]=y[M];else{let B=Math.max(0,G-S);A[M]=" ".repeat(B)+N}}return A.join(`
|
|
55
|
+
`)}function at(){if(l>=a||i.charCodeAt(l)!==ge)return"";let p=l;ke(ge,fe);let h=i.slice(p,l);if(h.includes(`
|
|
56
|
+
`)){let m="",y=!1;for(let w=0;w<h.length;w++){let E=h.charCodeAt(w);if(E===32||E===9||E===10||E===13){if(!y&&m.length>0)m+=" ",y=!0}else m+=h[w],y=!1}if(m.charCodeAt(1)===32)m=`<${m.slice(2)}`;if(m.charCodeAt(m.length-2)===32)m=`${m.slice(0,-2)}>`;return m}return h}function Et(){if(l>=a||i.charCodeAt(l)!==ee)return"()";let p=l;return ke(ee,we),i.slice(p,l)}function Ft(p){let h=p.slice(1,-1).trim();if(!h)return"()";if(p.indexOf(`
|
|
57
|
+
`)===-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===ee||G===ge||G===V)M++;else if(G===we||G===fe||G===J)M--;else if(M===0){if(G===Qe)S++;else if(G===et)A++}}if(S>=A+1){let N=!1;for(let G=0;G<mn.length;G++){let B=mn[G],D=h.indexOf(B);if(D!==-1){let W=D+B.length;if((D===0||!Ve(h.charCodeAt(D-1)))&&(W>=h.length||!Ve(h.charCodeAt(W)))){N=!0;break}}}if(!N)return p}}let m=[],y=0,w=0,E=!1,x=0;for(let S=0;S<=h.length;S++){if(S===h.length){m.push(h.slice(y).trim());break}let A=h.charCodeAt(S);if(E){if(A===He){S++;continue}if(A===x)E=!1;continue}if(A===z&&S+1<h.length){let M=h.charCodeAt(S+1);if(M===ve){S+=2;while(S+1<h.length&&!(h.charCodeAt(S)===ve&&h.charCodeAt(S+1)===z))S++;S++;continue}if(M===z){while(S<h.length&&h.charCodeAt(S)!==10)S++;continue}}if(A===ie||A===le||A===Pe){E=!0,x=A;continue}if(A===ee||A===V||A===pe||A===ge)w++;else if(A===we||A===J||A===$e||A===fe&&!(S>0&&h.charCodeAt(S-1)===be))w--;else if(A===et&&w===0)m.push(h.slice(y,S).trim()),y=S+1}let O=[];for(let S of m){if(!S)continue;let A=S.trim();if(A.startsWith("//")||A.startsWith("/*"))continue;let M=S;{let N=!1,G=0,B=0,D=0;for(let W=0;W<M.length-1;W++){let j=M.charCodeAt(W);if(j===ne){D=W+1;continue}if(N){if(j===He){W++;continue}if(j===G)N=!1;continue}if(j===ie||j===le||j===Pe){N=!0,G=j;continue}if(j===V||j===pe||j===ee||j===ge){B++;continue}if(j===J||j===$e||j===we||j===fe){if(B>0)B--;continue}if(j===z&&M.charCodeAt(W+1)===z){if(B===0){M=M.slice(0,W).trimEnd();break}let me=M.indexOf(`
|
|
58
|
+
`,W);if(me===-1){M=M.slice(0,D).trimEnd();break}let Bt=M.slice(0,D),hc=M.slice(me+1);M=`${Bt}${hc}`,W=D-1}}}if(!M.trim())continue;O.push(Es(M))}return`(${O.join(", ")})`}function sc(p){if(!p.startsWith("{")&&!p.startsWith("["))return p;let h="",m=0,y=0,w=!1,E=0;while(m<p.length){let x=p.charCodeAt(m);if(w){if(x===He&&m+1<p.length){h+=p[m]+p[m+1],m+=2;continue}if(x===E)w=!1;h+=p[m],m++;continue}if(x===z&&m+1<p.length){let O=p.charCodeAt(m+1);if(O===ve){let S=m;m+=2;while(m+1<p.length&&!(p.charCodeAt(m)===ve&&p.charCodeAt(m+1)===z))m++;m=Math.min(m+2,p.length),h+=p.slice(S,m);continue}if(O===z){let S=m;while(m<p.length&&p.charCodeAt(m)!==10)m++;h+=p.slice(S,m);continue}}if(x===ie||x===le||x===Pe){w=!0,E=x,h+=p[m],m++;continue}if(x===V||x===pe||x===ee)y++;else if(x===J||x===$e||x===we)y--;if(y>=1&&x===be&&(m+1>=p.length||p.charCodeAt(m+1)!==be&&p.charCodeAt(m+1)!==fe)){while(h.length>0&&(h[h.length-1]===" "||h[h.length-1]==="\t"||h[h.length-1]===`
|
|
59
|
+
`))h=h.slice(0,-1);m++;let O=0;while(m<p.length){let S=p.charCodeAt(m);if(S===ie||S===le||S===Pe){let A=S;m++;while(m<p.length){if(p.charCodeAt(m)===He){m+=2;continue}if(p.charCodeAt(m)===A){m++;break}m++}continue}if(S===V||S===pe||S===ee)O++;else if(S===J||S===$e||S===we){if(O===0)break;O--}else if(S===et&&O===0)break;m++}continue}if(y===1&&x===ct&&m+2<p.length&&p.charCodeAt(m+1)===ct&&p.charCodeAt(m+2)===ct){m+=3;continue}h+=p[m],m++}return h}function Es(p){let h=p.trim(),m=h.startsWith("...");if(m)h=h.slice(3).trim();while(h.startsWith("@")){let D=1;while(D<h.length&&Ve(h.charCodeAt(D)))D++;if(D<h.length&&h.charCodeAt(D)===ee){let W=1;D++;while(D<h.length&&W>0){if(h.charCodeAt(D)===ee)W++;else if(h.charCodeAt(D)===we)W--;D++}}h=h.slice(D).trim()}let y=!0;while(y){y=!1;for(let D of mn)if(h.startsWith(D)&&h.length>D.length&&!Ve(h.charCodeAt(D.length))){let W=h.slice(D.length).trim();if(W.charCodeAt(0)===Qe||W.charCodeAt(0)===jr&&W.length>1&&W.charCodeAt(1)===Qe)break;h=W,y=!0;break}}let w=-1,E=-1,x=0,O=!1,S=0;for(let D=0;D<h.length;D++){let W=h.charCodeAt(D);if(O){if(W===He){D++;continue}if(W===S)O=!1;continue}if(W===z&&D+1<h.length){let j=h.charCodeAt(D+1);if(j===ve){D+=2;while(D+1<h.length&&!(h.charCodeAt(D)===ve&&h.charCodeAt(D+1)===z))D++;D++;continue}if(j===z){while(D<h.length&&h.charCodeAt(D)!==10)D++;continue}}if(W===ie||W===le||W===Pe){O=!0,S=W;continue}if(W===ee||W===V||W===pe||W===ge)x++;else if(W===we||W===J||W===$e||W===fe&&!(D>0&&h.charCodeAt(D-1)===be))x--;else if(x===0){if(W===Qe&&w===-1)w=D;else if(W===be&&E===-1&&(D===0||h.charCodeAt(D-1)!==be)&&(D+1>=h.length||h.charCodeAt(D+1)!==be&&h.charCodeAt(D+1)!==fe))E=D}}let A,M,N=E!==-1;if(w!==-1&&(E===-1||w<E))if(A=h.slice(0,w).trim(),E!==-1)M=h.slice(w+1,E).trim();else M=h.slice(w+1).trim();else if(E!==-1)A=h.slice(0,E).trim(),M=Gi(h.slice(E+1).trim());else A=h,M="unknown";if(A=sc(A),(A.startsWith("{")||A.startsWith("["))&&A.includes(`
|
|
60
60
|
`)){let D=A.replace(/\s*\n\s*/g," ").replace(/\s+/g," ");if(D.length<=40)A=D;else A=A.split(`
|
|
61
|
-
`).map((
|
|
62
|
-
`)}let G=A.endsWith("?")||
|
|
63
|
-
`,E+2),M=A===-1?p.length:A;w+=p.slice(E,M),E=M;continue}let
|
|
64
|
-
`;if(m==="t")return"\t";if(m==="r")return"\r";if(m==="0")return"\x00";return m})}function cc(p){return`'${p.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function kr(p){if(p.endsWith("as const"))return null;let h=0,m=-1;for(let y=0;y<p.length;y++){let w=p.charCodeAt(y);if(w===ie||w===le||w===
|
|
61
|
+
`).map((W)=>{let j=W.trim();if(!j)return"";if(j==="{"||j==="}"||j==="["||j==="]"||j.startsWith("}")||j.startsWith("]"))return j;return` ${j}`}).join(`
|
|
62
|
+
`)}let G=A.endsWith("?")||N;if(A.endsWith("?"))A=A.slice(0,-1).trim();let B=G&&!m?"?":"";if(m)return`...${A}: ${M}`;return`${A}${B}: ${M}`}function bs(p){let h=0;if(h<p.length&&p.charCodeAt(h)===45)h++;if(h>=p.length)return!1;let m=p.charCodeAt(h);if(m<48||m>57)return!1;while(h<p.length&&p.charCodeAt(h)>=48&&p.charCodeAt(h)<=57)h++;if(h<p.length&&p.charCodeAt(h)===46){if(h++,h>=p.length||p.charCodeAt(h)<48||p.charCodeAt(h)>57)return!1;while(h<p.length&&p.charCodeAt(h)>=48&&p.charCodeAt(h)<=57)h++}return h===p.length}function Gi(p){let h=p.trim();if(h==="true"||h==="false")return"boolean";if(bs(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 ji(p){let h=p.trim();if(h.endsWith("as const"))h=h.slice(0,-8).trim();if(h==="true"||h==="false")return h;if(bs(h))return h;let m=oc(h);if(m!==null)return m;return"unknown"}function oc(p){if(p==="")return null;if(p.charCodeAt(0)===ie||p.charCodeAt(0)===le){if(Vr(p,0,p.charCodeAt(0))===p.length)return p}let h=ac(p,"+");if(h.length>1){let m=!1,y=!0,w=[];for(let E of h){let x=E.trim(),O=x.charCodeAt(0);if((O===ie||O===le)&&Vr(x,0,O)===x.length)m=!0,w.push(lc(x));else y=!1}if(y)return cc(w.join(""));if(m)return"string";return null}if(/^[\d\s()+*/%.\-]+$/.test(p)&&/\d/.test(p)&&/[+*/%\-\s]/.test(p))return"number";return null}function ac(p,h){let m=[],y=0,w="",E=0;while(E<p.length){let x=p.charCodeAt(E);if(x===ie||x===le||x===Pe){let O=Vr(p,E,x);w+=p.slice(E,O),E=O;continue}if(x===z&&(p.charCodeAt(E+1)===z||p.charCodeAt(E+1)===42)){if(p.charCodeAt(E+1)===z){let A=p.indexOf(`
|
|
63
|
+
`,E+2),M=A===-1?p.length:A;w+=p.slice(E,M),E=M;continue}let O=p.indexOf("*/",E+2),S=O===-1?p.length:O+2;w+=p.slice(E,S),E=S;continue}if(x===ee||x===pe||x===V)y++;else if(x===we||x===$e||x===J)y--;if(p[E]===h&&y===0){m.push(w),w="",E++;continue}w+=p[E],E++}return m.push(w),m}function lc(p){return p.slice(1,-1).replace(/\\(.)/g,(h,m)=>{if(m==="n")return`
|
|
64
|
+
`;if(m==="t")return"\t";if(m==="r")return"\r";if(m==="0")return"\x00";return m})}function cc(p){return`'${p.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function kr(p){if(p.endsWith("as const"))return null;let h=0,m=-1;for(let y=0;y<p.length;y++){let w=p.charCodeAt(y);if(w===ie||w===le||w===Pe)y=Vr(p,y,w)-1;else if(w===123||w===91||w===40)h++;else if(w===125||w===93||w===41)h--;else if(h===0&&w===32&&y+4<=p.length&&p.substring(y,y+4)===" as ")m=y}if(m===-1)return null;return p.slice(m+4).trim()||null}function sr(){if(d(),l<a&&i.charCodeAt(l)===Qe){l++,d();let p=l,h=0;while(l<a){if(T())continue;let m=i.charCodeAt(l);if(m===ee||m===pe||m===ge)h++;else if(m===we||m===$e||m===fe&&!Me())h--;else if(m===V)if(h>0)h++;else{let y=g(p,l),w=(E)=>{let x=y.length-E.length;return x>=0&&y.endsWith(E)&&(x===0||!Ve(y.charCodeAt(x-1)))};if(y.length===0||y.endsWith("|")||y.endsWith("&")||w("is")||w("extends"))h++;else break}else if(m===J){if(h===0)break;h--}else if(h===0&&m===Y)break;if(h===0&&re())break;l++}return g(p,l)}return""}function bt(p,h,m,y){l+=8,d();let w=l<a&&i.charCodeAt(l)===ve;if(w)l++,d();let E=L();if(!E&&!y)return null;d();let x=at();d();let O=Et();d();let S=sr(),A=S.length>0;if(!S)if(m&&w)S="AsyncGenerator<unknown, void, unknown>";else if(w)S="Generator<unknown, void, unknown>";else if(m)S="Promise<void>";else S="void";d();let M=!1;if(l<a&&i.charCodeAt(l)===V){M=!0;let D=l+1;if(ke(V,J),!o&&!A&&!w)S=hr(i.slice(D,l-1),m,O)}else if(l<a&&i.charCodeAt(l)===Y)l++;let N=Ft(O),G=`${h?y?"export default function ":"export declare function ":"declare function "}${E||(y?"":"default")}${x}${N}: ${S};`,B=Je(p);if(M)u.add(c.length);return{kind:"function",name:E||"default",text:G,isExported:h,isDefault:y,isAsync:m,isGenerator:w,returnType:S,generics:x||void 0,leadingComments:B,start:p,end:l}}function Nt(p,h,m){l+=h.length,d();let y=[];do{if(d(),l>=a)break;let w=i.charCodeAt(l);if(w===V||w===pe)return Q(),y;let E=L();if(!E)return Q(),y;d();let x,O,S=!1;if(l<a&&i.charCodeAt(l)===Qe){l++,d();let N=l,G=0;while(l<a){if(T())continue;let B=i.charCodeAt(l);if(B===ee||B===V||B===pe||B===ge)G++;else if(B===we||B===J||B===$e||B===fe&&!Me())G--;else if(G===0&&(B===Y||B===et))break;else if(G===0&&B===be&&!ft())break;if(G===0&&(q()||Z()))break;l++}x=g(N,l)}if(l<a&&i.charCodeAt(l)===be)if(o&&x&&(!s||!gf(x)))It();else{l++,d();let N=l,G=0,B=0,D=0,W=!0;for(;;){l=N,G=0,B=0,D=0;while(l<a){if(T())continue;let j=i.charCodeAt(l);if(j===ee||j===V||j===pe)G++;else if(j===we||j===J||j===$e)G--;else if(j===ge&&G===0){let me=Ss(l);if(me!==null)D=Math.max(0,D+me);else if(W&&(l+1>=a||i.charCodeAt(l+1)!==be))B++}else if(j===fe&&G===0&&D===0&&!Me()){if(B>0&&(l+1>=a||i.charCodeAt(l+1)!==be))B--}else if(G===0&&B===0&&D===0&&(j===Y||j===et))break;if(G===0&&B===0&&D===0&&(q()||H()))break;l++}if(B>0&&W){W=!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,me=ji(j);x=me!=="unknown"?me:void 0}}else if(!x){let j=kr(O);if(j)x=j}}if(l<a){let N=i.charCodeAt(l);if(N===et){l++;continue}if(N===Y)l++}let A=Je(p),M=`${m?"export ":""}declare ${h} ${E}: ${x||"unknown"};`;y.push({kind:"variable",name:E,text:M,isExported:m,typeAnnotation:x,value:O,modifiers:S?[h,"const assertion"]:[h],leadingComments:A,start:p,end:l});break}while(l<a);return y}function Ss(p){if(i.charCodeAt(p)!==ge||p+1>=a)return null;let h=i.charCodeAt(p+1);if(h===fe)return 1;if(h===z)return-1;if(!Ot(h))return null;let m=p+2;while(m<a){let A=i.charCodeAt(m);if(!Ve(A)&&A!==ct&&A!==58&&A!==45)break;m++}let y=i.slice(p+1,m),w=i.charCodeAt(m);if(w>32&&w!==fe&&w!==z)return null;let E=0,x=0,O=m;for(;O<a;O++){let A=i.charCodeAt(O);if(x!==0){if(A===He)O++;else if(A===x)x=0;continue}if(A===ie||A===le||A===Pe)x=A;else if(A===V)E++;else if(A===J&&E>0)E--;else if(A===fe&&E===0)break}if(O>=a)return null;let S=O-1;while(S>p&&i.charCodeAt(S)<=32)S--;if(i.charCodeAt(S)===z)return 0;return i.indexOf(`</${y}`,O+1)===-1?null:1}function _i(p,h){l+=9,d();let m=L();d();let y=at();d();let w="";if(P("extends")){l+=7,d();let A=l,M=0;while(l<a){if(T())continue;let N=i.charCodeAt(l);if(N===ge)M++;else if(N===fe&&!Me())M--;else if(N===V&&M===0)break;l++}w=g(A,l)}d();let E=l<a&&i.charCodeAt(l)===V?Bi():"{}",x=vs(E),O=`${h?"export ":""}declare interface ${m}${y}${w?` extends ${w}`:""} ${x}`,S=Je(p);return{kind:"interface",name:m,text:O,isExported:h,extends:w||void 0,generics:y||void 0,leadingComments:S,start:p,end:l}}function Vi(p,h){l+=4,d();let m=L();d();let y=at();if(d(),l<a&&i.charCodeAt(l)===be)l++;d();let w=l,E=0;while(l<a){if(T())continue;let A=i.charCodeAt(l);if(A===ee||A===V||A===pe||A===ge)E++;else if(A===we||A===J||A===$e||A===fe&&!Me())E--;else if(E===0&&A===Y)break;if(E===0&&(q()||Z()))break;l++}let x=g(w,l);if(l<a&&i.charCodeAt(l)===Y)l++;let O=`${h?"export ":""}type ${m}${y} = ${x}`,S=Je(p);return{kind:"type",name:m,text:O,isExported:h,generics:y||void 0,leadingComments:S,start:p,end:l}}function Lt(p,h,m){l+=4,d();let y=L();d();let w=l;if(l<a&&i.charCodeAt(l)===V)ke(V,J);let E=g(p,l),x=Je(p);return{kind:"enum",name:y,text:E,isExported:h,modifiers:m?["const"]:void 0,leadingComments:x,start:p,end:l}}function St(p,h,m,y=!1){l+=5,d();let w=L()||"AnonymousClass";d();let E=at();d();let x="";if(P("extends")){l+=7,d();let N=l,G=0;while(l<a){if(T())continue;let B=i.charCodeAt(l);if(B===ge)G++;else if(B===fe&&!Me())G--;else if(G===0&&(B===V||P("implements")))break;l++}x=g(N,l)}let O;if(P("implements")){l+=10,d();let N=l,G=0;while(l<a){if(T())continue;let D=i.charCodeAt(l);if(D===ge)G++;else if(D===fe&&!Me())G--;else if(G===0&&D===V)break;l++}let B=g(N,l);if(B)O=B.split(",").map((D)=>D.trim())}d();let S=Ui(),A=`${h?y?"export default ":"export declare ":"declare "}${m?"abstract ":""}class ${w}${E}${x?` extends ${x}`:""}${O&&O.length>0?` implements ${O.join(", ")}`:""} ${S}`,M=Je(p);return{kind:"class",name:w,text:A,isExported:h,isDefault:y,extends:x||void 0,implements:O,generics:E||void 0,modifiers:m?["abstract"]:void 0,leadingComments:M,start:p,end:l}}function Ui(){if(l>=a||i.charCodeAt(l)!==V)return"{}";l++;let p=[];while(l<a){if(d(),l>=a)break;if(i.charCodeAt(l)===J){l++;break}if(i.charCodeAt(l)===Y){l++;continue}if(P("static")&&As("static")===V){l+=6,d(),ke(V,J);continue}let h=!1,m=!1,y=!1,w=!1,E=!1,x=!1,O=!1,S=!1,A=!0;while(A){if(d(),P("private")){h=!0,l+=7;continue}if(P("protected")){m=!0,l+=9;continue}if(P("public")){l+=6;continue}if(P("static")){y=!0,l+=6;continue}if(P("abstract")){w=!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(d(),l>=a||i.charCodeAt(l)===J)break;if(i.charCodeAt(l)===_r)h=!0;if(h){Hi();continue}let M=" ";if(m)M+="protected ";if(y)M+="static ";if(w)M+="abstract ";if(E)M+="readonly ";if(P("constructor")){l+=11,d();let N=Et();if(d(),fc(N,p),l<a&&i.charCodeAt(l)===V)ke(V,J);else if(l<a&&i.charCodeAt(l)===Y)l++;let G=Ft(N);p.push(` constructor${G};`)}else if(P("get"))if(l+=3,d(),l<a&&(Ot(i.charCodeAt(l))||i.charCodeAt(l)===pe||i.charCodeAt(l)===_r)){let N=Ki();if(N.startsWith("#")){if(d(),l<a&&i.charCodeAt(l)===ee)Et();if(d(),sr(),d(),l<a&&i.charCodeAt(l)===V)ke(V,J);else if(l<a&&i.charCodeAt(l)===Y)l++;continue}d(),Et(),d();let G=sr()||"unknown";if(d(),l<a&&i.charCodeAt(l)===V)ke(V,J);else if(l<a&&i.charCodeAt(l)===Y)l++;p.push(`${M}get ${N}(): ${G};`)}else $s("get",M,y,E,S,p);else if(P("set"))if(l+=3,d(),l<a&&(Ot(i.charCodeAt(l))||i.charCodeAt(l)===pe||i.charCodeAt(l)===_r)){let N=Ki();if(N.startsWith("#")){if(d(),l<a&&i.charCodeAt(l)===ee)Et();if(d(),l<a&&i.charCodeAt(l)===V)ke(V,J);else if(l<a&&i.charCodeAt(l)===Y)l++;continue}d();let G=Et();if(d(),l<a&&i.charCodeAt(l)===V)ke(V,J);else if(l<a&&i.charCodeAt(l)===Y)l++;let B=Ft(G);p.push(`${M}set ${N}${B};`)}else $s("set",M,y,E,S,p);else{let N=i.charCodeAt(l)===ve;if(N)l++,d();let G=Ki();if(!G){Hi();continue}xs(G,M,y,E,N,w,S,p)}}return`{
|
|
65
65
|
${p.join(`
|
|
66
66
|
`)}
|
|
67
|
-
}`}function Ki(){if(l>=a)return"";let p=i.charCodeAt(l);if(p===
|
|
67
|
+
}`}function Ki(){if(l>=a)return"";let p=i.charCodeAt(l);if(p===pe){let h=l;return ke(pe,$e),i.slice(h,l)}if(p===_r)return l++,`#${L()}`;return L()}function As(p){let h=l+p.length;while(h<a&&De(i.charCodeAt(h)))h++;return h<a?i.charCodeAt(h):0}function Hi(){let p=0;while(l<a){if(T())continue;let h=i.charCodeAt(l);if(h===V||h===ee)p++;else if(h===J||h===we){if(p===0)return;p--}else if(h===Y&&p===0){l++;return}if(p===0&&re())return;l++}}function $s(p,h,m,y,w,E){xs(p,h,m,y,!1,!1,w,E)}function xs(p,h,m,y,w,E,x,O){if(d(),l>=a)return;let S=i.charCodeAt(l),A=!1;if(S===jr)A=!0,l++,d();if(l<a&&i.charCodeAt(l)===33)l++,d();let M=l<a?i.charCodeAt(l):0;if(M===ee||M===ge){let N=M===ge?at():"";d();let G=Et();d();let B=sr(),D=B.length>0;if(!B)if(x&&w)B="AsyncGenerator<unknown, void, unknown>";else if(w)B="Generator<unknown, void, unknown>";else if(x)B="Promise<void>";else B="void";if(d(),l<a&&i.charCodeAt(l)===V){let me=l+1;if(ke(V,J),!o&&!D&&!w)B=hr(i.slice(me,l-1),x,G)}else if(l<a&&i.charCodeAt(l)===Y)l++;let W=Ft(G),j=A?"?":"";O.push(`${h}${p}${j}${N}${W}: ${B};`)}else if(M===Qe||M===be||M===Y||M===J||M===ne||M===ye){let N="";if(M===Qe){l++,d();let D=l,W=0;while(l<a){if(T())continue;let j=i.charCodeAt(l);if(j===ee||j===V||j===pe||j===ge)W++;else if(j===we||j===J||j===$e||j===fe&&!Me()){if(W===0)break;W--}else if(W===0&&(j===Y||j===et))break;else if(W===0&&j===be&&!ft())break;if(W===0&&re())break;l++}N=g(D,l)}let G="";if(l<a&&i.charCodeAt(l)===be)if(o&&N){l++;let D=0;while(l<a){if(T())continue;let W=i.charCodeAt(l);if(W===ee||W===V||W===pe)D++;else if(W===we||W===J||W===$e){if(D===0&&W===J)break;D--}else if(D===0&&W===Y)break;if(D===0&&re())break;l++}}else{l++,d();let D=l,W=0;while(l<a){if(T())continue;let j=i.charCodeAt(l);if(j===ee||j===V||j===pe)W++;else if(j===we||j===J||j===$e){if(W===0&&j===J)break;W--}else if(W===0&&j===Y)break;if(W===0&&re())break;l++}G=g(D,l)}if(l<a&&i.charCodeAt(l)===Y)l++;if(!N)if(G){let D=kr(G);if(D)N=D;else N=G.endsWith("as const")||m&&y?ji(G):Gi(G)}else N="unknown";let B=A?"?":"";O.push(`${h}${p}${B}: ${N};`)}else Hi()}function fc(p,h){let m=p.slice(1,-1).trim();if(!m)return;let y=[],w=0,E=0,x=!1,O=0;for(let S=0;S<=m.length;S++){if(S===m.length){y.push(m.slice(w).trim());break}let A=m.charCodeAt(S);if(x){if(A===He){S++;continue}if(A===O)x=!1;continue}if(A===ie||A===le||A===Pe){x=!0,O=A;continue}if(A===ee||A===V||A===pe||A===ge)E++;else if(A===we||A===J||A===$e||A===fe&&!(S>0&&m.charCodeAt(S-1)===be))E--;else if(A===et&&E===0)y.push(m.slice(w,S).trim()),w=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 B=S,D=[];if(A){let me=6;while(me<B.length&&De(B.charCodeAt(me)))me++;B=B.slice(me),D.push("public")}if(M){let me=9;while(me<B.length&&De(B.charCodeAt(me)))me++;B=B.slice(me),D.push("protected")}if(G){let me=B.indexOf("readonly ");if(me!==-1){let Bt=me+8;while(Bt<B.length&&De(B.charCodeAt(Bt)))Bt++;B=B.slice(0,me)+B.slice(Bt)}D.push("readonly")}let W=D.length>0?`${D.join(" ")} `:"",j=Es(B);h.push(` ${W}${j};`)}}function zi(p=" "){if(l>=a||i.charCodeAt(l)!==V)return"{}";l++;let h=[];while(l<a){if(d(),l>=a)break;if(i.charCodeAt(l)===J){l++;break}if(i.charCodeAt(l)===Y){l++;continue}let m=!1;if(P("export"))m=!0,l+=6,d();if(P("declare"))l+=7,d();let y=m?"export ":"";if(P("function")||P("async")&&uc("async","function")){let w=!1;if(P("async"))w=!0,l+=5,d();if(l+=8,d(),l<a&&i.charCodeAt(l)===ve)l++,d();let E=L();d();let x=at();d();let O=Et();d();let S=sr();if(!S)S=w?"Promise<void>":"void";if(d(),l<a&&i.charCodeAt(l)===V)ke(V,J);else if(l<a&&i.charCodeAt(l)===Y)l++;let A=Ft(O);h.push(`${p}${y}function ${E}${x}${A}: ${S};`)}else if(P("const")||P("let")||P("var")){let w=P("const")?"const":P("let")?"let":"var";l+=w.length,d();let E=L();if(!E){Q();continue}d();let x="";if(l<a&&i.charCodeAt(l)===Qe){l++,d();let S=l,A=0;while(l<a){if(T())continue;let M=i.charCodeAt(l);if(M===ee||M===V||M===pe||M===ge)A++;else if(M===we||M===J||M===$e||M===fe&&!Me())A--;else if(A===0&&(M===Y||M===et))break;else if(A===0&&M===be&&!ft())break;if(A===0&&q())break;l++}x=g(S,l)}let O="";if(l<a&&i.charCodeAt(l)===be){l++,d();let S=l,A=0;while(l<a){if(T())continue;let M=i.charCodeAt(l);if(M===ee||M===V||M===pe||M===ge)A++;else if(M===we||M===J||M===$e||M===fe&&!Me())A--;else if(A===0&&(M===Y||M===et))break;if(A===0&&q())break;l++}O=g(S,l)}if(l<a&&i.charCodeAt(l)===Y)l++;if(!x&&O){let S=kr(O);if(S)x=S;else if(w==="const")x=ji(O);else x=Gi(O)}if(!x)x="unknown";h.push(`${p}${y}${w} ${E}: ${x};`)}else if(P("interface")){l+=9,d();let w=L();d();let E=at();d();let x="";if(P("extends")){l+=7,d();let S=l,A=0;while(l<a){if(T())continue;let M=i.charCodeAt(l);if(M===ge)A++;else if(M===fe&&!Me())A--;else if(M===V&&A===0)break;l++}x=g(S,l)}let O=vs(Bi());h.push(`${p}${y}interface ${w}${E}${x?` extends ${x}`:""} ${O}`)}else if(P("type")){l+=4,d();let w=L();d();let E=at();if(d(),l<a&&i.charCodeAt(l)===be){l++,d();let x=l,O=0;while(l<a){if(T())continue;let A=i.charCodeAt(l);if(A===ee||A===V||A===pe||A===ge)O++;else if(A===we||A===J||A===$e||A===fe&&!Me())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(`${p}${y}type ${w}${E} = ${S}`)}}else if(P("class")){l+=5,d();let w=L();d();let E=at();d();let x=l,O=0;while(l<a){if(T())continue;let N=i.charCodeAt(l);if(N===ge)O++;else if(N===fe&&!Me())O--;else if(N===V&&O===0)break;l++}let S=g(x,l),A=S?` ${S}`:"",M=Ui();h.push(`${p}${y}class ${w}${E}${A} ${M}`)}else if(P("enum")){l+=4,d();let w=L();d();let E=Bi();h.push(`${p}${y}enum ${w} ${E}`)}else if(P("namespace")||P("module")){let w=P("namespace")?"namespace":"module";l+=w.length,d();let E=L();d();let x=zi(p);h.push(`${p}${y}${w} ${E} ${x}`)}else if(P("abstract"))if(l+=8,d(),P("class")){l+=5,d();let w=L();d();let E=at();d();let x=l,O=0;while(l<a){if(T())continue;let N=i.charCodeAt(l);if(N===ge)O++;else if(N===fe&&!Me())O--;else if(N===V&&O===0)break;l++}let S=g(x,l),A=S?` ${S}`:"",M=Ui();h.push(`${p}${y}abstract class ${w}${E}${A} ${M}`)}else Q();else if(m&&P("default")){l+=7,d();let w=l;Q();let E=g(w,l);if(E.charCodeAt(E.length-1)===Y)E=E.slice(0,-1);if(E)h.push(`${p}export default ${E};`)}else if(!m&&(i.charCodeAt(l)===ie||i.charCodeAt(l)===le||i.charCodeAt(l)===Pe))Q();else Q()}if(h.length===0)return"{}";return`{
|
|
68
68
|
${h.join(`
|
|
69
69
|
`)}
|
|
70
|
-
}`}function uc(p,h){let m=l+p.length;while(m<a&&De(i.charCodeAt(m)))m++;for(let y=0;y<h.length;y++)if(m+y>=a||i.charCodeAt(m+y)!==h.charCodeAt(y))return!1;return m+h.length>=a||!Ve(i.charCodeAt(m+h.length))}function Wt(p,h,m){l+=m.length,d();let y="",w=i.charCodeAt(l);if(w===ie||w===le){let A=l;b(w),y=i.slice(A,l)}else{y=W();while(l<a&&i.charCodeAt(l)===ct)l++,y+=`.${W()}`}d();let E=l<a&&i.charCodeAt(l)===V?zi():"{}",x=`${h?"export ":""}declare ${m} ${y} ${E}`,P=Je(p),S=y.startsWith("'")||y.startsWith('"');return{kind:"module",name:y,text:x,isExported:h,source:S?y.slice(1,-1):void 0,leadingComments:P,start:p,end:l}}function Ts(p,h){Q();let m=g(h,l);if(m.charCodeAt(m.length-1)===Y)m=m.slice(0,-1).trimEnd();if(!m)return;let y=Pt(m.charCodeAt(0));for(let A=1;y&&A<m.length;A++)y=Ve(m.charCodeAt(A));let w=Je(p);if(y){c.push({kind:"export",name:"default",text:`export default ${m};`,isExported:!0,isTypeOnly:!1,leadingComments:w,start:p,end:l});return}let E="__dtsx_default_export__",x=1;while(i.includes(E))E=`__dtsx_default_export_${x++}__`;let P=kr(m)||Te(m,!1),S=P==="unknown"&&pf(m)?`typeof ${m}`:P;c.push({kind:"variable",name:E,text:`declare const ${E}: ${S};`,isExported:!1,typeAnnotation:S,modifiers:["const"],start:p,end:l}),c.push({kind:"export",name:"default",text:`export default ${E};`,isExported:!0,isTypeOnly:!1,leadingComments:w,start:p,end:l})}while(l<a){if(d(),l>=a)break;let p=l,h=i.charCodeAt(l);if(h===105&&R("import"))c.push(nc(p));else if(h===101&&R("export")){l+=6,d();let m=i.charCodeAt(l);if(m===100&&R("default")){l+=7,d();let y=l,w=i.charCodeAt(l);if(w===102&&R("function")){let E=bt(p,!0,!1,!0);if(E)c.push(E)}else if(w===97&&R("async")&&As("async")!==Y)if(l+=5,d(),R("function")){let E=bt(p,!0,!0,!0);if(E)c.push(E)}else Ts(p,y);else if(w===99&&R("class")){let E=St(p,!0,!1,!0);c.push(E)}else if(w===97&&R("abstract")){if(l+=8,d(),R("class")){let E=St(p,!0,!0,!0);c.push(E)}}else Ts(p,y)}else if(m===116&&R("type")){let y=l;if(l+=4,d(),l<a&&i.charCodeAt(l)===V){nr();let w=g(p,l),E=Je(p);c.push({kind:"export",name:"",text:w,isExported:!0,isTypeOnly:!0,source:Pr(w),leadingComments:E,start:p,end:l})}else if(l<a&&i.charCodeAt(l)===we){Cs();let w=g(p,l);c.push({kind:"export",name:"",text:w,isExported:!0,isTypeOnly:!0,source:Pr(w),start:p,end:l})}else{l=y;let w=Vi(p,!0);c.push(w)}}else if(m===105&&R("interface")){let y=_i(p,!0);c.push(y)}else if(m===102&&R("function")){let y=bt(p,!0,!1,!1);if(y)c.push(y)}else if(m===97&&R("async"))if(l+=5,d(),R("function")){let y=bt(p,!0,!0,!1);if(y)c.push(y)}else Q();else if(m===99)if(R("class")){let y=St(p,!0,!1);c.push(y)}else if(R("const")){let y=l;if(l+=5,d(),R("enum")){l=y+5,d();let w=Lt(p,!0,!0);c.push(w)}else{l=y;let w=Nt(p,"const",!0);for(let E=0;E<w.length;E++)c.push(w[E])}}else Q();else if(m===97&&R("abstract")){if(l+=8,d(),R("class")){let y=St(p,!0,!0);c.push(y)}}else if(m===108&&R("let")){let y=Nt(p,"let",!0);for(let w=0;w<y.length;w++)c.push(y[w])}else if(m===118&&R("var")){let y=Nt(p,"var",!0);for(let w=0;w<y.length;w++)c.push(y[w])}else if(m===101&&R("enum")){let y=Lt(p,!0,!1);c.push(y)}else if(m===100&&R("declare"))l+=7,d(),Rs(p,!0);else if(m===110&&R("namespace")&&F(9)){let y=Wt(p,!0,"namespace");c.push(y)}else if(m===109&&R("module")&&F(6)){let y=Wt(p,!0,"module");c.push(y)}else if(m===V){nr();let y=g(p,l),w=y.includes("export type"),E=Je(p);c.push({kind:"export",name:"",text:y,isExported:!0,isTypeOnly:w,source:Pr(y),leadingComments:E,start:p,end:l})}else if(m===we){Cs();let y=g(p,l),w=Je(p);c.push({kind:"export",name:"",text:y,isExported:!0,isTypeOnly:!1,source:Pr(y),leadingComments:w,start:p,end:l})}else{Q();let y=g(p,l);if(y)c.push({kind:"export",name:"",text:y,isExported:!0,start:p,end:l})}}else if(h===100&&R("declare"))l+=7,d(),Rs(p,!1);else if(h===105&&R("interface")){let m=_i(p,!1);f.set(m.name,m)}else if(h===116&&R("type")){let m=Vi(p,!1);f.set(m.name,m),c.push(m)}else if(h===102&&R("function")){let m=bt(p,!1,!1,!1);if(m)f.set(m.name,m);else Q()}else if(h===97)if(R("async")){let m=l;if(l+=5,d(),R("function")){let y=bt(p,!1,!0,!1);if(y)f.set(y.name,y);else l=m,Q()}else l=m,Q()}else if(R("abstract"))if(l+=8,d(),R("class")){let m=St(p,!1,!1);f.set(m.name,m),c.push(m)}else Q();else l++,Q();else if(h===99)if(R("class")){let m=St(p,!1,!1);f.set(m.name,m),c.push(m)}else if(R("const")){let m=l;if(l+=5,d(),R("enum")){l=m+5,d();let y=Lt(p,!1,!0);f.set(y.name,y),c.push(y)}else{l=m;let y=Nt(p,"const",!1);for(let w=0;w<y.length;w++)f.set(y[w].name,y[w])}}else l++,Q();else if(h===101&&R("enum")){let m=Lt(p,!1,!1);f.set(m.name,m),c.push(m)}else if(h===108&&R("let"))Q();else if(h===118&&R("var"))Q();else if(h===109&&R("module")&&F(6)){let m=Wt(p,!1,"module");c.push(m)}else if(h===110&&R("namespace")&&F(9)){let m=Wt(p,!1,"namespace");c.push(m)}else{let m=i.charCodeAt(l);if(m===Y)l++;else if(m===ie||m===le){if(b(m),l<a&&i.charCodeAt(l)===Y)l++}else if(m===Re){if(C(),l<a&&i.charCodeAt(l)===Y)l++}else if(m===df){if(l++,W(),d(),l<a&&i.charCodeAt(l)===ct)l++,W(),d();if(l<a&&i.charCodeAt(l)===ee)ke(ee,Ce)}else l++,Q()}}if(f.size>0)yf(c,f);if(u.size>0){let p=new Map;for(let m of c)if(m.kind==="function")p.set(m.name,(p.get(m.name)||0)+1);let h=new Set;for(let[m,y]of p)if(y>1)h.add(m);if(h.size>0){let m=new Set;for(let y of h)for(let w=c.length-1;w>=0;w--)if(c[w].kind==="function"&&c[w].name===y&&u.has(w)){m.add(w);break}if(m.size>0){let y=[...m].sort((w,E)=>E-w);for(let w of y)c.splice(w,1)}}}return c;function Rs(p,h){if(R("function")){let m=bt(p,h,!1,!1);if(m)c.push(m)}else if(R("async")){if(l+=5,d(),R("function")){let m=bt(p,h,!0,!1);if(m)c.push(m)}}else if(R("class")){let m=St(p,h,!1);c.push(m)}else if(R("abstract")){if(l+=8,d(),R("class")){let m=St(p,h,!0);c.push(m)}}else if(R("interface")){let m=_i(p,h);c.push(m)}else if(R("type")){let m=Vi(p,h);c.push(m)}else if(R("enum")){let m=Lt(p,h,!1);c.push(m)}else if(R("const")){let m=l;if(l+=5,d(),R("enum")){l=m+5,d();let y=Lt(p,h,!0);c.push(y)}else if(h){l=m;let y=Nt(p,"const",!0);for(let w=0;w<y.length;w++)c.push(y[w])}else Q()}else if(R("let")||R("var"))if(h){let m=R("let")?"let":"var",y=Nt(p,m,!0);for(let w=0;w<y.length;w++)c.push(y[w])}else Q();else if(R("module")){let m=Wt(p,h,"module");c.push(m)}else if(R("namespace")){let m=Wt(p,h,"namespace");c.push(m)}else if(R("global")){l+=6,d();let m=`declare global ${l<a&&i.charCodeAt(l)===V?zi():"{}"}`,y=Je(p);c.push({kind:"module",name:"global",text:m,isExported:!1,leadingComments:y,start:p,end:l})}else Q()}}function to(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 ro(e,t){let r=0;while(r<e.length){let n=e.charCodeAt(r);if(n===ie||n===le||n===Re){let u=n;r++;while(r<e.length)if(e.charCodeAt(r)===He)r+=2;else if(e.charCodeAt(r++)===u)break;continue}if(n===z&&e.charCodeAt(r+1)===z){r+=2;while(r<e.length&&e.charCodeAt(r)!==ne&&e.charCodeAt(r)!==ge)r++;continue}if(n===z&&e.charCodeAt(r+1)===we){let u=e.indexOf("*/",r+2);r=u===-1?e.length:u+2;continue}if(!Pt(n)){r++;continue}let i=r++;while(r<e.length&&Ve(e.charCodeAt(r)))r++;let s=i-1,o=r;while(s>=0&&De(e.charCodeAt(s)))s--;while(o<e.length&&De(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===Qe||a===ct&&!f)continue;if(c===ee&&(a===V||a===et))continue;t.add(e.slice(i,r))}}function yf(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),to(a.text,i),typeof a.value==="string")ro(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),to(f.text,i),typeof f.value==="string")ro(f.value,i)}}}var be=32,Se=9,ne=10,ge=13,z=47,we=42,ie=39,le=34,Re=96,He=92,V=123,J=125,ee=40,Ce=41,me=91,Ae=93,pe=60,fe=62,Y=59,Qe=58,Ee=61,et=44,ct=46,jr=63,_r=35,df=64,io=36,mf=95,mn;var ao=ce(()=>{dn();mn=["public","protected","private","readonly","override"]});function co(e,t,r=!0,n=!1){if(Ms(t))e=Fs(e);else if(Ls(t))e=Ws(e);let i=or(e),s=`${t}:${r?1:0}:${n?1:0}`,o=_t.get(s);if(o&&o.contentHash===i)return o.lastAccess=++lo,o.declarations;let a=n?no(e,t,r):so(e,t,r);if(_t.set(s,{declarations:a,contentHash:i,lastAccess:++lo}),_t.size>Cf){let c=Math.max(1,Math.ceil(_t.size*0.1)),f=[];for(let[u,l]of _t)f.push([u,l.lastAccess]);f.sort((u,l)=>u[1]-l[1]);for(let u=0;u<c&&u<f.length;u++)_t.delete(f[u][0])}return a}var Cf=100,lo=0,_t;var fo=ce(()=>{sn();Bs();ao();Ji();_t=new Map});function Ur(e,t,r=!0,n=!1){return co(e,t,r,n)}var pn=ce(()=>{fo()});import{dirname as tp,relative as wf,resolve as rp}from"path";async function uo(e,t,r){let n=new Map,i=[],s=new Set,o=0,a=0,c=0,f=[];for(let k of e){let O=t.get(k);if(!O)continue;f.push({file:k,decls:Ur(O,k,r.keepComments)})}for(let{file:k,decls:O}of f){o+=O.length;for(let I of O)if(I.kind==="import"){a++;let j=I.source||"";if(j.startsWith("."))continue;if(!n.has(j))n.set(j,{source:j,specifiers:new Map,isTypeOnly:I.isTypeOnly||!1,isSideEffect:I.isSideEffect||!1});let W=n.get(j);if(I.specifiers)for(let R of I.specifiers){let F=R.alias||R.name;if(!W.specifiers.has(F))W.specifiers.set(F,{name:R.name,alias:R.alias,isType:R.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()),d=Array(g.length);for(let k=0;k<g.length;k++){let O=g[k].source,I=l.length;for(let j=0;j<l.length;j++)if(O.startsWith(l[j])){I=j;break}d[k]=I}let v=g.map((k,O)=>O);v.sort((k,O)=>{let I=d[k],j=d[O];if(I!==j)return I-j;return g[k].source.localeCompare(g[O].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 O=Array.from(k.specifiers.values()).map((j)=>{let W=j.isType?"type ":"";return j.alias?`${W}${j.name} as ${j.alias}`:`${W}${j.name}`}),I=k.isTypeOnly?"type ":"";u.push(`import ${I}{ ${O.join(", ")} } from '${k.source}';`)}if(b.length>0)u.push("");let C=new Map;for(let{declaration:k,file:O}of i){if(!C.has(O))C.set(O,[]);C.get(O).push(k)}for(let[k,O]of C){let I=wf(r.cwd,k);u.push(`// From: ${I}`);for(let j of O){if(r.keepComments&&j.leadingComments)for(let W of j.leadingComments)u.push(W);u.push(ho(j))}u.push("")}let T=u.join(`
|
|
70
|
+
}`}function uc(p,h){let m=l+p.length;while(m<a&&De(i.charCodeAt(m)))m++;for(let y=0;y<h.length;y++)if(m+y>=a||i.charCodeAt(m+y)!==h.charCodeAt(y))return!1;return m+h.length>=a||!Ve(i.charCodeAt(m+h.length))}function Wt(p,h,m){l+=m.length,d();let y="",w=i.charCodeAt(l);if(w===ie||w===le){let A=l;b(w),y=i.slice(A,l)}else{y=L();while(l<a&&i.charCodeAt(l)===ct)l++,y+=`.${L()}`}d();let E=l<a&&i.charCodeAt(l)===V?zi():"{}",x=`${h?"export ":""}declare ${m} ${y} ${E}`,O=Je(p),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:p,end:l}}function Ts(p,h){Q();let m=g(h,l);if(m.charCodeAt(m.length-1)===Y)m=m.slice(0,-1).trimEnd();if(!m)return;let y=Ot(m.charCodeAt(0));for(let A=1;y&&A<m.length;A++)y=Ve(m.charCodeAt(A));let w=Je(p);if(y){c.push({kind:"export",name:"default",text:`export default ${m};`,isExported:!0,isTypeOnly:!1,leadingComments:w,start:p,end:l});return}let E="__dtsx_default_export__",x=1;while(i.includes(E))E=`__dtsx_default_export_${x++}__`;let O=kr(m)||Te(m,!1),S=O==="unknown"&&pf(m)?`typeof ${m}`:O;c.push({kind:"variable",name:E,text:`declare const ${E}: ${S};`,isExported:!1,typeAnnotation:S,modifiers:["const"],start:p,end:l}),c.push({kind:"export",name:"default",text:`export default ${E};`,isExported:!0,isTypeOnly:!1,leadingComments:w,start:p,end:l})}while(l<a){if(d(),l>=a)break;let p=l,h=i.charCodeAt(l);if(h===105&&P("import"))c.push(nc(p));else if(h===101&&P("export")){l+=6,d();let m=i.charCodeAt(l);if(m===100&&P("default")){l+=7,d();let y=l,w=i.charCodeAt(l);if(w===102&&P("function")){let E=bt(p,!0,!1,!0);if(E)c.push(E)}else if(w===97&&P("async")&&As("async")!==Y)if(l+=5,d(),P("function")){let E=bt(p,!0,!0,!0);if(E)c.push(E)}else Ts(p,y);else if(w===99&&P("class")){let E=St(p,!0,!1,!0);c.push(E)}else if(w===97&&P("abstract")){if(l+=8,d(),P("class")){let E=St(p,!0,!0,!0);c.push(E)}}else Ts(p,y)}else if(m===116&&P("type")){let y=l;if(l+=4,d(),l<a&&i.charCodeAt(l)===V){nr();let w=g(p,l),E=Je(p);c.push({kind:"export",name:"",text:w,isExported:!0,isTypeOnly:!0,source:Or(w),leadingComments:E,start:p,end:l})}else if(l<a&&i.charCodeAt(l)===ve){Cs();let w=g(p,l);c.push({kind:"export",name:"",text:w,isExported:!0,isTypeOnly:!0,source:Or(w),start:p,end:l})}else{l=y;let w=Vi(p,!0);c.push(w)}}else if(m===105&&P("interface")){let y=_i(p,!0);c.push(y)}else if(m===102&&P("function")){let y=bt(p,!0,!1,!1);if(y)c.push(y)}else if(m===97&&P("async"))if(l+=5,d(),P("function")){let y=bt(p,!0,!0,!1);if(y)c.push(y)}else Q();else if(m===99)if(P("class")){let y=St(p,!0,!1);c.push(y)}else if(P("const")){let y=l;if(l+=5,d(),P("enum")){l=y+5,d();let w=Lt(p,!0,!0);c.push(w)}else{l=y;let w=Nt(p,"const",!0);for(let E=0;E<w.length;E++)c.push(w[E])}}else Q();else if(m===97&&P("abstract")){if(l+=8,d(),P("class")){let y=St(p,!0,!0);c.push(y)}}else if(m===108&&P("let")){let y=Nt(p,"let",!0);for(let w=0;w<y.length;w++)c.push(y[w])}else if(m===118&&P("var")){let y=Nt(p,"var",!0);for(let w=0;w<y.length;w++)c.push(y[w])}else if(m===101&&P("enum")){let y=Lt(p,!0,!1);c.push(y)}else if(m===100&&P("declare"))l+=7,d(),Ps(p,!0);else if(m===110&&P("namespace")&&F(9)){let y=Wt(p,!0,"namespace");c.push(y)}else if(m===109&&P("module")&&F(6)){let y=Wt(p,!0,"module");c.push(y)}else if(m===V){nr();let y=g(p,l),w=y.includes("export type"),E=Je(p);c.push({kind:"export",name:"",text:y,isExported:!0,isTypeOnly:w,source:Or(y),leadingComments:E,start:p,end:l})}else if(m===ve){Cs();let y=g(p,l),w=Je(p);c.push({kind:"export",name:"",text:y,isExported:!0,isTypeOnly:!1,source:Or(y),leadingComments:w,start:p,end:l})}else{Q();let y=g(p,l);if(y)c.push({kind:"export",name:"",text:y,isExported:!0,start:p,end:l})}}else if(h===100&&P("declare"))l+=7,d(),Ps(p,!1);else if(h===105&&P("interface")){let m=_i(p,!1);f.set(m.name,m)}else if(h===116&&P("type")){let m=Vi(p,!1);f.set(m.name,m),c.push(m)}else if(h===102&&P("function")){let m=bt(p,!1,!1,!1);if(m)f.set(m.name,m);else Q()}else if(h===97)if(P("async")){let m=l;if(l+=5,d(),P("function")){let y=bt(p,!1,!0,!1);if(y)f.set(y.name,y);else l=m,Q()}else l=m,Q()}else if(P("abstract"))if(l+=8,d(),P("class")){let m=St(p,!1,!1);f.set(m.name,m),c.push(m)}else Q();else l++,Q();else if(h===99)if(P("class")){let m=St(p,!1,!1);f.set(m.name,m),c.push(m)}else if(P("const")){let m=l;if(l+=5,d(),P("enum")){l=m+5,d();let y=Lt(p,!1,!0);f.set(y.name,y),c.push(y)}else{l=m;let y=Nt(p,"const",!1);for(let w=0;w<y.length;w++)f.set(y[w].name,y[w])}}else l++,Q();else if(h===101&&P("enum")){let m=Lt(p,!1,!1);f.set(m.name,m),c.push(m)}else if(h===108&&P("let"))Q();else if(h===118&&P("var"))Q();else if(h===109&&P("module")&&F(6)){let m=Wt(p,!1,"module");c.push(m)}else if(h===110&&P("namespace")&&F(9)){let m=Wt(p,!1,"namespace");c.push(m)}else{let m=i.charCodeAt(l);if(m===Y)l++;else if(m===ie||m===le){if(b(m),l<a&&i.charCodeAt(l)===Y)l++}else if(m===Pe){if(C(),l<a&&i.charCodeAt(l)===Y)l++}else if(m===df){if(l++,L(),d(),l<a&&i.charCodeAt(l)===ct)l++,L(),d();if(l<a&&i.charCodeAt(l)===ee)ke(ee,we)}else l++,Q()}}if(f.size>0)yf(c,f);if(u.size>0){let p=new Map;for(let m of c)if(m.kind==="function")p.set(m.name,(p.get(m.name)||0)+1);let h=new Set;for(let[m,y]of p)if(y>1)h.add(m);if(h.size>0){let m=new Set;for(let y of h)for(let w=c.length-1;w>=0;w--)if(c[w].kind==="function"&&c[w].name===y&&u.has(w)){m.add(w);break}if(m.size>0){let y=[...m].sort((w,E)=>E-w);for(let w of y)c.splice(w,1)}}}return c;function Ps(p,h){if(P("function")){let m=bt(p,h,!1,!1);if(m)c.push(m)}else if(P("async")){if(l+=5,d(),P("function")){let m=bt(p,h,!0,!1);if(m)c.push(m)}}else if(P("class")){let m=St(p,h,!1);c.push(m)}else if(P("abstract")){if(l+=8,d(),P("class")){let m=St(p,h,!0);c.push(m)}}else if(P("interface")){let m=_i(p,h);c.push(m)}else if(P("type")){let m=Vi(p,h);c.push(m)}else if(P("enum")){let m=Lt(p,h,!1);c.push(m)}else if(P("const")){let m=l;if(l+=5,d(),P("enum")){l=m+5,d();let y=Lt(p,h,!0);c.push(y)}else if(h){l=m;let y=Nt(p,"const",!0);for(let w=0;w<y.length;w++)c.push(y[w])}else Q()}else if(P("let")||P("var"))if(h){let m=P("let")?"let":"var",y=Nt(p,m,!0);for(let w=0;w<y.length;w++)c.push(y[w])}else Q();else if(P("module")){let m=Wt(p,h,"module");c.push(m)}else if(P("namespace")){let m=Wt(p,h,"namespace");c.push(m)}else if(P("global")){l+=6,d();let m=`declare global ${l<a&&i.charCodeAt(l)===V?zi():"{}"}`,y=Je(p);c.push({kind:"module",name:"global",text:m,isExported:!1,leadingComments:y,start:p,end:l})}else Q()}}function to(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 ro(e,t){let r=0;while(r<e.length){let n=e.charCodeAt(r);if(n===ie||n===le||n===Pe){let u=n;r++;while(r<e.length)if(e.charCodeAt(r)===He)r+=2;else if(e.charCodeAt(r++)===u)break;continue}if(n===z&&e.charCodeAt(r+1)===z){r+=2;while(r<e.length&&e.charCodeAt(r)!==ne&&e.charCodeAt(r)!==ye)r++;continue}if(n===z&&e.charCodeAt(r+1)===ve){let u=e.indexOf("*/",r+2);r=u===-1?e.length:u+2;continue}if(!Ot(n)){r++;continue}let i=r++;while(r<e.length&&Ve(e.charCodeAt(r)))r++;let s=i-1,o=r;while(s>=0&&De(e.charCodeAt(s)))s--;while(o<e.length&&De(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===Qe||a===ct&&!f)continue;if(c===ee&&(a===V||a===et))continue;t.add(e.slice(i,r))}}function yf(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),to(a.text,i),typeof a.value==="string")ro(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),to(f.text,i),typeof f.value==="string")ro(f.value,i)}}}var Se=32,Ae=9,ne=10,ye=13,z=47,ve=42,ie=39,le=34,Pe=96,He=92,V=123,J=125,ee=40,we=41,pe=91,$e=93,ge=60,fe=62,Y=59,Qe=58,be=61,et=44,ct=46,jr=63,_r=35,df=64,io=36,mf=95,mn;var ao=ce(()=>{dn();mn=["public","protected","private","readonly","override"]});function co(e,t,r=!0,n=!1){if(Ms(t))e=Fs(e);else if(Ls(t))e=Ws(e);let i=or(e),s=`${t}:${r?1:0}:${n?1:0}`,o=_t.get(s);if(o&&o.contentHash===i)return o.lastAccess=++lo,o.declarations;let a=n?no(e,t,r):so(e,t,r);if(_t.set(s,{declarations:a,contentHash:i,lastAccess:++lo}),_t.size>Cf){let c=Math.max(1,Math.ceil(_t.size*0.1)),f=[];for(let[u,l]of _t)f.push([u,l.lastAccess]);f.sort((u,l)=>u[1]-l[1]);for(let u=0;u<c&&u<f.length;u++)_t.delete(f[u][0])}return a}var Cf=100,lo=0,_t;var fo=ce(()=>{sn();Bs();ao();Ji();_t=new Map});function Ur(e,t,r=!0,n=!1){return co(e,t,r,n)}var pn=ce(()=>{fo()});import{dirname as tp,relative as wf,resolve as rp}from"path";async function uo(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:Ur(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 L=n.get(_);if(I.specifiers)for(let P of I.specifiers){let F=P.alias||P.name;if(!L.specifiers.has(F))L.specifiers.set(F,{name:P.name,alias:P.alias,isType:P.isType||!1})}if(!I.isTypeOnly)L.isTypeOnly=!1}else if(I.isExported||I.kind==="export"){if(c++,I.kind==="export"&&I.source&&(I.source.startsWith(".")||I.source.startsWith("/")))continue;if(I.name&&s.has(I.name))continue;if(I.name)s.add(I.name);i.push({declaration:I,file:k})}}let u=[];u.push("/**"),u.push(" * Bundled TypeScript declarations"),u.push(` * Generated from ${e.length} source files`),u.push(" */"),u.push("");let l=r.importOrder||["bun"],g=Array.from(n.values()),d=Array(g.length);for(let k=0;k<g.length;k++){let R=g[k].source,I=l.length;for(let _=0;_<l.length;_++)if(R.startsWith(l[_])){I=_;break}d[k]=I}let v=g.map((k,R)=>R);v.sort((k,R)=>{let I=d[k],_=d[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 L=_.isType?"type ":"";return _.alias?`${L}${_.name} as ${_.alias}`:`${L}${_.name}`}),I=k.isTypeOnly?"type ":"";u.push(`import ${I}{ ${R.join(", ")} } from '${k.source}';`)}if(b.length>0)u.push("");let C=new Map;for(let{declaration:k,file:R}of i){if(!C.has(R))C.set(R,[]);C.get(R).push(k)}for(let[k,R]of C){let I=wf(r.cwd,k);u.push(`// From: ${I}`);for(let _ of R){if(r.keepComments&&_.leadingComments)for(let L of _.leadingComments)u.push(L);u.push(ho(_))}u.push("")}let T=u.join(`
|
|
71
71
|
`);return{content:T,files:e,declarationCount:o,importCount:a,exportCount:c,size:Buffer.byteLength(T,"utf8"),warnings:[]}}function ho(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(`(${vf(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(` ${ho(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(`,
|
|
72
72
|
`)}`)}t.push("}");break;default:return e.text||""}return t.join(" ")}function vf(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 mo=ce(()=>{pn()});import{existsSync as pr,mkdirSync as Ef,readFileSync as yn,renameSync as bf,rmSync as po,statSync as go,writeFileSync as yo}from"fs";import{join as Co,relative as Kr,resolve as Sf}from"path";class Cn{cacheDir;manifestPath;manifest=null;configHash;constructor(e){this.cacheDir=Sf(e.cwd,Hr),this.manifestPath=Co(this.cacheDir,Af),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(or(JSON.stringify(t)))}hashString(e){return String(or(e))}load(){try{if(!pr(this.manifestPath))return!1;let e=yn(this.manifestPath,"utf-8"),t=JSON.parse(e);if(t.version!==gn)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:gn,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};if(this.manifest.updatedAt=Date.now(),!pr(this.cacheDir))Ef(this.cacheDir,{recursive:!0});let e=`${this.manifestPath}.${process.pid}.tmp`;try{yo(e,JSON.stringify(this.manifest,null,2)),bf(e,this.manifestPath)}finally{if(pr(e))po(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=Kr(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=go(e),{mtimeMs:s,ctimeMs:o}=i;if(i.size!==n.sourceSize)return null;if(s!==n.sourceMtime||o!==n.sourceCtime){let a=yn(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:gn,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};let i=Kr(n,e),s,o,a;try{let c=go(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=Kr(t,e);delete this.manifest.entries[r]}clear(){this.manifest=null;try{if(pr(this.manifestPath))po(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)=>Kr(t,i)));for(let i of Object.keys(this.manifest.entries))if(!n.has(i))delete this.manifest.entries[i],r++;return r}}function wo(e){let t=Co(e,".gitignore");try{let r="";if(pr(t))r=yn(t,"utf-8");if(!r.split(/\r?\n/).some((n)=>n.trim()===Hr||n.trim()===`${Hr}/`)){let n=r.trimEnd(),i=`${n}${n?`
|
|
73
73
|
|
|
74
74
|
`:""}# dtsx cache
|
|
75
75
|
${Hr}/
|
|
76
|
-
`;yo(t,i)}}catch{}}var gn=3,Hr=".dtsx-cache",Af="manifest.json";var vo=ce(()=>{Ji()});import{readFile as $f,stat as cp,writeFile as xf}from"fs/promises";async function Eo(e,t){if(zr)return globalThis.Bun.write(e,t);let r=typeof t==="string"?t:t instanceof ArrayBuffer?Buffer.from(t):t;return await xf(e,r),typeof t==="string"?Buffer.byteLength(t):t.byteLength}async function ht(e){if(zr)return globalThis.Bun.file(e).text();return $f(e,"utf-8")}var zr,fp;var Jr=ce(()=>{zr=typeof globalThis.Bun<"u",fp=!zr&&typeof process<"u"&&!!process.versions?.node});function Vt(e){return bo[e]>=bo[qr]}function Of(){if(!Rf)return"";return`[${new Date().toISOString().slice(11,23)}] `}function Pf(e,t){let r=Of();if(e||r)return[`${r}${e}`,...t];return t}function Ut(e,t,r){let n=Pf(t,r);if(So){So(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 Ao(e){return{debug:(...t)=>{if(Vt("debug"))Ut("debug",e,t)},info:(...t)=>{if(Vt("info"))Ut("info",e,t)},warn:(...t)=>{if(Vt("warn"))Ut("warn",e,t)},error:(...t)=>{if(Vt("error"))Ut("error",e,t)},setLevel:(t)=>{qr=t},getLevel:()=>qr,child:(t)=>{let r=e?`${e}:${t}`:`[${t}]`;return Ao(r)},time:(t)=>{let r=performance.now();return()=>{let n=performance.now()-r;if(Vt("debug"))Ut("debug",e,[`${t}: ${n.toFixed(2)}ms`])}},progress:(t)=>{if(Vt("info"))if(typeof process<"u"&&process.stdout?.isTTY)process.stdout.write(`\r${e} ${t}`);else Ut("info",e,[t])}}}function wn(e){qr=e}var bo,qr="info",Tf="[dtsx]",Rf=!1,So=null,K;var $o=ce(()=>{bo={debug:0,info:1,warn:2,error:3,silent:4};K=Ao(Tf)});import kf from"process";import{existsSync as xo,statSync as To}from"fs";import{existsSync as Mf,mkdirSync as gp,readdirSync as yp,readFileSync as Df,writeFileSync as Cp}from"fs";import{homedir as Kt}from"os";import{dirname as Ep,resolve as tt}from"path";import Oi from"process";import{existsSync as Ro,statSync as Oo}from"fs";import{existsSync as Bn,mkdirSync as If,readdirSync as Ff,writeFileSync as Nf}from"fs";import{homedir as Ht}from"os";import{dirname as Po,resolve as Ke}from"path";import kt from"process";import{join as Lf,relative as Wf,resolve as ko}from"path";import pi from"process";import{existsSync as ha,mkdirSync as kp,readdirSync as Mp,writeFileSync as Dp}from"fs";import{homedir as vn}from"os";import{dirname as Np,resolve as Ue}from"path";import yr from"process";import{join as Bf,relative as Gf,resolve as Mo}from"path";import gi from"process";import{existsSync as da,mkdirSync as jp,readdirSync as _p,writeFileSync as Vp}from"fs";import{dirname as Kp,resolve as yi}from"path";import Gn from"process";import{Buffer as At}from"buffer";import{createCipheriv as jf,createDecipheriv as _f,randomBytes as En}from"crypto";import{closeSync as bn,createReadStream as Do,createWriteStream as Vf,existsSync as Sn,fsyncSync as Io,openSync as Fo,writeFileSync as Uf}from"fs";import{access as Kf,constants as No,mkdir as Hf,readdir as Yr,rename as Lo,stat as zt,unlink as Zr,writeFile as An}from"fs/promises";import{join as Jt}from"path";import Be from"process";import{pipeline as zf}from"stream/promises";import{createGzip as Wo}from"zlib";import qt from"process";import gt from"process";import{Buffer as dt}from"buffer";import{createCipheriv as Jf,createDecipheriv as qf,randomBytes as $n}from"crypto";import{closeSync as xn,createReadStream as Bo,createWriteStream as Yf,existsSync as Xr,fsyncSync as Go,openSync as jo,writeFileSync as Zf}from"fs";import{access as Xf,constants as _o,mkdir as Qf,readdir as Qr,rename as Vo,stat as Yt,unlink as ei,writeFile as Tn}from"fs/promises";import{isAbsolute as eu,join as Zt,resolve as tu}from"path";import ue from"process";import{pipeline as ru}from"stream/promises";import{createGzip as Uo}from"zlib";import Xt from"process";import yt from"process";import ti from"process";import{existsSync as ri}from"fs";import{resolve as Rn}from"path";import{existsSync as iu}from"fs";import{existsSync as nu,readdirSync as su}from"fs";import{extname as On,resolve as Ko}from"path";import ou from"process";import{join as au,relative as lu,resolve as Ho}from"path";import Ci from"process";import{Buffer as mt}from"buffer";import{createCipheriv as cu,createDecipheriv as fu,randomBytes as Pn}from"crypto";import{closeSync as kn,createReadStream as zo,createWriteStream as uu,existsSync as ii,fsyncSync as Jo,openSync as qo,writeFileSync as hu}from"fs";import{access as du,constants as Yo,mkdir as mu,readdir as ni,rename as Zo,stat as Qt,unlink as si,writeFile as Mn}from"fs/promises";import{isAbsolute as pu,join as er,resolve as gu}from"path";import he from"process";import{pipeline as yu}from"stream/promises";import{createGzip as Xo}from"zlib";import tr from"process";import Ct from"process";import oi from"process";import{existsSync as ai}from"fs";import{resolve as Dn}from"path";import{existsSync as Cu}from"fs";class ma{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(!xo(e))return!0;return To(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=xo(r)?To(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class pa{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),s}catch(s){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Eu(e,t){this[e]=vu.bind(null,t)}class Xn{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(!Ro(e))return!0;return Oo(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=Ro(r)?Oo(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 Qn{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 Au(e,t={}){let r=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return r?`${e}:${r}`:e}function $u(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function xu(e){return e.getStats().size*2}function es(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&ve(t[0])&&"id"in t[0]&&t[0].id===3&&ve(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(ve(t)&&ve(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(ve(e)&&"arr"in e&&Array.isArray(e.arr)&&ve(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&ve(t[0])&&ve(e[0])){let n=[...t];for(let i of e)if(ve(i)&&"name"in i){if(!n.find((s)=>ve(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(ve(i)&&"path"in i){if(!n.find((s)=>ve(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((s)=>vi(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!ve(t)||!ve(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(ve(i)&&ve(r[n]))r[n]=es(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&ve(i[0])&&ve(r[n][0])){let s=[...i];for(let o of r[n])if(ve(o)&&"name"in o){if(!s.find((a)=>ve(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(ve(o)&&"path"in o){if(!s.find((a)=>ve(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((a)=>vi(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 vi(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!vi(e[r],t[r]))return!1;return!0}if(ve(e)&&ve(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!vi(e[i],t[i]))return!1}return!0}return!1}function ve(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Tu(e,t){if(!da(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 es(t,n)}catch{return null}}catch{return null}}async function Ru({name:e="",cwd:t,defaultConfig:r}){let n=t||Gn.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=yi(n,`${o}${a}`),f=await Tu(c,r);if(f!==null)return f}try{let o=yi(n,"package.json");if(da(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return es(r,a)}catch{}}}catch{}return r}function Ou(e,t={}){let r=gi.cwd();while(r.includes("storage"))r=Mo(r,"..");let n=Mo(r,e||"");if(t?.relative)return Gf(gi.cwd(),n);return n}async function Pu(){try{let e=await Ru({name:"clarity",defaultConfig:ui,cwd:gi.cwd(),endpoint:"",headers:{}});return{...ui,...e}}catch{return ui}}function $e(){if(gt.env.NODE_ENV==="test"||gt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ku(){if(gt.env.NODE_ENV==="test"||gt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof gt<"u"){let e=gt.type;if(e==="renderer"||e==="worker")return!1;return!!(gt.versions&&(gt.versions.node||gt.versions.bun))}return!1}class ya{async format(e){let t=await ku(),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 Ei{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={..._n},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new ya,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Be.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...hi,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...hi};return{...hi,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:_n.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 Kf(this.config.logDirectory,No.F_OK|No.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Hf(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:At.from(e);try{if(!Sn(this.currentLogFile))await An(this.currentLogFile,"",{mode:420});if(n=Fo(this.currentLogFile,"a",420),Uf(n,a,{flag:"a"}),Io(n),n!==void 0)bn(n),n=void 0;if((await zt(this.currentLogFile)).size===0){if(await An(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{bn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===s-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}i++;let c=o*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Jt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Jt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Jt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if($e())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 En(16).toString("hex")}generateKey(){return En(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=En(16),n=jf("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=Wo(),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($e())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 Yr(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 Lo(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await Zr(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 An(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await zt(r).catch(()=>null))await Lo(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await Yr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await Zr(Jt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Do(e),n=Vf(t),i=Wo();await zf(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Sn(this.currentLogFile))try{let e=Fo(this.currentLogFile,"r+");Io(e),bn(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!$e()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Yr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Zr(Jt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?ye.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,a=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let c=Be.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${i}`;else if(s==="info"||s==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${ye.cyan(i)}`;if(!o)return f.trim();let u=a(f).trim().length,l=a(t).length,g=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(g)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let a=Number.parseInt(o,10);return a<t[0].length?String(t[0][a]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let a=t[n++];switch(o){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,a;if(t instanceof Error)o=t.message,a=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!$e()){let f=Ta[e],u=this.options.showTags!==!1&&this.name?ye.gray(this.formatTag(this.name)):"",l;switch(e){case"debug":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:ye.gray(o),level:e}),console.error(l);break;case"info":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:o,level:e}),console.error(l);break;case"success":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:ye.green(o),level:e}),console.error(l);break;case"warning":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:o,level:e}),console.warn(l);break;case"error":if(l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:o,level:e}),console.error(l),a){let g=a.split(`
|
|
77
|
-
`);for(let d of g)if(d.trim()&&!d.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:
|
|
76
|
+
`;yo(t,i)}}catch{}}var gn=3,Hr=".dtsx-cache",Af="manifest.json";var vo=ce(()=>{Ji()});import{readFile as $f,stat as cp,writeFile as xf}from"fs/promises";async function Eo(e,t){if(zr)return globalThis.Bun.write(e,t);let r=typeof t==="string"?t:t instanceof ArrayBuffer?Buffer.from(t):t;return await xf(e,r),typeof t==="string"?Buffer.byteLength(t):t.byteLength}async function ht(e){if(zr)return globalThis.Bun.file(e).text();return $f(e,"utf-8")}var zr,fp;var Jr=ce(()=>{zr=typeof globalThis.Bun<"u",fp=!zr&&typeof process<"u"&&!!process.versions?.node});function Vt(e){return bo[e]>=bo[qr]}function Rf(){if(!Pf)return"";return`[${new Date().toISOString().slice(11,23)}] `}function Of(e,t){let r=Rf();if(e||r)return[`${r}${e}`,...t];return t}function Ut(e,t,r){let n=Of(t,r);if(So){So(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 Ao(e){return{debug:(...t)=>{if(Vt("debug"))Ut("debug",e,t)},info:(...t)=>{if(Vt("info"))Ut("info",e,t)},warn:(...t)=>{if(Vt("warn"))Ut("warn",e,t)},error:(...t)=>{if(Vt("error"))Ut("error",e,t)},setLevel:(t)=>{qr=t},getLevel:()=>qr,child:(t)=>{let r=e?`${e}:${t}`:`[${t}]`;return Ao(r)},time:(t)=>{let r=performance.now();return()=>{let n=performance.now()-r;if(Vt("debug"))Ut("debug",e,[`${t}: ${n.toFixed(2)}ms`])}},progress:(t)=>{if(Vt("info"))if(typeof process<"u"&&process.stdout?.isTTY)process.stdout.write(`\r${e} ${t}`);else Ut("info",e,[t])}}}function wn(e){qr=e}var bo,qr="info",Tf="[dtsx]",Pf=!1,So=null,K;var $o=ce(()=>{bo={debug:0,info:1,warn:2,error:3,silent:4};K=Ao(Tf)});import kf from"process";import{existsSync as xo,statSync as To}from"fs";import{existsSync as Mf,mkdirSync as gp,readdirSync as yp,readFileSync as Df,writeFileSync as Cp}from"fs";import{homedir as Kt}from"os";import{dirname as Ep,resolve as tt}from"path";import Ri from"process";import{existsSync as Po,statSync as Ro}from"fs";import{existsSync as Bn,mkdirSync as If,readdirSync as Ff,writeFileSync as Nf}from"fs";import{homedir as Ht}from"os";import{dirname as Oo,resolve as Ke}from"path";import kt from"process";import{join as Lf,relative as Wf,resolve as ko}from"path";import pi from"process";import{existsSync as ha,mkdirSync as kp,readdirSync as Mp,writeFileSync as Dp}from"fs";import{homedir as vn}from"os";import{dirname as Np,resolve as Ue}from"path";import yr from"process";import{join as Bf,relative as Gf,resolve as Mo}from"path";import gi from"process";import{existsSync as da,mkdirSync as jp,readdirSync as _p,writeFileSync as Vp}from"fs";import{dirname as Kp,resolve as yi}from"path";import Gn from"process";import{Buffer as At}from"buffer";import{createCipheriv as jf,createDecipheriv as _f,randomBytes as En}from"crypto";import{closeSync as bn,createReadStream as Do,createWriteStream as Vf,existsSync as Sn,fsyncSync as Io,openSync as Fo,writeFileSync as Uf}from"fs";import{access as Kf,constants as No,mkdir as Hf,readdir as Yr,rename as Lo,stat as zt,unlink as Zr,writeFile as An}from"fs/promises";import{join as Jt}from"path";import Be from"process";import{pipeline as zf}from"stream/promises";import{createGzip as Wo}from"zlib";import qt from"process";import gt from"process";import{Buffer as dt}from"buffer";import{createCipheriv as Jf,createDecipheriv as qf,randomBytes as $n}from"crypto";import{closeSync as xn,createReadStream as Bo,createWriteStream as Yf,existsSync as Xr,fsyncSync as Go,openSync as jo,writeFileSync as Zf}from"fs";import{access as Xf,constants as _o,mkdir as Qf,readdir as Qr,rename as Vo,stat as Yt,unlink as ei,writeFile as Tn}from"fs/promises";import{isAbsolute as eu,join as Zt,resolve as tu}from"path";import ue from"process";import{pipeline as ru}from"stream/promises";import{createGzip as Uo}from"zlib";import Xt from"process";import yt from"process";import ti from"process";import{existsSync as ri}from"fs";import{resolve as Pn}from"path";import{existsSync as iu}from"fs";import{existsSync as nu,readdirSync as su}from"fs";import{extname as Rn,resolve as Ko}from"path";import ou from"process";import{join as au,relative as lu,resolve as Ho}from"path";import Ci from"process";import{Buffer as mt}from"buffer";import{createCipheriv as cu,createDecipheriv as fu,randomBytes as On}from"crypto";import{closeSync as kn,createReadStream as zo,createWriteStream as uu,existsSync as ii,fsyncSync as Jo,openSync as qo,writeFileSync as hu}from"fs";import{access as du,constants as Yo,mkdir as mu,readdir as ni,rename as Zo,stat as Qt,unlink as si,writeFile as Mn}from"fs/promises";import{isAbsolute as pu,join as er,resolve as gu}from"path";import he from"process";import{pipeline as yu}from"stream/promises";import{createGzip as Xo}from"zlib";import tr from"process";import Ct from"process";import oi from"process";import{existsSync as ai}from"fs";import{resolve as Dn}from"path";import{existsSync as Cu}from"fs";class ma{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(!xo(e))return!0;return To(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=xo(r)?To(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class pa{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),s}catch(s){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Eu(e,t){this[e]=vu.bind(null,t)}class Xn{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 Qn{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 Au(e,t={}){let r=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return r?`${e}:${r}`:e}function $u(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function xu(e){return e.getStats().size*2}function es(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)=>vi(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!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]=es(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)=>vi(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 vi(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!vi(e[r],t[r]))return!1;return!0}if(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(!vi(e[i],t[i]))return!1}return!0}return!1}function Ee(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Tu(e,t){if(!da(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 es(t,n)}catch{return null}}catch{return null}}async function Pu({name:e="",cwd:t,defaultConfig:r}){let n=t||Gn.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=yi(n,`${o}${a}`),f=await Tu(c,r);if(f!==null)return f}try{let o=yi(n,"package.json");if(da(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return es(r,a)}catch{}}}catch{}return r}function Ru(e,t={}){let r=gi.cwd();while(r.includes("storage"))r=Mo(r,"..");let n=Mo(r,e||"");if(t?.relative)return Gf(gi.cwd(),n);return n}async function Ou(){try{let e=await Pu({name:"clarity",defaultConfig:ui,cwd:gi.cwd(),endpoint:"",headers:{}});return{...ui,...e}}catch{return ui}}function xe(){if(gt.env.NODE_ENV==="test"||gt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ku(){if(gt.env.NODE_ENV==="test"||gt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof gt<"u"){let e=gt.type;if(e==="renderer"||e==="worker")return!1;return!!(gt.versions&&(gt.versions.node||gt.versions.bun))}return!1}class ya{async format(e){let t=await ku(),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 Ei{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={..._n},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new ya,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Be.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...hi,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...hi};return{...hi,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:_n.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 Kf(this.config.logDirectory,No.F_OK|No.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Hf(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:At.from(e);try{if(!Sn(this.currentLogFile))await An(this.currentLogFile,"",{mode:420});if(n=Fo(this.currentLogFile,"a",420),Uf(n,a,{flag:"a"}),Io(n),n!==void 0)bn(n),n=void 0;if((await zt(this.currentLogFile)).size===0){if(await An(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{bn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===s-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}i++;let c=o*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Jt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Jt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Jt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(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 En(16).toString("hex")}generateKey(){return En(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=En(16),n=jf("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=Wo(),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 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 Yr(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 Lo(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await Zr(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 An(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await zt(r).catch(()=>null))await Lo(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await Yr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await Zr(Jt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Do(e),n=Vf(t),i=Wo();await zf(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Sn(this.currentLogFile))try{let e=Fo(this.currentLogFile,"r+");Io(e),bn(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!xe()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Yr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Zr(Jt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?Ce.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,a=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let c=Be.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${i}`;else if(s==="info"||s==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${Ce.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=Ta[e],u=this.options.showTags!==!1&&this.name?Ce.gray(this.formatTag(this.name)):"",l;switch(e){case"debug":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:Ce.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:Ce.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(`
|
|
77
|
+
`);for(let d of g)if(d.trim()&&!d.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:Ce.gray(` ${d}`),level:e,showTimestamp:!1}))}break}}else if(!xe()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),a)console.error(a)}if(!this.shouldLog(e))return;let c=`${s} ${this.environment}.${e.toUpperCase()}: ${o}
|
|
78
78
|
`;if(a)c+=`${a}
|
|
79
|
-
`;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(e){let t=performance.now();if(this.fancy
|
|
80
|
-
`,c=c.replace(this.ANSI_PATTERN,""),this.fancy
|
|
81
|
-
`),o=Math.max(...s.map((u)=>u.length))+2,a=`\u250C${"\u2500".repeat(o)}\u2510`,c=`\u2514${"\u2500".repeat(o)}\u2518`,f=s.map((u)=>{let l=" ".repeat(o-u.length-2);return`\u2502 ${u}${l} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:
|
|
82
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(
|
|
83
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(e,t=""){if(!this.enabled||!this.fancy
|
|
84
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||$e()||!Be.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if($e()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Yr(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let i=Jt(this.config.logDirectory,n);if(e.before)try{if((await zt(i)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${i}:`,s);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Zr(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function fi(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&de(t[0])&&"id"in t[0]&&t[0].id===3&&de(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(de(t)&&de(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(de(e)&&"arr"in e&&Array.isArray(e.arr)&&de(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&de(t[0])&&de(e[0])){let n=[...t];for(let i of e)if(de(i)&&"name"in i){if(!n.find((s)=>de(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(de(i)&&"path"in i){if(!n.find((s)=>de(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(!de(t)||!de(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(de(i)&&de(r[n]))r[n]=fi(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&de(i[0])&&de(r[n][0])){let s=[...i];for(let o of r[n])if(de(o)&&"name"in o){if(!s.find((a)=>de(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(de(o)&&"path"in o){if(!s.find((a)=>de(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 ts(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:fi(e,t);if(Array.isArray(e))return r==="replace"?t:fi(e,t);if(!de(t)||!de(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]=fi(o,s);else if(de(s)&&de(o))n[i]=ts(o,s,r);else n[i]=s}return n}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(de(e)&&de(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 de(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function li(e,t,r="replace"){if(!ha(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 ts(t,i,r)}catch{return null}}catch{return null}}function Mu(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(),d=`${n}_${l.map(g).join("_")}`,v=`${n}_${l.map((b)=>b.toUpperCase()).join("_")}`;if(r)je.info(`Checking environment variable ${d} for config ${e}.${l.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))c[f]=s(u,l);else{let b=yr.env[d]||yr.env[v];if(b!==void 0){if(r)je.info(`Using environment variable ${b?d: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 C=JSON.parse(b);if(Array.isArray(C))c[f]=C;else c[f]=b.split(",").map((T)=>T.trim())}catch{c[f]=b.split(",").map((C)=>C.trim())}else c[f]=b}}}return c}return s(i)}async function Du({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)?Mu(e,i,s):i,f=r||yr.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)je.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${f}`);let l=[e,`.${e}`].filter(Boolean),g=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],v=t?[`${t}.config`,`.${t}.config`]:[],b=Array.from(new Set([f,Ue(f,"config"),Ue(f,".config"),n?Ue(f,n):void 0].filter(Boolean)));for(let C of b){if(s)je.info(`Searching for configuration in: ${C}`);let T=[Ue(f,"config"),Ue(f,".config")].concat(n?[Ue(f,n)]:[]).includes(C)?[...l,...g,...d,...v]:[...g,...l,...v,...d];for(let k of T)for(let O of u){let I=Ue(C,`${k}${O}`),j=await li(I,c,a);if(j!==null){if(s)je.success(`Configuration loaded from: ${I}`);return j}}}if(e){let C=Ue(vn(),".config",e),T=["config",`${e}.config`];if(t)T.push(`${t}.config`);if(s)je.info(`Checking user config directory: ${C}`);for(let k of T)for(let O of u){let I=Ue(C,`${k}${O}`),j=await li(I,c,a);if(j!==null){if(s)je.success(`Configuration loaded from user config directory: ${I}`);return j}}}if(e){let C=Ue(vn(),".config"),T=[`.${e}.config`];if(t)T.push(`.${t}.config`);if(s)je.info(`Checking user config directory for dotfile configs: ${C}`);for(let k of T)for(let O of u){let I=Ue(C,`${k}${O}`),j=await li(I,c,a);if(j!==null){if(s)je.success(`Configuration loaded from user config directory dotfile: ${I}`);return j}}}if(e){let C=vn(),T=[`.${e}.config`,`.${e}`];if(t)T.push(`.${t}.config`),T.push(`.${t}`);if(s)je.info(`Checking user home directory for dotfile configs: ${C}`);for(let k of T)for(let O of u){let I=Ue(C,`${k}${O}`),j=await li(I,c,a);if(j!==null){if(s)je.success(`Configuration loaded from user home directory: ${I}`);return j}}}try{let C=Ue(f,"package.json");if(ha(C)){let T=await import(C),k=T[e];if(!k&&t){if(k=T[t],k&&s)je.success(`Using alias "${t}" configuration from package.json`)}if(k&&typeof k==="object"&&!Array.isArray(k))try{if(s)je.success(`Configuration loaded from package.json: ${k===T[e]?e:t}`);return ts(c,k,a)}catch(O){if(s)je.warn("Failed to merge package.json config:",O)}}}catch(C){if(s)je.warn("Failed to load package.json:",C)}if(s)je.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function Iu(e,t={}){let r=pi.cwd();while(r.includes("storage"))r=ko(r,"..");let n=ko(r,e||"");if(t?.relative)return Wf(pi.cwd(),n);return n}async function Fu(){try{let e=await Du({name:"clarity",alias:"logging",defaultConfig:di,cwd:pi.cwd()});return{...di,...e||{}}}catch{return di}}function Ie(){if(yt.env.NODE_ENV==="test"||yt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Nu(){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 Ca{async format(e){let t=await Nu(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Xt.pid,hostname:t(),environment:Xt.env.NODE_ENV||"development",platform:Xt.platform,version:Xt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Xt.env.NODE_ENV||Xt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Si{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={...Vn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ca,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??ue.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},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{...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:Vn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Ie()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,i=0,s=3,o=1000;while(i<s)try{try{try{await Xf(this.config.logDirectory,_o.F_OK|_o.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Qf(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:dt.from(e);try{if(!Xr(this.currentLogFile))await Tn(this.currentLogFile,"",{mode:420});if(n=jo(this.currentLogFile,"a",420),Zf(n,a,{flag:"a"}),Go(n),n!==void 0)xn(n),n=void 0;if((await Yt(this.currentLogFile)).size===0){if(await Tn(this.currentLogFile,a,{flag:"w",mode:420}),(await Yt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(i<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let l=o*2**i;await new Promise((g)=>setTimeout(g,l)),i++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(n!==void 0)try{xn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===s-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}i++;let c=o*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Zt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Zt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Zt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Ie())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,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 $n(16).toString("hex")}generateKey(){return $n(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=$n(16),n=Jf("aes-256-gcm",t,r),i=dt.isBuffer(e)?e:dt.from(e,"utf8"),s=n.update(i),o=n.final(),a=s.length+o.length,c=n.getAuthTag(),f=dt.allocUnsafe(16+a+16);return r.copy(f,0),s.copy(f,16),o.copy(f,16+s.length),c.copy(f,16+a),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Uo(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(dt.from(dt.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Ie())return;if(!this.shouldWriteToFile())return;let e=await Yt(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Qr(this.config.logDirectory),s=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${o}`;if(await Yt(r).catch(()=>null))try{if(await Vo(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await ei(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 Tn(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await Yt(r).catch(()=>null))await Vo(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await Qr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await ei(Zt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Bo(e),n=Yf(t),i=Uo();await ru(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()})),Xr(this.currentLogFile))try{let e=jo(this.currentLogFile,"r+");Go(e),xn(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Ie()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Qr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await ei(Zt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?te.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Ie())return!1;let e=typeof ue.env.NO_COLOR<"u",t=ue.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof ue.stderr<"u"&&ue.stderr.isTTY||typeof ue.stdout<"u"&&ue.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,a=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let c=ue.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${i}`;else if(s==="info"||s==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${te.cyan(i)}`;if(!o)return f.trim();let u=a(f).trim().length,l=a(t).length,g=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(g)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let a=Number.parseInt(o,10);return a<t[0].length?String(t[0][a]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let a=t[n++];switch(o){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=te.underline(te.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(o)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${a}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>te.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>te.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>te.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>te.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>te.strikethrough(n)),t}supportsHyperlinks(){if(Ie())return!1;let e=ue.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=ue.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(eu(t)||t.startsWith("./")||t.startsWith("../"))t=tu(t);else return null;return Xr(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?"":Ra[e],g=this.options.showTags!==!1&&this.name?te.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:te.gray(c),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:te.green(c),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.error(d),a){let v=a.split(`
|
|
79
|
+
`;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(e){let t=performance.now();if(this.fancy&&!xe()){let r=this.options.showTags!==!1&&this.name?Ce.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:Ce.blue("\u25D0"),tag:r,message:`${Ce.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,a=this.formatConsoleTimestamp(o),c=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
|
|
80
|
+
`,c=c.replace(this.ANSI_PATTERN,""),this.fancy&&!xe()){let f=this.options.showTags!==!1&&this.name?Ce.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:Ce.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!xe())console.error(c.trim());await this.writeToFile(c)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Ei(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(xe())throw Error("createReadStream is not supported in browser environments");if(!Sn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Do(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=At.isBuffer(e)?e:At.from(e,"base64"),i=n.slice(0,16),s=n.slice(-16),o=n.slice(16,-16),a=_f("aes-256-gcm",r,i);return a.setAuthTag(s),At.concat([a.update(o),a.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return xe()}isServerMode(){return!xe()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!xe()){let s=e.split(`
|
|
81
|
+
`),o=Math.max(...s.map((u)=>u.length))+2,a=`\u250C${"\u2500".repeat(o)}\u2510`,c=`\u2514${"\u2500".repeat(o)}\u2518`,f=s.map((u)=>{let l=" ".repeat(o-u.length-2);return`\u2502 ${u}${l} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:Ce.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:Ce.cyan(a)})),f.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:Ce.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:Ce.cyan(c),showTimestamp:!1}))}else if(!xe())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let i=`${n} ${this.environment}.INFO: [BOX] ${e}
|
|
82
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(xe())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${Ce.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();Be.stdin.removeListener("data",r);try{if(typeof Be.stdin.setRawMode==="function")Be.stdin.setRawMode(!1)}catch{}Be.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof Be.stdin.setRawMode==="function")Be.stdin.setRawMode(!0)}catch{}Be.stdin.resume(),Be.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let i=/%([sdijfo%])/g,s=0;if(r=e.replace(i,(o,a)=>{if(a==="%")return"%";if(s>=t.length)return o;let c=t[s++];switch(a){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return o}}),s<t.length)r+=` ${t.slice(s).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`}if(this.fancy&&!xe()){let i=this.options.showTags!==!1&&this.name?Ce.gray(this.formatTag(this.name)):"",s=Ce.blue("\u25D0");console.error(`${s} ${i} ${Ce.cyan(r)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
83
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(e,t=""){if(!this.enabled||!this.fancy||xe()||e<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(n,i)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||xe())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,n)),i!==void 0)this.activeProgressBar.message=i;let s=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,s)},finish:(n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||xe())return;if(this.activeProgressBar.current=this.activeProgressBar.total,n!==void 0)this.activeProgressBar.message=n;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(n,i="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||xe())return;Be.stdout.write(`${"\r".padEnd(Be.stdout.columns||80)}\r`),this.log(i,n),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||xe()||!Be.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=Ce.green("\u2501".repeat(n)),o=Ce.gray("\u2501".repeat(i)),a=`[${s}${o}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=t||r===100?Ce.green("\u2713"):Ce.blue("\u25B6"),l=this.options.showTags!==!1&&this.name?` ${Ce.gray(this.formatTag(this.name))}`:"",g=`\r${u}${l} ${a} ${c}${f}`,d=Be.stdout.columns||80,v=" ".repeat(Math.max(0,d-g.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${g}${v}`,Be.stdout.write(e.lastRenderedLine),t)Be.stdout.write(`
|
|
84
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||xe()||!Be.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(xe()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Yr(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let i=Jt(this.config.logDirectory,n);if(e.before)try{if((await zt(i)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${i}:`,s);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Zr(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function fi(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&de(t[0])&&"id"in t[0]&&t[0].id===3&&de(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(de(t)&&de(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(de(e)&&"arr"in e&&Array.isArray(e.arr)&&de(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&de(t[0])&&de(e[0])){let n=[...t];for(let i of e)if(de(i)&&"name"in i){if(!n.find((s)=>de(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(de(i)&&"path"in i){if(!n.find((s)=>de(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(!de(t)||!de(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(de(i)&&de(r[n]))r[n]=fi(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&de(i[0])&&de(r[n][0])){let s=[...i];for(let o of r[n])if(de(o)&&"name"in o){if(!s.find((a)=>de(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(de(o)&&"path"in o){if(!s.find((a)=>de(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 ts(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:fi(e,t);if(Array.isArray(e))return r==="replace"?t:fi(e,t);if(!de(t)||!de(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]=fi(o,s);else if(de(s)&&de(o))n[i]=ts(o,s,r);else n[i]=s}return n}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(de(e)&&de(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 de(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function li(e,t,r="replace"){if(!ha(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 ts(t,i,r)}catch{return null}}catch{return null}}function Mu(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(),d=`${n}_${l.map(g).join("_")}`,v=`${n}_${l.map((b)=>b.toUpperCase()).join("_")}`;if(r)je.info(`Checking environment variable ${d} for config ${e}.${l.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))c[f]=s(u,l);else{let b=yr.env[d]||yr.env[v];if(b!==void 0){if(r)je.info(`Using environment variable ${b?d: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 C=JSON.parse(b);if(Array.isArray(C))c[f]=C;else c[f]=b.split(",").map((T)=>T.trim())}catch{c[f]=b.split(",").map((C)=>C.trim())}else c[f]=b}}}return c}return s(i)}async function Du({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)?Mu(e,i,s):i,f=r||yr.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)je.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${f}`);let l=[e,`.${e}`].filter(Boolean),g=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],v=t?[`${t}.config`,`.${t}.config`]:[],b=Array.from(new Set([f,Ue(f,"config"),Ue(f,".config"),n?Ue(f,n):void 0].filter(Boolean)));for(let C of b){if(s)je.info(`Searching for configuration in: ${C}`);let T=[Ue(f,"config"),Ue(f,".config")].concat(n?[Ue(f,n)]:[]).includes(C)?[...l,...g,...d,...v]:[...g,...l,...v,...d];for(let k of T)for(let R of u){let I=Ue(C,`${k}${R}`),_=await li(I,c,a);if(_!==null){if(s)je.success(`Configuration loaded from: ${I}`);return _}}}if(e){let C=Ue(vn(),".config",e),T=["config",`${e}.config`];if(t)T.push(`${t}.config`);if(s)je.info(`Checking user config directory: ${C}`);for(let k of T)for(let R of u){let I=Ue(C,`${k}${R}`),_=await li(I,c,a);if(_!==null){if(s)je.success(`Configuration loaded from user config directory: ${I}`);return _}}}if(e){let C=Ue(vn(),".config"),T=[`.${e}.config`];if(t)T.push(`.${t}.config`);if(s)je.info(`Checking user config directory for dotfile configs: ${C}`);for(let k of T)for(let R of u){let I=Ue(C,`${k}${R}`),_=await li(I,c,a);if(_!==null){if(s)je.success(`Configuration loaded from user config directory dotfile: ${I}`);return _}}}if(e){let C=vn(),T=[`.${e}.config`,`.${e}`];if(t)T.push(`.${t}.config`),T.push(`.${t}`);if(s)je.info(`Checking user home directory for dotfile configs: ${C}`);for(let k of T)for(let R of u){let I=Ue(C,`${k}${R}`),_=await li(I,c,a);if(_!==null){if(s)je.success(`Configuration loaded from user home directory: ${I}`);return _}}}try{let C=Ue(f,"package.json");if(ha(C)){let T=await import(C),k=T[e];if(!k&&t){if(k=T[t],k&&s)je.success(`Using alias "${t}" configuration from package.json`)}if(k&&typeof k==="object"&&!Array.isArray(k))try{if(s)je.success(`Configuration loaded from package.json: ${k===T[e]?e:t}`);return ts(c,k,a)}catch(R){if(s)je.warn("Failed to merge package.json config:",R)}}}catch(C){if(s)je.warn("Failed to load package.json:",C)}if(s)je.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function Iu(e,t={}){let r=pi.cwd();while(r.includes("storage"))r=ko(r,"..");let n=ko(r,e||"");if(t?.relative)return Wf(pi.cwd(),n);return n}async function Fu(){try{let e=await Du({name:"clarity",alias:"logging",defaultConfig:di,cwd:pi.cwd()});return{...di,...e||{}}}catch{return di}}function Ie(){if(yt.env.NODE_ENV==="test"||yt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Nu(){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 Ca{async format(e){let t=await Nu(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Xt.pid,hostname:t(),environment:Xt.env.NODE_ENV||"development",platform:Xt.platform,version:Xt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Xt.env.NODE_ENV||Xt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Si{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={...Vn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ca,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??ue.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},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{...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:Vn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Ie()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,i=0,s=3,o=1000;while(i<s)try{try{try{await Xf(this.config.logDirectory,_o.F_OK|_o.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Qf(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:dt.from(e);try{if(!Xr(this.currentLogFile))await Tn(this.currentLogFile,"",{mode:420});if(n=jo(this.currentLogFile,"a",420),Zf(n,a,{flag:"a"}),Go(n),n!==void 0)xn(n),n=void 0;if((await Yt(this.currentLogFile)).size===0){if(await Tn(this.currentLogFile,a,{flag:"w",mode:420}),(await Yt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(i<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let l=o*2**i;await new Promise((g)=>setTimeout(g,l)),i++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(n!==void 0)try{xn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(i===s-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}i++;let c=o*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Zt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Zt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Zt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Ie())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,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 $n(16).toString("hex")}generateKey(){return $n(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=$n(16),n=Jf("aes-256-gcm",t,r),i=dt.isBuffer(e)?e:dt.from(e,"utf8"),s=n.update(i),o=n.final(),a=s.length+o.length,c=n.getAuthTag(),f=dt.allocUnsafe(16+a+16);return r.copy(f,0),s.copy(f,16),o.copy(f,16+s.length),c.copy(f,16+a),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Uo(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(dt.from(dt.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Ie())return;if(!this.shouldWriteToFile())return;let e=await Yt(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Qr(this.config.logDirectory),s=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${o}`;if(await Yt(r).catch(()=>null))try{if(await Vo(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await ei(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 Tn(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await Yt(r).catch(()=>null))await Vo(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await Qr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await ei(Zt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Bo(e),n=Yf(t),i=Uo();await ru(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()})),Xr(this.currentLogFile))try{let e=jo(this.currentLogFile,"r+");Go(e),xn(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Ie()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Qr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await ei(Zt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?te.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Ie())return!1;let e=typeof ue.env.NO_COLOR<"u",t=ue.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof ue.stderr<"u"&&ue.stderr.isTTY||typeof ue.stdout<"u"&&ue.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,a=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let c=ue.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${i}`;else if(s==="info"||s==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${te.cyan(i)}`;if(!o)return f.trim();let u=a(f).trim().length,l=a(t).length,g=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(g)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let a=Number.parseInt(o,10);return a<t[0].length?String(t[0][a]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let a=t[n++];switch(o){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=te.underline(te.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(o)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${a}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>te.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>te.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>te.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>te.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>te.strikethrough(n)),t}supportsHyperlinks(){if(Ie())return!1;let e=ue.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=ue.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(eu(t)||t.startsWith("./")||t.startsWith("../"))t=tu(t);else return null;return Xr(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?"":Pa[e],g=this.options.showTags!==!1&&this.name?te.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:te.gray(c),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:te.green(c),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.error(d),a){let v=a.split(`
|
|
85
85
|
`);for(let b of v)if(b.trim()&&!b.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:te.gray(` ${b}`),level:e,showTimestamp:!1}))}break}}else if(!Ie()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),a)console.error(a)}if(!this.shouldLog(e))return;let u=`${s} ${this.environment}.${e.toUpperCase()}: ${f}
|
|
86
86
|
`;if(a)u+=`${a}
|
|
87
87
|
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(i,s)=>{},finish:(i)=>{},interrupt:(i,s)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!Ie()&&ue.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(i,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,i),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!Ie()&&ue.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,s="info")=>{if(!Ie()&&ue.stdout.isTTY)ue.stdout.write(`
|
|
@@ -90,7 +90,7 @@ ${Hr}/
|
|
|
90
90
|
`),c=Math.max(...a.map((g)=>g.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,l=a.map((g)=>this.formatConsoleMessage({timestamp:r,message:te.cyan(g),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:te.cyan(f),showTimestamp:!1})),l.forEach((g)=>console.error(g)),console.error(this.formatConsoleMessage({timestamp:r,message:te.cyan(u),showTimestamp:!1}))}else if(!Ie())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
|
|
91
91
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(Ie())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${te.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();ue.stdin.removeListener("data",r);try{if(typeof ue.stdin.setRawMode==="function")ue.stdin.setRawMode(!1)}catch{}ue.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof ue.stdin.setRawMode==="function")ue.stdin.setRawMode(!0)}catch{}ue.stdin.resume(),ue.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,a=0;if(r=e.replace(o,(c,f)=>{if(f==="%")return"%";if(a>=t.length)return c;let u=t[a++];switch(f){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return c}}),a<t.length)r+=` ${t.slice(a).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?te.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${te.blue("\u25D0")} `;console.error(`${a}${o} ${te.cyan(n)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
92
92
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!ue.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=te.green("\u2501".repeat(n)),o=te.gray("\u2501".repeat(i)),a=`[${s}${o}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?te.green("\u2713"):te.blue("\u25B6"),l=this.options.showTags!==!1&&this.name?` ${te.gray(this.formatTag(this.name))}`:"",g=`\r${u}${l} ${a} ${c}${f}`,d=ue.stdout.columns||80,v=" ".repeat(Math.max(0,d-g.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${g}${v}`,ue.stdout.write(e.lastRenderedLine),t)ue.stdout.write(`
|
|
93
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ie()||!ue.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Ie()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Qr(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let i=Zt(this.config.logDirectory,n);if(e.before)try{if((await Yt(i)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${i}:`,s);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await ei(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function wa(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let a=0;a<=r;a++)try{return await e()}catch(c){if(o=c instanceof Error?c:Error(String(c)),a===r||!i(o))break;if(n>0)await new Promise((f)=>setTimeout(f,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function va(e){return e instanceof Ye}function Lu(e){return e instanceof Ai}function Wu(e){if(va(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((t)=>e.message.toLowerCase().includes(t.toLowerCase()))}class
|
|
93
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ie()||!ue.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Ie()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Qr(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let i=Zt(this.config.logDirectory,n);if(e.before)try{if((await Yt(i)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${i}:`,s);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await ei(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function wa(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let a=0;a<=r;a++)try{return await e()}catch(c){if(o=c instanceof Error?c:Error(String(c)),a===r||!i(o))break;if(n>0)await new Promise((f)=>setTimeout(f,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function va(e){return e instanceof Ye}function Lu(e){return e instanceof Ai}function Wu(e){if(va(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((t)=>e.message.toLowerCase().includes(t.toLowerCase()))}class Oi{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:a=!1,trackPerformance:c=!0}=r,f=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),l={...t};return this.processObject(l,[],u,{useCamelCase:i,useBackwardCompatibility:s,customParsers:o,verbose:a,configName:e}),{config:l,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return vr.track("applyEnvironmentVariables",f,{configName:e});return f()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],a=o.map((u)=>this.formatEnvKey(u,n.useCamelCase)),c=`${r}_${a.join("_")}`,f=n.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,n);else{let u=ti.env[c]||(f?ti.env[f]:void 0);if(u!==void 0){if(n.verbose){let l=ti.env[c]?c:f}try{e[i]=this.parseEnvironmentValue(u,typeof s,c,n.customParsers,n.configName)}catch(l){if(l instanceof $i)throw l;throw $t.envVar(c,u,typeof s,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[s,o]of Object.entries(n))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw $t.envVar(r,e,`${t} (via ${s.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(ti.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,s=n||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),i){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],a=`${r}_${o.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,n);else n.push({key:a,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
94
94
|
|
|
95
95
|
`;for(let n of e)r+=`${n.key}
|
|
96
96
|
`,r+=` Type: ${n.type}
|
|
@@ -102,16 +102,16 @@ ${Hr}/
|
|
|
102
102
|
`;r+=`| Variable | Type | Description | Example |
|
|
103
103
|
`,r+=`|----------|------|-------------|----------|
|
|
104
104
|
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
105
|
-
`;return r}}function Bu(e,t){let r=$a("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function Ea(e,t,r={}){return ba(e,t,r,new WeakMap)}function ba(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 Sa(e,t,i,n);if(!rt(t)||!rt(e))return t;return Vu(e,t,r,n)}function Sa(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 Gu(e,t);case"smart":return ju(e,t,n);default:return t}return t}function Gu(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>jn(i,n)))r.push(n);return r}function ju(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(rt(t[0])&&rt(e[0]))return _u(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 _u(e,t,r){let n=[...t];for(let i of e){if(!rt(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)=>rt(c)&&(a in c)&&c[a]===i[a])){o=!0;break}}if(!o)n.push(i)}return n}function Vu(e,t,r,n){let i=t;if(rt(i)&&n.has(i))return n.get(i);let s={...e};if(rt(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(rt(a)&&rt(c))s[o]=ba(c,a,r,n);else if(Array.isArray(a)||Array.isArray(c))s[o]=Sa(c,a,r.arrayMergeMode||"smart",n);else s[o]=a}return s}function rs(e,t,r="replace"){return Ea(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function jn(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!jn(e[r],t[r]))return!1;return!0}if(rt(e)&&rt(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!jn(e[i],t[i]))return!1}return!0}return!1}function rt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class ki{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=rr.getWithFileCheck("file",e);if(f){if(a)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!ri(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,g="default"in u,d=Object.keys(u).length>0;if(!g&&!d)throw new Cr(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new Cr(e,Error("Configuration must export a valid object"),"unknown");let v={config:rs(t,l,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)rr.setWithFileCheck("file",v,e,s);return v}catch(f){throw f instanceof Error?$t.configLoad(e,f):$t.configLoad(e,Error(String(f)))}};if(o)return vr.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(Rn(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 wa(async()=>ri(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!ri(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=Rn(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=Rn(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(!ri(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 is{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:a=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],g={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,g);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],g);else return this.validateWithJSONSchema(e,t,g)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(a)return await vr.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!iu(t))throw new wr(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 wr(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:Pa},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class ns{fileLoader=new ki;envProcessor=new Pi;validator=new is;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)st.warn(`Slow configuration loading detected: ${c.duration}ms for ${o.name}`);a.metrics=c}return a}catch(a){let c=Date.now()-t;throw st.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||kt.cwd(),g=[],d=await this.loadLocalConfiguration(n,i,l,o,a,f,u,c,r);if(d)return g.push(...this.getLocalSearchPaths(n,i,l,o)),this.finalizeResult(d,g,c,n,u);let 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(Ke(l,"package.json")),this.finalizeResult(b,g,c,n,u);if(g.push(...this.getAllSearchPaths(n,i,l,o)),t)throw $t.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?gr(e,i,o):i,u=this.getLocalDirectories(r,n);for(let l of u){if(o)st.info(`Searching for configuration in: ${l}`);let g=this.fileLoader.generateConfigPaths(e,l,t),d=await this.fileLoader.tryLoadFromPaths(g,f,{arrayStrategy:s,verbose:o,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(d){if(o)st.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?gr(e,r,i):r,a=[Ke(Ht(),".config",e),Ke(Ht(),".config"),Ht()];for(let c of a){if(i)st.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)st.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?gr(e,n,s):n;try{let c=Ke(r,"package.json");if(!Bn(c))return null;let f=await import(c),u=f[e],l=e;if(!u&&t)u=f[t],l=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)st.success(`Configuration loaded from package.json: ${l}`);return{config:rs(a,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)st.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:gr(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 $t.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return rr.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);rr.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,Ke(e,"config"),Ke(e,".config"),t?Ke(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(Ke(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=[Ke(Ht(),".config",e),Ke(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 Qo(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 Uu(e){return wt.loadConfig({...e,__strictErrorHandling:!0})}async function Aa(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await wt.loadConfig(e);else n=await wt.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",s=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||s.includes("config"))&&e.verbose)st.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let o=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await wt.applyEnvironmentVariables(o.name||"",t,!0,o.verbose||!1))?.config??t;return t}}async function Ku(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await wt.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Qo(r)))return(await wt.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await wt.loadConfig({...e,cwd:e.cwd||kt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Qo(t)))return(await wt.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Hu(e,t,r="replace"){let n=new ki;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function gr(e,t,r=!1){let n=new Pi,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("")}`],d,v;for(let b of g)if(d=kt.env[b],d!==void 0){v=b;break}if(d!==void 0&&v)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let b=Number(d);if(!Number.isNaN(b))c[f]=b}else if(Array.isArray(u))try{c[f]=JSON.parse(d)}catch{c[f]=d.split(",").map((b)=>b.trim())}else c[f]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,l)}return c}return s(t)}function zu(e){let t=Ke(kt.cwd(),e.configDir),r=Ke(kt.cwd(),e.generatedDir),n=Ke(r,"config-types.ts");if(!Bn(Po(n)))If(Po(n),{recursive:!0,mode:511});let i=Bn(t)?Ff(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${bh}
|
|
105
|
+
`;return r}}function Bu(e,t){let r=$a("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function Ea(e,t,r={}){return ba(e,t,r,new WeakMap)}function ba(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 Sa(e,t,i,n);if(!rt(t)||!rt(e))return t;return Vu(e,t,r,n)}function Sa(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 Gu(e,t);case"smart":return ju(e,t,n);default:return t}return t}function Gu(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>jn(i,n)))r.push(n);return r}function ju(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(rt(t[0])&&rt(e[0]))return _u(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 _u(e,t,r){let n=[...t];for(let i of e){if(!rt(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)=>rt(c)&&(a in c)&&c[a]===i[a])){o=!0;break}}if(!o)n.push(i)}return n}function Vu(e,t,r,n){let i=t;if(rt(i)&&n.has(i))return n.get(i);let s={...e};if(rt(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(rt(a)&&rt(c))s[o]=ba(c,a,r,n);else if(Array.isArray(a)||Array.isArray(c))s[o]=Sa(c,a,r.arrayMergeMode||"smart",n);else s[o]=a}return s}function rs(e,t,r="replace"){return Ea(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function jn(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!jn(e[r],t[r]))return!1;return!0}if(rt(e)&&rt(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!jn(e[i],t[i]))return!1}return!0}return!1}function rt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class ki{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=rr.getWithFileCheck("file",e);if(f){if(a)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!ri(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,g="default"in u,d=Object.keys(u).length>0;if(!g&&!d)throw new Cr(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new Cr(e,Error("Configuration must export a valid object"),"unknown");let v={config:rs(t,l,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)rr.setWithFileCheck("file",v,e,s);return v}catch(f){throw f instanceof Error?$t.configLoad(e,f):$t.configLoad(e,Error(String(f)))}};if(o)return vr.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(Pn(t,`${s}${o}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return wa(async()=>ri(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!ri(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let a=Pn(e,`${s}${o}`);if(await this.checkFileAccess(a))n.push(a)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let a=Pn(e,o);if(await this.checkFileAccess(a))n.push(a)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!ri(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 is{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:a=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],g={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,g);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],g);else return this.validateWithJSONSchema(e,t,g)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(a)return await vr.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!iu(t))throw new wr(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 wr(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:Oa},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class ns{fileLoader=new ki;envProcessor=new Oi;validator=new is;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)st.warn(`Slow configuration loading detected: ${c.duration}ms for ${o.name}`);a.metrics=c}return a}catch(a){let c=Date.now()-t;throw st.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||kt.cwd(),g=[],d=await this.loadLocalConfiguration(n,i,l,o,a,f,u,c,r);if(d)return g.push(...this.getLocalSearchPaths(n,i,l,o)),this.finalizeResult(d,g,c,n,u);let 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(Ke(l,"package.json")),this.finalizeResult(b,g,c,n,u);if(g.push(...this.getAllSearchPaths(n,i,l,o)),t)throw $t.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?gr(e,i,o):i,u=this.getLocalDirectories(r,n);for(let l of u){if(o)st.info(`Searching for configuration in: ${l}`);let g=this.fileLoader.generateConfigPaths(e,l,t),d=await this.fileLoader.tryLoadFromPaths(g,f,{arrayStrategy:s,verbose:o,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(d){if(o)st.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?gr(e,r,i):r,a=[Ke(Ht(),".config",e),Ke(Ht(),".config"),Ht()];for(let c of a){if(i)st.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)st.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?gr(e,n,s):n;try{let c=Ke(r,"package.json");if(!Bn(c))return null;let f=await import(c),u=f[e],l=e;if(!u&&t)u=f[t],l=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)st.success(`Configuration loaded from package.json: ${l}`);return{config:rs(a,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)st.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:gr(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 $t.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return rr.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);rr.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,Ke(e,"config"),Ke(e,".config"),t?Ke(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(Ke(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=[Ke(Ht(),".config",e),Ke(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 Qo(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 Uu(e){return wt.loadConfig({...e,__strictErrorHandling:!0})}async function Aa(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await wt.loadConfig(e);else n=await wt.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",s=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||s.includes("config"))&&e.verbose)st.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let o=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await wt.applyEnvironmentVariables(o.name||"",t,!0,o.verbose||!1))?.config??t;return t}}async function Ku(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await wt.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Qo(r)))return(await wt.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await wt.loadConfig({...e,cwd:e.cwd||kt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Qo(t)))return(await wt.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Hu(e,t,r="replace"){let n=new ki;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function gr(e,t,r=!1){let n=new Oi,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("")}`],d,v;for(let b of g)if(d=kt.env[b],d!==void 0){v=b;break}if(d!==void 0&&v)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let b=Number(d);if(!Number.isNaN(b))c[f]=b}else if(Array.isArray(u))try{c[f]=JSON.parse(d)}catch{c[f]=d.split(",").map((b)=>b.trim())}else c[f]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,l)}return c}return s(t)}function zu(e){let t=Ke(kt.cwd(),e.configDir),r=Ke(kt.cwd(),e.generatedDir),n=Ke(r,"config-types.ts");if(!Bn(Oo(n)))If(Oo(n),{recursive:!0,mode:511});let i=Bn(t)?Ff(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${bh}
|
|
106
106
|
export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
|
|
107
|
-
`;Nf(n,s,{mode:438})}function Ju(e){let t=null,r=null,n=()=>{if(!r)r=Aa(e).then((s)=>(t=s,s),(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)st.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return o});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(s,o){if(t)return t[o];let a=i[o];return n(),a},has(s,o){return o in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(s,o){return Object.getOwnPropertyDescriptor(t||i,o)},set(s,o,a){if(!t)t={...i};return t[o]=a,!0}})}function qu(e){let t=Ko(ou.cwd(),e?.configDir||"./config");function r(){if(!nu(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=su(t).filter((c)=>i.has(
|
|
107
|
+
`;Nf(n,s,{mode:438})}function Ju(e){let t=null,r=null,n=()=>{if(!r)r=Aa(e).then((s)=>(t=s,s),(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)st.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return o});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(s,o){if(t)return t[o];let a=i[o];return n(),a},has(s,o){return o in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(s,o){return Object.getOwnPropertyDescriptor(t||i,o)},set(s,o,a){if(!t)t={...i};return t[o]=a,!0}})}function qu(e){let t=Ko(ou.cwd(),e?.configDir||"./config");function r(){if(!nu(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=su(t).filter((c)=>i.has(Rn(c))).map((c)=>({base:c.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:c})),a=new Map;for(let{base:c,file:f}of o){let u=Rn(f).toLowerCase(),l=a.get(c);if(!l){a.set(c,f);continue}let g=Rn(l).toLowerCase();if(s.indexOf(u)<s.indexOf(g))a.set(c,f)}return Array.from(a.entries()).map(([c,f])=>({base:c,file:f})).sort((c,f)=>c.base.localeCompare(f.base))}function n(){let i=r(),s=i.map((c)=>c.base),o=s.length?s.map((c)=>`'${c}'`).join(" | "):"string",a=i.length?`{
|
|
108
108
|
${i.map((c)=>{let f=Ko(t,c.file).replace(/\\/g,"/");return` '${c.base}': typeof import('${f}').default`}).join(`,
|
|
109
109
|
`)}
|
|
110
110
|
}`:"Record<string, any>";return`export type ConfigNames = ${o}
|
|
111
111
|
export type ConfigByName = ${a}
|
|
112
112
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
113
113
|
export type ConfigOf = Config
|
|
114
|
-
`}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 Ah(e,t={}){let r=Ci.cwd();while(r.includes("storage"))r=Ho(r,"..");let n=Ho(r,e||"");if(t?.relative)return lu(Ci.cwd(),n);return n}function Ne(){if(Ct.env.NODE_ENV==="test"||Ct.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function xh(){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 Ia{async format(e){let t=await xh(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:tr.pid,hostname:t(),environment:tr.env.NODE_ENV||"development",platform:tr.platform,version:tr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:tr.env.NODE_ENV||tr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Mi{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={...xi},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ia,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??he.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Wn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Wn};return{...Wn,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:xi.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Ne()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,i=0,s=3,o=1000;while(i<s)try{try{try{await du(this.config.logDirectory,Yo.F_OK|Yo.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await mu(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(!ii(this.currentLogFile))await Mn(this.currentLogFile,"",{mode:420});if(n=qo(this.currentLogFile,"a",420),hu(n,a,{flag:"a"}),Jo(n),n!==void 0)kn(n),n=void 0;if((await Qt(this.currentLogFile)).size===0){if(await Mn(this.currentLogFile,a,{flag:"w",mode:420}),(await Qt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(i<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{kn(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 er(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return er(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return er(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Ne())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,o],[,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 Pn(16).toString("hex")}generateKey(){return Pn(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Pn(16),n=cu("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=Xo(),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(Ne())return;if(!this.shouldWriteToFile())return;let e=await Qt(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await ni(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 Qt(r).catch(()=>null))try{if(await Zo(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await si(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await Mn(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await Qt(r).catch(()=>null))await Zo(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await ni(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await si(er(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=zo(e),n=uu(t),i=Xo();await yu(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);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()})),ii(this.currentLogFile))try{let e=qo(this.currentLogFile,"r+");Jo(e),kn(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Ne()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await ni(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await si(er(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?se.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Ne())return!1;let e=typeof he.env.NO_COLOR<"u",t=he.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof he.stderr<"u"&&he.stderr.isTTY||typeof he.stdout<"u"&&he.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,a=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let c=he.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${i}`;else if(s==="info"||s==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${se.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=se.underline(se.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)=>se.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>se.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>se.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>se.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>se.strikethrough(n)),t}supportsHyperlinks(){if(Ne())return!1;let e=he.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=he.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(pu(t)||t.startsWith("./")||t.startsWith("../"))t=gu(t);else return null;return ii(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?"":kh[e],g=this.options.showTags!==!1&&this.name?se.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:se.gray(c),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:se.green(c),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.error(d),a){let v=a.split(`
|
|
114
|
+
`}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 Ah(e,t={}){let r=Ci.cwd();while(r.includes("storage"))r=Ho(r,"..");let n=Ho(r,e||"");if(t?.relative)return lu(Ci.cwd(),n);return n}function Ne(){if(Ct.env.NODE_ENV==="test"||Ct.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function xh(){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 Ia{async format(e){let t=await xh(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:tr.pid,hostname:t(),environment:tr.env.NODE_ENV||"development",platform:tr.platform,version:tr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:tr.env.NODE_ENV||tr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Mi{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={...xi},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ia,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??he.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Wn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Wn};return{...Wn,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:xi.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Ne()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,i=0,s=3,o=1000;while(i<s)try{try{try{await du(this.config.logDirectory,Yo.F_OK|Yo.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await mu(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(!ii(this.currentLogFile))await Mn(this.currentLogFile,"",{mode:420});if(n=qo(this.currentLogFile,"a",420),hu(n,a,{flag:"a"}),Jo(n),n!==void 0)kn(n),n=void 0;if((await Qt(this.currentLogFile)).size===0){if(await Mn(this.currentLogFile,a,{flag:"w",mode:420}),(await Qt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(i<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{kn(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 er(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return er(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return er(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Ne())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,o],[,a])=>a.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,i);if(n.length>s)for(let[o]of n.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return On(16).toString("hex")}generateKey(){return On(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=On(16),n=cu("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=Xo(),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(Ne())return;if(!this.shouldWriteToFile())return;let e=await Qt(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await ni(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 Qt(r).catch(()=>null))try{if(await Zo(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await si(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await Mn(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await Qt(r).catch(()=>null))await Zo(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await ni(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await si(er(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=zo(e),n=uu(t),i=Xo();await yu(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);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()})),ii(this.currentLogFile))try{let e=qo(this.currentLogFile,"r+");Jo(e),kn(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Ne()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await ni(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await si(er(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?se.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Ne())return!1;let e=typeof he.env.NO_COLOR<"u",t=he.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof he.stderr<"u"&&he.stderr.isTTY||typeof he.stdout<"u"&&he.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,a=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let c=he.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${i}`;else if(s==="info"||s==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${se.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=se.underline(se.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)=>se.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>se.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>se.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>se.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>se.strikethrough(n)),t}supportsHyperlinks(){if(Ne())return!1;let e=he.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=he.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(pu(t)||t.startsWith("./")||t.startsWith("../"))t=gu(t);else return null;return ii(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?"":kh[e],g=this.options.showTags!==!1&&this.name?se.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:se.gray(c),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:se.green(c),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:l,tag:g,message:c,level:e}),console.error(d),a){let v=a.split(`
|
|
115
115
|
`);for(let b of v)if(b.trim()&&!b.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:se.gray(` ${b}`),level:e,showTimestamp:!1}))}break}}else if(!Ne()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),a)console.error(a)}let u=`${s} ${this.environment}.${e.toUpperCase()}: ${f}
|
|
116
116
|
`;if(a)u+=`${a}
|
|
117
117
|
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(i,s)=>{},finish:(i)=>{},interrupt:(i,s)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!Ne()&&he.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(i,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,i),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!Ne()&&he.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,s="info")=>{if(!Ne()&&he.stdout.isTTY)he.stdout.write(`
|
|
@@ -132,7 +132,7 @@ export type ConfigOf = Config
|
|
|
132
132
|
`;r+=`| Variable | Type | Description | Example |
|
|
133
133
|
`,r+=`|----------|------|-------------|----------|
|
|
134
134
|
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
135
|
-
`;return r}}function Dh(e,t,r={}){return Va(e,t,r,new WeakMap)}function Va(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let a=o(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return Ua(e,t,i,n);if(!it(t)||!it(e))return t;return Lh(e,t,r,n)}function Ua(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return Ih(e,t);case"smart":return Fh(e,t,n);default:return t}return t}function Ih(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Yn(i,n)))r.push(n);return r}function Fh(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(it(t[0])&&it(e[0]))return Nh(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function Nh(e,t,r){let n=[...t];for(let i of e){if(!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 Lh(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]=Va(c,a,r,n);else if(Array.isArray(a)||Array.isArray(c))s[o]=Ua(c,a,r.arrayMergeMode||"smart",n);else s[o]=a}return s}function Ka(e,t,r="replace"){return Dh(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Yn(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(!Yn(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(!Yn(e[i],t[i]))return!1}return!0}return!1}function it(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Ha{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=wi.getWithFileCheck("file",e);if(f){if(a)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!ai(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,g="default"in u,d=Object.keys(u).length>0;if(!g&&!d)throw new Ti(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new Ti(e,Error("Configuration must export a valid object"),"unknown");let v={config:Ka(t,l,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)wi.setWithFileCheck("file",v,e,s);return v}catch(f){throw f instanceof Error?ir.configLoad(e,f):ir.configLoad(e,Error(String(f)))}};if(o)return Zn.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(Dn(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 Mh(async()=>ai(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!ai(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=Dn(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=Dn(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(!ai(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 za{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:a=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],g={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,g);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],g);else return this.validateWithJSONSchema(e,t,g)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(a)return await Zn.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!Cu(t))throw new Ri(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new Ri(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(o)){if(n.push({path:r,message:`Expected type ${a.join(" or ")}, got ${o}`,expected:a.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let a=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,a,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let a of t.required)if(!(a in o)){if(n.push({path:r?`${r}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[a,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:Wh},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function Bh(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 Ja{fileLoader=new Ha;envProcessor=new os;validator=new za;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let c=this.checkCache(o.name||"",o);if(c)return c}let a;try{a=await this.loadConfigurationStrategies(o,!0,r)}catch(c){let f=o.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),l=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),g=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(g||u))throw c;if(l&&(!f||!g))a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(i||s)await this.validateConfiguration(a.config,i,s,o.name);if(r?.enabled&&a)this.cacheResult(o.name||"",a,r,o);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)pt.warn(`Slow configuration loading detected: ${c.duration}ms for ${o.name}`);a.metrics=c}return a}catch(a){if(a instanceof Error&&a.name==="ConfigNotFoundError")throw a;let c=Date.now()-t;throw pt.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:a,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=s||Oi.cwd(),g=[],d=await this.loadLocalConfiguration(n,i,l,o,a,f,u,c,r);if(d)return g.push(...this.getLocalSearchPaths(n,i,l,o)),this.finalizeResult(d,g,c,n,u);let 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(tt(l,"package.json")),this.finalizeResult(b,g,c,n,u);if(g.push(...this.getAllSearchPaths(n,i,l,o)),t)throw ir.configNotFound(n,g,i);return{...await this.applyEnvironmentVariables(n,a,c,u),warnings:[`No configuration file found for "${n}"${Bh(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,a,c){let f=a?ci(e,i,o):i,u=this.getLocalDirectories(r,n);for(let l of u){if(o)pt.info(`Searching for configuration in: ${l}`);let g=this.fileLoader.generateConfigPaths(e,l,t),d=await this.fileLoader.tryLoadFromPaths(g,f,{arrayStrategy:s,verbose:o,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(d){if(o)pt.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?ci(e,r,i):r,a=[tt(Kt(),".config",e),tt(Kt(),".config"),Kt()];for(let c of a){if(i)pt.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,o,{arrayStrategy:n,verbose:i});if(u){if(i)pt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let a=o?ci(e,n,s):n;try{let c=tt(r,"package.json");if(!Mf(c))return null;let f={};try{f=JSON.parse(Df(c,"utf8"))}catch(g){if(s)pt.warn("Failed to parse package.json:",[g instanceof Error?g:Error(String(g))]);return null}let u=f[e],l=e;if(!u&&t){let g=Array.isArray(t)?t:[t];for(let d of g){if(!d)continue;if(f[d]){u=f[d],l=d;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)pt.success(`Configuration loaded from package.json: ${l}`);return{config:Ka(a,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)pt.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:ci(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 ir.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return wi.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);wi.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,tt(e,"config"),tt(e,".config"),t?tt(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(tt(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=[tt(Kt(),".config",e),tt(Kt(),".config"),Kt()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function ci(e,t,r=!1){let n=new os,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("")}`],d,v;for(let b of g)if(d=Oi.env[b],d!==void 0){v=b;break}if(d!==void 0&&v)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let b=Number(d);if(!Number.isNaN(b))c[f]=b}else if(Array.isArray(u))try{c[f]=JSON.parse(d)}catch{c[f]=d.split(",").map((b)=>b.trim())}else c[f]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,l)}return c}return s(t)}var wi,Zn,wu,vu=(e)=>e,bu=(e,t)=>{for(var r in t)wu(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Eu.bind(t,r)})},Su=(e,t)=>()=>(e&&(t=e(e=0)),t),ga,$a,rr,vr,xa,Yu,Zu,ea,ui,_n,Ge,ye,Xu,ta,Qu,ra,eh,th,In,rh,ia,na,Fn,ih,nh,sh,oh,hi,Ta,ah,je,lh,ch,sa,di,Vn,Fe,te,fh,oa,uh,aa,hh,dh,Nn,mh,la,ca,ph,Ln,gh,yh,Ch,wh,vh,mi,Ra,Eh,bh="0.15.6",Ye,Ai,Cr,Un,Kn,$i,Hn,zn,wr,Jn,qn,$t,Oa,Pa,st,wt,ka,Ma,Sh,$h,Da,xi,Ng,Fa,se,Lg,Th,Wg,Rh,Bg,Gg,fa,jg,Oh,Ph,_g,ua,Vg,Ug,Kg,Hg,zg,Wn,kh,Jg,ot,Na,Ti,La,Wa,ss,Ba,Ga,Ri,ja,_a,ir,Wh,pt,qg,Yg,Zg,Gh,qa;var Ya=ce(()=>{wi=new ma,Zn=new pa,wu=Object.defineProperty;ga={};bu(ga,{withErrorRecovery:()=>wa,tryLoadConfig:()=>Hu,loadConfigWithResult:()=>Uu,loadConfig:()=>Aa,isRetryableError:()=>Wu,isConfigNotFoundError:()=>Lu,isBunfigError:()=>va,globalPerformanceMonitor:()=>vr,globalCache:()=>rr,getEnvOrDefault:()=>Bu,generateConfigTypes:()=>zu,defaultGeneratedDir:()=>Ma,defaultConfigDir:()=>ka,deepMergeWithArrayStrategy:()=>rs,deepMerge:()=>Ea,createLibraryConfig:()=>Ju,config:()=>Ku,bunfigPlugin:()=>qu,applyEnvVarsToConfig:()=>gr,TypeGenerationError:()=>zn,SchemaValidationError:()=>wr,PluginError:()=>qn,PerformanceMonitor:()=>Qn,FileSystemError:()=>Hn,ErrorFactory:()=>$t,EnvVarError:()=>$i,EnvProcessor:()=>Pi,ConfigValidator:()=>is,ConfigValidationError:()=>Un,ConfigNotFoundError:()=>Ai,ConfigMergeError:()=>Kn,ConfigLoader:()=>ns,ConfigLoadError:()=>Cr,ConfigFileLoader:()=>ki,ConfigCache:()=>Xn,CacheUtils:()=>xa,BunfigError:()=>Ye,BrowserConfigError:()=>Jn,ArrayMergeStrategies:()=>Oa});Sh=Su(async()=>{$a=import.meta.require,rr=new Xn,vr=new Qn,xa={createKey:Au,isEquivalent:$u,estimateMemoryUsage:xu},Yu=yi(Gn.cwd(),"config"),Zu=yi(Gn.cwd(),"src/generated"),ea=gi.env.CLARITY_LOG_DIR||Bf(Ou(),"logs"),ui={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ea,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},_n=await Pu(),Ge={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},ye=Ge,Xu=Ge.red,ta=Ge.green,Qu=Ge.yellow,ra=Ge.blue,eh=Ge.magenta,th=Ge.cyan,In=Ge.white,rh=Ge.gray,ia=Ge.bgRed,na=Ge.bgYellow,Fn=Ge.bold,ih=Ge.dim,nh=Ge.italic,sh=Ge.underline,oh=Ge.reset,hi={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ta={debug:"\uD83D\uDD0D",info:ra("\u2139"),success:ta("\u2713"),warning:na(In(Fn(" WARN "))),error:ia(In(Fn(" ERROR ")))},ah=new Ei("stacks"),je=new Ei("bunfig",{showTags:!0}),lh=Ue(yr.cwd(),"config"),ch=Ue(yr.cwd(),"src/generated"),sa=pi.env.CLARITY_LOG_DIR||Lf(Iu(),"logs"),di={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:sa,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Vn=await Fu(),Fe={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},te=Fe,fh=Fe.red,oa=Fe.green,uh=Fe.yellow,aa=Fe.blue,hh=Fe.magenta,dh=Fe.cyan,Nn=Fe.white,mh=Fe.gray,la=Fe.bgRed,ca=Fe.bgYellow,ph=Fe.bgGray,Ln=Fe.bold,gh=Fe.dim,yh=Fe.italic,Ch=Fe.underline,wh=Fe.strikethrough,vh=Fe.reset,mi={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ra={debug:"\uD83D\uDD0D",info:aa("\u2139"),success:oa("\u2713"),warning:ca(Nn(Ln(" WARN "))),error:la(Nn(Ln(" ERROR ")))},Eh=new Si("stacks"),Ye=class extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},Ai=class extends Ye{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r?` or alias "${r}"`:"";super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},Cr=class extends Ye{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},Un=class extends Ye{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Kn=class extends Ye{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},$i=class extends Ye{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}},Hn=class extends Ye{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},zn=class extends Ye{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},wr=class extends Ye{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Jn=class extends Ye{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}},qn=class extends Ye{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},$t={configNotFound(e,t,r){return new Ai(e,t,r)},configLoad(e,t,r){return new Cr(e,t,r)},configValidation(e,t,r){return new Un(e,t,r)},configMerge(e,t,r,n){return new Kn(e,t,r,n)},envVar(e,t,r,n){return new $i(e,t,r,n)},fileSystem(e,t,r){return new Hn(e,t,r)},typeGeneration(e,t,r){return new zn(e,t,r)},schemaValidation(e,t,r){return new wr(e,t,r)},browserConfig(e,t,r,n){return new Jn(e,t,r,n)},plugin(e,t,r){return new qn(e,t,r)}},Oa={replace:"replace",concat:"concat",smart:"smart"},Pa=/^https?:\/\//,st=new Si("bunfig",{showTags:!0}),wt=new ns,ka=Ke(kt.cwd(),"config"),Ma=Ke(kt.cwd(),"src/generated")});$h=Ci.env.CLARITY_LOG_DIR||au(Ah(),"logs"),Da={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:$h,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},xi={...Da},Ng=(async()=>{try{let{loadConfig:e}=await Sh().then(()=>ga),t=await e({name:"clarity",alias:"logging",defaultConfig:Da,cwd:Ci.cwd()});if(t)Object.assign(xi,t)}catch{}return xi})();Fa={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"},se=Fa,{red:Lg,green:Th,yellow:Wg,blue:Rh,magenta:Bg,cyan:Gg,white:fa,gray:jg,bgRed:Oh,bgYellow:Ph,bgGray:_g,bold:ua,dim:Vg,italic:Ug,underline:Kg,strikethrough:Hg,reset:zg}=Fa,Wn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},kh={debug:"\uD83D\uDD0D",info:Rh("\u2139"),success:Th("\u2713"),warning:Ph(fa(ua(" WARN "))),error:Oh(fa(ua(" ERROR ")))};Jg=new Mi("stacks");ot=class ot extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}};Na=class Na extends ot{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],i="";if(n.length===1)i=` or alias "${n[0]}"`;else if(n.length>1)i=` or aliases ${n.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}};Ti=class Ti extends ot{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}};La=class La extends ot{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};Wa=class Wa extends ot{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}};ss=class ss extends ot{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}};Ba=class Ba extends ot{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}};Ga=class Ga extends ot{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}};Ri=class Ri extends ot{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}};ja=class ja extends ot{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}};_a=class _a extends ot{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}};ir={configNotFound(e,t,r){return new Na(e,t,r)},configLoad(e,t,r){return new Ti(e,t,r)},configValidation(e,t,r){return new La(e,t,r)},configMerge(e,t,r,n){return new Wa(e,t,r,n)},envVar(e,t,r,n){return new ss(e,t,r,n)},fileSystem(e,t,r){return new Ba(e,t,r)},typeGeneration(e,t,r){return new Ga(e,t,r)},schemaValidation(e,t,r){return new Ri(e,t,r)},browserConfig(e,t,r,n){return new ja(e,t,r,n)},plugin(e,t,r){return new _a(e,t,r)}};Wh=/^https?:\/\//;pt=new Mi("bunfig",{showTags:!0});qg=new Ja;Yg=tt(Oi.cwd(),"config"),Zg=tt(Oi.cwd(),"src/generated"),Gh={cwd:kf.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},qa=Gh});function Za(e,t,r){let n={file:t,message:"Unknown error",code:Er.UNKNOWN_ERROR};if(e instanceof Error){n.message=e.message,n.stack=e.stack;let i=e.message.match(/\((\d+),(\d+)\)/);if(i)n.location={line:Number.parseInt(i[1],10),column:Number.parseInt(i[2],10)};if(e.message.includes("Cannot find")||e.message.includes("not found"))n.code=Er.FILE_NOT_FOUND,n.suggestion="Check that the file path is correct and the file exists.";else if(e.message.includes("syntax")||e.message.includes("Unexpected token"))n.code=Er.SYNTAX_ERROR,n.suggestion="Check for syntax errors in your TypeScript code.";else if(e.message.includes("type")&&e.message.includes("cannot"))n.code=Er.TYPE_INFERENCE_ERROR,n.suggestion="Add explicit type annotations to help with type inference.";else if(e.message.includes("parse")||e.message.includes("Parse"))n.code=Er.PARSE_ERROR,n.suggestion="The file contains invalid TypeScript syntax."}else if(typeof e==="string")n.message=e;return n}function Xa(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(`
|
|
135
|
+
`;return r}}function Dh(e,t,r={}){return Va(e,t,r,new WeakMap)}function Va(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let a=o(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return Ua(e,t,i,n);if(!it(t)||!it(e))return t;return Lh(e,t,r,n)}function Ua(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return Ih(e,t);case"smart":return Fh(e,t,n);default:return t}return t}function Ih(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Yn(i,n)))r.push(n);return r}function Fh(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(it(t[0])&&it(e[0]))return Nh(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function Nh(e,t,r){let n=[...t];for(let i of e){if(!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 Lh(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]=Va(c,a,r,n);else if(Array.isArray(a)||Array.isArray(c))s[o]=Ua(c,a,r.arrayMergeMode||"smart",n);else s[o]=a}return s}function Ka(e,t,r="replace"){return Dh(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Yn(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(!Yn(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(!Yn(e[i],t[i]))return!1}return!0}return!1}function it(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Ha{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=wi.getWithFileCheck("file",e);if(f){if(a)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!ai(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,g="default"in u,d=Object.keys(u).length>0;if(!g&&!d)throw new Ti(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new Ti(e,Error("Configuration must export a valid object"),"unknown");let v={config:Ka(t,l,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)wi.setWithFileCheck("file",v,e,s);return v}catch(f){throw f instanceof Error?ir.configLoad(e,f):ir.configLoad(e,Error(String(f)))}};if(o)return Zn.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(Dn(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 Mh(async()=>ai(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!ai(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=Dn(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=Dn(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(!ai(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 za{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:a=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],g={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,g);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],g);else return this.validateWithJSONSchema(e,t,g)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(a)return await Zn.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!Cu(t))throw new Pi(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new Pi(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let 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:Wh},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function Bh(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 Ja{fileLoader=new Ha;envProcessor=new os;validator=new za;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let c=this.checkCache(o.name||"",o);if(c)return c}let a;try{a=await this.loadConfigurationStrategies(o,!0,r)}catch(c){let f=o.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),l=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),g=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(g||u))throw c;if(l&&(!f||!g))a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(i||s)await this.validateConfiguration(a.config,i,s,o.name);if(r?.enabled&&a)this.cacheResult(o.name||"",a,r,o);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)pt.warn(`Slow configuration loading detected: ${c.duration}ms for ${o.name}`);a.metrics=c}return a}catch(a){if(a instanceof Error&&a.name==="ConfigNotFoundError")throw a;let c=Date.now()-t;throw pt.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:a,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=s||Ri.cwd(),g=[],d=await this.loadLocalConfiguration(n,i,l,o,a,f,u,c,r);if(d)return g.push(...this.getLocalSearchPaths(n,i,l,o)),this.finalizeResult(d,g,c,n,u);let 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(tt(l,"package.json")),this.finalizeResult(b,g,c,n,u);if(g.push(...this.getAllSearchPaths(n,i,l,o)),t)throw ir.configNotFound(n,g,i);return{...await this.applyEnvironmentVariables(n,a,c,u),warnings:[`No configuration file found for "${n}"${Bh(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,a,c){let f=a?ci(e,i,o):i,u=this.getLocalDirectories(r,n);for(let l of u){if(o)pt.info(`Searching for configuration in: ${l}`);let g=this.fileLoader.generateConfigPaths(e,l,t),d=await this.fileLoader.tryLoadFromPaths(g,f,{arrayStrategy:s,verbose:o,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(d){if(o)pt.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?ci(e,r,i):r,a=[tt(Kt(),".config",e),tt(Kt(),".config"),Kt()];for(let c of a){if(i)pt.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,o,{arrayStrategy:n,verbose:i});if(u){if(i)pt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let a=o?ci(e,n,s):n;try{let c=tt(r,"package.json");if(!Mf(c))return null;let f={};try{f=JSON.parse(Df(c,"utf8"))}catch(g){if(s)pt.warn("Failed to parse package.json:",[g instanceof Error?g:Error(String(g))]);return null}let u=f[e],l=e;if(!u&&t){let g=Array.isArray(t)?t:[t];for(let d of g){if(!d)continue;if(f[d]){u=f[d],l=d;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)pt.success(`Configuration loaded from package.json: ${l}`);return{config:Ka(a,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)pt.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:ci(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 ir.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return wi.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);wi.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,tt(e,"config"),tt(e,".config"),t?tt(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(tt(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=[tt(Kt(),".config",e),tt(Kt(),".config"),Kt()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function ci(e,t,r=!1){let n=new os,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("")}`],d,v;for(let b of g)if(d=Ri.env[b],d!==void 0){v=b;break}if(d!==void 0&&v)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let b=Number(d);if(!Number.isNaN(b))c[f]=b}else if(Array.isArray(u))try{c[f]=JSON.parse(d)}catch{c[f]=d.split(",").map((b)=>b.trim())}else c[f]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,l)}return c}return s(t)}var wi,Zn,wu,vu=(e)=>e,bu=(e,t)=>{for(var r in t)wu(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Eu.bind(t,r)})},Su=(e,t)=>()=>(e&&(t=e(e=0)),t),ga,$a,rr,vr,xa,Yu,Zu,ea,ui,_n,Ge,Ce,Xu,ta,Qu,ra,eh,th,In,rh,ia,na,Fn,ih,nh,sh,oh,hi,Ta,ah,je,lh,ch,sa,di,Vn,Fe,te,fh,oa,uh,aa,hh,dh,Nn,mh,la,ca,ph,Ln,gh,yh,Ch,wh,vh,mi,Pa,Eh,bh="0.15.6",Ye,Ai,Cr,Un,Kn,$i,Hn,zn,wr,Jn,qn,$t,Ra,Oa,st,wt,ka,Ma,Sh,$h,Da,xi,Ng,Fa,se,Lg,Th,Wg,Ph,Bg,Gg,fa,jg,Rh,Oh,_g,ua,Vg,Ug,Kg,Hg,zg,Wn,kh,Jg,ot,Na,Ti,La,Wa,ss,Ba,Ga,Pi,ja,_a,ir,Wh,pt,qg,Yg,Zg,Gh,qa;var Ya=ce(()=>{wi=new ma,Zn=new pa,wu=Object.defineProperty;ga={};bu(ga,{withErrorRecovery:()=>wa,tryLoadConfig:()=>Hu,loadConfigWithResult:()=>Uu,loadConfig:()=>Aa,isRetryableError:()=>Wu,isConfigNotFoundError:()=>Lu,isBunfigError:()=>va,globalPerformanceMonitor:()=>vr,globalCache:()=>rr,getEnvOrDefault:()=>Bu,generateConfigTypes:()=>zu,defaultGeneratedDir:()=>Ma,defaultConfigDir:()=>ka,deepMergeWithArrayStrategy:()=>rs,deepMerge:()=>Ea,createLibraryConfig:()=>Ju,config:()=>Ku,bunfigPlugin:()=>qu,applyEnvVarsToConfig:()=>gr,TypeGenerationError:()=>zn,SchemaValidationError:()=>wr,PluginError:()=>qn,PerformanceMonitor:()=>Qn,FileSystemError:()=>Hn,ErrorFactory:()=>$t,EnvVarError:()=>$i,EnvProcessor:()=>Oi,ConfigValidator:()=>is,ConfigValidationError:()=>Un,ConfigNotFoundError:()=>Ai,ConfigMergeError:()=>Kn,ConfigLoader:()=>ns,ConfigLoadError:()=>Cr,ConfigFileLoader:()=>ki,ConfigCache:()=>Xn,CacheUtils:()=>xa,BunfigError:()=>Ye,BrowserConfigError:()=>Jn,ArrayMergeStrategies:()=>Ra});Sh=Su(async()=>{$a=import.meta.require,rr=new Xn,vr=new Qn,xa={createKey:Au,isEquivalent:$u,estimateMemoryUsage:xu},Yu=yi(Gn.cwd(),"config"),Zu=yi(Gn.cwd(),"src/generated"),ea=gi.env.CLARITY_LOG_DIR||Bf(Ru(),"logs"),ui={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ea,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},_n=await Ou(),Ge={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},Ce=Ge,Xu=Ge.red,ta=Ge.green,Qu=Ge.yellow,ra=Ge.blue,eh=Ge.magenta,th=Ge.cyan,In=Ge.white,rh=Ge.gray,ia=Ge.bgRed,na=Ge.bgYellow,Fn=Ge.bold,ih=Ge.dim,nh=Ge.italic,sh=Ge.underline,oh=Ge.reset,hi={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ta={debug:"\uD83D\uDD0D",info:ra("\u2139"),success:ta("\u2713"),warning:na(In(Fn(" WARN "))),error:ia(In(Fn(" ERROR ")))},ah=new Ei("stacks"),je=new Ei("bunfig",{showTags:!0}),lh=Ue(yr.cwd(),"config"),ch=Ue(yr.cwd(),"src/generated"),sa=pi.env.CLARITY_LOG_DIR||Lf(Iu(),"logs"),di={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:sa,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Vn=await Fu(),Fe={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},te=Fe,fh=Fe.red,oa=Fe.green,uh=Fe.yellow,aa=Fe.blue,hh=Fe.magenta,dh=Fe.cyan,Nn=Fe.white,mh=Fe.gray,la=Fe.bgRed,ca=Fe.bgYellow,ph=Fe.bgGray,Ln=Fe.bold,gh=Fe.dim,yh=Fe.italic,Ch=Fe.underline,wh=Fe.strikethrough,vh=Fe.reset,mi={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Pa={debug:"\uD83D\uDD0D",info:aa("\u2139"),success:oa("\u2713"),warning:ca(Nn(Ln(" WARN "))),error:la(Nn(Ln(" ERROR ")))},Eh=new Si("stacks"),Ye=class extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},Ai=class extends Ye{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r?` or alias "${r}"`:"";super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},Cr=class extends Ye{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},Un=class extends Ye{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Kn=class extends Ye{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},$i=class extends Ye{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}},Hn=class extends Ye{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},zn=class extends Ye{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},wr=class extends Ye{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Jn=class extends Ye{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}},qn=class extends Ye{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},$t={configNotFound(e,t,r){return new Ai(e,t,r)},configLoad(e,t,r){return new Cr(e,t,r)},configValidation(e,t,r){return new Un(e,t,r)},configMerge(e,t,r,n){return new Kn(e,t,r,n)},envVar(e,t,r,n){return new $i(e,t,r,n)},fileSystem(e,t,r){return new Hn(e,t,r)},typeGeneration(e,t,r){return new zn(e,t,r)},schemaValidation(e,t,r){return new wr(e,t,r)},browserConfig(e,t,r,n){return new Jn(e,t,r,n)},plugin(e,t,r){return new qn(e,t,r)}},Ra={replace:"replace",concat:"concat",smart:"smart"},Oa=/^https?:\/\//,st=new Si("bunfig",{showTags:!0}),wt=new ns,ka=Ke(kt.cwd(),"config"),Ma=Ke(kt.cwd(),"src/generated")});$h=Ci.env.CLARITY_LOG_DIR||au(Ah(),"logs"),Da={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:$h,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},xi={...Da},Ng=(async()=>{try{let{loadConfig:e}=await Sh().then(()=>ga),t=await e({name:"clarity",alias:"logging",defaultConfig:Da,cwd:Ci.cwd()});if(t)Object.assign(xi,t)}catch{}return xi})();Fa={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"},se=Fa,{red:Lg,green:Th,yellow:Wg,blue:Ph,magenta:Bg,cyan:Gg,white:fa,gray:jg,bgRed:Rh,bgYellow:Oh,bgGray:_g,bold:ua,dim:Vg,italic:Ug,underline:Kg,strikethrough:Hg,reset:zg}=Fa,Wn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},kh={debug:"\uD83D\uDD0D",info:Ph("\u2139"),success:Th("\u2713"),warning:Oh(fa(ua(" WARN "))),error:Rh(fa(ua(" ERROR ")))};Jg=new Mi("stacks");ot=class ot extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}};Na=class Na extends ot{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],i="";if(n.length===1)i=` or alias "${n[0]}"`;else if(n.length>1)i=` or aliases ${n.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}};Ti=class Ti extends ot{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}};La=class La extends ot{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};Wa=class Wa extends ot{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}};ss=class ss extends ot{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}};Ba=class Ba extends ot{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}};Ga=class Ga extends ot{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}};Pi=class Pi extends ot{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}};ja=class ja extends ot{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}};_a=class _a extends ot{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}};ir={configNotFound(e,t,r){return new Na(e,t,r)},configLoad(e,t,r){return new Ti(e,t,r)},configValidation(e,t,r){return new La(e,t,r)},configMerge(e,t,r,n){return new Wa(e,t,r,n)},envVar(e,t,r,n){return new ss(e,t,r,n)},fileSystem(e,t,r){return new Ba(e,t,r)},typeGeneration(e,t,r){return new Ga(e,t,r)},schemaValidation(e,t,r){return new Pi(e,t,r)},browserConfig(e,t,r,n){return new ja(e,t,r,n)},plugin(e,t,r){return new _a(e,t,r)}};Wh=/^https?:\/\//;pt=new Mi("bunfig",{showTags:!0});qg=new Ja;Yg=tt(Ri.cwd(),"config"),Zg=tt(Ri.cwd(),"src/generated"),Gh={cwd:kf.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},qa=Gh});function Za(e,t,r){let n={file:t,message:"Unknown error",code:Er.UNKNOWN_ERROR};if(e instanceof Error){n.message=e.message,n.stack=e.stack;let i=e.message.match(/\((\d+),(\d+)\)/);if(i)n.location={line:Number.parseInt(i[1],10),column:Number.parseInt(i[2],10)};if(e.message.includes("Cannot find")||e.message.includes("not found"))n.code=Er.FILE_NOT_FOUND,n.suggestion="Check that the file path is correct and the file exists.";else if(e.message.includes("syntax")||e.message.includes("Unexpected token"))n.code=Er.SYNTAX_ERROR,n.suggestion="Check for syntax errors in your TypeScript code.";else if(e.message.includes("type")&&e.message.includes("cannot"))n.code=Er.TYPE_INFERENCE_ERROR,n.suggestion="Add explicit type annotations to help with type inference.";else if(e.message.includes("parse")||e.message.includes("Parse"))n.code=Er.PARSE_ERROR,n.suggestion="The file contains invalid TypeScript syntax."}else if(typeof e==="string")n.message=e;return n}function Xa(e,t){let r=[],n=e.file;if(e.location)n+=`:${e.location.line}:${e.location.column}`;if(e.code)n+=` [${e.code}]`;if(r.push(n),r.push(` Error: ${e.message}`),t&&e.location){r.push("");let i=t.split(`
|
|
136
136
|
`),s=e.location.line-1;if(s>=0&&s<i.length){let o=Math.max(0,s-1),a=Math.min(i.length-1,s+1);for(let c=o;c<=a;c++){let f=(c+1).toString().padStart(4," "),u=c===s?">":" ";if(r.push(` ${u} ${f} | ${i[c]}`),c===s&&e.location.column>0){let l=" ".repeat(10+e.location.column-1);r.push(` ${l}^`)}}}}if(e.suggestion)r.push(""),r.push(` Suggestion: ${e.suggestion}`);return r.join(`
|
|
137
137
|
`)}var Er;var Qa=ce(()=>{Er={PARSE_ERROR:"PARSE_ERROR",SYNTAX_ERROR:"SYNTAX_ERROR",FILE_NOT_FOUND:"FILE_NOT_FOUND",FILE_READ_ERROR:"FILE_READ_ERROR",FILE_WRITE_ERROR:"FILE_WRITE_ERROR",TYPE_INFERENCE_ERROR:"TYPE_INFERENCE_ERROR",UNRESOLVED_TYPE:"UNRESOLVED_TYPE",EXTRACTION_ERROR:"EXTRACTION_ERROR",PROCESSING_ERROR:"PROCESSING_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",INVALID_DECLARATION:"INVALID_DECLARATION",CONFIG_ERROR:"CONFIG_ERROR",INVALID_ENTRYPOINT:"INVALID_ENTRYPOINT",CIRCULAR_DEPENDENCY:"CIRCULAR_DEPENDENCY",TIMEOUT_ERROR:"TIMEOUT_ERROR",NOT_SUPPORTED:"NOT_SUPPORTED",UNKNOWN_ERROR:"UNKNOWN_ERROR"}});async function jh(){if(Di!==null)return Di;try{return xt=await import("prettier"),Di=!0,!0}catch{return Di=!1,!1}}async function _h(e,t){if(!xt)return null;try{if(t&&xt.resolveConfig){let r=await xt.resolveConfig(t);if(r)return r}if(e&&xt.resolveConfig){let r=await xt.resolveConfig(e);if(r)return r}return null}catch{return null}}async function Vh(e,t){if(!xt)throw Error("Prettier is not available");let r={...t,parser:t.parser||"typescript"};return xt.format(e,r)}function Uh(e,t={}){let{indentSize:r=2,useTabs:n=!1,maxLineWidth:i=100,trailingNewline:s=!0,normalizeWhitespace:o=!0,sortImports:a=!0,groupImports:c=!0}=t,f=e,u=n?"\t":" ".repeat(r);if(f.indexOf(`\r
|
|
138
138
|
`)!==-1)f=f.replace(/\r\n/g,`
|
|
@@ -163,23 +163,23 @@ export type ConfigOf = Config
|
|
|
163
163
|
`)}function md(e,t){let{groups:r=ld,separateGroups:n=!0,alphabetize:i=!0}=t,s=e.split(`
|
|
164
164
|
`),o=[],a=[],c=-1;for(let v=0;v<s.length;v++){let b=s[v],C=al(b);if(C)o.push({line:b,source:C.source,group:C.group,isType:C.isType}),c=v;else if(o.length>0&&b.trim()==="")continue;else if(o.length>0||b.trim()!==""){if(o.length===0||v>c+1)a.push(b)}}if(o.length===0)return e;let f=new Map;for(let v of r)f.set(v,[]);for(let v of o)(f.get(v.group)||f.get("external")||[]).push(v);if(i)for(let[,v]of f)v.sort((b,C)=>{if(b.isType!==C.isType)return b.isType?1:-1;return b.source.localeCompare(C.source)});let u=[],l=null;for(let v of r){let b=f.get(v)||[];if(b.length===0)continue;if(n&&l!==null)u.push("");for(let C of b)u.push(C.line);l=v}let g=s.slice(0,s.findIndex((v)=>al(v)!==null)),d=a;while(d.length>0&&d[0].trim()==="")d.shift();return[...g,...u,"",...d].join(`
|
|
165
165
|
`)}function al(e){let t=e.trim(),r=t.match(/^import\s+(type\s+)?.*from\s+['"]([^'"]+)['"]/);if(!r){let s=t.match(/^import\s+['"]([^'"]+)['"]/);if(s)return{source:s[1],group:ll(s[1]),isType:!1};return null}let n=!!r[1],i=r[2];return{source:i,group:n?"type":ll(i),isType:n}}function ll(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 pd(e,t){let{kinds:r=ad,alphabetize:n=!1,groupExports:i=!0}=t,s=e.split(`
|
|
166
|
-
`),o=[],a=[],c=[],f=null,u=0,l=!0,g=!1,d=[];for(let C=0;C<s.length;C++){let T=s[C],k=T.trim(),
|
|
166
|
+
`),o=[],a=[],c=[],f=null,u=0,l=!0,g=!1,d=[];for(let C=0;C<s.length;C++){let T=s[C],k=T.trim(),R=u,I=k.startsWith("///"),_=R===0&&!I&&(k.startsWith("//")||k.startsWith("/*"));if(g||_){if(d.push(T),!g&&k.startsWith("/*")&&!k.includes("*/"))g=!0;else if(g&&k.includes("*/"))g=!1;continue}if(R===0&&d.length>0&&k===""){d.push(T);continue}u+=(T.match(/\{/g)||[]).length,u-=(T.match(/\}/g)||[]).length;let L=gd(k);if(l&&L&&L.kind!=="import"&&!k.startsWith("//")&&!k.startsWith("/*"))l=!1;if(l){if(d.length>0){if(L?.kind==="import"||!L)a.push(...d),d.length=0}a.push(T);continue}if(L&&u<=1){if(f)o.push(f);f={lines:d.length>0?[...d,T]:[T],kind:L.kind,name:L.name,isExport:L.isExport},d.length=0}else if(f)f.lines.push(T);else{if(k==="")continue;c.push(T)}}if(f)o.push(f);if(d.length>0)c.push(...d);o.sort((C,T)=>{if(i&&C.isExport!==T.isExport)return C.isExport?-1:1;let k=r.indexOf(C.kind),R=r.indexOf(T.kind),I=k>=0?k:r.length,_=R>=0?R:r.length;if(I!==_)return I-_;if(n)return C.name.localeCompare(T.name);return 0});let v=[...a],b=null;for(let C of o){if(b!==null&&C.kind!==b)v.push("");v.push(...C.lines),b=C.kind}if(c.length>0)v.push(""),v.push(...c);return v.join(`
|
|
167
167
|
`)}function gd(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 ad,ld;var fl=ce(()=>{ad=["import","type","interface","enum","class","function","variable","export","module","namespace","unknown"],ld=["builtin","external","scoped","internal","parent","sibling","index","type"]});function Ed(e){switch(e){case"strict":return Cd;case"readonly":return wd;case"simplified":return vd;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 hl{rules;compiled=[];cache=new Map;constructor(e={rules:[]}){if(this.rules=[],e.includeDefaults!==!1)this.rules.push(...yd);if(e.presets)for(let t of e.presets)this.rules.push(...Ed(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(bd,"\\$&"),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>=ul){let o=Math.ceil(ul*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 Li(e={rules:[]}){return new hl(e)}function dl(e,t,r={}){return e.replace(/:\s*([^;,)\]}]+)/g,(n,i)=>`: ${t.map(i.trim(),r)}`)}var yd,Cd,wd,vd,bd,ul=2048,vy,Ey;var ml=ce(()=>{yd=[{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}],Cd=[{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}],wd=[{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}],vd=[{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}];bd=/[.*+?^${}()|[\]\\]/g;vy=Li({rules:[]}),Ey=Li({rules:[],presets:["strict"]})});var pl;var gl=ce(()=>{pl=new Set(["ANGLE_instanced_arrays","ARIAMixin","AacBitstreamFormat","AacEncoderConfig","AbortController","AbortSignal","AbortSignalEventMap","AbstractRange","AbstractWorker","AbstractWorkerEventMap","ActiveXObject","AddEventListenerOptions","AddressErrors","AddressType","AddressValue","AesCbcParams","AesCtrParams","AesDerivedKeyParams","AesGcmParams","AesKeyAlgorithm","AesKeyGenParams","AggregateError","AggregateErrorConstructor","Algorithm","AlgorithmIdentifier","AlignSetting","AllAcceptedCredentialsOptions","AllowSharedBufferSource","AlphaOption","AnalyserNode","AnalyserOptions","Animatable","Animation","AnimationEffect","AnimationEvent","AnimationEventInit","AnimationEventMap","AnimationFrameProvider","AnimationPlayState","AnimationPlaybackEvent","AnimationPlaybackEventInit","AnimationReplaceState","AnimationTimeline","AppendMode","Array","ArrayBuffer","ArrayBufferConstructor","ArrayBufferLike","ArrayBufferTypes","ArrayBufferView","ArrayConstructor","ArrayIterator","ArrayLike","AssignedNodesOptions","AsyncDisposable","AsyncDisposableStack","AsyncDisposableStackConstructor","AsyncGenerator","AsyncGeneratorFunction","AsyncGeneratorFunctionConstructor","AsyncIterable","AsyncIterableIterator","AsyncIterator","AsyncIteratorObject","Atomics","AttestationConveyancePreference","Attr","Audio","AudioBuffer","AudioBufferOptions","AudioBufferSourceNode","AudioBufferSourceOptions","AudioConfiguration","AudioContext","AudioContextLatencyCategory","AudioContextOptions","AudioContextState","AudioData","AudioDataCopyToOptions","AudioDataInit","AudioDataOutputCallback","AudioDecoder","AudioDecoderConfig","AudioDecoderEventMap","AudioDecoderInit","AudioDecoderSupport","AudioDestinationNode","AudioEncoder","AudioEncoderConfig","AudioEncoderEventMap","AudioEncoderInit","AudioEncoderSupport","AudioListener","AudioNode","AudioNodeOptions","AudioParam","AudioParamMap","AudioProcessingEvent","AudioProcessingEventInit","AudioSampleFormat","AudioScheduledSourceNode","AudioScheduledSourceNodeEventMap","AudioTimestamp","AudioWorklet","AudioWorkletNode","AudioWorkletNodeEventMap","AudioWorkletNodeOptions","AuthenticationExtensionsClientInputs","AuthenticationExtensionsClientInputsJSON","AuthenticationExtensionsClientOutputs","AuthenticationExtensionsClientOutputsJSON","AuthenticationExtensionsLargeBlobInputs","AuthenticationExtensionsLargeBlobInputsJSON","AuthenticationExtensionsLargeBlobOutputs","AuthenticationExtensionsLargeBlobOutputsJSON","AuthenticationExtensionsPRFInputs","AuthenticationExtensionsPRFInputsJSON","AuthenticationExtensionsPRFOutputs","AuthenticationExtensionsPRFOutputsJSON","AuthenticationExtensionsPRFValues","AuthenticationExtensionsPRFValuesJSON","AuthenticationResponseJSON","AuthenticatorAssertionResponse","AuthenticatorAssertionResponseJSON","AuthenticatorAttachment","AuthenticatorAttestationResponse","AuthenticatorAttestationResponseJSON","AuthenticatorResponse","AuthenticatorSelectionCriteria","AuthenticatorTransport","AutoFill","AutoFillAddressKind","AutoFillBase","AutoFillContactField","AutoFillContactKind","AutoFillCredentialField","AutoFillField","AutoFillNormalField","AutoFillSection","AutoKeyword","AutomationRate","AvcBitstreamFormat","AvcEncoderConfig","Awaited","BarProp","Base64URLString","BaseAudioContext","BaseAudioContextEventMap","BeforeUnloadEvent","BigInt","BigInt64Array","BigInt64ArrayConstructor","BigIntConstructor","BigIntToLocaleStringOptions","BigInteger","BigUint64Array","BigUint64ArrayConstructor","BinaryType","BiquadFilterNode","BiquadFilterOptions","BiquadFilterType","BitrateMode","Blob","BlobCallback","BlobEvent","BlobEventInit","BlobPart","BlobPropertyBag","Body","BodyInit","Boolean","BooleanConstructor","BroadcastChannel","BroadcastChannelEventMap","Buffer","BufferEncoding","BufferSource","BuiltinIteratorReturn","Bun","BunFile","ByteLengthQueuingStrategy","CDATASection","COSEAlgorithmIdentifier","CSS","CSSAnimation","CSSConditionRule","CSSContainerRule","CSSCounterStyleRule","CSSFontFaceRule","CSSFontFeatureValuesRule","CSSFontPaletteValuesRule","CSSGroupingRule","CSSImageValue","CSSImportRule","CSSKeyframeRule","CSSKeyframesRule","CSSKeywordValue","CSSKeywordish","CSSLayerBlockRule","CSSLayerStatementRule","CSSMathClamp","CSSMathInvert","CSSMathMax","CSSMathMin","CSSMathNegate","CSSMathOperator","CSSMathProduct","CSSMathSum","CSSMathValue","CSSMatrixComponent","CSSMatrixComponentOptions","CSSMediaRule","CSSNamespaceRule","CSSNestedDeclarations","CSSNumberish","CSSNumericArray","CSSNumericBaseType","CSSNumericType","CSSNumericValue","CSSPageDescriptors","CSSPageRule","CSSPerspective","CSSPerspectiveValue","CSSPositionTryDescriptors","CSSPositionTryRule","CSSPropertyRule","CSSRotate","CSSRule","CSSRuleList","CSSScale","CSSScopeRule","CSSSkew","CSSSkewX","CSSSkewY","CSSStartingStyleRule","CSSStyleDeclaration","CSSStyleDeclarationBase","CSSStyleProperties","CSSStyleRule","CSSStyleSheet","CSSStyleSheetInit","CSSStyleValue","CSSSupportsRule","CSSTransformComponent","CSSTransformValue","CSSTransition","CSSTranslate","CSSUnitValue","CSSUnparsedSegment","CSSUnparsedValue","CSSVariableReferenceValue","CSSViewTransitionRule","Cache","CacheQueryOptions","CacheStorage","CalendarLike","CallableFunction","CanPlayTypeResult","CanvasCaptureMediaStreamTrack","CanvasCompositing","CanvasDirection","CanvasDrawImage","CanvasDrawPath","CanvasFillRule","CanvasFillStrokeStyles","CanvasFilters","CanvasFontKerning","CanvasFontStretch","CanvasFontVariantCaps","CanvasGradient","CanvasImageData","CanvasImageSmoothing","CanvasImageSource","CanvasLineCap","CanvasLineJoin","CanvasPath","CanvasPathDrawingStyles","CanvasPattern","CanvasRect","CanvasRenderingContext2D","CanvasRenderingContext2DSettings","CanvasSettings","CanvasShadowStyles","CanvasState","CanvasText","CanvasTextAlign","CanvasTextBaseline","CanvasTextDrawingStyles","CanvasTextRendering","CanvasTransform","CanvasUserInterface","Capitalize","CaretPosition","CaretPositionFromPointOptions","ChannelCountMode","ChannelInterpretation","ChannelMergerNode","ChannelMergerOptions","ChannelSplitterNode","ChannelSplitterOptions","CharacterData","CheckVisibilityOptions","ChildNode","ClassAccessorDecoratorContext","ClassAccessorDecoratorResult","ClassAccessorDecoratorTarget","ClassDecorator","ClassDecoratorContext","ClassFieldDecoratorContext","ClassGetterDecoratorContext","ClassMemberDecoratorContext","ClassMethodDecoratorContext","ClassSetterDecoratorContext","Client","ClientQueryOptions","ClientRect","ClientTypes","Clients","Clipboard","ClipboardEvent","ClipboardEventInit","ClipboardItem","ClipboardItemData","ClipboardItemOptions","ClipboardItems","CloseEvent","CloseEventInit","CodecState","Collator","CollatorConstructor","CollatorOptions","ColorGamut","ColorSpaceConversion","CommandEvent","CommandEventInit","Comment","CompileError","CompositeOperation","CompositeOperationOrAuto","CompositionEvent","CompositionEventInit","CompressionFormat","CompressionStream","ComputedEffectTiming","ComputedKeyframe","ConcatArray","Console","ConstantSourceNode","ConstantSourceOptions","ConstrainBoolean","ConstrainBooleanOrDOMString","ConstrainBooleanOrDOMStringParameters","ConstrainBooleanParameters","ConstrainDOMString","ConstrainDOMStringParameters","ConstrainDouble","ConstrainDoubleRange","ConstrainULong","ConstrainULongRange","ConstructorParameters","ContentVisibilityAutoStateChangeEvent","ContentVisibilityAutoStateChangeEventInit","ConvolverNode","ConvolverOptions","CookieChangeEvent","CookieChangeEventInit","CookieInit","CookieList","CookieListItem","CookieSameSite","CookieStore","CookieStoreDeleteOptions","CookieStoreEventMap","CookieStoreGetOptions","CookieStoreManager","CountQueuingStrategy","Credential","CredentialCreationOptions","CredentialMediationRequirement","CredentialPropertiesOutput","CredentialRequestOptions","CredentialsContainer","Crypto","CryptoKey","CryptoKeyPair","CurrentUserDetailsOptions","CustomElementConstructor","CustomElementRegistry","CustomEvent","CustomEventInit","CustomStateSet","DOMException","DOMHighResTimeStamp","DOMImplementation","DOMMatrix","DOMMatrix2DInit","DOMMatrixInit","DOMMatrixReadOnly","DOMParser","DOMParserSupportedType","DOMPoint","DOMPointInit","DOMPointReadOnly","DOMQuad","DOMQuadInit","DOMRect","DOMRectInit","DOMRectList","DOMRectReadOnly","DOMStringList","DOMStringMap","DOMTokenList","DataTransfer","DataTransferItem","DataTransferItemList","DataView","DataViewConstructor","Date","DateConstructor","DateLikeObject","DateTimeFormat","DateTimeFormatConstructor","DateTimeFormatOptions","DateTimeFormatPart","DateTimeFormatPartTypes","DateTimeFormatPartTypesRegistry","DateTimeLikeObject","DateTimeRangeFormatPart","DateUnit","DecodeErrorCallback","DecodeSuccessCallback","DecompressionStream","DecoratorContext","DecoratorMetadata","DecoratorMetadataObject","DedicatedWorkerGlobalScope","DedicatedWorkerGlobalScopeEventMap","DelayNode","DelayOptions","DeviceMotionEvent","DeviceMotionEventAcceleration","DeviceMotionEventAccelerationInit","DeviceMotionEventInit","DeviceMotionEventRotationRate","DeviceMotionEventRotationRateInit","DeviceOrientationEvent","DeviceOrientationEventInit","DigitalCredential","DirectionSetting","Dirent","DisambiguationOptions","DisplayCaptureSurfaceType","DisplayMediaStreamOptions","DisplayNames","DisplayNamesFallback","DisplayNamesLanguageDisplay","DisplayNamesOptions","DisplayNamesType","Disposable","DisposableStack","DisposableStackConstructor","DistanceModelType","Document","DocumentEventMap","DocumentFragment","DocumentOrShadowRoot","DocumentReadyState","DocumentTimeline","DocumentTimelineOptions","DocumentType","DocumentVisibilityState","DoubleRange","DragEvent","DragEventInit","Duration","DurationConstructor","DurationFormat","DurationFormatDisplayOption","DurationFormatLocaleMatcher","DurationFormatOptions","DurationFormatPart","DurationFormatStyle","DurationFormatUnit","DurationFormatUnitSingular","DurationLike","DurationLikeObject","DurationRelativeToOptions","DurationRoundingOptions","DurationToStringOptions","DurationTotalOptions","DynamicsCompressorNode","DynamicsCompressorOptions","EXT_blend_minmax","EXT_color_buffer_float","EXT_color_buffer_half_float","EXT_float_blend","EXT_frag_depth","EXT_sRGB","EXT_shader_texture_lod","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","EXT_texture_norm16","EcKeyAlgorithm","EcKeyGenParams","EcKeyImportParams","EcdhKeyDeriveParams","EcdsaParams","EffectTiming","Element","ElementCSSInlineStyle","ElementContentEditable","ElementCreationOptions","ElementDefinitionOptions","ElementEventMap","ElementInternals","ElementTagNameMap","EncodedAudioChunk","EncodedAudioChunkInit","EncodedAudioChunkMetadata","EncodedAudioChunkOutputCallback","EncodedAudioChunkType","EncodedVideoChunk","EncodedVideoChunkInit","EncodedVideoChunkMetadata","EncodedVideoChunkOutputCallback","EncodedVideoChunkType","EndOfStreamError","EndingType","Enumerator","EnumeratorConstructor","EpochTimeStamp","Error","ErrorCallback","ErrorConstructor","ErrorEvent","ErrorEventInit","ErrorOptions","EvalError","EvalErrorConstructor","Event","EventCounts","EventInit","EventListener","EventListenerObject","EventListenerOptions","EventListenerOrEventListenerObject","EventModifierInit","EventSource","EventSourceEventMap","EventSourceInit","EventTarget","Exception","ExceptionOptions","Exclude","ExportValue","Exports","ExtendableCookieChangeEvent","ExtendableCookieChangeEventInit","ExtendableEvent","ExtendableEventInit","ExtendableMessageEvent","ExtendableMessageEventInit","External","Extract","FetchEvent","FetchEventInit","File","FileCallback","FileList","FilePropertyBag","FileReader","FileReaderEventMap","FileReaderSync","FileSink","FileSystem","FileSystemCreateWritableOptions","FileSystemDirectoryEntry","FileSystemDirectoryHandle","FileSystemDirectoryHandleAsyncIterator","FileSystemDirectoryReader","FileSystemEntriesCallback","FileSystemEntry","FileSystemEntryCallback","FileSystemFileEntry","FileSystemFileHandle","FileSystemFlags","FileSystemGetDirectoryOptions","FileSystemGetFileOptions","FileSystemHandle","FileSystemHandleKind","FileSystemReadWriteOptions","FileSystemRemoveOptions","FileSystemSyncAccessHandle","FileSystemWritableFileStream","FileSystemWriteChunkType","FillLightMode","FillMode","FinalizationRegistry","FinalizationRegistryConstructor","FlatArray","Float16Array","Float16ArrayConstructor","Float32Array","Float32ArrayConstructor","Float32List","Float64Array","Float64ArrayConstructor","FocusEvent","FocusEventInit","FocusOptions","FontDisplay","FontFace","FontFaceDescriptors","FontFaceLoadStatus","FontFaceSet","FontFaceSetEventMap","FontFaceSetLoadEvent","FontFaceSetLoadEventInit","FontFaceSetLoadStatus","FontFaceSource","FormData","FormDataEntryValue","FormDataEvent","FormDataEventInit","FormDataIterator","FormattableTemporalObject","FragmentDirective","FrameRequestCallback","FrameType","FullscreenNavigationUI","FullscreenOptions","Function","FunctionConstructor","FunctionStringCallback","GLbitfield","GLboolean","GLclampf","GLenum","GLfloat","GLint","GLint64","GLintptr","GLsizei","GLsizeiptr","GLuint","GLuint64","GPU","GPUAdapter","GPUAdapterInfo","GPUAddressMode","GPUAutoLayoutMode","GPUBindGroup","GPUBindGroupDescriptor","GPUBindGroupEntry","GPUBindGroupLayout","GPUBindGroupLayoutDescriptor","GPUBindGroupLayoutEntry","GPUBindingCommandsMixin","GPUBindingResource","GPUBlendComponent","GPUBlendFactor","GPUBlendOperation","GPUBlendState","GPUBuffer","GPUBufferBinding","GPUBufferBindingLayout","GPUBufferBindingType","GPUBufferDescriptor","GPUBufferDynamicOffset","GPUBufferMapState","GPUBufferUsageFlags","GPUCanvasAlphaMode","GPUCanvasConfiguration","GPUCanvasContext","GPUCanvasToneMapping","GPUCanvasToneMappingMode","GPUColor","GPUColorDict","GPUColorTargetState","GPUColorWriteFlags","GPUCommandBuffer","GPUCommandBufferDescriptor","GPUCommandEncoder","GPUCommandEncoderDescriptor","GPUCompareFunction","GPUCompilationInfo","GPUCompilationMessage","GPUCompilationMessageType","GPUComputePassDescriptor","GPUComputePassEncoder","GPUComputePassTimestampWrites","GPUComputePipeline","GPUComputePipelineDescriptor","GPUCopyExternalImageDestInfo","GPUCopyExternalImageSource","GPUCopyExternalImageSourceInfo","GPUCullMode","GPUDebugCommandsMixin","GPUDepthBias","GPUDepthStencilState","GPUDevice","GPUDeviceDescriptor","GPUDeviceEventMap","GPUDeviceLostInfo","GPUDeviceLostReason","GPUError","GPUErrorFilter","GPUExtent3D","GPUExtent3DDict","GPUExternalTexture","GPUExternalTextureBindingLayout","GPUExternalTextureDescriptor","GPUFeatureName","GPUFilterMode","GPUFlagsConstant","GPUFragmentState","GPUFrontFace","GPUIndex32","GPUIndexFormat","GPUIntegerCoordinate","GPUIntegerCoordinateOut","GPUInternalError","GPULoadOp","GPUMapModeFlags","GPUMipmapFilterMode","GPUMultisampleState","GPUObjectBase","GPUObjectDescriptorBase","GPUOrigin2D","GPUOrigin2DDict","GPUOrigin3D","GPUOrigin3DDict","GPUOutOfMemoryError","GPUPipelineBase","GPUPipelineConstantValue","GPUPipelineDescriptorBase","GPUPipelineError","GPUPipelineErrorInit","GPUPipelineErrorReason","GPUPipelineLayout","GPUPipelineLayoutDescriptor","GPUPowerPreference","GPUPrimitiveState","GPUPrimitiveTopology","GPUProgrammableStage","GPUQuerySet","GPUQuerySetDescriptor","GPUQueryType","GPUQueue","GPUQueueDescriptor","GPURenderBundle","GPURenderBundleDescriptor","GPURenderBundleEncoder","GPURenderBundleEncoderDescriptor","GPURenderCommandsMixin","GPURenderPassColorAttachment","GPURenderPassDepthStencilAttachment","GPURenderPassDescriptor","GPURenderPassEncoder","GPURenderPassLayout","GPURenderPassTimestampWrites","GPURenderPipeline","GPURenderPipelineDescriptor","GPURequestAdapterOptions","GPUSampleMask","GPUSampler","GPUSamplerBindingLayout","GPUSamplerBindingType","GPUSamplerDescriptor","GPUShaderModule","GPUShaderModuleDescriptor","GPUShaderStageFlags","GPUSignedOffset32","GPUSize32","GPUSize32Out","GPUSize64","GPUSize64Out","GPUStencilFaceState","GPUStencilOperation","GPUStencilValue","GPUStorageTextureAccess","GPUStorageTextureBindingLayout","GPUStoreOp","GPUSupportedFeatures","GPUSupportedLimits","GPUTexelCopyBufferInfo","GPUTexelCopyBufferLayout","GPUTexelCopyTextureInfo","GPUTexture","GPUTextureAspect","GPUTextureBindingLayout","GPUTextureDescriptor","GPUTextureDimension","GPUTextureFormat","GPUTextureSampleType","GPUTextureUsageFlags","GPUTextureView","GPUTextureViewDescriptor","GPUTextureViewDimension","GPUUncapturedErrorEvent","GPUUncapturedErrorEventInit","GPUValidationError","GPUVertexAttribute","GPUVertexBufferLayout","GPUVertexFormat","GPUVertexState","GPUVertexStepMode","GainNode","GainOptions","Gamepad","GamepadButton","GamepadEffectParameters","GamepadEvent","GamepadEventInit","GamepadHapticActuator","GamepadHapticEffectType","GamepadHapticsResult","GamepadMappingType","Generator","GeneratorFunction","GeneratorFunctionConstructor","GenericTransformStream","Geolocation","GeolocationCoordinates","GeolocationPosition","GeolocationPositionError","GetAnimationsOptions","GetComposedRangesOptions","GetHTMLOptions","GetNotificationOptions","GetRootNodeOptions","Global","GlobalCompositeOperation","GlobalDescriptor","GlobalEventHandlers","GlobalEventHandlersEventMap","HTMLAllCollection","HTMLAnchorElement","HTMLAreaElement","HTMLAudioElement","HTMLBRElement","HTMLBaseElement","HTMLBodyElement","HTMLBodyElementEventMap","HTMLButtonElement","HTMLCanvasElement","HTMLCollection","HTMLCollectionBase","HTMLCollectionOf","HTMLDListElement","HTMLDataElement","HTMLDataListElement","HTMLDetailsElement","HTMLDialogElement","HTMLDirectoryElement","HTMLDivElement","HTMLDocument","HTMLElement","HTMLElementDeprecatedTagNameMap","HTMLElementEventMap","HTMLElementTagNameMap","HTMLEmbedElement","HTMLFieldSetElement","HTMLFontElement","HTMLFormControlsCollection","HTMLFormElement","HTMLFrameElement","HTMLFrameSetElement","HTMLFrameSetElementEventMap","HTMLHRElement","HTMLHeadElement","HTMLHeadingElement","HTMLHtmlElement","HTMLHyperlinkElementUtils","HTMLIFrameElement","HTMLImageElement","HTMLInputElement","HTMLLIElement","HTMLLabelElement","HTMLLegendElement","HTMLLinkElement","HTMLMapElement","HTMLMarqueeElement","HTMLMediaElement","HTMLMediaElementEventMap","HTMLMenuElement","HTMLMetaElement","HTMLMeterElement","HTMLModElement","HTMLOListElement","HTMLObjectElement","HTMLOptGroupElement","HTMLOptionElement","HTMLOptionsCollection","HTMLOrSVGElement","HTMLOrSVGImageElement","HTMLOrSVGScriptElement","HTMLOutputElement","HTMLParagraphElement","HTMLParamElement","HTMLPictureElement","HTMLPreElement","HTMLProgressElement","HTMLQuoteElement","HTMLScriptElement","HTMLSelectElement","HTMLSlotElement","HTMLSourceElement","HTMLSpanElement","HTMLStyleElement","HTMLTableCaptionElement","HTMLTableCellElement","HTMLTableColElement","HTMLTableDataCellElement","HTMLTableElement","HTMLTableHeaderCellElement","HTMLTableRowElement","HTMLTableSectionElement","HTMLTemplateElement","HTMLTextAreaElement","HTMLTimeElement","HTMLTitleElement","HTMLTrackElement","HTMLUListElement","HTMLUnknownElement","HTMLVideoElement","HTMLVideoElementEventMap","HardwareAcceleration","HashAlgorithmIdentifier","HashChangeEvent","HashChangeEventInit","HdrMetadataType","Headers","HeadersInit","HeadersIterator","Highlight","HighlightRegistry","HighlightType","History","HkdfParams","HmacImportParams","HmacKeyAlgorithm","HmacKeyGenParams","IArguments","IDBCursor","IDBCursorDirection","IDBCursorWithValue","IDBDatabase","IDBDatabaseEventMap","IDBDatabaseInfo","IDBFactory","IDBIndex","IDBIndexParameters","IDBKeyRange","IDBObjectStore","IDBObjectStoreParameters","IDBOpenDBRequest","IDBOpenDBRequestEventMap","IDBRequest","IDBRequestEventMap","IDBRequestReadyState","IDBTransaction","IDBTransactionDurability","IDBTransactionEventMap","IDBTransactionMode","IDBTransactionOptions","IDBValidKey","IDBVersionChangeEvent","IDBVersionChangeEventInit","IIRFilterNode","IIRFilterOptions","ITextWriter","IdleDeadline","IdleRequestCallback","IdleRequestOptions","Image","ImageBitmap","ImageBitmapOptions","ImageBitmapRenderingContext","ImageBitmapRenderingContextSettings","ImageBitmapSource","ImageBufferSource","ImageCapture","ImageData","ImageDataArray","ImageDataPixelFormat","ImageDataSettings","ImageDecodeOptions","ImageDecodeResult","ImageDecoder","ImageDecoderInit","ImageEncodeOptions","ImageOrientation","ImageSmoothingQuality","ImageTrack","ImageTrackList","Immediate","ImportAssertions","ImportAttributes","ImportCallOptions","ImportExportKind","ImportMeta","ImportNodeOptions","ImportValue","Imports","Infinity","InputDeviceInfo","InputEvent","InputEventInit","InsertPosition","Instance","InstanceType","Instant","InstantConstructor","InstantLike","InstantToStringOptions","Int16Array","Int16ArrayConstructor","Int32Array","Int32ArrayConstructor","Int32List","Int8Array","Int8ArrayConstructor","IntersectionObserver","IntersectionObserverCallback","IntersectionObserverEntry","IntersectionObserverInit","Intl","Iterable","IterableIterator","IterationCompositeOperation","Iterator","IteratorConstructor","IteratorObject","IteratorObjectConstructor","IteratorResult","IteratorReturnResult","IteratorYieldResult","JSON","JsonWebKey","KHR_parallel_shader_compile","KeyAlgorithm","KeyFormat","KeySystemTrackConfiguration","KeyType","KeyUsage","KeyboardEvent","KeyboardEventInit","Keyframe","KeyframeAnimationOptions","KeyframeEffect","KeyframeEffectOptions","LDMLPluralRule","LargestContentfulPaint","LatencyMode","LineAlignSetting","LineAndPositionSetting","LinkError","LinkStyle","ListFormat","ListFormatLocaleMatcher","ListFormatOptions","ListFormatStyle","ListFormatType","Locale","LocaleCollationCaseFirst","LocaleHourCycleKey","LocaleOptions","LocalesArgument","Location","Lock","LockGrantedCallback","LockInfo","LockManager","LockManagerSnapshot","LockMode","LockOptions","LoginStatus","Lowercase","MIDIAccess","MIDIAccessEventMap","MIDIConnectionEvent","MIDIConnectionEventInit","MIDIInput","MIDIInputEventMap","MIDIInputMap","MIDIMessageEvent","MIDIMessageEventInit","MIDIOptions","MIDIOutput","MIDIOutputMap","MIDIPort","MIDIPortConnectionState","MIDIPortDeviceState","MIDIPortEventMap","MIDIPortType","Map","MapConstructor","MapIterator","Math","MathMLElement","MathMLElementEventMap","MathMLElementTagNameMap","MediaCapabilities","MediaCapabilitiesDecodingInfo","MediaCapabilitiesEncodingInfo","MediaCapabilitiesInfo","MediaCapabilitiesKeySystemConfiguration","MediaConfiguration","MediaDecodingConfiguration","MediaDecodingType","MediaDeviceInfo","MediaDeviceKind","MediaDevices","MediaDevicesEventMap","MediaElementAudioSourceNode","MediaElementAudioSourceOptions","MediaEncodingConfiguration","MediaEncodingType","MediaEncryptedEvent","MediaEncryptedEventInit","MediaError","MediaImage","MediaKeyMessageEvent","MediaKeyMessageEventInit","MediaKeyMessageType","MediaKeySession","MediaKeySessionClosedReason","MediaKeySessionEventMap","MediaKeySessionType","MediaKeyStatus","MediaKeyStatusMap","MediaKeyStatusMapIterator","MediaKeySystemAccess","MediaKeySystemConfiguration","MediaKeySystemMediaCapability","MediaKeys","MediaKeysPolicy","MediaKeysRequirement","MediaList","MediaMetadata","MediaMetadataInit","MediaPositionState","MediaProvider","MediaQueryList","MediaQueryListEvent","MediaQueryListEventInit","MediaQueryListEventMap","MediaRecorder","MediaRecorderEventMap","MediaRecorderOptions","MediaSession","MediaSessionAction","MediaSessionActionDetails","MediaSessionActionHandler","MediaSessionPlaybackState","MediaSettingsRange","MediaSource","MediaSourceEventMap","MediaSourceHandle","MediaStream","MediaStreamAudioDestinationNode","MediaStreamAudioSourceNode","MediaStreamAudioSourceOptions","MediaStreamConstraints","MediaStreamEventMap","MediaStreamTrack","MediaStreamTrackEvent","MediaStreamTrackEventInit","MediaStreamTrackEventMap","MediaStreamTrackProcessor","MediaStreamTrackProcessorInit","MediaStreamTrackState","MediaTrackCapabilities","MediaTrackConstraintSet","MediaTrackConstraints","MediaTrackSettings","MediaTrackSupportedConstraints","Memory","MemoryDescriptor","MessageChannel","MessageEvent","MessageEventInit","MessageEventSource","MessageEventTarget","MessageEventTargetEventMap","MessagePort","MessagePortEventMap","MethodDecorator","MimeType","MimeTypeArray","Module","ModuleExportDescriptor","ModuleImportDescriptor","ModuleImports","MouseEvent","MouseEventInit","MultiCacheQueryOptions","MutationCallback","MutationObserver","MutationObserverInit","MutationRecord","MutationRecordType","NaN","NamedCurve","NamedNodeMap","NavigateEvent","NavigateEventInit","Navigation","NavigationActivation","NavigationCurrentEntryChangeEvent","NavigationCurrentEntryChangeEventInit","NavigationDestination","NavigationEventMap","NavigationFocusReset","NavigationHistoryBehavior","NavigationHistoryEntry","NavigationHistoryEntryEventMap","NavigationInterceptHandler","NavigationInterceptOptions","NavigationNavigateOptions","NavigationOptions","NavigationPrecommitController","NavigationPrecommitHandler","NavigationPreloadManager","NavigationPreloadState","NavigationReloadOptions","NavigationResult","NavigationScrollBehavior","NavigationTimingType","NavigationTransition","NavigationType","NavigationUpdateCurrentEntryOptions","Navigator","NavigatorAutomationInformation","NavigatorBadge","NavigatorConcurrentHardware","NavigatorContentUtils","NavigatorCookies","NavigatorGPU","NavigatorID","NavigatorLanguage","NavigatorLocks","NavigatorLogin","NavigatorOnLine","NavigatorPlugins","NavigatorStorage","NewableFunction","NoInfer","Node","NodeFilter","NodeIterator","NodeJS","NodeList","NodeListOf","NodeModule","NodeRequire","NonDocumentTypeChildNode","NonElementParentNode","NonNullable","Notification","NotificationDirection","NotificationEvent","NotificationEventInit","NotificationEventMap","NotificationOptions","NotificationPermission","NotificationPermissionCallback","Now","Number","NumberConstructor","NumberFormat","NumberFormatConstructor","NumberFormatOptions","NumberFormatOptionsCurrencyDisplay","NumberFormatOptionsCurrencyDisplayRegistry","NumberFormatOptionsSignDisplay","NumberFormatOptionsSignDisplayRegistry","NumberFormatOptionsStyle","NumberFormatOptionsStyleRegistry","NumberFormatOptionsUseGrouping","NumberFormatOptionsUseGroupingRegistry","NumberFormatPart","NumberFormatPartTypeRegistry","NumberFormatPartTypes","NumberFormatRangePartTypeRegistry","NumberFormatRangePartTypes","NumberRangeFormatPart","OES_draw_buffers_indexed","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_float_linear","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","OVR_multiview2","Object","ObjectConstructor","OfflineAudioCompletionEvent","OfflineAudioCompletionEventInit","OfflineAudioContext","OfflineAudioContextEventMap","OfflineAudioContextOptions","OffscreenCanvas","OffscreenCanvasEventMap","OffscreenCanvasRenderingContext2D","OffscreenRenderingContext","OffscreenRenderingContextId","Omit","OmitThisParameter","OnBeforeUnloadEventHandler","OnBeforeUnloadEventHandlerNonNull","OnErrorEventHandler","OnErrorEventHandlerNonNull","Option","OptionalEffectTiming","OptionalPostfixToken","OptionalPrefixToken","OpusBitstreamFormat","OpusEncoderConfig","OrientationLockType","OrientationType","OscillatorNode","OscillatorOptions","OscillatorType","OverSampleType","OverconstrainedError","OverflowOptions","PageRevealEvent","PageRevealEventInit","PageSwapEvent","PageSwapEventInit","PageTransitionEvent","PageTransitionEventInit","PaintTimingMixin","PannerNode","PannerOptions","PanningModelType","ParameterDecorator","Parameters","ParentNode","Partial","PartialTemporalLike","Path2D","PayerErrors","PaymentAddress","PaymentComplete","PaymentCurrencyAmount","PaymentDetailsBase","PaymentDetailsInit","PaymentDetailsModifier","PaymentDetailsUpdate","PaymentItem","PaymentMethodChangeEvent","PaymentMethodChangeEventInit","PaymentMethodData","PaymentOptions","PaymentRequest","PaymentRequestEventMap","PaymentRequestUpdateEvent","PaymentRequestUpdateEventInit","PaymentResponse","PaymentResponseEventMap","PaymentShippingOption","PaymentShippingType","PaymentValidationErrors","Pbkdf2Params","Performance","PerformanceEntry","PerformanceEntryList","PerformanceEventMap","PerformanceEventTiming","PerformanceMark","PerformanceMarkOptions","PerformanceMeasure","PerformanceMeasureOptions","PerformanceNavigation","PerformanceNavigationTiming","PerformanceObserver","PerformanceObserverCallback","PerformanceObserverEntryList","PerformanceObserverInit","PerformancePaintTiming","PerformanceResourceTiming","PerformanceServerTiming","PerformanceTiming","PeriodicWave","PeriodicWaveConstraints","PeriodicWaveOptions","PermissionDescriptor","PermissionName","PermissionState","PermissionStatus","PermissionStatusEventMap","Permissions","PhotoCapabilities","PhotoSettings","Pick","PictureInPictureEvent","PictureInPictureEventInit","PictureInPictureWindow","PictureInPictureWindowEventMap","PlainDate","PlainDateConstructor","PlainDateLike","PlainDateTime","PlainDateTimeConstructor","PlainDateTimeLike","PlainDateTimeToStringOptions","PlainDateToStringOptions","PlainDateToZonedDateTimeOptions","PlainMonthDay","PlainMonthDayConstructor","PlainMonthDayLike","PlainMonthDayToPlainDateOptions","PlainTime","PlainTimeConstructor","PlainTimeLike","PlainTimeToStringOptions","PlainYearMonth","PlainYearMonthConstructor","PlainYearMonthLike","PlainYearMonthToPlainDateOptions","PlaneLayout","PlaybackDirection","Plugin","PluginArray","PluralRuleType","PluralRules","PluralRulesConstructor","PluralRulesOptions","PluralizeUnit","PointerEvent","PointerEventInit","PointerLockOptions","PopStateEvent","PopStateEventInit","PopoverTargetAttributes","PositionAlignSetting","PositionCallback","PositionErrorCallback","PositionOptions","PredefinedColorSpace","PremultiplyAlpha","PresentationStyle","ProcessingInstruction","ProgressEvent","ProgressEventInit","Promise","PromiseConstructor","PromiseConstructorLike","PromiseFulfilledResult","PromiseLike","PromiseRejectedResult","PromiseRejectionEvent","PromiseRejectionEventInit","PromiseSettledResult","PromiseWithResolvers","PropertyDecorator","PropertyDefinition","PropertyDescriptor","PropertyDescriptorMap","PropertyIndexedKeyframes","PropertyKey","Proxy","ProxyConstructor","ProxyHandler","PublicKeyCredential","PublicKeyCredentialClientCapabilities","PublicKeyCredentialCreationOptions","PublicKeyCredentialCreationOptionsJSON","PublicKeyCredentialDescriptor","PublicKeyCredentialDescriptorJSON","PublicKeyCredentialEntity","PublicKeyCredentialParameters","PublicKeyCredentialRequestOptions","PublicKeyCredentialRequestOptionsJSON","PublicKeyCredentialRpEntity","PublicKeyCredentialType","PublicKeyCredentialUserEntity","PublicKeyCredentialUserEntityJSON","PushEncryptionKeyName","PushEvent","PushEventInit","PushManager","PushManagerAttribute","PushMessageData","PushMessageDataInit","PushSubscription","PushSubscriptionChangeEvent","PushSubscriptionChangeEventInit","PushSubscriptionJSON","PushSubscriptionOptions","PushSubscriptionOptionsInit","QueuingStrategy","QueuingStrategyInit","QueuingStrategySize","RTCAnswerOptions","RTCBundlePolicy","RTCCertificate","RTCCertificateExpiration","RTCConfiguration","RTCDTMFSender","RTCDTMFSenderEventMap","RTCDTMFToneChangeEvent","RTCDTMFToneChangeEventInit","RTCDataChannel","RTCDataChannelEvent","RTCDataChannelEventInit","RTCDataChannelEventMap","RTCDataChannelInit","RTCDataChannelState","RTCDegradationPreference","RTCDtlsFingerprint","RTCDtlsRole","RTCDtlsTransport","RTCDtlsTransportEventMap","RTCDtlsTransportState","RTCEncodedAudioFrame","RTCEncodedAudioFrameMetadata","RTCEncodedFrameMetadata","RTCEncodedVideoFrame","RTCEncodedVideoFrameMetadata","RTCError","RTCErrorDetailType","RTCErrorEvent","RTCErrorEventInit","RTCErrorInit","RTCIceCandidate","RTCIceCandidateInit","RTCIceCandidatePair","RTCIceCandidatePairStats","RTCIceCandidateType","RTCIceComponent","RTCIceConnectionState","RTCIceGathererState","RTCIceGatheringState","RTCIceProtocol","RTCIceRole","RTCIceServer","RTCIceTcpCandidateType","RTCIceTransport","RTCIceTransportEventMap","RTCIceTransportPolicy","RTCIceTransportState","RTCInboundRtpStreamStats","RTCLocalIceCandidateInit","RTCLocalSessionDescriptionInit","RTCOfferAnswerOptions","RTCOfferOptions","RTCOutboundRtpStreamStats","RTCPeerConnection","RTCPeerConnectionErrorCallback","RTCPeerConnectionEventMap","RTCPeerConnectionIceErrorEvent","RTCPeerConnectionIceErrorEventInit","RTCPeerConnectionIceEvent","RTCPeerConnectionIceEventInit","RTCPeerConnectionState","RTCPriorityType","RTCQualityLimitationReason","RTCReceivedRtpStreamStats","RTCRtcpMuxPolicy","RTCRtcpParameters","RTCRtpCapabilities","RTCRtpCodec","RTCRtpCodecParameters","RTCRtpCodingParameters","RTCRtpContributingSource","RTCRtpEncodingParameters","RTCRtpHeaderExtensionCapability","RTCRtpHeaderExtensionParameters","RTCRtpParameters","RTCRtpReceiveParameters","RTCRtpReceiver","RTCRtpReceiverTransform","RTCRtpScriptTransform","RTCRtpScriptTransformer","RTCRtpSendParameters","RTCRtpSender","RTCRtpSenderTransform","RTCRtpStreamStats","RTCRtpSynchronizationSource","RTCRtpTransceiver","RTCRtpTransceiverDirection","RTCRtpTransceiverInit","RTCSctpTransport","RTCSctpTransportEventMap","RTCSctpTransportState","RTCSdpType","RTCSentRtpStreamStats","RTCSessionDescription","RTCSessionDescriptionCallback","RTCSessionDescriptionInit","RTCSetParameterOptions","RTCSignalingState","RTCStats","RTCStatsIceCandidatePairState","RTCStatsReport","RTCStatsType","RTCTrackEvent","RTCTrackEventInit","RTCTransformEvent","RTCTransportStats","RadioNodeList","Range","RangeError","RangeErrorConstructor","ReadableByteStreamController","ReadableStream","ReadableStreamAsyncIterator","ReadableStreamBYOBReader","ReadableStreamBYOBReaderReadOptions","ReadableStreamBYOBRequest","ReadableStreamController","ReadableStreamDefaultController","ReadableStreamDefaultReader","ReadableStreamGenericReader","ReadableStreamGetReaderOptions","ReadableStreamIteratorOptions","ReadableStreamReadDoneResult","ReadableStreamReadResult","ReadableStreamReadValueResult","ReadableStreamReader","ReadableStreamReaderMode","ReadableStreamType","ReadableWritablePair","Readonly","ReadonlyArray","ReadonlyMap","ReadonlySet","ReadonlySetLike","ReadyState","Record","RecordingState","RedEyeReduction","ReferenceError","ReferenceErrorConstructor","ReferrerPolicy","Reflect","RegExp","RegExpConstructor","RegExpExecArray","RegExpIndicesArray","RegExpMatchArray","RegExpStringIterator","RegistrationOptions","RegistrationResponseJSON","RelativeTimeFormat","RelativeTimeFormatLocaleMatcher","RelativeTimeFormatNumeric","RelativeTimeFormatOptions","RelativeTimeFormatPart","RelativeTimeFormatStyle","RelativeTimeFormatUnit","RelativeTimeFormatUnitSingular","RemotePlayback","RemotePlaybackAvailabilityCallback","RemotePlaybackEventMap","RemotePlaybackState","RenderingContext","Report","ReportBody","ReportList","ReportingObserver","ReportingObserverCallback","ReportingObserverOptions","Request","RequestCache","RequestCredentials","RequestDestination","RequestInfo","RequestInit","RequestMode","RequestPriority","RequestRedirect","Required","ResidentKeyRequirement","ResizeObserver","ResizeObserverBoxOptions","ResizeObserverCallback","ResizeObserverEntry","ResizeObserverOptions","ResizeObserverSize","ResizeQuality","ResolvedCollatorOptions","ResolvedDateTimeFormatOptions","ResolvedDisplayNamesOptions","ResolvedDurationFormatOptions","ResolvedListFormatOptions","ResolvedNumberFormatOptions","ResolvedNumberFormatOptionsUseGrouping","ResolvedPluralRulesOptions","ResolvedRelativeTimeFormatOptions","ResolvedSegmenterOptions","Response","ResponseInit","ResponseType","ReturnType","RoundingOptions","RoundingOptionsWithLargestUnit","RsaHashedImportParams","RsaHashedKeyAlgorithm","RsaHashedKeyGenParams","RsaKeyAlgorithm","RsaKeyGenParams","RsaOaepParams","RsaOtherPrimesInfo","RsaPssParams","RuntimeError","SVGAElement","SVGAngle","SVGAnimateElement","SVGAnimateMotionElement","SVGAnimateTransformElement","SVGAnimatedAngle","SVGAnimatedBoolean","SVGAnimatedEnumeration","SVGAnimatedInteger","SVGAnimatedLength","SVGAnimatedLengthList","SVGAnimatedNumber","SVGAnimatedNumberList","SVGAnimatedPoints","SVGAnimatedPreserveAspectRatio","SVGAnimatedRect","SVGAnimatedString","SVGAnimatedTransformList","SVGAnimationElement","SVGBoundingBoxOptions","SVGCircleElement","SVGClipPathElement","SVGComponentTransferFunctionElement","SVGDefsElement","SVGDescElement","SVGElement","SVGElementEventMap","SVGElementTagNameMap","SVGEllipseElement","SVGFEBlendElement","SVGFEColorMatrixElement","SVGFEComponentTransferElement","SVGFECompositeElement","SVGFEConvolveMatrixElement","SVGFEDiffuseLightingElement","SVGFEDisplacementMapElement","SVGFEDistantLightElement","SVGFEDropShadowElement","SVGFEFloodElement","SVGFEFuncAElement","SVGFEFuncBElement","SVGFEFuncGElement","SVGFEFuncRElement","SVGFEGaussianBlurElement","SVGFEImageElement","SVGFEMergeElement","SVGFEMergeNodeElement","SVGFEMorphologyElement","SVGFEOffsetElement","SVGFEPointLightElement","SVGFESpecularLightingElement","SVGFESpotLightElement","SVGFETileElement","SVGFETurbulenceElement","SVGFilterElement","SVGFilterPrimitiveStandardAttributes","SVGFitToViewBox","SVGForeignObjectElement","SVGGElement","SVGGeometryElement","SVGGradientElement","SVGGraphicsElement","SVGImageElement","SVGLength","SVGLengthList","SVGLineElement","SVGLinearGradientElement","SVGMPathElement","SVGMarkerElement","SVGMaskElement","SVGMatrix","SVGMetadataElement","SVGNumber","SVGNumberList","SVGPathElement","SVGPatternElement","SVGPoint","SVGPointList","SVGPolygonElement","SVGPolylineElement","SVGPreserveAspectRatio","SVGRadialGradientElement","SVGRect","SVGRectElement","SVGSVGElement","SVGSVGElementEventMap","SVGScriptElement","SVGSetElement","SVGStopElement","SVGStringList","SVGStyleElement","SVGSwitchElement","SVGSymbolElement","SVGTSpanElement","SVGTests","SVGTextContentElement","SVGTextElement","SVGTextPathElement","SVGTextPositioningElement","SVGTitleElement","SVGTransform","SVGTransformList","SVGURIReference","SVGUnitTypes","SVGUseElement","SVGViewElement","Sanitizer","SanitizerAttribute","SanitizerAttributeNamespace","SanitizerConfig","SanitizerElement","SanitizerElementNamespace","SanitizerElementNamespaceWithAttributes","SanitizerElementWithAttributes","SanitizerPresets","Scheduler","SchedulerPostTaskCallback","SchedulerPostTaskOptions","Screen","ScreenOrientation","ScreenOrientationEventMap","ScriptProcessorNode","ScriptProcessorNodeEventMap","ScrollAxis","ScrollBehavior","ScrollIntoViewOptions","ScrollLogicalPosition","ScrollOptions","ScrollRestoration","ScrollSetting","ScrollTimeline","ScrollTimelineOptions","ScrollToOptions","SecurityPolicyViolationEvent","SecurityPolicyViolationEventDisposition","SecurityPolicyViolationEventInit","SegmentData","SegmentIterator","Segmenter","SegmenterOptions","Segments","Selection","SelectionDirection","SelectionMode","Server","ServerWebSocket","ServiceWorker","ServiceWorkerContainer","ServiceWorkerContainerEventMap","ServiceWorkerEventMap","ServiceWorkerGlobalScope","ServiceWorkerGlobalScopeEventMap","ServiceWorkerRegistration","ServiceWorkerRegistrationEventMap","ServiceWorkerState","ServiceWorkerUpdateViaCache","Set","SetConstructor","SetIterator","ShadowRoot","ShadowRootEventMap","ShadowRootInit","ShadowRootMode","ShareData","SharedArrayBuffer","SharedArrayBufferConstructor","SharedWorker","SharedWorkerGlobalScope","SharedWorkerGlobalScopeEventMap","ShellPromise","ShowPopoverOptions","SlotAssignmentMode","Slottable","Socket","SocketHandler","SourceBuffer","SourceBufferEventMap","SourceBufferList","SourceBufferListEventMap","SpeechRecognitionAlternative","SpeechRecognitionErrorCode","SpeechRecognitionErrorEvent","SpeechRecognitionErrorEventInit","SpeechRecognitionEvent","SpeechRecognitionEventInit","SpeechRecognitionResult","SpeechRecognitionResultList","SpeechSynthesis","SpeechSynthesisErrorCode","SpeechSynthesisErrorEvent","SpeechSynthesisErrorEventInit","SpeechSynthesisEvent","SpeechSynthesisEventInit","SpeechSynthesisEventMap","SpeechSynthesisUtterance","SpeechSynthesisUtteranceEventMap","SpeechSynthesisVoice","StartViewTransitionOptions","StaticRange","StaticRangeInit","Stats","StereoPannerNode","StereoPannerOptions","Storage","StorageEstimate","StorageEvent","StorageEventInit","StorageManager","StreamPipeOptions","String","StringConstructor","StringIterator","StringNumericLiteral","StructuredSerializeOptions","StylePropertyMap","StylePropertyMapReadOnly","StylePropertyMapReadOnlyIterator","StyleSheet","StyleSheetList","SubmitEvent","SubmitEventInit","Subprocess","SubtleCrypto","SuppressedError","SuppressedErrorConstructor","SvcOutputMetadata","Symbol","SymbolConstructor","SyntaxError","SyntaxErrorConstructor","TCPSocket","Table","TableDescriptor","TableKind","Tag","TagType","TaskController","TaskControllerInit","TaskPriority","TaskPriorityChangeEvent","TaskPriorityChangeEventInit","TaskSignal","TaskSignalAnyInit","TaskSignalEventMap","TemplateStringsArray","Temporal","TexImageSource","Text","TextDecodeOptions","TextDecoder","TextDecoderCommon","TextDecoderOptions","TextDecoderStream","TextEncoder","TextEncoderCommon","TextEncoderEncodeIntoResult","TextEncoderStream","TextEvent","TextInfo","TextMetrics","TextStreamBase","TextStreamReader","TextStreamWriter","TextTrack","TextTrackCue","TextTrackCueEventMap","TextTrackCueList","TextTrackEventMap","TextTrackKind","TextTrackList","TextTrackListEventMap","TextTrackMode","ThisParameterType","ThisType","TimeLikeObject","TimeRanges","TimeUnit","TimeZoneLike","TimelineRangeOffset","Timeout","Timer","TimerHandler","ToStringRoundingOptions","ToStringRoundingOptionsWithFractionalSeconds","ToggleEvent","ToggleEventInit","TogglePopoverOptions","Touch","TouchEvent","TouchEventInit","TouchInit","TouchList","TouchType","TrackEvent","TrackEventInit","TransferFunction","Transferable","TransformStream","TransformStreamDefaultController","Transformer","TransformerFlushCallback","TransformerStartCallback","TransformerTransformCallback","TransitionEvent","TransitionEventInit","TransitionOptions","TreeWalker","TypeError","TypeErrorConstructor","TypedArray","TypedPropertyDescriptor","UIEvent","UIEventInit","ULongRange","URIError","URIErrorConstructor","URL","URLPattern","URLPatternComponentResult","URLPatternInit","URLPatternInput","URLPatternOptions","URLPatternResult","URLSearchParams","URLSearchParamsIterator","Uint16Array","Uint16ArrayConstructor","Uint32Array","Uint32ArrayConstructor","Uint32List","Uint8Array","Uint8ArrayConstructor","Uint8ClampedArray","Uint8ClampedArrayConstructor","Uncapitalize","UnderlyingByteSource","UnderlyingDefaultSource","UnderlyingSink","UnderlyingSinkAbortCallback","UnderlyingSinkCloseCallback","UnderlyingSinkStartCallback","UnderlyingSinkWriteCallback","UnderlyingSource","UnderlyingSourceCancelCallback","UnderlyingSourcePullCallback","UnderlyingSourceStartCallback","UnicodeBCP47LocaleIdentifier","UnknownCredentialOptions","Uppercase","UserActivation","UserVerificationRequirement","VBArray","VBArrayConstructor","VTTCue","VTTRegion","ValidityState","ValidityStateFlags","ValueType","ValueTypeMap","VibratePattern","VideoColorPrimaries","VideoColorSpace","VideoColorSpaceInit","VideoConfiguration","VideoDecoder","VideoDecoderConfig","VideoDecoderEventMap","VideoDecoderInit","VideoDecoderSupport","VideoEncoder","VideoEncoderBitrateMode","VideoEncoderConfig","VideoEncoderEncodeOptions","VideoEncoderEncodeOptionsForAvc","VideoEncoderEventMap","VideoEncoderInit","VideoEncoderSupport","VideoFacingModeEnum","VideoFrame","VideoFrameBufferInit","VideoFrameCallbackMetadata","VideoFrameCopyToOptions","VideoFrameInit","VideoFrameOutputCallback","VideoFrameRequestCallback","VideoMatrixCoefficients","VideoPixelFormat","VideoPlaybackQuality","VideoTransferCharacteristics","ViewTimeline","ViewTimelineOptions","ViewTransition","ViewTransitionTypeSet","ViewTransitionUpdateCallback","VisualViewport","VisualViewportEventMap","VoidFunction","WEBGL_color_buffer_float","WEBGL_compressed_texture_astc","WEBGL_compressed_texture_etc","WEBGL_compressed_texture_etc1","WEBGL_compressed_texture_pvrtc","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_depth_texture","WEBGL_draw_buffers","WEBGL_lose_context","WEBGL_multi_draw","WGSLLanguageFeatures","WSH","WScript","WakeLock","WakeLockSentinel","WakeLockSentinelEventMap","WakeLockType","WaveShaperNode","WaveShaperOptions","WeakKey","WeakKeyTypes","WeakMap","WeakMapConstructor","WeakRef","WeakRefConstructor","WeakSet","WeakSetConstructor","WebAssembly","WebAssemblyCompileOptions","WebAssemblyInstantiatedSource","WebCodecsErrorCallback","WebGL2RenderingContext","WebGL2RenderingContextBase","WebGL2RenderingContextOverloads","WebGLActiveInfo","WebGLBuffer","WebGLContextAttributes","WebGLContextEvent","WebGLContextEventInit","WebGLFramebuffer","WebGLPowerPreference","WebGLProgram","WebGLQuery","WebGLRenderbuffer","WebGLRenderingContext","WebGLRenderingContextBase","WebGLRenderingContextOverloads","WebGLSampler","WebGLShader","WebGLShaderPrecisionFormat","WebGLSync","WebGLTexture","WebGLTransformFeedback","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES","WebKitCSSMatrix","WebSocket","WebSocketEventMap","WebSocketHandler","WebTransport","WebTransportBidirectionalStream","WebTransportCloseInfo","WebTransportCongestionControl","WebTransportDatagramDuplexStream","WebTransportError","WebTransportErrorOptions","WebTransportErrorSource","WebTransportHash","WebTransportOptions","WebTransportSendOptions","WebTransportSendStreamOptions","WeekInfo","WheelEvent","WheelEventInit","Window","WindowClient","WindowEventHandlers","WindowEventHandlersEventMap","WindowEventMap","WindowLocalStorage","WindowOrWorkerGlobalScope","WindowPostMessageOptions","WindowProxy","WindowSessionStorage","WithImplicitCoercion","Worker","WorkerEventMap","WorkerGlobalScope","WorkerGlobalScopeEventMap","WorkerLocation","WorkerNavigator","WorkerOptions","WorkerType","Worklet","WorkletOptions","WritableStream","WritableStreamDefaultController","WritableStreamDefaultWriter","WriteCommandType","WriteParams","XMLDocument","XMLHttpRequest","XMLHttpRequestBodyInit","XMLHttpRequestEventMap","XMLHttpRequestEventTarget","XMLHttpRequestEventTargetEventMap","XMLHttpRequestResponseType","XMLHttpRequestUpload","XMLSerializer","XPathEvaluator","XPathEvaluatorBase","XPathExpression","XPathNSResolver","XPathResult","XSLTProcessor","YearMonthLikeObject","ZonedDateTime","ZonedDateTimeConstructor","ZonedDateTimeFromOptions","ZonedDateTimeLike","ZonedDateTimeLikeObject","ZonedDateTimeToStringOptions","global","globalThis","process","structuredClone"])});function yl(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(`
|
|
168
168
|
`,n),a=o===-1?e.length:o;r+=" ".repeat(a-n),n=a;continue}if(i==="/*"){let o=e.indexOf("*/",n+2),a=o===-1?e.length:o+2;for(let c=n;c<a;c++)r+=e[c]===`
|
|
169
169
|
`?`
|
|
170
170
|
`:" ";n=a;continue}let s=e[n];if(t.strings&&(s==='"'||s==="'"||s==="`")){let o=s;r+=" ",n++;while(n<e.length){if(e[n]==="\\"){r+=" ",n+=2;continue}if(e[n]===o){r+=" ",n++;break}r+=e[n]===`
|
|
171
171
|
`?`
|
|
172
|
-
`:" ",n++}continue}r+=s,n++}return r}function Ad(e){let t=new Set,r=[/\b(?:export\s+)?(?:declare\s+)?(?:abstract\s+)?(?:type|interface|class|enum|namespace|module)\s+([A-Za-z_$][\w$]*)/g,/\b(?:export\s+)?(?:declare\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/g,/\b(?:export\s+)?declare\s+(?:const|let|var)\s+([A-Za-z_$][\w$]*)/g];for(let n of r)for(let i of e.matchAll(n))t.add(i[1]);return t}function $d(e){let t=new Set;for(let r of e.matchAll(/\bimport\s+(?:type\s+)?([\s\S]*?)\s+from\s*['"`]/g)){let n=r[1],i=/\*\s*as\s+([A-Za-z_$][\w$]*)/.exec(n);if(i)t.add(i[1]);let s=n.split("{")[0].replace(/\*\s*as\s+[A-Za-z_$][\w$]*/,"");for(let a of s.split(",")){let c=a.trim();if(/^[A-Za-z_$][\w$]*$/.test(c))t.add(c)}let o=/\{([\s\S]*?)\}/.exec(n);if(o)for(let a of o[1].split(",")){let c=a.trim().replace(/^type\s+/,"");if(!c)continue;let f=/\bas\s+([A-Za-z_$][\w$]*)$/.exec(c);t.add(f?f[1]:c.split(/\s+/)[0])}}for(let r of e.matchAll(/\bimport\s*\(\s*['"`][^'"`]*['"`]\s*\)\s*\.\s*([A-Za-z_$][\w$]*)/g))t.add(r[1]);return t}function xd(e){let t=new Set,r=(i)=>{for(let s of i.split(",")){let o=s.trim().split(/\s+|=/)[0]?.trim();if(o&&/^[A-Za-z_$][\w$]*$/.test(o))t.add(o)}},n=/\b(?:type|interface|class|function)\s+[A-Za-z_$][\w$]*\s*<([^<>]*(?:<[^<>]*>[^<>]*)*)>/g;for(let i of e.matchAll(n))r(i[1]);for(let i of e.matchAll(/(?:\b[A-Za-z_$][\w$]*)?\s*<([^<>()]*)>\s*\(/g))r(i[1]);for(let i of e.matchAll(/\binfer\s+([A-Za-z_$][\w$]*)/g))t.add(i[1]);for(let i of e.matchAll(/\[\s*([A-Za-z_$][\w$]*)\s+in\b/g))t.add(i[1]);return t}function Td(e){let t=new Map,r=(i)=>{let s=1;for(let o=0;o<i&&o<e.length;o++)if(e.charCodeAt(o)===10)s++;return s},n=(i,s,o)=>{for(let a of i.matchAll(/\b([A-Z][\w$]*)\b/g)){let c=a[1];if(t.has(c))continue;let f=i.slice(a.index+c.length);if(/^\s*\??:/.test(f))continue;t.set(c,{line:r(s),context:o.trim().slice(0,120)})}};for(let i of e.matchAll(/\btype\s+[A-Za-z_$][\w$]*\s*(?:<[^=]*?>)?\s*=([^;]*)/g))n(i[1],i.index+i[0].indexOf("="),i[0]);for(let i of e.matchAll(/\b(?:extends|implements)\s+([^{;]*)/g))n(i[1],i.index,i[0]);for(let i of e.matchAll(/:\s*([^;,){}\n=]+)/g))n(i[1],i.index,i[0]);for(let i of e.matchAll(/<([^<>()]*)>/g))n(i[1],i.index,i[0]);return t}function Cl(e){let t=yl(e),r=yl(e,{strings:!1}),n=new Set([...Ad(t),...$d(r),...xd(t),...pl,...Sd]),i=[];for(let[s,o]of Td(t)){if(n.has(s))continue;if(new RegExp(`[\\w$]\\s*\\.\\s*${s}\\b`).test(t))continue;i.push({name:s,line:o.line,context:o.context})}return i.sort((s,o)=>s.line-o.line||s.name.localeCompare(o.name))}var Sd;var wl=ce(()=>{gl();Sd=new Set(["This","True","False","Null","Undefined","Void","Never","Any","Unknown","Object","Infinity","NaN"])});function Tt(e,t){let r=1,n=1;for(let i=0;i<t;i++)if(e.charCodeAt(i)===10)r++,n=1;else n++;return{line:r,column:n}}function El(e){let t=[],r=[],n=[],i={")":"(","]":"[","}":"{"},s=0,o=0,a=-1;for(let f=0;f<e.length;f++){let u=e.charCodeAt(f),l=e.charCodeAt(f+1);if(a!==-1){if(u===42&&l===47)r.push({start:a,end:f+2}),a=-1,f++;continue}if(s){if(u===92)f++;else if(u===s)r.push({start:o,end:f+1}),s=0;continue}if(u===47&&l===42){a=f,f++;continue}if(u===47&&l===47){let d=f;while(f<e.length&&e.charCodeAt(f)!==10)f++;r.push({start:d,end:f});continue}if(u===39||u===34||u===96){s=u,o=f;continue}let g=e[f];if(g==="("||g==="["||g==="{")n.push({char:g,offset:f});else if(i[g]){let d=n.pop();if(!d||d.char!==i[g])t.push({...Tt(e,f),message:`Unexpected closing delimiter ${g}`,code:"DTSX1004"})}}if(s)t.push({...Tt(e,o),message:"Unterminated string literal",code:"DTSX1002"});if(a!==-1)t.push({...Tt(e,a),message:"Unterminated block comment",code:"DTSX1003"});for(let f of n)t.push({...Tt(e,f.offset),message:`Unclosed delimiter ${f.char}`,code:"DTSX1001"});let c=[[/\b(?:interface|class|enum)\s*(?=[{=])/g,"Declaration name expected"],[/\bfunction\s*(?=\()/g,"Function name expected"],[/\(\s*:/g,"Parameter name expected"]];for(let[f,u]of c)for(let l of e.matchAll(f)){if(r.some((g)=>l.index>=g.start&&l.index<g.end))continue;t.push({...Tt(e,l.index),message:u,code:"DTSX1005"})}for(let f of e.matchAll(/\btype\s*(?=[{=])/g)){if(r.some((l)=>f.index>=l.start&&f.index<l.end))continue;let u=e.slice(0,f.index).trimEnd();if(u.endsWith("import")||u.endsWith("export"))continue;t.push({...Tt(e,f.index),message:"Declaration name expected",code:"DTSX1005"})}return t.push(...
|
|
172
|
+
`:" ",n++}continue}r+=s,n++}return r}function Ad(e){let t=new Set,r=[/\b(?:export\s+)?(?:declare\s+)?(?:abstract\s+)?(?:type|interface|class|enum|namespace|module)\s+([A-Za-z_$][\w$]*)/g,/\b(?:export\s+)?(?:declare\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/g,/\b(?:export\s+)?declare\s+(?:const|let|var)\s+([A-Za-z_$][\w$]*)/g];for(let n of r)for(let i of e.matchAll(n))t.add(i[1]);return t}function $d(e){let t=new Set;for(let r of e.matchAll(/\bimport\s+(?:type\s+)?([\s\S]*?)\s+from\s*['"`]/g)){let n=r[1],i=/\*\s*as\s+([A-Za-z_$][\w$]*)/.exec(n);if(i)t.add(i[1]);let s=n.split("{")[0].replace(/\*\s*as\s+[A-Za-z_$][\w$]*/,"");for(let a of s.split(",")){let c=a.trim();if(/^[A-Za-z_$][\w$]*$/.test(c))t.add(c)}let o=/\{([\s\S]*?)\}/.exec(n);if(o)for(let a of o[1].split(",")){let c=a.trim().replace(/^type\s+/,"");if(!c)continue;let f=/\bas\s+([A-Za-z_$][\w$]*)$/.exec(c);t.add(f?f[1]:c.split(/\s+/)[0])}}for(let r of e.matchAll(/\bimport\s*\(\s*['"`][^'"`]*['"`]\s*\)\s*\.\s*([A-Za-z_$][\w$]*)/g))t.add(r[1]);return t}function xd(e){let t=new Set,r=(i)=>{for(let s of i.split(",")){let o=s.trim().split(/\s+|=/)[0]?.trim();if(o&&/^[A-Za-z_$][\w$]*$/.test(o))t.add(o)}},n=/\b(?:type|interface|class|function)\s+[A-Za-z_$][\w$]*\s*<([^<>]*(?:<[^<>]*>[^<>]*)*)>/g;for(let i of e.matchAll(n))r(i[1]);for(let i of e.matchAll(/(?:\b[A-Za-z_$][\w$]*)?\s*<([^<>()]*)>\s*\(/g))r(i[1]);for(let i of e.matchAll(/\binfer\s+([A-Za-z_$][\w$]*)/g))t.add(i[1]);for(let i of e.matchAll(/\[\s*([A-Za-z_$][\w$]*)\s+in\b/g))t.add(i[1]);return t}function Td(e){let t=new Map,r=(i)=>{let s=1;for(let o=0;o<i&&o<e.length;o++)if(e.charCodeAt(o)===10)s++;return s},n=(i,s,o)=>{for(let a of i.matchAll(/\b([A-Z][\w$]*)\b/g)){let c=a[1];if(t.has(c))continue;let f=i.slice(a.index+c.length);if(/^\s*\??:/.test(f))continue;t.set(c,{line:r(s),context:o.trim().slice(0,120)})}};for(let i of e.matchAll(/\btype\s+[A-Za-z_$][\w$]*\s*(?:<[^=]*?>)?\s*=([^;]*)/g))n(i[1],i.index+i[0].indexOf("="),i[0]);for(let i of e.matchAll(/\b(?:extends|implements)\s+([^{;]*)/g))n(i[1],i.index,i[0]);for(let i of e.matchAll(/:\s*([^;,){}\n=]+)/g))n(i[1],i.index,i[0]);for(let i of e.matchAll(/<([^<>()]*)>/g))n(i[1],i.index,i[0]);return t}function Cl(e){let t=yl(e),r=yl(e,{strings:!1}),n=new Set([...Ad(t),...$d(r),...xd(t),...pl,...Sd]),i=[];for(let[s,o]of Td(t)){if(n.has(s))continue;if(new RegExp(`[\\w$]\\s*\\.\\s*${s}\\b`).test(t))continue;i.push({name:s,line:o.line,context:o.context})}return i.sort((s,o)=>s.line-o.line||s.name.localeCompare(o.name))}var Sd;var wl=ce(()=>{gl();Sd=new Set(["This","True","False","Null","Undefined","Void","Never","Any","Unknown","Object","Infinity","NaN"])});function Tt(e,t){let r=1,n=1;for(let i=0;i<t;i++)if(e.charCodeAt(i)===10)r++,n=1;else n++;return{line:r,column:n}}function El(e){let t=[],r=[],n=[],i={")":"(","]":"[","}":"{"},s=0,o=0,a=-1;for(let f=0;f<e.length;f++){let u=e.charCodeAt(f),l=e.charCodeAt(f+1);if(a!==-1){if(u===42&&l===47)r.push({start:a,end:f+2}),a=-1,f++;continue}if(s){if(u===92)f++;else if(u===s)r.push({start:o,end:f+1}),s=0;continue}if(u===47&&l===42){a=f,f++;continue}if(u===47&&l===47){let d=f;while(f<e.length&&e.charCodeAt(f)!==10)f++;r.push({start:d,end:f});continue}if(u===39||u===34||u===96){s=u,o=f;continue}let g=e[f];if(g==="("||g==="["||g==="{")n.push({char:g,offset:f});else if(i[g]){let d=n.pop();if(!d||d.char!==i[g])t.push({...Tt(e,f),message:`Unexpected closing delimiter ${g}`,code:"DTSX1004"})}}if(s)t.push({...Tt(e,o),message:"Unterminated string literal",code:"DTSX1002"});if(a!==-1)t.push({...Tt(e,a),message:"Unterminated block comment",code:"DTSX1003"});for(let f of n)t.push({...Tt(e,f.offset),message:`Unclosed delimiter ${f.char}`,code:"DTSX1001"});let c=[[/\b(?:interface|class|enum)\s*(?=[{=])/g,"Declaration name expected"],[/\bfunction\s*(?=\()/g,"Function name expected"],[/\(\s*:/g,"Parameter name expected"]];for(let[f,u]of c)for(let l of e.matchAll(f)){if(r.some((g)=>l.index>=g.start&&l.index<g.end))continue;t.push({...Tt(e,l.index),message:u,code:"DTSX1005"})}for(let f of e.matchAll(/\btype\s*(?=[{=])/g)){if(r.some((l)=>f.index>=l.start&&f.index<l.end))continue;let u=e.slice(0,f.index).trimEnd();if(u.endsWith("import")||u.endsWith("export"))continue;t.push({...Tt(e,f.index),message:"Declaration name expected",code:"DTSX1005"})}return t.push(...Rd(e,r)),t.sort((f,u)=>f.line-u.line||f.column-u.column)}function Rd(e,t){let r=[],n=(i)=>t.some((s)=>i>=s.start&&i<s.end);for(let i of e.matchAll(/\b(import|export)\s+(?:type\s+)?\{/g)){let s=i.index;if(n(s))continue;let o=s+i[0].length-1,a=-1;for(let u=o+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(o+1,a);if(!c.trim())continue;let f=o+1;for(let u of c.split(",")){let l=u.trim();if(l){let g=f+u.indexOf(l);if(l.includes(";"))r.push({...Tt(e,g),message:`Unexpected ';' in ${i[1]} clause \u2014 specifiers are separated by ','`,code:"DTSX1006"});else if(!Pd.test(l))r.push({...Tt(e,g),message:`Invalid ${i[1]} specifier '${l}'`,code:"DTSX1006"})}f+=u.length+1}}return r}var vl,Pd;var bl=ce(()=>{vl=String.raw`(?:[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*|'[^']*'|"[^"]*")`,Pd=new RegExp(`^(?:type\\s+)?${vl}(?:\\s+as\\s+${vl})?$`,"u")});import{statSync as Od}from"fs";import{readFile as kd,readdir as My}from"fs/promises";import{createRequire as Md}from"module";import{dirname as Dd,isAbsolute as Sl,join as Id,resolve as Al}from"path";import Fd from"process";function us(){return`${String.fromCharCode(47,47,35)} sourceMappingURL=`}async function br(e,t,r="lf"){let n=t.replace(/\r\n/g,`
|
|
173
173
|
`);if(!n.endsWith(`
|
|
174
174
|
`))n+=`
|
|
175
175
|
`;if(r==="crlf")n=n.replace(/\n/g,`\r
|
|
176
176
|
`);await Eo(e,n)}function Nd(e){let t="",r=0,n=0;while(r<e.length){let i=e.charCodeAt(r);if(n){if(t+=e[r],i===92&&r+1<e.length){t+=e[r+1],r+=2;continue}if(i===n)n=0;r++;continue}if(i===34){n=i,t+=e[r++];continue}if(i===47&&e.charCodeAt(r+1)===47){r+=2;while(r<e.length&&e.charCodeAt(r)!==10)r++;continue}if(i===47&&e.charCodeAt(r+1)===42){r+=2;while(r+1<e.length&&!(e.charCodeAt(r)===42&&e.charCodeAt(r+1)===47)){if(e.charCodeAt(r)===10)t+=`
|
|
177
|
-
`;r++}r=Math.min(r+2,e.length);continue}if(i===44){let s=r+1;while(s<e.length){while(s<e.length&&e.charCodeAt(s)<=32)s++;if(e.charCodeAt(s)===47&&e.charCodeAt(s+1)===47){s+=2;while(s<e.length&&e.charCodeAt(s)!==10)s++;continue}if(e.charCodeAt(s)===47&&e.charCodeAt(s+1)===42){s+=2;while(s+1<e.length&&!(e.charCodeAt(s)===42&&e.charCodeAt(s+1)===47))s++;s=Math.min(s+2,e.length);continue}break}let o=e.charCodeAt(s);if(o===93||o===125){r++;continue}}t+=e[r++]}return t}function fs(e){let t=[e];if(!e.endsWith(".json"))t.push(`${e}.json`);t.push(Id(e,"tsconfig.json"));for(let r of t)try{if(
|
|
177
|
+
`;r++}r=Math.min(r+2,e.length);continue}if(i===44){let s=r+1;while(s<e.length){while(s<e.length&&e.charCodeAt(s)<=32)s++;if(e.charCodeAt(s)===47&&e.charCodeAt(s+1)===47){s+=2;while(s<e.length&&e.charCodeAt(s)!==10)s++;continue}if(e.charCodeAt(s)===47&&e.charCodeAt(s+1)===42){s+=2;while(s+1<e.length&&!(e.charCodeAt(s)===42&&e.charCodeAt(s+1)===47))s++;s=Math.min(s+2,e.length);continue}break}let o=e.charCodeAt(s);if(o===93||o===125){r++;continue}}t+=e[r++]}return t}function fs(e){let t=[e];if(!e.endsWith(".json"))t.push(`${e}.json`);t.push(Id(e,"tsconfig.json"));for(let r of t)try{if(Od(r).isFile())return r}catch{}return null}function Ld(e,t){if(Sl(e)||e.startsWith("."))return fs(Al(Dd(t),e));let r=Md(t);for(let n of[e,`${e}/tsconfig.json`])try{let i=fs(r.resolve(n));if(i)return i}catch{}return null}async function $l(e,t){let r=fs(e);if(!r||t.has(r))return;t.add(r);let n=await kd(r,"utf8"),i=JSON.parse(Nd(n)),s=typeof i.extends==="string"?[i.extends]:i.extends??[],o;for(let a of s){let c=Ld(a,r);if(!c)continue;let f=await $l(c,t);if(f!==void 0)o=f}return i.compilerOptions?.isolatedDeclarations??o}async function xl(e){try{let t=e?.cwd||Fd.cwd(),r=e?.tsconfigPath||"tsconfig.json",n=Sl(r)?r:Al(t,r);return await $l(n,new Set)??!1}catch{return!1}}function Tl(e,t){let r={isValid:!0,errors:[]};for(let n of El(e))r.errors.push({line:n.line,column:n.column,message:n.message,code:n.code});for(let n of Cl(e))r.errors.push({line:n.line,column:1,message:`'${n.name}' is used but never declared or imported here, so it resolves to an error type for anything consuming this file. It is most likely an ambient global in the source project \u2014 import it explicitly. Referenced by: ${n.context}`,code:"dangling-type-reference"});return r.isValid=r.errors.length===0,r}function Pl(e,t,r){if(e===t)return"";let n=e.split(`
|
|
178
178
|
`),i=t.split(`
|
|
179
179
|
`),s=new Map,o=new Map;for(let u=0;u<n.length;u++)s.set(n[u],(s.get(n[u])??0)+1);for(let u=0;u<i.length;u++)o.set(i[u],(o.get(i[u])??0)+1);let a=[],c=[];for(let[u,l]of s){let g=l-(o.get(u)??0);for(let d=0;d<g;d++)a.push(u)}for(let[u,l]of o){let g=l-(s.get(u)??0);for(let d=0;d<g;d++)c.push(u)}if(a.length===0&&c.length===0)return"";let f=[`--- ${r}`,`+++ ${r}`];for(let u=0;u<a.length;u++)f.push(`- ${a[u]}`);for(let u=0;u<c.length;u++)f.push(`+ ${c[u]}`);return f.join(`
|
|
180
|
-
`)}function
|
|
180
|
+
`)}function Rl(e,t,r,n){let i=e.split(`
|
|
181
181
|
`),s=[];function o(l){let g="",d=l<0?-l<<1|1:l<<1;do{let v=d&31;if(d>>>=5,d>0)v|=32;g+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[v]}while(d>0);return g}let a=0,c=0,f=0,u=n.split(`
|
|
182
|
-
`).length;for(let l=0;l<i.length;l++){if(i[l].trim()===""){s.push("");continue}a=0;let g=Math.min(l,u-1),d=[],v=0-a,b=0,C=g-c,T=0-f;d.push(o(v)+o(b)+o(C)+o(T)),a=0,c=g,f=0,s.push(d.join(","))}return{version:3,file:t,sourceRoot:"",sources:[r],sourcesContent:[n],mappings:s.join(";")}}function
|
|
182
|
+
`).length;for(let l=0;l<i.length;l++){if(i[l].trim()===""){s.push("");continue}a=0;let g=Math.min(l,u-1),d=[],v=0-a,b=0,C=g-c,T=0-f;d.push(o(v)+o(b)+o(C)+o(T)),a=0,c=g,f=0,s.push(d.join(","))}return{version:3,file:t,sourceRoot:"",sources:[r],sourcesContent:[n],mappings:s.join(";")}}function Ol(e,t){return`${e}
|
|
183
183
|
${us()}${t}
|
|
184
184
|
`}var kl=ce(()=>{Jr();wl();bl()});function vt(e,t=!0){if(!t||!e||e.length===0)return"";if(e.length===1){let n=e[0];if(n.length>0&&n.charCodeAt(0)>32&&n.charCodeAt(n.length-1)>32)return`${n}
|
|
185
185
|
`;return`${n.trim()}
|
|
@@ -213,18 +213,18 @@ ${u.split(`
|
|
|
213
213
|
*/
|
|
214
214
|
${n}`}if(a)return`${Wd(a)}${n}`;return r+n}function jd(e,t=!0){let r=vt(e.leadingComments,t),n=e.text;if(n.startsWith("export declare interface")||n.startsWith("declare interface"))return r+n;let i="";if(e.isExported)i+="export ";if(i+="declare interface ",i+=e.name,e.generics)i+=e.generics;if(e.extends)i+=` extends ${e.extends}`;let s=Bd(e.text);if(s!==-1)i+=` ${e.text.slice(s)}`;else i+=" {}";return r+i}function _d(e,t=!0){let r=vt(e.leadingComments,t);if(e.text.includes("{")&&e.text.includes("}")&&e.text.includes("from"))return r+e.text;let n="";if(e.isExported)n+="export ";if(!e.isExported&&!e.text.includes(" from "))n+="declare ";let i=e.text.indexOf("type ");if(i!==-1){let o=e.text.slice(i),a=o.length;while(a>0&&(o.charCodeAt(a-1)===59||o.charCodeAt(a-1)===32||o.charCodeAt(a-1)===10||o.charCodeAt(a-1)===13))a--;if(a<o.length)o=o.slice(0,a);n+=o}else{if(n+=`type ${e.name}`,e.generics)n+=e.generics;n+=" = any"}let s=n.trimEnd();if(!s.endsWith(";")&&!s.endsWith("}"))n+=";";return r+n}function Vd(e,t=!0){return vt(e.leadingComments,t)+e.text}function Ud(e,t=!0){let r=vt(e.leadingComments,t),n="";if(e.isExported)n+="export ";if(n+="declare ",e.modifiers?.includes("const"))n+="const ";n+="enum ",n+=e.name;let i=e.text.indexOf("{");if(i!==-1)n+=` ${e.text.slice(i)}`;else n+=" {}";return r+n}function Kd(e,t=!0){let r=vt(e.leadingComments,t);if(e.text.startsWith("declare global"))return r+e.text;if(e.source||(e.name.startsWith('"')||e.name.startsWith("'")||e.name.startsWith("`"))){let s="declare module ";s+=e.name;let o=e.text.indexOf("{");if(o!==-1)s+=` ${e.text.slice(o)}`;else s+=" {}";return r+s}let n="";if(e.isExported)n+="export ";if(!e.modifiers?.includes("declare"))n+="declare ";n+="namespace ",n+=e.name;let i=e.text.indexOf("{");if(i!==-1)n+=` ${e.text.slice(i)}`;else n+=" {}";return r+n}function Hd(e){let t=Mt.get(e);if(t)return Mt.delete(e),Mt.set(e,t),t;return null}function Il(e,t){if(Mt.set(e,t),Mt.size>200){let r=0;for(let n of Mt.keys()){if(r++>=20)break;Mt.delete(n)}}}function zd(e){let t=e.indexOf(" from ");if(t===-1)return null;let r=e.slice(t+6).trim(),n=r[0];if(n!=='"'&&n!=="'")return null;let i=r.indexOf(n,1);if(i===-1)return null;let s=r.slice(1,i),o=e.slice(0,t).trim(),a=o.startsWith("import type ");if(o.startsWith("import "))o=o.slice(7).trim();if(o.startsWith("type "))o=o.slice(5).trim();let c=null,f=[],u=!1,l=o.indexOf("{"),g=o.lastIndexOf("}");if(l!==-1&&g!==-1){let d=o.slice(0,l).trim();if(d.endsWith(","))c=d.slice(0,-1).trim()||null;let v=o.slice(l+1,g),b=0;for(let C=0;C<=v.length;C++)if(C===v.length||v.charCodeAt(C)===44){let T=b,k=C;while(T<k&&(v.charCodeAt(T)===32||v.charCodeAt(T)===9||v.charCodeAt(T)===10))T++;while(k>T&&(v.charCodeAt(k-1)===32||v.charCodeAt(k-1)===9||v.charCodeAt(k-1)===10))k--;if(T<k)f.push(v.slice(T,k));b=C+1}}else{let d=o.trim();if(d.startsWith("* as "))c=d.slice(5).trim()||null,u=!0;else c=d||null}return{defaultName:c,namedItems:f,source:s,isTypeOnly:a,isNamespace:u}}function Jd(e){let t=Hd(e);if(t)return t;let r=[],n=e.indexOf(" from ");if(n===-1)return Il(e,r),r;let i=e.slice(0,n).trim();if(i.startsWith("import "))i=i.slice(7).trim();if(i.startsWith("type "))i=i.slice(5).trim();let s=i.indexOf("{"),o=i.lastIndexOf("}");if(s!==-1&&o!==-1){let a=i.slice(0,s).trim();if(a.endsWith(",")){let f=a.slice(0,-1).trim();if(f)r.push(f)}else if(a&&!a.includes(","))r.push(a);let c=i.slice(s+1,o).split(",");for(let f=0;f<c.length;f++){let u=c[f].trim();if(!u)continue;if(u.startsWith("type "))u=u.slice(5).trim();let l=u.indexOf(" as ");if(l!==-1)u=u.slice(l+4).trim();if(u)r.push(u)}}else{let a=i.trim();if(a.startsWith("* as ")){let c=a.slice(5).trim();if(c)r.push(c)}else if(a)r.push(a)}return Il(e,r),r}function Xd(e){let t=[],r=0;for(let n=0;n<=e.length;n++)if(n===e.length||e[n]===`
|
|
215
215
|
`){let i=r,s=n;while(i<s&&(e[i]===" "||e[i]==="\t"||e[i]==="\r"))i++;while(s>i&&(e[s-1]===" "||e[s-1]==="\t"||e[s-1]==="\r"))s--;let o=e.slice(i,s);if(r=n+1,o.startsWith("///")){if(o.indexOf("<")===-1)continue;if(qd.test(o)||Yd.test(o)||Zd.test(o))t.push(o)}else if(o===""||o.startsWith("//"))continue;else break}return t}function Fl(e,t){throw Error(t||`Unexpected value: ${e}`)}function Qd(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===95||e===36||e>127}function Nl(e){let t=new Set,r=0,n=e.length;while(r<n){let i=e.charCodeAt(r);if(i>=65&&i<=90||i>=97&&i<=122||i===95||i===36||i>127){let s=r;r++;while(r<n&&Qd(e.charCodeAt(r)))r++;t.add(e.substring(s,r))}else r++}return t}function Gl(e,t,r=!0,n=["bun"]){let i="",s=t.sourceCode;if(s){let F=0;while(F<s.length&&(s.charCodeAt(F)===32||s.charCodeAt(F)===9||s.charCodeAt(F)===10||s.charCodeAt(F)===13))F++;if(F<s.length-2&&s.charCodeAt(F)===47&&s.charCodeAt(F+1)===47&&s.charCodeAt(F+2)===47){let U=Xd(s);if(U.length>0)for(let q=0;q<U.length;q++){if(i)i+=`
|
|
216
|
-
`;i+=U[q]}}}let o=[],a=[],c=[],f=[],u=[],l=[],g=[],d=[],v=[];for(let F of e){let U=F.kind;switch(U){case"import":o.push(F);break;case"function":a.push(F);break;case"variable":c.push(F);break;case"interface":f.push(F);break;case"type":u.push(F);break;case"class":l.push(F);break;case"enum":g.push(F);break;case"module":d.push(F);break;case"export":v.push(F);break;case"namespace":d.push(F);break;case"unknown":break;default:Fl(U,`Unhandled declaration kind: ${U}`)}}let b=new Set,C=[],T=[],k=[],
|
|
217
|
-
`));for(let q of f)if(U.has(q.name))
|
|
218
|
-
`);if(q&&I.size>0){let H=Nl(q);for(let Z of I.keys())if(H.has(Z))F.add(Z)}for(let H of b)if(I.has(H))F.add(H);for(let H of o){if(H.isSideEffect){let ae=H.text.trim(),Q=ae.endsWith(";")?ae:`${ae};`;
|
|
219
|
-
`;i+=
|
|
220
|
-
`;i+=C[F]}let
|
|
216
|
+
`;i+=U[q]}}}let o=[],a=[],c=[],f=[],u=[],l=[],g=[],d=[],v=[];for(let F of e){let U=F.kind;switch(U){case"import":o.push(F);break;case"function":a.push(F);break;case"variable":c.push(F);break;case"interface":f.push(F);break;case"type":u.push(F);break;case"class":l.push(F);break;case"enum":g.push(F);break;case"module":d.push(F);break;case"export":v.push(F);break;case"namespace":d.push(F);break;case"unknown":break;default:Fl(U,`Unhandled declaration kind: ${U}`)}}let b=new Set,C=[],T=[],k=[],R=new Set;for(let F of v){let U=vt(F.leadingComments,r);if(F.text.startsWith("export default")){let q=F.text.endsWith(";")?F.text:`${F.text};`;k.push(U+q)}else{let q=F.text.trim();if(!q.endsWith(";"))q+=";";let oe=q.match(em);if(oe){let Z=oe[1],re=0;for(let X=0;X<=Z.length;X++)if(X===Z.length||Z.charCodeAt(X)===44){let Re=re,Oe=X;while(Re<Oe&&Z.charCodeAt(Re)<=32)Re++;while(Oe>Re&&Z.charCodeAt(Oe-1)<=32)Oe--;if(Re<Oe)b.add(Z.slice(Re,Oe));re=X+1}}let H=U+q;if(!R.has(H))if(R.add(H),H.includes("export type"))C.push(H);else T.push(H)}}let I=new Map;if(o.length>0)for(let F of o){let U=Jd(F.text);for(let q of U)I.set(q,F)}let _=new Set;if(f.length>0){let F=[];for(let U of a)if(U.isExported)F.push(U.text);for(let U of l)F.push(U.text);for(let U of u)F.push(U.text);if(F.length>0){let U=Nl(F.join(`
|
|
217
|
+
`));for(let q of f)if(U.has(q.name))_.add(q.name)}}let L=[];if(o.length>0){let F=new Set,U=[];for(let H of a)if(H.isExported)U.push(H.text);for(let H of c)if(U.push(H.text),H.typeAnnotation)U.push(H.typeAnnotation);else if(H.isExported&&H.value)U.push(Dl(H,!1));for(let H of f)if(H.isExported||_.has(H.name))U.push(H.text);for(let H of u)U.push(H.text);for(let H of l)U.push(H.text);for(let H of g)U.push(H.text);for(let H of d)U.push(H.text);for(let H of v)U.push(H.text);let q=U.join(`
|
|
218
|
+
`);if(q&&I.size>0){let H=Nl(q);for(let Z of I.keys())if(H.has(Z))F.add(Z)}for(let H of b)if(I.has(H))F.add(H);for(let H of o){if(H.isSideEffect){let ae=H.text.trim(),Q=ae.endsWith(";")?ae:`${ae};`;L.push(Q);continue}let Z=zd(H.text);if(!Z)continue;let{defaultName:re,namedItems:X,source:Re,isTypeOnly:Oe,isNamespace:Dt}=Z,ke=re?F.has(re):!1,Me="",ft=0;for(let ae=0;ae<X.length;ae++){let Q=X[ae],It=Q.charCodeAt(0)===116&&Q.startsWith("type ")?Q.slice(5).trim():Q.trim(),nr=It.indexOf(" as ");if(nr!==-1)It=It.slice(nr+4).trim();if(F.has(It)){if(ft>0)Me+=", ";Me+=Q,ft++}}if(ke||ft>0){let ae=Oe?"import type ":"import ";if(ke&&re)if(Dt)ae+=`* as ${re}`;else ae+=ft>0?`${re}, { ${Me} }`:re;else if(ft>0)ae+=`{ ${Me} }`;ae+=` from '${Re}';`,L.push(ae)}}let oe=n.length;if(L.length>1){if(Ll!==n)Ll=n,Wl=n.map((X)=>`from '${X}`),Bl=n.map((X)=>`from "${X}`);let H=Wl,Z=Bl,re=new Map;for(let X of L){let Re=oe;for(let Oe=0;Oe<n.length;Oe++)if(X.includes(H[Oe])||X.includes(Z[Oe])){Re=Oe;break}re.set(X,Re)}L.sort((X,Re)=>{let Oe=re.get(X),Dt=re.get(Re);return Oe!==Dt?Oe-Dt:X.localeCompare(Re)})}}for(let F=0;F<L.length;F++){if(i)i+=`
|
|
219
|
+
`;i+=L[F]}for(let F=0;F<C.length;F++){if(i)i+=`
|
|
220
|
+
`;i+=C[F]}let P=[a,c,f,u,l,g,d];for(let F=0;F<P.length;F++){let U=P[F];for(let q=0;q<U.length;q++){let oe=U[q],H="",Z=oe.kind;switch(Z){case"function":H=Gd(oe,r);break;case"variable":H=Dl(oe,r);break;case"interface":H=jd(oe,r);break;case"type":H=_d(oe,r);break;case"class":H=Vd(oe,r);break;case"enum":H=Ud(oe,r);break;case"module":case"namespace":H=Kd(oe,r);break;case"import":case"export":case"unknown":break;default:Fl(Z,`Unhandled declaration kind in processor: ${Z}`)}if(H){if(i)i+=`
|
|
221
221
|
`;i+=H}}}for(let F=0;F<T.length;F++){if(i)i+=`
|
|
222
222
|
`;i+=T[F]}for(let F=0;F<k.length;F++){if(i)i+=`
|
|
223
223
|
`;i+=k[F]}if(!i&&(o.length>0||v.length>0))return"export {};";return i}var Mt,qd,Yd,Zd,em,Ll=null,Wl,Bl;var jl=ce(()=>{Ml();dn();Mt=new Map;qd=/^\/\/\/\s*<reference\s+(?:path|types|lib|no-default-lib)\s*=\s*["'][^"']+["']\s*\/>/,Yd=/^\/\/\/\s*<amd-module\s+name\s*=\s*["'][^"']+["']\s*\/>/,Zd=/^\/\/\/\s*<amd-dependency\s+path\s*=\s*["'][^"']+["']/;em=/export\s+(?:type\s+)?\{\s*([^}]+)\s*\}/,Wl=[],Bl=[]});import{existsSync as _l}from"fs";import{mkdir as hs,readdir as tm,realpath as rm,rm as im}from"fs/promises";import{availableParallelism as nm}from"os";import{basename as Hl,dirname as Ar,extname as sm,isAbsolute as $r,parse as om,relative as Le,resolve as ze}from"path";async function Vl(e,t,r,n,i){let s=Hl(e)||"output.d.ts",o=Le(Ar(e),t),a=`${s}.map`,c=r.lastIndexOf(`
|
|
224
|
-
${us()}`),f=c===-1?r:r.slice(0,c),u=
|
|
225
|
-
${X}`);else K.debug(`[no changes] ${
|
|
226
|
-
...`:"")),K.debug("--- End preview ---")};if(s){let Z=s.getCachedIfValid(C,r.cwd);if(Z){await I(Z);let re=
|
|
227
|
-
`);if(r.failOnUnresolvedReExport)throw Error(k);K.warn(k),K.warn('Generated .d.ts files reference modules that were not emitted \u2014 consumers will see "has no exported member" errors.')}}if(r.bundle&&(o.filesGenerated>0||a>0)&&c.length>0)try{K.debug("Bundling declarations...");let C=new Map,T=async(
|
|
224
|
+
${us()}`),f=c===-1?r:r.slice(0,c),u=Rl(f,s,o,n),l=`${e}.map`;return await br(l,JSON.stringify(u)),K.debug(` Generated source map: ${Le(i,l)}`),a}async function ps(e){let t=Date.now(),r={...qa,...e};if(r.logLevel)wn(r.logLevel);else if(r.verbose)wn("debug");let n=new Ni;if(r.plugins&&r.plugins.length>0){for(let C of r.plugins)n.register(C),K.debug(`Registered plugin: ${C.name}`);r=await n.runOnStart(r)}if(await lm(r),r.isolatedDeclarations===void 0)r.isolatedDeclarations=await xl(r);let i=r.typeMappings?Li(r.typeMappings):void 0,s=null;if(r.incremental){if(s=new Cn(r),r.clearCache){if(K.debug("Clearing build cache..."),!r.dryRun)s.clear()}else if(s.load()){let C=s.getStats();K.debug(`Loaded build cache with ${C.entries} entries`)}else K.debug("No existing build cache found, starting fresh");if(!r.dryRun)wo(r.cwd)}let o={generationMode:r.isolatedDeclarations?"isolated":"semantic",filesProcessed:0,filesGenerated:0,filesFailed:0,filesValidated:0,validationErrors:0,declarationsFound:0,importsProcessed:0,exportsProcessed:0,durationMs:0,errors:[]},a=0;if(K.debug("Starting DTS generation..."),K.debug(`Using ${o.generationMode} declaration generation path`),K.debug("Config:",r),r.clean&&!r.dryRun)await fm(r);let c=await dm(r);hm(r,c);let f=c.slice(),u=null;if(r.autoIncludeReExports!==!1&&f.length>0){u=await cs(f,{includeImports:!0});let C=ze(r.cwd,r.root),T=r.exclude||[],k=[];for(let R of u.reachable){if(f.includes(R))continue;if(!ms(R))continue;if(R.endsWith(".d.ts"))continue;if(R.includes("node_modules"))continue;if(!xr(R,C)){K.warn(`Skipping auto-included source outside root: ${Le(r.cwd,R)}`);continue}if(ds(R,T,C))continue;k.push(R)}if(k.length>0)f=[...f,...k],K.debug(`Auto-included ${k.length} file(s) reached via relative re-exports`)}if(mm(f,r),s&&!r.dryRun){let C=s.prune(new Set(f),r.cwd);if(C>0)K.debug(`Pruned ${C} deleted files from cache`)}if(K.debug(`Found ${f.length} TypeScript files`),r.progress&&f.length>0){let C=r.parallel?"parallel":"sequential";K.info(`Processing ${f.length} files (${C})...`)}let l=async(C,T)=>{let k;try{let R=Tr(C,r),I=async(Z)=>{if(!r.diff)return;try{let re=await ht(R),X=Pl(re,Z,Le(r.cwd,R));if(X)K.info(`
|
|
225
|
+
${X}`);else K.debug(`[no changes] ${R}`)}catch{K.info(`[new file] ${Le(r.cwd,R)}`)}},_=(Z)=>{if(!r.validate)return 0;let re=Tl(Z,R);if(re.isValid)return K.debug(`[validation] ${R} - OK`),0;K.warn(`[validation] ${Le(r.cwd,R)} has ${re.errors.length} error(s):`);for(let X of re.errors){let Re=` Line ${X.line}:${X.column}`;if(X.code)Re+=` [${X.code}]`;if(Re+=` - ${X.message}`,K.warn(Re),X.suggestion)K.warn(` Suggestion: ${X.suggestion}`)}return re.errors.length},L=(Z)=>{K.info(`[dry-run] Would generate: ${R}`),K.debug("--- Content preview ---"),K.debug(Z.slice(0,500)+(Z.length>500?`
|
|
226
|
+
...`:"")),K.debug("--- End preview ---")};if(s){let Z=s.getCachedIfValid(C,r.cwd);if(Z){await I(Z);let re=_(Z);if(r.dryRun)L(Z);else{if(await hs(Ar(R),{recursive:!0}),r.declarationMap)k=T??await ht(C),await Vl(R,C,Z,k,r.cwd);await br(R,Z,r.lineEnding)}return K.debug(`[cached] ${Le(r.cwd,R)}`),{success:!0,file:C,declarationCount:0,importCount:0,exportCount:0,cached:!0,validationErrorCount:re}}}k=T??await ht(C);let{content:P,declarationCount:F,importCount:U,exportCount:q}=await ym(C,k,r,n,i),oe=P;if(r.prettier||r.indentStyle||r.indentSize){let Z=await el(oe,{usePrettier:r.prettier,builtIn:{indentSize:r.indentSize||2,useTabs:r.indentStyle==="tabs",normalizeWhitespace:!0,sortImports:!0,trailingNewline:!0}},R);oe=Z.content;for(let re of Z.warnings??[])K.warn(`[format] ${re}`)}if(r.declarationMap){let Z=`${Hl(R)||"output.d.ts"}.map`;oe=Ol(oe,Z)}await I(oe);let H=_(oe);if(r.dryRun)L(oe);else{if(await hs(Ar(R),{recursive:!0}),r.declarationMap&&k)await Vl(R,C,oe,k,r.cwd);if(await br(R,oe,r.lineEnding),s&&k)s.update(C,k,oe,r.cwd);K.debug(`Generated: ${R}`)}return{success:!0,file:C,declarationCount:F,importCount:U,exportCount:q,validationErrorCount:H}}catch(R){let I=Za(R,C,k);if(r.plugins&&r.plugins.length>0)await n.runOnError(R instanceof Error?R:Error(String(R)),C,k||"");return{success:!1,file:C,declarationCount:0,importCount:0,exportCount:0,dtsError:I,validationErrorCount:0}}},g=r.parallel||r.parallel!==!1&&f.length>=10,d=Rs(r.concurrency,nm?.()??8),v=new Map;if(g&&f.length>1){let C=f.map(async(T)=>{try{let k=await ht(T);return{file:T,source:k}}catch{return{file:T,source:null}}});for(let T of await Promise.all(C))if(T.source!==null)v.set(T.file,T.source)}let b=(C)=>{if(o.filesProcessed++,C.success){if(C.cached)a++;else o.filesGenerated++,o.declarationsFound+=C.declarationCount,o.importsProcessed+=C.importCount,o.exportsProcessed+=C.exportCount;if(r.validate){if(o.filesValidated++,C.validationErrorCount)o.validationErrors+=C.validationErrorCount}}else if(o.filesFailed++,C.dtsError){o.errors.push(C.dtsError);let T=Xa(C.dtsError);if(r.continueOnError)K.warn(T);else throw K.error(T),Error(C.dtsError.message)}};if(g)for(let C=0;C<f.length;C+=d){let T=f.slice(C,C+d),k=await Promise.all(T.map((R)=>l(R,v.get(R))));for(let R of k)b(R);if(r.progress){let R=Math.round(o.filesProcessed/f.length*100);K.info(`[${o.filesProcessed}/${f.length}] ${R}%`)}}else for(let C of f){let T=await l(C);if(b(T),r.progress){let k=Math.round(o.filesProcessed/f.length*100),R=T.cached?"[cached]":"";K.info(`[${o.filesProcessed}/${f.length}] ${k}% - ${Le(r.cwd,C)} ${R}`)}}if(s&&!r.dryRun)s.save(),K.debug("Saved build cache");if(!r.bundle){let C=[];if(u)for(let T of u.unresolved)C.push({from:T.from,specifier:T.specifier,reason:"missing"});if(r.autoIncludeReExports===!1&&f.length>0){let T=new Set(f);for(let k of f){let R;try{R=await ht(k)}catch{continue}for(let I of ls(R)){if(!I.specifier.startsWith("."))continue;let _=Fi(I.specifier,k);if(!_.resolved)C.push({from:k,specifier:I.specifier,reason:"missing"});else if(!/\.d\.(?:ts|mts|cts)$/.test(_.resolved)&&!T.has(_.resolved))C.push({from:k,specifier:I.specifier,reason:"not-emitted"})}}}if(C.length>0){let T=[];T.push(`Found ${C.length} re-export(s) pointing at siblings that won't be in the output:`);for(let R of C){let I=Le(r.cwd,R.from);if(R.reason==="missing")T.push(` ${I} \u2192 '${R.specifier}' (path not found on disk)`);else T.push(` ${I} \u2192 '${R.specifier}' (resolved but not in entrypoints; set autoIncludeReExports: true or add to entrypoints)`)}let k=T.join(`
|
|
227
|
+
`);if(r.failOnUnresolvedReExport)throw Error(k);K.warn(k),K.warn('Generated .d.ts files reference modules that were not emitted \u2014 consumers will see "has no exported member" errors.')}}if(r.bundle&&(o.filesGenerated>0||a>0)&&c.length>0)try{K.debug("Bundling declarations...");let C=new Map,T=async(R)=>{let I=C.get(R);if(I!==void 0)return I;return I=await ht(R),C.set(R,I),I};for(let R of f)await T(R);let k=c.length===1&&!!r.bundleOutput;for(let R of c){let I=await cs([R],{includeImports:!0}),_=new Set;for(let q of I.reachable){if(q.endsWith(".d.ts"))continue;if(q.includes("node_modules"))continue;_.add(q)}let L=f.filter((q)=>_.has(q));if(!L.includes(R))L.push(R);let P=new Map;for(let q of L){let oe=C.get(q)??await T(q);P.set(q,oe)}let F=await uo(L,P,r),U=k?ze(r.cwd,r.outdir,r.bundleOutput):Tr(R,r);if(r.dryRun)K.info(`[dry-run] Would bundle ${F.files.length} files to: ${Le(r.cwd,U)}`);else await hs(Ar(U),{recursive:!0}),await br(U,F.content,r.lineEnding),K.info(`Bundled ${F.files.length} files to: ${Le(r.cwd,U)}`);if(k)break}}catch(C){let T=C instanceof Error?C.message:String(C);K.error(`Bundle failed: ${T}`)}if(o.durationMs=Date.now()-t,r.stats)if(r.outputFormat==="json")console.log(JSON.stringify(o,null,2));else{if(K.info(`
|
|
228
228
|
--- Generation Statistics ---`),K.info(`Files processed: ${o.filesProcessed}`),K.info(`Files generated: ${o.filesGenerated}`),a>0)K.info(`Files cached: ${a}`);if(o.filesFailed>0)K.info(`Files failed: ${o.filesFailed}`);if(K.info(`Declarations found: ${o.declarationsFound}`),K.info(`Imports processed: ${o.importsProcessed}`),K.info(`Exports processed: ${o.exportsProcessed}`),o.filesValidated>0){if(K.info(`Files validated: ${o.filesValidated}`),o.validationErrors>0)K.info(`Validation errors: ${o.validationErrors}`)}if(K.info(`Duration: ${o.durationMs}ms`),o.errors.length>0){K.info(`
|
|
229
229
|
Errors:`);for(let C of o.errors){let T=` - ${C.file}`;if(C.location)T+=`:${C.location.line}:${C.location.column}`;if(C.code)T+=` [${C.code}]`;if(T+=`: ${C.message}`,K.info(T),C.suggestion)K.info(` Suggestion: ${C.suggestion}`)}}K.info(`-----------------------------
|
|
230
230
|
`)}if(r.plugins&&r.plugins.length>0)await n.runOnEnd(o);return K.debug("DTS generation complete!"),o}async function Ul(e){try{return await rm(e)}catch{return ze(e)}}async function lm(e){let t=ze(e.cwd,e.outdir);if(e.bundle&&e.bundleOutput){if($r(e.bundleOutput))throw Error("bundleOutput must be relative to outdir");let i=ze(t,e.bundleOutput);if(!xr(i,t))throw Error("bundleOutput must stay within outdir")}if(!e.clean||e.dryRun)return;if(t===om(t).root)throw Error("Refusing to clean declarations from the filesystem root");let[r,n]=await Promise.all([Ul(t),Ul(ze(e.cwd,e.root))]);if(xr(n,r))throw Error("Refusing to clean an outdir that contains the source root")}function cm(e){let t=Sr.get(e);if(!t){if(t=new Kl(e),Sr.set(e,t),Sr.size>am){let r=Sr.keys().next().value;if(r!==void 0)Sr.delete(r)}}return t}async function fm(e){let t=ze(e.cwd,e.outdir);async function r(n){let i;try{i=await tm(n,{withFileTypes:!0})}catch{return}await Promise.all(i.map(async(s)=>{let o=ze(n,s.name);if(s.isDirectory()){await r(o);return}if(s.name.endsWith(".d.ts")||s.name.endsWith(".d.mts")||s.name.endsWith(".d.cts")||s.name.endsWith(".d.ts.map")||s.name.endsWith(".d.mts.map")||s.name.endsWith(".d.cts.map"))await im(o,{force:!0})}))}await r(t)}function ds(e,t,r){if(!t||t.length===0)return!1;let n=Le(r,e);for(let i of t){let s=cm(i);if(s.match(n)||s.match(e))return!0}return!1}function hm(e,t){let r=ze(e.cwd,e.root),n=` root: ${r}
|
|
@@ -232,6 +232,6 @@ Errors:`);for(let C of o.errors){let T=` - ${C.file}`;if(C.location)T+=`:${C.lo
|
|
|
232
232
|
`+(e.exclude?.length?` exclude: ${e.exclude.map((s)=>JSON.stringify(s)).join(", ")}
|
|
233
233
|
`:"")+"Entrypoints are resolved relative to --root. Pass several by repeating --entrypoints or separating them with commas.";if(t.length===0){if(e.entrypoints.filter((s)=>$r(s)&&_l(s)&&!xr(s,r)).length===e.entrypoints.length)return;throw Error(`No source files matched. Nothing was generated.
|
|
234
234
|
${n}`)}let i=e.entrypoints.filter((s)=>{if(um.test(s))return!1;return!_l($r(s)?s:ze(r,s))});if(i.length>0)throw Error(`Entrypoint${i.length>1?"s":""} not found: ${i.map((s)=>JSON.stringify(s)).join(", ")}
|
|
235
|
-
${n}`)}async function dm(e){let t=[],r=ze(e.cwd,e.root),n=e.exclude||[],i=[...e.entrypoints,...e.include??[]];for(let s of i)if($r(s)&&ms(s)){if(!s.includes("node_modules")){if(!xr(s,r)&&e.outputStructure!=="flat")K.warn(`Skipping entrypoint outside root: ${Le(e.cwd,s)}`);else if(!ds(s,n,r))t.push(s)}}else{let o=new Kl(s);for await(let a of o.scan({cwd:r,absolute:!0,onlyFiles:!0}))if(ms(a)&&!a.includes("node_modules")){if(!ds(a,n,r))t.push(a)}}return[...new Set(t)].sort()}function xr(e,t){let r=Le(t,e);return r!==".."&&!r.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!$r(r)}function mm(e,t){let r=new Map;for(let n of e){let i=Tr(n,t),s=r.get(i);if(s&&s!==n)throw Error(`Output path collision: ${Le(t.cwd,s)} and ${Le(t.cwd,n)} both emit ${Le(t.cwd,i)}`);r.set(i,n)}}function ms(e){return/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/.test(e)&&!/\.d\.(?:ts|mts|cts)$/.test(e)}function Tr(e,t){let r=ze(t.cwd,t.root),n=Le(r,e).replace(/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/,(i)=>{if(i===".mts"||i===".mjs")return".d.mts";if(i===".cts"||i===".cjs")return".d.cts";return".d.ts"});if(t.outputStructure==="mirror")return ze(t.cwd,t.outdir,n);else{let i=n.split("/").pop();return ze(t.cwd,t.outdir,i)}}function pm(e,t,r=""){let n=Le(Ar(e),t).replace(/\\/g,"/");if(n=n.replace(/\.d\.mts$/,"").replace(/\.d\.cts$/,"").replace(/\.d\.ts$/,""),r)n+=r;if(!n.startsWith("."))n=`./${n}`;return n}function gm(e,t,r){let n=Tr(t,r),i=(s)=>{let o=Fi(s,t);if(!o.isRelative||!o.resolved)return s;if(/\.d\.(?:ts|mts|cts)$/.test(o.resolved))return s;let a=s.match(/[?#].*$/)?.[0]??"",c=a?s.slice(0,-a.length):s,f=sm(c),u=/^(?:\.js|\.jsx|\.mjs|\.cjs)$/.test(f)?f:"";return pm(n,Tr(o.resolved,r),u)+a};return e.replace(/\b(from\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,o,a,c)=>`${o}${a}${i(c)}${a}`).replace(/\b(import\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,o,a,c)=>`${o}${a}${i(c)}${a}`).replace(/\b(import\s*\(\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,o,a,c)=>`${o}${a}${i(c)}${a}`)}async function ym(e,t,r,n,i){let s=t;if(n)s=await n.runOnBeforeFile(e,t);let o=Ur(s,e,r.keepComments,r.isolatedDeclarations??!1);if(n)o=await n.runOnDeclarations(e,s,o);let a=0,c=0;for(let u=0;u<o.length;u++){let l=o[u];if(l.kind==="import")a++;if(l.kind==="export"||l.isExported)c++}let f=Gl(o,{filePath:e,sourceCode:s,declarations:o},r.keepComments,r.importOrder);if(f=gm(f,e,r),i)f=dl(f,i,{filePath:e});if(r.normalizeOutput===!0||r.declarationOrder)f=cl(f,{lineEnding:"lf",declarationOrder:r.declarationOrder,indent:{style:r.indentStyle??"spaces",size:r.indentSize??2}});if(n)f=await n.runOnAfterFile(e,s,f);return{content:f,declarationCount:o.length,importCount:a,exportCount:c}}var Kl,am=50,Sr,um;var zl=ce(()=>{
|
|
235
|
+
${n}`)}async function dm(e){let t=[],r=ze(e.cwd,e.root),n=e.exclude||[],i=[...e.entrypoints,...e.include??[]];for(let s of i)if($r(s)&&ms(s)){if(!s.includes("node_modules")){if(!xr(s,r)&&e.outputStructure!=="flat")K.warn(`Skipping entrypoint outside root: ${Le(e.cwd,s)}`);else if(!ds(s,n,r))t.push(s)}}else{let o=new Kl(s);for await(let a of o.scan({cwd:r,absolute:!0,onlyFiles:!0}))if(ms(a)&&!a.includes("node_modules")){if(!ds(a,n,r))t.push(a)}}return[...new Set(t)].sort()}function xr(e,t){let r=Le(t,e);return r!==".."&&!r.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!$r(r)}function mm(e,t){let r=new Map;for(let n of e){let i=Tr(n,t),s=r.get(i);if(s&&s!==n)throw Error(`Output path collision: ${Le(t.cwd,s)} and ${Le(t.cwd,n)} both emit ${Le(t.cwd,i)}`);r.set(i,n)}}function ms(e){return/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/.test(e)&&!/\.d\.(?:ts|mts|cts)$/.test(e)}function Tr(e,t){let r=ze(t.cwd,t.root),n=Le(r,e).replace(/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/,(i)=>{if(i===".mts"||i===".mjs")return".d.mts";if(i===".cts"||i===".cjs")return".d.cts";return".d.ts"});if(t.outputStructure==="mirror")return ze(t.cwd,t.outdir,n);else{let i=n.split("/").pop();return ze(t.cwd,t.outdir,i)}}function pm(e,t,r=""){let n=Le(Ar(e),t).replace(/\\/g,"/");if(n=n.replace(/\.d\.mts$/,"").replace(/\.d\.cts$/,"").replace(/\.d\.ts$/,""),r)n+=r;if(!n.startsWith("."))n=`./${n}`;return n}function gm(e,t,r){let n=Tr(t,r),i=(s)=>{let o=Fi(s,t);if(!o.isRelative||!o.resolved)return s;if(/\.d\.(?:ts|mts|cts)$/.test(o.resolved))return s;let a=s.match(/[?#].*$/)?.[0]??"",c=a?s.slice(0,-a.length):s,f=sm(c),u=/^(?:\.js|\.jsx|\.mjs|\.cjs)$/.test(f)?f:"";return pm(n,Tr(o.resolved,r),u)+a};return e.replace(/\b(from\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,o,a,c)=>`${o}${a}${i(c)}${a}`).replace(/\b(import\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,o,a,c)=>`${o}${a}${i(c)}${a}`).replace(/\b(import\s*\(\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,o,a,c)=>`${o}${a}${i(c)}${a}`)}async function ym(e,t,r,n,i){let s=t;if(n)s=await n.runOnBeforeFile(e,t);let o=Ur(s,e,r.keepComments,r.isolatedDeclarations??!1);if(n)o=await n.runOnDeclarations(e,s,o);let a=0,c=0;for(let u=0;u<o.length;u++){let l=o[u];if(l.kind==="import")a++;if(l.kind==="export"||l.isExported)c++}let f=Gl(o,{filePath:e,sourceCode:s,declarations:o},r.keepComments,r.importOrder);if(f=gm(f,e,r),i)f=dl(f,i,{filePath:e});if(r.normalizeOutput===!0||r.declarationOrder)f=cl(f,{lineEnding:"lf",declarationOrder:r.declarationOrder,indent:{style:r.indentStyle??"spaces",size:r.indentSize??2}});if(n)f=await n.runOnAfterFile(e,s,f);return{content:f,declarationCount:o.length,importCount:a,exportCount:c}}var Kl,am=50,Sr,um;var zl=ce(()=>{Os();pn();mo();vo();Jr();Ya();$o();Qa();tl();sl();ol();fl();ml();kl();jl();({Glob:Kl}=globalThis.Bun);Sr=new Map;um=/[*?[\]{}!]/});var Jl=ce(()=>{zl()});import{createHash as wm}from"crypto";import{existsSync as vm,readFileSync as Em,writeFileSync as bm}from"fs";import{dirname as Sm,join as Am,relative as ql,resolve as Pr,sep as Wi}from"path";import Zl from"process";class Xl{listeners=new Map;on(e,t){let r=this.listeners.get(e)||[];r.push(t),this.listeners.set(e,r)}async emit(e,t){let r={type:e,timestamp:Date.now(),data:t},n=this.listeners.get(e)||[];for(let i of n)await i(r)}}class Ql{manifest;cacheDir;manifestPath;constructor(e,t){this.cacheDir=e,this.manifestPath=Am(e,"manifest.json"),this.manifest=this.loadManifest(t)}loadManifest(e){try{if(vm(this.manifestPath)){let t=JSON.parse(Em(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}=Cm("fs");e(this.cacheDir,{recursive:!0}),bm(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 $m(e){let t={root:e.root,outdir:e.outdir,entrypoints:e.entrypoints,clean:e.clean,tsconfigPath:e.tsconfigPath};return wm("md5").update(JSON.stringify(t)).digest("hex")}function ec(e={}){let{onSuccess:t,onError:r,failOnError:n=!0,incremental:i=!1,cacheDir:s=".dtsx-cache",on:o,timeout:a=60000,continueOnError:c=!1,verbose:f=!1,...u}=e,l=new Xl;if(o){for(let[g,d]of Object.entries(o))if(d)l.on(g,d)}return{name:"bun-plugin-dtsx",async setup(g){let d=Date.now(),v=null,b=0;try{let C=Pm(u,g),T=$m(C);if(C.clean){let _=Pr(C.cwd??Zl.cwd(),C.outdir??"./dist");if(Yl.has(_))C.clean=!1;else Yl.add(_)}if(i)v=new Ql(Pr(s),T);if(await l.emit("start",{type:"start",files:C.entrypoints||[],config:C}),f){if(console.log("[bun-plugin-dtsx] Starting declaration generation..."),i)console.log("[bun-plugin-dtsx] Incremental mode enabled")}let R=await(async()=>new Promise((_,L)=>{let P=setTimeout(()=>{L(new Rr(`Generation timed out after ${a}ms`,"TIMEOUT_ERROR",{timeout:a}))},a);ps(C).then((F)=>{clearTimeout(P),_(F)}).catch((F)=>{clearTimeout(P),L(F)})}))(),I=Date.now()-d;if(v)v.save();if(await l.emit("complete",{type:"complete",stats:R,duration:I,fromCache:b}),f){if(console.log(`[bun-plugin-dtsx] Generation complete in ${I}ms`),b>0)console.log(`[bun-plugin-dtsx] ${b} files served from cache`)}if(t)await t(R)}catch(C){let T=xm(C);if(await l.emit("error",{type:"error",error:T}),r)await r(T);else{if(console.error("[bun-plugin-dtsx] Error generating declarations:"),console.error(` Code: ${T.code}`),console.error(` Message: ${T.message}`),T.context)console.error(` Context: ${JSON.stringify(T.context)}`);if(f&&T.stack)console.error(` Stack: ${T.stack}`)}if(n&&!c)throw T}}}}function xm(e){if(e instanceof Rr)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 Rr(e.message,t,{originalError:e.name},e)}return new Rr(String(e),"GENERATION_ERROR")}function Tm(e){let t=e.map((n)=>Sm(n).split(Wi)),r=t[0];for(let n of t.slice(1)){let i=0;while(i<r.length&&i<n.length&&r[i]===n[i])i++;r=r.slice(0,i)}return r.join(Wi)||Wi}function Pm(e,t){let r=e.cwd||Zl.cwd(),n=t?.config?.entrypoints,i=e.outdir||e.build?.config.outdir||t?.config.outdir||"./dist",s=e.root||e.build?.config.root||t?.config.root;if(!s&&n?.length){let a=Tm(n.map((c)=>Pr(r,c)));s=ql(r,a)||"."}s=s||"./src";let o=e.entrypoints;if(!o)if(n?.length){let a=Pr(r,s),c=[];for(let f of n){let u=Pr(r,f);if(u===a||u.startsWith(a+Wi))c.push(ql(a,u));else console.warn(`[bun-plugin-dtsx] Skipping entrypoint outside root "${s}": ${f}`)}o=c.length?c:["index.ts"]}else o=["index.ts"];return{...e,cwd:r,root:s,entrypoints:o,outdir:i,clean:e.clean??!0,tsconfigPath:e.tsconfigPath}}var Cm,Rr,Yl;var tc=ce(()=>{Jl();Cm=import.meta.require;Rr=class Rr extends Error{code;context;cause;constructor(e,t,r,n){super(e);if(this.name="DtsxPluginError",this.code=t,this.context=r,this.cause=n,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,context:this.context,stack:this.stack}}};Yl=new Set});import{mkdir as Rm,stat as Om}from"fs/promises";import{bold as gs,dim as ys,green as km,italic as rc,log as Mm}from"@stacksjs/cli";import{path as nt}from"@stacksjs/path";import{glob as ic}from"@stacksjs/storage";async function Dm(e){let t=await ic([nt.resolve(e,"dist","**/*.d.ts")],{absolute:!0}),r=new Bun.Transpiler({loader:"ts",target:"bun"});for(let n of t){let i=await Bun.file(n).text();try{r.transformSync(i)}catch(s){throw Error(`Invalid declaration generated at ${n}: ${s instanceof Error?s.message:String(s)}`)}}}async function Im(e){let t=nt.resolve(e,"dist","index.js");if(!await Bun.file(t).exists())return;let r=Bun.spawnSync({cmd:[process.execPath,"-e",`await import(${JSON.stringify(t)})`],stdout:"ignore",stderr:"pipe",env:{...process.env,NODE_ENV:"test"}});if(r.exitCode===0)return;let n=new TextDecoder().decode(r.stderr??new Uint8Array);if(/needs to refer to a top-level declared variable|does not provide an export named|Export named .* not found/i.test(n))throw Error(`Built package at ${t} cannot be imported: ${n.trim().split(`
|
|
236
236
|
`)[0]}
|
|
237
|
-
This is the minified-barrel failure. Build with \`transpilePackage\` instead of a minifying \`Bun.build\`.`)}async function
|
|
237
|
+
This is the minified-barrel failure. Build with \`transpilePackage\` instead of a minifying \`Bun.build\`.`)}async function P0(e){let r=Date.now()-e.startTime,n=e.pkgName??`@stacksjs/${nt.basename(e.dir)}`;if(e.result.errors&&e.result.errors.length>0)throw console.error("Build errors:",e.result.errors),Error(`Build failed with errors: ${JSON.stringify(e.result.errors)}`);else if(e.result.success!==void 0&&!e.result.success){let s=e.result.logs?.[0]||"Unknown build error";throw console.log(s),Error(`Build failed: ${s}`)}await Dm(e.dir),await Im(e.dir);let i=await ic([nt.resolve(e.dir,"dist","**/*")],{absolute:!0});for(let s of i){let o=await Om(s),a;if(o.size<1048576)a=`${(o.size/1024).toFixed(2)}kb`;else a=`${(o.size/1024/1024).toFixed(2)}mb`;let c=nt.relative(e.dir,s).replace("dist/","");console.log(`${gs(ys(`[${a}]`))} ${ys("dist/")}${c}`)}console.log(`${gs(ys(`[${r}ms]`))} Built ${rc(gs(km(n)))}`)}async function R0(e){let t=e.pkgName??`@stacksjs/${nt.basename(e.dir)}`;if(e.styled===!1)console.log(`Building ${t}...`);else Mm.info(`Building ${rc(t)}...`);return{startTime:Date.now()}}async function O0(e){await Promise.resolve().then(() => tc());let r=nt.resolve(e.dir,"src"),n=nt.resolve(e.dir,"dist"),i=(await Array.fromAsync(new Bun.Glob("**/*.ts").scan({cwd:r}))).filter((o)=>!o.endsWith(".d.ts")).filter((o)=>!o.endsWith(".test.ts")&&!o.endsWith(".spec.ts"));await Bun.build({entrypoints:i.map((o)=>nt.resolve(r,o)),outdir:n,root:r,target:"bun",format:"esm",splitting:!1,external:e.external??Fm(),plugins:[ec({root:r,outdir:n})]});let s=new Bun.Transpiler({loader:"ts",target:"bun",minifyWhitespace:!0});for(let o of i){let a=s.transformSync(await Bun.file(nt.resolve(r,o)).text());a=a.replace(/(['"])(\.\.?\/[^'"]+?)\.tsx?\1/g,"$1$2.js$1");let c=nt.resolve(n,o.replace(/\.ts$/,".js"));await Rm(nt.dirname(c),{recursive:!0}),await Bun.write(c,a)}}function Fm(e=[]){let t=[];try{let r=dc("fs"),n=JSON.parse(r.readFileSync(`${process.cwd()}/package.json`,"utf8"));t=[...Object.keys(n.dependencies??{}),...Object.keys(n.peerDependencies??{}),...Object.keys(n.optionalDependencies??{})]}catch{}return["@stacksjs/*",...t,...t.map((r)=>`${r}/*`),"bun-queue","ioredis","localtunnels","localtunnels/*","@craft-native/ts","ts-md","meilisearch","algoliasearch","@opensearch-project/opensearch","*.yaml","*.yml",...e]}export{Fm as frameworkExternal,R0 as intro,P0 as outro,O0 as transpilePackage,Dm as validateDeclarations,Im as validateRuntimeExports};
|