<commit_before>'use strict'

const fs = require('fs')
const path = require('path')
const autoprefixer = require('autoprefixer')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin')
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin')
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const paths = require('./paths')
const getClientEnvironment = require('./env')
const argv = require('minimist')(process.argv.slice(2))
const rxPaths = require('rxjs/_esm2015/path-mapping')
const TsConfigPathsPlugin = require('tsconfig-paths-webpack-plugin')
const JsConfigPathsPlugin = require('jsconfig-paths-webpack-plugin')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin

// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
const publicPath = paths.servedPath
// Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
const shouldUseRelativeAssetPaths = publicPath === './'
// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false'
// `publicUrl` is just like `publicPath`, but we will provide it 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.
const publicUrl = publicPath.slice(0, -1)
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl)

// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (env.stringified['process.env'].NODE_ENV !== '"production"') {
  throw new Error('Production builds must have NODE_ENV=production.')
}

// Note: defined here because it will be used more than once.
const cssFilename = '[name].css'

// ExtractTextPlugin expects the build output to be flat.
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
// However, our output is structured with css, js and media folders.
// To have this structure working with relative paths, we have to use custom options.
const extractTextPluginOptions = shouldUseRelativeAssetPaths
  ? // Making sure that the publicPath goes back to to build folder.
    { publicPath: Array(cssFilename.split('/').length).join('../') }
  : {}

// Every folder in app src would generate a entry
// except 'manifest', 'assets','components', 'typings' and name starts with '_'
const entries = fs.readdirSync(paths.appSrc)
  .filter(name => !name.startsWith('_'))
  .map(name => ({name, dirPath: path.join(paths.appSrc, name)}))
  .filter(({name, dirPath}) => !/^assets|components|manifest|typings$/.test(name) && fs.lstatSync(dirPath).isDirectory())

// This is the production configuration.
// It compiles slowly and is focused on producing a fast and minimal bundle.
// The development configuration is different and lives in a separate file.
module.exports = {
  // Don't attempt to continue if there are any errors.
  bail: true,
  // We generate sourcemaps in production. This is slow but gives good results.
  // You can exclude the *.map files from the build during deployment.
  devtool: shouldUseSourceMap ? 'source-map' : false,
  // In production, we only want to load the polyfills and the app code.
  entry: entries.reduce((result, {name, dirPath}) => {
    const names = fs.readdirSync(dirPath)
    const indexFile = names.find(name => /index\.((t|j)sx?)$/.test(name))
    if (!indexFile) { throw new Error(`Missing entry file for ${dirPath}`) }
    result[name] = [require.resolve('./polyfills'), path.join(dirPath, indexFile)]
    return result
  }, {}),
  output: {
    // The build folder.
    path: paths.appBuild,
    // Generated JS file names (with nested folders).
    // There will be one main bundle, and one file per asynchronous chunk.
    // We don't currently advertise code splitting but Webpack supports it.
    filename: '[name].js',
    chunkFilename: '[name].chunk.js',
    // We inferred the "public path" (such as / or /my-project) from homepage.
    publicPath: publicPath,
    // Point sourcemap entries to original disk location (format as URL on Windows)
    devtoolModuleFilenameTemplate: info =>
      path
        .relative(paths.appSrc, info.absoluteResourcePath)
        .replace(/\\/g, '/'),
  },
  resolve: {
    // This allows you to set a fallback for where Webpack should look for modules.
    // We placed these paths second because we want `node_modules` to "win"
    // if there are any conflicts. This matches Node resolution mechanism.
    // https://github.com/facebookincubator/create-react-app/issues/253
    modules: ['node_modules', paths.appNodeModules].concat(
      // It is guaranteed to exist because we tweak it in `env.js`
      process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
    ),
    // 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/facebookincubator/create-react-app/issues/290
    // `web` extension prefixes have been added for better support
    // for React Native Web.
    extensions: ['.ts', '.tsx', '.js', '.json', '.jsx', '.vue'],
    alias: {
      // Support React Native Web
      // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
      'react-native': 'react-native-web',
      'vue$': 'vue/dist/vue.runtime.esm.js',
      ...rxPaths(),
    },
    plugins: [
      // Prevents users from importing files from outside of src/ (or node_modules/).
      // This often causes confusion because we only process files within src/ with babel.
      // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
      // please link the files into your node_modules/ and let module-resolution kick in.
      // Make sure your source files are compiled, as they will not be processed in any way.
      new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
      new JsConfigPathsPlugin(),
      new TsConfigPathsPlugin(),
    ],
  },
  module: {
    strictExportPresence: true,
    rules: [
      // TODO: Disable require.ensure as it's not a standard language feature.
      // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
      // { 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: [
          // "url" loader works just like "file" loader but it also embeds
          // assets smaller than specified size as data URLs to avoid requests.
          {
            test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/, /\.svg$/],
            loader: require.resolve('url-loader'),
            options: {
              limit: 10000,
              name: 'static/[name].[ext]',
            },
          },
          {
            test: /\.tsx?$/,
            include: paths.appSrc,
            use: [
              {
                loader: require.resolve('babel-loader'),
                options: {
                  compact: true,
                },
              },
              {
                loader: require.resolve('ts-loader'),
              }
            ],
          },
          // Process JS with Babel.
          {
            test: /\.jsx?$/,
            include: paths.appSrc,
            loader: require.resolve('babel-loader'),
            options: {
              compact: true,
            },
          },
          {
            test: /\.vue$/,
            loader: 'vue-loader',
            options: {
              loaders: {
                css: genStyleLoaders('css', true),
                scss: genStyleLoaders('scss', true),
              },
              cssSourceMap: shouldUseSourceMap,
              // If you have problems debugging vue-files in devtools,
              // set this to false - it *may* help
              // https://vue-loader.vuejs.org/en/options.html#cachebusting
              cacheBusting: true,
              transformToRequire: {
                video: ['src', 'poster'],
                source: 'src',
                img: 'src',
                image: 'xlink:href'
              },
              esModule: true
            }
          },
          {
            test: /\.scss$/,
            loader: genStyleLoaders('scss', false),
          },
          {
            test: /\.css$/,
            loader: genStyleLoaders('css', false),
          },
          // "file" loader makes sure assets end up in the `build` folder.
          // When you `import` an asset, you get its filename.
          // This loader doesn't use a "test" so it will catch all modules
          // that fall through the other loaders.
          {
            loader: require.resolve('file-loader'),
            // Exclude `js` files to keep "css" loader working as it injects
            // it's runtime that would otherwise processed through "file" loader.
            // Also exclude `html` and `json` extensions so they get processed
            // by webpacks internal loaders.
            exclude: [/\.js$/, /\.html$/, /\.json$/],
            options: {
              name: 'static/[name].[ext]',
            },
          },
          // ** STOP ** Are you adding a new loader?
          // Make sure to add the new loader(s) before the "file" loader.
        ],
      },
    ],
  },
  plugins: [
    new ForkTsCheckerWebpackPlugin({tslint: true, async: false}),
    // Makes some environment variables available in index.html.
    // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
    // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    // In production, it will be an empty string unless you specify "homepage"
    // in `package.json`, in which case it will be the pathname of that URL.
    new InterpolateHtmlPlugin(env.raw),
    // Generates an `index.html` file with the <script> injected.
    ...entries.map(({name, dirPath}) => ({name, dirPath, template: path.join(dirPath, 'index.html')}))
      .filter(({template}) => fs.existsSync(template))
      .map(({name, template}) => new HtmlWebpackPlugin({
        inject: true,
        filename: name + '.html',
        chunks: [name],
        template,
        minify: {
          removeComments: true,
          collapseWhitespace: true,
          removeRedundantAttributes: true,
          useShortDoctype: true,
          removeEmptyAttributes: true,
          removeStyleLinkTypeAttributes: true,
          keepClosingSlash: true,
          minifyJS: true,
          minifyCSS: true,
          minifyURLs: true,
        },
      })),
    // Makes some environment variables available to the JS code, for example:
    // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
    // It is absolutely essential that NODE_ENV was set to production here.
    // Otherwise React will be compiled in the very slow development mode.
    new webpack.DefinePlugin(env.stringified),
    // RxJs https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md
    argv.devbuild
    ? null
    : new webpack.optimize.ModuleConcatenationPlugin(),
    // Minify the code.
    argv.devbuild
    ? null
    : new UglifyJsPlugin({
      uglifyOptions: {
        ie8: false,
        ecma: 6,
        compress: {
          warnings: false,
          // Disabled because of an issue with Uglify breaking seemingly valid code:
          // https://github.com/facebookincubator/create-react-app/issues/2376
          // Pending further investigation:
          // https://github.com/mishoo/UglifyJS2/issues/2011
          comparisons: false,
        },
        mangle: {
          safari10: true,
        },
        output: {
          comments: false,
          // Turned on because emoji and regex is not minified properly using default
          // https://github.com/facebookincubator/create-react-app/issues/2488
          ascii_only: true,
        },
      },
      sourceMap: shouldUseSourceMap,
    }),
    // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
    new ExtractTextPlugin({
      filename: cssFilename,
    }),
    // Tailor locales
    new webpack.ContextReplacementPlugin(/moment[\\/]locale$/, /^\.\/(en|zh-cn|zh-tw)$/),
    argv.analyze
    ? new BundleAnalyzerPlugin()
    : null,
  ].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.
  node: {
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty',
  },
}

