1 import { InjectionZone, isValidInjectionZone } from "@medusajs/admin-shared"
2 import fs from "fs/promises"
3 import outdent from "outdent"
4 import {
5 File,
6 isArrayExpression,
7 isStringLiteral,
8 isTemplateLiteral,
9 Node,
10 parse,
11 ParseResult,
12 traverse,
13 type ExportNamedDeclaration,
14 type NodePath,
15 type VariableDeclarator,
16 } from "../babel"
17 import { logger } from "../logger"
18 import {
19 generateHash,
20 getConfigObjectProperties,
21 getParserOptions,
22 hasDefaultExport,
23 normalizePath,
24 } from "../utils"
25 import { getWidgetFilesFromSources } from "./helpers"
26
27 type WidgetConfig = {
28 Component: string
29 zone: InjectionZone[]
30 widgetId: string
31 }
32
33 type ParsedWidgetConfig = {
34 import: string
35 widget: WidgetConfig
36 }
37
38 export async function generateWidgets(sources: Set<string>) {
39 const files = await getWidgetFilesFromSources(sources)
40 const results = await getWidgetResults(files)
41
42 const imports = results.map((r) => r.import)
43 const code = generateCode(results)
44
45 return {
46 imports,
47 code,
48 }
49 }
50
51 async function getWidgetResults(
52 files: string[]
53 ): Promise<ParsedWidgetConfig[]> {
54 return (await Promise.all(files.map(parseFile))).filter(
55 (r) => r !== null
56 ) as ParsedWidgetConfig[]
57 }
58
59 function generateCode(results: ParsedWidgetConfig[]): string {
60 return outdent`
61 widgets: [
62 ${results.map((r) => formatWidget(r.widget)).join(",\n")}
63 ]
64 `
65 }
66
67 function formatWidget(widget: WidgetConfig): string {
68 return outdent`
69 {
70 Component: ${widget.Component},
71 zone: [${widget.zone.map((z) => `"${z}"`).join(", ")}],
72 widgetId: "${widget.widgetId}"
73 }
74 `
75 }
76
77 /**
78 * Derives a stable, machine-independent identifier for a widget.
79 *
80 * Prefers an explicit `id` from the widget config. Otherwise falls back to a
81 * `Widget-<short hash>` id, where the hash is derived from the file's path
82 * relative to the admin source root (the segment from `widgets/` onward) so the
83 * id is unaffected by where the project lives on disk or which machine builds
84 * it, and only changes if the file itself is renamed.
85 */
86 function getWidgetId(idOverride: string | null, file: string): string {
87 if (idOverride) {
88 return idOverride
89 }
90
91 const normalized = normalizePath(file)
92 const marker = "/widgets/"
93 const markerIndex = normalized.lastIndexOf(marker)
94 const relative =
95 markerIndex >= 0 ? normalized.slice(markerIndex + 1) : normalized
96
97 return `Widget-${generateHash(relative).slice(0, 4)}`
98 }
99
100 async function parseFile(
101 file: string,
102 index: number
103 ): Promise<ParsedWidgetConfig | null> {
104 const code = await fs.readFile(file, "utf-8")
105 let ast: ParseResult<File>
106
107 try {
108 ast = parse(code, getParserOptions(file))
109 } catch (e) {
110 logger.error(`An error occurred while parsing the file.`, {
111 file,
112 error: e,
113 })
114 return null
115 }
116
117 let fileHasDefaultExport = false
118
119 try {
120 fileHasDefaultExport = await hasDefaultExport(ast)
121 } catch (e) {
122 logger.error(`An error occurred while checking for a default export.`, {
123 file,
124 error: e,
125 })
126 return null
127 }
128
129 if (!fileHasDefaultExport) {
130 return null
131 }
132
133 let zone: InjectionZone[] | null
134
135 try {
136 zone = await getWidgetZone(ast, file)
137 } catch (e) {
138 logger.error(`An error occurred while traversing the file.`, {
139 file,
140 error: e,
141 })
142 return null
143 }
144
145 if (!zone) {
146 logger.warn(`'zone' property is missing from the widget config.`, { file })
147 return null
148 }
149
150 let idOverride: string | null = null
151
152 try {
153 idOverride = getWidgetIdOverride(ast)
154 } catch (e) {
155 logger.error(`An error occurred while reading the widget id.`, {
156 file,
157 error: e,
158 })
159 }
160
161 const import_ = generateImport(file, index)
162 const widget = generateWidget(zone, index, getWidgetId(idOverride, file))
163
164 return {
165 widget,
166 import: import_,
167 }
168 }
169
170 function generateWidgetComponentName(index: number): string {
171 return `WidgetComponent${index}`
172 }
173
174 function generateWidgetConfigName(index: number): string {
175 return `WidgetConfig${index}`
176 }
177
178 function generateImport(file: string, index: number): string {
179 const path = normalizePath(file)
180 return `import ${generateWidgetComponentName(
181 index
182 )}, { config as ${generateWidgetConfigName(index)} } from "${path}"`
183 }
184
185 function generateWidget(
186 zone: InjectionZone[],
187 index: number,
188 widgetId: string
189 ): WidgetConfig {
190 return {
191 Component: generateWidgetComponentName(index),
192 zone: zone,
193 widgetId,
194 }
195 }
196
197 /**
198 * Extracts an explicit string `id` from the widget config, if present. Uses the
199 * shared `getConfigObjectProperties` helper so it works for both bundled
200 * (`VariableDeclarator`) and unbundled (`ExportNamedDeclaration`) files.
201 */
202 function getWidgetIdOverride(ast: ParseResult<File>): string | null {
203 let id: string | null = null
204 let found = false
205
206 const readId = (path: NodePath<VariableDeclarator | ExportNamedDeclaration>) => {
207 if (found) {
208 return
209 }
210 const properties = getConfigObjectProperties(path)
211 if (!properties) {
212 return
213 }
214 const idProperty = properties.find(
215 (p: any) => p.type === "ObjectProperty" && p.key.name === "id"
216 )
217 if (idProperty?.type === "ObjectProperty") {
218 if (idProperty.value.type === "StringLiteral") {
219 id = idProperty.value.value
220 }
221 found = true
222 }
223 }
224
225 traverse(ast, {
226 VariableDeclarator: readId,
227 ExportNamedDeclaration: readId,
228 })
229
230 return id
231 }
232
233 async function getWidgetZone(
234 ast: ParseResult<File>,
235 file: string
236 ): Promise<InjectionZone[] | null> {
237 const zones: string[] = []
238
239 /**
240 * We need to keep track of whether we have found a zone in the file.
241 * This is to avoid processing the same config both using the `ExportNamedDeclaration`
242 * and `VariableDeclarator` paths, which would be the case for the unbundled files.
243 */
244 let zoneFound = false
245
246 traverse(ast, {
247 /**
248 * In case we are processing a bundled file, the `config` will most likely
249 * not be a named export. Instead we look for a `VariableDeclaration` named
250 * `config` and extract the `zone` property from it.
251 */
252 VariableDeclarator(path) {
253 if (zoneFound) {
254 return
255 }
256
257 if (
258 path.node.id.type === "Identifier" &&
259 path.node.id.name === "config" &&
260 path.node.init?.type === "CallExpression"
261 ) {
262 const arg = path.node.init.arguments[0]
263 if (arg?.type === "ObjectExpression") {
264 const zoneProperty = arg.properties.find(
265 (p: any) => p.type === "ObjectProperty" && p.key.name === "zone"
266 )
267 if (zoneProperty?.type === "ObjectProperty") {
268 extractZoneValues(zoneProperty.value, zones, file)
269 zoneFound = true
270 }
271 }
272 }
273 },
274 /**
275 * For unbundled files, the `config` will always be a named export.
276 */
277 ExportNamedDeclaration(path) {
278 if (zoneFound) {
279 return
280 }
281
282 const declaration = path.node.declaration
283 if (
284 declaration?.type === "VariableDeclaration" &&
285 declaration.declarations[0]?.type === "VariableDeclarator" &&
286 declaration.declarations[0].id.type === "Identifier" &&
287 declaration.declarations[0].id.name === "config" &&
288 declaration.declarations[0].init?.type === "CallExpression"
289 ) {
290 const arg = declaration.declarations[0].init.arguments[0]
291 if (arg?.type === "ObjectExpression") {
292 const zoneProperty = arg.properties.find(
293 (p: any) => p.type === "ObjectProperty" && p.key.name === "zone"
294 )
295 if (zoneProperty?.type === "ObjectProperty") {
296 extractZoneValues(zoneProperty.value, zones, file)
297 zoneFound = true
298 }
299 }
300 }
301 },
302 })
303
304 if (!zoneFound) {
305 logger.warn(`'zone' property is missing from the widget config.`, { file })
306 return null
307 }
308
309 const validatedZones = zones.filter(isValidInjectionZone)
310
311 if (validatedZones.length === 0) {
312 logger.warn(`'zone' property is not a valid injection zone.`, {
313 file,
314 })
315 return null
316 }
317
318 return validatedZones
319 }
320
321 function extractZoneValues(value: Node, zones: string[], file: string) {
322 if (isTemplateLiteral(value)) {
323 logger.warn(
324 `'zone' property cannot be a template literal (e.g. \`product.details.after\`).`,
325 { file }
326 )
327 return
328 }
329
330 if (isStringLiteral(value)) {
331 zones.push(value.value)
332 } else if (isArrayExpression(value)) {
333 const values = value.elements
334 .filter((e) => isStringLiteral(e))
335 .map((e) => e.value)
336 zones.push(...values)
337 } else {
338 logger.warn(`'zone' property is not a string or array.`, { file })
339 return
340 }
341 }