create-vendure-app.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. import { intro, note, outro, select, spinner } from '@clack/prompts';
  2. import { program } from 'commander';
  3. import fs from 'fs-extra';
  4. import { ChildProcess, spawn } from 'node:child_process';
  5. import { setTimeout as sleep } from 'node:timers/promises';
  6. import open from 'open';
  7. import os from 'os';
  8. import path from 'path';
  9. import pc from 'picocolors';
  10. import { REQUIRED_NODE_VERSION, SERVER_PORT } from './constants';
  11. import {
  12. getCiConfiguration,
  13. getManualConfiguration,
  14. getQuickStartConfiguration,
  15. } from './gather-user-responses';
  16. import {
  17. checkCancel,
  18. checkDbConnection,
  19. checkNodeVersion,
  20. checkThatNpmCanReadCwd,
  21. cleanUpDockerResources,
  22. getDependencies,
  23. installPackages,
  24. isSafeToCreateProjectIn,
  25. isServerPortInUse,
  26. resolvePackageRootDir,
  27. scaffoldAlreadyExists,
  28. startPostgresDatabase,
  29. } from './helpers';
  30. import { log, setLogLevel } from './logger';
  31. import { CliLogLevel, PackageManager } from './types';
  32. // eslint-disable-next-line @typescript-eslint/no-var-requires
  33. const packageJson = require('../package.json');
  34. checkNodeVersion(REQUIRED_NODE_VERSION);
  35. let projectName: string | undefined;
  36. // Set the environment variable which can then be used to
  37. // conditionally modify behaviour of core or plugins.
  38. const createEnvVar: import('@vendure/common/lib/shared-constants').CREATING_VENDURE_APP =
  39. 'CREATING_VENDURE_APP';
  40. process.env[createEnvVar] = 'true';
  41. program
  42. .version(packageJson.version)
  43. .arguments('<project-directory>')
  44. .usage(`${pc.green('<project-directory>')} [options]`)
  45. .action(name => {
  46. projectName = name;
  47. })
  48. .option(
  49. '--log-level <logLevel>',
  50. "Log level, either 'silent', 'info', or 'verbose'",
  51. /^(silent|info|verbose)$/i,
  52. 'info',
  53. )
  54. .option('--verbose', 'Alias for --log-level verbose', false)
  55. .option(
  56. '--use-npm',
  57. 'Uses npm rather than as the default package manager. DEPRECATED: Npm is now the default',
  58. )
  59. .option('--ci', 'Runs without prompts for use in CI scenarios', false)
  60. .parse(process.argv);
  61. const options = program.opts();
  62. void createVendureApp(
  63. projectName,
  64. options.useNpm,
  65. options.verbose ? 'verbose' : options.logLevel || 'info',
  66. options.ci,
  67. ).catch(err => {
  68. log(err);
  69. process.exit(1);
  70. });
  71. export async function createVendureApp(
  72. name: string | undefined,
  73. useNpm: boolean,
  74. logLevel: CliLogLevel,
  75. isCi: boolean = false,
  76. ) {
  77. setLogLevel(logLevel);
  78. if (!runPreChecks(name, useNpm)) {
  79. return;
  80. }
  81. intro(
  82. `Let's create a ${pc.blue(pc.bold('Vendure App'))} ✨ ${pc.dim(`v${packageJson.version as string}`)}`,
  83. );
  84. const mode = isCi
  85. ? 'ci'
  86. : ((await select({
  87. message: 'How should we proceed?',
  88. options: [
  89. { label: 'Quick Start', value: 'quick', hint: 'Get up an running in a single step' },
  90. {
  91. label: 'Manual Configuration',
  92. value: 'manual',
  93. hint: 'Customize your Vendure project with more advanced settings',
  94. },
  95. ],
  96. initialValue: 'quick' as 'quick' | 'manual',
  97. })) as 'quick' | 'manual');
  98. checkCancel(mode);
  99. const portSpinner = spinner();
  100. let port = SERVER_PORT;
  101. const attemptedPortRange = 20;
  102. portSpinner.start(`Establishing port...`);
  103. while (await isServerPortInUse(port)) {
  104. const nextPort = port + 1;
  105. portSpinner.message(pc.yellow(`Port ${port} is in use. Attempting to use ${nextPort}`));
  106. port = nextPort;
  107. if (port > SERVER_PORT + attemptedPortRange) {
  108. portSpinner.stop(pc.red('Could not find an available port'));
  109. outro(
  110. `Please ensure there is a port available between ${SERVER_PORT} and ${SERVER_PORT + attemptedPortRange}`,
  111. );
  112. process.exit(1);
  113. }
  114. }
  115. portSpinner.stop(`Using port ${port}`);
  116. process.env.PORT = port.toString();
  117. const root = path.resolve(name);
  118. const appName = path.basename(root);
  119. const scaffoldExists = scaffoldAlreadyExists(root, name);
  120. const packageManager: PackageManager = 'npm';
  121. if (scaffoldExists) {
  122. log(
  123. pc.yellow(
  124. 'It appears that a new Vendure project scaffold already exists. Re-using the existing files...',
  125. ),
  126. { newline: 'after' },
  127. );
  128. }
  129. const {
  130. dbType,
  131. configSource,
  132. envSource,
  133. envDtsSource,
  134. indexSource,
  135. indexWorkerSource,
  136. readmeSource,
  137. dockerfileSource,
  138. dockerComposeSource,
  139. populateProducts,
  140. } =
  141. mode === 'ci'
  142. ? await getCiConfiguration(root, packageManager)
  143. : mode === 'manual'
  144. ? await getManualConfiguration(root, packageManager)
  145. : await getQuickStartConfiguration(root, packageManager);
  146. process.chdir(root);
  147. if (packageManager !== 'npm' && !checkThatNpmCanReadCwd()) {
  148. process.exit(1);
  149. }
  150. const packageJsonContents = {
  151. name: appName,
  152. version: '0.1.0',
  153. private: true,
  154. scripts: {
  155. 'dev:server': 'ts-node ./src/index.ts',
  156. 'dev:worker': 'ts-node ./src/index-worker.ts',
  157. dev: 'concurrently npm:dev:*',
  158. build: 'tsc',
  159. 'start:server': 'node ./dist/index.js',
  160. 'start:worker': 'node ./dist/index-worker.js',
  161. start: 'concurrently npm:start:*',
  162. },
  163. };
  164. const setupSpinner = spinner();
  165. setupSpinner.start(
  166. `Setting up your new Vendure project in ${pc.green(root)}\nThis may take a few minutes...`,
  167. );
  168. const srcPathScript = (fileName: string): string => path.join(root, 'src', `${fileName}.ts`);
  169. fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify(packageJsonContents, null, 2) + os.EOL);
  170. const { dependencies, devDependencies } = getDependencies(dbType, `@${packageJson.version as string}`);
  171. setupSpinner.stop(`Created ${pc.green('package.json')}`);
  172. const installSpinner = spinner();
  173. installSpinner.start(`Installing ${dependencies[0]} + ${dependencies.length - 1} more dependencies`);
  174. try {
  175. await installPackages({ dependencies, logLevel });
  176. } catch (e) {
  177. outro(pc.red(`Failed to inst all dependencies. Please try again.`));
  178. process.exit(1);
  179. }
  180. installSpinner.stop(`Successfully installed ${dependencies.length} dependencies`);
  181. if (devDependencies.length) {
  182. const installDevSpinner = spinner();
  183. installDevSpinner.start(
  184. `Installing ${devDependencies[0]} + ${devDependencies.length - 1} more dev dependencies`,
  185. );
  186. try {
  187. await installPackages({ dependencies: devDependencies, isDevDependencies: true, logLevel });
  188. } catch (e) {
  189. outro(pc.red(`Failed to install dev dependencies. Please try again.`));
  190. process.exit(1);
  191. }
  192. installDevSpinner.stop(`Successfully installed ${devDependencies.length} dev dependencies`);
  193. }
  194. const scaffoldSpinner = spinner();
  195. scaffoldSpinner.start(`Generating app scaffold`);
  196. // We add this pause so that the above output is displayed before the
  197. // potentially lengthy file operations begin, which can prevent that
  198. // from displaying and thus make the user think that the process has hung.
  199. await sleep(500);
  200. fs.ensureDirSync(path.join(root, 'src'));
  201. const assetPath = (fileName: string) => path.join(__dirname, '../assets', fileName);
  202. const configFile = srcPathScript('vendure-config');
  203. try {
  204. await fs
  205. .writeFile(configFile, configSource)
  206. .then(() => fs.writeFile(path.join(root, '.env'), envSource))
  207. .then(() => fs.writeFile(srcPathScript('environment.d'), envDtsSource))
  208. .then(() => fs.writeFile(srcPathScript('index'), indexSource))
  209. .then(() => fs.writeFile(srcPathScript('index-worker'), indexWorkerSource))
  210. .then(() => fs.writeFile(path.join(root, 'README.md'), readmeSource))
  211. .then(() => fs.writeFile(path.join(root, 'Dockerfile'), dockerfileSource))
  212. .then(() => fs.writeFile(path.join(root, 'docker-compose.yml'), dockerComposeSource))
  213. .then(() => fs.ensureDir(path.join(root, 'src/plugins')))
  214. .then(() => fs.copyFile(assetPath('gitignore.template'), path.join(root, '.gitignore')))
  215. .then(() => fs.copyFile(assetPath('tsconfig.template.json'), path.join(root, 'tsconfig.json')))
  216. .then(() =>
  217. fs.copyFile(
  218. assetPath('tsconfig.dashboard.template.json'),
  219. path.join(root, 'tsconfig.dashboard.json'),
  220. ),
  221. )
  222. .then(() =>
  223. fs.copyFile(assetPath('vite.config.template.mts'), path.join(root, 'vite.config.mts')),
  224. )
  225. .then(() => createDirectoryStructure(root))
  226. .then(() => copyEmailTemplates(root));
  227. } catch (e: any) {
  228. outro(pc.red(`Failed to create app scaffold: ${e.message as string}`));
  229. process.exit(1);
  230. }
  231. scaffoldSpinner.stop(`Generated app scaffold`);
  232. if (mode === 'quick' && dbType === 'postgres') {
  233. cleanUpDockerResources(name);
  234. await startPostgresDatabase(root);
  235. }
  236. const populateSpinner = spinner();
  237. populateSpinner.start(`Initializing your new Vendure server`);
  238. // We want to display a set of tips and instructions to the user
  239. // as the initialization process is running because it can take
  240. // a few minutes to complete.
  241. const tips = [
  242. populateProducts
  243. ? 'We are populating sample data so that you can start testing right away'
  244. : 'We are setting up your Vendure server',
  245. '☕ This can take a minute or two, so grab a coffee',
  246. `✨ We'd love it if you drop us a star on GitHub: https://github.com/vendure-ecommerce/vendure`,
  247. `📖 Check out the Vendure documentation at https://docs.vendure.io`,
  248. `💬 Join our Discord community to chat with other Vendure developers: https://vendure.io/community`,
  249. '💡 In the mean time, here are some tips to get you started',
  250. `Vendure provides dedicated GraphQL APIs for both the Admin and Shop`,
  251. `Almost every aspect of Vendure is customizable via plugins`,
  252. `You can run 'vendure add' from the command line to add new plugins & features`,
  253. `Use the EventBus in your plugins to react to events in the system`,
  254. `Vendure supports multiple languages & currencies out of the box`,
  255. `☕ Did we mention this can take a while?`,
  256. `Our custom fields feature allows you to add any kind of data to your entities`,
  257. `Vendure is built with TypeScript, so you get full type safety`,
  258. `Combined with GraphQL's static schema, your type safety is end-to-end`,
  259. `☕ Almost there now... thanks for your patience!`,
  260. `Collections allow you to group products together`,
  261. `Our AssetServerPlugin allows you to dynamically resize & optimize images`,
  262. `Order flows are fully customizable to suit your business requirements`,
  263. `Role-based permissions allow you to control access to every part of the system`,
  264. `Customers can be grouped for targeted promotions & custom pricing`,
  265. `You can find integrations in the Vendure Hub: https://vendure.io/hub`,
  266. ];
  267. let tipIndex = 0;
  268. let timer: any;
  269. const tipInterval = 10_000;
  270. function displayTip() {
  271. populateSpinner.message(tips[tipIndex]);
  272. tipIndex++;
  273. if (tipIndex >= tips.length) {
  274. // skip the intro tips if looping
  275. tipIndex = 3;
  276. }
  277. timer = setTimeout(displayTip, tipInterval);
  278. }
  279. timer = setTimeout(displayTip, tipInterval);
  280. // register ts-node so that the config file can be loaded
  281. // eslint-disable-next-line @typescript-eslint/no-var-requires
  282. require(resolvePackageRootDir('ts-node', root)).register();
  283. let superAdminCredentials: { identifier: string; password: string } | undefined;
  284. try {
  285. const { populate } = await import(
  286. path.join(resolvePackageRootDir('@vendure/core', root), 'cli', 'populate')
  287. );
  288. const { bootstrap, DefaultLogger, LogLevel, JobQueueService } = await import(
  289. path.join(resolvePackageRootDir('@vendure/core', root), 'dist', 'index')
  290. );
  291. const { config } = await import(configFile);
  292. const assetsDir = path.join(__dirname, '../assets');
  293. superAdminCredentials = config.authOptions.superadminCredentials;
  294. const initialDataPath = path.join(assetsDir, 'initial-data.json');
  295. const vendureLogLevel =
  296. logLevel === 'info' || logLevel === 'silent'
  297. ? LogLevel.Error
  298. : logLevel === 'verbose'
  299. ? LogLevel.Verbose
  300. : LogLevel.Info;
  301. const bootstrapFn = async () => {
  302. await checkDbConnection(config.dbConnectionOptions, root);
  303. const _app = await bootstrap({
  304. ...config,
  305. apiOptions: {
  306. ...(config.apiOptions ?? {}),
  307. port,
  308. },
  309. dbConnectionOptions: {
  310. ...config.dbConnectionOptions,
  311. synchronize: true,
  312. },
  313. logger: new DefaultLogger({ level: vendureLogLevel }),
  314. importExportOptions: {
  315. importAssetsDir: path.join(assetsDir, 'images'),
  316. },
  317. });
  318. await _app.get(JobQueueService).start();
  319. return _app;
  320. };
  321. const app = await populate(
  322. bootstrapFn,
  323. initialDataPath,
  324. populateProducts ? path.join(assetsDir, 'products.csv') : undefined,
  325. );
  326. // Pause to ensure the worker jobs have time to complete.
  327. if (isCi) {
  328. log('[CI] Pausing before close...');
  329. }
  330. await sleep(isCi ? 30000 : 2000);
  331. await app.close();
  332. if (isCi) {
  333. log('[CI] Pausing after close...');
  334. await sleep(10000);
  335. }
  336. populateSpinner.stop(`Server successfully initialized${populateProducts ? ' and populated' : ''}`);
  337. clearTimeout(timer);
  338. /**
  339. * This is currently disabled because I am running into issues actually getting the server
  340. * to quite properly in response to a SIGINT.
  341. * This means that the server runs, but cannot be ended, without forcefully
  342. * killing the process.
  343. *
  344. * Once this has been resolved, the following code can be re-enabled by
  345. * setting `autoRunServer` to `true`.
  346. */
  347. const autoRunServer = false;
  348. if (mode === 'quick' && autoRunServer) {
  349. // In quick-start mode, we want to now run the server and open up
  350. // a browser window to the Admin UI.
  351. try {
  352. const adminUiUrl = `http://localhost:${port}/admin`;
  353. const quickStartInstructions = [
  354. 'Use the following credentials to log in to the Admin UI:',
  355. `Username: ${pc.green(config.authOptions.superadminCredentials?.identifier)}`,
  356. `Password: ${pc.green(config.authOptions.superadminCredentials?.password)}`,
  357. `Open your browser and navigate to: ${pc.green(adminUiUrl)}`,
  358. '',
  359. ];
  360. note(quickStartInstructions.join('\n'));
  361. const npmCommand = os.platform() === 'win32' ? 'npm.cmd' : 'npm';
  362. let quickStartProcess: ChildProcess | undefined;
  363. try {
  364. quickStartProcess = spawn(npmCommand, ['run', 'dev'], {
  365. cwd: root,
  366. stdio: 'inherit',
  367. });
  368. } catch (e: any) {
  369. /* empty */
  370. }
  371. // process.stdin.resume();
  372. process.on('SIGINT', function () {
  373. displayOutro(root, name, superAdminCredentials);
  374. quickStartProcess?.kill('SIGINT');
  375. process.exit(0);
  376. });
  377. // Give enough time for the server to get up and running
  378. // before opening the window.
  379. await sleep(10_000);
  380. try {
  381. await open(adminUiUrl, {
  382. newInstance: true,
  383. });
  384. } catch (e: any) {
  385. /* empty */
  386. }
  387. } catch (e: any) {
  388. log(pc.red(`Failed to start the server: ${e.message as string}`), {
  389. newline: 'after',
  390. level: 'verbose',
  391. });
  392. }
  393. } else {
  394. clearTimeout(timer);
  395. displayOutro(root, name, superAdminCredentials);
  396. process.exit(0);
  397. }
  398. } catch (e: any) {
  399. log(e.toString());
  400. outro(pc.red(`Failed to initialize server. Please try again.`));
  401. process.exit(1);
  402. }
  403. }
  404. function displayOutro(
  405. root: string,
  406. name: string,
  407. superAdminCredentials?: { identifier: string; password: string },
  408. ) {
  409. const startCommand = 'npm run dev';
  410. const nextSteps = [
  411. `Your new Vendure server was created!`,
  412. pc.gray(root),
  413. `\n`,
  414. `Next, run:`,
  415. pc.gray('$ ') + pc.blue(pc.bold(`cd ${name}`)),
  416. pc.gray('$ ') + pc.blue(pc.bold(`${startCommand}`)),
  417. `\n`,
  418. `This will start the server in development mode.`,
  419. `To access the Admin UI, open your browser and navigate to:`,
  420. `\n`,
  421. pc.green(`http://localhost:3000/admin`),
  422. `\n`,
  423. `Use the following credentials to log in:`,
  424. `Username: ${pc.green(superAdminCredentials?.identifier ?? 'superadmin')}`,
  425. `Password: ${pc.green(superAdminCredentials?.password ?? 'superadmin')}`,
  426. '\n',
  427. '➡️ Docs: https://docs.vendure.io',
  428. '➡️ Discord community: https://vendure.io/community',
  429. '➡️ Star us on GitHub:',
  430. ' https://github.com/vendure-ecommerce/vendure',
  431. ];
  432. note(nextSteps.join('\n'), pc.green('Setup complete!'));
  433. outro(`Happy hacking!`);
  434. }
  435. /**
  436. * Run some initial checks to ensure that it is okay to proceed with creating
  437. * a new Vendure project in the given location.
  438. */
  439. function runPreChecks(name: string | undefined, useNpm: boolean): name is string {
  440. if (typeof name === 'undefined') {
  441. log(pc.red(`Please specify the project directory:`));
  442. log(` ${pc.cyan(program.name())} ${pc.green('<project-directory>')}`, { newline: 'after' });
  443. log('For example:');
  444. log(` ${pc.cyan(program.name())} ${pc.green('my-vendure-app')}`);
  445. process.exit(1);
  446. return false;
  447. }
  448. const root = path.resolve(name);
  449. try {
  450. fs.ensureDirSync(name);
  451. } catch (e: any) {
  452. log(pc.red(`Could not create project directory ${name}: ${e.message as string}`));
  453. return false;
  454. }
  455. if (!isSafeToCreateProjectIn(root, name)) {
  456. process.exit(1);
  457. }
  458. return true;
  459. }
  460. /**
  461. * Generate the default directory structure for a new Vendure project
  462. */
  463. async function createDirectoryStructure(root: string) {
  464. await fs.ensureDir(path.join(root, 'static', 'email', 'test-emails'));
  465. await fs.ensureDir(path.join(root, 'static', 'assets'));
  466. }
  467. /**
  468. * Copy the email templates into the app
  469. */
  470. async function copyEmailTemplates(root: string) {
  471. const emailPackageDirname = resolvePackageRootDir('@vendure/email-plugin', root);
  472. const templateDir = path.join(emailPackageDirname, 'templates');
  473. try {
  474. await fs.copy(templateDir, path.join(root, 'static', 'email', 'templates'));
  475. } catch (err: any) {
  476. log(pc.red('Failed to copy email templates.'));
  477. log(err);
  478. process.exit(0);
  479. }
  480. }