create-vendure-app.ts 28 KB

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