get webpack config

@param  {Object} config
@param  {Object} context
@return {Object} result - webpack config
431348
function getWebpackConfig(config, context) {
  var webpackConfig = {
    module: {
      rules: [
        {
          exclude: /node_modules/,
          loader: assist.resolve('babel-loader'),
          test: /\.(es6|js)$/
        }
      ]
    },
    output: {
      path: config.$path.target.client,
      filename: '[name].js'
    },
    resolve: {
      extensions: ['.js'],
      alias: config.alias || {}
    },
    externals: {}
  }

  var babelConfig = assist.getBabelConfig(context.env)
  var babelLoader = webpackConfig.module.rules
    .find(rule => rule.loader && /babel/.test(rule.loader))
  babelLoader.options = babelConfig

  var processEnv = {
    'process.env': {
      NODE_ENV: JSON.stringify(context.env || 'production'),
      IS_BROWSER: true
    }
  }
  if (context.env === 'development') {
    // development env
    webpackConfig.plugins = [
      new webpack.DefinePlugin(processEnv)
    ]
  } else {
    // production env
    webpackConfig.plugins = [
      new webpack.DefinePlugin(processEnv),
      new webpack.optimize.CommonsChunkPlugin({ name: 'common' }),
      new webpack.optimize.UglifyJsPlugin({ sourceMap: false })
    ]
  }

  return webpackConfig
}
956930
function acquireContext(item, config) {
		if (typeof item === 'string') {
			item = document.getElementById(item);
		} else if (item.length) {
			// Support for array based queries (such as jQuery)
			item = item[0];
		}

		if (item && item.canvas) {
			// Support for any object associated to a canvas (including a context2d)
			item = item.canvas;
		}

		if (item instanceof HTMLCanvasElement) {
			// To prevent canvas fingerprinting, some add-ons undefine the getContext
			// method, for example: https://github.com/kkapsner/CanvasBlocker
			// https://github.com/chartjs/Chart.js/issues/2807
			var context = item.getContext && item.getContext('2d');
			if (context instanceof CanvasRenderingContext2D) {
				initCanvas(item, config);
				return context;
			}
		}

		return null;
	}
