1 import {
2 isValidCustomFieldDisplayPath,
3 isValidCustomFieldDisplayZone,
4 type CustomFieldContainerZone,
5 type CustomFieldModel,
6 } from "@medusajs/admin-shared"
7 import fs from "fs/promises"
8 import {
9 ExportDefaultDeclaration,
10 File,
11 isArrayExpression,
12 isIdentifier,
13 isObjectExpression,
14 isObjectProperty,
15 isStringLiteral,
16 NodePath,
17 ObjectProperty,
18 parse,
19 ParseResult,
20 traverse,
21 } from "../babel"
22 import { logger } from "../logger"
23 import { crawl, getParserOptions, normalizePath } from "../utils"
24 import { getConfigArgument, getModel, validateLink } from "./helpers"
25
26 type CustomFieldDisplay = {
27 zone: CustomFieldContainerZone
28 Component: string
29 }
30
31 type ParsedCustomFieldDisplayConfig = {
32 import: string
33 model: CustomFieldModel
34 displays: CustomFieldDisplay[] | null
35 }
36
37 export async function generateCustomFieldDisplays(sources: Set<string>) {
38 const files = await getFilesFromSources(sources)
39 const results = await getCustomFieldDisplayResults(files)
40
41 const imports = results.map((result) => result.import).flat()
42 const code = generateDisplayCode(results)
43
44 return {
45 imports,
46 code,
47 }
48 }
49
50 async function getFilesFromSources(sources: Set<string>): Promise<string[]> {
51 const files = (
52 await Promise.all(
53 Array.from(sources).map(async (source) =>
54 crawl(`${source}/custom-fields`)
55 )
56 )
57 ).flat()
58 return files
59 }
60
61 function generateDisplayCode(
62 results: ParsedCustomFieldDisplayConfig[]
63 ): string {
64 const groupedByModel = new Map<
65 CustomFieldModel,
66 ParsedCustomFieldDisplayConfig[]
67 >()
68
69 results.forEach((result) => {
70 const model = result.model
71 if (!groupedByModel.has(model)) {
72 groupedByModel.set(model, [])
73 }
74 groupedByModel.get(model)!.push(result)
75 })
76
77 const segments: string[] = []
78
79 groupedByModel.forEach((results, model) => {
80 const displays = results
81 .map((result) => formatDisplays(result.displays))
82 .filter((display) => display !== "")
83 .join(",\n")
84
85 segments.push(`
86 ${model}: [
87 ${displays}
88 ],
89 `)
90 })
91
92 return `
93 displays: {
94 ${segments.join("\n")}
95 }
96 `
97 }
98
99 function formatDisplays(displays: CustomFieldDisplay[] | null): string {
100 if (!displays || displays.length === 0) {
101 return ""
102 }
103
104 return displays
105 .map(
106 (display) => `
107 {
108 zone: "${display.zone}",
109 Component: ${display.Component},
110 }
111 `
112 )
113 .join(",\n")
114 }
115
116 async function getCustomFieldDisplayResults(
117 files: string[]
118 ): Promise<ParsedCustomFieldDisplayConfig[]> {
119 return (
120 await Promise.all(
121 files.map(async (file, index) => parseDisplayFile(file, index))
122 )
123 ).filter(Boolean) as ParsedCustomFieldDisplayConfig[]
124 }
125
126 async function parseDisplayFile(
127 file: string,
128 index: number
129 ): Promise<ParsedCustomFieldDisplayConfig | null> {
130 const content = await fs.readFile(file, "utf8")
131 let ast: ParseResult<File>
132
133 try {
134 ast = parse(content, getParserOptions(file))
135 } catch (e) {
136 logger.error(`An error occurred while parsing the file`, { file, error: e })
137 return null
138 }
139
140 const import_ = generateImport(file, index)
141
142 let displays: CustomFieldDisplay[] | null = null
143 let model: CustomFieldModel | null = null
144 let hasLink = false
145 try {
146 traverse(ast, {
147 ExportDefaultDeclaration(path) {
148 const _model = getModel(path, file)
149
150 if (!_model) {
151 return
152 }
153
154 model = _model
155 displays = getDisplays(path, model, index, file)
156 hasLink = validateLink(path, file)
157 },
158 })
159 } catch (err) {
160 logger.error(`An error occurred while traversing the file.`, {
161 file,
162 error: err,
163 })
164 return null
165 }
166
167 if (!model) {
168 logger.warn(`'model' property is missing.`, { file })
169 return null
170 }
171
172 if (!hasLink) {
173 logger.warn(`'link' property is missing.`, { file })
174 return null
175 }
176
177 return {
178 import: import_,
179 model,
180 displays,
181 }
182 }
183
184 function getDisplays(
185 path: NodePath<ExportDefaultDeclaration>,
186 model: CustomFieldModel,
187 index: number,
188 file: string
189 ): CustomFieldDisplay[] | null {
190 const configArgument = getConfigArgument(path)
191
192 if (!configArgument) {
193 return null
194 }
195
196 const displayProperty = configArgument.properties.find(
197 (p) => isObjectProperty(p) && isIdentifier(p.key, { name: "displays" })
198 ) as ObjectProperty | undefined
199
200 if (!displayProperty) {
201 return null
202 }
203
204 if (!isArrayExpression(displayProperty.value)) {
205 logger.warn(
206 `'displays' is not an array. The 'displays' property must be an array of objects.`,
207 { file }
208 )
209 return null
210 }
211
212 const displays: CustomFieldDisplay[] = []
213
214 displayProperty.value.elements.forEach((element, j) => {
215 if (!isObjectExpression(element)) {
216 return
217 }
218
219 const zoneProperty = element.properties.find(
220 (p) => isObjectProperty(p) && isIdentifier(p.key, { name: "zone" })
221 ) as ObjectProperty | undefined
222
223 if (!zoneProperty) {
224 logger.warn(
225 `'zone' property is missing at the ${j} index of the 'displays' property.`,
226 { file }
227 )
228 return
229 }
230
231 if (!isStringLiteral(zoneProperty.value)) {
232 logger.warn(
233 `'zone' property at index ${j} in the 'displays' property is not a string literal. 'zone' must be a string literal, e.g. 'general' or 'attributes'.`,
234 { file }
235 )
236 return
237 }
238
239 const zone = zoneProperty.value.value
240 const fullPath = getDisplayEntryPath(model, zone)
241
242 if (
243 !isValidCustomFieldDisplayZone(zone) ||
244 !isValidCustomFieldDisplayPath(fullPath)
245 ) {
246 logger.warn(
247 `'zone' is invalid at index ${j} in the 'displays' property. Received: ${zone}.`,
248 { file }
249 )
250 return
251 }
252
253 const componentProperty = element.properties.find(
254 (p) => isObjectProperty(p) && isIdentifier(p.key, { name: "component" })
255 ) as ObjectProperty | undefined
256
257 if (!componentProperty) {
258 logger.warn(
259 `'component' property is missing at index ${j} in the 'displays' property.`,
260 { file }
261 )
262 return
263 }
264
265 displays.push({
266 zone: zone,
267 Component: getDisplayComponent(index, j),
268 })
269 })
270
271 return displays.length > 0 ? displays : null
272 }
273
274 function getDisplayEntryPath(model: CustomFieldModel, zone: string): string {
275 return `${model}.${zone}.$display`
276 }
277
278 function getDisplayComponent(
279 fileIndex: number,
280 displayEntryIndex: number
281 ): string {
282 const import_ = generateCustomFieldConfigName(fileIndex)
283 return `${import_}.displays[${displayEntryIndex}].component`
284 }
285
286 function generateCustomFieldConfigName(index: number): string {
287 return `CustomFieldConfig${index}`
288 }
289
290 function generateImport(file: string, index: number): string {
291 const path = normalizePath(file)
292 return `import ${generateCustomFieldConfigName(index)} from "${path}"`
293 }