// The notation here is somewhat confusing.
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader normally turns CSS into JS modules injecting <style>,
// but unlike in development configuration, we do something different.
// `ExtractTextPlugin` first applies the "postcss" and "css" loaders
// (second argument), then grabs the result CSS and puts it into a
// separate file in our build process. This way we actually ship
// a single CSS file in production instead of JS code injecting <style>
// tags. If you use code splitting, however, any async bundles will still
// use the "style" loader inside the async code so CSS from them won't be
// in the main CSS file.
function genStyleLoaders (format, isVue) {
  var use = [
    {
      loader: 'css-loader',
      options: {
        sourceMap: shouldUseSourceMap,
        minimize: !argv.devbuild,
      },
    },
    {
      loader: 'postcss-loader',
      options: { sourceMap: shouldUseSourceMap },
    },
  ]

  if (format === 'scss') {
    use.push({
      loader: 'sass-loader',
      options: {
        sourceMap: shouldUseSourceMap,
        includePaths: [path.resolve(__dirname, '../node_modules')],
      },
    })
  }

  return ExtractTextPlugin.extract(
    Object.assign(
      {
        fallback: {
          loader: require.resolve(isVue ? 'vue-style-loader' : 'style-loader'),
          options: {
            hmr: false,
          },
        },
        use,
      },
      extractTextPluginOptions
    )
  )
  // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
}

<commit_msg>build(build): ecma 7 ready<commit_after>'use strict'

const fs = require('fs')
const path = require('path')
const autoprefixer = require('autoprefixer')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin')
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin')
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const paths = require('./paths')
const getClientEnvironment = require('./env')
const argv = require('minimist')(process.argv.slice(2))
const rxPaths = require('rxjs/_esm2015/path-mapping')
const TsConfigPathsPlugin = require('tsconfig-paths-webpack-plugin')
const JsConfigPathsPlugin = require('jsconfig-paths-webpack-plugin')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin

// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
const publicPath = paths.servedPath
// Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
const shouldUseRelativeAssetPaths = publicPath === './'
// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false'
// `publicUrl` is just like `publicPath`, but we will provide it 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.
const publicUrl = publicPath.slice(0, -1)
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl)

// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (env.stringified['process.env'].NODE_ENV !== '"production"') {
  throw new Error('Production builds must have NODE_ENV=production.')
}

// Note: defined here because it will be used more than once.
const cssFilename = '[name].css'

// ExtractTextPlugin expects the build output to be flat.
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
// However, our output is structured with css, js and media folders.
// To have this structure working with relative paths, we have to use custom options.
const extractTextPluginOptions = shouldUseRelativeAssetPaths
  ? // Making sure that the publicPath goes back to to build folder.
    { publicPath: Array(cssFilename.split('/').length).join('../') }
  : {}

// Every folder in app src would generate a entry
// except 'manifest', 'assets','components', 'typings' and name starts with '_'
const entries = fs.readdirSync(paths.appSrc)
  .filter(name => !name.startsWith('_'))
  .map(name => ({name, dirPath: path.join(paths.appSrc, name)}))
  .filter(({name, dirPath}) => !/^assets|components|manifest|typings$/.test(name) && fs.lstatSync(dirPath).isDirectory())

// This is the production configuration.
// It compiles slowly and is focused on producing a fast and minimal bundle.
// The development configuration is different and lives in a separate file.
module.exports = {
  // Don't attempt to continue if there are any errors.
  bail: true,
  // We generate sourcemaps in production. This is slow but gives good results.
  // You can exclude the *.map files from the build during deployment.
  devtool: shouldUseSourceMap ? 'source-map' : false,
  // In production, we only want to load the polyfills and the app code.
  entry: entries.reduce((result, {name, dirPath}) => {
    const names = fs.readdirSync(dirPath)
    const indexFile = names.find(name => /index\.((t|j)sx?)$/.test(name))
    if (!indexFile) { throw new Error(`Missing entry file for ${dirPath}`) }
    result[name] = [require.resolve('./polyfills'), path.join(dirPath, indexFile)]
    return result
  }, {}),
  output: {
    // The build folder.
    path: paths.appBuild,
    // Generated JS file names (with nested folders).
    // There will be one main bundle, and one file per asynchronous chunk.
    // We don't currently advertise code splitting but Webpack supports it.
    filename: '[name].js',
    chunkFilename: '[name].chunk.js',
    // We inferred the "public path" (such as / or /my-project) from homepage.
    publicPath: publicPath,
    // Point sourcemap entries to original disk location (format as URL on Windows)
    devtoolModuleFilenameTemplate: info =>
      path
        .relative(paths.appSrc, info.absoluteResourcePath)
        .replace(/\\/g, '/'),
  },
  resolve: {
    // This allows you to set a fallback for where Webpack should look for modules.
    // We placed these paths second because we want `node_modules` to "win"
    // if there are any conflicts. This matches Node resolution mechanism.
    // https://github.com/facebookincubator/create-react-app/issues/253
    modules: ['node_modules', paths.appNodeModules].concat(
      // It is guaranteed to exist because we tweak it in `env.js`
      process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
    ),
    // 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/facebookincubator/create-react-app/issues/290
    // `web` extension prefixes have been added for better support
    // for React Native Web.
    extensions: ['.ts', '.tsx', '.js', '.json', '.jsx', '.vue'],
    alias: {
      // Support React Native Web
      // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
      'react-native': 'react-native-web',
      'vue$': 'vue/dist/vue.runtime.esm.js',
      ...rxPaths(),
    },
    plugins: [
      // Prevents users from importing files from outside of src/ (or node_modules/).
      // This often causes confusion because we only process files within src/ with babel.
      // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
      // please link the files into your node_modules/ and let module-resolution kick in.
      // Make sure your source files are compiled, as they will not be processed in any way.
      new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
      new JsConfigPathsPlugin(),
      new TsConfigPathsPlugin(),
    ],
  },
  module: {
    strictExportPresence: true,
    rules: [
      // TODO: Disable require.ensure as it's not a standard language feature.
      // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
      // { 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: [
          // "url" loader works just like "file" loader but it also embeds
          // assets smaller than specified size as data URLs to avoid requests.
          {
            test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/, /\.svg$/],
            loader: require.resolve('url-loader'),
            options: {
              limit: 10000,
              name: 'static/[name].[ext]',
            },
          },
          {
            test: /\.tsx?$/,
            include: paths.appSrc,
            use: [
              {
                loader: require.resolve('babel-loader'),
                options: {
                  compact: true,
                },
              },
              {
                loader: require.resolve('ts-loader'),
              }
            ],
          },
          // Process JS with Babel.
          {
            test: /\.jsx?$/,
            include: paths.appSrc,
            loader: require.resolve('babel-loader'),
            options: {
              compact: true,
            },
          },
          {
            test: /\.vue$/,
            loader: 'vue-loader',
            options: {
              loaders: {
                css: genStyleLoaders('css', true),
                scss: genStyleLoaders('scss', true),
              },
              cssSourceMap: shouldUseSourceMap,
              // If you have problems debugging vue-files in devtools,
              // set this to false - it *may* help
              // https://vue-loader.vuejs.org/en/options.html#cachebusting
              cacheBusting: true,
              transformToRequire: {
                video: ['src', 'poster'],
                source: 'src',
                img: 'src',
                image: 'xlink:href'
              },
              esModule: true
            }
          },
          {
            test: /\.scss$/,
            loader: genStyleLoaders('scss', false),
          },
          {
            test: /\.css$/,
            loader: genStyleLoaders('css', false),
          },
          // "file" loader makes sure assets end up in the `build` folder.
          // When you `import` an asset, you get its filename.
          // This loader doesn't use a "test" so it will catch all modules
          // that fall through the other loaders.
          {
            loader: require.resolve('file-loader'),
            // Exclude `js` files to keep "css" loader working as it injects
            // it's runtime that would otherwise processed through "file" loader.
            // Also exclude `html` and `json` extensions so they get processed
            // by webpacks internal loaders.
            exclude: [/\.js$/, /\.html$/, /\.json$/],
            options: {
              name: 'static/[name].[ext]',
            },
          },
          // ** STOP ** Are you adding a new loader?
          // Make sure to add the new loader(s) before the "file" loader.
        ],
      },
    ],
  },
  plugins: [
    new ForkTsCheckerWebpackPlugin({tslint: true, async: false}),
    // Makes some environment variables available in index.html.
    // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
    // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    // In production, it will be an empty string unless you specify "homepage"
    // in `package.json`, in which case it will be the pathname of that URL.
    new InterpolateHtmlPlugin(env.raw),
    // Generates an `index.html` file with the <script> injected.
    ...entries.map(({name, dirPath}) => ({name, dirPath, template: path.join(dirPath, 'index.html')}))
      .filter(({template}) => fs.existsSync(template))
      .map(({name, template}) => new HtmlWebpackPlugin({
        inject: true,
        filename: name + '.html',
        chunks: [name],
        template,
        minify: {
          removeComments: true,
          collapseWhitespace: true,
          removeRedundantAttributes: true,
          useShortDoctype: true,
          removeEmptyAttributes: true,
          removeStyleLinkTypeAttributes: true,
          keepClosingSlash: true,
          minifyJS: true,
          minifyCSS: true,
          minifyURLs: true,
        },
      })),
    // Makes some environment variables available to the JS code, for example:
    // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
    // It is absolutely essential that NODE_ENV was set to production here.
    // Otherwise React will be compiled in the very slow development mode.
    new webpack.DefinePlugin(env.stringified),
    // RxJs https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md
    argv.devbuild
    ? null
    : new webpack.optimize.ModuleConcatenationPlugin(),
    // Minify the code.
    argv.devbuild
    ? null
    : new UglifyJsPlugin({
      uglifyOptions: {
        ie8: false,
        ecma: 7,
        compress: {
          warnings: false,
          // Disabled because of an issue with Uglify breaking seemingly valid code:
          // https://github.com/facebookincubator/create-react-app/issues/2376
          // Pending further investigation:
          // https://github.com/mishoo/UglifyJS2/issues/2011
          comparisons: false,
        },
        mangle: {
          safari10: true,
        },
        output: {
          comments: false,
          // Turned on because emoji and regex is not minified properly using default
          // https://github.com/facebookincubator/create-react-app/issues/2488
          ascii_only: true,
        },
      },
      sourceMap: shouldUseSourceMap,
    }),
    // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
    new ExtractTextPlugin({
      filename: cssFilename,
    }),
    // Tailor locales
    new webpack.ContextReplacementPlugin(/moment[\\/]locale$/, /^\.\/(en|zh-cn|zh-tw)$/),
    argv.analyze
    ? new BundleAnalyzerPlugin()
    : null,
  ].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.
  node: {
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty',
  },
}

