create-vendure-app.ts 13 KB

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