1 | import * as tsm from 'ts-morph';
|
2 | import {
|
3 | DeclarationKinds,
|
4 | FunctionDeclaration,
|
5 | } from '../types/module-declarations';
|
6 | import { formatFunctionSignature } from './format';
|
7 | import { getJSDocs } from './get-jsdocs';
|
8 | import { hasFunctionLikeType } from './has-function-like-type';
|
9 | import { SourceProvider } from './source-provider';
|
10 | import { TypeChecker } from './type-checker';
|
11 |
|
12 | export function isFunction(
|
13 | declaration: tsm.Node
|
14 | ): declaration is tsm.FunctionDeclaration {
|
15 | return (
|
16 | tsm.Node.isFunctionDeclaration(declaration) &&
|
17 | (declaration.isAmbient() || declaration.isImplementation())
|
18 | );
|
19 | }
|
20 |
|
21 | export function newFunction({
|
22 | id,
|
23 | name,
|
24 | declaration,
|
25 | getSource,
|
26 | getType,
|
27 | }: {
|
28 | id: string;
|
29 | name: string;
|
30 | declaration: tsm.FunctionDeclaration;
|
31 | getSource: SourceProvider;
|
32 | getType: TypeChecker;
|
33 | }): FunctionDeclaration {
|
34 | const kind = DeclarationKinds.FunctionDeclaration;
|
35 | const docs = getJSDocs({ declaration });
|
36 | const source = getSource({ declaration });
|
37 | const type = getType({ declaration });
|
38 | const signature = getFunctionSignature({ name, type });
|
39 |
|
40 | return {
|
41 | kind,
|
42 | id,
|
43 | name,
|
44 | docs,
|
45 | source,
|
46 | signature,
|
47 | type,
|
48 | };
|
49 | }
|
50 |
|
51 | export function isFunctionExpression(
|
52 | declaration: tsm.Node
|
53 | ): declaration is tsm.VariableDeclaration {
|
54 | return (
|
55 | tsm.Node.isVariableDeclaration(declaration) &&
|
56 | hasFunctionLikeType(declaration)
|
57 | );
|
58 | }
|
59 |
|
60 | export function newFunctionExpression({
|
61 | id,
|
62 | name,
|
63 | declaration,
|
64 | getSource,
|
65 | getType,
|
66 | }: {
|
67 | id: string;
|
68 | name: string;
|
69 | declaration: tsm.VariableDeclaration;
|
70 | getSource: SourceProvider;
|
71 | getType: TypeChecker;
|
72 | }): FunctionDeclaration {
|
73 | const kind = DeclarationKinds.FunctionDeclaration;
|
74 | const docs = getJSDocs({ declaration });
|
75 | const source = getSource({ declaration });
|
76 | const type = getType({ declaration });
|
77 | const signature = getFunctionSignature({ name, type });
|
78 |
|
79 | return {
|
80 | kind,
|
81 | id,
|
82 | name,
|
83 | docs,
|
84 | source,
|
85 | signature,
|
86 | type,
|
87 | };
|
88 | }
|
89 |
|
90 | function getFunctionSignature({
|
91 | name,
|
92 | type,
|
93 | }: {
|
94 | name: string;
|
95 | type: string;
|
96 | }): string {
|
97 | const signature = `${name}: ${type}`;
|
98 | return formatFunctionSignature(signature);
|
99 | }
|