1 import ts from "typescript"
2 import DefaultKindGenerator, { GetDocBlockOptions } from "./default.js"
3 import { glob } from "glob"
4 import getMonorepoRoot from "../../utils/get-monorepo-root.js"
5 import { readFile } from "fs/promises"
6 import { MedusaEvent } from "types"
7
8 class EventsKindGenerator extends DefaultKindGenerator<ts.VariableDeclaration> {
9 protected allowedKinds: ts.SyntaxKind[] = [ts.SyntaxKind.VariableDeclaration]
10 public name = "events"
11 protected workflows: Record<string, string> = {}
12 protected workflowsEmittingEvents: Record<string, string> = {}
13
14 isAllowed(node: ts.Node): node is ts.VariableDeclaration {
15 if (
16 !super.isAllowed(node) ||
17 !node.initializer ||
18 !ts.isAsExpression(node.initializer) ||
19 !ts.isObjectLiteralExpression(node.initializer.expression)
20 ) {
21 return false
22 }
23
24 return node.initializer.expression.properties.length > 0
25 }
26
27 async getDocBlock(
28 node: ts.VariableDeclaration | ts.Node,
29 options?: GetDocBlockOptions
30 ): Promise<string> {
31 if (!this.isAllowed(node)) {
32 return await super.getDocBlock(node, options)
33 }
34
35 const properties = (
36 (node.initializer as ts.AsExpression)
37 .expression as ts.ObjectLiteralExpression
38 ).properties
39
40 const events: MedusaEvent[] = properties
41 .filter((property) => ts.isPropertyAssignment(property))
42 .map((property) => {
43 const propertyAssignment = property as ts.PropertyAssignment
44 const eventVariableName = node.name.getText()
45 const eventPropertyName = propertyAssignment.name.getText()
46 const workflows = this.getWorkflowsUsingEvent({
47 eventVariableName,
48 eventPropertyName,
49 })
50 const isWorkflowEvent = property.getSourceFile().fileName.includes("core-flows")
51 if (isWorkflowEvent && !workflows.length) {
52 return null
53 }
54
55 const commentsAndTags = ts.getJSDocCommentsAndTags(propertyAssignment)
56 let payloadTag: ts.JSDocTag | undefined
57 let sinceTag: ts.JSDocTag | undefined
58 let deprecatedTag: ts.JSDocTag | undefined
59 let description: string | undefined
60 commentsAndTags.forEach((comment) => {
61 if (!("tags" in comment)) {
62 return
63 }
64
65 if (typeof comment.comment === "string") {
66 description = comment.comment
67 }
68
69 comment.tags?.forEach((tag) => {
70 if (tag.tagName.getText() === "eventPayload") {
71 payloadTag = tag
72 }
73
74 if (tag.tagName.getText() === "since") {
75 sinceTag = tag
76 }
77
78 if (tag.tagName.getText() === "deprecated") {
79 deprecatedTag = tag
80 }
81 })
82 })
83
84 return {
85 name: propertyAssignment.initializer.getText().replaceAll(`"`, ""),
86 parentName: eventVariableName,
87 propertyName: eventPropertyName,
88 payload: (payloadTag?.comment as string) ?? "",
89 description,
90 workflows,
91 since: sinceTag?.comment as string,
92 deprecated: deprecatedTag !== undefined,
93 deprecated_message: deprecatedTag?.comment as string,
94 }
95 })
96 .filter((event) => event !== null)
97
98 return JSON.stringify(events)
99 }
100
101 getWorkflowsUsingEvent({
102 eventVariableName,
103 eventPropertyName,
104 }: {
105 eventVariableName: string
106 eventPropertyName: string
107 }): string[] {
108 const eventName = `${eventVariableName}.${eventPropertyName}`
109
110 const workflows = this.findWorkflowsUsingEvent(eventName)
111 return workflows
112 }
113
114 async populateWorkflows() {
115 if (Object.keys(this.workflows).length > 0) {
116 return
117 }
118
119 const files = await glob(
120 `${getMonorepoRoot()}/packages/core/core-flows/src/**/workflows/**/*.ts`
121 )
122
123 for (const file of files) {
124 const workflowFile = await readFile(file, "utf-8")
125 const workflowName = this.getWorkflowNameFromWorkflowFile(workflowFile)
126 if (!workflowName) {
127 continue
128 }
129
130 this.workflows[workflowName] = workflowFile
131 // remove comments in case the emitEventStep is commented out
132 const workflowWithoutComments = workflowFile.replace(
133 /\/\*[\s\S]*?\*\/|\/\/.*/g,
134 ""
135 )
136 // the emitEventStep should be mentioned at least twice in the workflow
137 // including the import statement
138 const emitEventStepCount = (
139 workflowWithoutComments.match(/emitEventStep/g) || []
140 ).length
141 if (emitEventStepCount >= 2) {
142 this.workflowsEmittingEvents[workflowName] = workflowWithoutComments
143 }
144 }
145 }
146
147 getWorkflowNameFromWorkflowFile(workflowFile: string) {
148 const workflowNameMatch = workflowFile.match(
149 /export const\s+(\w+)\s*=\s*createWorkflow\(/
150 )
151 return workflowNameMatch ? workflowNameMatch[1] : null
152 }
153
154 findWorkflowsUsingEvent(eventName: string) {
155 const workflows = Object.keys(this.workflowsEmittingEvents).filter(
156 (workflowName) =>
157 this.workflowsEmittingEvents[workflowName].includes(eventName)
158 )
159
160 // find workflows using the extracted workflows
161 let newWorkflows: string[] = [...workflows]
162 while (newWorkflows.length > 0) {
163 // loop over the workflows and find new workflows that use the extracted workflows
164 const foundWorkflows: string[] = []
165 for (const workflowName of newWorkflows) {
166 foundWorkflows.push(
167 ...Object.keys(this.workflows).filter(
168 (workflowKey) =>
169 workflowKey !== workflowName &&
170 this.workflows[workflowKey].match(
171 new RegExp(`${workflowName}[\n\\s]*\\.run`)
172 )
173 )
174 )
175 }
176
177 workflows.push(...foundWorkflows)
178 newWorkflows = foundWorkflows
179 }
180
181 return workflows
182 }
183 }
184
185 export default EventsKindGenerator