// The notation here is somewhat confusing.
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader normally turns CSS into JS modules injecting <style>,
// but unlike in development configuration, we do something different.
// `ExtractTextPlugin` first applies the "postcss" and "css" loaders
// (second argument), then grabs the result CSS and puts it into a
// separate file in our build process. This way we actually ship
// a single CSS file in production instead of JS code injecting <style>
// tags. If you use code splitting, however, any async bundles will still
// use the "style" loader inside the async code so CSS from them won't be
// in the main CSS file.
function genStyleLoaders (format, isVue) {
  var use = [
    {
      loader: 'css-loader',
      options: {
        sourceMap: shouldUseSourceMap,
        minimize: !argv.devbuild,
      },
    },
    {
      loader: 'postcss-loader',
      options: { sourceMap: shouldUseSourceMap },
    },
  ]

  if (format === 'scss') {
    use.push({
      loader: 'sass-loader',
      options: {
        sourceMap: shouldUseSourceMap,
        includePaths: [path.resolve(__dirname, '../node_modules')],
      },
    })
  }

  return ExtractTextPlugin.extract(
    Object.assign(
      {
        fallback: {
          loader: require.resolve(isVue ? 'vue-style-loader' : 'style-loader'),
          options: {
            hmr: false,
          },
        },
        use,
      },
      extractTextPluginOptions
    )
  )
  // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
}

<|endoftext|>


<commit_before>'use strict';

const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const paths = require('./paths');
const getClientEnvironment = require('./env');

// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
const publicPath = paths.servedPath;
// Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
const shouldUseRelativeAssetPaths = publicPath === './';
// `publicUrl` is just like `publicPath`, but we will provide it 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.
const publicUrl = publicPath.slice(0, -1);
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);

// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (env.stringified['process.env'].NODE_ENV !== '"production"') {
  throw new Error('Production builds must have NODE_ENV=production.');
}

// Note: defined here because it will be used more than once.
const cssFilename = 'static/css/[name].[contenthash:8].css';

// ExtractTextPlugin expects the build output to be flat.
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
// However, our output is structured with css, js and media folders.
// To have this structure working with relative paths, we have to use custom options.
const extractTextPluginOptions = shouldUseRelativeAssetPaths
  ? // Making sure that the publicPath goes back to to build folder.
    { publicPath: Array(cssFilename.split('/').length).join('../') }
  : {};