360996
function setup(context) {
  if (GLOBAL.config) {
    console.log('already configured');
    console.trace();
    return;
  }
  if (!context) {
    context = require('./config.js');
  }

  GLOBAL.config = context.config;

  var svc = { pubsub: pubsub, auth: auth, indexer: indexer, pageCache: pageCache };

  GLOBAL.svc = svc;
  auth.setupUsers(GLOBAL, context.logins);
}
641082
function getConfig(api) {
	const conf = api.resolveChainableWebpackConfig()

	// because we are dealing with hot replacement in vsg
	// remove duplicate hot module reload plugin
	conf.plugins.delete('hmr')

	const eslintRule = conf.module.rule('eslint')
	if (eslintRule) {
		const path = require('path')
		const vsgPath = path.resolve(path.dirname(require.resolve('vue-styleguidist')), '../')
		eslintRule.exclude.add(vsgPath)
	}

	// remove the double compiled successfully message
	conf.plugins.delete('friendly-errors')
	return api.resolveWebpackConfig(conf)
}
1221482
function getConfig(options) {
  options = options || {};

  let configFilepath;
  let config;

  // Read config options from a file
  configFilepath = findConfig(options.config);
  config = require(configFilepath);

  validateConfig(config);

  const configDir = configFilepath? path.dirname(configFilepath) : process.cwd();

  validateDependencies(configDir);

  let assetsDir = null;
  if (typeof config.assetsDir === 'string') {
    assetsDir = path.resolve(configDir, config.assetsDir);
    if (!utils.isDirectoryExists(assetsDir)) {
      throw new DvhbWebpackError('DvhbWebpack: "assetsDir" directory not found: ' + assetsDir);
    }
  }
  if (Array.isArray(config.assetsDir)) {
    assetsDir = [];
    config.assetsDir.forEach(function (dir) {
      assetsDir.push(path.resolve(configDir, dir));
    });
  }


  config = merge({}, DEFAULT_CONFIG, config);
  config = merge({}, config, {
    appEnv: options['app-env'],
    env: options.env || 'development',
    verbose: !!options.verbose,
    sourceDir: path.resolve(configDir, config.sourceDir),
    distDir: path.resolve(configDir, config.distDir),
    viewsDir: path.resolve(configDir, config.viewsDir),
    svgSpriteDir: path.resolve(configDir, config.svgSpriteDir),
    svgInlineDir: path.resolve(configDir, config.svgInlineDir),
    assetsDir: assetsDir,
    modernizrrc: path.resolve(configDir, config.modernizrrc),
    configDir,
  });

  if (options.port) {
    config.serverPort = options.port
  }

  config.serverHostNetwork = utils.getNetworkIp();

  if (fs.existsSync(path.resolve(configDir, config.eslintrc))) {
    config.eslintrc = path.resolve(configDir, config.eslintrc)
  } else {
    config.eslintrc = path.resolve(__dirname, '..', DEFAULT_CONFIG.eslintrc)
  }

  if (fs.existsSync(path.resolve(configDir, config.postcssrc))) {
    config.postcssrc = path.resolve(configDir, config.postcssrc)
  } else {
    config.postcssrc = path.resolve(__dirname, '..', DEFAULT_CONFIG.postcssrc)
  }

  let babelrcPath = path.resolve(configDir, '.babelrc');
  if (fs.existsSync(babelrcPath)) {
    config.babelrc = babelrcPath
  }

  if (config.verbose) {
    console.log();
    console.log('Using config file:', configFilepath);
    console.log(prettyjson.render(config));
    console.log();
  }

  return config;
}
721573
function getConfig(config) {

  // This file is spawned so we'll need to read the args again
  const minimist = require('minimist');
  const argv = minimist(process.argv.slice(2));
  const path = require('path');
  const srcPath = path.join(process.cwd(), 'src');

  const testWebpackConfig = require('../webpack/test.webpack.config');
  const remapIstanbul = require('remap-istanbul');

  const utils = require('istanbul').utils;

  // See minimist documentation regarding `argv._` https://github.com/substack/minimist
  const skyPagesConfig = require('../sky-pages/sky-pages.config').getSkyPagesConfig(argv._[0]);

  // Using __dirname so this file can be extended from other configuration file locations
  const specBundle = `${__dirname}/../../utils/spec-bundle.js`;
  const specStyles = `${__dirname}/../../utils/spec-styles.js`;

  const preprocessors = {};

  preprocessors[specBundle] = ['coverage', 'webpack', 'sourcemap'];
  preprocessors[specStyles] = ['webpack'];

  let onWriteReportIndex = -1;
  let coverageFailed;

  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    exclude: [],
    files: [
      {
        pattern: specBundle,
        watched: false
      },
      {
        pattern: specStyles,
        watched: false
      }
    ],
    preprocessors: preprocessors,
    skyPagesConfig: skyPagesConfig,
    webpack: testWebpackConfig.getWebpackConfig(skyPagesConfig, argv),
    coverageReporter: {
      dir: path.join(process.cwd(), 'coverage'),
      reporters: [
        { type: 'json' },
        { type: 'html' },
        { type: 'text-summary' },
        { type: 'lcov' },
        { type: 'in-memory' }
      ],
      _onWriteReport: function (collector) {
        onWriteReportIndex++;

        const newCollector = remapIstanbul.remap(collector.getFinalCoverage());

        const threshold = getCoverageThreshold(skyPagesConfig);

        // The karma-coverage library does not use the coverage summary from the remapped source
        // code, so its built-in code coverage check uses numbers that don't match what's reported
        // to the user.  This will use the coverage summary generated from the remapped
        // source code.
        if (threshold) {
          // When calling the _onWriteReport() method, karma-coverage loops through each reporter,
          // then for each reporter loops through each browser.  Since karma-coverage doesn't
          // supply this method with any information about the reporter or browser for which this
          // method is being called, we must calculate it by looking at how many times the method
          // has been called.
          const browserIndex = Math.floor(onWriteReportIndex / this.reporters.length);

          if (onWriteReportIndex % this.reporters.length === 0) {
            // The karma-coverage library has moved to the next browser and has started the first
            // reporter for that browser, so evaluate the code coverage now.
            const browserName = config.browsers[browserIndex];

            const summaries = [];

            newCollector.files().forEach((file) => {
              summaries.push(
                utils.summarizeFileCoverage(
                  newCollector.fileCoverageFor(file)
                )
              );
            });

            const remapCoverageSummary =
              utils.mergeSummaryObjects.apply(
                null,
                summaries
              );

            const keys = [
              'statements',
              'branches',
              'lines',
              'functions'
            ];

            keys.forEach((key) => {
              let actual = remapCoverageSummary[key].pct;

              if (actual < threshold) {
                coverageFailed = true;
                logger.error(
                  `Coverage in ${browserName} for ${key} (${actual}%) does not meet ` +
                  `global threshold (${threshold}%)`
                );
              }
            });
          }
        }

        // It's possible the user is running the watch command, so the field we're
        // using to track the number of calls to _onWriteReport() needs to be reset
        // after each run.
        if (onWriteReportIndex === (this.reporters.length * config.browsers.length - 1)) {
          onWriteReportIndex = -1;
        }

        return newCollector;
      },

      _onExit: function (done) {
        if (coverageFailed) {
          logger.info('Karma has exited with 1.');
          process.exit(1);
        }

        done();
      }
    },
    webpackServer: {
      noInfo: true,
      stats: 'minimal'
    },

    // This is necessary to stop endless test runs for skyux watch.
    // Without it, the coverage reports and .skypageslocales files will
    //  trigger the `invalid` event, causing karma to constantly re-rerun
    //  the tests.  This is a by-product of using `require.context`.
    // https://github.com/webpack-contrib/karma-webpack/issues/253#issuecomment-335545430
    // By using require.context in our @skyux/i18n library ALL project files are watched by default.
    // The function below ignores all files execpt the `src` directory.
    webpackMiddleware: {
      watchOptions: {
        // Returning `true` means the file should be ignored.
        // Fat-Arrow functions do not work as chokidar will inspect this method.
        ignored: function (item) {
          const resolvedPath = path.resolve(item);
          const ignore = (resolvedPath.indexOf(srcPath) === -1);
          return ignore;
        }
      }
    },

    // This flag allows console.log calls to come through the cli
    browserConsoleLogOptions: {
      level: 'log'
    },
    reporters: ['mocha', 'coverage'],
    port: 9876,
    colors: logger.logColor,
    logLevel: config.LOG_INFO,
    browserDisconnectTimeout: 3e5,
    browserDisconnectTolerance: 3,
    browserNoActivityTimeout: 3e5,
    captureTimeout: 3e5,
    autoWatch: false,
    singleRun: true,
    failOnEmptyTestSuite: false
  });
}
987050
function createWebpack ({ alias = {}, context, name = 'index' }) {
  const pkgJson = require(path.join(context, 'package.json'));
  const ENV = process.env.NODE_ENV || 'development';
  const isProd = ENV === 'production';
  const hasPublic = fs.existsSync(path.join(context, 'public'));
  const plugins = hasPublic
    ? [new CopyWebpackPlugin([{ from: 'public' }])]
    : [];

  return {
    context,
    devtool: isProd ? 'source-map' : 'cheap-eval-source-map',
    entry: [
      `./src/${name}.tsx`,
      isProd
        ? null
        : 'webpack-plugin-serve/client'
    ].filter((entry) => entry),
    mode: ENV,
    output: {
      chunkFilename: `[name].[chunkhash:8].js`,
      filename: `[name].[hash:8].js`,
      globalObject: `(typeof self !== 'undefined' ? self : this)`,
      path: path.join(context, 'build')
    },
    resolve: {
      alias,
      extensions: ['.js', '.jsx', '.ts', '.tsx']
    },
    module: {
      rules: [
        {
          test: /\.css$/,
          exclude: /(node_modules)/,
          use: [
            isProd
              ? MiniCssExtractPlugin.loader
              : require.resolve('style-loader'),
            {
              loader: require.resolve('css-loader'),
              options: {
                importLoaders: 1
              }
            },
            {
              loader: require.resolve('postcss-loader'),
              options: {
                ident: 'postcss',
                plugins: () => [
                  require('precss'),
                  require('autoprefixer'),
                  require('postcss-simple-vars'),
                  require('postcss-nested'),
                  require('postcss-import'),
                  require('postcss-clean')(),
                  require('postcss-flexbugs-fixes')
                ]
              }
            }
          ]
        },
        {
          test: /\.css$/,
          include: /node_modules/,
          use: [
            isProd
              ? MiniCssExtractPlugin.loader
              : require.resolve('style-loader'),
            require.resolve('css-loader')
          ]
        },
        {
          test: /\.(js|ts|tsx)$/,
          exclude: /(node_modules)/,
          use: [
            require.resolve('thread-loader'),
            {
              loader: require.resolve('babel-loader'),
              options: require('@polkadot/dev-react/config/babel')
            }
          ]
        },
        {
          test: /\.md$/,
          use: [
            require.resolve('html-loader'),
            require.resolve('markdown-loader')
          ]
        },
        {
          test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
          use: [
            {
              loader: require.resolve('url-loader'),
              options: {
                limit: 10000,
                name: 'static/[name].[hash:8].[ext]'
              }
            }
          ]
        },
        {
          test: [/\.eot$/, /\.ttf$/, /\.svg$/, /\.woff$/, /\.woff2$/],
          use: [
            {
              loader: require.resolve('file-loader'),
              options: {
                name: 'static/[name].[hash:8].[ext]'
              }
            }
          ]
        }
      ]
    },
    node: {
      child_process: 'empty',
      dgram: 'empty',
      fs: 'empty',
      net: 'empty',
      tls: 'empty'
    },
    optimization: {
      runtimeChunk: 'single',
      splitChunks: {
        cacheGroups: {
          vendorOther: {
            chunks: 'initial',
            enforce: true,
            name: 'vendor',
            test: /node_modules\/(asn1|bn\.js|buffer|cuint|elliptic|lodash|moment|readable-stream|rxjs)/
          },
          vendorReact: {
            chunks: 'initial',
            enforce: true,
            name: 'react',
            test: /node_modules\/(chart|i18next|react|semantic-ui)/
          },
          polkadotJs: {
            chunks: 'initial',
            enforce: true,
            name: 'polkadotjs',
            test: /node_modules\/(@polkadot\/wasm-(crypto|dalek-ed25519|schnorrkel))/
          }
        }
      }
    },
    performance: {
      hints: false
    },
    plugins: plugins.concat([
      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
      new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: JSON.stringify(ENV),
          VERSION: JSON.stringify(pkgJson.version),
          WS_URL: JSON.stringify(process.env.WS_URL)
        }
      }),
      new HtmlWebpackPlugin({
        inject: true,
        template: path.join(context, `${hasPublic ? 'public/' : ''}${name}.html`),
        PAGE_TITLE: 'Polkadot/Substrate Portal'
      }),
      new webpack.optimize.SplitChunksPlugin(),
      new MiniCssExtractPlugin({
        filename: `[name].[contenthash:8].css`
      }),
      isProd
        ? null
        : new WebpackPluginServe({
          port: 3000,
          static: path.join(process.cwd(), '/build')
        })
    ]).filter((plugin) => plugin),
    watch: !isProd
  };
}
236061
function loadConfig(config) {
  var options = normalizeOptions(config);

  if (config.options.plugins != null && !Array.isArray(config.options.plugins)) {
    throw new Error(".plugins should be an array, null, or undefined");
  }

  var plugins = (config.options.plugins || []).map(function (plugin, index) {
    var _normalizePair = normalizePair(plugin, _files.loadPlugin, config.dirname),
        filepath = _normalizePair.filepath,
        value = _normalizePair.value,
        options = _normalizePair.options;

    return {
      alias: filepath || config.loc + "$" + index,
      loc: filepath || config.loc,
      value: value,
      options: options,
      dirname: config.dirname
    };
  });

  if (config.options.presets != null && !Array.isArray(config.options.presets)) {
    throw new Error(".presets should be an array, null, or undefined");
  }

  var presets = (config.options.presets || []).map(function (preset, index) {
    var _normalizePair2 = normalizePair(preset, _files.loadPreset, config.dirname),
        filepath = _normalizePair2.filepath,
        value = _normalizePair2.value,
        options = _normalizePair2.options;

    return {
      alias: filepath || config.loc + "$" + index,
      loc: filepath || config.loc,
      value: value,
      options: options,
      dirname: config.dirname
    };
  });

  return { options: options, plugins: plugins, presets: presets };
}
190944
function overrideConfig(config) {
    if (fs.existsSync(config.config)) {
        var content = fs.readFileSync(config.config, {
            encoding: "utf8"
        });
        var configFile = JSON.parse(content);
        for (var key in configFile) {
            if (configFile.hasOwnProperty(key)) {
                config[key] = configFile[key];
            }
        }
    }
    return config;
}
186083
function getModuleConfig(nameOrPath,modules) {
    for (var i = 0; i < modules.length; i++) {
        var config = modules[i];
        if (config.options && (config.options.directory === nameOrPath || config.name === nameOrPath)) {
            return config;
        }
    }
    return null;
}
406747
function getEntries(config, context) {
  var filter = config.filter && new RegExp(config.filter)
  var files = context.entries.length > 0
    ? context.entries
    : glob.sync(config.$path.source.client + '/**/index.scss')
  files = files
    .filter(file => !/node_modules/.test(file))
    .filter(file => !filter || !filter.test(file))
    .filter(file => /index\.scss$/.test(file))
  var entries = {}
  files.forEach(file => {
    var name = path.relative(config.$path.source.client, file).slice(0, -5)
    entries[name] = file
  })
  return entries
}
1229098
function postConfig (context, _ref) {
  var merge = _ref.merge

  return function (prevConfig) {
    var _context$copyPlugin = context.copyPlugin,
      patterns = _context$copyPlugin.patterns,
      options = _context$copyPlugin.options

    var plugin = new _copyWebpackPlugin2.default(patterns, options)
    return merge({plugins: [plugin]})
  }
}
338321
def includeme(config):
    
    settings = config.registry.settings
    root_package_name = config.root_package.__name__
    config.registry.webpack = {
        'DEFAULT': WebpackState(settings, root_package_name)
    }
    for extra_config in aslist(settings.get('webpack.configs', [])):
        state = WebpackState(settings, root_package_name, name=extra_config)
        config.registry.webpack[extra_config] = state

    # Set up any static views
    for state in six.itervalues(config.registry.webpack):
        if state.static_view:
            config.add_static_view(name=state.static_view_name,
                                   path=state.static_view_path,
                                   cache_max_age=state.cache_max_age)

    config.add_request_method(get_webpack, 'webpack')
