pkgroll
Version:
Zero-config rollup bundler
33 lines (32 loc) • 34.7 kB
JavaScript
var oe=Object.defineProperty;var m=(n,e)=>oe(n,"name",{value:e,configurable:!0});import{createRequire as ae}from"node:module";const ce=ae(import.meta.url);import*as T from"node:path";import r from"typescript";import{createRequire as le}from"node:module";import q from"magic-string";function pe(n){return{...n,compilerOptions:n.compilerOptions??{},respectExternal:n.respectExternal??!1}}m(pe,"resolveDefaultOptions");const k=/\.d\.(c|m)?tsx?$/,_=/\.json$/,W=/((\.d)?\.(c|m)?(t|j)sx?|\.json)$/;function B(n){return n.replace(W,"")}m(B,"trimExtension");function J(n){return n.replace(W,".d.ts")}m(J,"getDeclarationId");function j(n,e){return r.createSourceFile(n,e,r.ScriptTarget.Latest,!0)}m(j,"parse");const V={getCurrentDirectory:m(()=>r.sys.getCurrentDirectory(),"getCurrentDirectory"),getNewLine:m(()=>r.sys.newLine,"getNewLine"),getCanonicalFileName:r.sys.useCaseSensitiveFileNames?n=>n:n=>n.toLowerCase()},fe={declaration:!0,noEmit:!1,emitDeclarationOnly:!0,noEmitOnError:!0,checkJs:!1,declarationMap:!1,skipLibCheck:!0,preserveSymlinks:!0,target:r.ScriptTarget.ESNext,resolveJsonModule:!0},R=new Map,M=m((...n)=>process.env.DTS_LOG_CACHE?console.log("[cache]",...n):null,"logCache");function X([n,e],t){for(M(n),R.set(n,t);n!==e&&n!==T.dirname(n);){if(n=T.dirname(n),M("up",n),R.has(n))return M("has",n);R.set(n,t)}}m(X,"cacheConfig");function z(n,e,t){const s={...fe,...e};let i=T.dirname(n),o=[];const c=t||i;if(R.has(c))M("HIT",c);else{M("miss",c);const u=t?T.resolve(process.cwd(),t):r.findConfigFile(i,r.sys.fileExists);if(!u)return{dtsFiles:o,dirName:i,compilerOptions:s};const h=i;i=T.dirname(u);const{config:g,error:w}=r.readConfigFile(u,r.sys.readFile);if(w)return console.error(r.formatDiagnostic(w,V)),{dtsFiles:o,dirName:i,compilerOptions:s};M("tsconfig",g);const C=r.parseJsonConfigFileContent(g,r.sys,i);X(t?[t,t]:[h,i],C)}const{fileNames:l,options:p,errors:f}=R.get(c);return o=l.filter(u=>k.test(u)),f.length?(console.error(r.formatDiagnostics(f,V)),{dtsFiles:o,dirName:i,compilerOptions:s}):{dtsFiles:o,dirName:i,compilerOptions:{...p,...s}}}m(z,"getCompilerOptions");function me(n,e,t){const{dtsFiles:s,compilerOptions:i}=z(n,e,t);return r.createProgram([n].concat(Array.from(s)),i,r.createCompilerHost(i,!0))}m(me,"createProgram$1");function ue(n,e,t){const s=[],i=new Set;let o=[],c="",l={};for(let p of n){if(k.test(p))continue;p=T.resolve(p);const f=z(p,e,t);if(f.dtsFiles.forEach(i.add,i),!o.length){o.push(p),{dirName:c,compilerOptions:l}=f;continue}if(f.dirName===c)o.push(p);else{const u=r.createCompilerHost(l,!0),h=r.createProgram(o.concat(Array.from(i)),l,u);s.push(h),o=[p],{dirName:c,compilerOptions:l}=f}}if(o.length){const p=r.createCompilerHost(l,!0),f=r.createProgram(o.concat(Array.from(i)),l,p);s.push(f)}return s}m(ue,"createPrograms");function de(){let n;try{return{codeFrameColumns:n}=ce("@babel/code-frame"),n}catch{try{return{codeFrameColumns:n}=le(import.meta.url)("@babel/code-frame"),n}catch{}}}m(de,"getCodeFrame");function he(n){const e=n.getSourceFile(),t=e.getLineAndCharacterOfPosition(n.getStart()),s=e.getLineAndCharacterOfPosition(n.getEnd());return{start:{line:t.line+1,column:t.character+1},end:{line:s.line+1,column:s.character+1}}}m(he,"getLocation");function ye(n){const e=de(),s=n.getSourceFile().getFullText(),i=he(n);return e?`
`+e(s,i,{highlightCode:!0}):`
${i.start.line}:${i.start.column}: \`${n.getFullText().trim()}\``}m(ye,"frameNode");class x extends Error{static{m(this,"UnsupportedSyntaxError")}constructor(e,t="Syntax not yet supported"){super(`${t}
${ye(e)}`)}}class ge{static{m(this,"NamespaceFixer")}constructor(e){this.sourceFile=e}findNamespaces(){const e=[],t={};for(const s of this.sourceFile.statements){const i={start:s.getStart(),end:s.getEnd()};if(r.isEmptyStatement(s)){e.unshift({name:"",exports:[],location:i});continue}if((r.isImportDeclaration(s)||r.isExportDeclaration(s))&&s.moduleSpecifier&&r.isStringLiteral(s.moduleSpecifier)){const{text:u}=s.moduleSpecifier;if(u.startsWith(".")&&(u.endsWith(".d.ts")||u.endsWith(".d.cts")||u.endsWith(".d.mts"))){const h=s.moduleSpecifier.getStart()+1,g=s.moduleSpecifier.getEnd()-1;e.unshift({name:"",exports:[],location:{start:h,end:g},textBeforeCodeAfter:u.replace(/\.d\.ts$/,".js").replace(/\.d\.cts$/,".cjs").replace(/\.d\.mts$/,".mjs")})}}if(r.isModuleDeclaration(s)&&s.body&&r.isModuleBlock(s.body)){for(const u of s.body.statements)if(r.isExportDeclaration(u)&&u.exportClause){if(r.isNamespaceExport(u.exportClause))continue;for(const h of u.exportClause.elements)h.propertyName&&h.propertyName.getText()==h.name.getText()&&e.unshift({name:"",exports:[],location:{start:h.propertyName.getEnd(),end:h.name.getEnd()}})}}if(r.isClassDeclaration(s)?t[s.name.getText()]={type:"class",generics:s.typeParameters}:r.isFunctionDeclaration(s)?t[s.name.getText()]={type:"function"}:r.isInterfaceDeclaration(s)?t[s.name.getText()]={type:"interface",generics:s.typeParameters}:r.isTypeAliasDeclaration(s)?t[s.name.getText()]={type:"type",generics:s.typeParameters}:r.isModuleDeclaration(s)&&r.isIdentifier(s.name)?t[s.name.getText()]={type:"namespace"}:r.isEnumDeclaration(s)&&(t[s.name.getText()]={type:"enum"}),!r.isVariableStatement(s))continue;const{declarations:o}=s.declarationList;if(o.length!==1)continue;const c=o[0],l=c.name.getText();if(!c.initializer||!r.isCallExpression(c.initializer)){t[l]={type:"var"};continue}const p=c.initializer.arguments[0];if(!c.initializer.expression.getFullText().includes("/*#__PURE__*/Object.freeze")||!r.isObjectLiteralExpression(p))continue;const f=[];for(const u of p.properties){if(!r.isPropertyAssignment(u)||!(r.isIdentifier(u.name)||r.isStringLiteral(u.name))||u.name.text!=="__proto__"&&!r.isIdentifier(u.initializer))throw new x(u,"Expected a property assignment");u.name.text!=="__proto__"&&f.push({exportedName:u.name.text,localName:u.initializer.getText()})}e.unshift({name:l,exports:f,location:i})}return{namespaces:e,itemTypes:t}}fix(){let e=this.sourceFile.getFullText();const{namespaces:t,itemTypes:s}=this.findNamespaces();for(const i of t){const o=e.slice(i.location.end);e=e.slice(0,i.location.start);for(const{exportedName:c,localName:l}of i.exports)if(c===l){const{type:p,generics:f}=s[l]||{};if(p==="interface"||p==="type"){const u=Y(f);e+=`type ${i.name}_${c}${u.in} = ${l}${u.out};
`}else if(p==="enum"||p==="class"){const u=Y(f);e+=`type ${i.name}_${c}${u.in} = ${l}${u.out};
`,e+=`declare const ${i.name}_${c}: typeof ${l};
`}else p==="namespace"?e+=`import ${i.name}_${c} = ${l};
`:e+=`declare const ${i.name}_${c}: typeof ${l};
`}if(i.name){e+=`declare namespace ${i.name} {
`,e+=` export {
`;for(const{exportedName:c,localName:l}of i.exports)c===l?e+=` ${i.name}_${c} as ${c},
`:e+=` ${l} as ${c},
`;e+=` };
`,e+="}"}e+=i.textBeforeCodeAfter??"",e+=o}return e}}function Y(n){return!n||!n.length?{in:"",out:""}:{in:`<${n.map(e=>e.getText()).join(", ")}>`,out:`<${n.map(e=>e.name.getText()).join(", ")}>`}}m(Y,"renderTypeParams");let Q=1;function xe(n){return E({type:"Program",sourceType:"module",body:[]},{start:n.getFullStart(),end:n.getEnd()})}m(xe,"createProgram");function Se(n){const e={type:"Identifier",name:String(Q++)};return{ident:e,expr:{type:"AssignmentPattern",left:e,right:n}}}m(Se,"createReference");function N(n){return E({type:"Identifier",name:n.getText()},n)}m(N,"createIdentifier");function Te(n){const e=E({type:"FunctionExpression",id:null,params:[],body:{type:"BlockStatement",body:[]}},n),t=E({type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:String(Q++)},arguments:[e],optional:!1}},n);return{fn:e,iife:t}}m(Te,"createIIFE");function ve(){const n={type:"ArrayExpression",elements:[]};return{expr:n,stmt:{type:"ReturnStatement",argument:n}}}m(ve,"createReturn");function Ee(n,e){return E({type:"FunctionDeclaration",id:E({type:"Identifier",name:r.idText(n)},n),params:[],body:{type:"BlockStatement",body:[]}},e)}m(Ee,"createDeclaration");function A(n){if(r.isLiteralExpression(n))return{type:"Literal",value:n.text};if(r.isPropertyAccessExpression(n)){if(r.isPrivateIdentifier(n.name))throw new x(n.name);return E({type:"MemberExpression",computed:!1,optional:!1,object:A(n.expression),property:A(n.name)},{start:n.expression.getStart(),end:n.name.getEnd()})}if(r.isIdentifier(n))return N(n);if(n.kind==r.SyntaxKind.NullKeyword)return{type:"Literal",value:null};throw new x(n)}m(A,"convertExpression");function E(n,e){const t="start"in e?e:{start:e.getStart(),end:e.getEnd()};return Object.assign(n,t)}m(E,"withStartEnd");function L(n,e){return(r.getCombinedModifierFlags(n)&e)===e}m(L,"matchesModifier");class Ne{static{m(this,"LanguageService")}constructor(e){this.fileName="index.d.ts";const t={getCompilationSettings:m(()=>({noEmit:!0,noResolve:!0,skipLibCheck:!0,declaration:!1,checkJs:!1,declarationMap:!1,target:r.ScriptTarget.ESNext}),"getCompilationSettings"),getScriptFileNames:m(()=>[this.fileName],"getScriptFileNames"),getScriptVersion:m(()=>"1","getScriptVersion"),getScriptSnapshot:m(s=>s===this.fileName?r.ScriptSnapshot.fromString(e):void 0,"getScriptSnapshot"),getCurrentDirectory:m(()=>"","getCurrentDirectory"),getDefaultLibFileName:m(()=>"","getDefaultLibFileName"),fileExists:m(s=>s===this.fileName,"fileExists"),readFile:m(s=>s===this.fileName?e:void 0,"readFile")};this.service=r.createLanguageService(t,r.createDocumentRegistry(void 0,""),r.LanguageServiceMode.PartialSemantic)}findReferenceCount(e){const t=this.service.findReferences(this.fileName,e.getStart());return t?.length?t.reduce((s,i)=>s+i.references.length,0):0}}class De{static{m(this,"TypeOnlyFixer")}constructor(e,t,s){this.sourcemap=s,this.DEBUG=!!process.env.DTS_EXPORTS_FIXER_DEBUG,this.types=new Set,this.values=new Set,this.typeHints=new Map,this.reExportTypeHints=new Map,this.importNodes=[],this.exportNodes=[],this.rawCode=t,this.source=j(e,t),this.code=new q(t)}fix(){return this.analyze(this.source.statements),(this.typeHints.size||this.reExportTypeHints.size)&&(this.service=new Ne(this.rawCode),this.importNodes.forEach(e=>this.fixTypeOnlyImport(e))),this.types.size&&this.exportNodes.forEach(e=>this.fixTypeOnlyExport(e)),this.types.size?{code:this.code.toString(),map:this.sourcemap?this.code.generateMap():null}:{code:this.rawCode,map:null}}fixTypeOnlyImport(e){let t=!1;const s=[],i=[],o=e.moduleSpecifier.getText(),c=e.importClause.name,l=e.importClause.namedBindings;if(c){const p=c.text;this.isTypeOnly(p)?this.isUselessImport(c)?t=!0:s.push(`import type ${p} from ${o};`):i.push(`import ${p} from ${o};`)}if(l&&r.isNamespaceImport(l)){const p=l.name.text;this.isTypeOnly(p)?this.isUselessImport(l.name)?t=!0:s.push(`import type * as ${p} from ${o};`):i.push(`import * as ${p} from ${o};`)}if(l&&r.isNamedImports(l)){const p=[],f=[];for(const u of l.elements)this.isTypeOnly(u.name.text)?this.isUselessImport(u.name)?t=!0:p.push(u.getText()):f.push(u.getText());p.length&&s.push(`import type { ${p.join(", ")} } from ${o};`),f.length&&i.push(`import { ${f.join(", ")} } from ${o};`)}(s.length||t)&&this.code.overwrite(e.getStart(),e.getEnd(),[...i,...s].join(`
${Z(e)}`))}fixTypeOnlyExport(e){const t=[],s=[],i=e.moduleSpecifier?.getText();if(r.isNamespaceExport(e.exportClause)){const o=e.exportClause.name.text;this.isReExportTypeOnly(o)?t.push(`export type * as ${o} from ${i};`):s.push(`export * as ${o} from ${i};`)}if(r.isNamedExports(e.exportClause)){const o=[],c=[];for(const l of e.exportClause.elements){const p=l.propertyName?.text||l.name.text;(e.moduleSpecifier?this.isReExportTypeOnly(l.name.text):this.isTypeOnly(p))?o.push(l.getText()):c.push(l.getText())}o.length&&t.push(`export type { ${o.join(", ")} }${i?` from ${i}`:""};`),c.length&&s.push(`export { ${c.join(", ")} }${i?` from ${i}`:""};`)}t.length&&this.code.overwrite(e.getStart(),e.getEnd(),[...s,...t].join(`
${Z(e)}`))}analyze(e){for(const t of e){if(this.DEBUG&&console.log(t.getText(),t.kind),r.isImportDeclaration(t)&&t.importClause){this.importNodes.push(t);continue}if(r.isExportDeclaration(t)&&t.exportClause){this.exportNodes.push(t);continue}if(r.isInterfaceDeclaration(t)){this.DEBUG&&console.log(`${t.name.getFullText()} is a type`),this.types.add(t.name.text);continue}if(r.isTypeAliasDeclaration(t)){const s=t.name.text;this.DEBUG&&console.log(`${t.name.getFullText()} is a type`),this.types.add(s);continue}if(r.isEnumDeclaration(t)||r.isFunctionDeclaration(t)||r.isClassDeclaration(t)||r.isVariableStatement(t)){if(r.isVariableStatement(t))for(const s of t.declarationList.declarations)r.isIdentifier(s.name)&&(this.DEBUG&&console.log(`${s.name.getFullText()} is a value (from var statement)`),this.values.add(s.name.text));else t.name&&(this.DEBUG&&console.log(`${t.name.getFullText()} is a value (from declaration)`),this.values.add(t.name.text));continue}if(r.isModuleBlock(t)){this.analyze(t.statements);continue}if(r.isModuleDeclaration(t)){t.name&&r.isIdentifier(t.name)&&(this.DEBUG&&console.log(`${t.name.getFullText()} is a value (from module declaration)`),this.values.add(t.name.text)),this.analyze(t.getChildren());continue}this.DEBUG&&console.log("unhandled statement",t.getFullText(),t.kind)}}isUselessImport(e){const t=this.service.findReferenceCount(e),s=this.typeHints.get(e.text);return s&&s+1>=t}isTypeOnly(e){return this.typeHints.has(e)||this.types.has(e)&&!this.values.has(e)}isReExportTypeOnly(e){return this.reExportTypeHints.has(e)}}function Z(n){const e=n.getFullText().match(/^(?:\n*)([ ]*)/);return" ".repeat(e?.[1]?.length||0)}m(Z,"getNodeIndent");function Ce({sourceFile:n,isEntry:e,isJSON:t}){const s=new q(n.getFullText()),i=!e&&Ie(n),o=new Set,c=new Set;let l="";const p=new Map,f=new Map;for(const a of n.statements){if(r.isEmptyStatement(a)){s.remove(a.getStart(),a.getEnd());continue}if(r.isImportDeclaration(a)){if(!a.importClause)continue;a.importClause.name&&o.add(a.importClause.name.text),a.importClause.namedBindings&&(r.isNamespaceImport(a.importClause.namedBindings)?o.add(a.importClause.namedBindings.name.text):a.importClause.namedBindings.elements.forEach(d=>o.add(d.name.text)))}else if(r.isEnumDeclaration(a)||r.isFunctionDeclaration(a)||r.isInterfaceDeclaration(a)||r.isClassDeclaration(a)||r.isTypeAliasDeclaration(a)||r.isModuleDeclaration(a)){if(a.name){const d=a.name.getText();o.add(d),L(a,r.ModifierFlags.ExportDefault)?l=d:(i&&r.isIdentifier(a.name)||L(a,r.ModifierFlags.Export))&&c.add(d),a.flags&r.NodeFlags.GlobalAugmentation||K(d,[U(a),te(a)])}r.isModuleDeclaration(a)&&we(s,a),ee(s,a)}else if(r.isVariableStatement(a)){const{declarations:d}=a.declarationList,S=L(a,r.ModifierFlags.Export);for(const v of a.declarationList.declarations)if(r.isIdentifier(v.name)){const I=v.name.getText();o.add(I),(i||S)&&c.add(I)}if(ee(s,a),d.length===1){const v=d[0];r.isIdentifier(v.name)&&K(v.name.getText(),[U(a),te(a)])}else{const v=d.slice(),I=v.shift();K(I.name.getText(),[U(a),I.getEnd()]);for(const O of v)r.isIdentifier(O.name)&&K(O.name.getText(),[O.getFullStart(),O.getEnd()])}const{flags:y}=a.declarationList,P=`declare ${y&r.NodeFlags.Let?"let":y&r.NodeFlags.Const?"const":"var"} `,$=a.declarationList.getChildren().find(v=>v.kind===r.SyntaxKind.SyntaxList).getChildren();let b=0;for(const v of $)if(v.kind===r.SyntaxKind.CommaToken)b=v.getStart(),s.remove(b,v.getEnd());else if(b){s.appendLeft(b,`;
`);const I=v.getFullStart(),O=s.slice(I,v.getStart()),H=O.length-O.trimStart().length;H?s.overwrite(I,I+H,P):s.appendLeft(I,P)}}}for(const a of n.statements)if(w(a),!!L(a,r.ModifierFlags.ExportDefault)&&(r.isFunctionDeclaration(a)||r.isClassDeclaration(a))){if(a.name)continue;l||(l=D("export_default"));const d=a.getChildren(),S=d.findIndex($=>$.kind===r.SyntaxKind.ClassKeyword||$.kind===r.SyntaxKind.FunctionKeyword),y=d[S],F=d[S+1];if(F.kind>=r.SyntaxKind.FirstPunctuation&&F.kind<=r.SyntaxKind.LastPunctuation){const $=s.slice(y.getEnd(),F.getStart())!=" ";s.appendLeft(F.getStart(),`${$?" ":""}${l}`)}else s.appendRight(y.getEnd(),` ${l}`)}for(const a of f.values()){const S=a.pop()[0];for(const y of a)s.move(y[0],y[1],S)}l&&s.append(`
export default ${l};
`),c.size&&s.append(`
export { ${[...c].join(", ")} };
`),t&&c.size&&(l=D("export_default"),s.append([`
declare const ${l}: {`,[...c].map(a=>` ${a}: typeof ${a};`).join(`
`),"};",`export default ${l};
`].join(`
`)));for(const[a,d]of p.entries())s.prepend(`import * as ${d} from "${a}";
`);const u=n.getLineStarts(),h=new Set;for(const a of n.typeReferenceDirectives){h.add(a.fileName);const{line:d}=n.getLineAndCharacterOfPosition(a.pos),S=u[d];let y=n.getLineEndOfPosition(a.pos);s.slice(y,y+1)===`
`&&(y+=1),s.remove(S,y)}const g=new Set;for(const a of n.referencedFiles){g.add(a.fileName);const{line:d}=n.getLineAndCharacterOfPosition(a.pos),S=u[d];let y=n.getLineEndOfPosition(a.pos);s.slice(y,y+1)===`
`&&(y+=1),s.remove(S,y)}return{code:s,typeReferences:h,fileReferences:g};function w(a){if(r.forEachChild(a,w),r.isImportTypeNode(a)){if(!r.isLiteralTypeNode(a.argument)||!r.isStringLiteral(a.argument.literal))throw new x(a,"inline imports should have a literal argument");const d=a.argument.literal.text,S=a.getChildren(),y=S.find(b=>b.kind===r.SyntaxKind.ImportKeyword).getStart();let F=a.getEnd();const P=S.find(b=>b.kind===r.SyntaxKind.DotToken||b.kind===r.SyntaxKind.LessThanToken);P&&(F=P.getStart());const $=C(d);s.overwrite(y,F,$)}}function C(a){let d=p.get(a);return d||(d=D(be(a)),p.set(a,d)),d}function D(a){let d=a;for(;o.has(d);)d=`_${d}`;return o.add(d),d}function K(a,d){let S=f.get(a);if(!S)S=[d],f.set(a,S);else{const y=S[S.length-1];y[1]===d[0]?y[1]=d[1]:S.push(d)}}}m(Ce,"preProcess");function Ie(n){let e=!1;for(const t of n.statements){if(r.isExportDeclaration(t)||r.isExportAssignment(t))return!1;(e||r.isImportDeclaration(t)||L(t,r.ModifierFlags.Export))&&(e=!0)}return e}m(Ie,"isGlobalModule");function ee(n,e){if(!r.canHaveModifiers(e))return;let t=!1;const s=r.isEnumDeclaration(e)||r.isClassDeclaration(e)||r.isFunctionDeclaration(e)||r.isModuleDeclaration(e)||r.isVariableStatement(e);for(const i of e.modifiers??[])switch(i.kind){case r.SyntaxKind.ExportKeyword:case r.SyntaxKind.DefaultKeyword:n.remove(i.getStart(),i.getEnd()+1);break;case r.SyntaxKind.DeclareKeyword:t=!0}s&&!t&&n.appendRight(e.getStart(),"declare ")}m(ee,"fixModifiers");function we(n,e){if(!(!e.body||!r.isModuleBlock(e.body))){for(const t of e.body.statements)if(r.isExportDeclaration(t)&&t.exportClause){if(r.isNamespaceExport(t.exportClause))continue;for(const s of t.exportClause.elements)s.propertyName||n.appendLeft(s.name.getEnd(),` as ${s.name.getText()}`)}}}m(we,"duplicateExports");function be(n){return n.replace(/[^a-zA-Z0-9_$]/g,()=>"_")}m(be,"getSafeName");function U(n){const e=n.getFullStart();return e+(re(n,e)?1:0)}m(U,"getStart");function te(n){const e=n.getEnd();return e+(re(n,e)?1:0)}m(te,"getEnd");function re(n,e){return n.getSourceFile().getFullText()[e]===`
`}m(re,"newlineAt");const Fe=new Set([r.SyntaxKind.LiteralType,r.SyntaxKind.VoidKeyword,r.SyntaxKind.UnknownKeyword,r.SyntaxKind.AnyKeyword,r.SyntaxKind.BooleanKeyword,r.SyntaxKind.NumberKeyword,r.SyntaxKind.StringKeyword,r.SyntaxKind.ObjectKeyword,r.SyntaxKind.NullKeyword,r.SyntaxKind.UndefinedKeyword,r.SyntaxKind.SymbolKeyword,r.SyntaxKind.NeverKeyword,r.SyntaxKind.ThisKeyword,r.SyntaxKind.ThisType,r.SyntaxKind.BigIntKeyword]);class se{static{m(this,"DeclarationScope")}constructor({id:e,range:t}){if(this.scopes=[],e)this.declaration=Ee(e,t);else{const{iife:i,fn:o}=Te(t);this.iife=i,this.declaration=o}const s=ve();this.declaration.body.body.push(s.stmt),this.returnExpr=s.expr}pushScope(){this.scopes.push(new Set)}popScope(e=1){for(let t=0;t<e;t++)this.scopes.pop()}pushTypeVariable(e){const t=e.getText();this.scopes[this.scopes.length-1]?.add(t)}pushReference(e){let t;if(e.type==="Identifier"?t=e.name:e.type==="MemberExpression"&&e.object.type==="Identifier"&&(t=e.object.name),t){for(const o of this.scopes)if(o.has(t))return}if(t==="this")return;const{ident:s,expr:i}=Se(e);this.declaration.params.push(i),this.returnExpr.elements.push(s)}pushIdentifierReference(e){this.pushReference(N(e))}convertEntityName(e){return r.isIdentifier(e)?N(e):E({type:"MemberExpression",computed:!1,optional:!1,object:this.convertEntityName(e.left),property:N(e.right)},e)}convertPropertyAccess(e){if(!r.isIdentifier(e.expression)&&!r.isPropertyAccessExpression(e.expression))throw new x(e.expression);if(r.isPrivateIdentifier(e.name))throw new x(e.name);const t=r.isIdentifier(e.expression)?N(e.expression):this.convertPropertyAccess(e.expression);return E({type:"MemberExpression",computed:!1,optional:!1,object:t,property:N(e.name)},e)}convertComputedPropertyName(e){if(!e.name||!r.isComputedPropertyName(e.name))return;const{expression:t}=e.name;if(!(r.isLiteralExpression(t)||r.isPrefixUnaryExpression(t))){if(r.isIdentifier(t))return this.pushReference(N(t));if(r.isPropertyAccessExpression(t))return this.pushReference(this.convertPropertyAccess(t));throw new x(t)}}convertParametersAndType(e){this.convertComputedPropertyName(e);const t=this.convertTypeParameters(e.typeParameters);for(const s of e.parameters)this.convertTypeNode(s.type);this.convertTypeNode(e.type),this.popScope(t)}convertHeritageClauses(e){for(const t of e.heritageClauses||[])for(const s of t.types)this.pushReference(A(s.expression)),this.convertTypeArguments(s)}convertTypeArguments(e){if(e.typeArguments)for(const t of e.typeArguments)this.convertTypeNode(t)}convertMembers(e){for(const t of e){if(r.isPropertyDeclaration(t)||r.isPropertySignature(t)||r.isIndexSignatureDeclaration(t)){r.isPropertyDeclaration(t)&&t.initializer&&r.isPropertyAccessExpression(t.initializer)&&this.pushReference(this.convertPropertyAccess(t.initializer)),this.convertComputedPropertyName(t),this.convertTypeNode(t.type);continue}if(r.isMethodDeclaration(t)||r.isMethodSignature(t)||r.isConstructorDeclaration(t)||r.isConstructSignatureDeclaration(t)||r.isCallSignatureDeclaration(t)||r.isGetAccessorDeclaration(t)||r.isSetAccessorDeclaration(t))this.convertParametersAndType(t);else throw new x(t)}}convertTypeParameters(e){if(!e)return 0;for(const t of e)this.convertTypeNode(t.constraint),this.convertTypeNode(t.default),this.pushScope(),this.pushTypeVariable(t.name);return e.length}convertTypeNode(e){if(e&&!Fe.has(e.kind)){if(r.isTypeReferenceNode(e)){this.pushReference(this.convertEntityName(e.typeName)),this.convertTypeArguments(e);return}if(r.isTypeLiteralNode(e)){this.convertMembers(e.members);return}if(r.isArrayTypeNode(e)){this.convertTypeNode(e.elementType);return}if(r.isTupleTypeNode(e)){for(const t of e.elements)this.convertTypeNode(t);return}if(r.isNamedTupleMember(e)||r.isParenthesizedTypeNode(e)||r.isTypeOperatorNode(e)||r.isTypePredicateNode(e)){this.convertTypeNode(e.type);return}if(r.isUnionTypeNode(e)||r.isIntersectionTypeNode(e)){for(const t of e.types)this.convertTypeNode(t);return}if(r.isMappedTypeNode(e)){const{typeParameter:t,type:s,nameType:i}=e;this.convertTypeNode(t.constraint),this.pushScope(),this.pushTypeVariable(t.name),this.convertTypeNode(s),i&&this.convertTypeNode(i),this.popScope();return}if(r.isConditionalTypeNode(e)){this.convertTypeNode(e.checkType),this.pushScope(),this.convertTypeNode(e.extendsType),this.convertTypeNode(e.trueType),this.convertTypeNode(e.falseType),this.popScope();return}if(r.isIndexedAccessTypeNode(e)){this.convertTypeNode(e.objectType),this.convertTypeNode(e.indexType);return}if(r.isFunctionOrConstructorTypeNode(e)){this.convertParametersAndType(e);return}if(r.isTypeQueryNode(e)){this.pushReference(this.convertEntityName(e.exprName));return}if(r.isRestTypeNode(e)){this.convertTypeNode(e.type);return}if(r.isOptionalTypeNode(e)){this.convertTypeNode(e.type);return}if(r.isTemplateLiteralTypeNode(e)){for(const t of e.templateSpans)this.convertTypeNode(t.type);return}if(r.isInferTypeNode(e)){const{typeParameter:t}=e;this.convertTypeNode(t.constraint),this.pushTypeVariable(t.name);return}else throw new x(e)}}convertNamespace(e,t=!1){if(this.pushScope(),t&&e.body&&r.isModuleDeclaration(e.body)){this.convertNamespace(e.body,!0);return}if(!e.body||!r.isModuleBlock(e.body))throw new x(e,'namespace must have a "ModuleBlock" body.');const{statements:s}=e.body;for(const i of s){if(r.isEnumDeclaration(i)||r.isFunctionDeclaration(i)||r.isClassDeclaration(i)||r.isInterfaceDeclaration(i)||r.isTypeAliasDeclaration(i)||r.isModuleDeclaration(i)){if(i.name&&r.isIdentifier(i.name))this.pushTypeVariable(i.name);else throw new x(i,"non-Identifier name not supported");continue}if(r.isVariableStatement(i)){for(const o of i.declarationList.declarations)if(r.isIdentifier(o.name))this.pushTypeVariable(o.name);else throw new x(o,"non-Identifier name not supported");continue}if(!r.isExportDeclaration(i))throw new x(i,"namespace child (hoisting) not supported yet")}for(const i of s){if(r.isVariableStatement(i)){for(const o of i.declarationList.declarations)o.type&&this.convertTypeNode(o.type);continue}if(r.isFunctionDeclaration(i)){this.convertParametersAndType(i);continue}if(r.isInterfaceDeclaration(i)||r.isClassDeclaration(i)){const o=this.convertTypeParameters(i.typeParameters);this.convertHeritageClauses(i),this.convertMembers(i.members),this.popScope(o);continue}if(r.isTypeAliasDeclaration(i)){const o=this.convertTypeParameters(i.typeParameters);this.convertTypeNode(i.type),this.popScope(o);continue}if(r.isModuleDeclaration(i)){this.convertNamespace(i,t);continue}if(!r.isEnumDeclaration(i))if(r.isExportDeclaration(i)){if(i.exportClause){if(r.isNamespaceExport(i.exportClause))throw new x(i.exportClause);for(const o of i.exportClause.elements){const c=o.propertyName||o.name;this.pushIdentifierReference(c)}}}else throw new x(i,"namespace child (walking) not supported yet")}this.popScope()}}function $e({sourceFile:n}){return new Oe(n).transform()}m($e,"convert");class Oe{static{m(this,"Transformer")}constructor(e){this.sourceFile=e,this.declarations=new Map,this.ast=xe(e);for(const t of e.statements)this.convertStatement(t)}transform(){return{ast:this.ast}}pushStatement(e){this.ast.body.push(e)}createDeclaration(e,t){const s={start:e.getFullStart(),end:e.getEnd()};if(!t){const l=new se({range:s});return this.pushStatement(l.iife),l}const i=t.getText(),o=new se({id:t,range:s}),c=this.declarations.get(i);if(c){c.pushIdentifierReference(t),c.declaration.end=s.end;const l=this.ast.body.findIndex(p=>p==c.declaration);for(let p=l+1;p<this.ast.body.length;p++){const f=this.ast.body[p];f.start=f.end=s.end}}else this.pushStatement(o.declaration),this.declarations.set(i,o);return c||o}convertStatement(e){if(r.isEnumDeclaration(e))return this.convertEnumDeclaration(e);if(r.isFunctionDeclaration(e))return this.convertFunctionDeclaration(e);if(r.isInterfaceDeclaration(e)||r.isClassDeclaration(e))return this.convertClassOrInterfaceDeclaration(e);if(r.isTypeAliasDeclaration(e))return this.convertTypeAliasDeclaration(e);if(r.isVariableStatement(e))return this.convertVariableStatement(e);if(r.isExportDeclaration(e)||r.isExportAssignment(e))return this.convertExportDeclaration(e);if(r.isModuleDeclaration(e))return this.convertNamespaceDeclaration(e);if(e.kind===r.SyntaxKind.NamespaceExportDeclaration)return this.removeStatement(e);if(r.isImportDeclaration(e)||r.isImportEqualsDeclaration(e))return this.convertImportDeclaration(e);throw new x(e)}removeStatement(e){this.pushStatement(E({type:"ExpressionStatement",expression:{type:"Literal",value:"pls remove me"}},e))}convertNamespaceDeclaration(e){if(e.flags&r.NodeFlags.GlobalAugmentation||!r.isIdentifier(e.name)){this.createDeclaration(e).convertNamespace(e,!0);return}const s=this.createDeclaration(e,e.name);s.pushIdentifierReference(e.name),s.convertNamespace(e)}convertEnumDeclaration(e){this.createDeclaration(e,e.name).pushIdentifierReference(e.name)}convertFunctionDeclaration(e){if(!e.name)throw new x(e,"FunctionDeclaration should have a name");const t=this.createDeclaration(e,e.name);t.pushIdentifierReference(e.name),t.convertParametersAndType(e)}convertClassOrInterfaceDeclaration(e){if(!e.name)throw new x(e,"ClassDeclaration / InterfaceDeclaration should have a name");const t=this.createDeclaration(e,e.name),s=t.convertTypeParameters(e.typeParameters);t.convertHeritageClauses(e),t.convertMembers(e.members),t.popScope(s)}convertTypeAliasDeclaration(e){const t=this.createDeclaration(e,e.name),s=t.convertTypeParameters(e.typeParameters);t.convertTypeNode(e.type),t.popScope(s)}convertVariableStatement(e){const{declarations:t}=e.declarationList;if(t.length!==1)throw new x(e,"VariableStatement with more than one declaration not yet supported");for(const s of t){if(!r.isIdentifier(s.name))throw new x(e,"VariableDeclaration must have a name");this.createDeclaration(e,s.name).convertTypeNode(s.type)}}convertExportDeclaration(e){if(r.isExportAssignment(e)){this.pushStatement(E({type:"ExportDefaultDeclaration",declaration:A(e.expression)},e));return}const t=e.moduleSpecifier?A(e.moduleSpecifier):void 0;if(!e.exportClause)this.pushStatement(E({type:"ExportAllDeclaration",source:t,exported:null},e));else if(r.isNamespaceExport(e.exportClause))this.pushStatement(E({type:"ExportAllDeclaration",source:t,exported:N(e.exportClause.name)},e));else{const s=[];for(const i of e.exportClause.elements)s.push(this.convertExportSpecifier(i));this.pushStatement(E({type:"ExportNamedDeclaration",declaration:null,specifiers:s,source:t},e))}}convertImportDeclaration(e){if(r.isImportEqualsDeclaration(e)){if(r.isEntityName(e.moduleReference)){const i=this.createDeclaration(e,e.name);i.pushReference(i.convertEntityName(e.moduleReference));return}if(!r.isExternalModuleReference(e.moduleReference))throw new x(e,"ImportEquals should have a literal source.");this.pushStatement(E({type:"ImportDeclaration",specifiers:[{type:"ImportDefaultSpecifier",local:N(e.name)}],source:A(e.moduleReference.expression)},e));return}const t=A(e.moduleSpecifier),s=e.importClause&&e.importClause.namedBindings?this.convertNamedImportBindings(e.importClause.namedBindings):[];e.importClause&&e.importClause.name&&s.push({type:"ImportDefaultSpecifier",local:N(e.importClause.name)}),this.pushStatement(E({type:"ImportDeclaration",specifiers:s,source:t},e))}convertNamedImportBindings(e){return r.isNamedImports(e)?e.elements.map(t=>{const s=N(t.name),i=t.propertyName?N(t.propertyName):s;return{type:"ImportSpecifier",local:s,imported:i}}):[{type:"ImportNamespaceSpecifier",local:N(e.name)}]}convertExportSpecifier(e){const t=N(e.name);return{type:"ExportSpecifier",exported:t,local:e.propertyName?N(e.propertyName):t}}}const Ae=m(()=>{const n=new Map,e=new Map;return{name:"dts-transform",options({onLog:t,...s}){return{...s,onLog(i,o,c){i==="warn"&&o.code==="CIRCULAR_DEPENDENCY"||(t?t(i,o,c):c(i,o))},treeshake:{moduleSideEffects:"no-external",propertyReadSideEffects:!0,unknownGlobalSideEffects:!1}}},outputOptions(t){return{...t,chunkFileNames:t.chunkFileNames||"[name]-[hash].d.ts",entryFileNames:t.entryFileNames||"[name].d.ts",format:"es",exports:"named",compact:!1,freeze:!0,interop:"esModule",generatedCode:Object.assign({symbols:!1},t.generatedCode),strict:!1}},transform(t,s){const i=B(s),o=this.getModuleIds(),c=Array.from(o).find(g=>B(g)===i),l=!!(c&&this.getModuleInfo(c)?.isEntry),p=!!(c&&_.test(c));let f=j(s,t);const u=Ce({sourceFile:f,isEntry:l,isJSON:p});n.set(f.fileName,u.typeReferences),e.set(f.fileName,u.fileReferences),t=u.code.toString(),f=j(s,t);const h=$e({sourceFile:f});return process.env.DTS_DUMP_AST&&(console.log(s),console.log(t),console.log(JSON.stringify(h.ast.body,void 0,2))),{code:t,ast:h.ast,map:u.code.generateMap()}},renderChunk(t,s,i){const o=j(s.fileName,t),c=new ge(o),l=new Set,p=new Set;for(const h of Object.keys(s.modules)){for(const g of n.get(h.split("\\").join("/"))||[])l.add(g);for(const g of e.get(h.split("\\").join("/"))||[])if(g.startsWith(".")){const w=T.join(T.dirname(h),g),C=i.file&&T.dirname(i.file)||s.facadeModuleId&&T.dirname(s.facadeModuleId)||".";let D=T.relative(C,w).split("\\").join("/");D[0]!=="."&&(D="./"+D),p.add(D)}else p.add(g)}let f=ie(Array.from(p,h=>`/// <reference path="${h}" />`));return f+=ie(Array.from(l,h=>`/// <reference types="${h}" />`)),f+=c.fix(),f||(f+=`
export { };`),new De(s.fileName,f,!!i.sourcemap).fix()}}},"transform");function ie(n){return n.length?n.join(`
`)+`
`:""}m(ie,"writeBlock");const Pe=/\.([cm]ts|[tj]sx?)$/;function G({entries:n,programs:e,resolvedOptions:{compilerOptions:t,tsconfig:s}},i,o){if(!e.length&&k.test(i))return{code:o};const c=n.includes(i),l=e.find(p=>{if(c)return p.getRootFileNames().includes(i);{const f=p.getSourceFile(i);return f&&p.isSourceFileFromExternalLibrary(f)?!1:!!f}});if(l){const p=l.getSourceFile(i);return{code:p?.getFullText(),source:p,program:l}}else if(r.sys.fileExists(i)){const p=me(i,t,s);e.push(p);const f=p.getSourceFile(i);return{code:f?.getFullText(),source:f,program:p}}else return null}m(G,"getModule");const ne=m((n={})=>{const e=Ae(),t={entries:[],programs:[],resolvedOptions:pe(n)};return{name:"dts",outputOptions:e.outputOptions,renderChunk:e.renderChunk,options(s){let{input:i=[]}=s;if(!Array.isArray(i))i=typeof i=="string"?[i]:Object.values(i);else if(i.length>1){s.input={};for(const o of i){let c=B(o);T.isAbsolute(o)?c=T.basename(c):c=T.normalize(c),s.input[c]=o}}return t.programs=ue(Object.values(i),t.resolvedOptions.compilerOptions,t.resolvedOptions.tsconfig),e.options.call(this,s)},transform(s,i){if(!Pe.test(i)&&!_.test(i))return null;const o=m(f=>{if(f.program){const u=T.dirname(i);f.program.getSourceFiles().map(g=>g.fileName).filter(g=>g.startsWith(u)).forEach(this.addWatchFile)}},"watchFiles"),c=m(()=>{const f=G(t,i,s);return f?(o(f),e.transform.call(this,f.code,i)):null},"handleDtsFile"),l=m(()=>{const f=J(i),u=G(t,f,s);return u?(o(u),e.transform.call(this,u.code,f)):null},"treatTsAsDts"),p=m(()=>{const f=G(t,i,s);if(!f||!f.source||!f.program)return null;o(f);const u=J(i);let h;const{emitSkipped:g,diagnostics:w}=f.program.emit(f.source,(C,D)=>{h=e.transform.call(this,D,u)},void 0,!0,void 0,!0);if(g){const C=w.filter(D=>D.category===r.DiagnosticCategory.Error);C.length&&(console.error(r.formatDiagnostics(C,V)),this.error("Failed to compile. Check the logs above."))}return h},"generateDts");return k.test(i)?c():_.test(i)?p():l()??p()},resolveId(s,i){if(!i){t.entries.push(T.resolve(s));return}i=i.split("\\").join("/");let o=t.resolvedOptions.compilerOptions;if(t.resolvedOptions.tsconfig){const l=s.startsWith(".")?T.resolve(T.dirname(i),s):s;o=z(l,t.resolvedOptions.compilerOptions,t.resolvedOptions.tsconfig).compilerOptions}const{resolvedModule:c}=r.resolveModuleName(s,i,o,r.sys);if(c)return!t.resolvedOptions.respectExternal&&c.isExternalLibraryImport?{id:s,external:!0}:{id:T.resolve(c.resolvedFileName)}}}},"plugin");export{ne as default,ne as dts};