create-vendure-app.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. import { intro, note, outro, select, spinner } from '@clack/prompts';
  2. import { SUPER_ADMIN_USER_IDENTIFIER, SUPER_ADMIN_USER_PASSWORD } from '@vendure/common/lib/shared-constants';
  3. import { program } from 'commander';
  4. import { randomBytes } from 'crypto';
  5. import fs from 'fs-extra';
  6. import Handlebars from 'handlebars';
  7. import { ChildProcess, spawn } from 'node:child_process';
  8. import { setTimeout as sleep } from 'node:timers/promises';
  9. import open from 'open';
  10. import os from 'os';
  11. import path from 'path';
  12. import pc from 'picocolors';
  13. import {
  14. AUTO_RUN_DELAY_MS,
  15. CI_PAUSE_AFTER_CLOSE_MS,
  16. CI_PAUSE_BEFORE_CLOSE_MS,
  17. DEFAULT_PROJECT_VERSION,
  18. NORMAL_PAUSE_BEFORE_CLOSE_MS,
  19. PORT_SCAN_RANGE,
  20. REQUIRED_NODE_VERSION,
  21. SCAFFOLD_DELAY_MS,
  22. SERVER_PORT,
  23. STOREFRONT_PORT,
  24. TIP_INTERVAL_MS,
  25. TIPS_WHILE_WAITING,
  26. } from './constants';
  27. import {
  28. getCiConfiguration,
  29. getManualConfiguration,
  30. getQuickStartConfiguration,
  31. } from './gather-user-responses';
  32. import {
  33. checkCancel,
  34. checkDbConnection,
  35. checkNodeVersion,
  36. checkThatNpmCanReadCwd,
  37. cleanUpDockerResources,
  38. downloadAndExtractStorefront,
  39. findAvailablePort,
  40. getDependencies,
  41. installPackages,
  42. isSafeToCreateProjectIn,
  43. resolvePackageRootDir,
  44. scaffoldAlreadyExists,
  45. startPostgresDatabase,
  46. } from './helpers';
  47. import { log, setLogLevel } from './logger';
  48. import { CliLogLevel, PackageManager } from './types';
  49. // eslint-disable-next-line @typescript-eslint/no-var-requires
  50. const packageJson = require('../package.json');
  51. checkNodeVersion(REQUIRED_NODE_VERSION);
  52. let projectName: string | undefined;
  53. // Set the environment variable which can then be used to
  54. // conditionally modify behaviour of core or plugins.
  55. const createEnvVar: import('@vendure/common/lib/shared-constants').CREATING_VENDURE_APP =
  56. 'CREATING_VENDURE_APP';
  57. process.env[createEnvVar] = 'true';
  58. program
  59. .version(packageJson.version)
  60. .arguments('<project-directory>')
  61. .usage(`${pc.green('<project-directory>')} [options]`)
  62. .action(name => {
  63. projectName = name;
  64. })
  65. .option(
  66. '--log-level <logLevel>',
  67. "Log level, either 'silent', 'info', or 'verbose'",
  68. /^(silent|info|verbose)$/i,
  69. 'info',
  70. )
  71. .option('--verbose', 'Alias for --log-level verbose', false)
  72. .option(
  73. '--use-npm',
  74. 'Uses npm rather than as the default package manager. DEPRECATED: Npm is now the default',
  75. )
  76. .option('--ci', 'Runs without prompts for use in CI scenarios', false)
  77. .option('--with-storefront', 'Include Next.js storefront (only used with --ci)', false)
  78. .parse(process.argv);
  79. const options = program.opts();
  80. void createVendureApp(
  81. projectName,
  82. options.useNpm,
  83. options.verbose ? 'verbose' : options.logLevel || 'info',
  84. options.ci,
  85. options.withStorefront,
  86. ).catch(err => {
  87. log(err);
  88. process.exit(1);
  89. });
  90. export async function createVendureApp(
  91. name: string | undefined,
  92. _useNpm: boolean, // Deprecated: npm is now the default package manager
  93. logLevel: CliLogLevel,
  94. isCi: boolean = false,
  95. withStorefront: boolean = false,
  96. ) {
  97. setLogLevel(logLevel);
  98. if (!runPreChecks(name)) {
  99. return;
  100. }
  101. intro(
  102. `Let's create a ${pc.blue(pc.bold('Vendure App'))} ✨ ${pc.dim(`v${packageJson.version as string}`)}`,
  103. );
  104. const mode = isCi
  105. ? 'ci'
  106. : ((await select({
  107. message: 'How should we proceed?',
  108. options: [
  109. { label: 'Quick Start', value: 'quick', hint: 'Get up an running in a single step' },
  110. {
  111. label: 'Manual Configuration',
  112. value: 'manual',
  113. hint: 'Customize your Vendure project with more advanced settings',
  114. },
  115. ],
  116. initialValue: 'quick' as 'quick' | 'manual',
  117. })) as 'quick' | 'manual');
  118. checkCancel(mode);
  119. const portSpinner = spinner();
  120. let port: number;
  121. let storefrontPort: number = STOREFRONT_PORT;
  122. portSpinner.start(`Establishing port...`);
  123. try {
  124. port = await findAvailablePort(SERVER_PORT, PORT_SCAN_RANGE);
  125. portSpinner.stop(`Using port ${port}`);
  126. } catch (e: any) {
  127. portSpinner.stop(pc.red('Could not find an available port'));
  128. outro(e.message);
  129. process.exit(1);
  130. }
  131. process.env.PORT = port.toString();
  132. const root = path.resolve(name);
  133. const appName = path.basename(root);
  134. const scaffoldExists = scaffoldAlreadyExists(root, name);
  135. const packageManager: PackageManager = 'npm';
  136. if (scaffoldExists) {
  137. log(
  138. pc.yellow(
  139. 'It appears that a new Vendure project scaffold already exists. Re-using the existing files...',
  140. ),
  141. { newline: 'after' },
  142. );
  143. }
  144. const {
  145. dbType,
  146. configSource,
  147. envSource,
  148. envDtsSource,
  149. indexSource,
  150. indexWorkerSource,
  151. readmeSource,
  152. dockerfileSource,
  153. dockerComposeSource,
  154. tsconfigDashboardSource,
  155. viteConfigSource,
  156. populateProducts,
  157. includeStorefront,
  158. } =
  159. mode === 'ci'
  160. ? await getCiConfiguration(root, packageManager, port, withStorefront)
  161. : mode === 'manual'
  162. ? await getManualConfiguration(root, packageManager, port)
  163. : await getQuickStartConfiguration(root, packageManager, port);
  164. // Determine the server root directory (either root or apps/server for monorepo)
  165. const serverRoot = includeStorefront ? path.join(root, 'apps', 'server') : root;
  166. const storefrontRoot = path.join(root, 'apps', 'storefront');
  167. // Find an available storefront port if including storefront
  168. if (includeStorefront) {
  169. const storefrontPortSpinner = spinner();
  170. storefrontPortSpinner.start(`Establishing storefront port...`);
  171. try {
  172. // Start scanning from the higher of STOREFRONT_PORT or serverPort + 1
  173. // to avoid conflicts with the server port
  174. const storefrontStartPort = Math.max(STOREFRONT_PORT, port + 1);
  175. storefrontPort = await findAvailablePort(storefrontStartPort, PORT_SCAN_RANGE);
  176. storefrontPortSpinner.stop(`Using storefront port ${storefrontPort}`);
  177. } catch (e: any) {
  178. storefrontPortSpinner.stop(pc.red('Could not find an available storefront port'));
  179. outro(e.message);
  180. process.exit(1);
  181. }
  182. }
  183. process.chdir(root);
  184. if (packageManager !== 'npm' && !checkThatNpmCanReadCwd()) {
  185. process.exit(1);
  186. }
  187. const setupSpinner = spinner();
  188. const projectType = includeStorefront ? 'monorepo' : 'project';
  189. setupSpinner.start(
  190. `Setting up your new Vendure ${projectType} in ${pc.green(root)}\nThis may take a few minutes...`,
  191. );
  192. const assetPath = (fileName: string) => path.join(__dirname, '../assets', fileName);
  193. const templatePath = (fileName: string) => path.join(__dirname, '../assets/monorepo', fileName);
  194. if (includeStorefront) {
  195. // Create monorepo structure
  196. await fs.ensureDir(path.join(root, 'apps'));
  197. await fs.ensureDir(serverRoot);
  198. await fs.ensureDir(path.join(serverRoot, 'src'));
  199. // Generate root package.json from template
  200. const rootPackageTemplate = await fs.readFile(templatePath('root-package.json.hbs'), 'utf-8');
  201. const rootPackageContent = Handlebars.compile(rootPackageTemplate)({ name: appName });
  202. fs.writeFileSync(path.join(root, 'package.json'), rootPackageContent + os.EOL);
  203. // Generate root README from template
  204. const rootReadmeTemplate = await fs.readFile(templatePath('root-readme.hbs'), 'utf-8');
  205. const rootReadmeContent = Handlebars.compile(rootReadmeTemplate)({
  206. name: appName,
  207. serverPort: port,
  208. storefrontPort,
  209. superadminIdentifier: SUPER_ADMIN_USER_IDENTIFIER,
  210. superadminPassword: SUPER_ADMIN_USER_PASSWORD,
  211. });
  212. fs.writeFileSync(path.join(root, 'README.md'), rootReadmeContent);
  213. // Copy root .gitignore
  214. await fs.copyFile(templatePath('root-gitignore.template'), path.join(root, '.gitignore'));
  215. // Create server package.json
  216. const serverPackageJsonContents = {
  217. name: 'server',
  218. version: DEFAULT_PROJECT_VERSION,
  219. private: true,
  220. scripts: getServerPackageScripts(),
  221. };
  222. fs.writeFileSync(
  223. path.join(serverRoot, 'package.json'),
  224. JSON.stringify(serverPackageJsonContents, null, 2) + os.EOL,
  225. );
  226. } else {
  227. // Single project structure (original behavior)
  228. const packageJsonContents = {
  229. name: appName,
  230. version: DEFAULT_PROJECT_VERSION,
  231. private: true,
  232. scripts: getServerPackageScripts(),
  233. };
  234. fs.writeFileSync(
  235. path.join(root, 'package.json'),
  236. JSON.stringify(packageJsonContents, null, 2) + os.EOL,
  237. );
  238. fs.ensureDirSync(path.join(root, 'src'));
  239. }
  240. setupSpinner.stop(`Created ${pc.green('package.json')}`);
  241. // Download storefront if needed
  242. if (includeStorefront) {
  243. const storefrontSpinner = spinner();
  244. storefrontSpinner.start(`Downloading Next.js storefront...`);
  245. try {
  246. await downloadAndExtractStorefront(storefrontRoot);
  247. // Update storefront package.json name and dev script port
  248. const storefrontPackageJsonPath = path.join(storefrontRoot, 'package.json');
  249. const storefrontPackageJson = await fs.readJson(storefrontPackageJsonPath);
  250. storefrontPackageJson.name = 'storefront';
  251. if (storefrontPackageJson.scripts?.dev) {
  252. storefrontPackageJson.scripts.dev = `next dev --port ${storefrontPort}`;
  253. }
  254. await fs.writeJson(storefrontPackageJsonPath, storefrontPackageJson, { spaces: 2 });
  255. // Generate storefront .env.local from template
  256. const storefrontEnvTemplate = await fs.readFile(templatePath('storefront-env.hbs'), 'utf-8');
  257. const storefrontEnvContent = Handlebars.compile(storefrontEnvTemplate)({
  258. serverPort: port,
  259. storefrontPort,
  260. name: appName,
  261. revalidationSecret: randomBytes(32).toString('base64'),
  262. });
  263. fs.writeFileSync(path.join(storefrontRoot, '.env.local'), storefrontEnvContent);
  264. storefrontSpinner.stop(`Downloaded Next.js storefront`);
  265. } catch (e: any) {
  266. storefrontSpinner.stop(pc.red(`Failed to download storefront`));
  267. log(e.message, { level: 'verbose' });
  268. outro(pc.red(`Failed to download storefront: ${e.message as string}`));
  269. process.exit(1);
  270. }
  271. }
  272. // Install dependencies
  273. const { dependencies, devDependencies } = getDependencies(dbType, `@${packageJson.version as string}`);
  274. // Install server dependencies
  275. await installDependenciesWithSpinner({
  276. dependencies,
  277. logLevel,
  278. cwd: serverRoot,
  279. spinnerMessage: `Installing ${dependencies[0]} + ${dependencies.length - 1} more dependencies`,
  280. successMessage: `Successfully installed ${dependencies.length} dependencies`,
  281. failureMessage: 'Failed to install dependencies. Please try again.',
  282. });
  283. if (devDependencies.length) {
  284. await installDependenciesWithSpinner({
  285. dependencies: devDependencies,
  286. isDevDependencies: true,
  287. logLevel,
  288. cwd: serverRoot,
  289. spinnerMessage: `Installing ${devDependencies[0]} + ${devDependencies.length - 1} more dev dependencies`,
  290. successMessage: `Successfully installed ${devDependencies.length} dev dependencies`,
  291. failureMessage: 'Failed to install dev dependencies. Please try again.',
  292. });
  293. }
  294. if (includeStorefront) {
  295. // Install storefront dependencies
  296. const storefrontInstalled = await installDependenciesWithSpinner({
  297. dependencies: [],
  298. logLevel,
  299. cwd: storefrontRoot,
  300. spinnerMessage: 'Installing storefront dependencies...',
  301. successMessage: 'Installed storefront dependencies',
  302. failureMessage: 'Failed to install storefront dependencies',
  303. warnOnFailure: true,
  304. });
  305. if (!storefrontInstalled) {
  306. log('You may need to run npm install in the storefront directory manually.', { level: 'info' });
  307. }
  308. }
  309. const scaffoldSpinner = spinner();
  310. scaffoldSpinner.start(`Generating app scaffold`);
  311. // We add this pause so that the above output is displayed before the
  312. // potentially lengthy file operations begin, which can prevent that
  313. // from displaying and thus make the user think that the process has hung.
  314. await sleep(SCAFFOLD_DELAY_MS);
  315. const srcPathScript = (fileName: string): string => path.join(serverRoot, 'src', `${fileName}.ts`);
  316. if (!includeStorefront) {
  317. fs.ensureDirSync(path.join(serverRoot, 'src'));
  318. }
  319. const configFile = srcPathScript('vendure-config');
  320. try {
  321. await fs
  322. .writeFile(configFile, configSource)
  323. .then(() => fs.writeFile(path.join(serverRoot, '.env'), envSource))
  324. .then(() => fs.writeFile(srcPathScript('environment.d'), envDtsSource))
  325. .then(() => fs.writeFile(srcPathScript('index'), indexSource))
  326. .then(() => fs.writeFile(srcPathScript('index-worker'), indexWorkerSource))
  327. .then(() => fs.writeFile(path.join(serverRoot, 'README.md'), readmeSource))
  328. .then(() => fs.writeFile(path.join(serverRoot, 'Dockerfile'), dockerfileSource))
  329. .then(() => fs.writeFile(path.join(serverRoot, 'docker-compose.yml'), dockerComposeSource))
  330. .then(() => fs.ensureDir(path.join(serverRoot, 'src/plugins')))
  331. .then(() => fs.copyFile(assetPath('gitignore.template'), path.join(serverRoot, '.gitignore')))
  332. .then(() =>
  333. fs.copyFile(assetPath('tsconfig.template.json'), path.join(serverRoot, 'tsconfig.json')),
  334. )
  335. .then(() =>
  336. fs.writeFile(path.join(serverRoot, 'tsconfig.dashboard.json'), tsconfigDashboardSource),
  337. )
  338. .then(() => fs.writeFile(path.join(serverRoot, 'vite.config.mts'), viteConfigSource))
  339. .then(() => createDirectoryStructure(serverRoot))
  340. .then(() => copyEmailTemplates(serverRoot));
  341. } catch (e: any) {
  342. outro(pc.red(`Failed to create app scaffold: ${e.message as string}`));
  343. process.exit(1);
  344. }
  345. scaffoldSpinner.stop(`Generated app scaffold`);
  346. if (mode === 'quick' && dbType === 'postgres') {
  347. cleanUpDockerResources(name);
  348. await startPostgresDatabase(serverRoot);
  349. }
  350. const populateSpinner = spinner();
  351. populateSpinner.start(`Initializing your new Vendure server`);
  352. // We want to display a set of tips and instructions to the user
  353. // as the initialization process is running because it can take
  354. // a few minutes to complete.
  355. const tips = [
  356. populateProducts
  357. ? 'We are populating sample data so that you can start testing right away'
  358. : 'We are setting up your Vendure server',
  359. ...TIPS_WHILE_WAITING,
  360. ];
  361. let tipIndex = 0;
  362. let timer: any;
  363. function displayTip() {
  364. populateSpinner.message(tips[tipIndex]);
  365. tipIndex++;
  366. if (tipIndex >= tips.length) {
  367. // skip the intro tips if looping
  368. tipIndex = 3;
  369. }
  370. timer = setTimeout(displayTip, TIP_INTERVAL_MS);
  371. }
  372. timer = setTimeout(displayTip, TIP_INTERVAL_MS);
  373. // Change to serverRoot so that ts-node can correctly resolve modules.
  374. // In monorepo mode, dependencies are hoisted to the root node_modules,
  375. // but ts-node needs to be anchored in the server directory for proper
  376. // module resolution and to find the tsconfig.json.
  377. process.chdir(serverRoot);
  378. // register ts-node so that the config file can be loaded
  379. // We use transpileOnly to skip type checking during bootstrap, as the
  380. // complex module resolution with npm workspaces and ESM packages can
  381. // cause false TypeScript errors. Type checking happens when users run
  382. // their own build/dev commands.
  383. // eslint-disable-next-line @typescript-eslint/no-var-requires
  384. require(resolvePackageRootDir('ts-node', serverRoot)).register({
  385. project: path.join(serverRoot, 'tsconfig.json'),
  386. transpileOnly: true,
  387. });
  388. let superAdminCredentials: { identifier: string; password: string } | undefined;
  389. try {
  390. const { populate } = await import(
  391. path.join(resolvePackageRootDir('@vendure/core', serverRoot), 'cli', 'populate')
  392. );
  393. const { bootstrap, DefaultLogger, LogLevel, JobQueueService } = await import(
  394. path.join(resolvePackageRootDir('@vendure/core', serverRoot), 'dist', 'index')
  395. );
  396. const { config } = await import(configFile);
  397. const assetsDir = path.join(__dirname, '../assets');
  398. superAdminCredentials = config.authOptions.superadminCredentials;
  399. const initialDataPath = path.join(assetsDir, 'initial-data.json');
  400. const vendureLogLevel =
  401. logLevel === 'info' || logLevel === 'silent'
  402. ? LogLevel.Error
  403. : logLevel === 'verbose'
  404. ? LogLevel.Verbose
  405. : LogLevel.Info;
  406. const bootstrapFn = async () => {
  407. await checkDbConnection(config.dbConnectionOptions, serverRoot);
  408. const _app = await bootstrap({
  409. ...config,
  410. apiOptions: {
  411. ...(config.apiOptions ?? {}),
  412. port,
  413. },
  414. dbConnectionOptions: {
  415. ...config.dbConnectionOptions,
  416. synchronize: true,
  417. },
  418. logger: new DefaultLogger({ level: vendureLogLevel }),
  419. importExportOptions: {
  420. importAssetsDir: path.join(assetsDir, 'images'),
  421. },
  422. });
  423. await _app.get(JobQueueService).start();
  424. return _app;
  425. };
  426. const app = await populate(
  427. bootstrapFn,
  428. initialDataPath,
  429. populateProducts ? path.join(assetsDir, 'products.csv') : undefined,
  430. );
  431. // Pause to ensure the worker jobs have time to complete.
  432. if (isCi) {
  433. log('[CI] Pausing before close...');
  434. }
  435. await sleep(isCi ? CI_PAUSE_BEFORE_CLOSE_MS : NORMAL_PAUSE_BEFORE_CLOSE_MS);
  436. await app.close();
  437. if (isCi) {
  438. log('[CI] Pausing after close...');
  439. await sleep(CI_PAUSE_AFTER_CLOSE_MS);
  440. }
  441. populateSpinner.stop(`Server successfully initialized${populateProducts ? ' and populated' : ''}`);
  442. clearTimeout(timer);
  443. /**
  444. * This is currently disabled because I am running into issues actually getting the server
  445. * to quite properly in response to a SIGINT.
  446. * This means that the server runs, but cannot be ended, without forcefully
  447. * killing the process.
  448. *
  449. * Once this has been resolved, the following code can be re-enabled by
  450. * setting `autoRunServer` to `true`.
  451. */
  452. const autoRunServer = false;
  453. if (mode === 'quick' && autoRunServer) {
  454. // In quick-start mode, we want to now run the server and open up
  455. // a browser window to the Dashboard.
  456. try {
  457. const dashboardUrl = `http://localhost:${port}/dashboard`;
  458. const quickStartInstructions = [
  459. 'Use the following credentials to log in to the Dashboard:',
  460. `Username: ${pc.green(config.authOptions.superadminCredentials?.identifier)}`,
  461. `Password: ${pc.green(config.authOptions.superadminCredentials?.password)}`,
  462. `Open your browser and navigate to: ${pc.green(dashboardUrl)}`,
  463. '',
  464. ];
  465. note(quickStartInstructions.join('\n'));
  466. const npmCommand = os.platform() === 'win32' ? 'npm.cmd' : 'npm';
  467. let quickStartProcess: ChildProcess | undefined;
  468. try {
  469. quickStartProcess = spawn(npmCommand, ['run', 'dev'], {
  470. cwd: root,
  471. stdio: 'inherit',
  472. });
  473. } catch (e: any) {
  474. /* empty */
  475. }
  476. // process.stdin.resume();
  477. process.on('SIGINT', function () {
  478. displayOutro({
  479. root,
  480. name,
  481. superAdminCredentials,
  482. includeStorefront,
  483. serverPort: port,
  484. storefrontPort,
  485. });
  486. quickStartProcess?.kill('SIGINT');
  487. process.exit(0);
  488. });
  489. // Give enough time for the server to get up and running
  490. // before opening the window.
  491. await sleep(AUTO_RUN_DELAY_MS);
  492. try {
  493. await open(dashboardUrl, {
  494. newInstance: true,
  495. });
  496. } catch (e: any) {
  497. /* empty */
  498. }
  499. } catch (e: any) {
  500. log(pc.red(`Failed to start the server: ${e.message as string}`), {
  501. newline: 'after',
  502. level: 'verbose',
  503. });
  504. }
  505. } else {
  506. clearTimeout(timer);
  507. displayOutro({
  508. root,
  509. name,
  510. superAdminCredentials,
  511. includeStorefront,
  512. serverPort: port,
  513. storefrontPort,
  514. });
  515. process.exit(0);
  516. }
  517. } catch (e: any) {
  518. log(e.toString());
  519. outro(pc.red(`Failed to initialize server. Please try again.`));
  520. process.exit(1);
  521. }
  522. }
  523. /**
  524. * Returns the standard npm scripts for the server package.json.
  525. */
  526. function getServerPackageScripts(): Record<string, string> {
  527. return {
  528. 'dev:server': 'ts-node ./src/index.ts',
  529. 'dev:worker': 'ts-node ./src/index-worker.ts',
  530. 'dev:dashboard': 'vite --clearScreen false',
  531. dev: 'concurrently --kill-others npm:dev:*',
  532. build: 'tsc',
  533. 'build:dashboard': 'vite build',
  534. 'start:server': 'node ./dist/index.js',
  535. 'start:worker': 'node ./dist/index-worker.js',
  536. start: 'concurrently npm:start:*',
  537. };
  538. }
  539. interface InstallDependenciesOptions {
  540. dependencies: string[];
  541. isDevDependencies?: boolean;
  542. logLevel: CliLogLevel;
  543. cwd: string;
  544. spinnerMessage: string;
  545. successMessage: string;
  546. failureMessage: string;
  547. warnOnFailure?: boolean;
  548. }
  549. /**
  550. * Installs dependencies with a spinner, handling success/failure messaging.
  551. * Returns true if installation succeeded, false otherwise.
  552. */
  553. async function installDependenciesWithSpinner(installOptions: InstallDependenciesOptions): Promise<boolean> {
  554. const {
  555. dependencies,
  556. isDevDependencies = false,
  557. logLevel,
  558. cwd,
  559. spinnerMessage,
  560. successMessage,
  561. failureMessage,
  562. warnOnFailure = false,
  563. } = installOptions;
  564. const installSpinner = spinner();
  565. installSpinner.start(spinnerMessage);
  566. try {
  567. await installPackages({ dependencies, isDevDependencies, logLevel, cwd });
  568. installSpinner.stop(successMessage);
  569. return true;
  570. } catch (e) {
  571. if (warnOnFailure) {
  572. installSpinner.stop(pc.yellow(`Warning: ${failureMessage}`));
  573. return false;
  574. } else {
  575. outro(pc.red(failureMessage));
  576. process.exit(1);
  577. }
  578. }
  579. }
  580. interface OutroOptions {
  581. root: string;
  582. name: string;
  583. superAdminCredentials?: { identifier: string; password: string };
  584. includeStorefront?: boolean;
  585. serverPort?: number;
  586. storefrontPort?: number;
  587. }
  588. // eslint-disable-next-line @typescript-eslint/no-shadow
  589. function displayOutro(outroOptions: OutroOptions) {
  590. const {
  591. root,
  592. name,
  593. superAdminCredentials,
  594. includeStorefront,
  595. serverPort = SERVER_PORT,
  596. storefrontPort = STOREFRONT_PORT,
  597. } = outroOptions;
  598. const startCommand = 'npm run dev';
  599. const identifier = superAdminCredentials?.identifier ?? SUPER_ADMIN_USER_IDENTIFIER;
  600. const password = superAdminCredentials?.password ?? SUPER_ADMIN_USER_PASSWORD;
  601. // Common footer for both modes
  602. const commonFooter = [
  603. `\n`,
  604. `Use the following credentials to log in:`,
  605. `Username: ${pc.green(identifier)}`,
  606. `Password: ${pc.green(password)}`,
  607. '\n',
  608. '➡️ Docs: https://docs.vendure.io',
  609. '➡️ Discord community: https://vendure.io/community',
  610. '➡️ Star us on GitHub:',
  611. ' https://github.com/vendurehq/vendure',
  612. ];
  613. let nextSteps: string[];
  614. if (includeStorefront) {
  615. nextSteps = [
  616. `Your new Vendure project was created!`,
  617. pc.gray(root),
  618. `\n`,
  619. `This is a monorepo with the following apps:`,
  620. ` ${pc.cyan('apps/server')} - Vendure backend`,
  621. ` ${pc.cyan('apps/storefront')} - Next.js frontend`,
  622. `\n`,
  623. `Next, run:`,
  624. pc.gray('$ ') + pc.blue(pc.bold(`cd ${name}`)),
  625. pc.gray('$ ') + pc.blue(pc.bold(`${startCommand}`)),
  626. `\n`,
  627. `This will start both the server and storefront.`,
  628. `\n`,
  629. `Access points:`,
  630. ` Dashboard: ${pc.green(`http://localhost:${serverPort}/dashboard`)}`,
  631. ` Storefront: ${pc.green(`http://localhost:${storefrontPort}`)}`,
  632. ...commonFooter,
  633. ];
  634. } else {
  635. nextSteps = [
  636. `Your new Vendure server was created!`,
  637. pc.gray(root),
  638. `\n`,
  639. `Next, run:`,
  640. pc.gray('$ ') + pc.blue(pc.bold(`cd ${name}`)),
  641. pc.gray('$ ') + pc.blue(pc.bold(`${startCommand}`)),
  642. `\n`,
  643. `This will start the server in development mode.`,
  644. `\n`,
  645. `To run the Dashboard, in a new terminal navigate to your project directory and run:`,
  646. pc.gray('$ ') + pc.blue(pc.bold(`npx vite`)),
  647. `\n`,
  648. `To access the Dashboard, open your browser and navigate to:`,
  649. pc.green(`http://localhost:${serverPort}/dashboard`),
  650. ...commonFooter,
  651. ];
  652. }
  653. note(nextSteps.join('\n'), pc.green('Setup complete!'));
  654. outro(`Happy hacking!`);
  655. }
  656. /**
  657. * Run some initial checks to ensure that it is okay to proceed with creating
  658. * a new Vendure project in the given location.
  659. */
  660. function runPreChecks(name: string | undefined): name is string {
  661. if (typeof name === 'undefined') {
  662. log(pc.red(`Please specify the project directory:`));
  663. log(` ${pc.cyan(program.name())} ${pc.green('<project-directory>')}`, { newline: 'after' });
  664. log('For example:');
  665. log(` ${pc.cyan(program.name())} ${pc.green('my-vendure-app')}`);
  666. process.exit(1);
  667. return false;
  668. }
  669. const root = path.resolve(name);
  670. try {
  671. fs.ensureDirSync(name);
  672. } catch (e: any) {
  673. log(pc.red(`Could not create project directory ${name}: ${e.message as string}`));
  674. return false;
  675. }
  676. if (!isSafeToCreateProjectIn(root, name)) {
  677. process.exit(1);
  678. }
  679. return true;
  680. }
  681. /**
  682. * Generate the default directory structure for a new Vendure project
  683. */
  684. async function createDirectoryStructure(root: string) {
  685. await fs.ensureDir(path.join(root, 'static', 'email', 'test-emails'));
  686. await fs.ensureDir(path.join(root, 'static', 'assets'));
  687. }
  688. /**
  689. * Copy the email templates into the app
  690. */
  691. async function copyEmailTemplates(root: string) {
  692. const emailPackageDirname = resolvePackageRootDir('@vendure/email-plugin', root);
  693. const templateDir = path.join(emailPackageDirname, 'templates');
  694. try {
  695. await fs.copy(templateDir, path.join(root, 'static', 'email', 'templates'));
  696. } catch (err: any) {
  697. log(pc.red('Failed to copy email templates.'));
  698. log(err);
  699. process.exit(0);
  700. }
  701. }