Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/sxzz/rolldown-plugin-dts. A Rolldown plugin to generate and bundle dts files.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330import { b, walk } from 'yuku'import { is, isIdentifierName } from 'yuku/utils'import { getIdentifierIndex, getIdFromTSEntityName, isReferenceId, isThisExpression, overwriteNode, TSEntityNameToRuntime,} from './utils.ts'import type { Dep, NamespaceMap, TypeParams } from './types.ts'import type { TransformPluginContext } from 'rolldown'import type * as t from 'yuku'
/** * Collects all TSTypeParameter nodes from the given node and groups them by * their name. One name can associate with one or more type parameters. These * names will be used as the parameter name in the generated JavaScript * dependency function. */export function collectParams(node: t.Node): TypeParams { const typeParams: t.Identifier[] = [] walk(node, { leave(node) { if ( 'typeParameters' in node && node.typeParameters?.type === 'TSTypeParameterDeclaration' ) { typeParams.push(...node.typeParameters.params.map(({ name }) => name)) } }, })
const paramMap = new Map<string, t.Identifier[]>() for (const typeParam of typeParams) { const name = typeParam.name const group = paramMap.get(name) if (group) { group.push(typeParam) } else { paramMap.set(name, [typeParam]) } }
return Array.from(paramMap, ([name, typeParams]) => ({ name, typeParams, }))}
/** * Member names of a namespace. Reported to the bundler as unresolved globals, * so no top-level binding takes a name that a member would shadow. */export function collectNamespaceMembers(node: t.Node): string[] { if ( node.type !== 'TSModuleDeclaration' || node.kind === 'global' || is.StringLiteral(node.id) || node.body?.type !== 'TSModuleBlock' ) { return [] }
const names: string[] = [] for (const stmt of node.body.body) { const decl = stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt if (decl?.type === 'VariableDeclaration') { for (const { id } of decl.declarations) { if (id.type === 'Identifier') names.push(id.name) } } else if (decl && 'id' in decl && decl.id?.type === 'Identifier') { names.push(decl.id.name) } } return names}
export async function collectDependencies( context: TransformPluginContext, node: t.Node, importer: string, namespaceStmts: NamespaceMap, children: Set<t.Node>, identifierMap: Record<string, number>,): Promise<Dep[]> { const bundledImports = await resolveImportTypes(context, node, importer) const deps = new Set<Dep>() const seen = new Set<t.Node>()
const inferredStack: string[][] = [] let currentInferred = new Set<string>() function isInferred(node: t.Node): boolean { return node.type === 'Identifier' && currentInferred.has(node.name) }
walk(node, { enter(node) { if (node.type !== 'TSConditionalType') return
const inferred = collectInferredNames(node.extendsType) inferredStack.push(inferred) }, leave(node, ctx) { const { parent } = ctx
// handle infer scope if (node.type === 'TSConditionalType') { inferredStack.pop() } else if (parent?.type === 'TSConditionalType') { const trueBranch = parent.trueType === node currentInferred = new Set<string>( (trueBranch ? inferredStack : inferredStack.slice(0, -1)).flat(), ) } else { currentInferred = new Set<string>() }
if (node.type === 'ExportNamedDeclaration') { for (const specifier of node.specifiers) { if (specifier.type === 'ExportSpecifier') { addDependency(specifier.local) } } } else if (node.type === 'TSInterfaceDeclaration' && node.extends) { for (const heritage of node.extends || []) { addDependency(heritage.expression) } } else if (node.type === 'ClassDeclaration') { if (node.superClass) addDependency(node.superClass) if (node.implements) { for (const implement of node.implements) { addDependency(implement.expression) } } } else if ( is.oneOf(node, [ 'Property', 'PropertyDefinition', 'TSAbstractPropertyDefinition', 'MethodDefinition', 'TSAbstractMethodDefinition', 'TSPropertySignature', 'TSMethodSignature', ]) ) { if (node.computed && isReferenceId(node.key)) { addDependency(node.key) } if ( 'value' in node && parent?.type !== 'ObjectPattern' && isReferenceId(node.value) ) { addDependency(node.value) } } else { switch (node.type) { case 'TSTypeReference': { addDependency(TSEntityNameToRuntime(node.typeName)) break } case 'TSQualifiedName': { // A qualified name inside one of these parents is resolved there as // a whole (`ns.A` as a member of `ns`); adding its leftmost // identifier as well would keep the entire namespace. if ( parent && is.oneOf(parent, [ 'TSTypeReference', 'TSTypeQuery', 'TSQualifiedName', 'TSImportType', ]) ) break addDependency(getIdFromTSEntityName(node.left)) break } case 'TSTypeQuery': { if (seen.has(node.exprName)) return if (node.exprName.type === 'TSImportType') break
addDependency(TSEntityNameToRuntime(node.exprName))
break } case 'TSImportType': { seen.add(node) const { source, qualifier } = node if (!bundledImports.has(source.value)) break
const dep = importNamespace( node, qualifier, source, namespaceStmts, identifierMap, ) if (dep) addDependency(dep) break } } }
if (parent && !deps.has(node as Dep) && isChildSymbol(node, parent)) { children.add(node) } }, })
return Array.from(deps)
function addDependency(node: Dep) { if (isThisExpression(node) || isInferred(node)) return deps.add(node) }}
async function resolveImportTypes( context: TransformPluginContext, node: t.Node, importer: string,): Promise<Set<string>> { const sources = new Set<string>() walk(node, { TSImportType(node) { sources.add(node.source.value) }, })
const bundled = new Set<string>() await Promise.all( Array.from(sources, async (source) => { const resolved = await context.resolve(source, importer) if (resolved && !resolved.external) bundled.add(source) }), ) return bundled}
function importNamespace( node: t.TSImportType, imported: t.TSTypeName | null | undefined, source: t.StringLiteral, namespaceStmts: NamespaceMap, identifierMap: Record<string, number>,): Dep | undefined { const sourceText = source.value.replaceAll(/\W/g, '_') // Use original source if it's already a valid identifier, // otherwise use formatted text with index. const localName = `_$${ isIdentifierName(source.value) ? source.value : `${sourceText}${getIdentifierIndex(identifierMap, sourceText)}` }` let local: t.Identifier | t.TSQualifiedName = b.Identifier({ name: localName, })
if (namespaceStmts.has(source.value)) { local = namespaceStmts.get(source.value)!.local } else { // prepend: import * as ${local} from ${source} namespaceStmts.set(source.value, { stmt: b.ImportDeclaration({ specifiers: [b.ImportNamespaceSpecifier({ local })], source, }), local, }) }
if (imported) { const importedLeft = getIdFromTSEntityName(imported) if ( imported.type === 'ThisExpression' || importedLeft.type === 'ThisExpression' ) { throw new Error('Cannot import `this` from module.') } overwriteNode( importedLeft, b.TSQualifiedName({ left: local, right: { ...importedLeft } }), ) local = imported }
let replacement: t.Node = node if (node.typeArguments) { overwriteNode( node, b.TSTypeReference({ typeName: local, typeArguments: node.typeArguments }), ) replacement = local } else { overwriteNode(node, local) }
const dep: Dep = { ...TSEntityNameToRuntime(local), replace(newNode) { overwriteNode(replacement, newNode) }, } return dep}
function isChildSymbol(node: t.Node, parent: t.Node) { if (node.type === 'Identifier') return true if ( is.oneOf(parent, ['TSPropertySignature', 'TSMethodSignature']) && parent.key === node ) return true
return false}
function collectInferredNames(node: t.Node) { const inferred: string[] = [] walk(node, { TSInferType(node) { inferred.push(node.typeParameter.name.name) }, }) return inferred}