HMR bundle setup based on code from
https://github.com/webpack/webpack-dev-server/blob/master/bin/webpack-dev-server.js
420600
function setupHMR (webpackConfig, port) {
  return webpackConfig.map((webpack) => ({
    ...webpack,
    entry: concatHMRBundle(webpack.entry, port)
  }))
}
140762
function checkModule(pth, cb) {
  checkStrider(pth, function(err, config){
    if (err) return cb(err);
    if (config){
      config.dir = pth;
      return cb(null, config);
    }
    checkPackageJson(pth, function(err, config){
      if (err) return cb(err);
      if (config){
        config.dir = pth;
        return cb(null, config);
      }
      return cb(null, false);
    });
  });
}
599323
function serve(argv, skyPagesConfig, webpack, WebpackDevServer) {

  const webpackConfig = require('../config/webpack/serve.webpack.config');
  let config = webpackConfig.getWebpackConfig(argv, skyPagesConfig);

  getPort(config, skyPagesConfig).then(port => {
    const localUrl = `https://localhost:${port}`;

    assetsProcessor.setSkyAssetsLoaderUrl(config, skyPagesConfig, localUrl);
    localeAssetsProcessor.prepareLocaleFiles();

    // Save our found or defined port
    config.devServer.port = port;

    /* istanbul ignore else */
    if (config.devServer.inline) {
      const inline = `webpack-dev-server/client?${localUrl}`;
      Object.keys(config.entry).forEach((entry) => {
        config.entry[entry].unshift(inline);
      });
    }

    if (config.devServer.hot) {
      const hot = `webpack/hot/only-dev-server`;
      Object.keys(config.entry).forEach((entry) => {
        config.entry[entry].unshift(hot);
      });

      // This is required in order to not have HMR requests routed to host.
      config.output.publicPath = `${localUrl}${config.devServer.publicPath}`;
      logger.info('Using hot module replacement.');
    }

    const compiler = webpack(config);
    const server = new WebpackDevServer(compiler, config.devServer);
    server.listen(config.devServer.port, 'localhost', (err) => {
      if (err) {
        logger.error(err);
      }
    });
  }).catch(err => logger.error(err));

}
532131
function bundleDTS() {
    const DST_PATH = path.join(__dirname, '..', config.dir.pkg);
    const TYPE_DEF_FILE = path.join(DST_PATH, config.dir.types, config.main.bundle_d_ts);
    const SRC_DEF_FILE = path.join(__dirname, '..', config.dir.built, config.main.basename + '-all.d.ts');

    let src = '\ufeff' + banner('.d.ts', config.main.basename) + fs.readFileSync(SRC_DEF_FILE).toString()
            .replace(/^\ufeff/gm, '')
            .replace(/\r\n/gm, '\n')
    ;

    const refPathInfo = [];
    const refPathDefs = src.match(/<reference path="[\s\S]*?"/g);

    if (null != refPathDefs) {
        refPathDefs.forEach((refpath) => {
            const filePath = refpath.match(/("|')[\s\S]*?("|')/)[0].replace(/("|')/g, '');
            const fileName = path.basename(filePath);
            refPathInfo.push({
                refpath: refpath,
                path: filePath,
                file: fileName,
            });
        });
        refPathInfo.forEach((target) => {
            src = src.replace(target.refpath, '<reference path="' + target.file + '"');
        });
        // remove '_dev.dependencies.d.ts' reference.
        src = src.replace(/\/\/\/ <reference path="_dev.dependencies.d.ts"[\s\S]*?\n/g, '');
    }

    if (!fs.existsSync(path.join(DST_PATH, config.dir.types))) {
        fs.mkdirSync(path.join(DST_PATH, config.dir.types));
    }
    fs.writeFileSync(TYPE_DEF_FILE, src);
}
527156
function (appServer) {
      appServer.use(function (req, res, next) {
        if (process.env.ENVIRONMENT === 'development') {
          // Lets not console log for status polling or webpack hot module reloading
          if (
            !req.url.includes('/status') &&
            !req.url.includes('/__webpack_hmr')
          ) {
            console.log('Using middleware for ' + req.url)
          }
        }
        next()
      })

      // Add webpack hot middleware to use for error overlay
      // Quiet is set to true because well let WebpackDevServer handle console logging
      appServer.use(webpackHotMiddleware(compiler))

      // If there is a server.js file load it and pass appServer to it
      if (pathToServer) {
        require(pathToServer)(appServer)
      }
    }