// This is the production configuration.
// It compiles slowly and is focused on producing a fast and minimal bundle.
// The development configuration is different and lives in a separate file.
module.exports = {
  // Don't attempt to continue if there are any errors.
  bail: true,
  // We generate sourcemaps in production. This is slow but gives good results.
  // You can exclude the *.map files from the build during deployment.
  devtool: 'source-map',
  // In production, we only want to load the polyfills and the app code.
  entry: [require.resolve('./polyfills'), paths.appIndexJs],
  output: {
    // The build folder.
    path: paths.appBuild,
    // Generated JS file names (with nested folders).
    // There will be one main bundle, and one file per asynchronous chunk.
    // We don't currently advertise code splitting but Webpack supports it.
    filename: 'static/js/[name].[chunkhash:8].js',
    chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
    // We inferred the "public path" (such as / or /my-project) from homepage.
    publicPath: publicPath,
    // Point sourcemap entries to original disk location (format as URL on Windows)
    devtoolModuleFilenameTemplate: info =>
      path
        .relative(paths.appSrc, info.absoluteResourcePath)
        .replace(/\\/g, '/'),
  },
  resolve: {
    // This allows you to set a fallback for where Webpack should look for modules.
    // We placed these paths second because we want `node_modules` to "win"
    // if there are any conflicts. This matches Node resolution mechanism.
    // https://github.com/facebookincubator/create-react-app/issues/253
    modules: ['node_modules', paths.appNodeModules].concat(
      // It is guaranteed to exist because we tweak it in `env.js`
      process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
    ),
    // 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/facebookincubator/create-react-app/issues/290
    // `web` extension prefixes have been added for better support
    // for React Native Web.
    extensions: ['.web.js', '.js', '.json', '.web.jsx', '.jsx'],
    alias: {

      // Support React Native Web
      // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
      'react-native': 'react-native-web',
    },
    plugins: [
      // Prevents users from importing files from outside of src/ (or node_modules/).
      // This often causes confusion because we only process files within src/ with babel.
      // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
      // please link the files into your node_modules/ and let module-resolution kick in.
      // Make sure your source files are compiled, as they will not be processed in any way.
      new ModuleScopePlugin(paths.appSrc),
    ],
  },
  module: {
    strictExportPresence: true,
    rules: [
      // TODO: Disable require.ensure as it's not a standard language feature.
      // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
      // { parser: { requireEnsure: false } },

      // First, run the linter.
      // It's important to do this before Babel processes the JS.
      {
        test: /\.(js|jsx)$/,
        enforce: 'pre',
        use: [
          {
            options: {
              formatter: eslintFormatter,

            },
            loader: require.resolve('eslint-loader'),
          },
        ],
        include: paths.appSrc,
      },
      // ** ADDING/UPDATING LOADERS **
      // The "file" loader handles all assets unless explicitly excluded.
      // The `exclude` list *must* be updated with every change to loader extensions.
      // When adding a new loader, you must add its `test`
      // as a new entry in the `exclude` list in the "file" loader.

      // "file" loader makes sure those assets end up in the `build` folder.
      // When you `import` an asset, you get its filename.
      {
        exclude: [
          /\.html$/,
          /\.(js|jsx)$/,
          /\.css$/,
          /\.json$/,
          /\.bmp$/,
          /\.gif$/,
          /\.jpe?g$/,
          /\.png$/,
        ],
        loader: require.resolve('file-loader'),
        options: {
          name: 'static/media/[name].[hash:8].[ext]',
        },
      },
      // "url" loader works just like "file" loader but it also embeds
      // assets smaller than specified size as data URLs to avoid requests.
      {
        test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
        loader: require.resolve('url-loader'),
        options: {
          limit: 10000,
          name: 'static/media/[name].[hash:8].[ext]',
        },
      },
      // Process JS with Babel.
      {
        test: /\.(js|jsx)$/,
        include: paths.appSrc,
        loader: require.resolve('babel-loader'),
        options: {

          compact: true,
        },
      },
      // The notation here is somewhat confusing.
      // "postcss" loader applies autoprefixer to our CSS.
      // "css" loader resolves paths in CSS and adds assets as dependencies.
      // "style" loader normally turns CSS into JS modules injecting <style>,
      // but unlike in development configuration, we do something different.
      // `ExtractTextPlugin` first applies the "postcss" and "css" loaders
      // (second argument), then grabs the result CSS and puts it into a
      // separate file in our build process. This way we actually ship
      // a single CSS file in production instead of JS code injecting <style>
      // tags. If you use code splitting, however, any async bundles will still
      // use the "style" loader inside the async code so CSS from them won't be
      // in the main CSS file.
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract(
          Object.assign(
            {
              fallback: require.resolve('style-loader'),
              use: [
                {
                  loader: require.resolve('css-loader'),
                  options: {
                    importLoaders: 1,
                    modules: true,
                    minimize: true,
                    sourceMap: true,
                  },
                },
                {
                  loader: require.resolve('postcss-loader'),
                  options: {
                    // Necessary for external CSS imports to work
                    // https://github.com/facebookincubator/create-react-app/issues/2677
                    ident: 'postcss',
                    plugins: () => [
                      require('postcss-flexbugs-fixes'),
                      autoprefixer({
                        browsers: [
                          '>1%',
                          'last 4 versions',
                          'Firefox ESR',
                          'not ie < 9', // React doesn't support IE8 anyway
                        ],
                        flexbox: 'no-2009',
                      }),
                    ],
                  },
                },
              ],
            },
            extractTextPluginOptions
          )
        ),
        // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
      },
      // ** STOP ** Are you adding a new loader?
      // Remember to add the new extension(s) to the "file" loader exclusion list.
    ],
  },
  plugins: [
    // Makes some environment variables available in index.html.
    // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
    // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    // In production, it will be an empty string unless you specify "homepage"
    // in `package.json`, in which case it will be the pathname of that URL.
    new InterpolateHtmlPlugin(env.raw),
    // Generates an `index.html` file with the <script> injected.
    new HtmlWebpackPlugin({
      inject: true,
      template: paths.appHtml,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
    }),
    // Makes some environment variables available to the JS code, for example:
    // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
    // It is absolutely essential that NODE_ENV was set to production here.
    // Otherwise React will be compiled in the very slow development mode.
    new webpack.DefinePlugin(env.stringified),
    // Minify the code.
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        // Disabled because of an issue with Uglify breaking seemingly valid code:
        // https://github.com/facebookincubator/create-react-app/issues/2376
        // Pending further investigation:
        // https://github.com/mishoo/UglifyJS2/issues/2011
        comparisons: false,
      },
      output: {
        comments: false,
        // Turned on because emoji and regex is not minified properly using default
        // https://github.com/facebookincubator/create-react-app/issues/2488
        ascii_only: true,
      },
      sourceMap: true,
    }),
    // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
    new ExtractTextPlugin({
      filename: cssFilename,
    }),
    // Generate a manifest file which contains a mapping of all asset filenames
    // to their corresponding output file so that tools can pick it up without
    // having to parse `index.html`.
    new ManifestPlugin({
      fileName: 'asset-manifest.json',
    }),
    // Generate a service worker script that will precache, and keep up to date,
    // the HTML & assets that are part of the Webpack build.
    new SWPrecacheWebpackPlugin({
      // By default, a cache-busting query parameter is appended to requests
      // used to populate the caches, to ensure the responses are fresh.
      // If a URL is already hashed by Webpack, then there is no concern
      // about it being stale, and the cache-busting can be skipped.
      dontCacheBustUrlsMatching: /\.\w{8}\./,
      filename: 'service-worker.js',
      logger(message) {
        if (message.indexOf('Total precache size is') === 0) {
          // This message occurs for every build and is a bit too noisy.
          return;
        }
        if (message.indexOf('Skipping static resource') === 0) {
          // This message obscures real errors so we ignore it.
          // https://github.com/facebookincubator/create-react-app/issues/2612
          return;
        }
        console.log(message);
      },
      minify: true,
      // For unknown URLs, fallback to the index page
      navigateFallback: publicUrl + '/index.html',
      // Ignores URLs starting from /__ (useful for Firebase):
      // https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
      navigateFallbackWhitelist: [/^(?!\/__).*/],
      // Don't precache sourcemaps (they're large) and build asset manifest:
      staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
    }),
    // 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(/^\.\/locale$/, /moment$/),
  ],
  // 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.
  node: {
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
  },
};
<commit_msg>prod sass configs<commit_after>'use strict';

const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const paths = require('./paths');
const getClientEnvironment = require('./env');

// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
const publicPath = paths.servedPath;
// Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
const shouldUseRelativeAssetPaths = publicPath === './';
// `publicUrl` is just like `publicPath`, but we will provide it 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.
const publicUrl = publicPath.slice(0, -1);
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);

// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (env.stringified['process.env'].NODE_ENV !== '"production"') {
  throw new Error('Production builds must have NODE_ENV=production.');
}

// Note: defined here because it will be used more than once.
const cssFilename = 'static/css/[name].[contenthash:8].css';

// ExtractTextPlugin expects the build output to be flat.
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
// However, our output is structured with css, js and media folders.
// To have this structure working with relative paths, we have to use custom options.
const extractTextPluginOptions = shouldUseRelativeAssetPaths
  ? // Making sure that the publicPath goes back to to build folder.
    { publicPath: Array(cssFilename.split('/').length).join('../') }
  : {};

