1 import ts from "typescript"
2 import DefaultKindGenerator, { GetDocBlockOptions } from "./default.js"
3 import {
4 DOCBLOCK_NEW_LINE,
5 DOCBLOCK_END_LINE,
6 DOCBLOCK_START,
7 DOCBLOCK_DOUBLE_LINES,
8 SUMMARY_PLACEHOLDER,
9 } from "../../constants.js"
10 import getSymbol from "../../utils/get-symbol.js"
11
12 export type FunctionNode =
13 | ts.MethodDeclaration
14 | ts.MethodSignature
15 | ts.FunctionDeclaration
16 | ts.ArrowFunction
17
18 export type VariableNode = ts.VariableDeclaration | ts.VariableStatement
19
20 export type FunctionOrVariableNode = FunctionNode | ts.VariableStatement
21
22 /**
23 * Docblock generator for functions.
24 */
25 // eslint-disable-next-line max-len
26 class FunctionKindGenerator extends DefaultKindGenerator<FunctionOrVariableNode> {
27 protected methodKinds: ts.SyntaxKind[] = [
28 ts.SyntaxKind.MethodDeclaration,
29 ts.SyntaxKind.MethodSignature,
30 ]
31 protected functionKinds: ts.SyntaxKind[] = [ts.SyntaxKind.FunctionDeclaration]
32 protected allowedKinds: ts.SyntaxKind[] = [
33 ...this.methodKinds,
34 ...this.functionKinds,
35 ]
36 public name = "function"
37 static EXAMPLE_PLACEHOLDER = `{example-code}`
38 protected aiParameterExceptions = ["sharedContext"]
39
40 /**
41 * Checks whether a node is considered a function node. A node is considered a function node if:
42 *
43 * 1. It is a method declaration (typically in classes), a method signature (typically in interfaces), or a function declaration.
44 * 2. An arrow function. However, for better docblock placement and formatting, we detect the variable statement surrounding the arrow function
45 * rather than the arrow function itself.
46 *
47 * @param {ts.Node} node - The node to check.
48 * @returns {boolean} Whether the node is a function node and can be handled by this generator.
49 */
50 isAllowed(node: ts.Node): node is FunctionOrVariableNode {
51 if (!super.isAllowed(node)) {
52 return ts.isVariableStatement(node) && this.isFunctionVariable(node)
53 }
54
55 return true
56 }
57
58 /**
59 * Checks whether a node is a variable statement/declaration with underlying node function
60 * using the {@link extractFunctionNode} method.
61 *
62 * @param {ts.Node} node - The node to check.
63 * @returns {boolean} Whether the node is a variable statement/declaration with underlying node function.
64 */
65 isFunctionVariable(node: ts.Node): node is VariableNode {
66 if (ts.isVariableStatement(node)) {
67 return node.declarationList.declarations.some((declaration) => {
68 return this.isFunctionVariable(declaration)
69 })
70 } else if (ts.isVariableDeclaration(node)) {
71 return this.extractFunctionNode(node) !== undefined
72 }
73
74 return false
75 }
76
77 /**
78 * Retrieves the underlying function/method/arrow function of a variable statement or declaration.
79 *
80 * @param {ts.Node} node - The variable statement/declaration to retrieve the function/method from.
81 * @returns The function/method if found.
82 */
83 extractFunctionNode(node: VariableNode): FunctionNode | undefined {
84 if (ts.isVariableStatement(node)) {
85 const variableDeclaration = node.declarationList.declarations.find(
86 (declaration) => ts.isVariableDeclaration(declaration)
87 )
88
89 return variableDeclaration
90 ? this.extractFunctionNode(variableDeclaration)
91 : undefined
92 } else if (
93 node.initializer &&
94 (this.isAllowed(node.initializer) || ts.isArrowFunction(node.initializer))
95 ) {
96 return node.initializer
97 }
98 }
99
100 /**
101 * Check whether a node refers to a method.
102 *
103 * @param {FunctionNode} node - The node to check.
104 * @returns {boolean} Whether the node is a method.
105 */
106 isMethod(
107 node: FunctionNode
108 ): node is ts.MethodDeclaration | ts.MethodSignature {
109 return this.methodKinds.includes(node.kind)
110 }
111
112 /**
113 * Checks whether a type, typically the type of a function's signature, has return data.
114 *
115 * @param {string} typeStr - The type's string representation.
116 * @returns {boolean} Whether the type has return data.
117 */
118 hasReturnData(typeStr: string): boolean {
119 return (
120 typeStr !== "void" &&
121 typeStr !== "never" &&
122 typeStr !== "Promise<void>" &&
123 typeStr !== "Promise<never>"
124 )
125 }
126
127 /**
128 * Retrieves the return type of a function.
129 *
130 * @param {FunctionNode} node - The function's node.
131 * @returns {ts.Type} The function's return type.
132 */
133 getReturnType(node: FunctionNode): ts.Type {
134 return node.type
135 ? this.checker.getTypeFromTypeNode(node.type)
136 : this.checker.getTypeAtLocation(node)
137 }
138
139 /**
140 * Retrieves the summary comment of a function.
141 *
142 * @param {FunctionNode} node - The function's options.
143 * @returns {string} The function's summary comment.
144 */
145 getFunctionSummary({
146 node,
147 symbol,
148 parentSymbol,
149 returnType,
150 }: {
151 /**
152 * The node's function.
153 */
154 node: FunctionNode
155 /**
156 * The node's symbol. If provided, the method will try to retrieve the summary from the {@link KnowledgeBaseFactory}.
157 */
158 symbol?: ts.Symbol
159 /**
160 * The node's parent symbol. This is useful to pass along the parent name to the knowledge base.
161 */
162 parentSymbol?: ts.Symbol
163 /**
164 * The node's return type. Useful for the {@link KnowledgeBaseFactory}
165 */
166 returnType?: string
167 }): string {
168 return symbol
169 ? this.knowledgeBaseFactory.tryToGetFunctionSummary({
170 symbol: symbol,
171 kind: node.kind,
172 templateOptions: {
173 rawParentName: parentSymbol?.getName(),
174 pluralIndicatorStr: returnType,
175 },
176 }) || this.getNodeSummary({ node, symbol })
177 : this.getNodeSummary({ node, symbol })
178 }
179
180 /**
181 * Retrieve the function's example comment.
182 *
183 * @param {ts.Symbol} symbol - The function's symbol. If provided, the method will try to retrieve the example from the {@link KnowledgeBaseFactory}.
184 * @returns {string} The function's example comment.
185 */
186 getFunctionPlaceholderExample(): string {
187 return this.formatExample(FunctionKindGenerator.EXAMPLE_PLACEHOLDER)
188 }
189
190 formatExample(example: string, withTag = true): string {
191 return `${
192 withTag ? `${DOCBLOCK_DOUBLE_LINES}@example${DOCBLOCK_NEW_LINE}` : ""
193 }${example}`
194 }
195
196 /**
197 * Retrieve the full docblock of a function.
198 *
199 * @param {FunctionOrVariableNode | ts.Node} node - The function node. If a variable statement is provided, the underlying function is retrieved.
200 * If a different node type is provided, the parent generator is used to retrieve the docblock comment.
201 * @param {GetDocBlockOptions} options - Formatting options.
202 * @returns {string} The function's docblock.
203 */
204 async getDocBlock(
205 node: FunctionOrVariableNode | ts.Node,
206 options: GetDocBlockOptions = { addEnd: true }
207 ): Promise<string> {
208 if (!this.isAllowed(node)) {
209 return await super.getDocBlock(node, options)
210 }
211
212 const actualNode = ts.isVariableStatement(node)
213 ? this.extractFunctionNode(node)
214 : node
215
216 if (!actualNode) {
217 return await super.getDocBlock(node, options)
218 }
219
220 const existingComments = this.getNodeCommentsFromRange(node)
221
222 if (existingComments?.includes(FunctionKindGenerator.EXAMPLE_PLACEHOLDER)) {
223 return existingComments.replace("/*", "").replace("*/", "")
224 }
225
226 const nodeSymbol = getSymbol(node, this.checker)
227 const nodeParentSymbol = getSymbol(node.parent, this.checker)
228 const nodeType = this.getReturnType(actualNode)
229 const returnTypeStr = this.checker.typeToString(nodeType)
230 const normalizedTypeStr = returnTypeStr.startsWith("Promise<")
231 ? returnTypeStr.replace(/^Promise</, "").replace(/>$/, "")
232 : returnTypeStr
233
234 let str = DOCBLOCK_START
235
236 // add summary
237 str += `${
238 options.summaryPrefix ||
239 (this.isMethod(actualNode) ? `This method` : `This function`)
240 } ${this.getFunctionSummary({
241 node: actualNode,
242 symbol: nodeSymbol,
243 parentSymbol: nodeParentSymbol,
244 returnType: normalizedTypeStr,
245 })}${DOCBLOCK_NEW_LINE}`
246
247 actualNode.parameters.map((parameterNode) => {
248 const symbol = getSymbol(parameterNode, this.checker)
249 if (!symbol) {
250 return
251 }
252
253 const symbolType = this.checker.getTypeOfSymbolAtLocation(
254 symbol,
255 parameterNode
256 )
257
258 const parameterName = symbol.getName()
259 const parameterSummary = this.getNodeSummary({
260 node: parameterNode,
261 symbol,
262 nodeType: symbolType,
263 knowledgeBaseOptions: {
264 templateOptions: {
265 rawParentName: nodeParentSymbol?.getName(),
266 pluralIndicatorStr: this.checker.typeToString(symbolType),
267 },
268 },
269 })
270
271 str += `${DOCBLOCK_NEW_LINE}@param {${this.checker.typeToString(
272 symbolType
273 )}} ${parameterName} - ${parameterSummary}`
274 })
275
276 // add returns
277 const possibleReturnSummary = !this.hasReturnData(returnTypeStr)
278 ? `Resolves when ${SUMMARY_PLACEHOLDER}`
279 : this.getNodeSummary({
280 node: actualNode,
281 nodeType,
282 })
283
284 str += `${DOCBLOCK_NEW_LINE}@returns {${returnTypeStr}} ${
285 nodeSymbol
286 ? this.knowledgeBaseFactory.tryToGetFunctionReturns({
287 symbol: nodeSymbol,
288 kind: actualNode.kind,
289 templateOptions: {
290 rawParentName: nodeParentSymbol?.getName(),
291 pluralIndicatorStr: normalizedTypeStr,
292 },
293 }) || possibleReturnSummary
294 : possibleReturnSummary
295 }`
296
297 // add example
298 str += this.getFunctionPlaceholderExample()
299
300 // add common docs
301 str += this.getCommonDocs(node, {
302 prefixWithLineBreaks: true,
303 })
304
305 if (options.addEnd) {
306 str += DOCBLOCK_END_LINE
307 }
308
309 return str
310 }
311
312 /**
313 * Allows documenting (updating) a node if it has the example placeholder.
314 *
315 * @param node - The node to document.
316 * @returns Whether the node can be documented.
317 */
318 canDocumentNode(node: ts.Node): boolean {
319 const comments = this.getNodeCommentsFromRange(node)
320
321 return (
322 !comments ||
323 comments?.includes(FunctionKindGenerator.EXAMPLE_PLACEHOLDER) ||
324 false
325 )
326 }
327 }
328
329 export default FunctionKindGenerator