"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = createWebpackConfig;
function _lodash() {
  const data = require("lodash");
  _lodash = function () {
    return data;
  };
  return data;
}
function _webpack() {
  const data = _interopRequireDefault(require("webpack"));
  _webpack = function () {
    return data;
  };
  return data;
}
function _miniCssExtractPlugin() {
  const data = _interopRequireDefault(require("mini-css-extract-plugin"));
  _miniCssExtractPlugin = function () {
    return data;
  };
  return data;
}
function _webpackManifestPlugin() {
  const data = require("webpack-manifest-plugin");
  _webpackManifestPlugin = function () {
    return data;
  };
  return data;
}
function _workboxWebpackPlugin() {
  const data = _interopRequireDefault(require("workbox-webpack-plugin"));
  _workboxWebpackPlugin = function () {
    return data;
  };
  return data;
}
function _getCSSModuleLocalIdent() {
  const data = _interopRequireDefault(require("react-dev-utils/getCSSModuleLocalIdent"));
  _getCSSModuleLocalIdent = function () {
    return data;
  };
  return data;
}
function _path() {
  const data = _interopRequireDefault(require("path"));
  _path = function () {
    return data;
  };
  return data;
}
function stylesRegexps() {
  const data = _interopRequireWildcard(require("@teambit/webpack.modules.style-regexps"));
  stylesRegexps = function () {
    return data;
  };
  return data;
}
function _webpackModules2() {
  const data = require("@teambit/webpack.modules.generate-style-loaders");
  _webpackModules2 = function () {
    return data;
  };
  return data;
}
function _webpack2() {
  const data = require("@teambit/webpack");
  _webpack2 = function () {
    return data;
  };
  return data;
}
function _postcss() {
  const data = require("./postcss.config");
  _postcss = function () {
    return data;
  };
  return data;
}
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
const baseStyleLoadersOptions = {
  injectingLoader: _miniCssExtractPlugin().default.loader,
  cssLoaderPath: require.resolve('css-loader'),
  postCssLoaderPath: require.resolve('postcss-loader'),
  postCssConfig: _postcss().postCssConfig
};
const moduleFileExtensions = ['web.mjs', 'mjs', 'web.js', 'js', 'web.ts', 'ts', 'web.tsx', 'tsx', 'json', 'web.jsx', 'jsx'];

// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
const imageInlineSizeLimit = parseInt(process.env.IMAGE_INLINE_SIZE_LIMIT || '10000');
const isEnvProduction = true;

