1 import OpenAPIParser from "@readme/openapi-parser"
2 import { Command, Option, OptionValues } from "commander"
3 import { lstat, mkdir, writeFile } from "fs/promises"
4 import { OpenAPIObject } from "openapi3-ts"
5 import * as path from "path"
6 import swaggerInline from "swagger-inline"
7 import { combineOAS } from "./utils/combine-oas"
8 import {
9 mergeBaseIntoOAS,
10 mergePathsAndSchemasIntoOAS,
11 } from "./utils/merge-oas"
12 import { isFile } from "./utils/fs-utils"
13
14 /**
15 * Constants
16 */
17 // Medusa core package directory
18 const medusaPackagePath = path.dirname(require.resolve("@medusajs/medusa"))
19 const basePath = path.resolve(__dirname, "../")
20
21 /**
22 * CLI Command declaration
23 */
24 export const commandName = "oas"
25 export const commandDescription =
26 "Compile full OAS from swagger-inline compliant JSDoc."
27
28 export const commandOptions: Option[] = [
29 new Option("-t, --type <type>", "API type to compile.")
30 .choices(["admin", "store", "combined"])
31 .makeOptionMandatory(),
32 new Option(
33 "-o, --out-dir <outDir>",
34 "Destination directory to output generated OAS files."
35 ).default(process.cwd()),
36 new Option("-D, --dry-run", "Do not output files."),
37 new Option(
38 "-p, --paths <paths...>",
39 "Additional paths to crawl for OAS JSDoc."
40 ),
41 new Option(
42 "-b, --base <base>",
43 "Custom base OAS file to use for swagger-inline."
44 ),
45 new Option("-F, --force", "Ignore OAS validation and output OAS files."),
46 new Option(
47 "--local",
48 "Generate OAS from local files rather than public OAS. This is useful for generating references in the Medusa monorepo."
49 ),
50 ]
51
52 export function getCommand() {
53 const command = new Command(commandName)
54 command.description(commandDescription)
55 for (const opt of commandOptions) {
56 command.addOption(opt)
57 }
58 command.action(async (options) => await execute(options))
59 command.showHelpAfterError(true)
60 return command
61 }
62
63 /**
64 * Main
65 */
66 export async function execute(cliParams: OptionValues) {
67 /**
68 * Process CLI options
69 */
70 const dryRun = !!cliParams.dryRun
71 const force = !!cliParams.force
72 const v2 = !!cliParams.v2
73 const local = !!cliParams.local
74
75 const apiType: ApiType = cliParams.type
76
77 const outDir = path.resolve(cliParams.outDir)
78
79 const additionalPaths = (cliParams.paths ?? []).map((additionalPath) =>
80 path.resolve(additionalPath)
81 )
82 for (const additionalPath of additionalPaths) {
83 if (!(await isDirectory(additionalPath))) {
84 throw new Error(`--paths must be a directory - ${additionalPath}`)
85 }
86 }
87
88 const baseFile = cliParams.base ? path.resolve(cliParams.base) : undefined
89 if (baseFile) {
90 if (!(await isFile(cliParams.base))) {
91 throw new Error(`--base must be a file - ${baseFile}`)
92 }
93 }
94
95 /**
96 * Command execution
97 */
98 if (!dryRun) {
99 await mkdir(outDir, { recursive: true })
100 }
101
102 let oas: OpenAPIObject
103 console.log(`🟣 Generating OAS - ${apiType}`)
104
105 if (apiType === "combined") {
106 const adminOAS = !local
107 ? await getPublicOas("admin")
108 : await getOASFromCodebase("admin")
109 const storeOAS = !local
110 ? await getPublicOas("store")
111 : await getOASFromCodebase("store")
112 oas = await combineOAS(adminOAS, storeOAS)
113 } else {
114 oas = !local
115 ? await getPublicOas(apiType)
116 : await getOASFromCodebase(apiType)
117 }
118
119 if (additionalPaths.length || baseFile) {
120 const customOAS = await getOASFromPaths(additionalPaths, baseFile)
121 if (baseFile) {
122 mergeBaseIntoOAS(oas, customOAS)
123 }
124 if (additionalPaths.length) {
125 mergePathsAndSchemasIntoOAS(oas, customOAS)
126 }
127 }
128
129 setMedusaVersion(oas)
130
131 await validateOAS(oas, apiType, force)
132 if (dryRun) {
133 console.log(`⚫️ Dry run - no files generated`)
134 return
135 }
136 await exportOASToJSON(oas, apiType, outDir)
137 }
138
139 /**
140 * Methods
141 */
142 async function getOASFromCodebase(apiType: ApiType): Promise<OpenAPIObject> {
143 /**
144 * OAS output directory
145 */
146 const oasOutputPath = path.resolve(
147 __dirname,
148 "..",
149 "..",
150 "..",
151 "..",
152 "..",
153 "www",
154 "utils",
155 "generated",
156 "oas-output"
157 )
158 const gen = await swaggerInline(
159 [
160 path.resolve(oasOutputPath, "operations", apiType),
161 path.resolve(oasOutputPath, "schemas"),
162 // We currently load error schemas from here. If we change
163 // that in the future, we should change the path.
164 path.resolve(medusaPackagePath, "dist", "utils/middlewares"),
165 ],
166 {
167 base: path.resolve(oasOutputPath, "base", `${apiType}.oas.base.yaml`),
168 format: ".json",
169 }
170 )
171 return (await OpenAPIParser.parse(JSON.parse(gen))) as OpenAPIObject
172 }
173
174 async function getPublicOas(apiType: ApiType) {
175 const url = `https://docs.medusajs.com/api/download/${apiType}`
176 return (await OpenAPIParser.parse(url)) as OpenAPIObject
177 }
178
179 async function getOASFromPaths(
180 additionalPaths: string[] = [],
181 customBaseFile?: string
182 ): Promise<OpenAPIObject> {
183 console.log(`🔵 Gathering custom OAS`)
184 const gen = await swaggerInline(
185 additionalPaths.map((additionalPath) => {
186 return additionalPath.replace(/\\/g, "/")
187 }),
188 {
189 base:
190 customBaseFile ??
191 path.resolve(basePath, "oas", "default.oas.base.yaml"),
192 format: ".json",
193 logger: (log) => {
194 console.log(log)
195 },
196 }
197 )
198 return (await OpenAPIParser.parse(JSON.parse(gen))) as OpenAPIObject
199 }
200
201 /**
202 * Sets `info.version` to the version of the installed `@medusajs/medusa`
203 * package, so that consumers of the OAS can tell which Medusa version the
204 * document describes. The version in the base OAS files is a static
205 * placeholder, which is why it's overridden here.
206 */
207 function setMedusaVersion(oas: OpenAPIObject): void {
208 let medusaVersion: string | undefined
209
210 try {
211 medusaVersion = require("@medusajs/medusa/package.json").version
212 } catch {
213 // the version stays as-is if the package can't be resolved
214 }
215
216 if (!medusaVersion) {
217 return
218 }
219
220 oas.info = {
221 ...oas.info,
222 version: medusaVersion,
223 }
224 console.log(`🔵 Set OAS version to ${medusaVersion}`)
225 }
226
227 async function validateOAS(
228 oas: OpenAPIObject,
229 apiType: ApiType,
230 force = false
231 ): Promise<void> {
232 try {
233 await OpenAPIParser.validate(JSON.parse(JSON.stringify(oas)))
234 console.log(`🟢 Valid OAS - ${apiType}`)
235 } catch (err) {
236 console.error(`🔴 Invalid OAS - ${apiType}`, err)
237 if (!force) {
238 process.exit(1)
239 }
240 }
241 }
242
243 async function exportOASToJSON(
244 oas: OpenAPIObject,
245 apiType: ApiType,
246 targetDir: string
247 ): Promise<void> {
248 const json = JSON.stringify(oas, null, 2)
249 const filePath = path.resolve(targetDir, `${apiType}.oas.json`)
250 await writeFile(filePath, json)
251 console.log(`⚫️ Exported OAS - ${apiType} - ${filePath}`)
252 }
253
254 async function isDirectory(dirPath: string): Promise<boolean> {
255 try {
256 return (await lstat(path.resolve(dirPath))).isDirectory()
257 } catch (err) {
258 console.log(err)
259 return false
260 }
261 }