1 import { track } from "@medusajs/telemetry"
2 import boxen from "boxen"
3 import chalk from "chalk"
4 import fs from "fs"
5 import { emojify } from "node-emoji"
6 import open from "open"
7 import { EOL } from "os"
8 import slugifyType from "slugify"
9 import waitOn from "wait-on"
10 import { promptClaudeCodePlugin } from "../claude-code-plugin.js"
11 import { runCloneRepo } from "../clone-repo.js"
12 import { isAbortError } from "../create-abort-controller.js"
13 import { getDbClientAndCredentials, runCreateDb } from "../create-db.js"
14 import { displayFactBox } from "../facts.js"
15 import logMessage from "../log-message.js"
16 import {
17 askForNextjsStarter,
18 installNextjsStarter,
19 startNextjsStarter,
20 } from "../nextjs-utils.js"
21 import prepareProject from "../prepare-project.js"
22 import startMedusa from "../start-medusa.js"
23 import {
24 getBackendDirectory,
25 getStorefrontDirectory,
26 } from "../project-paths.js"
27 import {
28 BaseProjectCreator,
29 ProjectCreator,
30 ProjectOptions,
31 } from "./creator.js"
32 import terminalLink from "terminal-link"
33
34 const slugify = slugifyType.default
35
36 // Medusa Project Creator
37 export class MedusaProjectCreator
38 extends BaseProjectCreator
39 implements ProjectCreator
40 {
41 private client: any = null
42 private dbConnectionString: string = ""
43 private isDbInitialized: boolean = false
44 private nextjsDirectory: string = ""
45 private inviteToken?: string
46
47 constructor(projectName: string, options: ProjectOptions, args: string[]) {
48 super(projectName, options, args)
49 this.setupProcessManager()
50 }
51
52 async create({ verbose }: { verbose?: boolean }): Promise<void> {
53 track("CREATE_CLI_CMA")
54
55 try {
56 await this.initializeProject()
57 await this.setupProject()
58 await this.startServices()
59 } catch (e: any) {
60 this.handleError(e, verbose)
61 }
62 }
63
64 private async initializeProject(): Promise<void> {
65 const installNextjs =
66 this.options.withNextjsStarter || (await askForNextjsStarter())
67 await promptClaudeCodePlugin()
68
69 if (!this.options.skipDb) {
70 await this.setupDatabase()
71 }
72
73 logMessage({
74 message: `${emojify(
75 ":rocket:"
76 )} Starting project setup, this may take a few minutes.`,
77 })
78
79 this.spinner.start()
80
81 this.factBoxOptions.interval = displayFactBox({
82 ...this.factBoxOptions,
83 title: "Setting up project...",
84 })
85
86 await runCloneRepo({
87 projectName: this.projectPath,
88 repoUrl: this.options.repoUrl ?? "",
89 abortController: this.abortController,
90 spinner: this.spinner,
91 verbose: this.options.verbose,
92 })
93
94 this.factBoxOptions.interval = displayFactBox({
95 ...this.factBoxOptions,
96 message: "Created project directory",
97 })
98
99 const storefrontDirectory = getStorefrontDirectory(this.projectPath)
100
101 if (!installNextjs) {
102 if (fs.existsSync(storefrontDirectory)) {
103 fs.rmSync(storefrontDirectory, { recursive: true, force: true })
104 }
105 } else {
106 this.nextjsDirectory = storefrontDirectory
107 await installNextjsStarter({
108 storefrontDirectory,
109 abortController: this.abortController,
110 factBoxOptions: this.factBoxOptions,
111 verbose: this.options.verbose,
112 packageManager: this.packageManager,
113 version: this.options.version,
114 })
115 }
116 }
117
118 private async setupDatabase(): Promise<void> {
119 let dbName = `medusa-${slugify(this.projectName)}`
120 const { client, dbConnectionString, ...rest } =
121 await getDbClientAndCredentials({
122 dbName,
123 dbUrl: this.options.dbUrl,
124 verbose: this.options.verbose,
125 })
126
127 this.client = client
128 this.dbConnectionString = dbConnectionString
129 this.isDbInitialized = true
130 dbName = rest.dbName || dbName
131
132 if (!this.options.dbUrl) {
133 this.factBoxOptions.interval = displayFactBox({
134 ...this.factBoxOptions,
135 message: "Creating database...",
136 })
137
138 this.client = await runCreateDb({
139 client: this.client,
140 dbName,
141 spinner: this.spinner,
142 })
143
144 this.factBoxOptions.interval = displayFactBox({
145 ...this.factBoxOptions,
146 message: `Database ${dbName} created`,
147 })
148 }
149 }
150
151 private async setupProject(): Promise<void> {
152 try {
153 this.inviteToken = await prepareProject({
154 isPlugin: false,
155 projectName: this.projectName,
156 directory: this.projectPath,
157 dbConnectionString: this.dbConnectionString,
158 seed: this.options.seed,
159 spinner: this.spinner,
160 processManager: this.processManager,
161 abortController: this.abortController,
162 skipDb: this.options.skipDb,
163 migrations: this.options.migrations,
164 onboardingType: this.nextjsDirectory ? "nextjs" : "default",
165 nextjsDirectory: this.nextjsDirectory,
166 client: this.client,
167 verbose: this.options.verbose,
168 packageManager: this.packageManager,
169 version: this.options.version,
170 })
171 } finally {
172 await this.client?.end()
173 }
174
175 this.spinner.succeed(chalk.green("Project Prepared"))
176 }
177
178 private async startServices(): Promise<void> {
179 if (this.options.skipDb || !this.options.browser) {
180 this.showSuccessMessage()
181 process.exit()
182 }
183
184 logMessage({
185 message: "Starting Medusa...",
186 })
187
188 startMedusa({
189 directory: getBackendDirectory(this.projectPath),
190 abortController: this.abortController,
191 packageManager: this.packageManager,
192 })
193
194 if (this.nextjsDirectory) {
195 startNextjsStarter({
196 directory: this.nextjsDirectory,
197 abortController: this.abortController,
198 verbose: this.options.verbose,
199 packageManager: this.packageManager,
200 })
201 }
202
203 this.isProjectCreated = true
204
205 await this.openBrowser()
206 }
207
208 private async openBrowser(): Promise<void> {
209 await waitOn({
210 resources: ["http://localhost:9000/health"],
211 }).then(async () =>
212 open(
213 this.inviteToken
214 ? `http://localhost:9000/app/invite?token=${this.inviteToken}&first_run=true`
215 : "http://localhost:9000/app"
216 )
217 )
218 }
219
220 private handleError(e: Error, verbose?: boolean): void {
221 if (isAbortError(e)) {
222 process.exit()
223 }
224
225 const showStack =
226 verbose || e.message?.includes("npm") || e.message?.includes("yarn")
227
228 this.spinner.stop()
229 logMessage({
230 message: `An error occurred: ${e}`,
231 type: "error",
232 stack: showStack ? e.stack?.replace(e.toString(), "") : "",
233 })
234 }
235
236 protected showSuccessMessage(): void {
237 const commandStr = this.packageManager.getCommandStr(`dev`)
238 logMessage({
239 message: boxen(
240 chalk.green(
241 `Change to the \`${
242 this.projectName
243 }\` directory to explore your Medusa project.${EOL}${EOL}Start your Medusa application again with the following command:${EOL}${EOL}${commandStr}${EOL}${EOL}${
244 this.inviteToken
245 ? `After you start the Medusa application, you can create an admin user with the URL http://localhost:9000/app/invite?token=${this.inviteToken}&first_run=true${EOL}${EOL}`
246 : ""
247 }${
248 this.nextjsDirectory?.length
249 ? `The storefront is available in the \`${this.nextjsDirectory}\` directory. Change to that directory and start it with the following command:${EOL}${EOL}${commandStr}${EOL}${EOL}`
250 : ""
251 }Check out the Medusa ${terminalLink(
252 "documentation",
253 "https://docs.medusajs.com/"
254 )} to start your development:${EOL}${EOL}Star us on ${terminalLink(
255 "GitHub",
256 "https://github.com/medusajs/medusa/stargazers"
257 )} if you like what we're building.`
258 ),
259 {
260 titleAlignment: "center",
261 textAlignment: "center",
262 padding: 1,
263 margin: 1,
264 float: "center",
265 }
266 ),
267 })
268 }
269
270 protected setupProcessManager(): void {
271 this.processManager.onTerminated(async () => {
272 this.spinner.stop()
273
274 // prevent an error from occurring if
275 // client hasn't been declared yet
276 if (this.isDbInitialized && this.client) {
277 await this.client.end()
278 }
279
280 if (!this.printedMessage && this.isProjectCreated) {
281 this.printedMessage = true
282 this.showSuccessMessage()
283 }
284 return
285 })
286 }
287 }