create-vendure-app.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. /* eslint-disable no-console */
  2. import chalk from 'chalk';
  3. import program from 'commander';
  4. import detectPort from 'detect-port';
  5. import fs from 'fs-extra';
  6. import Listr from 'listr';
  7. import os from 'os';
  8. import path from 'path';
  9. import { Observable } from 'rxjs';
  10. import { REQUIRED_NODE_VERSION, SERVER_PORT } from './constants';
  11. import { gatherCiUserResponses, gatherUserResponses } from './gather-user-responses';
  12. import {
  13. checkDbConnection,
  14. checkNodeVersion,
  15. checkThatNpmCanReadCwd,
  16. getDependencies,
  17. installPackages,
  18. isSafeToCreateProjectIn,
  19. isServerPortInUse,
  20. scaffoldAlreadyExists,
  21. shouldUseYarn,
  22. } from './helpers';
  23. import { CliLogLevel } from './types';
  24. // eslint-disable-next-line @typescript-eslint/no-var-requires
  25. const packageJson = require('../package.json');
  26. checkNodeVersion(REQUIRED_NODE_VERSION);
  27. let projectName: string | undefined;
  28. // Set the environment variable which can then be used to
  29. // conditionally modify behaviour of core or plugins.
  30. const createEnvVar: import('@vendure/common/lib/shared-constants').CREATING_VENDURE_APP =
  31. 'CREATING_VENDURE_APP';
  32. process.env[createEnvVar] = 'true';
  33. program
  34. .version(packageJson.version)
  35. .arguments('<project-directory>')
  36. .usage(`${chalk.green('<project-directory>')} [options]`)
  37. .action(name => {
  38. projectName = name;
  39. })
  40. .option(
  41. '--log-level <logLevel>',
  42. 'Log level, either \'silent\', \'info\', or \'verbose\'',
  43. /^(silent|info|verbose)$/i,
  44. 'silent',
  45. )
  46. .option('--use-npm', 'Uses npm rather than Yarn as the default package manager')
  47. .option('--ci', 'Runs without prompts for use in CI scenarios')
  48. .parse(process.argv);
  49. const options = program.opts();
  50. void createApp(projectName, options.useNpm, options.logLevel || 'silent', options.ci);
  51. async function createApp(
  52. name: string | undefined,
  53. useNpm: boolean,
  54. logLevel: CliLogLevel,
  55. isCi: boolean = false,
  56. ) {
  57. if (!runPreChecks(name, useNpm)) {
  58. return;
  59. }
  60. if (await isServerPortInUse()) {
  61. console.log(chalk.red(`Port ${SERVER_PORT} is in use. Please make it available and then re-try.`));
  62. process.exit(1);
  63. }
  64. console.log(chalk.cyan(`Welcome to @vendure/create v${packageJson.version as string}!`));
  65. console.log();
  66. console.log('Let\'s configure a new Vendure project. First a few questions:');
  67. console.log();
  68. const root = path.resolve(name);
  69. const appName = path.basename(root);
  70. const scaffoldExists = scaffoldAlreadyExists(root, name);
  71. const useYarn = useNpm ? false : shouldUseYarn();
  72. if (scaffoldExists) {
  73. console.log(
  74. chalk.green(
  75. 'It appears that a new Vendure project scaffold already exists. Re-using the existing files...',
  76. ),
  77. );
  78. console.log();
  79. }
  80. const {
  81. dbType,
  82. configSource,
  83. envSource,
  84. envDtsSource,
  85. indexSource,
  86. indexWorkerSource,
  87. migrationSource,
  88. readmeSource,
  89. dockerfileSource,
  90. dockerComposeSource,
  91. populateProducts,
  92. } = isCi
  93. ? await gatherCiUserResponses(root, useYarn)
  94. : await gatherUserResponses(root, scaffoldExists, useYarn);
  95. const originalDirectory = process.cwd();
  96. process.chdir(root);
  97. if (!useYarn && !checkThatNpmCanReadCwd()) {
  98. process.exit(1);
  99. }
  100. const packageJsonContents = {
  101. name: appName,
  102. version: '0.1.0',
  103. private: true,
  104. scripts: {
  105. 'dev:server': 'ts-node ./src/index.ts',
  106. 'dev:worker': 'ts-node ./src/index-worker.ts',
  107. dev: useYarn ? 'concurrently yarn:dev:*' : 'concurrently npm:dev:*',
  108. build: 'tsc',
  109. 'start:server': 'node ./dist/index.js',
  110. 'start:worker': 'node ./dist/index-worker.js',
  111. start: useYarn ? 'concurrently yarn:start:*' : 'concurrently npm:start:*',
  112. 'migration:generate': 'ts-node migration generate',
  113. 'migration:run': 'ts-node migration run',
  114. 'migration:revert': 'ts-node migration revert',
  115. },
  116. };
  117. console.log();
  118. console.log(`Setting up your new Vendure project in ${chalk.green(root)}`);
  119. console.log('This may take a few minutes...');
  120. console.log();
  121. const rootPathScript = (fileName: string): string => path.join(root, `${fileName}.ts`);
  122. const srcPathScript = (fileName: string): string => path.join(root, 'src', `${fileName}.ts`);
  123. const listrTasks: Listr.ListrTask[] = [];
  124. if (scaffoldExists) {
  125. // ...
  126. } else {
  127. listrTasks.push(
  128. {
  129. title: 'Installing dependencies',
  130. task: (() => {
  131. return new Observable(subscriber => {
  132. subscriber.next('Creating package.json');
  133. fs.writeFileSync(
  134. path.join(root, 'package.json'),
  135. JSON.stringify(packageJsonContents, null, 2) + os.EOL,
  136. );
  137. const { dependencies, devDependencies } = getDependencies(
  138. dbType,
  139. isCi ? `@${packageJson.version as string}` : '',
  140. );
  141. subscriber.next(`Installing ${dependencies.join(', ')}`);
  142. installPackages(root, useYarn, dependencies, false, logLevel, isCi)
  143. .then(() => {
  144. if (devDependencies.length) {
  145. subscriber.next(`Installing ${devDependencies.join(', ')}`);
  146. return installPackages(
  147. root,
  148. useYarn,
  149. devDependencies,
  150. true,
  151. logLevel,
  152. isCi,
  153. );
  154. }
  155. })
  156. .then(() => subscriber.complete())
  157. .catch(err => subscriber.error(err));
  158. });
  159. }) as any,
  160. },
  161. {
  162. title: 'Generating app scaffold',
  163. task: ctx => {
  164. return new Observable(subscriber => {
  165. fs.ensureDirSync(path.join(root, 'src'));
  166. const assetPath = (fileName: string) => path.join(__dirname, '../assets', fileName);
  167. ctx.configFile = srcPathScript('vendure-config');
  168. fs.writeFile(ctx.configFile, configSource)
  169. .then(() => fs.writeFile(path.join(root, '.env'), envSource))
  170. .then(() => fs.writeFile(srcPathScript('environment.d'), envDtsSource))
  171. .then(() => fs.writeFile(srcPathScript('index'), indexSource))
  172. .then(() => fs.writeFile(srcPathScript('index-worker'), indexWorkerSource))
  173. .then(() => fs.writeFile(rootPathScript('migration'), migrationSource))
  174. .then(() => fs.writeFile(path.join(root, 'README.md'), readmeSource))
  175. .then(() => fs.writeFile(path.join(root, 'Dockerfile'), dockerfileSource))
  176. .then(() =>
  177. fs.writeFile(path.join(root, 'docker-compose.yml'), dockerComposeSource),
  178. )
  179. .then(() => fs.mkdir(path.join(root, 'src/plugins')))
  180. .then(() =>
  181. fs.copyFile(assetPath('gitignore.template'), path.join(root, '.gitignore')),
  182. )
  183. .then(() => {
  184. subscriber.next('Created files');
  185. return fs.copyFile(
  186. assetPath('tsconfig.template.json'),
  187. path.join(root, 'tsconfig.json'),
  188. );
  189. })
  190. .then(() => createDirectoryStructure(root))
  191. .then(() => {
  192. subscriber.next('Created directory structure');
  193. return copyEmailTemplates(root);
  194. })
  195. .then(() => {
  196. subscriber.next('Copied email templates');
  197. subscriber.complete();
  198. })
  199. .catch(err => subscriber.error(err));
  200. }) as any;
  201. },
  202. },
  203. );
  204. }
  205. listrTasks.push({
  206. title: 'Initializing server',
  207. task: async ctx => {
  208. try {
  209. // register ts-node so that the config file can be loaded
  210. // eslint-disable-next-line @typescript-eslint/no-var-requires
  211. require(path.join(root, 'node_modules/ts-node')).register();
  212. const { populate } = await import(path.join(root, 'node_modules/@vendure/core/cli/populate'));
  213. const { bootstrap, DefaultLogger, LogLevel, JobQueueService } = await import(
  214. path.join(root, 'node_modules/@vendure/core/dist/index')
  215. );
  216. const configFile = srcPathScript('vendure-config');
  217. const { config } = await import(configFile);
  218. const assetsDir = path.join(__dirname, '../assets');
  219. const initialDataPath = path.join(assetsDir, 'initial-data.json');
  220. const port = await detectPort(3000);
  221. const vendureLogLevel =
  222. logLevel === 'silent'
  223. ? LogLevel.Error
  224. : logLevel === 'verbose'
  225. ? LogLevel.Verbose
  226. : LogLevel.Info;
  227. const bootstrapFn = async () => {
  228. await checkDbConnection(config.dbConnectionOptions, root);
  229. const _app = await bootstrap({
  230. ...config,
  231. apiOptions: {
  232. ...(config.apiOptions ?? {}),
  233. port,
  234. },
  235. silent: logLevel === 'silent',
  236. dbConnectionOptions: {
  237. ...config.dbConnectionOptions,
  238. synchronize: true,
  239. },
  240. logger: new DefaultLogger({ level: vendureLogLevel }),
  241. importExportOptions: {
  242. importAssetsDir: path.join(assetsDir, 'images'),
  243. },
  244. });
  245. await _app.get(JobQueueService).start();
  246. return _app;
  247. };
  248. const app = await populate(
  249. bootstrapFn,
  250. initialDataPath,
  251. populateProducts ? path.join(assetsDir, 'products.csv') : undefined,
  252. );
  253. // Pause to ensure the worker jobs have time to complete.
  254. if (isCi) {
  255. console.log('[CI] Pausing before close...');
  256. }
  257. await new Promise(resolve => setTimeout(resolve, isCi ? 30000 : 2000));
  258. await app.close();
  259. if (isCi) {
  260. console.log('[CI] Pausing after close...');
  261. await new Promise(resolve => setTimeout(resolve, 10000));
  262. }
  263. } catch (e: any) {
  264. console.log();
  265. console.error(chalk.red(e.message));
  266. console.log();
  267. console.log(e);
  268. throw e;
  269. }
  270. },
  271. });
  272. const tasks = new Listr(listrTasks);
  273. try {
  274. await tasks.run();
  275. } catch (e: any) {
  276. process.exit(1);
  277. }
  278. const startCommand = useYarn ? 'yarn dev' : 'npm run dev';
  279. console.log();
  280. console.log(chalk.green(`Success! Created a new Vendure server at ${root}`));
  281. console.log();
  282. console.log('We suggest that you start by typing:');
  283. console.log();
  284. console.log(chalk.green(` cd ${name}`));
  285. console.log(chalk.green(` ${startCommand}`));
  286. console.log();
  287. console.log('Happy hacking!');
  288. process.exit(0);
  289. }
  290. /**
  291. * Run some initial checks to ensure that it is okay to proceed with creating
  292. * a new Vendure project in the given location.
  293. */
  294. function runPreChecks(name: string | undefined, useNpm: boolean): name is string {
  295. if (typeof name === 'undefined') {
  296. console.error('Please specify the project directory:');
  297. console.log(` ${chalk.cyan(program.name())} ${chalk.green('<project-directory>')}`);
  298. console.log();
  299. console.log('For example:');
  300. console.log(` ${chalk.cyan(program.name())} ${chalk.green('my-vendure-app')}`);
  301. process.exit(1);
  302. return false;
  303. }
  304. const root = path.resolve(name);
  305. fs.ensureDirSync(name);
  306. if (!isSafeToCreateProjectIn(root, name)) {
  307. process.exit(1);
  308. }
  309. return true;
  310. }
  311. /**
  312. * Generate the default directory structure for a new Vendure project
  313. */
  314. async function createDirectoryStructure(root: string) {
  315. await fs.ensureDir(path.join(root, 'static', 'email', 'test-emails'));
  316. await fs.ensureDir(path.join(root, 'static', 'assets'));
  317. }
  318. /**
  319. * Copy the email templates into the app
  320. */
  321. async function copyEmailTemplates(root: string) {
  322. const templateDir = path.join(root, 'node_modules/@vendure/email-plugin/templates');
  323. try {
  324. await fs.copy(templateDir, path.join(root, 'static', 'email', 'templates'));
  325. } catch (err: any) {
  326. console.error(chalk.red('Failed to copy email templates.'));
  327. }
  328. }