idlize
60 строк · 2.5 Кб
1import * as ts from 'typescript'2import { ImportFeature, ImportsCollector } from './ImportsCollector'3
4const syntheticDeclarations: Map<string, {node: ts.Declaration, filename: string, dependencies: ImportFeature[]}> = new Map()5export function makeSyntheticDeclaration(targetFilename: string, declName: string, factory: () => ts.Declaration): ts.Declaration {6if (!syntheticDeclarations.has(declName))7syntheticDeclarations.set(declName, {node: factory(), filename: targetFilename, dependencies: []})8const decl = syntheticDeclarations.get(declName)!9if (decl.filename !== targetFilename)10throw "Two declarations with same name were declared"11return decl.node12}
13
14export function addSyntheticDeclarationDependency(node: ts.Declaration, dependency: ImportFeature) {15for (const decl of syntheticDeclarations.values())16if (decl.node === node) {17decl.dependencies.push(dependency)18return19}20throw "Declaration is not synthetic"21}
22
23export function makeSyntheticTypeAliasDeclaration(targetFilename: string, declName: string, type: ts.TypeNode): ts.TypeAliasDeclaration {24const decl = makeSyntheticDeclaration(targetFilename, declName, () => {25return ts.factory.createTypeAliasDeclaration(26undefined,27declName,28undefined,29type
30)31})32if (!ts.isTypeAliasDeclaration(decl))33throw "Expected declaration to be a TypeAlias"34return decl35}
36
37export function isSyntheticDeclaration(node: ts.Declaration): boolean {38for (const decl of syntheticDeclarations.values())39if (decl.node === node)40return true41return false42}
43
44export function syntheticDeclarationFilename(node: ts.Declaration): string {45for (const decl of syntheticDeclarations.values())46if (decl.node === node)47return decl.filename48throw "Declaration is not synthetic"49}
50
51export function makeSyntheticDeclarationsFiles(): Map<string, {dependencies: ImportFeature[], declarations: ts.Declaration[]}> {52const files = new Map<string, {dependencies: ImportFeature[], declarations: ts.Declaration[]}>()53for (const decl of syntheticDeclarations.values()) {54if (!files.has(decl.filename))55files.set(decl.filename, {dependencies: [], declarations: []})56files.get(decl.filename)!.declarations.push(decl.node)57files.get(decl.filename)!.dependencies.push(...decl.dependencies)58}59return files60}