UNPKG

1.53 kBPlain TextView Raw
1import * as tsm from 'ts-morph';
2import {
3 DeclarationKinds,
4 ModuleDeclarations,
5 NamespaceDeclaration,
6} from '../types/module-declarations';
7import { formatText } from './format';
8import { getFilename } from './get-filename';
9import { SourceProvider } from './source-provider';
10
11export function isFileModule(
12 declaration: tsm.Node
13): declaration is tsm.SourceFile {
14 return tsm.Node.isSourceFile(declaration);
15}
16
17export function newFileModule({
18 id,
19 name,
20 declaration,
21 declarations,
22 getSource,
23}: {
24 id: string;
25 name: string;
26 declaration: tsm.SourceFile;
27 declarations: ModuleDeclarations;
28 getSource: SourceProvider;
29}): NamespaceDeclaration {
30 const kind = DeclarationKinds.NamespaceDeclaration;
31 const docs = getFileModuleDocs({ declaration });
32 const source = getSource({ declaration });
33 const signature = getFileModuleSignature({ declaration });
34
35 return {
36 kind,
37 id,
38 name,
39 docs,
40 source,
41 signature,
42 declarations,
43 };
44}
45
46function getFileModuleDocs({
47 declaration,
48}: {
49 declaration: tsm.SourceFile;
50}): string[] {
51 const doc = declaration
52 .getDescendantsOfKind(tsm.SyntaxKind.JSDocComment)[0]
53 ?.getText();
54
55 return doc ? [doc] : [];
56}
57
58function getFileModuleSignature({
59 declaration,
60}: {
61 declaration: tsm.SourceFile;
62}): string {
63 const filename = getFilename({ declaration });
64 const signature = `module '${filename}' {}`;
65 return formatText(signature);
66}