create-vendure-app.ts 19 KB

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