"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = _default;
function _lodash() {
  const data = require("lodash");
  _lodash = function () {
    return data;
  };
  return data;
}
function _path() {
  const data = require("path");
  _path = function () {
    return data;
  };
  return data;
}
require("style-loader");
function _miniCssExtractPlugin() {
  const data = _interopRequireDefault(require("mini-css-extract-plugin"));
  _miniCssExtractPlugin = function () {
    return data;
  };
  return data;
}
function _getCSSModuleLocalIdent() {
  const data = _interopRequireDefault(require("react-dev-utils/getCSSModuleLocalIdent"));
  _getCSSModuleLocalIdent = function () {
    return data;
  };
  return data;
}
function _webpack() {
  const data = require("webpack");
  _webpack = 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 _postcss() {
  const data = require("./postcss.config");
  _postcss = function () {
    return data;
  };
  return data;
}
require("@teambit/react.babel.bit-react-transformer");
require("@mdx-js/loader");
function _mdxModules() {
  const data = require("@teambit/mdx.modules.mdx-v3-options");
  _mdxModules = function () {
    return data;
  };
  return data;
}
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
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(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : 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); } // Make sure the bit-react-transformer is a dependency
// TODO: remove it once we can set policy from component to component then set it via the component.json
// eslint-disable-next-line import/no-unresolved
const styleLoaderPath = require.resolve('style-loader');
const moduleFileExtensions = ['web.mjs', 'mjs', 'web.js', 'js', 'cjs', 'web.ts', 'ts', 'web.tsx', 'tsx', 'json', 'web.jsx', 'jsx', 'mdx', 'md'];

// 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');

// 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 _default(isEnvProduction = false) {
  // 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');
  const baseStyleLoadersOptions = {
    injectingLoader: isEnvProduction ? _miniCssExtractPlugin().default.loader : styleLoaderPath,
    cssLoaderPath: require.resolve('css-loader'),
    postCssLoaderPath: require.resolve('postcss-loader'),
    postCssConfig: _postcss().postCssConfig
  };

  // 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 {
    // TODO: make the dev tool according to shouldUseSourceMap and isEnvProduction
    // devtool: 'eval-cheap-module-source-map',
    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({
        'react/jsx-dev-runtime': require.resolve('react/jsx-dev-runtime'),
        'react/jsx-runtime': require.resolve('react/jsx-runtime'),
        'react-dom/server': require.resolve('react-dom/server')
      }, isEnvProductionProfile && {
        'react-dom$': 'react-dom/profiling',
        'scheduler/tracing': 'scheduler/tracing-profiling'
      })
    },
    module: {
      strictExportPresence: true,
      rules: [{
        test: /\.m?js/,
        resolve: {
          fullySpecified: 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
        },
        // Process application JS with Babel.
        // The preset includes JSX, Flow, TypeScript, and some ESnext features.
        {
          test: /\.(js|mjs|jsx|ts|tsx)$/,
          exclude: [/node_modules/, /\/dist\//],
          // consider: limit loader to files only in a capsule that has bitid in package.json
          // descriptionData: { componentId: ComponentID.isValidObject },
          // // or
          // include: capsulePaths
          loader: require.resolve('babel-loader'),
          options: {
            babelrc: false,
            configFile: false,
            presets: [require.resolve('@babel/preset-env'), require.resolve('@babel/preset-react')],
            // 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
          }
        },
        // MDX support (move to the mdx aspect and extend from there)
        {
          test: /\.mdx?$/,
          exclude: [/node_modules/],
          use: [{
            loader: require.resolve('babel-loader'),
            options: {
              babelrc: false,
              configFile: false,
              presets: [require.resolve('@babel/preset-env'), require.resolve('@babel/preset-react')]
            }
          }, {
            loader: require.resolve('@mdx-js/loader'),
            options: _mdxModules().mdxOptions
          }, {
            // inlined @teambit/mdx.modules.mdx-pre-loader in CJS format
            loader: require.resolve('./mdx-pre-loader.cjs')
          }]
        },
        // 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')
            }
          }))
        }, {
          test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
          type: 'asset',
          parser: {
            dataUrlCondition: {
              maxSize: imageInlineSizeLimit
            }
          },
          generator: {
            filename: 'static/images/[hash][ext][query]'
          }
        }, {
          // loads svg as both inlineUrl and react component, like:
          // import starUrl, { ReactComponent as StarIcon } from './star.svg';
          // (remove when there is native support for both opitons from webpack5 / svgr)
          test: /\.svg$/,
          oneOf: [{
            dependency: {
              not: ['url']
            },
            // exclude new URL calls
            use: [{
              loader: require.resolve('@svgr/webpack'),
              options: {
                titleProp: true,
                ref: true
              }
            }, require.resolve('new-url-loader')]
          }, {
            type: 'asset' // export a data URI or emit a separate file
          }]
        }, {
          test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
          type: 'asset',
          generator: {
            filename: 'static/fonts/[hash][ext][query]'
          }
        },
        // "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|cjs|jsx|ts|tsx)$/, /\.html$/, /\.mdx?/, /\.json$/, /\.css$/],
          generator: {
            filename: 'static/[hash][ext][query]'
          },
          type: 'asset'
        }
        // ** STOP ** Are you adding a new loader?
        // Make sure to add the new loader(s) before the "type:asset" loader.
        ]
      }]
    },
    plugins: [isEnvProduction && 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'
    }),
    // 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().IgnorePlugin)({
      resourceRegExp: new RegExp(`^\\.${_path().sep}locale$`),
      contextRegExp: /moment$/
    })].filter(Boolean),
    // Turn off performance processing because we utilize
    // our own hints via the FileSizeReporter
    performance: false
  };
}

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