1000807
function cacheModule(config) {
    config = utilities.parseConfig(config);
    var moduleCache = utilities.getCachePath();
    console.log('Module cache at ' + moduleCache);

    var version = getModuleVersionFromConfig(config);

    var pkgStr = config.nodePackageName + (version ? '@' + version : '');
    return utilities.getVersionForNpmPackage(pkgStr).then(function (versionString) {
        // Install correct cordova version if not available
        var packagePath = path.join(moduleCache, config.nodePackageName || CORDOVA);
        var versionPath = path.join(packagePath, version ? version : versionString);
        var targetModulePath = path.join(versionPath, 'node_modules', config.nodePackageName)
        if (!utilities.fileExistsSync(targetModulePath)) {  // Fix: Check module is there not just root path
            if (!utilities.fileExistsSync(packagePath)) {
                fs.mkdirSync(packagePath);
            }
            
            if (!utilities.fileExistsSync(versionPath)) {
                fs.mkdirSync(versionPath);
                fs.mkdirSync(path.join(versionPath, 'node_modules')); // node_modules being present ensures correct install loc
            }

            console.log('Installing ' + pkgStr + ' to ' + versionPath + '. (This may take a few minutes.)');
            var cmd = 'npm install --force ' + pkgStr + ' 2>&1';
            return exec(cmd, { cwd: versionPath })
                .then(utilities.handleExecReturn)
                .then(function () {
                return {
                    version: version,
                    path: targetModulePath
                };
            });
        } else {
            console.log(pkgStr + ' already installed.');
            return Q({
                version: version,
                path: targetModulePath
            });
        }
    });
}
794227
function compile(config) {
  let compiler;
  try {
    compiler = webpack(config);
  } catch (e) {
    console.log('Failed to compile: ', [e]); // eslint-disable-line
    process.exit(1);
  }
  return compiler;
}
646737
function getWebpackConfig(skyPagesConfig, argv) {
  const common = require('./common.webpack.config');

  // Webpackmege will attempt to merge each entries array, so we need to delete it
  let commonConfig = common.getWebpackConfig(skyPagesConfig, argv);
  commonConfig.entry = null;

  // Since the preloader is executed against the file system during an AoT build,
  // we need to remove it from the webpack config, otherwise it will get executed twice.
  commonConfig.module.rules = commonConfig.module.rules
    .filter((rule) => {
      const isPreloader = /(\/|\\)sky-processor(\/|\\)/.test(rule.loader);
      return (!isPreloader);
    });

  return webpackMerge(commonConfig, {
    entry: {
      polyfills: [skyPagesConfigUtil.spaPathTempSrc('polyfills.ts')],
      vendor: [skyPagesConfigUtil.spaPathTempSrc('vendor.ts')],
      skyux: [skyPagesConfigUtil.spaPathTempSrc('skyux.ts')],
      app: [skyPagesConfigUtil.spaPathTempSrc('main-internal.aot.ts')]
    },
    
    // Disable sourcemaps for production:
    // https://webpack.js.org/configuration/devtool/#production
    devtool: undefined,
    
    module: {
      rules: [
        {
          test: /\.ts$/,
          loader: '@ngtools/webpack'
        }
      ]
    },
    plugins: [
      new ngtools.AotPlugin({
        tsConfigPath: skyPagesConfigUtil.spaPathTempSrc('tsconfig.json'),
        entryModule: skyPagesConfigUtil.spaPathTempSrc('app', 'app.module') + '#AppModule',
        // Type checking handled by Builder's ts-linter utility.
        typeChecking: false
      }),
      SaveMetadata,
      new webpack.optimize.UglifyJsPlugin({
        beautify: false,
        comments: false,
        compress: { warnings: false },
        mangle: { screw_ie8: true, keep_fnames: true }
      })
    ]
  });
}
332455
function readWebpackConfig( server ) {

  const devConfig = server.webpackConfig && server.webpackConfig.dev;
  const configFile = paths.resolveApp( devConfig ) || appWebpackDevConfig;

  try {

    assert(
      existsSync( configFile ),
      `File ${devConfig || WEBPACK_DEV_CONFIG} is not exsit.`
    );

    const wpConfig = getConfig( configFile );

    // plugins: function
    if ( is.Function( wpConfig.plugins )) {
      wpConfig.plugins = wpConfig.plugins( wpConfig );
    }

    // plugins: not array
    if ( !is.Array( wpConfig.plugins )) {
      wpConfig.plugins = [wpConfig.plugins];
    }

    // plugins: array in array
    wpConfig.plugins = flatten( wpConfig.plugins.map(( plugin ) => {
      return is.Function( plugin ) ? plugin( wpConfig ) : plugin;
    }));

    server.webpackDevConfig = wpConfig;
    watchFiles.push( configFile );

    return Right( server );
  } catch ( e ) {
    print(
      chalk.red( `Failed to read ${devConfig || WEBPACK_DEV_CONFIG}.` ),
      e.message
    );
    print();
    return Left( null );
  }
}