1 import { CustomFieldModel } from "@medusajs/admin-shared"
2 import fs from "fs/promises"
3 import {
4 ExportDefaultDeclaration,
5 File,
6 isIdentifier,
7 isObjectProperty,
8 NodePath,
9 ObjectProperty,
10 parse,
11 ParseResult,
12 traverse,
13 } from "../babel"
14 import { logger } from "../logger"
15 import { crawl, getParserOptions, normalizePath } from "../utils"
16 import { getConfigArgument, getModel } from "./helpers"
17
18 type ParsedCustomFieldLink = {
19 import: string
20 model: CustomFieldModel
21 link: string
22 }
23
24 export async function generateCustomFieldLinks(sources: Set<string>) {
25 const files = await getFilesFromSources(sources)
26 const results = await getCustomFieldLinkResults(files)
27
28 const imports = results.map((result) => result.import)
29 const code = generateCode(results)
30
31 return {
32 imports,
33 code,
34 }
35 }
36
37 async function getFilesFromSources(sources: Set<string>): Promise<string[]> {
38 const files = (
39 await Promise.all(
40 Array.from(sources).map(async (source) =>
41 crawl(`${source}/custom-fields`)
42 )
43 )
44 ).flat()
45 return files
46 }
47
48 function generateCode(results: ParsedCustomFieldLink[]): string {
49 const groupedByModel = new Map<CustomFieldModel, ParsedCustomFieldLink[]>()
50
51 results.forEach((result) => {
52 const model = result.model
53 if (!groupedByModel.has(model)) {
54 groupedByModel.set(model, [])
55 }
56 groupedByModel.get(model)!.push(result)
57 })
58
59 const segments: string[] = []
60
61 groupedByModel.forEach((results, model) => {
62 const links = results.map((result) => result.link).join(",\n")
63
64 segments.push(`
65 ${model}: [
66 ${links}
67 ],
68 `)
69 })
70
71 return `
72 links: {
73 ${segments.join("\n")}
74 }
75 `
76 }
77
78 async function getCustomFieldLinkResults(
79 files: string[]
80 ): Promise<ParsedCustomFieldLink[]> {
81 return (
82 await Promise.all(files.map(async (file, index) => parseFile(file, index)))
83 ).filter(Boolean) as ParsedCustomFieldLink[]
84 }
85
86 async function parseFile(
87 file: string,
88 index: number
89 ): Promise<ParsedCustomFieldLink | null> {
90 const content = await fs.readFile(file, "utf8")
91 let ast: ParseResult<File>
92
93 try {
94 ast = parse(content, getParserOptions(file))
95 } catch (e) {
96 logger.error(`An error occurred while parsing the file`, { file, error: e })
97 return null
98 }
99
100 const import_ = generateImport(file, index)
101
102 let link: string | null = null
103 let model: CustomFieldModel | null = null
104 try {
105 traverse(ast, {
106 ExportDefaultDeclaration(path) {
107 const _model = getModel(path, file)
108
109 if (!_model) {
110 return
111 }
112
113 model = _model
114 link = getLink(path, index, file)
115 },
116 })
117 } catch (err) {
118 logger.error(`An error occurred while traversing the file.`, {
119 file,
120 error: err,
121 })
122 return null
123 }
124
125 if (!link || !model) {
126 return null
127 }
128
129 return {
130 import: import_,
131 model,
132 link,
133 }
134 }
135
136 function generateCustomFieldConfigName(index: number): string {
137 return `CustomFieldConfig${index}`
138 }
139
140 function generateImport(file: string, index: number): string {
141 const path = normalizePath(file)
142 return `import ${generateCustomFieldConfigName(index)} from "${path}"`
143 }
144
145 function getLink(
146 path: NodePath<ExportDefaultDeclaration>,
147 index: number,
148 file: string
149 ): string | null {
150 const configArgument = getConfigArgument(path)
151
152 if (!configArgument) {
153 return null
154 }
155
156 const linkProperty = configArgument.properties.find(
157 (p) => isObjectProperty(p) && isIdentifier(p.key, { name: "link" })
158 ) as ObjectProperty | undefined
159
160 if (!linkProperty) {
161 logger.warn(`'link' is missing.`, { file })
162 return null
163 }
164
165 const import_ = generateCustomFieldConfigName(index)
166
167 return `${import_}.link`
168 }