1155277
function (err) {
                var responseOptions = new __WEBPACK_IMPORTED_MODULE_3__base_response_options__["b" /* ResponseOptions */]({
                    body: err,
                    type: __WEBPACK_IMPORTED_MODULE_4__enums__["d" /* ResponseType */].Error,
                    status: _xhr.status,
                    statusText: _xhr.statusText,
                });
                if (baseResponseOptions != null) {
                    responseOptions = baseResponseOptions.merge(responseOptions);
                }
                responseObserver.error(new __WEBPACK_IMPORTED_MODULE_8__static_response__["a" /* Response */](responseOptions));
            }
1265344
function prepareServe() {

  if (webpackServer) {
    return bindServe();
  } else {
    return new Promise((resolve, reject) => {
      portfinder.getPortPromise()
        .then(writeConfigServe)
        .then(bindServe)
        .then(resolve)
        .catch(err => reject(err));
    });
  }
}
518485
function preparePackage() {
    var ignoreFiles = ['package.json', 'README.md', 'LICENSE.md', '.gitignore', '.npmignore'];
    var ignoreCopyFiles = [];
    var copyRecursiveSync = function(src, dest) {
        var exists = fs.existsSync(src);
        var stats = exists && fs.statSync(src);
        var isDirectory = exists && stats.isDirectory();
        if (exists && isDirectory) {
            if (!fs.existsSync(dest)) {
                fs.mkdirSync(dest);
            }
            fs.readdirSync(src).forEach(function(filename) {
                copyRecursiveSync(upath.join(src, filename),
                    upath.join(dest, filename));
            });
        } else {
            if (ignoreCopyFiles.indexOf(upath.basename(src)) === -1) {
                fs.linkSync(src, dest);
            }
        }
    };
    var srcPkg = upath.join(process.cwd(), 'src');
    if (fs.existsSync(srcPkg)) {
        fs.readdirSync(process.cwd()).forEach(function(filename) {
            var curPath = upath.join(process.cwd(), filename);
            if (ignoreFiles.indexOf(upath.basename(curPath)) === -1 && fs.statSync(curPath).isFile()) {
                fs.unlinkSync(curPath);
            }
        });
        copyRecursiveSync(srcPkg, process.cwd());
    }
    deleteFolderRecursive(srcPkg);
    deleteFolderRecursive(upath.join(process.cwd(), 'test'));
    deleteFolderRecursive(upath.join(process.cwd(), 'env'));
}
8752
def zip_bundle(tag=True):
    
    #rev = get_rev(tag)
    rev = __version__

    print("Cleaning old build files.")
    clean()

    local("mkdir -p build")

    print("Bundling new files.")
    with lcd("sphinx_bootstrap_theme/bootstrap"):
        local("zip -r ../../build/bootstrap.zip .")

    dest = os.path.abspath(os.path.join(DL_DIR, rev))
    with lcd("build"):
        local("mkdir -p %s" % dest)
        local("cp bootstrap.zip %s" % dest)

        print("Verifying contents.")
        local("unzip -l bootstrap.zip")
104177
function setupModule() {

    // Shims

    if(typeof self === 'undefined') {
      global.self = global;
    }

    if(!self.URL) {
      self.URL = self.webkitURL;
    }

    // Make sure are on https in browser,
    // otherwise crypto etc. wont work.

    if(isBrowser() &&
        self.location.protocol === 'http:' &&
        self.location.hostname !== 'localhost' &&
        !self.location.hostname.startsWith('192.168.')) {
      self.location.href = self.location.href.replace(/http/, 'https');
    }

    // Setup / export module

    da = self.direape || {};

    if(typeof module === 'undefined') {
      self.direape = da;
    } else {
      module.exports = da;
    }

    da.test = test;

    // Define name of testsuite

    testSuite('direape');
  }
