"use strict";

var _path = _interopRequireDefault(require("path"));

var _utils = require("../utils");

var _common = require("../common");

var _pluginUtils = require("../pluginUtils");

var _loaderUtils = require("../loaderUtils");

var _configsAssetsLoaders = require("../loaderUtils/configsAssetsLoaders");

var _resolvers = require("./resolvers");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

// import TerserPlugin from 'terser-webpack-plugin';
const options = (0, _utils.getOptions)();
const {
  app: {
    folder,
    context,
    outputFolder,
    disableES5Transpile,
    removeAttribute,
    enableSMap,
    server,
    plugins,
    exclude,
    patterns,
    mediaQueryHoverActiveString,
    cssVariableReplacementConfig,
    selectorWeightConfig,
    cssUniqueness,
    customClassNamePrefix,
    server: {
      mode
    },
    seperateCssModules,
    changeRuntimeChunkChar,
    cssHashSelectors,
    classNamePrefix,
    selectorReplace,
    removePropTypes,
    devConsoleExculde,
    crossorigin,
    postCssPluginOrder,
    externals
  }
} = options;
let {
  enableChunkHash
} = options.app;
const appPath = process.cwd();
const isDevelopment = mode === 'prod' || mode === 'dev' || mode === 'dev-no-warn';
enableChunkHash = !isDevelopment && enableChunkHash;
const output = {
  path: _path.default.resolve(appPath, outputFolder),
  filename: enableChunkHash ? 'js/[name].[chunkhash:20]_.js' : 'js/[name]_.js',
  chunkFilename: enableChunkHash ? 'js/[name].[chunkhash:20]_.js' : 'js/[name]_.js',
  jsonpFunction: `${context}Jsonp`,
  sourceMapFilename: enableChunkHash ? 'js/[name].[chunkhash:20]_.js.map' : 'js/[name]_.js.map'
};

if (crossorigin) {
  output.crossOriginLoading = 'anonymous';
}

if (isDevelopment) {
  const {
    disableContextURL
  } = server;
  const contextURL = disableContextURL ? '' : context;
  const serverUrl = (0, _utils.getServerURL)(server, 'https');
  output.publicPath = `${[serverUrl, contextURL].filter(a => a).join('/')}/`;
}

