1 import type { AdminOptions, ConfigModule, Logger } from "@medusajs/types"
2 import { FileSystem, getConfigFile, getResolvedPlugins } from "@medusajs/utils"
3 import chokidar from "chokidar"
4 import { access, constants, copyFile, mkdir, rm } from "fs/promises"
5 import path from "path"
6 import type tsStatic from "typescript"
7 import { isFileIgnored } from "./compiler-utils"
8
9 /**
10 * The compiler exposes the opinionated APIs for compiling Medusa
11 * applications and plugins. You can perform the following
12 * actions.
13 *
14 * - loadTSConfigFile: Load and parse the TypeScript config file. All errors
15 * will be reported using the logger.
16 *
17 * - buildAppBackend: Compile the Medusa application backend source code to the
18 * ".medusa/server" directory. The admin source and integration-tests are
19 * skipped.
20 *
21 * - buildAppFrontend: Compile the admin extensions using the "@medusjs/admin-bundler"
22 * package. Admin can be compiled for self hosting (aka adminOnly), or can be compiled
23 * to be bundled with the backend output.
24 */
25 export class Compiler {
26 #logger: Logger
27 #projectRoot: string
28 #tsConfigPath: string
29 #pluginsDistFolder: string
30 #backendIgnoreFiles: string[]
31 #adminOnlyDistFolder: string
32 #tsCompiler?: typeof tsStatic
33
34 constructor(projectRoot: string, logger: Logger) {
35 this.#projectRoot = projectRoot
36 this.#logger = logger
37 this.#tsConfigPath = path.join(this.#projectRoot, "tsconfig.json")
38 this.#adminOnlyDistFolder = path.join(this.#projectRoot, ".medusa/admin")
39 this.#pluginsDistFolder = path.join(this.#projectRoot, ".medusa/server")
40 this.#backendIgnoreFiles = [
41 "integration-tests",
42 "test",
43 "unit-tests",
44 "src/admin",
45 ]
46 }
47
48 /**
49 * Util to track duration using hrtime
50 */
51 #trackDuration() {
52 const startTime = process.hrtime()
53 return {
54 getSeconds() {
55 const duration = process.hrtime(startTime)
56 return (duration[0] + duration[1] / 1e9).toFixed(2)
57 },
58 }
59 }
60
61 /**
62 * Returns the dist folder from the tsconfig.outDir property
63 * or uses the ".medusa/server" folder
64 */
65 #computeDist(tsConfig: { options: { outDir?: string } }): string {
66 const distFolder = tsConfig.options.outDir ?? ".medusa/server"
67 return path.isAbsolute(distFolder)
68 ? distFolder
69 : path.join(this.#projectRoot, distFolder)
70 }
71
72 /**
73 * Imports and stores a reference to the TypeScript compiler.
74 * We dynamically import "typescript", since its is a dev
75 * only dependency
76 */
77 async #loadTSCompiler() {
78 if (!this.#tsCompiler) {
79 this.#tsCompiler = await import("typescript")
80 }
81 return this.#tsCompiler
82 }
83
84 /**
85 * Copies the file to the destination without throwing any
86 * errors if the source file is missing
87 */
88 async #copy(source: string, destination: string) {
89 let sourceExists = false
90 try {
91 await access(source, constants.F_OK)
92 sourceExists = true
93 } catch (error) {
94 if (error.code !== "ENOENT") {
95 throw error
96 }
97 }
98
99 if (sourceExists) {
100 await copyFile(path.join(source), path.join(destination))
101 }
102 }
103
104 /**
105 * Copies package manager files from the project root
106 * to the specified dist folder
107 */
108 async #copyPkgManagerFiles(dist: string) {
109 /**
110 * Copying package manager files
111 */
112 await this.#copy(
113 path.join(this.#projectRoot, "package.json"),
114 path.join(dist, "package.json")
115 )
116 await this.#copy(
117 path.join(this.#projectRoot, "yarn.lock"),
118 path.join(dist, "yarn.lock")
119 )
120 await this.#copy(
121 path.join(this.#projectRoot, "pnpm.lock"),
122 path.join(dist, "pnpm.lock")
123 )
124 await this.#copy(
125 path.join(this.#projectRoot, "package-lock.json"),
126 path.join(dist, "package-lock.json")
127 )
128 }
129
130 /**
131 * Removes the directory and its children recursively and
132 * ignores any errors
133 */
134 async #clean(path: string) {
135 await rm(path, { recursive: true }).catch(() => {})
136 }
137
138 /**
139 * Returns a boolean indicating if a file extension belongs
140 * to a JavaScript or TypeScript file
141 */
142 #isScriptFile(filePath: string) {
143 if (filePath.endsWith(".ts") && !filePath.endsWith(".d.ts")) {
144 return true
145 }
146 return filePath.endsWith(".js")
147 }
148
149 /**
150 * Loads the medusa config file and prints the error to
151 * the console (in case of any errors). Otherwise, the
152 * file path and the parsed config is returned
153 */
154 async #loadMedusaConfig() {
155 const { configModule, configFilePath, error } =
156 await getConfigFile<ConfigModule>(this.#projectRoot, "medusa-config")
157 if (error) {
158 this.#logger.error(`Failed to load medusa-config.(js|ts) file`)
159 this.#logger.error(error)
160 return
161 }
162
163 return { configFilePath, configModule }
164 }
165
166 /**
167 * Prints typescript diagnostic messages
168 */
169 #printDiagnostics(ts: typeof tsStatic, diagnostics: tsStatic.Diagnostic[]) {
170 if (diagnostics.length) {
171 console.error(
172 ts.formatDiagnosticsWithColorAndContext(
173 diagnostics,
174 ts.createCompilerHost({})
175 )
176 )
177 }
178 }
179
180 /**
181 * Given a tsconfig file, this method will write the compiled
182 * output to the specified destination
183 */
184 async #emitBuildOutput(
185 tsConfig: tsStatic.ParsedCommandLine,
186 chunksToIgnore: string[],
187 dist: string
188 ): Promise<{
189 emitResult: tsStatic.EmitResult
190 diagnostics: tsStatic.Diagnostic[]
191 }> {
192 const ts = await this.#loadTSCompiler()
193 const filesToCompile = tsConfig.fileNames.filter((fileName) => {
194 const relativeFileName = path.relative(this.#projectRoot, fileName)
195 return !isFileIgnored(relativeFileName, chunksToIgnore)
196 })
197
198 /**
199 * Create emit program to compile and emit output
200 */
201 const program = ts.createProgram(filesToCompile, {
202 ...tsConfig.options,
203 ...{
204 outDir: dist,
205 inlineSourceMap: !tsConfig.options.sourceMap,
206 },
207 })
208
209 const emitResult = program.emit()
210 const diagnostics = ts
211 .getPreEmitDiagnostics(program)
212 .concat(emitResult.diagnostics)
213
214 /**
215 * Log errors (if any)
216 */
217 this.#printDiagnostics(ts, diagnostics)
218
219 return { emitResult, diagnostics }
220 }
221
222 /**
223 * Loads and parses the TypeScript config file. In case of an error, the errors
224 * will be logged using the logger and undefined it returned
225 */
226 async loadTSConfigFile(): Promise<tsStatic.ParsedCommandLine | undefined> {
227 const ts = await this.#loadTSCompiler()
228 let tsConfigErrors: tsStatic.Diagnostic[] = []
229
230 const tsConfig = ts.getParsedCommandLineOfConfigFile(
231 this.#tsConfigPath,
232 {
233 inlineSourceMap: true,
234 excludes: [],
235 },
236 {
237 ...ts.sys,
238 useCaseSensitiveFileNames: true,
239 getCurrentDirectory: () => this.#projectRoot,
240 onUnRecoverableConfigFileDiagnostic: (error) =>
241 (tsConfigErrors = [error]),
242 }
243 )
244
245 /**
246 * Push errors from the tsConfig parsed output to the
247 * tsConfigErrors array.
248 */
249 if (tsConfig?.errors.length) {
250 tsConfigErrors.push(...tsConfig.errors)
251 }
252
253 /**
254 * Display all config errors using the diagnostics reporter
255 */
256 this.#printDiagnostics(ts, tsConfigErrors)
257
258 /**
259 * Return undefined when there are errors in parsing the config
260 * file
261 */
262 if (tsConfigErrors.length) {
263 return
264 }
265
266 return tsConfig
267 }
268
269 /**
270 * Builds the application backend source code using
271 * TypeScript's official compiler. Also performs
272 * type-checking
273 */
274 async buildAppBackend(
275 tsConfig: tsStatic.ParsedCommandLine
276 ): Promise<boolean> {
277 const tracker = this.#trackDuration()
278 const dist = this.#computeDist(tsConfig)
279 this.#logger.info("Compiling backend source...")
280
281 /**
282 * Step 1: Cleanup existing build output
283 */
284 this.#logger.info(
285 `Removing existing "${path.relative(this.#projectRoot, dist)}" folder`
286 )
287 await this.#clean(dist)
288
289 /**
290 * Create first the target directory now that everything is clean
291 */
292 await mkdir(dist, { recursive: true })
293
294 /**
295 * Step 2: Compile TypeScript source code
296 */
297 const { emitResult, diagnostics } = await this.#emitBuildOutput(
298 tsConfig,
299 this.#backendIgnoreFiles,
300 dist
301 )
302
303 /**
304 * Exit early if no output is written to the disk
305 */
306 if (emitResult.emitSkipped) {
307 this.#logger.warn("Backend build completed without emitting any output")
308 return false
309 }
310
311 /**
312 * Step 3: Copy package manager files to the output folder
313 */
314 await this.#copyPkgManagerFiles(dist)
315
316 /**
317 * Notify about the state of build
318 */
319 if (diagnostics.length) {
320 this.#logger.warn(
321 `Backend build completed with errors (${tracker.getSeconds()}s)`
322 )
323 return false
324 }
325
326 this.#logger.info(
327 `Backend build completed successfully (${tracker.getSeconds()}s)`
328 )
329 return true
330 }
331
332 /**
333 * Builds the frontend source code of a Medusa application
334 * using the "@medusajs/admin-bundler" package.
335 */
336 async buildAppFrontend(
337 adminOnly: boolean,
338 tsConfig: tsStatic.ParsedCommandLine,
339 adminBundler: {
340 build: (
341 options: AdminOptions & {
342 sources: string[]
343 plugins: string[]
344 outDir: string
345 }
346 ) => Promise<void>
347 }
348 ): Promise<boolean> {
349 const tracker = this.#trackDuration()
350
351 /**
352 * Step 1: Load the medusa config file to read
353 * admin options
354 */
355 const configFile = await this.#loadMedusaConfig()
356 if (!configFile) {
357 return false
358 }
359
360 /**
361 * Return early when admin is disabled and we are trying to
362 * create a bundled build for the admin.
363 */
364 if (configFile.configModule.admin.disable && !adminOnly) {
365 this.#logger.info(
366 "Skipping admin build, since its disabled inside the medusa-config file"
367 )
368 return true
369 }
370
371 /**
372 * Warn when we are creating an admin only build, but forgot to disable
373 * the admin inside the config file
374 */
375 if (!configFile.configModule.admin.disable && adminOnly) {
376 this.#logger.warn(
377 `You are building using the flag --admin-only but the admin is enabled in your medusa-config, If you intend to host the dashboard separately you should disable the admin in your medusa config`
378 )
379 }
380
381 const plugins = await getResolvedPlugins(
382 this.#projectRoot,
383 configFile.configModule,
384 true
385 )
386
387 const adminSources = plugins
388 .map((plugin) =>
389 plugin.admin?.type === "local" ? plugin.admin.resolve : undefined
390 )
391 .filter(Boolean) as string[]
392
393 const adminPlugins = plugins
394 .map((plugin) =>
395 plugin.admin?.type === "package" ? plugin.admin.resolve : undefined
396 )
397 .filter(Boolean) as string[]
398
399 try {
400 this.#logger.info("Compiling frontend source...")
401 await adminBundler.build({
402 disable: false,
403 sources: adminSources,
404 plugins: adminPlugins,
405 ...configFile.configModule.admin,
406 outDir: adminOnly
407 ? this.#adminOnlyDistFolder
408 : path.join(this.#computeDist(tsConfig), "./public/admin"),
409 })
410
411 this.#logger.info(
412 `Frontend build completed successfully (${tracker.getSeconds()}s)`
413 )
414 return true
415 } catch (error) {
416 this.#logger.error("Unable to compile frontend source")
417 this.#logger.error(error)
418 return false
419 }
420 }
421
422 /**
423 * Compiles the plugin source code to JavaScript using the
424 * TypeScript's official compiler
425 */
426 async buildPluginBackend(tsConfig: tsStatic.ParsedCommandLine) {
427 const tracker = this.#trackDuration()
428 const dist = this.#pluginsDistFolder
429 this.#logger.info("Compiling plugin source...")
430
431 /**
432 * Step 1: Cleanup existing build output
433 */
434 this.#logger.info(
435 `Removing existing "${path.relative(this.#projectRoot, dist)}" folder`
436 )
437 await this.#clean(dist)
438
439 /**
440 * Step 2: Compile TypeScript source code
441 */
442 const { emitResult, diagnostics } = await this.#emitBuildOutput(
443 tsConfig,
444 this.#backendIgnoreFiles,
445 dist
446 )
447
448 /**
449 * Exit early if no output is written to the disk
450 */
451 if (emitResult.emitSkipped) {
452 this.#logger.warn("Plugin build completed without emitting any output")
453 return false
454 }
455
456 /**
457 * Notify about the state of build
458 */
459 if (diagnostics.length) {
460 this.#logger.warn(
461 `Plugin build completed with errors (${tracker.getSeconds()}s)`
462 )
463 return false
464 }
465
466 this.#logger.info(
467 `Plugin build completed successfully (${tracker.getSeconds()}s)`
468 )
469 return true
470 }
471
472 /**
473 * Compiles the backend source code of a plugin project in watch
474 * mode. Type-checking is disabled to keep compilation fast.
475 *
476 * The "onFileChange" argument can be used to get notified when
477 * a file has changed.
478 */
479 async developPluginBackend(
480 transformer: (filePath: string) => Promise<string>,
481 onFileChange?: (
482 filePath: string,
483 action: "add" | "change" | "unlink"
484 ) => void
485 ) {
486 const fs = new FileSystem(this.#pluginsDistFolder)
487 await fs.createJson("medusa-plugin-options.json", {
488 srcDir: path.join(this.#projectRoot, "src"),
489 })
490
491 const watcher = chokidar.watch(["."], {
492 ignoreInitial: true,
493 cwd: this.#projectRoot,
494 ignored: [
495 /(^|[\\/\\])\../,
496 "node_modules",
497 "dist",
498 "static",
499 "private",
500 ".medusa",
501 ...this.#backendIgnoreFiles,
502 ],
503 })
504
505 watcher.on("add", async (file) => {
506 if (!this.#isScriptFile(file)) {
507 return
508 }
509 const relativePath = path.relative(this.#projectRoot, file)
510 const outputPath = relativePath.replace(/\.ts$/, ".js")
511
512 this.#logger.info(`${relativePath} updated: Republishing changes`)
513 await fs.create(outputPath, await transformer(file))
514
515 onFileChange?.(file, "add")
516 })
517 watcher.on("change", async (file) => {
518 if (!this.#isScriptFile(file)) {
519 return
520 }
521 const relativePath = path.relative(this.#projectRoot, file)
522 const outputPath = relativePath.replace(/\.ts$/, ".js")
523
524 this.#logger.info(`${relativePath} updated: Republishing changes`)
525 await fs.create(outputPath, await transformer(file))
526
527 onFileChange?.(file, "change")
528 })
529 watcher.on("unlink", async (file) => {
530 if (!this.#isScriptFile(file)) {
531 return
532 }
533 const relativePath = path.relative(this.#projectRoot, file)
534 const outputPath = relativePath.replace(/\.ts$/, ".js")
535
536 this.#logger.info(`${relativePath} removed: Republishing changes`)
537 await fs.remove(outputPath)
538 onFileChange?.(file, "unlink")
539 })
540
541 watcher.on("ready", () => {
542 this.#logger.info("watching for file changes")
543 })
544 }
545
546 async buildPluginAdminExtensions(bundler: {
547 plugin: (options: { root: string; outDir: string }) => Promise<void>
548 }) {
549 const tracker = this.#trackDuration()
550 this.#logger.info("Compiling plugin admin extensions...")
551
552 try {
553 await bundler.plugin({
554 root: this.#projectRoot,
555 outDir: this.#pluginsDistFolder,
556 })
557 this.#logger.info(
558 `Plugin admin extensions build completed successfully (${tracker.getSeconds()}s)`
559 )
560 return true
561 } catch (error) {
562 this.#logger.error(`Plugin admin extensions build failed`, error)
563 return false
564 }
565 }
566 }