helpers.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. /* tslint:disable:no-console */
  2. import chalk from 'chalk';
  3. import { execSync } from 'child_process';
  4. import spawn from 'cross-spawn';
  5. import fs from 'fs-extra';
  6. import path from 'path';
  7. import semver from 'semver';
  8. import { SERVER_PORT, TYPESCRIPT_VERSION } from './constants';
  9. import { CliLogLevel, DbType } from './types';
  10. /**
  11. * If project only contains files generated by GH, it’s safe.
  12. * Also, if project contains remnant error logs from a previous
  13. * installation, lets remove them now.
  14. * We also special case IJ-based products .idea because it integrates with CRA:
  15. * https://github.com/facebook/create-react-app/pull/368#issuecomment-243446094
  16. */
  17. export function isSafeToCreateProjectIn(root: string, name: string) {
  18. // These files should be allowed to remain on a failed install,
  19. // but then silently removed during the next create.
  20. const errorLogFilePatterns = ['npm-debug.log', 'yarn-error.log', 'yarn-debug.log'];
  21. const validFiles = [
  22. '.DS_Store',
  23. 'Thumbs.db',
  24. '.git',
  25. '.gitignore',
  26. '.idea',
  27. 'README.md',
  28. 'LICENSE',
  29. '.hg',
  30. '.hgignore',
  31. '.hgcheck',
  32. '.npmignore',
  33. 'mkdocs.yml',
  34. 'docs',
  35. '.travis.yml',
  36. '.gitlab-ci.yml',
  37. '.gitattributes',
  38. 'migration.ts',
  39. 'node_modules',
  40. 'package.json',
  41. 'package-lock.json',
  42. 'src',
  43. 'static',
  44. 'tsconfig.json',
  45. 'yarn.lock',
  46. ];
  47. console.log();
  48. const conflicts = fs
  49. .readdirSync(root)
  50. .filter(file => !validFiles.includes(file))
  51. // IntelliJ IDEA creates module files before CRA is launched
  52. .filter(file => !/\.iml$/.test(file))
  53. // Don't treat log files from previous installation as conflicts
  54. .filter(file => !errorLogFilePatterns.some(pattern => file.indexOf(pattern) === 0));
  55. if (conflicts.length > 0) {
  56. console.log(`The directory ${chalk.green(name)} contains files that could conflict:`);
  57. console.log();
  58. for (const file of conflicts) {
  59. console.log(` ${file}`);
  60. }
  61. console.log();
  62. console.log('Either try using a new directory name, or remove the files listed above.');
  63. return false;
  64. }
  65. // Remove any remnant files from a previous installation
  66. const currentFiles = fs.readdirSync(path.join(root));
  67. currentFiles.forEach(file => {
  68. errorLogFilePatterns.forEach(errorLogFilePattern => {
  69. // This will catch `(npm-debug|yarn-error|yarn-debug).log*` files
  70. if (file.indexOf(errorLogFilePattern) === 0) {
  71. fs.removeSync(path.join(root, file));
  72. }
  73. });
  74. });
  75. return true;
  76. }
  77. export function scaffoldAlreadyExists(root: string, name: string): boolean {
  78. const scaffoldFiles = ['migration.ts', 'package.json', 'tsconfig.json', 'README.md'];
  79. const files = fs.readdirSync(root);
  80. return scaffoldFiles.every(scaffoldFile => files.includes(scaffoldFile));
  81. }
  82. export function checkNodeVersion(requiredVersion: string) {
  83. if (!semver.satisfies(process.version, requiredVersion)) {
  84. console.error(
  85. chalk.red(
  86. 'You are running Node %s.\n' +
  87. 'Vendure requires Node %s or higher. \n' +
  88. 'Please update your version of Node.',
  89. ),
  90. process.version,
  91. requiredVersion,
  92. );
  93. process.exit(1);
  94. }
  95. }
  96. export function shouldUseYarn() {
  97. try {
  98. execSync('yarnpkg --version', { stdio: 'ignore' });
  99. return true;
  100. } catch (e: any) {
  101. return false;
  102. }
  103. }
  104. export function checkThatNpmCanReadCwd() {
  105. const cwd = process.cwd();
  106. let childOutput = null;
  107. try {
  108. // Note: intentionally using spawn over exec since
  109. // the problem doesn't reproduce otherwise.
  110. // `npm config list` is the only reliable way I could find
  111. // to reproduce the wrong path. Just printing process.cwd()
  112. // in a Node process was not enough.
  113. childOutput = spawn.sync('npm', ['config', 'list']).output.join('');
  114. } catch (err: any) {
  115. // Something went wrong spawning node.
  116. // Not great, but it means we can't do this check.
  117. // We might fail later on, but let's continue.
  118. return true;
  119. }
  120. if (typeof childOutput !== 'string') {
  121. return true;
  122. }
  123. const lines = childOutput.split('\n');
  124. // `npm config list` output includes the following line:
  125. // "; cwd = C:\path\to\current\dir" (unquoted)
  126. // I couldn't find an easier way to get it.
  127. const prefix = '; cwd = ';
  128. const line = lines.find(l => l.indexOf(prefix) === 0);
  129. if (typeof line !== 'string') {
  130. // Fail gracefully. They could remove it.
  131. return true;
  132. }
  133. const npmCWD = line.substring(prefix.length);
  134. if (npmCWD === cwd) {
  135. return true;
  136. }
  137. console.error(
  138. chalk.red(
  139. `Could not start an npm process in the right directory.\n\n` +
  140. `The current directory is: ${chalk.bold(cwd)}\n` +
  141. `However, a newly started npm process runs in: ${chalk.bold(npmCWD)}\n\n` +
  142. `This is probably caused by a misconfigured system terminal shell.`,
  143. ),
  144. );
  145. if (process.platform === 'win32') {
  146. console.error(
  147. chalk.red(`On Windows, this can usually be fixed by running:\n\n`) +
  148. ` ${chalk.cyan(
  149. 'reg',
  150. )} delete "HKCU\\Software\\Microsoft\\Command Processor" /v AutoRun /f\n` +
  151. ` ${chalk.cyan(
  152. 'reg',
  153. )} delete "HKLM\\Software\\Microsoft\\Command Processor" /v AutoRun /f\n\n` +
  154. chalk.red(`Try to run the above two lines in the terminal.\n`) +
  155. chalk.red(
  156. `To learn more about this problem, read: https://blogs.msdn.microsoft.com/oldnewthing/20071121-00/?p=24433/`,
  157. ),
  158. );
  159. }
  160. return false;
  161. }
  162. /**
  163. * Install packages via npm or yarn.
  164. * Based on the install function from https://github.com/facebook/create-react-app
  165. */
  166. export function installPackages(
  167. root: string,
  168. useYarn: boolean,
  169. dependencies: string[],
  170. isDev: boolean,
  171. logLevel: CliLogLevel,
  172. isCi: boolean = false,
  173. ): Promise<void> {
  174. return new Promise((resolve, reject) => {
  175. let command: string;
  176. let args: string[];
  177. if (useYarn) {
  178. command = 'yarnpkg';
  179. args = ['add', '--exact', '--ignore-engines'];
  180. if (isDev) {
  181. args.push('--dev');
  182. }
  183. if (isCi) {
  184. // In CI, publish to Verdaccio
  185. // See https://github.com/yarnpkg/yarn/issues/6029
  186. args.push('--registry http://localhost:4873/');
  187. // Increase network timeout
  188. // See https://github.com/yarnpkg/yarn/issues/4890#issuecomment-358179301
  189. args.push('--network-timeout 300000');
  190. }
  191. args = args.concat(dependencies);
  192. // Explicitly set cwd() to work around issues like
  193. // https://github.com/facebook/create-react-app/issues/3326.
  194. // Unfortunately we can only do this for Yarn because npm support for
  195. // equivalent --prefix flag doesn't help with this issue.
  196. // This is why for npm, we run checkThatNpmCanReadCwd() early instead.
  197. args.push('--cwd');
  198. args.push(root);
  199. } else {
  200. command = 'npm';
  201. args = ['install', '--save', '--save-exact', '--loglevel', 'error'].concat(dependencies);
  202. if (isDev) {
  203. args.push('--save-dev');
  204. }
  205. }
  206. if (logLevel === 'verbose') {
  207. args.push('--verbose');
  208. }
  209. const child = spawn(command, args, { stdio: logLevel === 'silent' ? 'ignore' : 'inherit' });
  210. child.on('close', code => {
  211. if (code !== 0) {
  212. let message = 'An error occurred when installing dependencies.';
  213. if (logLevel === 'silent') {
  214. message += ' Try running with `--log-level info` or `--log-level verbose` to diagnose.';
  215. }
  216. reject({
  217. message,
  218. command: `${command} ${args.join(' ')}`,
  219. });
  220. return;
  221. }
  222. resolve();
  223. });
  224. });
  225. }
  226. export function getDependencies(
  227. dbType: DbType,
  228. vendurePkgVersion = '',
  229. ): { dependencies: string[]; devDependencies: string[] } {
  230. const dependencies = [
  231. `@vendure/core${vendurePkgVersion}`,
  232. `@vendure/email-plugin${vendurePkgVersion}`,
  233. `@vendure/asset-server-plugin${vendurePkgVersion}`,
  234. `@vendure/admin-ui-plugin${vendurePkgVersion}`,
  235. dbDriverPackage(dbType),
  236. `typescript@${TYPESCRIPT_VERSION}`,
  237. ];
  238. const devDependencies = ['concurrently', 'dotenv', 'ts-node'];
  239. return { dependencies, devDependencies };
  240. }
  241. /**
  242. * Returns the name of the npm driver package for the
  243. * selected database.
  244. */
  245. function dbDriverPackage(dbType: DbType): string {
  246. switch (dbType) {
  247. case 'mysql':
  248. case 'mariadb':
  249. return 'mysql';
  250. case 'postgres':
  251. return 'pg';
  252. case 'sqlite':
  253. return 'better-sqlite3';
  254. case 'sqljs':
  255. return 'sql.js';
  256. case 'mssql':
  257. return 'mssql';
  258. case 'oracle':
  259. return 'oracledb';
  260. default:
  261. const n: never = dbType;
  262. console.error(chalk.red(`No driver package configured for type "${dbType}"`));
  263. return '';
  264. }
  265. }
  266. /**
  267. * Checks that the specified DB connection options are working (i.e. a connection can be
  268. * established) and that the named database exists.
  269. */
  270. export function checkDbConnection(options: any, root: string): Promise<true> {
  271. switch (options.type) {
  272. case 'mysql':
  273. return checkMysqlDbExists(options, root);
  274. case 'postgres':
  275. return checkPostgresDbExists(options, root);
  276. default:
  277. return Promise.resolve(true);
  278. }
  279. }
  280. async function checkMysqlDbExists(options: any, root: string): Promise<true> {
  281. const mysql = await import(path.join(root, 'node_modules/mysql'));
  282. const connectionOptions = {
  283. host: options.host,
  284. user: options.username,
  285. password: options.password,
  286. port: options.port,
  287. database: options.database,
  288. };
  289. const connection = mysql.createConnection(connectionOptions);
  290. return new Promise<boolean>((resolve, reject) => {
  291. connection.connect((err: any) => {
  292. if (err) {
  293. if (err.code === 'ER_BAD_DB_ERROR') {
  294. throwDatabaseDoesNotExist(options.database);
  295. }
  296. throwConnectionError(err);
  297. }
  298. resolve(true);
  299. });
  300. }).then(() => {
  301. return new Promise((resolve, reject) => {
  302. connection.end((err: any) => {
  303. resolve(true);
  304. });
  305. });
  306. });
  307. }
  308. async function checkPostgresDbExists(options: any, root: string): Promise<true> {
  309. const { Client } = await import(path.join(root, 'node_modules/pg'));
  310. const connectionOptions = {
  311. host: options.host,
  312. user: options.username,
  313. password: options.password,
  314. port: options.port,
  315. database: options.database,
  316. schema: options.schema,
  317. };
  318. const client = new Client(connectionOptions);
  319. try {
  320. await client.connect();
  321. const schema = await client.query(
  322. `SELECT schema_name FROM information_schema.schemata WHERE schema_name = '${options.schema}'`,
  323. );
  324. if (schema.rows.length === 0) {
  325. throw new Error('NO_SCHEMA');
  326. }
  327. } catch (e: any) {
  328. if (e.code === '3D000') {
  329. throwDatabaseDoesNotExist(options.database);
  330. } else if (e.message === 'NO_SCHEMA') {
  331. throwDatabaseSchemaDoesNotExist(options.database, options.schema);
  332. }
  333. throwConnectionError(e);
  334. await client.end();
  335. throw e;
  336. }
  337. await client.end();
  338. return true;
  339. }
  340. function throwConnectionError(err: any) {
  341. throw new Error(
  342. `Could not connect to the database. ` +
  343. `Please check the connection settings in your Vendure config.\n[${
  344. err.message || err.toString()
  345. }]`,
  346. );
  347. }
  348. function throwDatabaseDoesNotExist(name: string) {
  349. throw new Error(`Database "${name}" does not exist. Please create the database and then try again.`);
  350. }
  351. function throwDatabaseSchemaDoesNotExist(dbName: string, schemaName: string) {
  352. throw new Error(
  353. `Schema "${dbName}.${schemaName}" does not exist. Please create the schema "${schemaName}" and then try again.`,
  354. );
  355. }
  356. export async function isServerPortInUse(): Promise<boolean> {
  357. const tcpPortUsed = require('tcp-port-used');
  358. try {
  359. return tcpPortUsed.check(SERVER_PORT);
  360. } catch (e: any) {
  361. console.log(chalk.yellow(`Warning: could not determine whether port ${SERVER_PORT} is available`));
  362. return false;
  363. }
  364. }