const shouldRemovePropTypes = !isDevelopment && removePropTypes;
module.exports = {
  entry: (0, _common.getEntries)(options, 'production'),
  devtool: isDevelopment ? 'cheap-module-source-map' : enableSMap ? 'hidden-source-map' : 'none',
  mode: 'production',
  output,
  optimization: {
    splitChunks: _common.splitChunks,
    runtimeChunk: {
      name: entrypoint => changeRuntimeChunkChar ? `./runtime-${entrypoint.name}` : `./runtime~${entrypoint.name}`
    },
    concatenateModules: true,
    minimize: true,
    // by  default if  minimize: true in webpack minimize then webpack automaticaly add TerserPlugin,
    //  So we are overrideing it.
    // minimizer: [
    //   new TerserPlugin({
    //     cache: true,
    //     parallel: true,
    //     sourceMap: isDevelopment && enableSMap,
    //     exclude: /\/smap/
    //   })
    // ],
    moduleIds: 'named'
  },
  stats: {
    children: false,
    colors: true,
    // excludeAssets: /i18n/,
    // excludeAssets: /./,
    warningsFilter: /\[mini-css-extract-plugin\]/
  },
  plugins: (0, _pluginUtils.getProdPlugins)(options, output.publicPath),
  module: {
    /* strictExportPresence for break the build when imported module not present in respective file */
    strictExportPresence: true,
    rules: [{
      test: /\.js$/,
      use: [{
        loader: 'babel-loader',
        options: {
          presets: [[require.resolve('@babel/preset-env'), disableES5Transpile ? {
            modules: false,
            useBuiltIns: 'usage',
            corejs: 3,
            targets: {
              browsers: ['last 3 Chrome versions', 'last 3 Firefox versions', 'last 3 Edge versions', 'last 3 Safari versions']
            }
          } : {
            modules: false
          }], require.resolve('@babel/preset-react')],
          plugins: disableES5Transpile ? [removeAttribute ? require.resolve('../utils/removeAttributes') : false, require.resolve('@babel/plugin-syntax-dynamic-import'), require.resolve('babel-plugin-lodash'), require.resolve('@babel/plugin-proposal-object-rest-spread'), devConsoleExculde ? [require.resolve('babel-plugin-transform-remove-console'), {
            exclude: ['error', 'log']
          }] : null].filter(Boolean) : [removeAttribute ? require.resolve('../utils/removeAttributes') : false, shouldRemovePropTypes ? [require.resolve('babel-plugin-transform-react-remove-prop-types'), removePropTypes] : false, [require.resolve('@babel/plugin-transform-runtime'), {
            helpers: true,
            regenerator: false
          }], require.resolve('@babel/plugin-proposal-object-rest-spread'), require.resolve('@babel/plugin-syntax-dynamic-import'), require.resolve('babel-plugin-lodash'), devConsoleExculde ? [require.resolve('babel-plugin-transform-remove-console'), {
            exclude: ['error', 'log']
          }] : null].filter(Boolean),
          cacheDirectory: true
        }
      }].filter(Boolean),
      // include: path.join(appPath, folder)
      include: module => {
        const srcPath = _path.default.join(appPath, folder);

        const depsPath = _path.default.join(appPath, 'node_modules', '@zohodesk');

        if (module.includes(srcPath) || devConsoleExculde && module.includes(depsPath)) {
          return true;
        }

        return false;
      }
    }, seperateCssModules ? {
      test: /\.css$/,
      exclude: /\.module\.css$/,
      use: (0, _loaderUtils.getCSSLoaders)({
        plugins,
        exclude,
        patterns,
        cssVariableReplacementConfig,
        selectorWeightConfig,
        mediaQueryHoverActiveString,
        classNameBlob: '[local]',
        cssUniqueness: false,
        customClassNamePrefix,
        selectorReplace: null,
        postCssPluginOrder
      })
    } : null, {
      test: seperateCssModules ? /\.module\.css$/ : /\.css$/,
      use: (0, _loaderUtils.getCSSLoaders)({
        plugins,
        exclude,
        patterns,
        mediaQueryHoverActiveString,
        cssVariableReplacementConfig,
        selectorWeightConfig,
        classNameBlob: false,
        cssUniqueness,
        customClassNamePrefix,
        selectorReplace,
        cssHashSelectors,
        classNamePrefix,
        postCssPluginOrder
      })
    }, {
      test: /\.jpe?g$|\.gif$|\.png$/,
      use: [{
        loader: 'url-loader',
        options: {
          limit: 1000,
          name: enableChunkHash ? './images/[name].[hash:20].[ext]' : './images/[name].[ext]',
          fallback: _path.default.join(__dirname, '..', 'loaders', 'fileLoader.js')
        }
      }]
    }, (0, _configsAssetsLoaders.configVideoLoaderObj)(enableChunkHash ? './videos/[name].[hash:20].[ext]' : './videos/[name].[ext]'), {
      test: /\.woff2|\.woff$|\.ttf$|\.eot$/,
      use: [{
        loader: 'url-loader',
        options: {
          limit: 1000,
          name: enableChunkHash ? './fonts/[name].[hash:20].[ext]' : './fonts/[name].[ext]',
          fallback: _path.default.join(__dirname, '..', 'loaders', 'fileLoader.js')
        }
      }]
    }, {
      test: /\.svg$/,
      use: [{
        loader: 'url-loader',
        options: {
          limit: 1,
          name: enableChunkHash ? './fonts/[name].[hash:20].[ext]' : './fonts/[name].[ext]',
          fallback: _path.default.join(__dirname, '..', 'loaders', 'fileLoader.js')
        }
      }]
    }, {
      test: /\.ogg$/,
      use: [{
        loader: 'file-loader',
        options: {
          name: enableChunkHash ? './fonts/[name].[hash:20].[ext]' : './fonts/[name].[ext]'
        }
      }]
    }, {
      test: /\.tmpl$/,
      use: [{
        loader: 'html-loader',
        options: {
          minimize: false
        }
      }]
    }, {
      test: /\.worker.js$/,
      use: {
        loader: require.resolve('../loaders/workerLoader.js'),
        options: {
          esModule: true,
          filename: 'js/[name].[chunkhash:20].js'
        }
      }
    }].filter(Boolean)
  },
  externals: Object.assign({
    ZC: '$ZC'
  }, externals),
  resolve: (0, _resolvers.moduleResolver)(options),
  resolveLoader: (0, _resolvers.loaderResolver)(options)
};