// @bun
import{ec as u}from"./chunk-b0bkjk0p.js";import{hc as TY}from"./chunk-94h87sgb.js";import{kc as XJ}from"./chunk-50hbgzrj.js";import{Bc as gJ}from"./chunk-pdvve1gm.js";import{Tc as m}from"./chunk-365avtde.js";import{Vc as W,Xc as n}from"./chunk-57agx6g8.js";import{ad as kY,cd as BJ}from"./chunk-ns3hznyf.js";var{Glob:pJ}=globalThis.Bun;import{mkdir as i}from"fs/promises";import{availableParallelism as FY}from"os";import{dirname as g,relative as S,resolve as y}from"path";import{existsSync as YJ,mkdirSync as sJ,readFileSync as aJ,writeFileSync as iJ}from"fs";import{dirname as nJ,relative as oJ,resolve as rJ}from"path";async function KJ(J,Y,$){let X=new Map,Z=[],Q=new Set,U=0,z=0,H=0;for(let q of J){let G=Y.get(q);if(!G)continue;let O=u(G,q,$.keepComments);U+=O.length;for(let V of O)if(V.kind==="import"){z++;let K=V.source||"";if(K.startsWith("."))continue;if(!X.has(K))X.set(K,{source:K,specifiers:new Map,isTypeOnly:V.isTypeOnly||!1,isSideEffect:V.isSideEffect||!1});let B=X.get(K);if(V.specifiers)for(let k of V.specifiers){let T=k.alias||k.name;if(!B.specifiers.has(T))B.specifiers.set(T,{name:k.name,alias:k.alias,isType:k.isType||!1})}if(!V.isTypeOnly)B.isTypeOnly=!1}else if(V.isExported||V.kind==="export"){if(H++,V.name&&Q.has(V.name))continue;if(V.name)Q.add(V.name);Z.push({declaration:V,file:q})}}let j=[];j.push("/**"),j.push(" * Bundled TypeScript declarations"),j.push(` * Generated from ${J.length} source files`),j.push(" */"),j.push("");let _=Array.from(X.values()).sort((q,G)=>{let O=$.importOrder||["bun"],V=O.findIndex((B)=>q.source.startsWith(B)),K=O.findIndex((B)=>G.source.startsWith(B));if(V!==-1&&K!==-1)return V-K;if(V!==-1)return-1;if(K!==-1)return 1;return q.source.localeCompare(G.source)});for(let q of _)if(q.isSideEffect)j.push(`import '${q.source}';`);else if(q.specifiers.size>0){let O=Array.from(q.specifiers.values()).map((K)=>{let B=K.isType?"type ":"";return K.alias?`${B}${K.name} as ${K.alias}`:`${B}${K.name}`}),V=q.isTypeOnly?"type ":"";j.push(`import ${V}{ ${O.join(", ")} } from '${q.source}';`)}if(_.length>0)j.push("");let A=new Map;for(let{declaration:q,file:G}of Z){if(!A.has(G))A.set(G,[]);A.get(G).push(q)}for(let[q,G]of A){let O=oJ($.cwd,q);j.push(`// From: ${O}`);for(let V of G){if($.keepComments&&V.leadingComments)for(let K of V.leadingComments)j.push(K);j.push(OJ(V))}j.push("")}let R=j.join(`
`);return{content:R,files:J,declarationCount:U,importCount:z,exportCount:H,size:Buffer.byteLength(R,"utf8"),warnings:[]}}function OJ(J){if(J.text){let $=J.text.trim();if(J.isExported&&!$.startsWith("export"))$=`export ${$}`;if(!$.endsWith(";")&&!$.endsWith("}"))$+=";";return $}let Y=[];if(J.isExported)Y.push("export");if(J.isDefault)Y.push("default");switch(J.kind){case"function":if(Y.push("declare function"),Y.push(J.name),J.generics)Y.push(J.generics);if(Y.push(`(${tJ(J.parameters)})`),J.returnType)Y.push(`: ${J.returnType}`);break;case"variable":if(Y.push("declare const"),Y.push(J.name),J.typeAnnotation)Y.push(`: ${J.typeAnnotation}`);break;case"interface":if(Y.push("interface"),Y.push(J.name),J.generics)Y.push(J.generics);if(J.extends)Y.push(`extends ${J.extends}`);if(Y.push("{"),J.members)for(let $ of J.members)Y.push(`  ${$.name}${$.typeAnnotation?`: ${$.typeAnnotation}`:""};`);Y.push("}");break;case"type":if(Y.push("type"),Y.push(J.name),J.generics)Y.push(J.generics);Y.push("="),Y.push(J.typeAnnotation||"unknown");break;case"class":if(Y.push("declare class"),Y.push(J.name),J.generics)Y.push(J.generics);if(J.extends)Y.push(`extends ${J.extends}`);if(J.implements&&J.implements.length>0)Y.push(`implements ${J.implements.join(", ")}`);if(Y.push("{"),J.members)for(let $ of J.members)Y.push(`  ${OJ($)}`);Y.push("}");break;case"enum":if(Y.push("declare enum"),Y.push(J.name),Y.push("{"),J.members){let $=J.members.map((X)=>X.value!==void 0?`${X.name} = ${X.value}`:X.name);Y.push(`  ${$.join(`,
  `)}`)}Y.push("}");break;default:return J.text||""}return Y.join(" ")}function tJ(J){if(!J||J.length===0)return"";return J.map((Y)=>{let $="";if(Y.rest)$+="...";if($+=Y.name,Y.optional)$+="?";if(Y.type)$+=`: ${Y.type}`;if(Y.defaultValue)$+=` = ${Y.defaultValue}`;return $}).join(", ")}async function AJ(J,Y={}){let $=[],X=new Map,Z=[],Q=[],U=new Set,z=0,H=0,j=0;for(let q of J){if(!YJ(q)){$.push(`File not found: ${q}`);continue}let G=aJ(q,"utf-8");Q.push(q);let O=G.split(`
`),V=[],K=0,B=!1;for(let k of O){let T=k.trim();if(!T&&!B)continue;if(T.startsWith("import ")){H++;let M=T.match(/import\s+(type\s+)?(?:\{([^}]+)\}|(\w+)|\*\s+as\s+(\w+))\s+from\s+['"]([^'"]+)['"]/);if(M){let[,N,L,D,GJ,F]=M;if(Y.externals?.some((o)=>F.startsWith(o))){Z.push(T);continue}if(F.startsWith("."))continue;if(!X.has(F))X.set(F,{source:F,specifiers:new Map,isTypeOnly:!!N,isSideEffect:!1});let HJ=X.get(F);if(L){let o=L.split(",").map((r)=>r.trim());for(let r of o){let[t,e]=r.split(/\s+as\s+/).map((lJ)=>lJ.trim()),WJ=t.startsWith("type "),JJ=WJ?t.replace("type ",""):t;HJ.specifiers.set(e||JJ,{name:JJ,alias:e!==JJ?e:void 0,isType:WJ})}}if(!N)HJ.isTypeOnly=!1}continue}if(/^(export\s+)?(declare\s+)?(interface|type|class|function|const|let|var|enum|namespace|module)\s/.test(T)){if(B=!0,V=[k],K=(k.match(/\{/g)||[]).length-(k.match(/\}/g)||[]).length,K===0&&(T.endsWith(";")||!T.includes("{"))){let M=p(T);if(!U.has(M)||!Y.mergeDuplicates){if(U.add(M),Z.push(k),z++,T.startsWith("export"))j++}B=!1,V=[]}}else if(B){if(V.push(k),K+=(k.match(/\{/g)||[]).length-(k.match(/\}/g)||[]).length,K<=0){let M=V.join(`
`),N=p(V[0]);if(!U.has(N)||!Y.mergeDuplicates){if(U.add(N),Z.push(M),z++,V[0].trim().startsWith("export"))j++}B=!1,V=[]}}else if(T.startsWith("export ")&&!T.includes("declare"))Z.push(k),j++}}let _=[];if(Y.banner)_.push(Y.banner),_.push("");if(Y.includeReferences&&Y.references){for(let q of Y.references)_.push(`/// <reference types="${q}" />`);_.push("")}let A=Array.from(X.values()).sort((q,G)=>q.source.localeCompare(G.source));for(let q of A)if(q.specifiers.size>0){let O=Array.from(q.specifiers.values()).map((K)=>{let B=K.isType?"type ":"";return K.alias?`${B}${K.name} as ${K.alias}`:`${B}${K.name}`}),V=q.isTypeOnly?"type ":"";_.push(`import ${V}{ ${O.join(", ")} } from '${q.source}';`)}if(A.length>0)_.push("");if(Y.ambient&&Y.moduleName){_.push(`declare module '${Y.moduleName}' {`);for(let q of Z){let G=q.split(`
`).map((O)=>`  ${O.replace(/^(\s*)(export\s+)?declare\s+/,"$1$2")}`).join(`
`);_.push(G)}_.push("}")}else{if(Y.sortDeclarations)Z.sort((q,G)=>{let O=p(q),V=p(G);return O.localeCompare(V)});for(let q of Z)_.push(q)}if(Y.footer)_.push(""),_.push(Y.footer);let R=_.join(`
`);return{content:R,files:Q,declarationCount:z,importCount:H,exportCount:j,size:Buffer.byteLength(R,"utf-8"),warnings:$}}function p(J){let Y=J.match(/(interface|type|class|function|const|let|var|enum|namespace|module)\s+(\w+)/);return Y?`${Y[1]}:${Y[2]}`:J.trim()}async function eJ(J,Y,$={}){let X=await AJ(J,$),Z=nJ(Y);if(!YJ(Z))sJ(Z,{recursive:!0});return iJ(Y,X.content),X}function CY(J={}){return{bundle:(Y)=>AJ(Y,J),bundleAndWrite:(Y,$)=>eJ(Y,$,{...J,output:$})}}async function PY(J,Y=process.cwd()){let $=Array.isArray(J)?J:[J],X=[];for(let Z of $){if(Z.includes("*"))continue;let Q=rJ(Y,Z);if(YJ(Q))X.push(Q)}return X}import{existsSync as c,mkdirSync as JY,readFileSync as ZJ,statSync as RJ,writeFileSync as kJ}from"fs";import{join as TJ,relative as d,resolve as YY}from"path";var $J=1,qJ=".dtsx-cache",$Y="manifest.json";class QJ{cacheDir;manifestPath;manifest=null;configHash;constructor(J){this.cacheDir=YY(J.cwd,qJ),this.manifestPath=TJ(this.cacheDir,$Y),this.configHash=this.hashConfig(J)}hashConfig(J){let Y={keepComments:J.keepComments,importOrder:J.importOrder,outputStructure:J.outputStructure};return String(XJ(JSON.stringify(Y)))}hashString(J){return String(XJ(J))}load(){try{if(!c(this.manifestPath))return!1;let J=ZJ(this.manifestPath,"utf-8"),Y=JSON.parse(J);if(Y.version!==$J)return!1;if(Y.configHash!==this.configHash)return!1;return this.manifest=Y,!0}catch{return!1}}save(){if(!this.manifest)this.manifest={version:$J,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};if(this.manifest.updatedAt=Date.now(),!c(this.cacheDir))JY(this.cacheDir,{recursive:!0});kJ(this.manifestPath,JSON.stringify(this.manifest,null,2))}needsRegeneration(J,Y){return this.getCachedIfValid(J,Y)===null}getCached(J,Y){return this.getCachedIfValid(J,Y)}getCachedIfValid(J,Y){if(!this.manifest)return null;let $=d(Y,J),X=this.manifest.entries[$];if(!X)return null;try{let Q=RJ(J).mtimeMs;if(Q>X.sourceMtime){let U=ZJ(J,"utf-8");if(this.hashString(U)!==X.sourceHash)return null;X.sourceMtime=Q}return X.dtsContent}catch{return null}}update(J,Y,$,X){if(!this.manifest)this.manifest={version:$J,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};let Z=d(X,J),Q;try{Q=RJ(J).mtimeMs}catch{Q=Date.now()}this.manifest.entries[Z]={sourcePath:Z,sourceHash:this.hashString(Y),sourceMtime:Q,dtsContent:$,dtsHash:this.hashString($),generatedAt:Date.now(),configHash:this.configHash}}remove(J,Y){if(!this.manifest)return;let $=d(Y,J);delete this.manifest.entries[$]}clear(){this.manifest=null;try{if(c(this.manifestPath))BJ("fs").rmSync(this.cacheDir,{recursive:!0,force:!0})}catch{}}getStats(){if(!this.manifest)return{entries:0,size:0};let J=Object.keys(this.manifest.entries).length,Y=0;for(let $ of Object.values(this.manifest.entries))Y+=$.dtsContent.length;return{entries:J,size:Y}}prune(J,Y){if(!this.manifest)return 0;let $=0,X=new Set(Array.from(J).map((Z)=>d(Y,Z)));for(let Z of Object.keys(this.manifest.entries))if(!X.has(Z))delete this.manifest.entries[Z],$++;return $}}function NJ(J){let Y=TJ(J,".gitignore");try{let $="";if(c(Y))$=ZJ(Y,"utf-8");if(!$.includes(qJ)){let X=`${$.trimEnd()}

# dtsx cache
${qJ}/
`;kJ(Y,X)}}catch{}}import{spawn as XY}from"child_process";import{readFile as LJ,stat as ZY,writeFile as qY}from"fs/promises";var v=typeof globalThis.Bun<"u",cY=!v&&typeof process<"u"&&!!process.versions?.node,lY=v?"bun":"node";class MJ{name;_size=-1;constructor(J){this.name=J}async exists(){try{return await ZY(this.name),!0}catch{return!1}}async text(){return LJ(this.name,"utf-8")}async arrayBuffer(){let J=await LJ(this.name);return J.buffer.slice(J.byteOffset,J.byteOffset+J.byteLength)}get size(){if(this._size===-1)return-1;return this._size}}class SJ{pid;stdout;stderr;stdin;exited;process;constructor(J){this.process=J,this.pid=J.pid??0,this.stdout=J.stdout,this.stderr=J.stderr,this.stdin=J.stdin,this.exited=new Promise((Y)=>{J.on("exit",($)=>{Y($??0)}),J.on("error",()=>{Y(1)})})}kill(J){this.process.kill(J)}ref(){this.process.ref()}unref(){this.process.unref()}}function l(J){if(v)return globalThis.Bun.file(J);return new MJ(J)}async function UJ(J,Y){if(v)return globalThis.Bun.write(J,Y);let $=typeof Y==="string"?Y:Y instanceof ArrayBuffer?Buffer.from(Y):Y;return await qY(J,$),typeof Y==="string"?Buffer.byteLength(Y):Y.byteLength}function wJ(J,Y={}){if(v)return globalThis.Bun.spawn(J,Y);let $=Array.isArray(J)?J:[J],[X,...Z]=$,Q={cwd:Y.cwd,env:Y.env,stdio:[Y.stdin??"pipe",Y.stdout??"pipe",Y.stderr??"pipe"]},U=XY(X,Z,Q);return new SJ(U)}async function I(J){return l(J).text()}async function sY(J){return l(J).exists()}async function aY(J,Y){await UJ(J,Y)}function iY(){if(v)return{name:"bun",version:globalThis.Bun.version,isBun:!0,isNode:!1};return{name:"node",version:process.versions.node,isBun:!1,isNode:!0}}var P={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"};class w extends Error{code;context;constructor(J,Y="UNKNOWN_ERROR",$){super(J);if(this.name="DtsxError",this.code=Y,this.context=$,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toString(){let J=`${this.name} [${this.code}]: ${this.message}`;if(this.context)J+=`
Context: ${JSON.stringify(this.context,null,2)}`;return J}toJSON(){return{name:this.name,code:this.code,message:this.message,context:this.context,stack:this.stack}}}class FJ extends w{filePath;line;column;constructor(J,Y,$){super(J,"PARSE_ERROR",{filePath:Y,line:$?.line,column:$?.column});if(this.name="ParseError",this.filePath=Y,this.line=$?.line,this.column=$?.column,$?.cause)this.cause=$.cause}get locationString(){if(this.line!==void 0&&this.column!==void 0)return`${this.filePath}:${this.line}:${this.column}`;return this.line!==void 0?`${this.filePath}:${this.line}`:this.filePath}}class QY extends w{filePath;declarationKind;constructor(J,Y,$,X){super(J,"EXTRACTION_ERROR",{filePath:Y,declarationKind:$});if(this.name="ExtractionError",this.filePath=Y,this.declarationKind=$,X)this.cause=X}}class UY extends w{declarationName;constructor(J,Y,$){super(J,"PROCESSING_ERROR",{declarationName:Y});if(this.name="ProcessingError",this.declarationName=Y,$)this.cause=$}}class vJ extends w{filePath;operation;constructor(J,Y,$,X){super(J,$==="read"?"FILE_READ_ERROR":"FILE_WRITE_ERROR",{filePath:Y,operation:$});if(this.name="FileError",this.filePath=Y,this.operation=$,X)this.cause=X}}class EJ extends w{configPath;invalidKey;constructor(J,Y){super(J,"CONFIG_ERROR",{configPath:Y?.configPath,invalidKey:Y?.invalidKey});if(this.name="ConfigError",this.configPath=Y?.configPath,this.invalidKey=Y?.invalidKey,Y?.cause)this.cause=Y.cause}}class jY extends w{cycle;constructor(J){super(`Circular dependency detected: ${J.join(" -> ")}`,"CIRCULAR_DEPENDENCY",{cycle:J});this.name="CircularDependencyError",this.cycle=J}}function oY(J){return J instanceof w}function rY(J){return J instanceof FJ}function tY(J){return J instanceof vJ}function eY(J){return J instanceof EJ}function J0(J,Y="UNKNOWN_ERROR",$){if(J instanceof w)return J;let X=$||(J instanceof Error?J.message:String(J)),Z=new w(X,Y);if(J instanceof Error)Z.cause=J;return Z}function Y0(J,Y){let $=1,X=1,Z=0;for(let Q of J){if(Z>=Y)break;if(Q===`
`)$++,X=1;else X++;Z++}return{line:$,column:X,offset:Y}}function $0(J,Y,$,X){let Z=J.split(`
`),Q=Y.line-1,U=[];if(X)U.push(`${X}:${Y.line}:${Y.column}`);else U.push(`Line ${Y.line}, Column ${Y.column}`);U.push(`Error: ${$}`),U.push("");let z=Math.max(0,Q-1),H=Math.min(Z.length-1,Q+1);for(let j=z;j<=H;j++){let _=(j+1).toString().padStart(4," "),A=j===Q?">":" ";if(U.push(`${A} ${_} | ${Z[j]}`),j===Q){let R=" ".repeat(8+Y.column-1);U.push(`${R}^`)}}return U.join(`
`)}function jJ(J,Y,$){let X={file:Y,message:"Unknown error",code:P.UNKNOWN_ERROR};if(J instanceof Error){X.message=J.message,X.stack=J.stack;let Z=J.message.match(/\((\d+),(\d+)\)/);if(Z)X.location={line:Number.parseInt(Z[1],10),column:Number.parseInt(Z[2],10)};if(J.message.includes("Cannot find")||J.message.includes("not found"))X.code=P.FILE_NOT_FOUND,X.suggestion="Check that the file path is correct and the file exists.";else if(J.message.includes("syntax")||J.message.includes("Unexpected token"))X.code=P.SYNTAX_ERROR,X.suggestion="Check for syntax errors in your TypeScript code.";else if(J.message.includes("type")&&J.message.includes("cannot"))X.code=P.TYPE_INFERENCE_ERROR,X.suggestion="Add explicit type annotations to help with type inference.";else if(J.message.includes("parse")||J.message.includes("Parse"))X.code=P.PARSE_ERROR,X.suggestion="The file contains invalid TypeScript syntax."}else if(typeof J==="string")X.message=J;return X}function yJ(J,Y){let $=[],X=J.file;if(J.location)X+=`:${J.location.line}:${J.location.column}`;if(J.code)X+=` [${J.code}]`;if($.push(X),$.push(`  Error: ${J.message}`),Y&&J.location){$.push("");let Z=Y.split(`
`),Q=J.location.line-1;if(Q>=0&&Q<Z.length){let U=Math.max(0,Q-1),z=Math.min(Z.length-1,Q+1);for(let H=U;H<=z;H++){let j=(H+1).toString().padStart(4," "),_=H===Q?">":" ";if($.push(`  ${_} ${j} | ${Z[H]}`),H===Q&&J.location.column>0){let A=" ".repeat(10+J.location.column-1);$.push(`  ${A}^`)}}}}if(J.suggestion)$.push(""),$.push(`  Suggestion: ${J.suggestion}`);return $.join(`
`)}function X0(J){if(J.length===0)return"No errors";let Y=new Map;for(let X of J){let Z=X.code||"UNKNOWN";Y.set(Z,(Y.get(Z)||0)+1)}let $=[`${J.length} error(s) found:`];for(let[X,Z]of Y.entries())$.push(`  - ${X}: ${Z}`);return $.join(`
`)}var s=null,E=null;async function VY(){if(s!==null)return s;try{return E=await import("prettier"),s=!0,!0}catch{return s=!1,!1}}async function zY(J,Y){if(!E)return null;try{if(Y&&E.resolveConfig){let $=await E.resolveConfig(Y);if($)return $}if(J&&E.resolveConfig){let $=await E.resolveConfig(J);if($)return $}return null}catch{return null}}async function _Y(J,Y){if(!E)throw Error("Prettier is not available");let $={...Y,parser:Y.parser||"typescript"};return E.format(J,$)}function GY(J,Y={}){let{indentSize:$=2,useTabs:X=!1,maxLineWidth:Z=100,trailingNewline:Q=!0,normalizeWhitespace:U=!0,sortImports:z=!0,groupImports:H=!0}=Y,j=J,_=X?"\t":" ".repeat($);if(j=j.replace(/\r\n/g,`
`),U)j=j.replace(/[ \t]+$/gm,""),j=j.replace(/\n{3,}/g,`

`),j=HY(j,_);if(z||H)j=WY(j,{sort:z,group:H});if(Z>0)j=OY(j,Z,_);if(Q&&!j.endsWith(`
`))j+=`
`;return j}function HY(J,Y){let $=J.split(`
`),X=[];for(let Z of $){let Q=Z.match(/^(\s*)(.*)$/);if(!Q){X.push(Z);continue}let[,U,z]=Q;if(!z){X.push("");continue}let H=U.replace(/\t/g,"  ").length,j=Math.floor(H/2);X.push(Y.repeat(j)+z)}return X.join(`
`)}function WY(J,Y){let $=J.split(`
`),X=[],Z=[],Q=!1,U=0;for(let H=0;H<$.length;H++){let j=$[H],_=j.match(/^(import\s+(?:type\s+)?.*from\s+['"])([^'"]+)(['"].*)$/);if(_)Q=!0,U=H,X.push({line:j,source:_[2],isType:j.includes("import type")});else if(Q&&j.trim()==="")continue;else{if(Q)Q=!1;Z.push(j)}}if(X.length===0)return J;if(Y.sort)X.sort((H,j)=>{if(H.isType!==j.isType)return H.isType?1:-1;return KY(H.source,j.source)});let z;if(Y.group){let H=X.filter((q)=>q.source.startsWith("node:")),j=X.filter((q)=>!q.source.startsWith(".")&&!q.source.startsWith("node:")&&!q.source.includes("/")),_=X.filter((q)=>!q.source.startsWith(".")&&!q.source.startsWith("node:")&&q.source.includes("/")&&!q.source.startsWith("@")),A=X.filter((q)=>q.source.startsWith("@")),R=X.filter((q)=>q.source.startsWith("."));z=[...H.map((q)=>q.line),...H.length>0&&j.length>0?[""]:[],...j.map((q)=>q.line),...(H.length>0||j.length>0)&&_.length>0?[""]:[],..._.map((q)=>q.line),...A.length>0&&(H.length>0||j.length>0||_.length>0)?[""]:[],...A.map((q)=>q.line),...R.length>0?[""]:[],...R.map((q)=>q.line)]}else z=X.map((H)=>H.line);return[...z,"",...Z].join(`
`)}function KY(J,Y){let $=J.startsWith("node:"),X=Y.startsWith("node:");if($!==X)return $?-1:1;let Z=J.startsWith("."),Q=Y.startsWith(".");if(Z!==Q)return Z?1:-1;return J.localeCompare(Y)}function OY(J,Y,$){let X=J.split(`
`),Z=[];for(let Q of X){if(Q.length<=Y){Z.push(Q);continue}if(Q.trimStart().startsWith("import ")){Z.push(Q);continue}let U=Q.match(/^(\s*)/)?.[1]||"",z=U+$;if(Q.includes("{")&&Q.includes("}")){let H=AY(Q,Y,U,z);Z.push(...H);continue}if(Q.includes(" | ")){let H=RY(Q,Y,U,z);Z.push(...H);continue}Z.push(Q)}return Z.join(`
`)}function AY(J,Y,$,X){let Z=J.match(/^(\s*)(.*?)(\{)(.+)(\}.*)$/);if(!Z)return[J];let[,,Q,U,z,H]=Z,j=z.split(/;\s*|,\s*/).filter((A)=>A.trim());if(j.length<=1)return[J];return[`${$}${Q}${U}`,...j.map((A)=>`${X}${A.trim()};`),`${$}${H.trim()}`]}function RY(J,Y,$,X){let Z=J.match(/^(\s*)(.*?=\s*)(.+)$/);if(!Z)return[J];let[,,Q,U]=Z,z=U.split(/\s*\|\s*/).filter((j)=>j.trim());if(z.length<=2)return[J];return[`${$}${Q}`,...z.map((j,_)=>`${X}${_>0?"| ":"  "}${j.trim()}`)]}async function h(J,Y={},$){let X=[];if(Y.usePrettier!==!1){if(await VY())try{let z={...await zY(Y.prettierConfigPath,$),...Y.prettierOptions,parser:"typescript"};return{content:await _Y(J,z),usedPrettier:!0}}catch(U){X.push(`Prettier formatting failed: ${U}. Using built-in formatter.`)}else if(Y.usePrettier===!0)X.push("Prettier requested but not available. Using built-in formatter.")}return{content:GY(J,Y.builtIn),usedPrettier:!1,warnings:X.length>0?X:void 0}}async function BY(J,Y={}){let $=new Map;for(let[X,Z]of J){let Q=await h(Z,Y,X);$.set(X,Q)}return $}function q0(J={}){return{format:(Y,$)=>h(Y,J,$),formatMany:(Y)=>BY(Y,J)}}async function Q0(J){return(await h(J,{usePrettier:!0,builtIn:{indentSize:2,normalizeWhitespace:!0,sortImports:!0,trailingNewline:!0}})).content}class a{plugins=[];config=null;register(J){if(this.plugins.some((Y)=>Y.name===J.name))throw Error(`Plugin "${J.name}" is already registered`);this.plugins.push(J)}unregister(J){let Y=this.plugins.findIndex(($)=>$.name===J);if(Y>=0)return this.plugins.splice(Y,1),!0;return!1}getPlugins(){return this.plugins}createLogger(J){return{debug:(Y)=>console.debug(`[${J}] ${Y}`),info:(Y)=>console.info(`[${J}] ${Y}`),warn:(Y)=>console.warn(`[${J}] ${Y}`),error:(Y)=>console.error(`[${J}] ${Y}`)}}async runOnStart(J){let Y=J;for(let $ of this.plugins)if($.onStart){let X=await $.onStart(Y);if(X)Y=X}return this.config=Y,Y}async runOnBeforeFile(J,Y){let $=Y;for(let X of this.plugins)if(X.onBeforeFile){let Z={filePath:J,sourceCode:Y,content:$,config:this.config,log:this.createLogger(X.name)},Q=await X.onBeforeFile(Z);if(typeof Q==="string")$=Q}return $}async runOnDeclarations(J,Y,$){let X=$;for(let Z of this.plugins)if(Z.onDeclarations){let Q={filePath:J,sourceCode:Y,declarations:X,config:this.config,log:this.createLogger(Z.name)},U=await Z.onDeclarations(Q);if(U)X=U}return X}async runOnAfterFile(J,Y,$){let X=$;for(let Z of this.plugins)if(Z.onAfterFile){let Q={filePath:J,sourceCode:Y,content:X,config:this.config,log:this.createLogger(Z.name)},U=await Z.onAfterFile(Q);if(typeof U==="string")X=U}return X}async runOnEnd(J){for(let Y of this.plugins)if(Y.onEnd)await Y.onEnd(J)}async runOnError(J,Y,$){for(let X of this.plugins)if(X.onError){let Z={filePath:Y,sourceCode:$,config:this.config,log:this.createLogger(X.name)};await X.onError(J,Z)}}}var j0=new a;function VJ(J){return J}var V0=VJ({name:"strip-internal",version:"1.0.0",description:"Removes declarations marked with @internal",onDeclarations:(J)=>{return J.declarations.filter((Y)=>{if(Y.leadingComments){if(Y.leadingComments.some((X)=>X.includes("@internal")))return J.log.debug(`Stripping internal declaration: ${Y.name}`),!1}return!0})}});function z0(J){return VJ({name:"banner",version:"1.0.0",description:"Adds a banner comment to generated files",onAfterFile:(Y)=>{return`/**
 * ${J.split(`
`).join(`
 * `)}
 */

`+Y.content}})}function _0(J){return VJ({name:"filter",version:"1.0.0",description:"Filters declarations by name",onDeclarations:(Y)=>{return Y.declarations.filter(($)=>{if($.kind==="import")return!0;return J($.name)})}})}var b=kY(TY(),1);import{readdir as NY}from"fs/promises";import{dirname as LY,extname as MY,isAbsolute as SY,join as bJ,resolve as DJ}from"path";import xJ from"process";import{pathToFileURL as zJ}from"url";function B0(J,Y){throw Error(Y||`Unexpected value: ${J}`)}async function x(J,Y){let $=Y.replace(/\r\n/g,`
`);if(!$.endsWith(`
`))$+=`
`;await UJ(J,$)}async function wY(J){let Y=J??m.root,$=await NY(Y,{withFileTypes:!0}),X=await Promise.all($.map((Z)=>{let Q=bJ(Y,Z.name);return Z.isDirectory()?wY(Q):Q}));return Array.prototype.concat(...X).filter((Z)=>MY(Z)===".ts")}async function CJ(J){try{let Y=J?.cwd||xJ.cwd(),$=J?.tsconfigPath||bJ(Y,"tsconfig.json"),Z=await import(zJ($).href);if(Z.compilerOptions?.isolatedDeclarations===!0)return!0;if(Z.extends){let Q=IJ($,Z.extends),U=Q.endsWith(".json")?Q:`${Q}.json`,H=await import(zJ(U).href);if(H.compilerOptions?.isolatedDeclarations===!0)return!0;if(H.extends){let j=IJ(U,H.extends),_=j.endsWith(".json")?j:`${j}.json`;if((await import(zJ(_).href)).compilerOptions?.isolatedDeclarations===!0)return!0}}return!1}catch{return!1}}function PJ(J,Y){let $={isValid:!0,errors:[]},X=b.default.createSourceFile(Y,J,b.default.ScriptTarget.Latest,!0,b.default.ScriptKind.TS),Z={getSourceFile:(z)=>{if(z===Y)return X;return},getDefaultLibFileName:()=>"lib.d.ts",writeFile:()=>{},getCurrentDirectory:()=>"",getCanonicalFileName:(z)=>z,useCaseSensitiveFileNames:()=>!0,getNewLine:()=>`
`,fileExists:(z)=>z===Y,readFile:()=>{return}},U=[...b.default.createProgram({rootNames:[Y],options:{noEmit:!0,declaration:!0,skipLibCheck:!0,noLib:!0},host:Z}).getSyntacticDiagnostics(X)];for(let z of U){let H=b.default.flattenDiagnosticMessageText(z.messageText,`
`),j=`TS${z.code}`,_;switch(z.code){case 1005:_="Add a semicolon at the end of the statement.";break;case 1109:_="Check for missing or malformed expressions.";break;case 1128:_="Ensure proper declaration syntax is used.";break;case 2304:_="Import or declare the missing type/value.";break;case 2307:_="Check that the module exists and is installed.";break;case 2322:_="Check type compatibility between the values.";break;case 2339:_="Add the missing property to the type definition.";break;case 2345:_="Check the argument types match the expected parameters.";break}if(z.file&&z.start!==void 0){let{line:A,character:R}=z.file.getLineAndCharacterOfPosition(z.start);$.errors.push({line:A+1,column:R+1,message:H,code:j,suggestion:_})}else $.errors.push({line:0,column:0,message:H,code:j,suggestion:_})}return $.isValid=$.errors.length===0,$}function hJ(J,Y,$){let X=J.split(`
`),Z=Y.split(`
`),Q=new Set(X),U=new Set(Z),z=X.filter((_)=>!U.has(_)),H=Z.filter((_)=>!Q.has(_));if(z.length===0&&H.length===0)return"";let j=[];j.push(`--- ${$}`),j.push(`+++ ${$}`);for(let _ of z)j.push(`- ${_}`);for(let _ of H)j.push(`+ ${_}`);return j.join(`
`)}function IJ(J,Y){if(SY(Y))return Y;if(Y.startsWith("."))return DJ(LY(J),Y);return DJ(xJ.cwd(),"node_modules",Y)}function mJ(J,Y,$,X){let Z=J.split(`
`),Q=[];function U(_){let R="",q=_<0?-_<<1|1:_<<1;do{let G=q&31;if(q>>>=5,q>0)G|=32;R+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[G]}while(q>0);return R}let z=0,H=0,j=0;for(let _=0;_<Z.length;_++){if(Z[_].trim()===""){Q.push("");continue}z=0;let R=Math.min(_,X.split(`
`).length-1),q=[],G=0-z,O=0,V=R-H,K=0-j;q.push(U(G)+U(O)+U(V)+U(K)),z=0,H=R,j=0,Q.push(q.join(","))}return{version:3,file:Y,sourceRoot:"",sources:[$],sourcesContent:[X],mappings:Q.join(";")}}function fJ(J,Y){return`${J}
//# sourceMappingURL=${Y}
`}async function vY(J){let Y=Date.now(),$={...m,...J};if($.logLevel)n($.logLevel);else if($.verbose)n("debug");let X=new a;if($.plugins&&$.plugins.length>0){for(let q of $.plugins)X.register(q),W.debug(`Registered plugin: ${q.name}`);$=await X.runOnStart($)}if($.isolatedDeclarations===void 0)$.isolatedDeclarations=await CJ($);let Z=null;if($.incremental){if(Z=new QJ($),$.clearCache)W.debug("Clearing build cache..."),Z.clear();else if(Z.load()){let G=Z.getStats();W.debug(`Loaded build cache with ${G.entries} entries`)}else W.debug("No existing build cache found, starting fresh");NJ($.cwd)}let Q={filesProcessed:0,filesGenerated:0,filesFailed:0,filesValidated:0,validationErrors:0,declarationsFound:0,importsProcessed:0,exportsProcessed:0,durationMs:0,errors:[]},U=0;W.debug("Starting DTS generation..."),W.debug("Config:",$);let z=await DY($);if(Z){let q=Z.prune(new Set(z),$.cwd);if(q>0)W.debug(`Pruned ${q} deleted files from cache`)}if(W.debug(`Found ${z.length} TypeScript files`),$.progress&&z.length>0){let q=$.parallel?"parallel":"sequential";W.info(`Processing ${z.length} files (${q})...`)}let H=async(q,G)=>{let O;try{let V=uJ(q,$);if(Z){let M=Z.getCachedIfValid(q,$.cwd);if(M)return await i(g(V),{recursive:!0}),await x(V,M),W.debug(`[cached] ${S($.cwd,V)}`),{success:!0,file:q,declarationCount:0,importCount:0,exportCount:0,cached:!0,validationErrorCount:0}}O=G??await I(q);let{content:K,declarationCount:B,importCount:k,exportCount:T}=await cJ(q,O,$,X),C=0;if($.dryRun)W.info(`[dry-run] Would generate: ${V}`),W.debug("--- Content preview ---"),W.debug(K.slice(0,500)+(K.length>500?`
...`:"")),W.debug("--- End preview ---");else{if($.diff)try{let N=await I(V),L=hJ(N,K,S($.cwd,V));if(L)W.info(`
${L}`);else W.debug(`[no changes] ${V}`)}catch{W.info(`[new file] ${S($.cwd,V)}`)}await i(g(V),{recursive:!0});let M=K;if($.declarationMap&&O){let N=V.split("/").pop()||"output.d.ts",L=S(g(V),q),D=`${N}.map`,GJ=mJ(K,N,L,O),F=`${V}.map`;await x(F,JSON.stringify(GJ)),M=fJ(K,D),W.debug(`  Generated source map: ${S($.cwd,F)}`)}if($.prettier||$.indentStyle||$.indentSize){let N=await h(M,{usePrettier:$.prettier,builtIn:{indentSize:$.indentSize||2,useTabs:$.indentStyle==="tabs",normalizeWhitespace:!0,sortImports:!0,trailingNewline:!0}},V);if(M=N.content,N.warnings?.length)for(let L of N.warnings)W.warn(`[format] ${L}`)}if(await x(V,M),Z&&O)Z.update(q,O,M,$.cwd);if($.validate){let N=PJ(K,V);if(!N.isValid){C=N.errors.length,W.warn(`[validation] ${S($.cwd,V)} has ${N.errors.length} error(s):`);for(let L of N.errors){let D=`  Line ${L.line}:${L.column}`;if(L.code)D+=` [${L.code}]`;if(D+=` - ${L.message}`,W.warn(D),L.suggestion)W.warn(`    Suggestion: ${L.suggestion}`)}}else W.debug(`[validation] ${V} - OK`)}W.debug(`Generated: ${V}`)}return{success:!0,file:q,declarationCount:B,importCount:k,exportCount:T,validationErrorCount:C}}catch(V){let K=jJ(V,q,O);if($.plugins&&$.plugins.length>0)await X.runOnError(V instanceof Error?V:Error(String(V)),q,O||"");return{success:!1,file:q,declarationCount:0,importCount:0,exportCount:0,dtsError:K,validationErrorCount:0}}},j=$.parallel||$.parallel!==!1&&z.length>=10,_=$.concurrency||(FY?.()??8),A=new Map;if(j&&z.length>1){let q=z.map(async(G)=>{try{let O=await I(G);return{file:G,source:O}}catch{return{file:G,source:null}}});for(let G of await Promise.all(q))if(G.source!==null)A.set(G.file,G.source)}let R=(q)=>{if(Q.filesProcessed++,q.success){if(q.cached)U++;else Q.filesGenerated++,Q.declarationsFound+=q.declarationCount,Q.importsProcessed+=q.importCount,Q.exportsProcessed+=q.exportCount;if($.validate){if(Q.filesValidated++,q.validationErrorCount)Q.validationErrors+=q.validationErrorCount}}else if(Q.filesFailed++,q.dtsError){Q.errors.push(q.dtsError);let G=yJ(q.dtsError);if($.continueOnError)W.warn(G);else throw W.error(G),Error(q.dtsError.message)}};if(j)for(let q=0;q<z.length;q+=_){let G=z.slice(q,q+_),O=await Promise.all(G.map((V)=>H(V,A.get(V))));for(let V of O)R(V);if($.progress){let V=Math.round(Q.filesProcessed/z.length*100);W.info(`[${Q.filesProcessed}/${z.length}] ${V}%`)}}else for(let q of z){let G=await H(q);if(R(G),$.progress){let O=Math.round(Q.filesProcessed/z.length*100),V=G.cached?"[cached]":"";W.info(`[${Q.filesProcessed}/${z.length}] ${O}% - ${S($.cwd,q)} ${V}`)}}if(Z)Z.save(),W.debug("Saved build cache");if($.bundle&&(Q.filesGenerated>0||U>0))try{W.debug("Bundling declarations...");let q=new Map;for(let K of z){let B=await I(K);q.set(K,B)}let G=await KJ(z,q,$),O=$.bundleOutput||"index.d.ts",V=y($.cwd,$.outdir,O);await i(g(V),{recursive:!0}),await x(V,G.content),W.info(`Bundled ${G.files.length} files to: ${S($.cwd,V)}`)}catch(q){let G=q instanceof Error?q.message:String(q);W.error(`Bundle failed: ${G}`)}if(Q.durationMs=Date.now()-Y,$.stats)if($.outputFormat==="json")console.log(JSON.stringify(Q,null,2));else{if(W.info(`
--- Generation Statistics ---`),W.info(`Files processed:     ${Q.filesProcessed}`),W.info(`Files generated:     ${Q.filesGenerated}`),U>0)W.info(`Files cached:        ${U}`);if(Q.filesFailed>0)W.info(`Files failed:        ${Q.filesFailed}`);if(W.info(`Declarations found:  ${Q.declarationsFound}`),W.info(`Imports processed:   ${Q.importsProcessed}`),W.info(`Exports processed:   ${Q.exportsProcessed}`),Q.filesValidated>0){if(W.info(`Files validated:     ${Q.filesValidated}`),Q.validationErrors>0)W.info(`Validation errors:   ${Q.validationErrors}`)}if(W.info(`Duration:            ${Q.durationMs}ms`),Q.errors.length>0){W.info(`
Errors:`);for(let q of Q.errors){let G=`  - ${q.file}`;if(q.location)G+=`:${q.location.line}:${q.location.column}`;if(q.code)G+=` [${q.code}]`;if(G+=`: ${q.message}`,W.info(G),q.suggestion)W.info(`    Suggestion: ${q.suggestion}`)}}W.info(`-----------------------------
`)}if($.plugins&&$.plugins.length>0)await X.runOnEnd(Q);return W.debug("DTS generation complete!"),Q}var EY=50,f=new Map;function yY(J){let Y=f.get(J);if(!Y){if(Y=new pJ(J),f.set(J,Y),f.size>EY){let $=f.keys().next().value;if($!==void 0)f.delete($)}}return Y}function _J(J,Y,$){if(!Y||Y.length===0)return!1;let X=S($,J);for(let Z of Y){let Q=yY(Z);if(Q.match(X)||Q.match(J))return!0}return!1}async function DY(J){let Y=[],$=y(J.cwd,J.root),X=J.exclude||[];for(let Z of J.entrypoints)if(Z.startsWith("/")&&Z.endsWith(".ts")){if(!Z.endsWith(".d.ts")&&!Z.includes("node_modules")){if(!_J(Z,X,$))Y.push(Z)}}else{let Q=new pJ(Z);for await(let U of Q.scan({cwd:$,absolute:!0,onlyFiles:!0}))if(!U.endsWith(".d.ts")&&!U.includes("node_modules")){if(!_J(U,X,$))Y.push(U)}}return[...new Set(Y)]}function uJ(J,Y){let $=y(Y.cwd,Y.root),Z=S($,J).replace(/\.(m?tsx?|cts)$/,(Q)=>{if(Q===".mts")return".d.mts";if(Q===".cts")return".d.cts";return".d.ts"});if(Y.outputStructure==="mirror")return y(Y.cwd,Y.outdir,Z);else{let Q=Z.split("/").pop();return y(Y.cwd,Y.outdir,Q)}}async function h0(J,Y){return(await dJ(J,Y)).content}async function dJ(J,Y,$){let X=await I(J);return cJ(J,X,Y,$)}async function cJ(J,Y,$,X){let Z=Y;if(X)Z=await X.runOnBeforeFile(J,Y);let Q=u(Z,J,$.keepComments,$.isolatedDeclarations??!1);if(X)Q=await X.runOnDeclarations(J,Z,Q);let U=0,z=0;for(let _=0;_<Q.length;_++){let A=Q[_];if(A.kind==="import")U++;if(A.kind==="export"||A.isExported)z++}let j=gJ(Q,{filePath:J,sourceCode:Z,declarations:Q},$.keepComments,$.importOrder);if(X)j=await X.runOnAfterFile(J,Z,j);return{content:j,declarationCount:Q.length,importCount:U,exportCount:z}}async function m0(J){let Y={...m,...J};if(Y.logLevel)n(Y.logLevel);let $=y(Y.cwd,Y.root),X=150,Z=5,Q=1e4,U={pendingChanges:new Set,debounceTimer:null,isProcessing:!1,errorCount:0,lastErrorTime:0};W.info(`Watching for changes in ${$}...`),W.info(`Press Ctrl+C to stop
`);try{await vY(Y),W.info(`[watch] Initial generation complete
`)}catch(A){let R=A instanceof Error?A.message:String(A);W.error(`[watch] Initial generation failed: ${R}`),W.info(`[watch] Continuing to watch for changes...
`)}async function z(){if(U.isProcessing||U.pendingChanges.size===0)return;let A=Date.now();if(U.errorCount>=Z){if(A-U.lastErrorTime<Q){W.warn(`[watch] Too many errors, pausing for ${Math.ceil((Q-(A-U.lastErrorTime))/1000)}s...`);return}U.errorCount=0}U.isProcessing=!0;let R=Array.from(U.pendingChanges);U.pendingChanges.clear();let q=new Date().toLocaleTimeString();if(R.length===1)W.info(`
[${q}] File changed: ${R[0]}`);else W.info(`
[${q}] ${R.length} files changed`);let G=0,O=0;for(let V of R){let K=y($,V);try{let B=Y.exclude||[];if(_J(K,B,$)){W.debug(`  Skipping excluded file: ${V}`);continue}if(!await l(K).exists()){W.debug(`  Skipping deleted file: ${V}`);continue}let T=uJ(K,Y),{content:C}=await dJ(K,Y);await i(g(T),{recursive:!0}),await x(T,C),W.info(`  \u2713 ${S(Y.cwd,T)}`),G++}catch(B){O++,U.errorCount++,U.lastErrorTime=Date.now();let k=jJ(B,K);if(W.error(`  \u2717 ${V}: ${k.message}`),k.suggestion)W.error(`    Suggestion: ${k.suggestion}`)}}if(R.length>1)W.info(`  Done: ${G} generated, ${O} failed`);if(O===0)U.errorCount=0;if(U.isProcessing=!1,U.pendingChanges.size>0)U.debounceTimer=setTimeout(z,X)}function H(A){if(U.pendingChanges.add(A),U.debounceTimer)clearTimeout(U.debounceTimer);U.debounceTimer=setTimeout(z,X)}let _=wJ([v?"bun":"node","-e",`
    const fs = require('fs');

    const rootPath = '${$}';

    fs.watch(rootPath, { recursive: true }, (eventType, filename) => {
      if (filename && filename.endsWith('.ts') && !filename.endsWith('.d.ts')) {
        console.log('CHANGED:' + filename);
      }
    });

    // Keep process alive
    setInterval(() => {}, 1000);
  `],{stdout:"pipe",stderr:"inherit"});if(v){let A=_.stdout.getReader(),R=new TextDecoder,q="";while(!0){let{done:G,value:O}=await A.read();if(G)break;q+=R.decode(O,{stream:!0});let V=q.split(`
`);q=V.pop()||"";for(let K of V)if(K.startsWith("CHANGED:")){let B=K.slice(8);H(B)}}}else{let A=_.stdout,R="";A.on("data",(q)=>{R+=q.toString();let G=R.split(`
`);R=G.pop()||"";for(let O of G)if(O.startsWith("CHANGED:")){let V=O.slice(8);H(V)}}),await _.exited}}
export{KJ as ua,AJ as va,eJ as wa,CY as xa,PY as ya,QJ as za,NJ as Aa,v as Ba,cY as Ca,lY as Da,l as Ea,UJ as Fa,wJ as Ga,I as Ha,sY as Ia,aY as Ja,iY as Ka,P as La,w as Ma,FJ as Na,QY as Oa,UY as Pa,vJ as Qa,EJ as Ra,jY as Sa,oY as Ta,rY as Ua,tY as Va,eY as Wa,J0 as Xa,Y0 as Ya,$0 as Za,jJ as _a,yJ as $a,X0 as ab,h as bb,BY as cb,q0 as db,Q0 as eb,a as fb,j0 as gb,VJ as hb,V0 as ib,z0 as jb,_0 as kb,B0 as lb,x as mb,wY as nb,CJ as ob,PJ as pb,hJ as qb,mJ as rb,fJ as sb,vY as tb,h0 as ub,m0 as vb};
