1 import {
2 previewDocs,
3 PreviewDocsOptions,
4 } from "@redocly/cli/lib/commands/preview-docs"
5 import { commandWrapper } from "@redocly/cli/lib/wrapper"
6 import { Command, Option, OptionValues } from "commander"
7 import execa from "execa"
8 import fs, { mkdir } from "fs/promises"
9 import mergeWith from "lodash.mergewith"
10
11 import * as path from "path"
12 import yargs from "yargs"
13 import {
14 formatHintRecommendation,
15 getCircularPatchRecommendation,
16 getCircularReferences,
17 } from "./utils/circular-patch-utils"
18 import { getTmpDirectory, isFile } from "./utils/fs-utils"
19 import { readJson } from "./utils/json-utils"
20 import {
21 jsonObjectToYamlString,
22 readYaml,
23 writeYaml,
24 writeYamlFromJson,
25 } from "./utils/yaml-utils"
26
27 /**
28 * Constants
29 */
30 const basePath = path.resolve(__dirname, "../")
31
32 const medusaPluginRelativePath = "./plugins/medusa/index.js"
33 const medusaPluginAbsolutePath = path.resolve(
34 basePath,
35 "redocly/plugins/medusa/index.js"
36 )
37 const configFileDefault = path.resolve(basePath, "redocly/redocly-config.yaml")
38
39 /**
40 * CLI Command declaration
41 */
42 export const commandName = "docs"
43 export const commandDescription =
44 "Sanitize OAS for use with Redocly's API documentation viewer."
45
46 export const commandOptions: Option[] = [
47 new Option(
48 "-s, --src-file <srcFile>",
49 "Path to source OAS JSON file."
50 ).makeOptionMandatory(),
51 new Option(
52 "-o, --out-dir <outDir>",
53 "Destination directory to output the sanitized OAS files."
54 ).default(process.cwd()),
55 new Option(
56 "--config <config>",
57 "Configuration file to merge with default configuration before passing to Redocly's CLI."
58 ),
59 new Option("-D, --dry-run", "Do not output files."),
60 new Option(
61 "--clean",
62 "Delete destination directory content before generating documentation."
63 ),
64 new Option("--split", "Creates a multi-file structure output."),
65 new Option(
66 "--preview",
67 "Open a preview of the documentation. Does not output files."
68 ),
69 new Option(
70 "--html",
71 "Generate a static HTML using Redocly's build-docs command."
72 ),
73 new Option(
74 "--main-file-name <mainFileName>",
75 "The name of the main YAML file."
76 ).default("openapi.yaml"),
77 ]
78
79 export function getCommand(): Command {
80 const command = new Command(commandName)
81 command.description(commandDescription)
82 for (const opt of commandOptions) {
83 command.addOption(opt)
84 }
85 command.action(async (options) => await execute(options))
86 command.showHelpAfterError(true)
87 return command
88 }
89
90 /**
91 * Main
92 */
93 export async function execute(cliParams: OptionValues): Promise<void> {
94 /**
95 * Process CLI options
96 */
97 const shouldClean = !!cliParams.clean
98 const shouldSplit = !!cliParams.split
99 const shouldPreview = !!cliParams.preview
100 const shouldBuildHTML = !!cliParams.html
101 const dryRun = !!cliParams.dryRun
102 const srcFile = path.resolve(cliParams.srcFile)
103 const outDir = path.resolve(cliParams.outDir)
104 const configFileCustom = cliParams.config
105 ? path.resolve(cliParams.config)
106 : undefined
107 if (configFileCustom) {
108 if (!(await isFile(configFileCustom))) {
109 throw new Error(`--config must be a file - ${configFileCustom}`)
110 }
111 if (![".json", ".yaml"].includes(path.extname(configFileCustom))) {
112 throw new Error(
113 `--config file must be of type .json or .yaml - ${configFileCustom}`
114 )
115 }
116 }
117
118 /**
119 * Command execution
120 */
121 console.log(`🟣 Generating API documentation`)
122
123 const tmpDir = await getTmpDirectory()
124 const configTmpFile = path.resolve(tmpDir, "redocly-config.yaml")
125 /** matches naming convention from `redocly split` */
126 const finalOASFile = cliParams.mainFileName
127
128 await createTmpConfig(configFileDefault, configTmpFile)
129 if (configFileCustom) {
130 console.log(
131 `🔵 Merging configuration file - ${configFileCustom} > ${configTmpFile}`
132 )
133 await mergeConfig(configTmpFile, configFileCustom, configTmpFile)
134 }
135
136 if (!dryRun) {
137 if (shouldClean) {
138 console.log(`🟠 Cleaning output directory`)
139 await fs.rm(outDir, { recursive: true, force: true })
140 }
141 await mkdir(outDir, { recursive: true })
142 }
143
144 const srcFileSanitized = path.resolve(tmpDir, "tmp.oas.yaml")
145 await sanitizeOAS(srcFile, srcFileSanitized, configTmpFile)
146 await fixCirclularReferences(srcFileSanitized)
147
148 if (dryRun) {
149 console.log(`⚫️ Dry run - no files generated`)
150 // check out possible changes in redocly config
151 await execa("git", [
152 "checkout",
153 path.join(basePath, "redocly", "redocly-config.yaml"),
154 ])
155 return
156 }
157 if (shouldPreview) {
158 await preview(srcFileSanitized, configTmpFile)
159 return
160 }
161 if (shouldSplit) {
162 await generateReference(srcFileSanitized, outDir)
163 } else {
164 await writeYaml(
165 path.join(outDir, finalOASFile),
166 await fs.readFile(srcFileSanitized, "utf8")
167 )
168 }
169 if (shouldBuildHTML) {
170 const outHTMLFile = path.resolve(outDir, "index.html")
171 await buildHTML(finalOASFile, outHTMLFile, configTmpFile)
172 }
173 console.log(`⚫️ API documentation generated - ${outDir}`)
174 }
175
176 /**
177 * Methods
178 */
179 type RedoclyConfig = {
180 apis?: Record<string, unknown>
181 decorators?: Record<string, unknown>
182 extends?: string[]
183 organization?: string
184 plugins?: string[]
185 preprocessors?: Record<string, unknown>
186 region?: string
187 resolve?: Record<string, unknown>
188 rules?: Record<string, unknown>
189 theme?: Record<string, unknown>
190 }
191
192 const mergeConfig = async (
193 configFileDefault: string,
194 configFileCustom: string,
195 configFileOut: string
196 ): Promise<void> => {
197 const configDefault = await readYaml(configFileDefault)
198 const configCustom =
199 path.extname(configFileCustom) === ".yaml"
200 ? await readYaml(configFileCustom)
201 : await readJson(configFileCustom)
202
203 const config = mergeWith(configDefault, configCustom, (objValue, srcValue) =>
204 Array.isArray(objValue) ? objValue.concat(srcValue) : undefined
205 ) as RedoclyConfig
206
207 await writeYamlFromJson(configFileOut, config)
208 }
209
210 const createTmpConfig = async (
211 configFileDefault: string,
212 configFileOut: string
213 ): Promise<void> => {
214 const config = (await readYaml(configFileDefault)) as RedoclyConfig
215 config.plugins = (config.plugins ?? []).filter(
216 (plugin) => plugin !== medusaPluginRelativePath
217 )
218 config.plugins.push(medusaPluginAbsolutePath)
219
220 await writeYamlFromJson(configFileOut, config)
221 }
222
223 const sanitizeOAS = async (
224 srcFile: string,
225 outFile: string,
226 configFile: string
227 ): Promise<void> => {
228 const { all: logs } = await execa(
229 "yarn",
230 [
231 "redocly",
232 "bundle",
233 srcFile,
234 `--output=${outFile}`,
235 `--config=${configFile}`,
236 ],
237 { cwd: basePath, all: true }
238 )
239 console.log(logs)
240 }
241
242 const fixCirclularReferences = async (srcFile: string): Promise<void> => {
243 const { circularRefs, oas } = await getCircularReferences(srcFile)
244 if (circularRefs.length) {
245 const recommendation = getCircularPatchRecommendation(circularRefs, oas)
246 if (Object.keys(recommendation).length) {
247 const hint = formatHintRecommendation(recommendation)
248 const hintMessage = `
249 ###
250 ${hint}
251 ###
252 `
253 const redoclyConfigPath = path.join(
254 basePath,
255 "redocly",
256 "redocly-config.yaml"
257 )
258 const originalContent = (await readYaml(
259 redoclyConfigPath
260 )) as CircularReferenceConfig
261 Object.keys(recommendation).forEach((recKey) => {
262 originalContent.decorators["medusa/circular-patch"].schemas[recKey] = [
263 ...(originalContent.decorators["medusa/circular-patch"].schemas[
264 recKey
265 ] || []),
266 ...recommendation[recKey],
267 ]
268 })
269
270 await writeYaml(
271 redoclyConfigPath,
272 jsonObjectToYamlString(originalContent)
273 )
274 console.log(
275 `🟡 Added the following unhandled circular references to redocly-config.ts:` +
276 hintMessage
277 )
278 }
279 }
280 console.log(`🟢 All circular references are handled`)
281 }
282
283 const generateReference = async (
284 srcFile: string,
285 outDir: string
286 ): Promise<void> => {
287 const { all: logs } = await execa(
288 "yarn",
289 ["redocly", "split", srcFile, `--outDir=${outDir}`],
290 { cwd: basePath, all: true }
291 )
292 console.log(logs)
293 }
294
295 const preview = async (oasFile: string, configFile: string): Promise<void> => {
296 await commandWrapper(previewDocs)({
297 port: 8080,
298 host: "127.0.0.1",
299 api: oasFile,
300 config: configFile,
301 } as yargs.Arguments<PreviewDocsOptions>)
302 }
303
304 const buildHTML = async (
305 srcFile: string,
306 outFile: string,
307 configFile: string
308 ): Promise<void> => {
309 const { all: logs } = await execa(
310 "yarn",
311 [
312 "redocly",
313 "build-docs",
314 srcFile,
315 `--output=${outFile}`,
316 `--config=${configFile}`,
317 `--cdn=true`,
318 ],
319 { cwd: basePath, all: true }
320 )
321 console.log(logs)
322 }