1 /* eslint-disable no-case-declarations */
2 import { WorkflowManager } from "@medusajs/orchestration"
3 import * as path from "path"
4 import { existsSync, mkdirSync, rmSync, writeFileSync } from "fs"
5 import registerWorkflows from "../utils/register-workflows.js"
6 import DiagramBuilder from "../classes/diagram-builder.js"
7 import { run as runMermaid } from "@mermaid-js/mermaid-cli"
8
9 type Options = {
10 output: string
11 type: "docs" | "markdown" | "mermaid" | "console" | "svg" | "png" | "pdf"
12 theme: boolean
13 prettyNames: boolean
14 }
15
16 export default async function (workflowPath: string, options: Options) {
17 const workflowDefinitions = await registerWorkflows(workflowPath)
18
19 const diagramBuilder = new DiagramBuilder(options)
20
21 if (
22 workflowDefinitions.size > 0 &&
23 ["svg", "png", "pdf"].includes(options.type)
24 ) {
25 console.log(
26 `Generating ${options.type} file(s) with mermaid. This may take some time...`
27 )
28 }
29
30 for (const [name, code] of workflowDefinitions) {
31 const workflow = WorkflowManager.getWorkflow(name)
32
33 if (!workflow) {
34 continue
35 }
36
37 const diagram = diagramBuilder.buildDiagram(workflow.flow_)
38 if (!existsSync(options.output)) {
39 mkdirSync(options.output, { recursive: true })
40 }
41
42 switch (options.type) {
43 case "docs":
44 const workflowPath = path.join(options.output, name)
45 if (!existsSync(workflowPath)) {
46 mkdirSync(workflowPath, { recursive: true })
47 }
48 // write files
49 writeFileSync(path.join(workflowPath, "diagram.mermaid"), diagram)
50 if (code) {
51 writeFileSync(path.join(workflowPath, "code.ts"), code)
52 }
53 break
54 case "mermaid":
55 writeFileSync(path.join(options.output, `${name}.mermaid`), diagram)
56 break
57 case "markdown":
58 writeFileSync(
59 path.join(options.output, `${name}.md`),
60 `\`\`\`mermaid\n${diagram}\n\`\`\``
61 )
62 break
63 case "console":
64 console.log(`Diagram for workflow ${name}:\n${diagram}`)
65 break
66 case "svg":
67 case "png":
68 case "pdf":
69 const tempFilePath = path.join(options.output, `${name}.mermaid`)
70 writeFileSync(tempFilePath, diagram)
71 await runMermaid(
72 tempFilePath,
73 path.join(options.output, `${name}.${options.type}`) as
74 | `${string}.markdown`
75 | `${string}.svg`
76 | `${string}.png`
77 | `${string}.pdf`
78 | `${string}.md`,
79 {
80 quiet: true,
81 }
82 )
83 rmSync(tempFilePath)
84 }
85 }
86
87 console.log(`Generated diagrams for ${workflowDefinitions.size} workflows.`)
88 }