1 import ts from "typescript"
2 import FunctionKindGenerator, {
3 FunctionNode,
4 FunctionOrVariableNode,
5 } from "./function.js"
6 import {
7 DOCBLOCK_NEW_LINE,
8 DOCBLOCK_END_LINE,
9 DOCBLOCK_START,
10 DOCBLOCK_DOUBLE_LINES,
11 } from "../../constants.js"
12 import {
13 CUSTOM_NAMESPACE_TAG,
14 getCustomNamespaceTag,
15 } from "../../utils/medusa-react-utils.js"
16
17 /**
18 * Docblock generate for medusa-react hooks. Since hooks are essentially functions,
19 * it extends the {@link FunctionKindGenerator} class.
20 */
21 class MedusaReactHooksKindGenerator extends FunctionKindGenerator {
22 public name = "medusa-react"
23 /**
24 * Checks whether the generator can retrieve the docblock of the specified node. It uses the parent generator
25 * to check that the node is a function, then checks if the function is a mutation using the {@link isMutation} method,
26 * or a query using the {@link isQuery} method.
27 *
28 * @param {ts.Node} node - The node to check.
29 * @returns {boolean} Whether this generator can be used on this node.
30 */
31 isAllowed(node: ts.Node): node is FunctionOrVariableNode {
32 if (!super.isAllowed(node)) {
33 return false
34 }
35
36 const actualNode = ts.isVariableStatement(node)
37 ? this.extractFunctionNode(node)
38 : node
39
40 return (
41 actualNode !== undefined &&
42 (this.isMutation(actualNode) || this.isQuery(actualNode))
43 )
44 }
45
46 /**
47 * Checks whether a function node is a mutation.
48 *
49 * @param {FunctionNode} node - The function node to check.
50 * @returns {boolean} Whether the node is a mutation.
51 */
52 isMutation(node: FunctionNode): boolean {
53 const nodeType = this.getReturnType(node)
54
55 const callSignatures = nodeType.getCallSignatures()
56
57 return (
58 callSignatures.length > 0 &&
59 this.checker
60 .typeToString(this.checker.getReturnTypeOfSignature(callSignatures[0]))
61 .startsWith("UseMutationResult")
62 )
63 }
64
65 /**
66 * Checks whether a function node is a query.
67 *
68 * @param {FunctionNode} node - The function node to check.
69 * @returns {boolean} Whether the node is a query.
70 */
71 isQuery(node: FunctionNode): boolean {
72 return node.parameters.some(
73 (parameter) =>
74 parameter.type?.getText().startsWith("UseQueryOptionsWrapper")
75 )
76 }
77
78 /**
79 * Retrieves the docblock of the medusa-react hook or mutation.
80 *
81 * @param {FunctionNode & ts.VariableDeclaration} node - The node to retrieve its docblock.
82 * @returns {string} The node's docblock.
83 */
84 async getDocBlock(
85 node: FunctionNode & ts.VariableDeclaration
86 ): Promise<string> {
87 // TODO use the AiGenerator to generate summary + examples
88 if (!this.isAllowed(node)) {
89 return await super.getDocBlock(node)
90 }
91
92 const actualNode = ts.isVariableStatement(node)
93 ? this.extractFunctionNode(node)
94 : node
95
96 if (!actualNode) {
97 return await super.getDocBlock(node)
98 }
99 const isMutation = this.isMutation(actualNode)
100
101 let str = `${DOCBLOCK_START}This hook ${this.getFunctionSummary({
102 node,
103 })}`
104
105 // add example
106 str += this.getFunctionPlaceholderExample()
107
108 // loop over parameters that aren't query/mutation parameters
109 // and add docblock to them
110 await Promise.all(
111 this.getActualParameters(actualNode).map(async (parameter) => {
112 ts.addSyntheticLeadingComment(
113 parameter,
114 ts.SyntaxKind.MultiLineCommentTrivia,
115 await super.getDocBlock(parameter),
116 true
117 )
118 })
119 )
120
121 // check if mutation parameter is an intrinsic type and, if so, add the `@typeParamDefinition`
122 // tag to the hook
123 if (isMutation) {
124 const typeArg = this.getMutationRequestTypeArg(actualNode)
125 if (typeArg) {
126 str += `${DOCBLOCK_DOUBLE_LINES}@typeParamDefinition ${this.checker.typeToString(
127 typeArg
128 )} - {summary}`
129 }
130 }
131
132 // add common docs
133 str += this.getCommonDocs(node, {
134 prefixWithLineBreaks: true,
135 })
136
137 // add namespace in case it's not added
138 if (!str.includes(CUSTOM_NAMESPACE_TAG)) {
139 str += `${DOCBLOCK_DOUBLE_LINES}${getCustomNamespaceTag(actualNode)}`
140 }
141
142 // add the category
143 str += `${DOCBLOCK_NEW_LINE}@category ${
144 isMutation ? "Mutations" : "Queries"
145 }`
146
147 return `${str}${DOCBLOCK_END_LINE}`
148 }
149
150 /**
151 * Retrieves the parameters of a function node that aren't query/mutation options.
152 *
153 * @param {FunctionNode} node - The function node to retrieve its parameters.
154 * @returns {ts.ParameterDeclaration[]} - The function's actual parameters.
155 */
156 getActualParameters(node: FunctionNode): ts.ParameterDeclaration[] {
157 return node.parameters.filter((parameter) => {
158 const parameterTypeStr = parameter.type?.getText()
159 return (
160 !parameterTypeStr?.startsWith("UseQueryOptionsWrapper") &&
161 !parameterTypeStr?.startsWith("UseMutationOptions") &&
162 !this.nodeHasComments(parameter)
163 )
164 })
165 }
166
167 /**
168 * Retreives a mutation's intrinsic request type, if available, which is specified as the third type argument of `UseMutationOptions`.
169 *
170 * @param {FunctionNode} node - The function node to retrieve its request type.
171 * @returns {ts.Type | undefined} The mutation's request type, if available.
172 */
173 getMutationRequestTypeArg(node: FunctionNode): ts.Type | undefined {
174 const parameter = node.parameters.find(
175 (parameter) => parameter.type?.getText().startsWith("UseMutationOptions")
176 )
177
178 if (!parameter) {
179 return
180 }
181
182 const parameterType = this.checker.getTypeFromTypeNode(parameter.type!)
183 const typeArgs =
184 parameterType.aliasTypeArguments ||
185 ("resolvedTypeArguments" in parameterType
186 ? (parameterType.resolvedTypeArguments as ts.Type[])
187 : [])
188 if (
189 !typeArgs ||
190 typeArgs.length < 3 ||
191 !("intrinsicName" in typeArgs[2]) ||
192 ["void", "unknown"].includes(typeArgs[2].intrinsicName as string)
193 ) {
194 return
195 }
196
197 // find request in third type argument
198 return typeArgs[2]
199 }
200 }
201
202 export default MedusaReactHooksKindGenerator