// This is the production configuration.
// It compiles slowly and is focused on producing a fast and minimal bundle.
// The development configuration is different and lives in a separate file.
module.exports = {
  // Don't attempt to continue if there are any errors.
  bail: true,
  // We generate sourcemaps in production. This is slow but gives good results.
  // You can exclude the *.map files from the build during deployment.
  devtool: 'source-map',
  // In production, we only want to load the polyfills and the app code.
  entry: [require.resolve('./polyfills'), paths.appIndexJs],
  output: {
    // The build folder.
    path: paths.appBuild,
    // Generated JS file names (with nested folders).
    // There will be one main bundle, and one file per asynchronous chunk.
    // We don't currently advertise code splitting but Webpack supports it.
    filename: 'static/js/[name].[chunkhash:8].js',
    chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
    // We inferred the "public path" (such as / or /my-project) from homepage.
    publicPath: publicPath,
    // Point sourcemap entries to original disk location (format as URL on Windows)
    devtoolModuleFilenameTemplate: info =>
      path
        .relative(paths.appSrc, info.absoluteResourcePath)
        .replace(/\\/g, '/'),
  },
  resolve: {
    // This allows you to set a fallback for where Webpack should look for modules.
    // We placed these paths second because we want `node_modules` to "win"
    // if there are any conflicts. This matches Node resolution mechanism.
    // https://github.com/facebookincubator/create-react-app/issues/253
    modules: ['node_modules', paths.appNodeModules].concat(
      // It is guaranteed to exist because we tweak it in `env.js`
      process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
    ),
    // 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/facebookincubator/create-react-app/issues/290
    // `web` extension prefixes have been added for better support
    // for React Native Web.
    extensions: ['.web.js', '.js', '.json', '.web.jsx', '.jsx'],
    alias: {

      // Support React Native Web
      // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
      'react-native': 'react-native-web',
    },
    plugins: [
      // Prevents users from importing files from outside of src/ (or node_modules/).
      // This often causes confusion because we only process files within src/ with babel.
      // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
      // please link the files into your node_modules/ and let module-resolution kick in.
      // Make sure your source files are compiled, as they will not be processed in any way.
      new ModuleScopePlugin(paths.appSrc),
    ],
  },
  module: {
    strictExportPresence: true,
    rules: [
      // TODO: Disable require.ensure as it's not a standard language feature.
      // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
      // { parser: { requireEnsure: false } },

      // First, run the linter.
      // It's important to do this before Babel processes the JS.
      {
        test: /\.(js|jsx)$/,
        enforce: 'pre',
        use: [
          {
            options: {
              formatter: eslintFormatter,

            },
            loader: require.resolve('eslint-loader'),
          },
        ],
        include: paths.appSrc,
      },
      // ** ADDING/UPDATING LOADERS **
      // The "file" loader handles all assets unless explicitly excluded.
      // The `exclude` list *must* be updated with every change to loader extensions.
      // When adding a new loader, you must add its `test`
      // as a new entry in the `exclude` list in the "file" loader.

      // "file" loader makes sure those assets end up in the `build` folder.
      // When you `import` an asset, you get its filename.
      {
        exclude: [
          /\.html$/,
          /\.(js|jsx)$/,
          /\.css$/,
          /\.json$/,
          /\.bmp$/,
          /\.gif$/,
          /\.jpe?g$/,
          /\.png$/,
          /\.scss$/,
          /\.sass$/,
        ],
        loader: require.resolve('file-loader'),
        options: {
          name: 'static/media/[name].[hash:8].[ext]',
        },
      },
      // "url" loader works just like "file" loader but it also embeds
      // assets smaller than specified size as data URLs to avoid requests.
      {
        test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
        loader: require.resolve('url-loader'),
        options: {
          limit: 10000,
          name: 'static/media/[name].[hash:8].[ext]',
        },
      },
      // Process JS with Babel.
      {
        test: /\.(js|jsx)$/,
        include: paths.appSrc,
        loader: require.resolve('babel-loader'),
        options: {

          compact: true,
        },
      },
      // The notation here is somewhat confusing.
      // "postcss" loader applies autoprefixer to our CSS.
      // "css" loader resolves paths in CSS and adds assets as dependencies.
      // "style" loader normally turns CSS into JS modules injecting <style>,
      // but unlike in development configuration, we do something different.
      // `ExtractTextPlugin` first applies the "postcss" and "css" loaders
      // (second argument), then grabs the result CSS and puts it into a
      // separate file in our build process. This way we actually ship
      // a single CSS file in production instead of JS code injecting <style>
      // tags. If you use code splitting, however, any async bundles will still
      // use the "style" loader inside the async code so CSS from them won't be
      // in the main CSS file.
      {
        test: /\.s?[ca]ss$/,
        loader: ExtractTextPlugin.extract(
          Object.assign(
            {
              fallback: require.resolve('style-loader'),
              use: [
                {
                  loader: require.resolve('css-loader'),
                  options: {
                    importLoaders: 1,
                    modules: true,
                    minimize: true,
                    sourceMap: true,
                  },
                },
                {
                  loader: require.resolve('postcss-loader'),
                  options: {
                    // Necessary for external CSS imports to work
                    // https://github.com/facebookincubator/create-react-app/issues/2677
                    ident: 'postcss',
                    plugins: () => [
                      require('postcss-flexbugs-fixes'),
                      autoprefixer({
                        browsers: [
                          '>1%',
                          'last 4 versions',
                          'Firefox ESR',
                          'not ie < 9', // React doesn't support IE8 anyway
                        ],
                        flexbox: 'no-2009',
                      }),
                    ],
                  },
                }, {
                  loader: 'sass-loader'
                }
              ],
            },
            extractTextPluginOptions
          )
        ),
        // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
      },
      // ** STOP ** Are you adding a new loader?
      // Remember to add the new extension(s) to the "file" loader exclusion list.
    ],
  },
  plugins: [
    // Makes some environment variables available in index.html.
    // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
    // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    // In production, it will be an empty string unless you specify "homepage"
    // in `package.json`, in which case it will be the pathname of that URL.
    new InterpolateHtmlPlugin(env.raw),
    // Generates an `index.html` file with the <script> injected.
    new HtmlWebpackPlugin({
      inject: true,
      template: paths.appHtml,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
    }),
    // Makes some environment variables available to the JS code, for example:
    // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
    // It is absolutely essential that NODE_ENV was set to production here.
    // Otherwise React will be compiled in the very slow development mode.
    new webpack.DefinePlugin(env.stringified),
    // Minify the code.
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        // Disabled because of an issue with Uglify breaking seemingly valid code:
        // https://github.com/facebookincubator/create-react-app/issues/2376
        // Pending further investigation:
        // https://github.com/mishoo/UglifyJS2/issues/2011
        comparisons: false,
      },
      output: {
        comments: false,
        // Turned on because emoji and regex is not minified properly using default
        // https://github.com/facebookincubator/create-react-app/issues/2488
        ascii_only: true,
      },
      sourceMap: true,
    }),
    // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
    new ExtractTextPlugin({
      filename: cssFilename,
    }),
    // Generate a manifest file which contains a mapping of all asset filenames
    // to their corresponding output file so that tools can pick it up without
    // having to parse `index.html`.
    new ManifestPlugin({
      fileName: 'asset-manifest.json',
    }),
    // Generate a service worker script that will precache, and keep up to date,
    // the HTML & assets that are part of the Webpack build.
    new SWPrecacheWebpackPlugin({
      // By default, a cache-busting query parameter is appended to requests
      // used to populate the caches, to ensure the responses are fresh.
      // If a URL is already hashed by Webpack, then there is no concern
      // about it being stale, and the cache-busting can be skipped.
      dontCacheBustUrlsMatching: /\.\w{8}\./,
      filename: 'service-worker.js',
      logger(message) {
        if (message.indexOf('Total precache size is') === 0) {
          // This message occurs for every build and is a bit too noisy.
          return;
        }
        if (message.indexOf('Skipping static resource') === 0) {
          // This message obscures real errors so we ignore it.
          // https://github.com/facebookincubator/create-react-app/issues/2612
          return;
        }
        console.log(message);
      },
      minify: true,
      // For unknown URLs, fallback to the index page
      navigateFallback: publicUrl + '/index.html',
      // Ignores URLs starting from /__ (useful for Firebase):
      // https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
      navigateFallbackWhitelist: [/^(?!\/__).*/],
      // Don't precache sourcemaps (they're large) and build asset manifest:
      staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
    }),
    // 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(/^\.\/locale$/, /moment$/),
  ],
  // 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.
  node: {
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
  },
};
<|endoftext|>


<commit_before>/* eslint-disable no-var */

var path = require('path');
var webpack = require('webpack');
var merge = require('webpack-merge');
var HtmlWebpackPlugin = require('html-webpack-plugin');

var common = require('./webpack.common');

module.exports = merge(common, {
  entry: [
    'webpack-hot-middleware/client?reload=true',
    path.resolve(__dirname, '../app/index.js'),
  ],
  debug: true,
  devtool: 'cheap-module-eval-source-map',
  output: {
    path: path.resolve(__dirname, '../dist'),
    filename: 'app.js',
    publicPath: '/',
  },
  module: {
    preLoaders: [
      {
        test: /\.js$/,
        include: path.resolve(__dirname, '../app'),
        loader: 'eslint',
      },
    ],
    loaders: [
      {
        test: /\.js$/,
        include: path.resolve(__dirname, '../app'),
        exclude: path.resolve(__dirname, '../node_modules'),
        loader: 'babel',
        query: {
          'stage': 2,
          'plugins': ['react-transform'],
          'extra': {
            'react-transform': {
              'transforms': [{
                'transform': 'react-transform-hmr',
                'imports': ['react'],
                'locals': ['module'],
              }, {
                'transform': 'react-transform-catch-errors',
                'imports': ['react', 'redbox-react'],
              }],
            },
          },
        },
      },
      {
        test: /\.css$/,
        loader: 'style!css!postcss-loader',
      },
      {
        test: /\.less$/,
        loader: 'style!css!postcss-loader!less',
      },
    ],
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('development'),
      __DEVTOOLS__: true,
    }),
    new HtmlWebpackPlugin({
      favicon: './app/assets/images/favicon.ico',
      inject: true,
      template: './app/index.template.html',
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
  ],
});
<commit_msg>Disable devtools on development on default<commit_after>/* eslint-disable no-var */

var path = require('path');
var webpack = require('webpack');
var merge = require('webpack-merge');
var HtmlWebpackPlugin = require('html-webpack-plugin');

var common = require('./webpack.common');

