1 import ts from "typescript"
2 import { SyntaxKind } from "typescript"
3 import DefaultKindGenerator, { GetDocBlockOptions } from "./default.js"
4 import type { RouteExamples } from "types"
5 const EXAMPLE_CODEBLOCK_REGEX = /```(ts|typescript)\s*([.\s\S]*?)\s*```/
6
7 type RouteData = {
8 route: string
9 method: string
10 }
11
12 // eslint-disable-next-line max-len
13 class RouteExamplesKindGenerator extends DefaultKindGenerator<ts.MethodDeclaration> {
14 public name = "route-examples"
15 protected allowedKinds: SyntaxKind[] = [
16 SyntaxKind.MethodDeclaration,
17 SyntaxKind.ArrowFunction,
18 ]
19
20 /**
21 * Gets the route examples from the specified node.
22 *
23 * @param node - The node to get the route examples from.
24 * @param options - The options for the route examples.
25 * @returns The route examples for the specified node.
26 */
27 async getDocBlock(
28 node: ts.MethodDeclaration,
29 options?: GetDocBlockOptions
30 ): Promise<string> {
31 if (!this.isAllowed(node)) {
32 return await super.getDocBlock(node, options)
33 }
34
35 // extract the route path from the node
36 const routeData = this.findRoute(node.body as ts.Node)
37
38 if (!routeData.route) {
39 return ""
40 }
41 if (!routeData.method) {
42 routeData.method = "GET" // default method
43 }
44
45 // get examples from the comments
46 const example = ts
47 .getJSDocTags(node)
48 .find((tag) => tag.tagName.escapedText === "example")
49
50 if (!example || !example.comment) {
51 return ""
52 }
53
54 const exampleText = this.getExampleText(
55 typeof example.comment === "string"
56 ? example.comment
57 : example.comment[example.comment.length - 1].text
58 )
59
60 return JSON.stringify({
61 [this.formatRouteData(routeData)]: {
62 [this.getExampleType(node)]: exampleText,
63 },
64 } as RouteExamples)
65 }
66
67 getExampleText(comment: string): string {
68 // try to match the example codeblock first
69 const match = comment.match(EXAMPLE_CODEBLOCK_REGEX)
70 if (match) {
71 // return the last match
72 return match[match.length - 1]
73 }
74
75 // consider the comment as the example text
76 return comment
77 }
78
79 /**
80 * Use this method later to support different example types.
81 *
82 * @param node - The node to get the example type for.
83 * @returns The example type.
84 */
85 // eslint-disable-next-line @typescript-eslint/no-unused-vars
86 getExampleType(node: ts.MethodDeclaration): string {
87 return "js-sdk"
88 }
89
90 /**
91 * Finds the route data from the specified node.
92 *
93 * @param node - The node to find the route from.
94 * @returns The route data.
95 */
96 findRoute(node: ts.Node): RouteData {
97 const result = {
98 route: "",
99 method: "",
100 }
101
102 /**
103 * Internal function to maybe set the route result for a string
104 */
105 const maybeSetRouteResult = (str: string) => {
106 str = str.replace(/^["'`]|["'`]$/g, "")
107
108 // check if any of the template variables are local variables
109 const localVariables = this.getLocalVariables(node)
110 const templateVariables = str.match(/{(.+?)}/g) || []
111 for (const variable of templateVariables) {
112 const variableName = variable.slice(1, -1)
113 const localVariable = localVariables.get(variableName)
114 if (localVariable && localVariable.valueDeclaration) {
115 str = str.replace(
116 `$${variable}`,
117 this.getValueFromDeclaration(localVariable.valueDeclaration)
118 )
119 }
120 }
121
122 // replace the remaining template variables with correct OAS syntax
123 str = str.toLowerCase().replace(/\$\{(.+?)\}/g, `{$1}`)
124
125 // remove possible query params in string
126 const queryIndex = str.indexOf("?")
127 if (queryIndex > -1) {
128 str = str.slice(0, queryIndex)
129 }
130 if (
131 str.startsWith("/store") ||
132 str.startsWith("/admin") ||
133 str.startsWith("/auth")
134 ) {
135 result.route = str
136 } else if (
137 str === "get" ||
138 str === "post" ||
139 str === "put" ||
140 str === "delete"
141 ) {
142 result.method = str.toUpperCase()
143 }
144 }
145
146 if (
147 node.kind === ts.SyntaxKind.StringLiteral ||
148 node.kind === ts.SyntaxKind.NoSubstitutionTemplateLiteral ||
149 node.kind === ts.SyntaxKind.TemplateExpression
150 ) {
151 maybeSetRouteResult(node.getText())
152 } else if (
153 ts.isIdentifier(node) &&
154 ts.isCallExpression(node.parent) &&
155 node.parent.expression.getText().endsWith(".fetch")
156 ) {
157 const localVariables = this.getLocalVariables(node)
158 const variableSymbol = localVariables.get(node.getText())
159 if (variableSymbol?.valueDeclaration) {
160 maybeSetRouteResult(
161 this.getValueFromDeclaration(variableSymbol.valueDeclaration)
162 )
163 }
164 } else {
165 node.forEachChild((child) => {
166 if (result.route.length > 0 && result.method.length > 0) {
167 return
168 }
169
170 const childResult = this.findRoute(child)
171 if (result.route.length === 0) {
172 result.route = childResult.route
173 }
174 if (result.method.length === 0) {
175 result.method = childResult.method
176 }
177 })
178 }
179
180 return result
181 }
182
183 /**
184 * Formats the route data as a string.
185 *
186 * @param routeData - The route data to format.
187 * @returns The formatted route data as a string.
188 */
189 formatRouteData(routeData: RouteData): string {
190 return `${routeData.method} ${routeData.route}`
191 }
192
193 /**
194 * Checks whether a node can be documented.
195 *
196 * @param {ts.Node} node - The node to check for.
197 * @returns {boolean} Whether the node can be documented.
198 */
199 canDocumentNode(node: ts.Node): boolean {
200 // check if node has docblock
201 return ts.getJSDocCommentsAndTags(node).length > 0 && !this.isPrivate(node)
202 }
203
204 /**
205 * Checks whether a node is private.
206 *
207 * @param node - The node to check for.
208 * @returns Whether the node is private.
209 */
210 isPrivate(node: ts.Node): boolean {
211 // Check for explicit private keyword
212 if (ts.canHaveModifiers(node)) {
213 const modifiers = ts.getModifiers(node)
214 if (modifiers) {
215 return modifiers.some(
216 (modifier) => modifier.kind === ts.SyntaxKind.PrivateKeyword
217 )
218 }
219 }
220
221 // Check for private class member
222 return (node.flags & ts.ModifierFlags.Private) !== 0
223 }
224
225 getLocalVariables(node: ts.Node): Map<string, ts.Symbol> {
226 const sourceFile = node.getSourceFile()
227 return "locals" in sourceFile
228 ? (sourceFile.locals as Map<string, ts.Symbol>)
229 : new Map<string, ts.Symbol>()
230 }
231
232 getValueFromDeclaration(declaration: ts.Declaration) {
233 if (!ts.isVariableDeclaration(declaration)) {
234 return ""
235 }
236
237 const initializer = declaration.initializer
238 if (!initializer || !ts.isStringLiteral(initializer)) {
239 return ""
240 }
241
242 return initializer.getText().replace(/^["'`]|["'`]$/g, "")
243 }
244 }
245
246 export default RouteExamplesKindGenerator