<commit_before>import path from 'path';
import fse from 'fs-extra';
import { DefinePlugin, Configuration } from 'webpack';
import Dotenv from 'dotenv-webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import CaseSensitivePathsPlugin from 'case-sensitive-paths-webpack-plugin';
import PnpWebpackPlugin from 'pnp-webpack-plugin';
import VirtualModulePlugin from 'webpack-virtual-modules';
import TerserWebpackPlugin from 'terser-webpack-plugin';

import themingPaths from '@storybook/theming/paths';
import uiPaths from '@storybook/ui/paths';

import readPackage from 'read-pkg-up';
import { getManagerHeadHtml } from '../utils/template';
import { loadEnv } from '../config/utils';

import { babelLoader } from './babel-loader-manager';
import { resolvePathInStorybookCache } from '../utils/resolve-path-in-sb-cache';
import { es6Transpiler } from '../common/es6Transpiler';
import { ManagerWebpackOptions } from '../types';

export default async ({
  configDir,
  configType,
  docsMode,
  entries,
  refs,
  outputDir,
  cache,
  previewUrl,
  versionCheck,
  releaseNotesData,
  presets,
}: ManagerWebpackOptions): Promise<Configuration> => {
  const { raw, stringified } = loadEnv();
  const logLevel = await presets.apply('logLevel', undefined);
  const isProd = configType === 'PRODUCTION';
  const refsTemplate = fse.readFileSync(path.join(__dirname, 'virtualModuleRef.template.js'), {
    encoding: 'utf8',
  });
  const {
    packageJson: { version },
  } = await readPackage({ cwd: __dirname });

  // @ts-ignore
  // eslint-disable-next-line import/no-extraneous-dependencies
  const { BundleAnalyzerPlugin } = await import('webpack-bundle-analyzer').catch(() => ({}));

  return {
    name: 'manager',
    mode: isProd ? 'production' : 'development',
    bail: isProd,
    // FIXME: `none` is not a valid option for devtool
    // @ts-ignore
    devtool: 'none',
    entry: entries,
    output: {
      path: outputDir,
      filename: '[name].[chunkhash].bundle.js',
      publicPath: '',
    },
    cache,
    plugins: [
      refs
        ? new VirtualModulePlugin({
            [path.resolve(path.join(configDir, `generated-refs.js`))]: refsTemplate.replace(
              `'{{refs}}'`,
              JSON.stringify(refs)
            ),
          })
        : null,
      new HtmlWebpackPlugin({
        filename: `index.html`,
        // FIXME: `none` isn't a known option
        chunksSortMode: 'none' as any,
        alwaysWriteToDisk: true,
        inject: false,
        templateParameters: (compilation, files, options) => ({
          compilation,
          files,
          options,
          version,
          globals: {
            CONFIG_TYPE: configType,
            LOGLEVEL: logLevel,
            VERSIONCHECK: JSON.stringify(versionCheck),
            RELEASE_NOTES_DATA: JSON.stringify(releaseNotesData),
            DOCS_MODE: docsMode, // global docs mode
            PREVIEW_URL: previewUrl, // global preview URL
          },
          headHtmlSnippet: getManagerHeadHtml(configDir, process.env),
        }),
        template: require.resolve(`../templates/index.ejs`),
      }),
      new CaseSensitivePathsPlugin(),
      new Dotenv({ silent: true }),
      // graphql sources check process variable
      new DefinePlugin({
        'process.env': stringified,
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
      }),
      BundleAnalyzerPlugin &&
        new BundleAnalyzerPlugin({
          analyzerMode: isProd ? 'static' : 'server',
          analyzerPort: 'auto',
          openAnalyzer: false,
        }),
    ].filter(Boolean),
    module: {
      rules: [
        babelLoader(),
        es6Transpiler(),
        {<commit_msg>Don't include bundle analyzer when starting manager server.<commit_after>import path from 'path';
import fse from 'fs-extra';
import { DefinePlugin, Configuration } from 'webpack';
import Dotenv from 'dotenv-webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import CaseSensitivePathsPlugin from 'case-sensitive-paths-webpack-plugin';
import PnpWebpackPlugin from 'pnp-webpack-plugin';
import VirtualModulePlugin from 'webpack-virtual-modules';
import TerserWebpackPlugin from 'terser-webpack-plugin';

import themingPaths from '@storybook/theming/paths';
import uiPaths from '@storybook/ui/paths';

import readPackage from 'read-pkg-up';
import { getManagerHeadHtml } from '../utils/template';
import { loadEnv } from '../config/utils';

import { babelLoader } from './babel-loader-manager';
import { resolvePathInStorybookCache } from '../utils/resolve-path-in-sb-cache';
import { es6Transpiler } from '../common/es6Transpiler';
import { ManagerWebpackOptions } from '../types';

export default async ({
  configDir,
  configType,
  docsMode,
  entries,
  refs,
  outputDir,
  cache,
  previewUrl,
  versionCheck,
  releaseNotesData,
  presets,
}: ManagerWebpackOptions): Promise<Configuration> => {
  const { raw, stringified } = loadEnv();
  const logLevel = await presets.apply('logLevel', undefined);
  const isProd = configType === 'PRODUCTION';
  const refsTemplate = fse.readFileSync(path.join(__dirname, 'virtualModuleRef.template.js'), {
    encoding: 'utf8',
  });
  const {
    packageJson: { version },
  } = await readPackage({ cwd: __dirname });

  // @ts-ignore
  // eslint-disable-next-line import/no-extraneous-dependencies
  const { BundleAnalyzerPlugin } = await import('webpack-bundle-analyzer').catch(() => ({}));

  return {
    name: 'manager',
    mode: isProd ? 'production' : 'development',
    bail: isProd,
    // FIXME: `none` is not a valid option for devtool
    // @ts-ignore
    devtool: 'none',
    entry: entries,
    output: {
      path: outputDir,
      filename: '[name].[chunkhash].bundle.js',
      publicPath: '',
    },
    cache,
    plugins: [
      refs
        ? new VirtualModulePlugin({
            [path.resolve(path.join(configDir, `generated-refs.js`))]: refsTemplate.replace(
              `'{{refs}}'`,
              JSON.stringify(refs)
            ),
          })
        : null,
      new HtmlWebpackPlugin({
        filename: `index.html`,
        // FIXME: `none` isn't a known option
        chunksSortMode: 'none' as any,
        alwaysWriteToDisk: true,
        inject: false,
        templateParameters: (compilation, files, options) => ({
          compilation,
          files,
          options,
          version,
          globals: {
            CONFIG_TYPE: configType,
            LOGLEVEL: logLevel,
            VERSIONCHECK: JSON.stringify(versionCheck),
            RELEASE_NOTES_DATA: JSON.stringify(releaseNotesData),
            DOCS_MODE: docsMode, // global docs mode
            PREVIEW_URL: previewUrl, // global preview URL
          },
          headHtmlSnippet: getManagerHeadHtml(configDir, process.env),
        }),
        template: require.resolve(`../templates/index.ejs`),
      }),
      new CaseSensitivePathsPlugin(),
      new Dotenv({ silent: true }),
      // graphql sources check process variable
      new DefinePlugin({
        'process.env': stringified,
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
      }),
      isProd &&
        BundleAnalyzerPlugin &&
        new BundleAnalyzerPlugin({ analyzerMode: 'static', openAnalyzer: false }),
    ].filter(Boolean),
    module: {
      rules: [
        babelLoader(),
        es6Transpiler(),
        {
{'fraction_non_alphanumeric': 0.12718881498574724, 'fraction_numerical': 0.0010859237138591013, 'mean_word_length': 2.8195956454121305, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2886775', 'n_tokens_mistral': 2149, 'n_tokens_neox': 2096, 'n_words': 494}