module.exports = merge(common, {
  entry: [
    'webpack-hot-middleware/client?reload=true',
    path.resolve(__dirname, '../app/index.js'),
  ],
  debug: true,
  devtool: 'cheap-module-eval-source-map',
  output: {
    path: path.resolve(__dirname, '../dist'),
    filename: 'app.js',
    publicPath: '/',
  },
  module: {
    preLoaders: [
      {
        test: /\.js$/,
        include: path.resolve(__dirname, '../app'),
        loader: 'eslint',
      },
    ],
    loaders: [
      {
        test: /\.js$/,
        include: path.resolve(__dirname, '../app'),
        exclude: path.resolve(__dirname, '../node_modules'),
        loader: 'babel',
        query: {
          'stage': 2,
          'plugins': ['react-transform'],
          'extra': {
            'react-transform': {
              'transforms': [{
                'transform': 'react-transform-hmr',
                'imports': ['react'],
                'locals': ['module'],
              }, {
                'transform': 'react-transform-catch-errors',
                'imports': ['react', 'redbox-react'],
              }],
            },
          },
        },
      },
      {
        test: /\.css$/,
        loader: 'style!css!postcss-loader',
      },
      {
        test: /\.less$/,
        loader: 'style!css!postcss-loader!less',
      },
    ],
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('development'),
      __DEVTOOLS__: false,
    }),
    new HtmlWebpackPlugin({
      favicon: './app/assets/images/favicon.ico',
      inject: true,
      template: './app/index.template.html',
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
  ],
});
<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');
var merge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var baseConfig = require('./webpack.config');

module.exports = merge.smart(baseConfig, {
	devtool: false,

	entry: './docs/src/docs.js',

	output: {
		path: path.resolve(__dirname, '../docs/public'),
		publicPath: '/build/',
		filename: 'bundle.js',
	},

	module: {
		loaders: [
			{
				test: /\.styl$/,
				loader: ExtractTextPlugin.extract('style-loader', 'css-loader!postcss-loader!stylus-loader'),
			},
		],
	},

	plugins: [
		new webpack.optimize.UglifyJsPlugin({
			sourceMap: false,
			compress: {
				warnings: false,
			},
		}),
		new ExtractTextPlugin('styles.css'),
	],

	stylus: {
		import: [
			path.resolve(__dirname, '../docs/src/styles/config.styl'),
		],
	},
});
<commit_msg>UglifyJS: remove comments.<commit_after>var path = require('path');
var webpack = require('webpack');
var merge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var baseConfig = require('./webpack.config');

module.exports = merge.smart(baseConfig, {
	devtool: false,

	entry: './docs/src/docs.js',

	output: {
		path: path.resolve(__dirname, '../docs/public'),
		publicPath: '/build/',
		filename: 'bundle.js',
	},

	module: {
		loaders: [
			{
				test: /\.styl$/,
				loader: ExtractTextPlugin.extract('style-loader', 'css-loader!postcss-loader!stylus-loader'),
			},
		],
	},

	plugins: [
		new webpack.optimize.UglifyJsPlugin({
			sourceMap: false,
			compress: {
				warnings: false,
			},
			output: {
				comments: false,
			},
		}),
		new ExtractTextPlugin('styles.css'),
	],

	stylus: {
		import: [
			path.resolve(__dirname, '../docs/src/styles/config.styl'),
		],
	},
});
<|endoftext|>


<commit_before>var _ = require('underscore');

module.exports = _.clone(require('./bus'));
<commit_msg>Emit 'exit' on exit<commit_after>var process = require('process');
var _ = require('underscore');

var butler = module.exports = _.clone(require('./bus'));

process.on('exit', function(code) {
  butler.emit('exit', code);
});

process.on('SIGINT', function() {
  process.exit();
});

process.on('uncaughtException', function(err) {
  console.log(err.stack);
  process.exit(1);
});
<|endoftext|>


<commit_before>/* eslint max-nested-callbacks:[1] */

'use strict';

var fs = require('fs');
var path = require('path');
var gulp = require('gulp');
var iconfont = require('../src/index');
var assert = require('assert');
var neatequal = require('neatequal');
var streamtest = require('streamtest');

describe('gulp-iconfont', function() {
  var generationTimestamp = 3;

  streamtest.versions.forEach(function(version) {
    describe('for ' + version + ' streams', function() {

      describe('in stream mode', function() {

        it('should work', function(done) {
          var contents = [];
          var processedFiles = 0;

          gulp.src(path.join(__dirname, 'fixtures', 'iconsfont', '*.svg'), { buffer: false })
            .pipe(iconfont({
              fontName: 'iconsfont',
              timestamp: generationTimestamp,
            }))
            .pipe(streamtest[version].toObjects(function(err, files) {
              if(err) {
                return done(err);
              }
              assert.equal(files.length, 3);
              files.forEach(function(file, index) {
                file.contents.pipe(streamtest[version].toChunks(function(err2, chunks) {
                  if(err2) {
                    return done(err2);
                  }
                  contents[index] = Buffer.concat(chunks);
                  processedFiles++;
                  if(processedFiles === files.length) {
                    assert.deepEqual(
                      contents[0],
                      fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.ttf'))
                    );
                    assert.deepEqual(
                      contents[1],
                      fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.woff'))
                    );
                    assert.deepEqual(
                      contents[2],
                      fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.eot'))
                    );
                    return done();
                  }
                }));
              });
            }));
        });

        it('should work for only one font', function(done) {
          var contents = [];
          var processedFiles = 0;

          gulp.src(path.join(__dirname, 'fixtures', 'iconsfont', '*.svg'), { buffer: false })
            .pipe(iconfont({
              fontName: 'iconsfont',
              timestamp: generationTimestamp,
              formats: ['woff'],
            }))
            .pipe(streamtest[version].toObjects(function(err, files) {
              if(err) {
                return done(err);
              }
              assert.equal(files.length, 1);
              files.forEach(function(file, index) {
                file.contents.pipe(streamtest[version].toChunks(function(err2, chunks) {
                  if(err2) {
                    return done(err2);
                  }
                  contents[index] = Buffer.concat(chunks);
                  processedFiles++;
                  if(processedFiles === files.length) {
                    assert.deepEqual(
                      contents[0],
                      fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.woff'))
                    );
                    return done();
                  }
                }));
              });
            }));
        });

        it('should output SVG font with svg added to formats', function(done) {
          var contents = [];
          var processedFiles = 0;

          this.timeout(5000);
          gulp.src(path.join(__dirname, 'fixtures', 'iconsfont', '*.svg'), { buffer: false })
            .pipe(iconfont({
              fontName: 'iconsfont',
              formats: [
                'svg',
                'ttf',
                'eot',
                'woff',
              ],
              timestamp: generationTimestamp,
            }))
            .pipe(streamtest[version].toObjects(function(err, files) {
              if(err) {
                return done(err);
              }
              assert.equal(files.length, 4);
              files.forEach(function(file, index) {
                file.contents.pipe(streamtest[version].toChunks(function(err2, chunks) {
                  if(err2) {
                    return done(err2);
                  }
                  contents[index] = Buffer.concat(chunks);
                  processedFiles++;
                  if(processedFiles === files.length) {
                    assert.deepEqual(
                      contents[0],
                      fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.svg'))
                    );
                    assert.deepEqual(
                      contents[1],
                      fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.ttf'))
                    );
                    assert.deepEqual(
                      contents[2],
                      fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.woff'))
                    );
                    assert.deepEqual(
                      contents[3],
                      fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.eot'))
                    );
                    return done();
                  }
                }));
              });
            }));
        });

        it('should output WOFF2 font with woff2 added to formats', function(done) {
          var contents = [];
          var processedFiles = 0;

          this.timeout(5000);
          gulp.src(path.join(__dirname, 'fixtures', 'iconsfont', '*.svg'), { buffer: false })
            .pipe(iconfont({
              fontName: 'iconsfont',
              formats: [
                'ttf',
                'woff',
                'woff2',
              ],
              timestamp: generationTimestamp,
            }))
            .pipe(streamtest[version].toObjects(function(err, files) {
              if(err) {
                return done(err);
              }
              assert.equal(files.length, 3);
              files.forEach(function(file, index) {
                file.contents.pipe(streamtest[version].toChunks(function(err2, chunks) {
                  if(err2) {
                    return done(err2);
                  }
                  contents[index] = Buffer.concat(chunks);
                  processedFiles++;
                  if(processedFiles === files.length) {
                    assert.deepEqual(
                      contents[0],
                      fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.ttf'))
                    );
                    assert.deepEqual(
                      contents[1],
                      fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.woff2'))
                    );
                    assert.deepEqual(
                      contents[2],
                      fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.woff'))
                    );
                    return done();
                  }
                }));
              });
            }));
        });

      });

      describe('in buffer mode', function() {

        it('should work', function(done) {
          gulp.src(path.join(__dirname, 'fixtures', 'iconsfont', '*.svg'), { buffer: true })
            .pipe(iconfont({
              fontName: 'iconsfont',
              timestamp: generationTimestamp,
            }))
            .pipe(streamtest[version].toObjects(function(err, files) {
              if(err) {
                return done(err);
              }
              assert.equal(files.length, 3);
              assert.deepEqual(
                files[0].contents,
                fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.ttf'))
              );
              assert.deepEqual(
                files[1].contents,
                fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.woff'))
              );
              assert.deepEqual(
                files[2].contents,
                fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.eot'))
              );
              done();
            }));
        });

        it('should emit an event with the codepoint mapping', function(done) {
          var codepoints;

          gulp.src(path.join(__dirname, 'fixtures', 'iconsfont', '*.svg'), { buffer: true })
            .pipe(iconfont({
              fontName: 'iconsfont',
              timestamp: generationTimestamp,
            })).on('glyphs', function(_codepoints_) {
              codepoints = _codepoints_;
            })
            .pipe(streamtest[version].toObjects(function(err, files) {
              if(err) {
                return done(err);
              }
              assert.equal(files.length, 3);
              neatequal(codepoints,
                JSON.parse(fs.readFileSync(
                  path.join(__dirname, 'expected', 'codepoints.json'), 'utf8'))
              );
              done();
            }));
        });
        it.only('should work with autohinted iconsfont', function(done) {
          gulp.src(path.join(__dirname, 'fixtures', 'iconsfont', '*.svg'), { buffer: true })
            .pipe(iconfont({
              fontName: 'iconsfont',
              timestamp: generationTimestamp,
              autohint: __dirname + '/ttfautohint/ttfautohint.sh',
              formats: ['ttf']
            }))
            .pipe(streamtest[version].toObjects(function(err, files) {
              assert.equal(files.length, 1);
              if(err) {
                return done(err);
              }
              var contents = files[0].contents;
              var expected = fs.readFileSync(path.join(__dirname, 'expected', 'hinted', 'iconsfont.ttf'));
              // Clear the flags that change between invocations
              contents.writeUInt8(0, 0x0082);
              expected.writeUInt8(0, 0x0082);
              contents.writeUInt8(0, 0x0083);
              expected.writeUInt8(0, 0x0083);
              contents.writeUInt8(0, 0x715);
              expected.writeUInt8(0, 0x715);
              contents.writeUInt8(0, 0x716);
              expected.writeUInt8(0, 0x716);
              contents.writeUInt8(0, 0x717);
              expected.writeUInt8(0, 0x717);
              contents.writeUInt8(0, 0x72D);
              expected.writeUInt8(0, 0x72D);
              contents.writeUInt8(0, 0x72E);
              expected.writeUInt8(0, 0x72E);
              contents.writeUInt8(0, 0x72F);
              expected.writeUInt8(0, 0x72F);
              assert.deepEqual(
                contents,
                expected
              );
              done();
            }));
        });

      });
    });

  });

});
<commit_msg>Remove the `only`<commit_after>/* eslint max-nested-callbacks:[1] */