// This is the production and development configuration.
// It is focused on developer experience, fast rebuilds, and a minimal bundle.
// eslint-disable-next-line complexity
function createWebpackConfig(outputDir, entryFiles, publicDir = 'public') {
  // Variable used for enabling profiling in Production
  // passed into alias object. Uses a flag if passed into the build command
  const isEnvProductionProfile = process.argv.includes('--profile');

  // We will provide `paths.publicUrlOrPath` to our app
  // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
  // Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
  // Get environment variables to inject into our app.
  // const env = getClientEnvironment(publicUrlOrPath.slice(0, -1));

  return {
    stats: {
      children: true,
      errorDetails: true
    },
    mode: 'production',
    entry: {
      main: entryFiles
    },
    output: {
      // The build folder.
      path: _path().default.join(outputDir, publicDir),
      // default value

      filename: 'static/js/[name].[contenthash:8].js',
      // TODO: remove this when upgrading to webpack 5
      // futureEmitAssets: true,
      // There are also additional JS chunk files if you use code splitting.
      chunkFilename: 'static/js/[name].[contenthash:8].chunk.js'
      // this defaults to 'window', but by setting it to 'this' then
      // module chunks which are built will work in web workers as well.
      // Commented out to use the default (self) as according to tobias with webpack5 self is working with workers as well
      // globalObject: 'this',
    },
    resolve: {
      // These are the reasonable defaults supported by the Node ecosystem.
      // We also include JSX as a common component filename extension to support
      // some tools, although we do not recommend using it, see:
      // https://github.com/facebook/create-react-app/issues/290
      // `web` extension prefixes have been added for better support
      // for React Native Web.
      extensions: moduleFileExtensions.map(ext => `.${ext}`),
      alias: _objectSpread({
        // TODO: @uri please remember to remove after publishing evangelist and base-ui
        'react/jsx-runtime': require.resolve('react/jsx-runtime'),
        react: require.resolve('react'),
        'react-dom/server': require.resolve('react-dom/server'),
        'react-dom': require.resolve('react-dom')
      }, isEnvProductionProfile && {
        'react-dom$': 'react-dom/profiling',
        'scheduler/tracing': 'scheduler/tracing-profiling'
      }),
      fallback: {
        module: false,
        path: _webpack2().fallbacks.path,
        dgram: false,
        dns: false,
        fs: false,
        stream: false,
        http2: false,
        net: false,
        tls: false,
        child_process: false,
        process: _webpack2().fallbacks.process
      }
    },
    module: {
      strictExportPresence: true,
      rules: [{
        test: /\.m?js/,
        resolve: {
          fullySpecified: false
        }
      },
      // Disable require.ensure as it's not a standard language feature.
      // { parser: { requireEnsure: false } },
      {
        // "oneOf" will traverse all following loaders until one will
        // match the requirements. When no loader matches it will fall
        // back to the "file" loader at the end of the loader list.
        oneOf: [
        // "postcss" loader applies autoprefixer to our CSS.
        // "css" loader resolves paths in CSS and adds assets as dependencies.
        // "style" loader turns CSS into JS modules that inject <style> tags.
        // In production, we use MiniCSSExtractPlugin to extract that CSS
        // to a file, but in development "style" loader enables hot editing
        // of CSS.
        // By default we support CSS Modules with the extension .module.css
        {
          test: stylesRegexps().cssNoModulesRegex,
          use: (0, _webpackModules2().generateStyleLoaders)((0, _lodash().merge)({}, baseStyleLoadersOptions, {
            cssLoaderOpts: {
              importLoaders: 1,
              sourceMap: isEnvProduction || shouldUseSourceMap
            }
          })),
          // Don't consider CSS imports dead code even if the
          // containing package claims to have no side effects.
          // Remove this when webpack adds a warning or an error for this.
          // See https://github.com/webpack/webpack/issues/6571
          sideEffects: true
        },
        // "url" loader works like "file" loader except that it embeds assets
        // smaller than specified limit in bytes as data URLs to avoid requests.
        // A missing `test` is equivalent to a match.
        {
          test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/, /\.svg$/],
          type: 'asset',
          parser: {
            dataUrlCondition: {
              maxSize: imageInlineSizeLimit
            }
          }
        }, {
          test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
          type: 'asset',
          generator: {
            filename: 'static/fonts/[hash][ext][query]'
          }
        },
        // Process application JS with Babel.
        // The preset includes JSX, Flow, TypeScript, and some ESnext features.
        {
          test: /\.(js|mjs|jsx|ts|tsx)$/,
          loader: require.resolve('babel-loader'),
          options: {
            babelrc: false,
            configFile: false,
            // This is a feature of `babel-loader` for webpack (not Babel itself).
            // It enables caching results in ./node_modules/.cache/babel-loader/
            // directory for faster rebuilds.
            cacheDirectory: true,
            // See #6846 for context on why cacheCompression is disabled
            cacheCompression: false,
            compact: isEnvProduction,
            sourceType: 'unambiguous'
          }
        },
        // Adds support for CSS Modules (https://github.com/css-modules/css-modules)
        // using the extension .module.css
        {
          test: stylesRegexps().cssModuleRegex,
          use: (0, _webpackModules2().generateStyleLoaders)((0, _lodash().merge)({}, baseStyleLoadersOptions, {
            cssLoaderOpts: {
              importLoaders: 1,
              sourceMap: isEnvProduction || shouldUseSourceMap,
              modules: {
                getLocalIdent: _getCSSModuleLocalIdent().default
              }
            },
            shouldUseSourceMap: isEnvProduction || shouldUseSourceMap
          }))
        },
        // Opt-in support for SASS (using .scss or .sass extensions).
        // By default we support SASS Modules with the
        // extensions .module.scss or .module.sass
        {
          test: stylesRegexps().sassNoModuleRegex,
          use: (0, _webpackModules2().generateStyleLoaders)((0, _lodash().merge)({}, baseStyleLoadersOptions, {
            cssLoaderOpts: {
              importLoaders: 3,
              sourceMap: isEnvProduction || shouldUseSourceMap
            },
            shouldUseSourceMap: isEnvProduction || shouldUseSourceMap,
            preProcessOptions: {
              resolveUrlLoaderPath: require.resolve('resolve-url-loader'),
              preProcessorPath: require.resolve('sass-loader')
            }
          })),
          // Don't consider CSS imports dead code even if the
          // containing package claims to have no side effects.
          // Remove this when webpack adds a warning or an error for this.
          // See https://github.com/webpack/webpack/issues/6571
          sideEffects: true
        },
        // Adds support for CSS Modules, but using SASS
        // using the extension .module.scss or .module.sass
        {
          test: stylesRegexps().sassModuleRegex,
          use: (0, _webpackModules2().generateStyleLoaders)((0, _lodash().merge)({}, baseStyleLoadersOptions, {
            cssLoaderOpts: {
              importLoaders: 3,
              sourceMap: isEnvProduction || shouldUseSourceMap,
              modules: {
                getLocalIdent: _getCSSModuleLocalIdent().default
              }
            },
            shouldUseSourceMap: isEnvProduction || shouldUseSourceMap,
            preProcessOptions: {
              resolveUrlLoaderPath: require.resolve('resolve-url-loader'),
              preProcessorPath: require.resolve('sass-loader')
            }
          }))
        }, {
          test: stylesRegexps().lessNoModuleRegex,
          use: (0, _webpackModules2().generateStyleLoaders)((0, _lodash().merge)({}, baseStyleLoadersOptions, {
            cssLoaderOpts: {
              importLoaders: 1,
              sourceMap: isEnvProduction || shouldUseSourceMap
            },
            shouldUseSourceMap: isEnvProduction || shouldUseSourceMap,
            preProcessOptions: {
              resolveUrlLoaderPath: require.resolve('resolve-url-loader'),
              preProcessorPath: require.resolve('less-loader')
            }
          })),
          // Don't consider CSS imports dead code even if the
          // containing package claims to have no side effects.
          // Remove this when webpack adds a warning or an error for this.
          // See https://github.com/webpack/webpack/issues/6571
          sideEffects: true
        }, {
          test: stylesRegexps().lessModuleRegex,
          use: (0, _webpackModules2().generateStyleLoaders)((0, _lodash().merge)({}, baseStyleLoadersOptions, {
            cssLoaderOpts: {
              importLoaders: 1,
              sourceMap: isEnvProduction || shouldUseSourceMap,
              modules: {
                getLocalIdent: _getCSSModuleLocalIdent().default
              }
            },
            shouldUseSourceMap: isEnvProduction || shouldUseSourceMap,
            preProcessOptions: {
              resolveUrlLoaderPath: require.resolve('resolve-url-loader'),
              preProcessorPath: require.resolve('less-loader')
            }
          }))
        },
        // "file" loader makes sure those assets get served by WebpackDevServer.
        // When you `import` an asset, you get its (virtual) filename.
        // In production, they would get copied to the `build` folder.
        // This loader doesn't use a "test" so it will catch all modules
        // that fall through the other loaders.
        {
          // Exclude `js` files to keep "css" loader working as it injects
          // its runtime that would otherwise be processed through "file" loader.
          // Also exclude `html` and `json` extensions so they get processed
          // by webpacks internal loaders.
          exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/, /\.css$/],
          type: 'asset/resource'
        }
        // ** STOP ** Are you adding a new loader?
        // Make sure to add the new loader(s) before the "file" loader.
        ]
      }]
    },
    plugins: [new (_miniCssExtractPlugin().default)({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: 'static/css/[name].[contenthash:8].css',
      chunkFilename: 'static/css/[name].[contenthash:8].chunk.css'
    }),
    // Generate an asset manifest file with the following content:
    // - "files" key: Mapping of all asset filenames to their corresponding
    //   output file so that tools can pick it up without having to parse
    //   `index.html`
    //   can be used to reconstruct the HTML if necessary
    new (_webpackManifestPlugin().WebpackManifestPlugin)({
      fileName: 'asset-manifest.json',
      generate: (seed, files, entrypoints) => {
        const manifestFiles = files.reduce((manifest, file) => {
          manifest[file.name] = file.path;
          return manifest;
        }, seed);
        const entrypointFiles = entrypoints.main.filter(fileName => !fileName.endsWith('.map'));

        // @ts-ignore - https://github.com/shellscape/webpack-manifest-plugin/issues/276
        return {
          files: manifestFiles,
          entrypoints: entrypointFiles
        };
      }
    }),
    // Moment.js is an extremely popular library that bundles large locale files
    // by default due to how webpack interprets its code. This is a practical
    // solution that requires the user to opt into importing specific locales.
    // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
    // You can remove this if you don't use Moment.js:
    new (_webpack().default.IgnorePlugin)({
      resourceRegExp: /^\.\/locale$/,
      contextRegExp: /moment$/
    }),
    // Generate a service worker script that will precache, and keep up to date,
    // the HTML & assets that are part of the webpack build.
    isEnvProduction && new (_workboxWebpackPlugin().default.GenerateSW)({
      clientsClaim: true,
      maximumFileSizeToCacheInBytes: 5000000,
      exclude: [/\.map$/, /asset-manifest\.json$/],
      // importWorkboxFrom: 'cdn',
      navigateFallback: 'public/index.html',
      navigateFallbackDenylist: [
      // Exclude URLs starting with /_, as they're likely an API call
      new RegExp('^/_'),
      // Exclude any URLs whose last part seems to be a file extension
      // as they're likely a resource and not a SPA route.
      // URLs containing a "?" character won't be blacklisted as they're likely
      // a route with query params (e.g. auth callbacks).
      new RegExp('/[^/?]+\\.[^/]+$')]
    })].filter(Boolean),
    // Some libraries import Node modules but don't use them in the browser.
    // Tell webpack to provide empty mocks for them so importing them works.
    // Turn off performance processing because we utilize
    // our own hints via the FileSizeReporter
    performance: false
  };
}

//# sourceMappingURL=webpack.base.config.js.map