1077370
function(cb) {
      if (!has(fileReloaders, localHmr.updateMode)) {
        cb(new Error("updateMode "+localHmr.updateMode+" not implemented"));
        return;
      }
      var reloader = fileReloaders[localHmr.updateMode];
      reloader(function(err, data) {
        if (err || !data || lastScriptData === data) {
          cb(err, false);
          return;
        }
        lastScriptData = data;
        localHmr.newLoad = null;
        try {
          if (bundle__filename || bundle__dirname) {
            new Function('require', '__filename', '__dirname', data)(require, bundle__filename, bundle__dirname);
          } else {
            new Function('require', data)(require);
          }
          // running the file sets _hmr.newLoad
        } catch (err2) {
          localHmr.newLoad = null;
          cb(err2);
          return;
        }
        if (!localHmr.newLoad) {
          cb(new Error("Reloaded script did not set hot module reload data"));
          return;
        }
        cb(null, true);
      });
    }
62616
function requirePackage(pkg, mainjs) {
			var processed = {};
			var pkgName = path.basename(pkg);
			var code = grunt.file.read(mainjs);
			while (true) {
				var requires = detective(code);
				if (!requires.length) break;
				for (var requireIdx in requires) {
					var name = requires[requireIdx];
					var requiredCode = '';
					if (!processed[name]) {
						var filepath = path.join(pkg, 'lib', name.replace(pkgName + '/', '') + '.js');
						requiredCode = grunt.file.read(filepath);
						processed[name] = true;
					}
					code = code.replace(new RegExp('require\\([\\\'\"]' + name + '[\\\'\"]\\);?'), requiredCode);
				}
			}
			return code;
		}
661979
function linkPackages(dstPacksDir) {
  if (!dstPacksDir) {
    dstPacksDir = Path.resolve(rootDir, "packages");
  }
  else {
    dstPacksDir = Path.resolve(cwd, dstPacksDir);
  }

  // Ensure destination dir
  try {
    Fs.mkdirSync(dstPacksDir);
  }
  catch (_) {}

  var packNames = Fs.readdirSync(srcPacksDir);

  // Ensure symlinks
  packNames.forEach(function (packName) {
    var dstPackDir = Path.resolve(dstPacksDir, packName);
    var linkPath = Path.relative(dstPacksDir, Path.resolve(srcPacksDir, packName));

    try {
      Fs.symlinkSync(linkPath, dstPackDir);
    }
    catch (_) {}
  });

  console.log();
  console.log("Packages have been successfully linked at:")
  console.log();
  console.log("    " + dstPacksDir);
  console.log();
}
765351
function createUnpackedBundle() {
  fs.mkdirp(unpackedDir, err => {
    if (err && err.code !== 'EEXIST') {
      console.log(err);
      throw err;
    }

    let unpackedFile = path.join(__dirname, 'unpacked.js');
    let b = browserify(unpackedFile).bundle();
    b.on('error', console.error);
    let unpackedBundleFile = path.join(unpackedDir, 'unpacked-bundle.js');
    const bundleFileStream = fs.createWriteStream(unpackedBundleFile);
    bundleFileStream.on('finish', () => {
      console.log('Wrote bundled JS into ' + unpackedBundleFile);
    });
    bundleFileStream.on('pipe', () => {
      console.log('Writing bundled JS...');
    });
    bundleFileStream.on('error', console.error);
    b.pipe(bundleFileStream);
    // bundleFileStream.end();  // do not do this prematurely!
  });
}
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
  };
}
914572
function basePackageJson (opts) {
  opts = opts || {}
  const _name = opts.name || '<name>'
  const _version = opts.version || '1.0.0'
  const _private = opts.private || false

  var called = false

  return from({ objectMode: true }, function (size, next) {
    if (called) return next(null, null)

    const res = { name: _name, version: _version }
    if (_private) res.private = true
    res.scripts = {}
    res.dependencies = {}
    res.devDependencies = {}

    called = true
    next(null, res)
  })
}
510452
def buildpack(self, url):
        """"""
        cmd = ["heroku", "buildpacks:add", url, "--app", self.name]
        self._run(cmd)