'use strict';

var fs = require('fs');
var path = require('path');
var gulp = require('gulp');
var iconfont = require('../src/index');
var assert = require('assert');
var neatequal = require('neatequal');
var streamtest = require('streamtest');

describe('gulp-iconfont', function() {
  var generationTimestamp = 3;

  streamtest.versions.forEach(function(version) {
    describe('for ' + version + ' streams', function() {

      describe('in stream mode', function() {

        it('should work', function(done) {
          var contents = [];
          var processedFiles = 0;

          gulp.src(path.join(__dirname, 'fixtures', 'iconsfont', '*.svg'), { buffer: false })
            .pipe(iconfont({
              fontName: 'iconsfont',
              timestamp: generationTimestamp,
            }))
            .pipe(streamtest[version].toObjects(function(err, files) {
              if(err) {
                return done(err);
              }
              assert.equal(files.length, 3);
              files.forEach(function(file, index) {
                file.contents.pipe(streamtest[version].toChunks(function(err2, chunks) {
                  if(err2) {
                    return done(err2);
                  }
                  contents[index] = Buffer.concat(chunks);
                  processedFiles++;
                  if(processedFiles === files.length) {
                    assert.deepEqual(
                      contents[0],
                      fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.ttf'))
                    );
                    assert.deepEqual(
                      contents[1],
                      fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.woff'))
                    );
                    assert.deepEqual(
                      contents[2],
                      fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.eot'))
                    );
                    return done();
                  }
                }));
              });
            }));
        });

        it('should work for only one font', function(done) {
          var contents = [];
          var processedFiles = 0;

          gulp.src(path.join(__dirname, 'fixtures', 'iconsfont', '*.svg'), { buffer: false })
            .pipe(iconfont({
              fontName: 'iconsfont',
              timestamp: generationTimestamp,
              formats: ['woff'],
            }))
            .pipe(streamtest[version].toObjects(function(err, files) {
              if(err) {
                return done(err);
              }
              assert.equal(files.length, 1);
              files.forEach(function(file, index) {
                file.contents.pipe(streamtest[version].toChunks(function(err2, chunks) {
                  if(err2) {
                    return done(err2);
                  }
                  contents[index] = Buffer.concat(chunks);
                  processedFiles++;
                  if(processedFiles === files.length) {
                    assert.deepEqual(
                      contents[0],
                      fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.woff'))
                    );
                    return done();
                  }
                }));
              });
            }));
        });

        it('should output SVG font with svg added to formats', function(done) {
          var contents = [];
          var processedFiles = 0;

          this.timeout(5000);
          gulp.src(path.join(__dirname, 'fixtures', 'iconsfont', '*.svg'), { buffer: false })
            .pipe(iconfont({
              fontName: 'iconsfont',
              formats: [
                'svg',
                'ttf',
                'eot',
                'woff',
              ],
              timestamp: generationTimestamp,
            }))
            .pipe(streamtest[version].toObjects(function(err, files) {
              if(err) {
                return done(err);
              }
              assert.equal(files.length, 4);
              files.forEach(function(file, index) {
                file.contents.pipe(streamtest[version].toChunks(function(err2, chunks) {
                  if(err2) {
                    return done(err2);
                  }
                  contents[index] = Buffer.concat(chunks);
                  processedFiles++;
                  if(processedFiles === files.length) {
                    assert.deepEqual(
                      contents[0],
                      fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.svg'))
                    );
                    assert.deepEqual(
                      contents[1],
                      fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.ttf'))
                    );
                    assert.deepEqual(
                      contents[2],
                      fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.woff'))
                    );
                    assert.deepEqual(
                      contents[3],
                      fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.eot'))
                    );
                    return done();
                  }
                }));
              });
            }));
        });

        it('should output WOFF2 font with woff2 added to formats', function(done) {
          var contents = [];
          var processedFiles = 0;

          this.timeout(5000);
          gulp.src(path.join(__dirname, 'fixtures', 'iconsfont', '*.svg'), { buffer: false })
            .pipe(iconfont({
              fontName: 'iconsfont',
              formats: [
                'ttf',
                'woff',
                'woff2',
              ],
              timestamp: generationTimestamp,
            }))
            .pipe(streamtest[version].toObjects(function(err, files) {
              if(err) {
                return done(err);
              }
              assert.equal(files.length, 3);
              files.forEach(function(file, index) {
                file.contents.pipe(streamtest[version].toChunks(function(err2, chunks) {
                  if(err2) {
                    return done(err2);
                  }
                  contents[index] = Buffer.concat(chunks);
                  processedFiles++;
                  if(processedFiles === files.length) {
                    assert.deepEqual(
                      contents[0],
                      fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.ttf'))
                    );
                    assert.deepEqual(
                      contents[1],
                      fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.woff2'))
                    );
                    assert.deepEqual(
                      contents[2],
                      fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.woff'))
                    );
                    return done();
                  }
                }));
              });
            }));
        });

      });

      describe('in buffer mode', function() {

        it('should work', function(done) {
          gulp.src(path.join(__dirname, 'fixtures', 'iconsfont', '*.svg'), { buffer: true })
            .pipe(iconfont({
              fontName: 'iconsfont',
              timestamp: generationTimestamp,
            }))
            .pipe(streamtest[version].toObjects(function(err, files) {
              if(err) {
                return done(err);
              }
              assert.equal(files.length, 3);
              assert.deepEqual(
                files[0].contents,
                fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.ttf'))
              );
              assert.deepEqual(
                files[1].contents,
                fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.woff'))
              );
              assert.deepEqual(
                files[2].contents,
                fs.readFileSync(path.join(__dirname, 'expected', 'iconsfont.eot'))
              );
              done();
            }));
        });

        it('should emit an event with the codepoint mapping', function(done) {
          var codepoints;

          gulp.src(path.join(__dirname, 'fixtures', 'iconsfont', '*.svg'), { buffer: true })
            .pipe(iconfont({
              fontName: 'iconsfont',
              timestamp: generationTimestamp,
            })).on('glyphs', function(_codepoints_) {
              codepoints = _codepoints_;
            })
            .pipe(streamtest[version].toObjects(function(err, files) {
              if(err) {
                return done(err);
              }
              assert.equal(files.length, 3);
              neatequal(codepoints,
                JSON.parse(fs.readFileSync(
                  path.join(__dirname, 'expected', 'codepoints.json'), 'utf8'))
              );
              done();
            }));
        });
        it('should work with autohinted iconsfont', function(done) {
          gulp.src(path.join(__dirname, 'fixtures', 'iconsfont', '*.svg'), { buffer: true })
            .pipe(iconfont({
              fontName: 'iconsfont',
              timestamp: generationTimestamp,
              autohint: __dirname + '/ttfautohint/ttfautohint.sh',
              formats: ['ttf']
            }))
            .pipe(streamtest[version].toObjects(function(err, files) {
              assert.equal(files.length, 1);
              if(err) {
                return done(err);
              }
              var contents = files[0].contents;
              var expected = fs.readFileSync(path.join(__dirname, 'expected', 'hinted', 'iconsfont.ttf'));
              // Clear the flags that change between invocations
              contents.writeUInt8(0, 0x0082);
              expected.writeUInt8(0, 0x0082);
              contents.writeUInt8(0, 0x0083);
              expected.writeUInt8(0, 0x0083);
              contents.writeUInt8(0, 0x715);
              expected.writeUInt8(0, 0x715);
              contents.writeUInt8(0, 0x716);
              expected.writeUInt8(0, 0x716);
              contents.writeUInt8(0, 0x717);
              expected.writeUInt8(0, 0x717);
              contents.writeUInt8(0, 0x72D);
              expected.writeUInt8(0, 0x72D);
              contents.writeUInt8(0, 0x72E);
              expected.writeUInt8(0, 0x72E);
              contents.writeUInt8(0, 0x72F);
              expected.writeUInt8(0, 0x72F);
              assert.deepEqual(
                contents,
                expected
              );
              done();
            }));
        });

      });
    });

  });

});
<|endoftext|>


