Raw
1 import chalk from "chalk"
2 import { readFileSync, writeFileSync } from "fs"
3 import { STATUS_CODES } from "http"
4 import { OpenAPIV3 } from "openapi-types"
5 import { basename, join } from "path"
6 import ts, { SyntaxKind } from "typescript"
7 import { capitalize, kebabToTitle } from "utils"
8 import { parse, stringify } from "yaml"
9 import { DEFAULT_OAS_RESPONSES, SUMMARY_PLACEHOLDER } from "../../constants.js"
10 import {
11 OasEvent,
12 OpenApiDocument,
13 OpenApiOperation,
14 OpenApiSchema,
15 } from "../../types/index.js"
16 import formatOas from "../../utils/format-oas.js"
17 import getCorrectZodTypeName from "../../utils/get-correct-zod-type-name.js"
18 import {
19 getEventsOutputBasePath,
20 getOasOutputBasePath,
21 } from "../../utils/get-output-base-paths.js"
22 import isZodObject from "../../utils/is-zod-object.js"
23 import parseOas, { ExistingOas } from "../../utils/parse-oas.js"
24 import OasExamplesGenerator from "../examples/oas.js"
25 import { GeneratorEvent } from "../helpers/generator-event-manager.js"
26 import OasSchemaHelper from "../helpers/oas-schema.js"
27 import SchemaFactory from "../helpers/schema-factory.js"
28 import { GeneratorOptions, GetDocBlockOptions } from "./default.js"
29 import FunctionKindGenerator, {
30 FunctionNode,
31 FunctionOrVariableNode,
32 VariableNode,
33 } from "./function.js"
34 import { API_ROUTE_PARAM_REGEX } from "../../constants.js"
35 import QueryConfigHelper, {
36 FieldRestrictions,
37 } from "../helpers/query-config.js"
38 import TypesHelper from "../helpers/types.js"
39 import {
40 isLevelExceeded,
41 maybeIncrementLevel,
42 } from "../../utils/level-utils.js"
43 import { MedusaEvent } from "types"
44
45 const RES_STATUS_REGEX = /^res[\s\S]*\.status\((\d+)\)/
46 // matches responses that only send a status code, such as `res.sendStatus(201)`
47 // or the deprecated `res.send(200)`. Express sends the status code's message
48 // as a plain text body in these cases.
49 const RES_SEND_STATUS_REGEX = /^res[\s\S]*\.(?:sendStatus|send)\((\d+)\)/
50
51 type SchemaDescriptionOptions = {
52 symbol?: ts.Symbol
53 node?: ts.Node
54 nodeType?: ts.Type
55 typeStr: string
56 parentName?: string
57 rawParentName?: string
58 }
59
60 export type OasArea = "admin" | "store"
61
62 type ParameterType = "query" | "path" | "header"
63
64 type AuthRequests = {
65 exact?: string
66 startsWith?: string
67 requiresAuthentication: boolean
68 allowedAuthTypes?: string[]
69 httpMethods?: string[]
70 }
71
72 /**
73 * OAS generator for API routes. It extends the {@link FunctionKindGenerator}
74 * since API routes are functions.
75 */
76 class OasKindGenerator extends FunctionKindGenerator {
77 public name = "oas"
78 protected allowedKinds: SyntaxKind[] = [ts.SyntaxKind.FunctionDeclaration]
79 private MAX_LEVEL = 7
80 readonly METHOD_NAMES = [
81 "GET",
82 "POST",
83 "PUT",
84 "PATCH",
85 "DELETE",
86 "OPTIONS",
87 "HEAD",
88 "TRACE",
89 "CONNECT",
90 ]
91 readonly REQUEST_TYPE_NAMES = [
92 "MedusaRequest",
93 "RequestWithContext",
94 "AuthenticatedMedusaRequest",
95 "MedusaStoreRequest",
96 "StoreRequestWithContext",
97 "StoreVariantListRequest",
98 ]
99 readonly REQUEST_CHECK_QUERY_ARGS = [
100 "RequestWithContext",
101 "StoreVariantListRequest",
102 ]
103 // as it's not always possible to detect authenticated request
104 // use this to override the default detection logic.
105 readonly AUTH_REQUESTS: AuthRequests[] = [
106 {
107 exact: "store/orders",
108 requiresAuthentication: true,
109 },
110 {
111 startsWith: "store/customers",
112 requiresAuthentication: true,
113 },
114 {
115 exact: "store/orders/[id]/transfer/request",
116 requiresAuthentication: true,
117 },
118 {
119 exact: "store/orders/[id]/transfer/cancel",
120 requiresAuthentication: true,
121 },
122 {
123 exact: "admin/invites/accept",
124 httpMethods: ["post"],
125 requiresAuthentication: true,
126 allowedAuthTypes: ["cookie_auth", "jwt_token"],
127 },
128 {
129 startsWith: "admin/invites",
130 requiresAuthentication: true,
131 },
132 {
133 startsWith: "admin/users",
134 requiresAuthentication: true,
135 allowedAuthTypes: ["cookie_auth", "jwt_token"],
136 },
137 {
138 exact: "store/gift-cards/[idOrCode]/redeem",
139 requiresAuthentication: true,
140 },
141 {
142 startsWith: "store/store-credit-accounts",
143 requiresAuthentication: true,
144 },
145 {
146 exact: "store/carts/[id]/customer",
147 requiresAuthentication: true,
148 },
149 ]
150 readonly RESPONSE_TYPE_NAMES = ["MedusaResponse"]
151 readonly LOCALIZED_ROUTES = ["store/"]
152
153 /**
154 * This map collects tags of all the generated OAS, then, once the generation process finishes,
155 * it checks if it should be added to the base OAS document of the associated area.
156 */
157 private tags: Map<OasArea, Set<string>>
158 /**
159 * The path to the directory holding the base YAML files.
160 */
161 protected baseOutputPath: string
162 protected oasExamplesGenerator: OasExamplesGenerator
163 protected oasSchemaHelper: OasSchemaHelper
164 protected schemaFactory: SchemaFactory
165 protected typesHelper: TypesHelper
166 protected queryConfigHelper: QueryConfigHelper
167 protected events: MedusaEvent[] = []
168
169 constructor(options: GeneratorOptions) {
170 super(options)
171
172 this.oasExamplesGenerator = new OasExamplesGenerator()
173 this.baseOutputPath = getOasOutputBasePath()
174
175 this.tags = new Map()
176 this.oasSchemaHelper = new OasSchemaHelper()
177 this.schemaFactory = new SchemaFactory({ checker: this.checker })
178 this.typesHelper = new TypesHelper({
179 checker: this.checker,
180 })
181 this.queryConfigHelper = new QueryConfigHelper()
182 this.init()
183
184 this.generatorEventManager.listen(
185 GeneratorEvent.FINISHED_GENERATE_EVENT,
186 this.afterGenerate.bind(this)
187 )
188 }
189
190 /**
191 * Check whether the generator can be used for the specified node. The node must be a function that has
192 * two parameters of types in {@link REQUEST_TYPE_NAMES} and {@link RESPONSE_TYPE_NAMES}
193 *
194 * @param node - The node to check.
195 * @returns Whether the generator can be used for the specified node.
196 */
197 isAllowed(node: ts.Node): node is FunctionOrVariableNode {
198 const isFunction =
199 this.allowedKinds.includes(node.kind) ||
200 (ts.isVariableStatement(node) && this.isFunctionVariable(node))
201
202 if (!isFunction) {
203 return false
204 }
205
206 const functionNode = ts.isFunctionDeclaration(node)
207 ? node
208 : this.extractFunctionNode(node as VariableNode)
209 const functionName = this.getFunctionName(node as FunctionOrVariableNode)
210
211 if (
212 !functionNode ||
213 !this.METHOD_NAMES.includes(functionName) ||
214 functionNode.parameters.length !== 2
215 ) {
216 return false
217 }
218
219 if (this.isIgnored(functionNode)) {
220 return false
221 }
222
223 const hasCorrectRequestType =
224 this.getRequestTypeReferenceNode(functionNode.parameters[0].type) !==
225 undefined
226 const hasCorrectResponseType = this.RESPONSE_TYPE_NAMES.some((name) =>
227 functionNode.parameters[1].type?.getText().startsWith(name)
228 )
229
230 return hasCorrectRequestType && hasCorrectResponseType
231 }
232
233 /**
234 * Resolve the request's type reference node from a function's first parameter type.
235 * This supports a direct type reference, such as `MedusaRequest<T>`, a union of request
236 * types, such as `MedusaRequest<T> | AuthenticatedMedusaRequest<T>`, and an intersection
237 * with additional request properties, such as `MedusaStoreRequest<T> & ConfiguredStoreSearch`.
238 * In both composite cases, the first member matching {@link REQUEST_TYPE_NAMES} is returned,
239 * as union members share the same type arguments and intersection members are mixins.
240 *
241 * @param typeNode - The first parameter's type node.
242 * @returns The matching request type reference node, if any.
243 */
244 getRequestTypeReferenceNode(
245 typeNode: ts.TypeNode | undefined
246 ): ts.TypeReferenceNode | undefined {
247 if (!typeNode) {
248 return undefined
249 }
250
251 const candidateNodes: ts.TypeNode[] =
252 ts.isUnionTypeNode(typeNode) || ts.isIntersectionTypeNode(typeNode)
253 ? [...typeNode.types]
254 : [typeNode]
255
256 return candidateNodes.find(
257 (candidate): candidate is ts.TypeReferenceNode =>
258 ts.isTypeReferenceNode(candidate) &&
259 this.REQUEST_TYPE_NAMES.some((name) =>
260 candidate.typeName.getText().startsWith(name)
261 )
262 )
263 }
264
265 /**
266 * Check whether the node can be documented.
267 *
268 * @param node - The node to check.
269 * @returns Whether the node can be documented.
270 */
271 // eslint-disable-next-line @typescript-eslint/no-unused-vars
272 canDocumentNode(node: ts.Node): boolean {
273 // unlike other generators, this one
274 // can update existing OAS, so we just return
275 // true
276 return true
277 }
278
279 /**
280 * Try to retrieve the OAS previously generated for the function. If the OAS is retrieved, the
281 * OAS is updated rather than created.
282 *
283 * @param node - The node to retrieve its existing OAS.
284 * @returns The node's existing OAS, if available.
285 */
286 getExistingOas(node: FunctionOrVariableNode): ExistingOas | undefined {
287 // read the file holding the OAS, if it's available.
288 const fileContent = ts.sys.readFile(this.getAssociatedFileName(node))
289
290 if (!fileContent) {
291 // the file doesn't exist, meaning there's no existing OAS.
292 return
293 }
294
295 return parseOas(fileContent)
296 }
297
298 /**
299 * Retrieves the docblock of the node. If the node has existing OAS, the OAS is updated and returned. Otherwise,
300 * the OAS is generated.
301 *
302 * @param node - The node to get its OAS.
303 * @param options - The options to get the OAS.
304 * @returns The OAS as a string that can be used as a comment in a TypeScript file.
305 */
306 async getDocBlock(
307 node: ts.Node | FunctionOrVariableNode,
308 options?: GetDocBlockOptions
309 ): Promise<string> {
310 if (!this.isAllowed(node)) {
311 return await super.getDocBlock(node, options)
312 }
313 this.readEventsJson()
314
315 const actualNode = ts.isVariableStatement(node)
316 ? this.extractFunctionNode(node)
317 : node
318
319 if (!actualNode) {
320 return await super.getDocBlock(node, options)
321 }
322 const methodName = this.getHTTPMethodName(node)
323
324 const existingOas = this.getExistingOas(node)
325
326 if (existingOas?.oas) {
327 return this.updateExistingOas({
328 node: actualNode,
329 methodName,
330 oasOptions: existingOas,
331 })
332 }
333
334 return this.getNewOasDocBlock({
335 node: actualNode,
336 methodName,
337 })
338 }
339
340 /**
341 * Generate OAS of a node.
342 *
343 * @param param0 - The node's details.
344 * @returns The OAS comment.
345 */
346 getNewOasDocBlock({
347 node,
348 methodName,
349 }: {
350 /**
351 * The node to generate its OAS.
352 */
353 node: FunctionNode
354 /**
355 * The lowercase name of the method. For example, `get`.
356 */
357 methodName: string
358 }): string {
359 // collect necessary variables
360 const { oasPath, normalized: normalizedOasPath } = this.getOasPath(node)
361 const splitOasPath = oasPath.split("/")
362 const oasPrefix = this.getOasPrefix(methodName, normalizedOasPath)
363 const {
364 isAdminAuthenticated,
365 isStoreAuthenticated,
366 isAuthenticated,
367 allowedAuthTypes,
368 } = this.getAuthenticationDetails(node, oasPath, methodName)
369 const tagName = this.getTagName(splitOasPath)
370 const { summary, description } =
371 this.knowledgeBaseFactory.tryToGetOasMethodSummaryAndDescription({
372 oasPath,
373 httpMethod: methodName,
374 tag: tagName || "",
375 })
376
377 // construct oas
378 const oas: OpenApiOperation = {
379 operationId: this.getOperationId({
380 methodName,
381 splitOasPath,
382 }),
383 summary,
384 description,
385 "x-authenticated": isAuthenticated,
386 parameters: this.getPathParameters({ oasPath, tagName }),
387 security: [],
388 }
389
390 // get header params
391 const headerParams = this.getHeaderParameters(oasPath)
392 oas.parameters?.push(...headerParams)
393
394 // retreive query and request parameters
395 const { queryParameters, requestSchema } = this.getRequestParameters({
396 node,
397 tagName,
398 methodName,
399 oasPath,
400 })
401
402 oas.parameters?.push(...queryParameters)
403 if (!this.oasSchemaHelper.isSchemaEmpty(requestSchema)) {
404 oas.requestBody = {
405 content: {
406 "application/json": {
407 schema:
408 this.oasSchemaHelper.namedSchemaToReference(requestSchema!) ||
409 this.oasSchemaHelper.schemaChildrenToRefs(requestSchema!),
410 },
411 },
412 }
413 }
414
415 // retrieve response schema
416 const responseSchema = this.getResponseSchema({
417 node,
418 tagName,
419 })
420
421 const curlExample = this.oasExamplesGenerator.generateCurlExample({
422 method: methodName,
423 path: normalizedOasPath,
424 isAdminAuthenticated,
425 isStoreAuthenticated,
426 requestSchema,
427 })
428 const jsSdkExample = this.oasExamplesGenerator.generateJsSdkExanmple({
429 method: methodName,
430 path: normalizedOasPath,
431 })
432
433 // retrieve code examples
434 oas["x-codeSamples"] = []
435
436 if (jsSdkExample) {
437 oas["x-codeSamples"].push({
438 ...OasExamplesGenerator.JSCLIENT_CODESAMPLE_DATA,
439 source: jsSdkExample,
440 })
441 }
442
443 if (curlExample) {
444 oas["x-codeSamples"].push({
445 ...OasExamplesGenerator.CURL_CODESAMPLE_DATA,
446 source: curlExample,
447 })
448 }
449
450 // add security details if applicable
451 oas.security = this.getSecurity({
452 isAdminAuthenticated,
453 isAuthenticated,
454 auth_types: allowedAuthTypes,
455 })
456
457 if (tagName) {
458 oas.tags = [tagName]
459 }
460
461 // detect returned response status and content
462 const { status: responseStatus, content: responseContent } =
463 this.getResponseDetails(node)
464
465 // add responses
466 oas.responses = {
467 [responseStatus]: this.createSuccessResponse({
468 schema: responseSchema,
469 content: responseContent,
470 }),
471 ...DEFAULT_OAS_RESPONSES,
472 }
473
474 // push new tag to the tags property
475 if (tagName) {
476 const areaTags = this.tags.get(splitOasPath[0] as OasArea)
477 areaTags?.add(tagName)
478 }
479
480 // get associated workflow
481 oas["x-workflow"] = this.getAssociatedWorkflow(node)
482
483 if (oas["x-workflow"]) {
484 // get associated events
485 oas["x-events"] = this.getOasEvents(oas["x-workflow"])
486 }
487
488 // get the fields and relations restrictions of the route's query config
489 const fieldRestrictions = this.getFieldRestrictions({
490 node,
491 oasPath,
492 methodName,
493 })
494
495 oas["x-allowed"] = fieldRestrictions?.allowed
496 oas["x-disallowed"] = fieldRestrictions?.disallowed
497
498 // check deprecation and version in tags
499 const { deprecatedTag, sinceTag, featureFlagTag } =
500 this.getInformationFromTags(node)
501
502 if (deprecatedTag) {
503 oas.deprecated = true
504 oas["x-deprecated_message"] = deprecatedTag.comment
505 ? (deprecatedTag.comment as string)
506 : undefined
507 }
508
509 if (sinceTag) {
510 oas["x-since"] = sinceTag.comment
511 ? (sinceTag.comment as string)
512 : undefined
513 }
514
515 if (featureFlagTag) {
516 oas["x-featureFlag"] = featureFlagTag.comment
517 ? (featureFlagTag.comment as string)
518 : undefined
519 }
520
521 return formatOas(oas, oasPrefix)
522 }
523
524 /**
525 * Update an existing OAS operation.
526 *
527 * @param param0 - The OAS's details.
528 * @returns The updated OAS
529 */
530 updateExistingOas({
531 node,
532 methodName,
533 oasOptions: { oas, oasPrefix },
534 }: {
535 /**
536 * The node that the OAS is associated with.
537 */
538 node: FunctionNode
539 /**
540 * The lower case method name of the operation.
541 */
542 methodName: string
543 /**
544 * The existing OAS's details.
545 */
546 oasOptions: ExistingOas
547 }): string {
548 // collect necessary variables
549 const { oasPath, normalized: normalizedOasPath } = this.getOasPath(node)
550 const splitOasPath = oasPath.split("/")
551 const tagName = this.getTagName(splitOasPath)
552
553 // update tag name
554 oas.tags = tagName ? [tagName] : []
555
556 // check if the prefix line should be updated.
557 const updatedOasPrefix = this.getOasPrefix(methodName, normalizedOasPath)
558 if (updatedOasPrefix !== oasPrefix) {
559 oasPrefix = updatedOasPrefix
560 }
561
562 // check if operation ID should be updated
563 const updatedOperationId = this.getOperationId({
564 methodName,
565 splitOasPath,
566 })
567
568 if (updatedOperationId !== oas.operationId) {
569 oas.operationId = updatedOperationId
570 }
571
572 // update summary and description either if they're empty or default summary
573 const shouldUpdateSummary =
574 !oas.summary || oas.summary === SUMMARY_PLACEHOLDER
575 const shouldUpdateDescription =
576 !oas.description || oas.description === SUMMARY_PLACEHOLDER
577 if (shouldUpdateSummary || shouldUpdateDescription) {
578 const { summary, description } =
579 this.knowledgeBaseFactory.tryToGetOasMethodSummaryAndDescription({
580 oasPath,
581 httpMethod: methodName,
582 tag: tagName || "",
583 })
584
585 if (shouldUpdateSummary) {
586 oas.summary = summary
587 }
588
589 if (shouldUpdateDescription) {
590 oas.description = description
591 }
592 }
593
594 // check if authentication details (including security) should be updated
595 const {
596 isAdminAuthenticated,
597 isStoreAuthenticated,
598 isAuthenticated,
599 allowedAuthTypes,
600 } = this.getAuthenticationDetails(node, oasPath, methodName)
601
602 oas["x-authenticated"] = isAuthenticated
603 oas.security = this.getSecurity({
604 isAdminAuthenticated,
605 isAuthenticated,
606 auth_types: allowedAuthTypes,
607 })
608
609 let parametersUpdated = false
610
611 // update path parameters
612 const newPathParameters = this.getPathParameters({ oasPath, tagName })
613
614 // get header params
615 const headerParams = this.getHeaderParameters(oasPath)
616 newPathParameters.push(...headerParams)
617
618 let updateParameterResult = this.updateParameters({
619 oldParameters: oas.parameters as OpenAPIV3.ParameterObject[],
620 newParameters: newPathParameters,
621 types: ["path", "header"],
622 })
623
624 oas.parameters = updateParameterResult.parameters
625 parametersUpdated = updateParameterResult.wasUpdated
626
627 // retrieve updated query and request schemas
628 const { queryParameters, requestSchema } = this.getRequestParameters({
629 node,
630 tagName,
631 methodName,
632 oasPath,
633 forUpdate: true,
634 })
635
636 // update query parameters
637 updateParameterResult = this.updateParameters({
638 oldParameters: oas.parameters as OpenAPIV3.ParameterObject[],
639 newParameters: queryParameters,
640 types: ["query"],
641 })
642
643 oas.parameters = updateParameterResult.parameters
644 parametersUpdated = updateParameterResult.wasUpdated || parametersUpdated
645
646 if (!oas.parameters.length) {
647 oas.parameters = undefined
648 }
649
650 // update request schema
651 const existingRequestBodySchema = (
652 oas.requestBody as OpenAPIV3.RequestBodyObject
653 )?.content?.["application/json"].schema as OpenApiSchema
654 const updatedRequestSchema = this.updateSchema({
655 oldSchema: existingRequestBodySchema,
656 newSchema: requestSchema,
657 })
658
659 parametersUpdated = updatedRequestSchema?.wasUpdated || parametersUpdated
660
661 if (this.oasSchemaHelper.isSchemaEmpty(updatedRequestSchema?.schema)) {
662 // if there's no request schema, remove it from the OAS
663 delete oas.requestBody
664 } else {
665 // update the schema
666 oas.requestBody = {
667 content: {
668 "application/json": {
669 schema:
670 this.oasSchemaHelper.namedSchemaToReference(
671 updatedRequestSchema!.schema!
672 ) ||
673 this.oasSchemaHelper.schemaChildrenToRefs(
674 updatedRequestSchema!.schema!
675 ),
676 },
677 },
678 }
679 }
680
681 // update response schema and status
682 const { status: newStatus, content: newResponseContent } =
683 this.getResponseDetails(node)
684 const newResponseSchema = this.getResponseSchema({
685 node,
686 tagName,
687 forUpdate: true,
688 })
689 let updatedResponseSchema: OpenApiSchema | undefined
690
691 if (!oas.responses && (newResponseSchema || newResponseContent)) {
692 // add response schema
693 oas.responses = {
694 [newStatus]: this.createSuccessResponse({
695 schema: newResponseSchema,
696 content: newResponseContent,
697 }),
698 ...DEFAULT_OAS_RESPONSES,
699 }
700 updatedResponseSchema = newResponseSchema
701 } else if (oas.responses && !newResponseSchema) {
702 // the route doesn't send a JSON body, so only the generated content,
703 // if any, is kept. Manually added content types are kept as-is.
704 if (newResponseContent || !this.hasResponseType(node, oas)) {
705 // remove response schema by only keeping the default responses
706 oas.responses = {
707 ...DEFAULT_OAS_RESPONSES,
708 [newStatus]: this.createSuccessResponse({
709 content: newResponseContent,
710 }),
711 }
712 }
713 } else {
714 // check if response status should be changed
715 const oldResponseStatus = Object.keys(oas.responses!).find(
716 (status) => !Object.keys(DEFAULT_OAS_RESPONSES).includes(status)
717 )
718 const oldResponseSchema = oldResponseStatus
719 ? ((oas.responses![oldResponseStatus] as OpenAPIV3.ResponseObject)
720 .content?.["application/json"]?.schema as OpenApiSchema)
721 : undefined
722
723 updatedResponseSchema = this.updateSchema({
724 oldSchema: oldResponseSchema,
725 newSchema: newResponseSchema,
726 })?.schema
727
728 if (oldResponseStatus && oldResponseSchema !== newStatus) {
729 // delete the old response schema if its status is different
730 delete oas.responses![oldResponseStatus]
731 }
732
733 if (updatedResponseSchema && Object.keys(updatedResponseSchema).length) {
734 // update the response schema
735 oas.responses![newStatus] = this.createSuccessResponse({
736 schema: updatedResponseSchema,
737 })
738 } else if (oldResponseStatus) {
739 // delete the old response schema
740 delete oas.responses![oldResponseStatus]
741 }
742 }
743
744 // check if cURL example should be updated.
745 const oldCurlExampleIndex = oas["x-codeSamples"]
746 ? oas["x-codeSamples"].findIndex(
747 (example) =>
748 example.label === OasExamplesGenerator.CURL_CODESAMPLE_DATA.label
749 )
750 : -1
751
752 if (oldCurlExampleIndex === -1) {
753 // only generate example if it doesn't already exist
754 const newCurlExample = this.oasExamplesGenerator.generateCurlExample({
755 method: methodName,
756 path: normalizedOasPath,
757 isAdminAuthenticated,
758 isStoreAuthenticated,
759 requestSchema,
760 })
761 oas["x-codeSamples"] = [
762 ...(oas["x-codeSamples"] || []),
763 {
764 ...OasExamplesGenerator.CURL_CODESAMPLE_DATA,
765 source: newCurlExample,
766 },
767 ]
768 } else if (parametersUpdated) {
769 // show a warning if the request parameters have changed
770 console.warn(
771 chalk.yellow(
772 `[WARNING] The request parameters of ${methodName} ${oasPath} have changed. Please update the cURL example.`
773 )
774 )
775 }
776
777 // generate JS SDK example
778 const oldJsSdkExampleIndex = oas["x-codeSamples"]
779 ? oas["x-codeSamples"].findIndex(
780 (example) =>
781 example.label ===
782 OasExamplesGenerator.JSCLIENT_CODESAMPLE_DATA.label
783 )
784 : -1
785 const jsSdkExample = this.oasExamplesGenerator.generateJsSdkExanmple({
786 method: methodName,
787 path: normalizedOasPath,
788 })
789 if (jsSdkExample) {
790 if (oldJsSdkExampleIndex === -1) {
791 oas["x-codeSamples"] = [
792 ...(oas["x-codeSamples"] || []),
793 {
794 ...OasExamplesGenerator.JSCLIENT_CODESAMPLE_DATA,
795 source: jsSdkExample,
796 },
797 ]
798 } else {
799 oas["x-codeSamples"]![oldJsSdkExampleIndex] = {
800 ...OasExamplesGenerator.JSCLIENT_CODESAMPLE_DATA,
801 source: jsSdkExample,
802 }
803 }
804 } else if (oldJsSdkExampleIndex !== -1) {
805 // output a warning that maybe the JS SDK should be updated
806 console.warn(
807 chalk.yellow(
808 `[WARNING] The JS SDK example of ${methodName} ${oasPath} is missing from generated route examples. Consider updating it.`
809 )
810 )
811 }
812
813 // sort the code samples to show JS SDK first
814 oas["x-codeSamples"] = oas["x-codeSamples"]?.sort((a) => {
815 return a.label === OasExamplesGenerator.JSCLIENT_CODESAMPLE_DATA.label
816 ? -1
817 : 1
818 })
819
820 // push new tags to the tags property
821 if (tagName) {
822 const areaTags = this.tags.get(splitOasPath[0] as OasArea)
823 areaTags?.add(tagName)
824 }
825
826 // get associated workflow
827 oas["x-workflow"] = this.getAssociatedWorkflow(node)
828
829 if (oas["x-workflow"]) {
830 // get associated events
831 oas["x-events"] = this.getOasEvents(oas["x-workflow"])
832 }
833
834 // update the fields and relations restrictions of the route's query config
835 const fieldRestrictions = this.getFieldRestrictions({
836 node,
837 oasPath,
838 methodName,
839 })
840
841 if (fieldRestrictions?.allowed) {
842 oas["x-allowed"] = fieldRestrictions.allowed
843 } else {
844 delete oas["x-allowed"]
845 }
846
847 if (fieldRestrictions?.disallowed) {
848 oas["x-disallowed"] = fieldRestrictions.disallowed
849 } else {
850 delete oas["x-disallowed"]
851 }
852
853 // check deprecation and version in tags
854 const { deprecatedTag, sinceTag, featureFlagTag } =
855 this.getInformationFromTags(node)
856
857 if (deprecatedTag) {
858 oas.deprecated = true
859 oas["x-deprecated_message"] = deprecatedTag.comment
860 ? (deprecatedTag.comment as string)
861 : undefined
862 } else {
863 delete oas.deprecated
864 delete oas["x-deprecated_message"]
865 }
866
867 if (sinceTag) {
868 oas["x-since"] = sinceTag.comment
869 ? (sinceTag.comment as string)
870 : undefined
871 } else {
872 delete oas["x-since"]
873 }
874
875 if (featureFlagTag) {
876 oas["x-featureFlag"] = featureFlagTag.comment
877 ? (featureFlagTag.comment as string)
878 : undefined
879 } else {
880 delete oas["x-featureFlag"]
881 }
882
883 return formatOas(oas, oasPrefix)
884 }
885
886 /**
887 * Get the API route's path details.
888 *
889 * @param node - The node to retrieve its path details.
890 * @returns The path details.
891 */
892 getOasPath(node: FunctionOrVariableNode): {
893 /**
894 * The path, generally left as-is, which helps detecting path parameters.
895 */
896 oasPath: string
897 /**
898 * The normalized path which adds a backslash at the beginning of the
899 * oasPath and replaces path parameters of pattern `[paramName]` with
900 * `{paramName}`. This can be used in the prefix line of the OAS.
901 */
902 normalized: string
903 } {
904 const filePath = node.getSourceFile().fileName
905 const oasPath = filePath
906 .substring(filePath.indexOf("/api/"))
907 .replace(/^\/api\//, "")
908 .replace(`/${basename(filePath)}`, "")
909 const normalizedOasPath = `/${oasPath.replaceAll(
910 API_ROUTE_PARAM_REGEX,
911 `{$1}`
912 )}`
913
914 return {
915 oasPath,
916 normalized: normalizedOasPath,
917 }
918 }
919
920 /**
921 * Get the function's name, which is used to retrieve the HTTP method.
922 *
923 * @param node - The node to retrieve its function name.
924 * @returns the name of the function.
925 */
926 getFunctionName(node: FunctionOrVariableNode): string {
927 if (ts.isFunctionDeclaration(node)) {
928 return node.name?.getText() || ""
929 }
930
931 return (
932 (
933 node as ts.VariableStatement
934 ).declarationList?.declarations[0].name.getText() || ""
935 )
936 }
937
938 /**
939 * Retrieve the HTTP method of a node.
940 *
941 * @param node - The node to retrieve its HTTP method.
942 * @returns The lowercase HTTP method name.
943 */
944 getHTTPMethodName(node: FunctionOrVariableNode): string {
945 return this.getFunctionName(node).toLowerCase()
946 }
947
948 /**
949 * Retrieve the OAS prefix line that's added before the YAML schema.
950 *
951 * @param methodName - The HTTP method name.
952 * @param oasPath - The API route's path
953 * @returns The OAS prefix line.
954 */
955 getOasPrefix(methodName: string, oasPath: string): string {
956 return `@oas [${methodName}] ${oasPath}`
957 }
958
959 /**
960 * Retrieve the tag name from the split OAS path.
961 *
962 * @param splitOasPath - The split OAS path.
963 * @returns The tag name if available.
964 */
965 getTagName(splitOasPath: string[]): string | undefined {
966 return splitOasPath.length >= 2 ? kebabToTitle(splitOasPath[1]) : undefined
967 }
968
969 /**
970 * Retrieve the authentication details of a node.
971 *
972 * @param node - The node to retrieve its authentication details.
973 * @param oasPath - The OAS path of the node.
974 * @returns The authentication details.
975 */
976 getAuthenticationDetails(
977 node: FunctionNode,
978 oasPath: string,
979 httpMethod: string
980 ): {
981 /**
982 * Whether the OAS operation requires admin authentication.
983 */
984 isAdminAuthenticated: boolean
985 /**
986 * Whether the OAS operation requires customer authentication.
987 */
988 isStoreAuthenticated: boolean
989 /**
990 * Whether the OAS operation requires authentication in genral.
991 */
992 isAuthenticated: boolean
993 /**
994 * Override the default security requirements.
995 */
996 allowedAuthTypes?: string[]
997 } {
998 const isAuthenticationDisabled = node
999 .getSourceFile()
1000 .statements.some((statement) =>
1001 statement.getText().includes("AUTHENTICATE = false")
1002 )
1003 const hasAuthenticationOverride = this.AUTH_REQUESTS.find((authRequest) => {
1004 const pathMatch =
1005 authRequest.exact === oasPath ||
1006 (authRequest.startsWith && oasPath.startsWith(authRequest.startsWith))
1007 const httpMethodMatch =
1008 !authRequest.httpMethods || authRequest.httpMethods.includes(httpMethod)
1009 return pathMatch && httpMethodMatch
1010 })
1011 const isAuthRequired =
1012 hasAuthenticationOverride?.requiresAuthentication === true
1013 const isAdminAuthenticated =
1014 (!isAuthenticationDisabled || isAuthRequired) &&
1015 oasPath.startsWith("admin")
1016 const isStoreAuthenticated = isAuthRequired
1017 ? oasPath.startsWith("store")
1018 : !isAuthenticationDisabled &&
1019 isAuthRequired &&
1020 oasPath.startsWith("store")
1021 const isAuthenticated =
1022 isAdminAuthenticated || isStoreAuthenticated || isAuthRequired
1023
1024 return {
1025 isAdminAuthenticated,
1026 isStoreAuthenticated,
1027 isAuthenticated,
1028 allowedAuthTypes: hasAuthenticationOverride?.allowedAuthTypes,
1029 }
1030 }
1031
1032 /**
1033 * Retrieve the OAS operation's ID.
1034 *
1035 * @param param0 - The OAS operation's details.
1036 * @returns The operation's ID.
1037 */
1038 getOperationId({
1039 methodName,
1040 splitOasPath,
1041 }: {
1042 /**
1043 * The HTTP method's name.
1044 */
1045 methodName: string
1046 /**
1047 * The split OAS path.
1048 */
1049 splitOasPath: string[]
1050 }): string {
1051 let str = capitalize(methodName)
1052 splitOasPath.slice(1).forEach((item) => {
1053 if (API_ROUTE_PARAM_REGEX.test(item)) {
1054 item = item.replace(API_ROUTE_PARAM_REGEX, "$1")
1055 }
1056
1057 str += item
1058 .split("-")
1059 .map((subitem) => capitalize(subitem))
1060 .join("")
1061 })
1062
1063 return str
1064 }
1065
1066 /**
1067 * Retrieve the security details of an OAS operation.
1068 *
1069 * @param param0 - The authentication details.
1070 * @returns The security details.
1071 */
1072 getSecurity({
1073 isAdminAuthenticated,
1074 isAuthenticated,
1075 auth_types,
1076 }: {
1077 /**
1078 * Whether the operation requires admin authentication.
1079 */
1080 isAdminAuthenticated: boolean
1081 /**
1082 * Whether the operation requires general authentication.
1083 */
1084 isAuthenticated: boolean
1085 /**
1086 * Override the default security requirements.
1087 */
1088 auth_types?: string[]
1089 }): OpenAPIV3.SecurityRequirementObject[] | undefined {
1090 const security: OpenAPIV3.SecurityRequirementObject[] = []
1091 const allowed_auth_types =
1092 auth_types ||
1093 [
1094 "cookie_auth",
1095 "jwt_token",
1096 isAdminAuthenticated ? "api_token" : undefined,
1097 ].filter(Boolean)
1098 if (isAdminAuthenticated && allowed_auth_types.includes("api_token")) {
1099 security.push({
1100 api_token: [],
1101 })
1102 }
1103 if (isAuthenticated) {
1104 if (allowed_auth_types.includes("cookie_auth")) {
1105 security.push({
1106 cookie_auth: [],
1107 })
1108 }
1109 if (allowed_auth_types.includes("jwt_token")) {
1110 security.push({
1111 jwt_token: [],
1112 })
1113 }
1114 }
1115
1116 return security.length ? security : undefined
1117 }
1118
1119 /**
1120 * Format a schema as a parameter object. Can be used for path or query parameters.
1121 *
1122 * @param param0 - The operation's details.
1123 * @returns The parameter object.
1124 */
1125 getParameterObject({
1126 type,
1127 name,
1128 description,
1129 required,
1130 schema,
1131 }: {
1132 /**
1133 * The parameter type.
1134 */
1135 type: ParameterType
1136 /**
1137 * The name of the parameter.
1138 */
1139 name: string
1140 /**
1141 * Whether the parameter is required.
1142 */
1143 required: boolean
1144 /**
1145 * The parameter's description.
1146 */
1147 description?: string
1148 /**
1149 * The parameter's schema.
1150 */
1151 schema: OpenApiSchema
1152 }): OpenAPIV3.ParameterObject {
1153 return {
1154 name: name,
1155 in: type,
1156 description: description,
1157 required: required,
1158 schema: schema,
1159 }
1160 }
1161
1162 /**
1163 * Retrieve the path parameters.
1164 *
1165 * @param param0 - The OAS operation's details.
1166 * @returns The list of path parameters.
1167 */
1168 getPathParameters({
1169 oasPath,
1170 tagName,
1171 }: {
1172 /**
1173 * The OAS path.
1174 */
1175 oasPath: string
1176 /**
1177 * The tag name.
1178 */
1179 tagName?: string
1180 }): OpenAPIV3.ParameterObject[] {
1181 // reset regex manually
1182 API_ROUTE_PARAM_REGEX.lastIndex = 0
1183 let pathParameters: string[] | undefined
1184 const parameters: OpenAPIV3.ParameterObject[] = []
1185 while (
1186 (pathParameters = API_ROUTE_PARAM_REGEX.exec(oasPath)?.slice(1)) !==
1187 undefined
1188 ) {
1189 if (pathParameters.length) {
1190 pathParameters.forEach((parameter) =>
1191 parameters.push(
1192 this.getParameterObject({
1193 type: "path",
1194 name: parameter,
1195 description: this.getSchemaDescription({
1196 typeStr: parameter,
1197 parentName: tagName,
1198 }),
1199 required: true,
1200 schema: {
1201 type: "string",
1202 },
1203 })
1204 )
1205 )
1206 }
1207 }
1208
1209 return parameters
1210 }
1211
1212 /**
1213 * Retrieve the request query parameters and body schema.
1214 *
1215 * @param param0 - The operation's details.
1216 * @returns The request query parameters and body schema.
1217 */
1218 getRequestParameters({
1219 node,
1220 tagName,
1221 methodName,
1222 oasPath,
1223 forUpdate = false,
1224 }: {
1225 /**
1226 * The node to retrieve its request parameters.
1227 */
1228 node: FunctionNode
1229 /**
1230 * The HTTP method name of the function.
1231 */
1232 methodName: string
1233 /**
1234 * The tag's name.
1235 */
1236 tagName?: string
1237 /**
1238 * The OAS path.
1239 */
1240 oasPath: string
1241 /**
1242 * Whether the request parameters are retrieved for update purposes only.
1243 */
1244 forUpdate?: boolean
1245 }): {
1246 /**
1247 * The query parameters.
1248 */
1249 queryParameters: OpenAPIV3.ParameterObject[]
1250 /**
1251 * The request schema.
1252 */
1253 requestSchema?: OpenApiSchema
1254 } {
1255 const queryParameters: OpenAPIV3.ParameterObject[] = []
1256 let requestSchema: OpenApiSchema | undefined
1257 const isLocalizedRoute = this.LOCALIZED_ROUTES.some((route) =>
1258 oasPath.startsWith(route)
1259 )
1260
1261 if (isLocalizedRoute) {
1262 queryParameters.push(
1263 this.getParameterObject({
1264 type: "query",
1265 name: "locale",
1266 description:
1267 "The locale in BCP 47 format to retrieve localized content.",
1268 required: false,
1269 schema: {
1270 type: "string",
1271 example: "en-US",
1272 externalDocs: {
1273 url: "https://docs.medusajs.com/resources/commerce-modules/translation/storefront",
1274 description:
1275 "Learn more in the Serve Translations in Storefront guide.",
1276 },
1277 },
1278 })
1279 )
1280 }
1281
1282 const requestTypeReferenceNode = this.getRequestTypeReferenceNode(
1283 node.parameters[0].type
1284 )
1285
1286 if (!requestTypeReferenceNode) {
1287 return {
1288 queryParameters,
1289 requestSchema,
1290 }
1291 }
1292
1293 const requestType = this.checker.getTypeFromTypeNode(
1294 requestTypeReferenceNode
1295 ) as ts.TypeReference
1296
1297 const requestTypeArguments =
1298 requestType.typeArguments || requestType.aliasTypeArguments
1299 const shouldCheckTypeArgumentForQuery =
1300 this.REQUEST_CHECK_QUERY_ARGS.includes(
1301 requestTypeReferenceNode.typeName.getText()
1302 )
1303
1304 if (
1305 !requestTypeArguments ||
1306 (requestTypeArguments.length < 2 && !shouldCheckTypeArgumentForQuery)
1307 ) {
1308 return {
1309 queryParameters,
1310 requestSchema,
1311 }
1312 }
1313
1314 const checkQueryIndex = requestTypeArguments.length >= 2 ? 1 : 0
1315 // Not all routes support a second type argument yet,
1316 // so the query param may be passed in the first type argument
1317 const hasQueryParams =
1318 requestTypeArguments[checkQueryIndex].getProperties().length > 0
1319 // Not all routes support a second type argument yet,
1320 // so we have to support routes that pass the query parameters type
1321 // in the first type argument
1322 const isQuery = methodName === "get"
1323
1324 const zodObjectRequestBodyTypeName = getCorrectZodTypeName({
1325 typeReferenceNode: requestTypeReferenceNode,
1326 itemType: requestTypeArguments[0],
1327 })
1328 const zodObjectQueryTypeName = getCorrectZodTypeName({
1329 typeReferenceNode: requestTypeReferenceNode,
1330 itemType: requestTypeArguments[checkQueryIndex],
1331 })
1332
1333 const requestBodyParameterSchema = this.typeToSchema({
1334 itemType: requestTypeArguments[0],
1335 descriptionOptions: {
1336 parentName: tagName,
1337 rawParentName: this.checker.typeToString(requestTypeArguments[0]),
1338 },
1339 zodObjectTypeName: zodObjectRequestBodyTypeName,
1340 context: isQuery ? "query" : "request",
1341 saveSchema: !forUpdate,
1342 })
1343 const queryParameterSchema = hasQueryParams
1344 ? this.typeToSchema({
1345 itemType: requestTypeArguments[checkQueryIndex],
1346 descriptionOptions: {
1347 parentName: tagName,
1348 rawParentName: this.checker.typeToString(
1349 requestTypeArguments[checkQueryIndex]
1350 ),
1351 },
1352 zodObjectTypeName: zodObjectQueryTypeName,
1353 context: "query",
1354 saveSchema: !forUpdate,
1355 })
1356 : requestBodyParameterSchema
1357
1358 // If function is a GET function, add the type parameter to the
1359 // query parameters instead of request parameters.
1360 if (
1361 (isQuery || hasQueryParams) &&
1362 queryParameterSchema.type === "object" &&
1363 queryParameterSchema.properties
1364 ) {
1365 Object.entries(queryParameterSchema.properties).forEach(
1366 ([key, propertySchema]) => {
1367 if ("$ref" in propertySchema) {
1368 return
1369 }
1370
1371 // check if parameter is already added
1372 const isAdded = queryParameters.some((param) => param.name === key)
1373
1374 if (isAdded) {
1375 return
1376 }
1377
1378 queryParameters.push(
1379 this.getParameterObject({
1380 name: key,
1381 type: "query",
1382 description: propertySchema.description,
1383 required: queryParameterSchema.required?.includes(key) || false,
1384 schema: propertySchema,
1385 })
1386 )
1387 }
1388 )
1389 }
1390
1391 if (methodName !== "get") {
1392 requestSchema = requestBodyParameterSchema
1393 }
1394
1395 return {
1396 queryParameters,
1397 requestSchema,
1398 }
1399 }
1400
1401 /**
1402 * Retrieve the header parameters of the OAS route.
1403 *
1404 * @param oasPath - The OAS path.
1405 * @returns The header parameters of the route.
1406 */
1407 getHeaderParameters(oasPath: string): OpenAPIV3.ParameterObject[] {
1408 if (!oasPath.startsWith("store")) {
1409 return []
1410 }
1411
1412 return [
1413 this.getParameterObject({
1414 type: "header",
1415 name: "x-publishable-api-key",
1416 description: "Publishable API Key created in the Medusa Admin.",
1417 required: true,
1418 schema: {
1419 type: "string",
1420 externalDocs: {
1421 url: "https://docs.medusajs.com/api/store/publishable-api-key",
1422 },
1423 },
1424 }),
1425 this.getParameterObject({
1426 type: "header",
1427 name: "x-medusa-locale",
1428 description:
1429 "The locale in BCP 47 format to retrieve localized content.",
1430 required: false,
1431 schema: {
1432 type: "string",
1433 example: "en-US",
1434 externalDocs: {
1435 url: "https://docs.medusajs.com/resources/commerce-modules/translation/storefront",
1436 description:
1437 "Learn more in the Serve Translations in Storefront guide.",
1438 },
1439 },
1440 }),
1441 ]
1442 }
1443
1444 /**
1445 * Retrieve the status and content of the response that the route sends.
1446 *
1447 * @param node - The node to retrieve its response details.
1448 * @returns The response's status and, if the route doesn't send a JSON body,
1449 * the response's content.
1450 */
1451 getResponseDetails(node: FunctionNode): {
1452 /**
1453 * The response's status.
1454 */
1455 status: string
1456 /**
1457 * The response's content, if the route sends a body that isn't JSON.
1458 */
1459 content?: OpenAPIV3.ResponseObject["content"]
1460 } {
1461 let status = "200"
1462 let content: OpenAPIV3.ResponseObject["content"] | undefined
1463
1464 if ("body" in node && node.body && "statements" in node.body) {
1465 node.body.statements.forEach((statement) => {
1466 const statementText = statement.getText()
1467 const sendStatusMatched =
1468 RES_SEND_STATUS_REGEX.exec(statementText)?.at(1)
1469
1470 if (sendStatusMatched) {
1471 status = sendStatusMatched
1472 content = this.getStatusMessageContent(status)
1473 return
1474 }
1475
1476 const statusMatched = RES_STATUS_REGEX.exec(statementText)?.at(1)
1477
1478 if (statusMatched) {
1479 status = statusMatched
1480 content = undefined
1481 }
1482 })
1483 }
1484
1485 return { status, content }
1486 }
1487
1488 /**
1489 * Retrieve the content of a response whose body is the status code's message,
1490 * such as `Created` for the `201` status code.
1491 *
1492 * @param status - The response's status.
1493 * @returns The response's content, if the status has an associated message.
1494 */
1495 getStatusMessageContent(
1496 status: string
1497 ): OpenAPIV3.ResponseObject["content"] | undefined {
1498 const statusMessage = STATUS_CODES[status]
1499
1500 if (!statusMessage) {
1501 return
1502 }
1503
1504 return {
1505 "text/plain": {
1506 schema: {
1507 type: "string",
1508 title: "message",
1509 description: `The ${status} status code's message.`,
1510 example: statusMessage,
1511 },
1512 },
1513 }
1514 }
1515
1516 /**
1517 * Create the success response of an OAS operation.
1518 *
1519 * @param param0 - The response's details.
1520 * @returns The success response.
1521 */
1522 createSuccessResponse({
1523 schema,
1524 content,
1525 }: {
1526 /**
1527 * The JSON schema of the response's body, if available.
1528 */
1529 schema?: OpenApiSchema
1530 /**
1531 * The response's content, used if the response doesn't have a JSON body.
1532 */
1533 content?: OpenAPIV3.ResponseObject["content"]
1534 }): OpenAPIV3.ResponseObject {
1535 const response: OpenAPIV3.ResponseObject = {
1536 description: "OK",
1537 }
1538
1539 if (schema && Object.keys(schema).length > 0) {
1540 response.content = {
1541 "application/json": {
1542 schema:
1543 this.oasSchemaHelper.namedSchemaToReference(schema) ||
1544 this.oasSchemaHelper.schemaChildrenToRefs(schema),
1545 },
1546 }
1547 } else if (content) {
1548 response.content = content
1549 }
1550
1551 return response
1552 }
1553
1554 /**
1555 * Retrieve the response schema of the OAS operation.
1556 *
1557 * @param param0 - The OAS operation's details.
1558 * @returns The response schema.
1559 */
1560 getResponseSchema({
1561 node,
1562 tagName,
1563 forUpdate = false,
1564 }: {
1565 /**
1566 * The node to retrieve its response schema.
1567 */
1568 node: FunctionNode
1569 /**
1570 * The tag's name.
1571 */
1572 tagName?: string
1573 /**
1574 * Whether the response schema is retrieved for update only.
1575 */
1576 forUpdate?: boolean
1577 }): OpenApiSchema | undefined {
1578 let responseSchema: OpenApiSchema | undefined
1579
1580 if (
1581 node.parameters[1].type &&
1582 ts.isTypeReferenceNode(node.parameters[1].type)
1583 ) {
1584 const responseType = this.checker.getTypeFromTypeNode(
1585 node.parameters[1].type
1586 ) as ts.TypeReference
1587 const responseTypeArguments =
1588 responseType.aliasTypeArguments ||
1589 this.checker.getTypeArguments(responseType)
1590
1591 if (responseTypeArguments.length === 1) {
1592 responseSchema = this.typeToSchema({
1593 itemType: responseTypeArguments[0],
1594 descriptionOptions: {
1595 parentName: tagName,
1596 rawParentName: this.checker.typeToString(responseTypeArguments[0]),
1597 },
1598 zodObjectTypeName: getCorrectZodTypeName({
1599 typeReferenceNode: node.parameters[1].type,
1600 itemType: responseTypeArguments[0],
1601 }),
1602 context: "response",
1603 saveSchema: !forUpdate,
1604 })
1605 }
1606 }
1607
1608 return responseSchema
1609 }
1610
1611 /**
1612 * Convert a TypeScript type to a schema object.
1613 *
1614 * @param param0 - The type and additional details.
1615 * @returns The schema object.
1616 */
1617 typeToSchema({
1618 itemType,
1619 level = 1,
1620 title,
1621 descriptionOptions,
1622 allowedChildren,
1623 disallowedChildren,
1624 zodObjectTypeName,
1625 saveSchema = true,
1626 symbol: originalSymbol,
1627 ...rest
1628 }: {
1629 /**
1630 * The TypeScript type.
1631 */
1632 itemType: ts.Type
1633 /**
1634 * The current level. Used to limit the recursive loop.
1635 */
1636 level?: number
1637 /**
1638 * The type's title, if available.
1639 */
1640 title?: string
1641 /**
1642 * options to retrieve a parameter/property's description.
1643 */
1644 descriptionOptions?: Partial<SchemaDescriptionOptions>
1645 /**
1646 * Children that can be allowed to retrieve. If this property is supplied,
1647 * only children in this array are added to the returned schema.
1648 */
1649 allowedChildren?: string[]
1650 /**
1651 * Children that aren't allowed to retrieve. If this property is supplied,
1652 * only children not included in this array are added to the schema.
1653 */
1654 disallowedChildren?: string[]
1655 /**
1656 * By default, the type name is generated from itemType, which
1657 * doesn't work for types created by Zod. This allows to correct the
1658 * generated type name.
1659 */
1660 zodObjectTypeName?: string
1661 /**
1662 * Whether the type is in a request / response
1663 */
1664 context?: "request" | "response" | "query"
1665 /**
1666 * Whether to save object schemas. Useful when only getting schemas to update.
1667 */
1668 saveSchema?: boolean
1669 /**
1670 * The symbol of the node to retrieve the schema from.
1671 */
1672 symbol?: ts.Symbol
1673 }): OpenApiSchema {
1674 if (isLevelExceeded(level, this.MAX_LEVEL)) {
1675 return {}
1676 }
1677
1678 const symbol = itemType.aliasSymbol || itemType.symbol
1679 // the TSDoc comment of the property, if any, is more accurate than the
1680 // description generated from the knowledge base.
1681 const description =
1682 this.getSymbolDescription(originalSymbol) ||
1683 (descriptionOptions?.typeStr
1684 ? this.getSchemaDescription(
1685 descriptionOptions as SchemaDescriptionOptions
1686 )
1687 : title
1688 ? this.getSchemaDescription({ typeStr: title, nodeType: itemType })
1689 : SUMMARY_PLACEHOLDER)
1690 const typeAsString =
1691 zodObjectTypeName || this.checker.typeToString(itemType)
1692
1693 const schemaFromFactory =
1694 this.schemaFactory.tryGetSchema({
1695 name:
1696 itemType.symbol?.getName() ||
1697 itemType.aliasSymbol?.getName() ||
1698 title ||
1699 typeAsString,
1700 additionalData: {
1701 title: title || typeAsString,
1702 description,
1703 },
1704 context: rest.context,
1705 type: itemType,
1706 }) ||
1707 this.schemaFactory.tryGetSchema({
1708 // remove type arguments from name
1709 name: typeAsString.replace(/<.*>$/, ""),
1710 additionalData: {
1711 title: title || typeAsString,
1712 description,
1713 },
1714 context: rest.context,
1715 type: itemType,
1716 })
1717
1718 if (schemaFromFactory) {
1719 return schemaFromFactory
1720 }
1721
1722 const isEnum = itemType.flags === ts.TypeFlags.Enum
1723 const isEnumParent =
1724 itemType.symbol &&
1725 "parent" in itemType.symbol &&
1726 (itemType.symbol.parent as ts.Symbol)?.valueDeclaration?.kind ===
1727 ts.SyntaxKind.EnumDeclaration
1728
1729 const commentsAndTags = originalSymbol?.valueDeclaration
1730 ? ts.getJSDocCommentsAndTags(originalSymbol?.valueDeclaration)
1731 : symbol?.valueDeclaration
1732 ? ts.getJSDocCommentsAndTags(symbol?.valueDeclaration)
1733 : []
1734
1735 // check if type is now deprecated
1736 const isDeprecated =
1737 commentsAndTags.some((comment) => {
1738 if (!("tags" in comment)) {
1739 return false
1740 }
1741
1742 return comment.tags?.some((tag) => {
1743 return tag.tagName.getText() === "deprecated"
1744 })
1745 }) || undefined // avoid showing it as false in the generated OAS
1746
1747 let featureFlag: string | undefined
1748
1749 commentsAndTags.some((comment) => {
1750 if (!("tags" in comment)) {
1751 return false
1752 }
1753
1754 comment.tags?.some((tag) => {
1755 if (tag.tagName.getText() !== "featureFlag" || !tag.comment) {
1756 return false
1757 }
1758
1759 featureFlag =
1760 typeof tag.comment === "string" ? tag.comment : tag.comment.join(" ")
1761
1762 return true
1763 })
1764
1765 return featureFlag !== undefined
1766 })
1767
1768 switch (true) {
1769 case isEnum || isEnumParent:
1770 const enumMembers: string[] = []
1771 if (isEnum) {
1772 symbol?.members?.forEach((enumMember) => {
1773 if ((enumMember.valueDeclaration as ts.EnumMember).initializer) {
1774 enumMembers.push(
1775 (
1776 enumMember.valueDeclaration as ts.EnumMember
1777 ).initializer!.getText()
1778 )
1779 }
1780 })
1781 } else {
1782 // the item itself is the enum member so add it to the array
1783 enumMembers.push(itemType.symbol.getName())
1784 }
1785 return {
1786 type: "string",
1787 description,
1788 enum: enumMembers,
1789 deprecated: isDeprecated,
1790 "x-featureFlag": featureFlag,
1791 }
1792 case itemType.isLiteral() || typeAsString === "RegExp":
1793 const isString =
1794 itemType.flags === ts.TypeFlags.StringLiteral ||
1795 typeAsString === "RegExp"
1796 return {
1797 type: isString
1798 ? "string"
1799 : itemType.flags === ts.TypeFlags.NumberLiteral
1800 ? "number"
1801 : "boolean",
1802 title: title || typeAsString,
1803 description,
1804 format: this.getSchemaTypeFormat({
1805 typeName: typeAsString,
1806 name: title,
1807 }),
1808 deprecated: isDeprecated,
1809 "x-featureFlag": featureFlag,
1810 }
1811 case itemType.flags === ts.TypeFlags.String ||
1812 itemType.flags === ts.TypeFlags.Number ||
1813 itemType.flags === ts.TypeFlags.Boolean ||
1814 typeAsString === "Date":
1815 return {
1816 type:
1817 typeAsString === "Date"
1818 ? "string"
1819 : (typeAsString as OpenAPIV3.NonArraySchemaObjectType),
1820 title: title || typeAsString,
1821 description,
1822 default: symbol?.valueDeclaration
1823 ? this.getDefaultValue(symbol?.valueDeclaration)
1824 : undefined,
1825 format: this.getSchemaTypeFormat({
1826 typeName: typeAsString,
1827 name: title,
1828 }),
1829 deprecated: isDeprecated,
1830 "x-featureFlag": featureFlag,
1831 }
1832 case ("intrinsicName" in itemType &&
1833 itemType.intrinsicName === "boolean") ||
1834 itemType.flags === ts.TypeFlags.BooleanLiteral:
1835 return {
1836 type: "boolean",
1837 title: title || typeAsString,
1838 description,
1839 default: symbol?.valueDeclaration
1840 ? this.getDefaultValue(symbol?.valueDeclaration)
1841 : undefined,
1842 deprecated: isDeprecated,
1843 "x-featureFlag": featureFlag,
1844 }
1845 case this.checker.isArrayType(itemType):
1846 return {
1847 type: "array",
1848 description,
1849 deprecated: isDeprecated,
1850 items: this.typeToSchema({
1851 itemType: this.checker.getTypeArguments(
1852 itemType as ts.TypeReference
1853 )[0],
1854 level: maybeIncrementLevel(level, "array"),
1855 title,
1856 descriptionOptions:
1857 descriptionOptions || title
1858 ? {
1859 ...descriptionOptions,
1860 parentName: title || descriptionOptions?.parentName,
1861 }
1862 : undefined,
1863 saveSchema,
1864 ...rest,
1865 }),
1866 "x-featureFlag": featureFlag,
1867 }
1868 case itemType.isUnion():
1869 // if it's a union of literal types,
1870 // consider it an enum
1871 const cleanedUpTypes = this.typesHelper.cleanUpTypes(
1872 (itemType as ts.UnionType).types
1873 )
1874 const allLiteral = cleanedUpTypes.every((unionType) =>
1875 unionType.isLiteral()
1876 )
1877
1878 if (allLiteral) {
1879 return {
1880 type: "string",
1881 description,
1882 deprecated: isDeprecated,
1883 enum: cleanedUpTypes.map(
1884 (unionType) => (unionType as ts.LiteralType).value
1885 ),
1886 "x-featureFlag": featureFlag,
1887 }
1888 }
1889
1890 const oneOfItems = cleanedUpTypes.map((unionType) =>
1891 this.typeToSchema({
1892 itemType: unionType,
1893 level: maybeIncrementLevel(level, "oneOf"),
1894 title,
1895 descriptionOptions,
1896 saveSchema,
1897 ...rest,
1898 })
1899 )
1900
1901 if (oneOfItems.length === 1) {
1902 return {
1903 ...oneOfItems[0],
1904 "x-featureFlag": oneOfItems[0]["x-featureFlag"] || featureFlag,
1905 deprecated: oneOfItems[0].deprecated || isDeprecated,
1906 }
1907 }
1908
1909 return {
1910 oneOf: oneOfItems,
1911 deprecated: isDeprecated,
1912 "x-featureFlag": featureFlag,
1913 }
1914 case itemType.isIntersection():
1915 const allOfItems = this.typesHelper
1916 .cleanUpIntersectionTypes((itemType as ts.IntersectionType).types)
1917 .map((intersectionType) => {
1918 return this.typeToSchema({
1919 itemType: intersectionType,
1920 level: maybeIncrementLevel(level, "allOf"),
1921 title,
1922 descriptionOptions,
1923 saveSchema,
1924 ...rest,
1925 })
1926 })
1927
1928 if (allOfItems.length === 1) {
1929 return {
1930 ...allOfItems[0],
1931 "x-featureFlag": allOfItems[0]["x-featureFlag"] || featureFlag,
1932 deprecated: allOfItems[0].deprecated || isDeprecated,
1933 }
1934 }
1935
1936 return {
1937 allOf: allOfItems,
1938 deprecated: isDeprecated,
1939 "x-featureFlag": featureFlag,
1940 }
1941 case typeAsString.startsWith("Pick"):
1942 const pickTypeArgs =
1943 itemType.aliasTypeArguments ||
1944 this.checker.getTypeArguments(itemType as ts.TypeReference)
1945
1946 if (pickTypeArgs.length < 2) {
1947 return {}
1948 }
1949 const pickedProperties = pickTypeArgs[1].isUnion()
1950 ? pickTypeArgs[1].types.map((unionType) =>
1951 this.typesHelper.getTypeName(unionType)
1952 )
1953 : [this.typesHelper.getTypeName(pickTypeArgs[1])]
1954 return this.typeToSchema({
1955 itemType: pickTypeArgs[0],
1956 title,
1957 level,
1958 descriptionOptions,
1959 allowedChildren: pickedProperties,
1960 saveSchema,
1961 ...rest,
1962 })
1963 case typeAsString.startsWith("Omit"):
1964 const omitTypeArgs =
1965 itemType.aliasTypeArguments ||
1966 this.checker.getTypeArguments(itemType as ts.TypeReference)
1967
1968 if (omitTypeArgs.length < 2) {
1969 return {}
1970 }
1971 const omitProperties = omitTypeArgs[1].isUnion()
1972 ? omitTypeArgs[1].types.map((unionType) =>
1973 this.typesHelper.getTypeName(unionType)
1974 )
1975 : [this.typesHelper.getTypeName(omitTypeArgs[1])]
1976 return this.typeToSchema({
1977 itemType: omitTypeArgs[0],
1978 title,
1979 level,
1980 descriptionOptions,
1981 disallowedChildren: omitProperties,
1982 saveSchema,
1983 ...rest,
1984 })
1985 case typeAsString.startsWith("Partial"):
1986 const typeArg =
1987 itemType.aliasTypeArguments ||
1988 this.checker.getTypeArguments(itemType as ts.TypeReference)
1989 if (!typeArg.length) {
1990 return {}
1991 }
1992
1993 const schema = this.typeToSchema({
1994 itemType: typeArg[0],
1995 title,
1996 level,
1997 descriptionOptions,
1998 disallowedChildren,
1999 allowedChildren,
2000 saveSchema,
2001 ...rest,
2002 })
2003
2004 // remove all required items
2005 delete schema.required
2006
2007 return schema
2008 case itemType.isClassOrInterface() ||
2009 itemType.isTypeParameter() ||
2010 (itemType as ts.Type).flags === ts.TypeFlags.Object:
2011 const requiredProperties: string[] = []
2012
2013 const baseType = itemType.getBaseTypes()?.[0]
2014 const isDeleteResponse =
2015 baseType?.aliasSymbol?.getEscapedName() === "DeleteResponse"
2016
2017 const schemaName =
2018 itemType.isClassOrInterface() ||
2019 itemType.isTypeParameter() ||
2020 (isZodObject(itemType) && zodObjectTypeName)
2021 ? this.oasSchemaHelper.normalizeSchemaName(typeAsString)
2022 : undefined
2023
2024 const objSchema: OpenApiSchema = {
2025 type: "object",
2026 // a named schema is written to its own file and referenced with `$ref`,
2027 // which discards the description of the property it was reached from.
2028 // So, the type's description is used instead when available.
2029 description: schemaName
2030 ? this.getSymbolDescription(symbol) || description
2031 : description,
2032 deprecated: isDeprecated,
2033 "x-schemaName": schemaName,
2034 // this is changed later
2035 required: undefined,
2036 "x-featureFlag": featureFlag,
2037 }
2038
2039 const properties: Record<
2040 string,
2041 OpenApiSchema | OpenAPIV3.ReferenceObject
2042 > = {}
2043 let isAdditionalProperties = false
2044
2045 if (!isLevelExceeded(level + 1, this.MAX_LEVEL)) {
2046 let itemProperties = itemType.getProperties()
2047
2048 if (
2049 !itemProperties.length &&
2050 itemType.aliasTypeArguments?.length === 2 &&
2051 itemType.aliasTypeArguments[0].flags === ts.TypeFlags.String
2052 ) {
2053 const isValueObj =
2054 itemType.aliasTypeArguments[1].isClassOrInterface() ||
2055 itemType.aliasTypeArguments[1].isTypeParameter() ||
2056 ((itemType.aliasTypeArguments[1] as ts.Type).flags ===
2057 ts.TypeFlags.Object &&
2058 !this.checker.isArrayType(itemType.aliasTypeArguments[1]))
2059
2060 if (isValueObj) {
2061 // object has dynamic keys, so put the properties under additionalProperties
2062 itemProperties = itemType.aliasTypeArguments[1].getProperties()
2063 isAdditionalProperties = true
2064 }
2065 }
2066
2067 itemProperties.forEach((property) => {
2068 if (
2069 (allowedChildren && !allowedChildren.includes(property.name)) ||
2070 (disallowedChildren && disallowedChildren.includes(property.name))
2071 ) {
2072 return
2073 }
2074
2075 const shouldIgnore = property
2076 .getJsDocTags()
2077 .some((tag) => tag.name === "ignore")
2078
2079 if (shouldIgnore) {
2080 return
2081 }
2082
2083 if (this.isRequired(property)) {
2084 requiredProperties.push(property.name)
2085 }
2086 const propertyType = this.checker.getTypeOfSymbol(property)
2087
2088 // if property's type is same as parent's property,
2089 // create a reference to the parent
2090 const arrHasParentType =
2091 rest.context !== "query" &&
2092 this.checker.isArrayType(propertyType) &&
2093 this.typesHelper.areTypesEqual(
2094 itemType,
2095 this.checker.getTypeArguments(
2096 propertyType as ts.TypeReference
2097 )[0]
2098 )
2099 const isParentType =
2100 rest.context !== "query" &&
2101 this.typesHelper.areTypesEqual(itemType, propertyType)
2102
2103 if (isParentType && objSchema["x-schemaName"]) {
2104 properties[property.name] = {
2105 $ref: this.oasSchemaHelper.constructSchemaReference(
2106 objSchema["x-schemaName"]
2107 ),
2108 }
2109
2110 return
2111 } else if (arrHasParentType && objSchema["x-schemaName"]) {
2112 properties[property.name] = {
2113 type: "array",
2114 description,
2115 items: {
2116 $ref: this.oasSchemaHelper.constructSchemaReference(
2117 objSchema["x-schemaName"]
2118 ),
2119 },
2120 } as OpenAPIV3.ArraySchemaObject
2121
2122 return
2123 }
2124
2125 properties[property.name] = this.typeToSchema({
2126 itemType: propertyType,
2127 level: maybeIncrementLevel(level, "object"),
2128 title: property.name,
2129 descriptionOptions: {
2130 ...descriptionOptions,
2131 typeStr: property.name,
2132 parentName: title || descriptionOptions?.parentName,
2133 },
2134 saveSchema,
2135 symbol: property,
2136 ...rest,
2137 })
2138
2139 if (
2140 isDeleteResponse &&
2141 property.name === "object" &&
2142 !this.oasSchemaHelper.isRefObject(properties[property.name])
2143 ) {
2144 const schemaProperty = properties[property.name] as OpenApiSchema
2145 // try to retrieve default from `DeleteResponse`'s type argument
2146 const deleteTypeArg = baseType.aliasTypeArguments?.[0]
2147 schemaProperty.default =
2148 deleteTypeArg && "value" in deleteTypeArg
2149 ? (deleteTypeArg.value as string)
2150 : schemaProperty.default
2151 }
2152 })
2153 }
2154
2155 if (Object.values(properties).length) {
2156 if (isAdditionalProperties) {
2157 objSchema.additionalProperties = {
2158 type: "object",
2159 properties,
2160 }
2161 } else {
2162 objSchema.properties = properties
2163 }
2164 }
2165
2166 objSchema.required =
2167 requiredProperties.length > 0 ? requiredProperties : undefined
2168
2169 if (saveSchema && objSchema["x-schemaName"]) {
2170 // add object to schemas to be created
2171 // if necessary
2172 this.oasSchemaHelper.namedSchemaToReference(objSchema)
2173 }
2174
2175 return objSchema
2176 default:
2177 return {}
2178 }
2179 }
2180
2181 /**
2182 * Retrieve the description of a symbol from its TSDoc comment.
2183 *
2184 * @param symbol - The symbol to retrieve its description.
2185 * @returns The symbol's description, if it has a TSDoc comment.
2186 */
2187 getSymbolDescription(symbol?: ts.Symbol): string | undefined {
2188 const commentParts = symbol?.getDocumentationComment(this.checker)
2189
2190 if (!commentParts?.length) {
2191 return
2192 }
2193
2194 return ts.displayPartsToString(commentParts).trim() || undefined
2195 }
2196
2197 /**
2198 * Retrieve the description of a symbol, type, or node. Can be used to retrieve
2199 * the description of a property or parameter in a schema.
2200 *
2201 * @param param0 - The details of the item to retrieve its description.
2202 * @returns The description.
2203 */
2204 getSchemaDescription({
2205 symbol,
2206 node,
2207 nodeType,
2208 typeStr,
2209 ...templateOptions
2210 }: SchemaDescriptionOptions): string {
2211 if (!symbol && !node && !nodeType) {
2212 // if none of the associated symbol, node, or type are provided,
2213 // either retrieve the description from the knowledge base or use
2214 // the default summary
2215 return (
2216 this.knowledgeBaseFactory.tryToGetOasSchemaDescription({
2217 str: typeStr,
2218 templateOptions,
2219 }) || SUMMARY_PLACEHOLDER
2220 )
2221 }
2222
2223 if (node) {
2224 return this.getNodeSummary({
2225 node: node,
2226 symbol,
2227 nodeType,
2228 })
2229 }
2230
2231 let description = ""
2232
2233 if (nodeType) {
2234 description = this.getTypeDocBlock(nodeType)
2235 }
2236
2237 if (!description.length && symbol) {
2238 description = this.getSymbolDocBlock(symbol)
2239 }
2240
2241 return description.length ? description : SUMMARY_PLACEHOLDER
2242 }
2243
2244 /**
2245 * Check whether a symbol is required.
2246 *
2247 * @param symbol - The symbol to check.
2248 * @param level - The current recursion level to avoid max-stack error
2249 * @returns Whether the symbol is required.
2250 */
2251 isRequired(symbol: ts.Symbol, level = 1): boolean {
2252 let isRequired = true
2253 const checkNode = (node: ts.Node) => {
2254 switch (node.kind) {
2255 case ts.SyntaxKind.CallExpression:
2256 const expression =
2257 "expression" in node
2258 ? (node.expression as ts.Expression)
2259 : undefined
2260
2261 if (!expression || !("name" in expression)) {
2262 break
2263 }
2264
2265 const expressionName = (expression.name as ts.Identifier).getText()
2266 isRequired =
2267 expressionName !== "optional" && expressionName !== "nullish"
2268 break
2269 case ts.SyntaxKind.QuestionToken:
2270 isRequired = false
2271 }
2272
2273 if (!isRequired) {
2274 return
2275 }
2276
2277 node.forEachChild(checkNode)
2278 }
2279 if (
2280 !symbol.valueDeclaration &&
2281 symbol.declarations?.length &&
2282 "symbol" in symbol.declarations[0] &&
2283 !isLevelExceeded(level, this.MAX_LEVEL)
2284 ) {
2285 return this.isRequired(
2286 symbol.declarations[0].symbol as ts.Symbol,
2287 maybeIncrementLevel(level, "object")
2288 )
2289 }
2290
2291 ;(symbol.valueDeclaration || symbol.declarations?.[0])?.forEachChild(
2292 checkNode
2293 )
2294
2295 return isRequired
2296 }
2297
2298 /**
2299 * Retrieve the format of a property/parameter in a schema.
2300 *
2301 * @param param0 - The item's details.
2302 * @returns The format, if available.
2303 */
2304 getSchemaTypeFormat({
2305 typeName,
2306 name,
2307 }: {
2308 typeName: string
2309 name?: string
2310 }): string | undefined {
2311 switch (true) {
2312 case typeName === "Date":
2313 return "date-time"
2314 case name?.includes("email"):
2315 return "email"
2316 case name?.includes("password"):
2317 return "password"
2318 }
2319 }
2320
2321 /**
2322 * Initialize the {@link tags} property.
2323 */
2324 init() {
2325 this.tags.set("admin", new Set())
2326 this.tags.set("store", new Set())
2327 }
2328
2329 /**
2330 * Update an array of parameters with a new one.
2331 *
2332 * @param param0 - The parameter details.
2333 * @returns The updated parameters.
2334 */
2335 updateParameters({
2336 oldParameters,
2337 newParameters,
2338 types,
2339 }: {
2340 /**
2341 * The old list of parameters.
2342 */
2343 oldParameters?: OpenAPIV3.ParameterObject[]
2344 /**
2345 * The new list of parameters.
2346 */
2347 newParameters?: OpenAPIV3.ParameterObject[]
2348 /**
2349 * The type of parameters.
2350 */
2351 types: ParameterType[]
2352 }): {
2353 parameters: OpenAPIV3.ParameterObject[]
2354 wasUpdated: boolean
2355 } {
2356 let wasUpdated = false
2357 if (!oldParameters) {
2358 return {
2359 parameters: newParameters || [],
2360 wasUpdated: !!newParameters?.length,
2361 }
2362 }
2363 const oppositeParamType = ["path", "query", "header"].filter(
2364 (item) => !types.includes(item as ParameterType)
2365 ) as ParameterType[]
2366 const oppositeParams: OpenAPIV3.ParameterObject[] =
2367 oldParameters?.filter((param) =>
2368 oppositeParamType.includes(param.in as ParameterType)
2369 ) || []
2370 // check and update/add parameters if necessary
2371 const existingParams: OpenAPIV3.ParameterObject[] =
2372 oldParameters?.filter((param) =>
2373 types.includes(param.in as ParameterType)
2374 ) || []
2375 const paramsToRemove = new Set<string>()
2376
2377 existingParams.forEach((parameter) => {
2378 const updatedParameter = newParameters?.find(
2379 (newParam) => newParam.name === parameter.name
2380 )
2381 if (!updatedParameter) {
2382 // remove the parameter
2383 paramsToRemove.add(parameter.name)
2384 wasUpdated = true
2385 return
2386 }
2387
2388 if (
2389 updatedParameter.description !== parameter.description &&
2390 parameter.description === SUMMARY_PLACEHOLDER
2391 ) {
2392 parameter.description = updatedParameter.description
2393 }
2394
2395 if (updatedParameter.required !== parameter.required) {
2396 parameter.required = updatedParameter.required
2397 wasUpdated = true
2398 }
2399
2400 if (
2401 (updatedParameter.schema as OpenApiSchema).type !==
2402 (parameter.schema as OpenApiSchema).type
2403 ) {
2404 // the entire schema should be updated if the type changes.
2405 parameter.schema = updatedParameter.schema
2406 wasUpdated = true
2407 } else if ((updatedParameter.schema as OpenApiSchema).type === "array") {
2408 const updateResult = this.updateSchema({
2409 oldSchema: (parameter.schema as OpenAPIV3.ArraySchemaObject).items,
2410 newSchema: (updatedParameter.schema as OpenAPIV3.ArraySchemaObject)
2411 .items,
2412 })
2413 ;(parameter.schema as OpenAPIV3.ArraySchemaObject).items =
2414 updateResult?.schema ||
2415 (updatedParameter.schema as OpenAPIV3.ArraySchemaObject).items
2416 wasUpdated = updateResult?.wasUpdated || wasUpdated
2417 } else if ((updatedParameter.schema as OpenApiSchema).type === "object") {
2418 const updateResult = this.updateSchema({
2419 oldSchema: parameter.schema,
2420 newSchema: updatedParameter.schema,
2421 })
2422 parameter.schema = updateResult?.schema || updatedParameter.schema
2423 wasUpdated = updateResult?.wasUpdated || wasUpdated
2424 }
2425
2426 if (
2427 (updatedParameter.schema as OpenApiSchema).title !==
2428 (parameter.schema as OpenApiSchema).title
2429 ) {
2430 ;(parameter.schema as OpenApiSchema).title = (
2431 updatedParameter.schema as OpenApiSchema
2432 ).title
2433 wasUpdated = true
2434 }
2435
2436 if (
2437 (updatedParameter.schema as OpenApiSchema).description !==
2438 (parameter.schema as OpenApiSchema).description &&
2439 (parameter.schema as OpenApiSchema).description === SUMMARY_PLACEHOLDER
2440 ) {
2441 ;(parameter.schema as OpenApiSchema).description = (
2442 updatedParameter.schema as OpenApiSchema
2443 ).description
2444 }
2445 })
2446
2447 // find new parameters to add
2448 newParameters?.forEach((parameter) => {
2449 if (existingParams.some((newParam) => newParam.name === parameter.name)) {
2450 return
2451 }
2452
2453 existingParams?.push(parameter)
2454 wasUpdated = true
2455 })
2456
2457 // remove parameters no longer existing
2458 return {
2459 parameters: [
2460 ...oppositeParams,
2461 ...(existingParams?.filter(
2462 (parameter) =>
2463 oppositeParamType.includes(
2464 (parameter as OpenAPIV3.ParameterObject).in as ParameterType
2465 ) ||
2466 !paramsToRemove.has((parameter as OpenAPIV3.ParameterObject).name)
2467 ) || []),
2468 ],
2469 wasUpdated,
2470 }
2471 }
2472
2473 /**
2474 * Retrieve the updated schema. Can be used for request and response schemas.
2475 *
2476 * @param param0 - The schema details.
2477 * @returns The updated schema.
2478 */
2479 updateSchema({
2480 oldSchema,
2481 newSchema,
2482 level = 1,
2483 }: {
2484 /**
2485 * The old schema.
2486 */
2487 oldSchema?: OpenApiSchema | OpenAPIV3.ReferenceObject
2488 /**
2489 * The new schema.
2490 */
2491 newSchema?: OpenApiSchema | OpenAPIV3.ReferenceObject
2492 /**
2493 * The current level in the update schema. Used to avoid
2494 * maximum call stack size exceeded error
2495 */
2496 level?: number
2497 }):
2498 | {
2499 schema: OpenApiSchema | undefined
2500 wasUpdated: boolean
2501 }
2502 | undefined {
2503 let wasUpdated = false
2504 if (isLevelExceeded(level, this.MAX_LEVEL)) {
2505 return
2506 }
2507
2508 let oldSchemaObj = (
2509 oldSchema && "$ref" in oldSchema
2510 ? this.oasSchemaHelper.getSchemaByName(oldSchema.$ref, true, true)
2511 ?.schema
2512 : oldSchema
2513 ) as OpenApiSchema | undefined
2514 const newSchemaObj = (
2515 newSchema && "$ref" in newSchema
2516 ? this.oasSchemaHelper.getSchemaByName(newSchema.$ref)?.schema
2517 : newSchema
2518 ) as OpenApiSchema | undefined
2519
2520 const oldSchemaKeys = oldSchemaObj ? Object.keys(oldSchemaObj) : []
2521 const hasOldSchemaObj =
2522 oldSchemaObj !== undefined && oldSchemaKeys.length > 0
2523 const hasNewSchemaObj =
2524 newSchemaObj !== undefined && Object.keys(newSchemaObj).length > 0
2525
2526 if (!hasOldSchemaObj || !hasNewSchemaObj) {
2527 // if old schema is just made up of description, return it.
2528 const useOldSchema =
2529 oldSchemaKeys.length === 1 &&
2530 newSchemaObj !== undefined &&
2531 oldSchemaKeys[0] === "description"
2532 return {
2533 schema: hasNewSchemaObj
2534 ? newSchemaObj
2535 : useOldSchema
2536 ? oldSchemaObj
2537 : undefined,
2538 wasUpdated: !hasNewSchemaObj
2539 ? !useOldSchema && hasOldSchemaObj
2540 : hasOldSchemaObj !== hasNewSchemaObj,
2541 }
2542 }
2543
2544 const oldSchemaType = this.inferOasSchemaType(oldSchemaObj)
2545 const newSchemaType = this.inferOasSchemaType(newSchemaObj)
2546
2547 if (oldSchemaType !== newSchemaType && newSchemaType && newSchemaObj) {
2548 oldSchemaObj = {
2549 ...newSchemaObj,
2550 description: oldSchemaObj?.description,
2551 example: oldSchemaObj?.example || newSchemaObj.example,
2552 }
2553 wasUpdated = true
2554 } else if (
2555 oldSchemaObj?.allOf &&
2556 newSchemaObj.allOf &&
2557 oldSchemaObj.allOf.length !== newSchemaObj.allOf.length
2558 ) {
2559 oldSchemaObj.allOf = newSchemaObj.allOf
2560 wasUpdated = true
2561 } else if (
2562 oldSchemaObj?.oneOf &&
2563 newSchemaObj.oneOf &&
2564 oldSchemaObj.oneOf.length !== newSchemaObj.oneOf.length
2565 ) {
2566 oldSchemaObj.oneOf = newSchemaObj.oneOf
2567 wasUpdated = true
2568 } else if (
2569 oldSchemaObj?.anyOf &&
2570 newSchemaObj.anyOf &&
2571 oldSchemaObj.anyOf.length !== newSchemaObj.anyOf.length
2572 ) {
2573 oldSchemaObj.anyOf = newSchemaObj.anyOf
2574 wasUpdated = true
2575 } else if (oldSchemaType === "object") {
2576 if (!oldSchemaObj?.properties && newSchemaObj?.properties) {
2577 oldSchemaObj!.properties = newSchemaObj.properties
2578 wasUpdated = true
2579 } else if (!newSchemaObj?.properties) {
2580 if (oldSchemaObj!.properties) {
2581 wasUpdated = true
2582 }
2583 delete oldSchemaObj!.properties
2584
2585 // check if additionalProperties should be updated
2586 if (
2587 !oldSchemaObj!.additionalProperties &&
2588 newSchemaObj.additionalProperties
2589 ) {
2590 oldSchemaObj!.additionalProperties = newSchemaObj.additionalProperties
2591 } else if (!newSchemaObj.additionalProperties) {
2592 delete oldSchemaObj!.additionalProperties
2593 } else if (
2594 typeof oldSchemaObj!.additionalProperties !== "boolean" &&
2595 typeof newSchemaObj!.additionalProperties !== "boolean"
2596 ) {
2597 const updateResult = this.updateSchema({
2598 oldSchema: oldSchemaObj!.additionalProperties,
2599 newSchema: newSchemaObj.additionalProperties,
2600 level: maybeIncrementLevel(level, "object"),
2601 })
2602 oldSchemaObj!.additionalProperties =
2603 updateResult?.schema || oldSchemaObj!.additionalProperties
2604 }
2605 } else {
2606 // update existing properties
2607 Object.entries(oldSchemaObj!.properties!).forEach(
2608 ([propertyName, propertySchema]) => {
2609 const newPropertySchemaKey = Object.keys(
2610 newSchemaObj!.properties!
2611 ).find((newPropertyName) => newPropertyName === propertyName)
2612 if (!newPropertySchemaKey) {
2613 // remove property
2614 delete oldSchemaObj!.properties![propertyName]
2615 wasUpdated = true
2616 return
2617 }
2618
2619 const updateResult = this.updateSchema({
2620 oldSchema: propertySchema as OpenApiSchema,
2621 newSchema: newSchemaObj!.properties![
2622 propertyName
2623 ] as OpenApiSchema,
2624 level: maybeIncrementLevel(level, "object"),
2625 })
2626 oldSchemaObj!.properties![propertyName] =
2627 updateResult?.schema || propertySchema
2628 wasUpdated = updateResult?.wasUpdated || wasUpdated
2629 }
2630 )
2631 // add new properties
2632 Object.keys(newSchemaObj!.properties!)
2633 .filter(
2634 (propertyKey) =>
2635 !Object.hasOwn(oldSchemaObj!.properties!, propertyKey)
2636 )
2637 .forEach((newPropertyKey) => {
2638 const tryToUpdateSchema = (
2639 schema: OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject
2640 ) => {
2641 let updatedSchema = schema
2642 const newPropertySchemaName = this.oasSchemaHelper.isRefObject(
2643 schema
2644 )
2645 ? schema.$ref
2646 : "x-schemaName" in schema
2647 ? (schema["x-schemaName"] as string)
2648 : undefined
2649 if (newPropertySchemaName) {
2650 const schemaToUpdate = this.oasSchemaHelper.getSchemaByName(
2651 newPropertySchemaName,
2652 true,
2653 true
2654 )
2655
2656 if (schemaToUpdate) {
2657 const updateResult = this.updateSchema({
2658 oldSchema: schemaToUpdate.schema,
2659 newSchema: schema,
2660 level: maybeIncrementLevel(level, "object"),
2661 })
2662 updatedSchema = updateResult?.schema || newProperty
2663 wasUpdated = updateResult?.wasUpdated || wasUpdated
2664 }
2665 }
2666
2667 return updatedSchema
2668 }
2669
2670 let newProperty = newSchemaObj!.properties![newPropertyKey]
2671
2672 if (
2673 !this.oasSchemaHelper.isRefObject(newProperty) &&
2674 newProperty.type === "array"
2675 ) {
2676 newProperty.items = tryToUpdateSchema(newProperty.items)
2677 } else {
2678 newProperty = tryToUpdateSchema(newProperty)
2679 }
2680
2681 oldSchemaObj!.properties![newPropertyKey] = newProperty
2682 })
2683 }
2684 } else if (
2685 oldSchemaObj?.type === "array" &&
2686 newSchemaObj?.type === "array"
2687 ) {
2688 const updateResult = this.updateSchema({
2689 oldSchema: oldSchemaObj.items as OpenApiSchema,
2690 newSchema: newSchemaObj!.items as OpenApiSchema,
2691 level: maybeIncrementLevel(level, "array"),
2692 })
2693 oldSchemaObj.items = updateResult?.schema || oldSchemaObj.items
2694 wasUpdated = updateResult?.wasUpdated || wasUpdated
2695 }
2696
2697 if (
2698 oldSchemaObj!.description !== newSchemaObj?.description &&
2699 oldSchemaObj!.description === SUMMARY_PLACEHOLDER
2700 ) {
2701 oldSchemaObj!.description =
2702 newSchemaObj?.description || SUMMARY_PLACEHOLDER
2703 }
2704
2705 if (oldSchemaObj?.deprecated !== newSchemaObj?.deprecated) {
2706 // avoid many changes to existing OAS
2707 if (!newSchemaObj?.deprecated) {
2708 if (oldSchemaObj!.deprecated) {
2709 wasUpdated = true
2710 }
2711 delete oldSchemaObj!.deprecated
2712 } else {
2713 oldSchemaObj!.deprecated = newSchemaObj.deprecated
2714 wasUpdated = true
2715 }
2716 }
2717
2718 if (oldSchemaObj?.["x-featureFlag"] !== newSchemaObj?.["x-featureFlag"]) {
2719 // avoid many changes to existing OAS
2720 if (!newSchemaObj?.["x-featureFlag"]) {
2721 if (oldSchemaObj!["x-featureFlag"]) {
2722 wasUpdated = true
2723 }
2724 delete oldSchemaObj!["x-featureFlag"]
2725 } else {
2726 oldSchemaObj!["x-featureFlag"] = newSchemaObj["x-featureFlag"]
2727 wasUpdated = true
2728 }
2729 }
2730
2731 if (!wasUpdated) {
2732 const requiredChanged =
2733 oldSchemaObj!.required?.length !== newSchemaObj?.required?.length ||
2734 oldSchemaObj!.required?.some(
2735 (item, index) => item !== newSchemaObj!.required![index]
2736 ) ||
2737 false
2738
2739 const schemaNameChanged =
2740 !!newSchemaObj?.["x-schemaName"] &&
2741 oldSchemaObj!["x-schemaName"] !== newSchemaObj["x-schemaName"]
2742 wasUpdated = requiredChanged || schemaNameChanged
2743 }
2744 oldSchemaObj!.required = newSchemaObj?.required
2745 if (newSchemaObj?.["x-schemaName"]) {
2746 oldSchemaObj!["x-schemaName"] = newSchemaObj?.["x-schemaName"]
2747 }
2748
2749 return {
2750 schema: oldSchemaObj,
2751 wasUpdated,
2752 }
2753 }
2754
2755 /**
2756 * This method infers a schema's type.
2757 *
2758 * @param schema - The schema to infer its type
2759 * @returns The type, if available.
2760 */
2761 inferOasSchemaType(schema?: OpenApiSchema): string | undefined {
2762 switch (true) {
2763 case schema === undefined:
2764 return undefined
2765 case schema?.allOf !== undefined:
2766 return "allOf"
2767 case schema?.anyOf !== undefined:
2768 return "anyOf"
2769 case schema?.oneOf !== undefined:
2770 return "oneOf"
2771 case schema?.type !== undefined:
2772 return schema.type
2773 case schema !== undefined:
2774 default:
2775 return "object"
2776 }
2777 }
2778
2779 /**
2780 * Retrieve the fields and relations that an API route allows or disallows
2781 * requesting, as configured in the route's middleware.
2782 *
2783 * @param param0 - The route's details.
2784 * @returns The route's restrictions, if it has any.
2785 */
2786 getFieldRestrictions({
2787 node,
2788 oasPath,
2789 methodName,
2790 }: {
2791 /**
2792 * The node of the route's function.
2793 */
2794 node: FunctionNode
2795 /**
2796 * The route's OAS path.
2797 */
2798 oasPath: string
2799 /**
2800 * The lowercase name of the method. For example, `get`.
2801 */
2802 methodName: string
2803 }): FieldRestrictions | undefined {
2804 return this.queryConfigHelper.getFieldRestrictions({
2805 routeFilePath: node.getSourceFile().fileName,
2806 oasPath,
2807 httpMethod: methodName,
2808 })
2809 }
2810
2811 /**
2812 * This method retrieves the workflow used in an API route.
2813 *
2814 * @param node - The node to search through
2815 * @returns The workflow's name.
2816 */
2817 getAssociatedWorkflow(node: FunctionNode): string | undefined {
2818 let workflow: string | undefined
2819
2820 if (!ts.isFunctionDeclaration(node) && !ts.isArrowFunction(node)) {
2821 return
2822 }
2823
2824 const sourceFile = node.getSourceFile()
2825
2826 // if a source file doesn't have imports, then it's assumed that it's not using workflows.
2827 if (!("imports" in sourceFile) || !Array.isArray(sourceFile.imports)) {
2828 return
2829 }
2830
2831 // retrieve workflows imported from `@medusajs/core-flows`
2832 // since there could be multiple import statements from the
2833 // same package, put them in an array
2834 const coreFlowsImports: ts.ImportClause[] = []
2835 ;(sourceFile.imports as ts.Node[]).forEach((importNode) => {
2836 if (
2837 !importNode.parent ||
2838 !ts.isImportDeclaration(importNode.parent) ||
2839 !importNode.parent.importClause?.namedBindings ||
2840 importNode.getText() !== `"@medusajs/core-flows"`
2841 ) {
2842 return
2843 }
2844
2845 coreFlowsImports.push(importNode.parent.importClause)
2846 })
2847
2848 // if no imports found from `@medusajs/core-flows`, return
2849 if (!coreFlowsImports.length) {
2850 return
2851 }
2852
2853 // check if any of the imported vars are used in the function node
2854 // const fileWorkflowImports: Map<string, ts.Identifier> = new Map()
2855 const fnText = node.getText()
2856 coreFlowsImports.forEach((coreFlowsImport) => {
2857 coreFlowsImport.namedBindings?.forEachChild((childImport) => {
2858 if (!ts.isImportSpecifier(childImport) || workflow) {
2859 return
2860 }
2861
2862 const workflowName = childImport.name.getText()
2863
2864 if (
2865 fnText.includes(`${workflowName}(`) ||
2866 fnText.includes(`${workflowName} (`) ||
2867 fnText.includes(`${workflowName}.`) ||
2868 fnText.includes(`we.run(${workflowName}`) ||
2869 fnText.includes(`we.run (${workflowName}`) ||
2870 fnText.includes(`we.run(
2871 ${workflowName}
2872 )`)
2873 ) {
2874 // workaround for API routes that execute a workflow
2875 // by its ID. Not very smart but will do for now.
2876 workflow = workflowName.replace(/Id$/, "")
2877 }
2878 })
2879 })
2880
2881 return workflow
2882 }
2883
2884 /**
2885 * Retrieve the file name that's used to write the OAS operation of a node.
2886 *
2887 * @param node - The node to retrieve its associated file name.
2888 * @returns The file name.
2889 */
2890 getAssociatedFileName(node: FunctionOrVariableNode): string {
2891 const methodName = this.getHTTPMethodName(node)
2892 const { oasPath } = this.getOasPath(node)
2893 const area = oasPath.split("/")[0]
2894
2895 const filename = `${methodName}_${oasPath.replaceAll("/", "_")}.ts`
2896
2897 return join(this.baseOutputPath, "operations", area, filename)
2898 }
2899
2900 /**
2901 * This method is executed when the {@link GeneratorEvent.FINISHED_GENERATE_EVENT} event is triggered.
2902 * It writes new tags, if available, in base YAML.
2903 */
2904 afterGenerate() {
2905 this.writeNewTags("admin")
2906 this.writeNewTags("store")
2907 this.oasSchemaHelper.writeNewSchemas()
2908
2909 // reset tags
2910 this.init()
2911 // reset schemas
2912 this.oasSchemaHelper.init()
2913 }
2914
2915 /**
2916 * Add new tags to the base YAML of an area.
2917 *
2918 * @param area - The area that the tag belongs to.
2919 */
2920 writeNewTags(area: OasArea) {
2921 // load base oas files
2922 const areaYamlPath = join(
2923 this.baseOutputPath,
2924 "base",
2925 `${area}.oas.base.yaml`
2926 )
2927 const areaYaml = parse(
2928 readFileSync(areaYamlPath, "utf-8")
2929 ) as OpenApiDocument
2930 let modifiedTags = false
2931
2932 areaYaml.tags = [...(areaYaml.tags || [])]
2933
2934 this.tags.get(area)?.forEach((tag) => {
2935 const existingTag = areaYaml.tags!.find((baseTag) => baseTag.name === tag)
2936 const schemaName = this.oasSchemaHelper.tagNameToSchemaName(tag, area)
2937 const schema = this.oasSchemaHelper.getSchemaByName(schemaName, false)
2938 const associatedSchema = schema?.schema?.["x-schemaName"]
2939 ? {
2940 $ref: this.oasSchemaHelper.constructSchemaReference(
2941 schema.schema["x-schemaName"]
2942 ),
2943 }
2944 : undefined
2945 if (!existingTag) {
2946 areaYaml.tags!.push({
2947 name: tag,
2948 "x-associatedSchema": associatedSchema,
2949 })
2950 modifiedTags = true
2951 } else if (
2952 existingTag["x-associatedSchema"]?.$ref !== associatedSchema?.$ref
2953 ) {
2954 existingTag["x-associatedSchema"] = associatedSchema
2955 modifiedTags = true
2956 }
2957 })
2958
2959 if (modifiedTags) {
2960 // sort alphabetically
2961 areaYaml.tags.sort((tagA, tagB) => {
2962 return tagA.name.localeCompare(tagB.name)
2963 })
2964 // write to the file
2965 writeFileSync(areaYamlPath, stringify(areaYaml))
2966 }
2967 }
2968
2969 hasResponseType(node: FunctionNode, oas: OpenApiOperation): boolean {
2970 const oldResponseStatus = Object.keys(oas.responses!).find(
2971 (status) => !Object.keys(DEFAULT_OAS_RESPONSES).includes(status)
2972 )
2973 if (!oldResponseStatus) {
2974 return false
2975 }
2976
2977 const responseContent = (
2978 oas.responses![oldResponseStatus] as OpenAPIV3.ResponseObject
2979 ).content
2980 if (!responseContent) {
2981 return false
2982 }
2983
2984 const fnText = node.getText()
2985
2986 return Object.keys(responseContent).some((responseType) =>
2987 fnText.includes(responseType)
2988 )
2989 }
2990
2991 readEventsJson() {
2992 if (this.events.length) {
2993 return
2994 }
2995
2996 const eventsJsonPath = getEventsOutputBasePath()
2997
2998 this.events = JSON.parse(readFileSync(eventsJsonPath, "utf-8"))
2999 }
3000
3001 getOasEvents(workflow: string): OasEvent[] {
3002 const events: OasEvent[] = []
3003
3004 const workflowEvents = this.events.filter((event) =>
3005 event.workflows.includes(workflow)
3006 )
3007
3008 if (workflowEvents.length) {
3009 events.push(
3010 ...workflowEvents.map((event) => ({
3011 name: event.name,
3012 payload: event.payload,
3013 description: event.description,
3014 deprecated: event.deprecated,
3015 deprecated_message: event.deprecated_message,
3016 since: event.since,
3017 }))
3018 )
3019 }
3020
3021 return events
3022 }
3023 }
3024
3025 export default OasKindGenerator