1import chalk from 'chalk';
2import { promisify } from 'util';
3import type webpack from 'webpack';
4
5import { formatWebpackMessages } from './formatWebpackMessages';
6import * as Log from '../../../log';
7import { CommandError } from '../../../utils/errors';
8
9/** Run the `webpack` compiler and format errors/warnings. */
10export async function compileAsync(compiler: webpack.Compiler) {
11  const stats = await promisify(compiler.run.bind(compiler))();
12  const { errors, warnings } = formatWebpackMessages(
13    stats.toJson({ all: false, warnings: true, errors: true })
14  );
15  if (errors?.length) {
16    // Only keep the first error. Others are often indicative
17    // of the same problem, but confuse the reader with noise.
18    if (errors.length > 1) {
19      errors.length = 1;
20    }
21    throw new CommandError('WEBPACK_BUNDLE', errors.join('\n\n'));
22  }
23  if (warnings?.length) {
24    Log.warn(chalk.yellow('Compiled with warnings\n'));
25    Log.warn(warnings.join('\n\n'));
26  } else {
27    Log.log(chalk.green('Compiled successfully'));
28  }
29
30  return { errors, warnings };
31}
32