<commit_before>'use strict';

const express = require('express');
const app = express.Router();
const messagesApi = require('./messages.js');
const dataUriToBuffer = require('data-uri-to-buffer');
const ftDataSquasher = require('ftdatasquasher');
const lwip = require('lwip');
const denodeify = require('denodeify');
const co = require('co');
const errorResponse = require('./errorResponse');

// maintain a global color promise because lwip can't run in paralel
lwip.colorPromise = Promise.resolve();

function loadImageFromMessage(postid) {

	return messagesApi
	.readSingleMessage(postid)
	.then(m => {
		if (m.type !== 'photo') {
			throw Error('Message is not a photo: ' + postid);
		}
		const buffer = dataUriToBuffer(ftDataSquasher.decompress(m.message));
		return denodeify(lwip.open)(buffer, 'png')
		.then(image => denodeify(image.resize.bind(image))(192, 192, 'nearest-neighbor'));
	});
}

// One years caching on images.
app.use(function (req, res, next) {
	res.set('Cache-Control', 'public, max-age=31557600');
	next();
});

app.all('/get-image', function (req, res) {
	if (!req.query.postid) {
		return errorResponse(res, Error('No postid param'));
	}

	lwip.colorPromise = lwip.colorPromise
	.then(() => loadImageFromMessage(req.query.postid))
	.then(image => denodeify(image.toBuffer.bind(image))('png', {}))
	.then(buffer => {
	    res.set('Content-Type', 'image/png');
		res.send(buffer);
	})
	.catch(e => errorResponse(res, e));
});

app.all('/get-collage', function (req, res) {
	if (!req.query.postids) {
		return errorResponse(res, Error('No postids param'));
	}

	const postids = req.query.postids.split(',');

	if (postids.length === 1) {
		return errorResponse(res, Error('Needs more than one id, comma seperated.'));
	}

	if (postids.length > 4) {
		return errorResponse(res, Error('Sorry four is the limit.'));
	}

	lwip.colorPromise = lwip.colorPromise
	.then(() => Promise.all(postids.map(postid => loadImageFromMessage(postid))))
	.then(images => {
		const padding = 8;
		const columns = postids.length === 3 ? 3 : 2;
		const rows = Math.ceil(images.length/columns);
		return denodeify(lwip.create)(
			(192+padding) * columns + padding,
			(192+padding) * rows + padding,
			[255, 240, 245]
		)
		.then(canvas => {
			return co(function *() {
				for (let i=0; i<images.length; i++) {
					const image = images[i];
					const x = (i % 2);
					const y = Math.floor(i/columns);
					const posX = x * (192+padding) + padding;
					const posY = y * (192+padding) + padding;
					yield denodeify(canvas.paste.bind(canvas))(posX, posY, image);
				}
				return canvas;
			});
		});
	})
	.then(image => denodeify(image.toBuffer.bind(image))('png', {}))
	.then(buffer => {
	    res.set('Content-Type', 'image/png');
		res.send(buffer);
	})
	.catch(e => errorResponse(res, e));
});

module.exports = app;
<commit_msg>fix 3x3<commit_after>'use strict';

const express = require('express');
const app = express.Router();
const messagesApi = require('./messages.js');
const dataUriToBuffer = require('data-uri-to-buffer');
const ftDataSquasher = require('ftdatasquasher');
const lwip = require('lwip');
const denodeify = require('denodeify');
const co = require('co');
const errorResponse = require('./errorResponse');

// maintain a global color promise because lwip can't run in paralel
lwip.colorPromise = Promise.resolve();

function loadImageFromMessage(postid) {

	return messagesApi
	.readSingleMessage(postid)
	.then(m => {
		if (m.type !== 'photo') {
			throw Error('Message is not a photo: ' + postid);
		}
		const buffer = dataUriToBuffer(ftDataSquasher.decompress(m.message));
		return denodeify(lwip.open)(buffer, 'png')
		.then(image => denodeify(image.resize.bind(image))(192, 192, 'nearest-neighbor'));
	});
}

// One years caching on images.
app.use(function (req, res, next) {
	res.set('Cache-Control', 'public, max-age=31557600');
	next();
});

app.all('/get-image', function (req, res) {
	if (!req.query.postid) {
		return errorResponse(res, Error('No postid param'));
	}

	lwip.colorPromise = lwip.colorPromise
	.then(() => loadImageFromMessage(req.query.postid))
	.then(image => denodeify(image.toBuffer.bind(image))('png', {}))
	.then(buffer => {
	    res.set('Content-Type', 'image/png');
		res.send(buffer);
	})
	.catch(e => errorResponse(res, e));
});

app.all('/get-collage', function (req, res) {
	if (!req.query.postids) {
		return errorResponse(res, Error('No postids param'));
	}

	const postids = req.query.postids.split(',');

	if (postids.length === 1) {
		return errorResponse(res, Error('Needs more than one id, comma seperated.'));
	}

	if (postids.length > 4) {
		return errorResponse(res, Error('Sorry four is the limit.'));
	}

	lwip.colorPromise = lwip.colorPromise
	.then(() => Promise.all(postids.map(postid => loadImageFromMessage(postid))))
	.then(images => {
		const padding = 8;
		const columns = postids.length === 3 ? 3 : 2;
		const rows = Math.ceil(images.length/columns);
		return denodeify(lwip.create)(
			(192+padding) * columns + padding,
			(192+padding) * rows + padding,
			[255, 240, 245]
		)
		.then(canvas => {
			return co(function *() {
				for (let i=0; i<images.length; i++) {
					const image = images[i];
					const x = (i % columns);
					const y = Math.floor(i/columns);
					const posX = x * (192+padding) + padding;
					const posY = y * (192+padding) + padding;
					yield denodeify(canvas.paste.bind(canvas))(posX, posY, image);
				}
				return canvas;
			});
		});
	})
	.then(image => denodeify(image.toBuffer.bind(image))('png', {}))
	.then(buffer => {
	    res.set('Content-Type', 'image/png');
		res.send(buffer);
	})
	.catch(e => errorResponse(res, e));
});

module.exports = app;
<|endoftext|>