<commit_before>const helpers = require('./helpers');
const HtmlPlugin = require('html-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
// const CopyPlugin = require('copy-webpack-plugin');
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

const devServer = require('./devServer');
const spritesmithConfig = require('./spritesmithConfig');
const htmlLoaderConfig = require('./htmlLoaderConfig');
const INDEX_HTML = helpers.root('src/index.html');
const COMMON_STYLE = helpers.root('src/styles/common.scss');

module.exports = function(options) {

    const supportES2015 = helpers.supportES2015();

    return {

        devServer: devServer,

        entry: {
            polyfills: [helpers.root('src/polyfills.ts')],
            main: [helpers.root('src/main.ts')],
            common: [COMMON_STYLE]
        },

        output: {
            path: helpers.root('dist'),
            filename: '[name].bundle.js',
            chunkFilename: '[name].chunk.js',
            sourceMapFilename: '[file].map',
        },

        resolve: {
            extensions: ['.ts', '.js'],
            modules: [helpers.root('node_modules')],

            /**
             * Add support for lettable operators.
             *
             * For existing codebase a refactor is required.
             * All rxjs operator imports (e.g. `import 'rxjs/add/operator/map'` or `import { map } from `rxjs/operator/map'`
             * must change to `import { map } from 'rxjs/operators'` (note that all operators are now under that import.
             * Additionally some operators have changed to to JS keyword constraints (do => tap, catch => catchError)
             *
             * Remember to use the `pipe()` method to chain operators, this functinoally makes lettable operators similar to
             * the old operators usage paradigm.
             *
             * For more details see:
             * https://github.com/ReactiveX/rxjs/blob/master/doc/lettable-operators.md#build-and-treeshaking
             *
             * If you are not planning on refactoring your codebase (or not planning on using imports from `rxjs/operators`
             * comment out this line.
             *
             * BE AWARE that not using lettable operators will probably result in significant payload added to your bundle.
             */
            alias: helpers.rxjsAlias(supportES2015)
        },

        optimization: {
            runtimeChunk: { name: 'runtime' },
            splitChunks: {
                cacheGroups: {
                    polyfills: {
                        name: 'polyfills',
                        chunks: 'all',
                        priority: -10,
                        enforce: true,
                        test (module, chunks) {
                            return chunks.some(chunk => chunk.name === 'polyfills');
                        },
                    },
                    vendors: {
                        test: /[\\/]node_modules[\\/].*\.(t|j)sx?$|[\\/]styles[\\/].*\.(s[ac]|c)ss$/,
                        name: 'vendors',
                        chunks: 'all',
                        priority: -15,
                        enforce: true
                    },
                }
            },
        },

        module: {
            rules: [
                { test: /\.css$/,  use: ['raw-loader', 'postcss-loader', 'sass-loader'], exclude: [COMMON_STYLE] },
                { test: /\.scss$/, use: ['raw-loader', 'postcss-loader', 'sass-loader'], exclude: [COMMON_STYLE] },
                {
                    test: /\.html$/,
                    use: [{
                        loader: 'html-loader',
                        options: htmlLoaderConfig
                    }], exclude: [INDEX_HTML]
                },
                {
                    test: /\.(jpe?g|png|gif|svg)$/,
                    use: [{
                        loader: 'url-loader',
                        options: {
                            limit: 10240,
                            name: '[path][name].[hash].[ext]',
                            outputPath: url => url.replace(/^src/i, '.')
                        }
                    }]
                },
                {
                    test: /\.(eot|woff2?|ttf)([\?]?.*)$/,
                    use: [{
                        loader: 'file-loader',
                        options: {
                            name: '[path][name].[hash].[ext]',
                            outputPath: url => url.replace(/^src/i, '.')
                        }
                    }]
                },
            ]
        },

        plugins: [
            /* new CopyPlugin([{
                from: helpers.root('src/assets'),
                to: 'assets/[path][name].[hash].[ext]',
                ignore: ['favicon.ico']
            }]), */
            new CheckerPlugin(),
            new HtmlPlugin({
                filename: 'index.html',
                template: helpers.root('src/index.html'),
                favicon: helpers.root('src/assets/favicon.ico'),
                chunksSortMode: 'dependency',
                inject: 'body',
            }),
            ...spritesmithConfig,
            /**
             * If you are interested to drill down to exact dependencies, try analyzing your bundle without ModuleConcatenationPlugin. See issue https://github.com/webpack-contrib/webpack-bundle-analyzer/issues/115 for more discussion.
             */
            // new BundleAnalyzerPlugin(),
        ]
    }
}<commit_msg>update<commit_after>const helpers = require('./helpers');
const HtmlPlugin = require('html-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
// const CopyPlugin = require('copy-webpack-plugin');
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

const devServer = require('./devServer');
const spritesmithConfig = require('./spritesmithConfig');
const htmlLoaderConfig = require('./htmlLoaderConfig');
const INDEX_HTML = helpers.root('src/index.html');
const COMMON_STYLE = helpers.root('src/styles/common.scss');

module.exports = function(options) {

    const supportES2015 = helpers.supportES2015();

    return {

        devServer: devServer,

        entry: {
            polyfills: [helpers.root('src/polyfills.ts')],
            main: [helpers.root('src/main.ts')],
            common: [COMMON_STYLE]
        },

        output: {
            path: helpers.root('dist'),
            filename: '[name].bundle.js',
            chunkFilename: '[name].chunk.js',
            sourceMapFilename: '[file].map',
        },

        resolve: {
            extensions: ['.ts', '.js'],
            modules: [helpers.root('node_modules')],

            /**
             * Add support for lettable operators.
             *
             * For existing codebase a refactor is required.
             * All rxjs operator imports (e.g. `import 'rxjs/add/operator/map'` or `import { map } from `rxjs/operator/map'`
             * must change to `import { map } from 'rxjs/operators'` (note that all operators are now under that import.
             * Additionally some operators have changed to to JS keyword constraints (do => tap, catch => catchError)
             *
             * Remember to use the `pipe()` method to chain operators, this functinoally makes lettable operators similar to
             * the old operators usage paradigm.
             *
             * For more details see:
             * https://github.com/ReactiveX/rxjs/blob/master/doc/lettable-operators.md#build-and-treeshaking
             *
             * If you are not planning on refactoring your codebase (or not planning on using imports from `rxjs/operators`
             * comment out this line.
             *
             * BE AWARE that not using lettable operators will probably result in significant payload added to your bundle.
             */
            alias: helpers.rxjsAlias(supportES2015)
        },

        optimization: {
            runtimeChunk: { name: 'runtime' },
            splitChunks: {
                cacheGroups: {
                    polyfills: {
                        name: 'polyfills',
                        chunks: 'initial',
                        priority: -10,
                        enforce: true,
                        test (module, chunks) {
                            return chunks.some(chunk => chunk.name === 'polyfills');
                        },
                    },
                    vendors: {
                        test: /[\\/]node_modules[\\/].*\.(t|j)sx?$|[\\/]styles[\\/].*\.(s[ac]|c)ss$/,
                        name: 'vendors',
                        chunks: 'initial',
                        priority: -15,
                        enforce: true
                    },
                }
            },
        },

        module: {
            rules: [
                { test: /\.css$/,  use: ['raw-loader', 'postcss-loader', 'sass-loader'], exclude: [COMMON_STYLE] },
                { test: /\.scss$/, use: ['raw-loader', 'postcss-loader', 'sass-loader'], exclude: [COMMON_STYLE] },
                {
                    test: /\.html$/,
                    use: [{
                        loader: 'html-loader',
                        options: htmlLoaderConfig
                    }], exclude: [INDEX_HTML]
                },
                {
                    test: /\.(jpe?g|png|gif|svg)$/,
                    use: [{
                        loader: 'url-loader',
                        options: {
                            limit: 10240,
                            name: '[path][name].[hash].[ext]',
                            outputPath: url => url.replace(/^src/i, '.')
                        }
                    }]
                },
                {
                    test: /\.(eot|woff2?|ttf)([\?]?.*)$/,
                    use: [{
                        loader: 'file-loader',
                        options: {
                            name: '[path][name].[hash].[ext]',
                            outputPath: url => url.replace(/^src/i, '.')
                        }
                    }]
                },
            ]
        },

        plugins: [
            /* new CopyPlugin([{
                from: helpers.root('src/assets'),
                to: 'assets/[path][name].[hash].[ext]',
                ignore: ['favicon.ico']
            }]), */
            new CheckerPlugin(),
            new HtmlPlugin({
                filename: 'index.html',
                template: helpers.root('src/index.html'),
                favicon: helpers.root('src/assets/favicon.ico'),
                chunksSortMode: 'dependency',
                inject: 'body',
            }),
            ...spritesmithConfig,
            /**
             * If you are interested to drill down to exact dependencies, try analyzing your bundle without ModuleConcatenationPlugin. See issue https://github.com/webpack-contrib/webpack-bundle-analyzer/issues/115 for more discussion.
             */
            // new BundleAnalyzerPlugin(),
        ]
    }
}<|endoftext|>


<commit_before>const webpack                      = require('webpack');
const DefinePlugin                 = require('webpack/lib/DefinePlugin');
const ProvidePlugin                = require('webpack/lib/ProvidePlugin');
const OccurrenceOrderPlugin        = require('webpack/lib/optimize/OccurrenceOrderPlugin');
const LoaderOptionsPlugin          = require('webpack/lib/LoaderOptionsPlugin');
const ContextReplacementPlugin     = require('webpack/lib/ContextReplacementPlugin');
const CopyWebpackPlugin            = require('copy-webpack-plugin');

const HtmlWebpackPlugin            = require('html-webpack-plugin');
const ExtractTextPlugin            = require('extract-text-webpack-plugin');
const ManifestPlugin               = require('webpack-manifest-plugin');
const InlineManifestWebpackPlugin  = require('inline-manifest-webpack-plugin');
const autoprefixer                 = require('autoprefixer');

const helpers                      = require('./helpers');
const TITLE                        = 'My MEAN Website';
const TITLE_ADMIN                  = 'Admin My MEAN Website';
const TEMPLATE_PATH                = './src/index.ejs';
const TEMPLATE_ADMIN_PATH          = './src/admin.ejs';
const TEMPLATE_HTML                = 'index.html';
const TEMPLATE_ADMIN_HTML          = 'admin.html';

module.exports = {
  entry: {
    polyfills: './src/polyfills.ts',
    vendor: './src/vendor.ts',
    app: './src/main.ts',
    admin: './src/admin.ts'
  },
  resolve: {
    descriptionFiles: ['package.json'],
    extensions: ['.ts', '.js', '.css', '.scss', 'json', '.html']
  },
  module: {
    rules: [
      {
        enforce: 'pre',
        test: /\.ts$/,
        loader: 'tslint-loader',
        exclude: [/\.(spec|e2e)\.ts$/, /node_modules/]
      },
      {
        test: /\.ts$/,
        loaders: [
          'awesome-typescript-loader',
          'angular2-template-loader'
        ],
        exclude: [/\.(spec|e2e)\.ts$/]
      },
      {
        test: /\.html$/,
        loader: 'raw-loader'
      },
      {
        test: /\.css$/,
        exclude: [helpers.root('src', 'app'), helpers.root('src', 'admin')],
        loader: ExtractTextPlugin
          .extract({
              fallbackLoader: "style-loader",
              loader: ['css-loader', 'postcss-loader']
          })
      },
      {
        test: /\.css$/,
        include: [helpers.root('src', 'app'), helpers.root('src', 'admin')],
        loader: 'raw-loader!postcss-loader'
      },
      {
        test: /\.scss$/,
        exclude: /node_modules/,
        loaders: ['raw-loader', 'sass-loader']
      },
      {
        test: /\.json$/,
        loader: 'json-loader'
      },
      {
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: "url-loader?limit=10000&mimetype=application/font-woff"
      },
      {
        test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: "file-loader"
      },
      // Bootstrap 4
      { test: /bootstrap\/dist\/js\/umd\//, loader: 'imports?jQuery=jquery' }
    ],
    noParse: [/node_modules\/angular2\/bundles\//]
  },
  plugins: [
    new ManifestPlugin(), // TODO check if I can remove this
    new InlineManifestWebpackPlugin(), // TODO check if I can remove this
    new HtmlWebpackPlugin({
      title: TITLE,
      inject: true,
      // chunksSortMode: 'auto', // auto is the default value
      chunks: ['polyfills', 'vendor', 'app'],
      template: TEMPLATE_PATH,
      filename: TEMPLATE_HTML
    }),
    new HtmlWebpackPlugin({
      title: TITLE_ADMIN,
      inject: true,
      chunksSortMode: function (chunk1, chunk2) {
        let orders = ['polyfills', 'vendor', 'admin'];
        let order1 = orders.indexOf(chunk1.names[0]);
        let order2 = orders.indexOf(chunk2.names[0]);
        if (order1 > order2) {
          return 1;
        } else if (order1 < order2) {
          return -1;
        } else {
          return 0;
        }
      },
      chunks: ['polyfills', 'vendor', 'admin'],
      template: TEMPLATE_ADMIN_PATH,
      filename: TEMPLATE_ADMIN_HTML
    }),
    new OccurrenceOrderPlugin(true),
    new ProvidePlugin({
      jQuery: 'jquery',
      jquery: 'jquery',
      $: 'jquery',
      "Tether": 'tether',
      "window.Tether": "tether",
      //---------------------------------------------------
      //------------- temporary workaround ----------------
      // https://github.com/shakacode/bootstrap-loader/issues/172#issuecomment-247205500
      //this requires exports-loader installed from npm
      Tooltip: "exports-loader?Tooltip!bootstrap/js/dist/tooltip",
      Alert: "exports-loader?Alert!bootstrap/js/dist/alert",
      Button: "exports-loader?Button!bootstrap/js/dist/button",
      Carousel: "exports-loader?Carousel!bootstrap/js/dist/carousel",
      Collapse: "exports-loader?Collapse!bootstrap/js/dist/collapse",
      Dropdown: "exports-loader?Dropdown!bootstrap/js/dist/dropdown",
      Modal: "exports-loader?Modal!bootstrap/js/dist/modal",
      Popover: "exports-loader?Popover!bootstrap/js/dist/popover",
      Scrollspy: "exports-loader?Scrollspy!bootstrap/js/dist/scrollspy",
      Tab: "exports-loader?Tab!bootstrap/js/dist/tab",
      Util: "exports-loader?Util!bootstrap/js/dist/util"
      //---------------------------------------------------
    }),
    new CopyWebpackPlugin([{from: './assets', to: './assets'}]),
    new ContextReplacementPlugin(
      // The (\\|\/) piece accounts for path separators in *nix and Windows
      /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
      helpers.root('./src') // location of your src
    ),
    new LoaderOptionsPlugin({
      debug: true,
      options: {
        context: __dirname,
        output: { path :  './' },
        postcss: [autoprefixer],
        tslint: {
          emitErrors: false,
          failOnHint: false,
          resourcePath: helpers.root('./src'),
          formattersDirectory: "./node_modules/tslint-loader/formatters/"
        }
      }
    })
  ],
  node: {
    global: true,
    process: true,
    Buffer: false,
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false,
    clearTimeout: true,
    setTimeout: true
  }
};
<commit_msg>fixed noParse regex #19<commit_after>const webpack                      = require('webpack');
const DefinePlugin                 = require('webpack/lib/DefinePlugin');
const ProvidePlugin                = require('webpack/lib/ProvidePlugin');
const OccurrenceOrderPlugin        = require('webpack/lib/optimize/OccurrenceOrderPlugin');
const LoaderOptionsPlugin          = require('webpack/lib/LoaderOptionsPlugin');
const ContextReplacementPlugin     = require('webpack/lib/ContextReplacementPlugin');
const CopyWebpackPlugin            = require('copy-webpack-plugin');

const HtmlWebpackPlugin            = require('html-webpack-plugin');
const ExtractTextPlugin            = require('extract-text-webpack-plugin');
const ManifestPlugin               = require('webpack-manifest-plugin');
const InlineManifestWebpackPlugin  = require('inline-manifest-webpack-plugin');
const autoprefixer                 = require('autoprefixer');

const helpers                      = require('./helpers');
const TITLE                        = 'My MEAN Website';
const TITLE_ADMIN                  = 'Admin My MEAN Website';
const TEMPLATE_PATH                = './src/index.ejs';
const TEMPLATE_ADMIN_PATH          = './src/admin.ejs';
const TEMPLATE_HTML                = 'index.html';
const TEMPLATE_ADMIN_HTML          = 'admin.html';

module.exports = {
  entry: {
    polyfills: './src/polyfills.ts',
    vendor: './src/vendor.ts',
    app: './src/main.ts',
    admin: './src/admin.ts'
  },
  resolve: {
    descriptionFiles: ['package.json'],
    extensions: ['.ts', '.js', '.css', '.scss', 'json', '.html']
  },
  module: {
    rules: [
      {
        enforce: 'pre',
        test: /\.ts$/,
        loader: 'tslint-loader',
        exclude: [/\.(spec|e2e)\.ts$/, /node_modules/]
      },
      {
        test: /\.ts$/,
        loaders: [
          'awesome-typescript-loader',
          'angular2-template-loader'
        ],
        exclude: [/\.(spec|e2e)\.ts$/]
      },
      {
        test: /\.html$/,
        loader: 'raw-loader'
      },
      {
        test: /\.css$/,
        exclude: [helpers.root('src', 'app'), helpers.root('src', 'admin')],
        loader: ExtractTextPlugin
          .extract({
              fallbackLoader: "style-loader",
              loader: ['css-loader', 'postcss-loader']
          })
      },
      {
        test: /\.css$/,
        include: [helpers.root('src', 'app'), helpers.root('src', 'admin')],
        loader: 'raw-loader!postcss-loader'
      },
      {
        test: /\.scss$/,
        exclude: /node_modules/,
        loaders: ['raw-loader', 'sass-loader']
      },
      {
        test: /\.json$/,
        loader: 'json-loader'
      },
      {
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: "url-loader?limit=10000&mimetype=application/font-woff"
      },
      {
        test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: "file-loader"
      },
      // Bootstrap 4
      { test: /bootstrap\/dist\/js\/umd\//, loader: 'imports?jQuery=jquery' }
    ],
    noParse: [/node_modules\/@angular\/\*\*\/bundles\//]
  },
  plugins: [
    new ManifestPlugin(), // TODO check if I can remove this
    new InlineManifestWebpackPlugin(), // TODO check if I can remove this
    new HtmlWebpackPlugin({
      title: TITLE,
      inject: true,
      // chunksSortMode: 'auto', // auto is the default value
      chunks: ['polyfills', 'vendor', 'app'],
      template: TEMPLATE_PATH,
      filename: TEMPLATE_HTML
    }),
    new HtmlWebpackPlugin({
      title: TITLE_ADMIN,
      inject: true,
      chunksSortMode: function (chunk1, chunk2) {
        let orders = ['polyfills', 'vendor', 'admin'];
        let order1 = orders.indexOf(chunk1.names[0]);
        let order2 = orders.indexOf(chunk2.names[0]);
        if (order1 > order2) {
          return 1;
        } else if (order1 < order2) {
          return -1;
        } else {
          return 0;
        }
      },
      chunks: ['polyfills', 'vendor', 'admin'],
      template: TEMPLATE_ADMIN_PATH,
      filename: TEMPLATE_ADMIN_HTML
    }),
    new OccurrenceOrderPlugin(true),
    new ProvidePlugin({
      jQuery: 'jquery',
      jquery: 'jquery',
      $: 'jquery',
      "Tether": 'tether',
      "window.Tether": "tether",
      //---------------------------------------------------
      //------------- temporary workaround ----------------
      // https://github.com/shakacode/bootstrap-loader/issues/172#issuecomment-247205500
      //this requires exports-loader installed from npm
      Tooltip: "exports-loader?Tooltip!bootstrap/js/dist/tooltip",
      Alert: "exports-loader?Alert!bootstrap/js/dist/alert",
      Button: "exports-loader?Button!bootstrap/js/dist/button",
      Carousel: "exports-loader?Carousel!bootstrap/js/dist/carousel",
      Collapse: "exports-loader?Collapse!bootstrap/js/dist/collapse",
      Dropdown: "exports-loader?Dropdown!bootstrap/js/dist/dropdown",
      Modal: "exports-loader?Modal!bootstrap/js/dist/modal",
      Popover: "exports-loader?Popover!bootstrap/js/dist/popover",
      Scrollspy: "exports-loader?Scrollspy!bootstrap/js/dist/scrollspy",
      Tab: "exports-loader?Tab!bootstrap/js/dist/tab",
      Util: "exports-loader?Util!bootstrap/js/dist/util"
      //---------------------------------------------------
    }),
    new CopyWebpackPlugin([{from: './assets', to: './assets'}]),
    new ContextReplacementPlugin(
      // The (\\|\/) piece accounts for path separators in *nix and Windows
      /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
      helpers.root('./src') // location of your src
    ),
    new LoaderOptionsPlugin({
      debug: true,
      options: {
        context: __dirname,
        output: { path :  './' },
        postcss: [autoprefixer],
        tslint: {
          emitErrors: false,
          failOnHint: false,
          resourcePath: helpers.root('./src'),
          formattersDirectory: "./node_modules/tslint-loader/formatters/"
        }
      }
    })
  ],
  node: {
    global: true,
    process: true,
    Buffer: false,
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false,
    clearTimeout: true,
    setTimeout: true
  }
};
<|endoftext|>


<commit_before>/**
 * @author: @AngularClass
 */

const webpack = require('webpack');
const helpers = require('./helpers');
const ngtools = require('@ngtools/webpack');
const branding = require('./branding');
const path = require('path');
const stringify = require('json-stringify');
const fs = require('fs');

/*
 * Webpack Plugins
 */
const autoprefixer = require('autoprefixer');
//const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const IgnorePlugin = require('webpack/lib/IgnorePlugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
// const ngcWebpack = require('ngc-webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ProvidePlugin = require('webpack/lib/ProvidePlugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');

/*
 * Webpack Constants
 */
// const HMR = helpers.hasProcessFlag('hot');
// const AOT = helpers.hasNpmFlag('aot');
const METADATA = {
  baseUrl: '/',
  isDevServer: helpers.isWebpackDevServer(),
  FABRIC8_BRANDING: process.env.FABRIC8_BRANDING || 'fabric8',
  PUBLIC_PATH: process.env.PUBLIC_PATH || '/',
};

/*
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = function (options) {
  const isProd = options.env === 'production';
  const aotMode = false;//options && options.aot !== undefined;
  console.log('The options from the webpack config: ' + stringify(options, null, 2));

  // const entryFile = aotMode ? './src/main.browser.aot.ts' : './src/main.browser.ts';
  // const outPath = aotMode ? 'dist' : 'aot';
  // const devtool = aotMode ? 'source-map' : 'eval-source-map';
  // const srcPath = path.join(__dirname, 'demo', 'src');
  var config = {

    /*
     * Cache generated modules and chunks to improve performance for multiple incremental builds.
     * This is enabled by default in watch mode.
     * You can pass false to disable it.
     *
     * See: http://webpack.github.io/docs/configuration.html#cache
     */
    //cache: false,

    /*
     * The entry point for the bundle
     * Our Angular.js app
     *
     * See: https://webpack.js.org/configuration/entry-context/#entry
     */
    entry: {
      'vendor': './src/vendor.browser.ts',
      'polyfills': './src/polyfills.browser.ts',
      // 'main': aotMode ? './src/main.browser.aot.ts' : './src/main.browser.ts'
      'main': [
        './src/main.browser.ts',
        // workaround for https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/456
        // 'style-loader/lib/addStyles',
        // 'css-loader/lib/css-base',
      ]
    },

    /**
     * Options affecting the resolving of modules.
     *
     * See: https://webpack.js.org/configuration/resolve
     */
    resolve: {

      /**
       * An array that automatically resolve certain extensions.
       * Which is what enables users to leave off the extension when importing.
       *
       * See: https://webpack.js.org/configuration/resolve/#resolve-extensions
       */
      extensions: ['.ts', '.js', '.json']
    },

    /*
     * Options affecting the normal modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#module
     */
    module: {

      rules: [

        /*
         * Typescript loader support for .ts and Angular 2 async routes via .async.ts
         * Replace templateUrl and stylesUrl with require()
         *
         * See: https://github.com/s-panferov/awesome-typescript-loader
         * See: https://github.com/TheLarkInn/angular2-template-loader
         */
        {
          test: /\.ts$/,
          use: aotMode ? [
            '@ngtools/webpack'
          ] : [
              '@angularclass/hmr-loader?pretty=' + !isProd + '&prod=' + isProd,
              'ts-loader',
              'angular2-template-loader',
              'angular2-router-loader'
            ],
          // loaders: '@ngtools/webpack',
          exclude: [/\.(spec|e2e)\.ts$/]
        },

        /**
         * Static analysis linter for TypeScript advanced options configuration
         * Description: An extensible linter for the TypeScript language.
         *
         * See: https://github.com/wbuchwalter/tslint-loader
         */
        {
          test: /\.ts$/,
          enforce: 'pre',
          loader: 'tslint-loader',
          exclude: [
            /node_modules/,
            /src\/a-runtime-console/,
            // /src\/main.browser.ts/,
            // /src\/polyfills.browser.ts/,
            // /src\/vendor.browser.ts/
          ],
          options: {
          //   configuration: {
          //     rules: {
          //       quotemark: [true, 'double']
          //     }
          //   },
          //
            // can specify a custom config file relative to current directory or with absolute path
            // 'tslint-custom.json'
            configFile: "tslint.json",

            // tslint errors are displayed by default as warnings
            // set emitErrors to true to display them as errors
            emitErrors: true,

            // tslint does not interrupt the compilation by default
            // if you want any file with tslint errors to fail
            // set failOnHint to true
            failOnHint: true,

            // enables type checked rules like 'for-in-array'
            // uses tsconfig.json from current working directory
            typeCheck: false,

            // automatically fix linting errors
            fix: false,

            // can specify a custom tsconfig file relative to current directory or with absolute path
            // to be used with type checked rules
            tsConfigFile: 'tsconfig.json',

            // path to directory containing formatter (optional)
            formattersDirectory: 'node_modules/tslint-loader/formatters/',

            // name of your formatter (optional)
            formatter: 'custom',

            // These options are useful if you want to save output to files
            // for your continuous integration server
            fileOutput: {
              // The directory where each file's report is saved
              dir: './lint/',

              // The extension to use for each report's filename. Defaults to 'txt'
              ext: 'xml',

              // If true, all files are removed from the report directory at the beginning of run
              clean: true,

              // A string to include at the top of every report file.
              // Useful for some report formats.
              header: '<?xml version="1.0" encoding="utf-8"?>\n<checkstyle version="5.7">',

              // A string to include at the bottom of every report file.
              // Useful for some report formats.
              footer: '</checkstyle>'
            }
          }
        },

        /**
         * Json loader support for *.json files.
         *
         * See: https://github.com/webpack/json-loader
         */
        {
          test: /\.json$/,
          type: "javascript/auto",
          use: ['json-loader']
        },

        /**
         * HTML Linter
         * Checks all files against .htmlhintrc
         */
        {
          enforce: 'pre',
          test: /\.html$/,
          use: {
            loader: 'htmlhint-loader',
            options: {
              configFile: './.htmlhintrc'
            }
          },
          exclude: [/node_modules/, /src\/a-runtime-console/]
        },

        /**
         * Raw loader support for *.html
         * Returns file content as string
         *
         * See: https://github.com/webpack/raw-loader
         */
        {
          test: /\.html$/,
          use: ['html-loader']
        },

        /**
         * to string and css loader support for *.css files
         * Returns file content as string
         *
         */
        {
          test: /^(?!.*component).*\.css$/,
          use: [
            'style-loader',
            // isProd ? MiniCssExtractPlugin.loader : 'style-loader',
            {
              loader: 'css-loader',
              options: {
                sourceMap: true,
                context: '/'
              },
            },
          ]
        },
        {
          test: /\.component\.css$/,
          use: [
            'to-string-loader',
            {
              loader: 'css-loader',
              options: {
                minimize: true,
                sourceMap: true,
                context: '/'
              }
            }
          ]
        },

        {
          test: /^(?!.*component).*\.less$/,
          use: [
            'style-loader',
            {
              loader: 'css-loader',
              options: {
                minimize: true,
                sourceMap: true,
                context: '/'
              }
            }, {
              loader: 'less-loader',
              options: {
                paths: [
                  path.resolve(__dirname, "../node_modules/patternfly/dist/less"),
                  path.resolve(__dirname, "../node_modules/patternfly/dist/less/dependencies"),
                  path.resolve(__dirname, "../node_modules/patternfly/dist/less/dependencies/bootstrap"),
                  path.resolve(__dirname, "../node_modules/patternfly/dist/less/dependencies/font-awesome"),
                ],
                sourceMap: true
              }
            }
          ]
        }, {
          test: /\.component\.less$/,
          use: [
            'to-string-loader',
            {
              loader: 'css-loader',
              options: {
                minimize: true,
                sourceMap: true,
                context: '/'
              }
            }, {
              loader: 'less-loader',
              options: {
                paths: [
                  path.resolve(__dirname, "../node_modules/patternfly/dist/less"),
                  path.resolve(__dirname, "../node_modules/patternfly/dist/less/dependencies"),
                  path.resolve(__dirname, "../node_modules/patternfly/dist/less/dependencies/bootstrap"),
                  path.resolve(__dirname, "../node_modules/patternfly/dist/less/dependencies/font-awesome"),
                ],
                sourceMap: true
              }
            }
          ]
        },

        /**
         * File loader for supporting fonts, for example, in CSS files.
         */
        {
          test: /\.(woff2|woff|ttf|eot|svg)$/,
          use: {
            loader: 'url-loader',
            query: {
              limit: 3000,
              includePaths: [
                path.resolve(__dirname, "../node_modules/patternfly/dist/fonts/")
              ],
              name: '_assets/fonts/[name]' + (isProd ? '.[hash]' : '') + '.[ext]'
            }
          },
          exclude: [
            path.resolve(__dirname, "../src/assets/images/"),
            /OpenSans.*\.(woff2|woff|ttf|eot|svg)$/ // Exclude loading OpenSans fonts as it will come from CDN
          ]
        },
        {
          test: /\.(jpg|png|svg|gif|jpeg)$/,
          use: {
            loader: 'url-loader',
            query: {
              limit: 3000,
              includePaths: [
                path.resolve(__dirname, "../src/assets/images/")
              ],
              name: '_assets/images/[name]' + (isProd ? '.[hash]' : '') + '.[ext]'
            }
          },
          exclude: path.resolve(__dirname, "../node_modules/patternfly/dist/fonts/")
        }
      ]
    },

    /**
     * Add additional plugins to the compiler.
     *
     * See: http://webpack.github.io/docs/configuration.html#plugins
     */
    plugins: [
      /**
       * Plugin: ForkCheckerPlugin
       * Description: Do type checking in a separate process, so webpack don't need to wait.
       *
       * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
       */
      //new CheckerPlugin(),

      /**
       * Plugin: ContextReplacementPlugin
       * Description: Provides context to Angular's use of System.import
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin
       * See: https://github.com/angular/angular/issues/11580
       */
      new ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        // /angular(\\|\/)core(\\|\/)@angular/,
        /\@angular(\\|\/)core(\\|\/)fesm5/,
        helpers.root('./src')
      ),
      new ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
        helpers.root('src') // location of your src
      ),

      /*
       * Plugin: CopyWebpackPlugin
       * Description: Copy files and directories in webpack.
       *
       * Copies project static assets.
       *
       * See: https://www.npmjs.com/package/copy-webpack-plugin
       */
       /*
       * this needs to be redirected to reside in the _assets/ directory
       */
      new CopyWebpackPlugin([
        {
          from: 'src/meta'
        }
      ]),

      /*
       * Plugin: HtmlWebpackPlugin
       * Description: Simplifies creation of HTML files to serve your webpack bundles.
       * This is especially useful for webpack bundles that include a hash in the filename
       * which changes every compilation.
       *
       * See: https://github.com/ampedandwired/html-webpack-plugin
       */
      new HtmlWebpackPlugin({
        template: 'src/index.ejs',
        title: branding.assets[METADATA.FABRIC8_BRANDING].title.prefix,
        metadata: METADATA
      }),

      /*
       * Plugin: ScriptExtHtmlWebpackPlugin
       * Description: Enhances html-webpack-plugin functionality
       * with different deployment options for your scripts including:
       *
       * See: https://github.com/numical/script-ext-html-webpack-plugin
       */
      new ScriptExtHtmlWebpackPlugin({
        defaultAttribute: 'defer'
      }),

      /*
       * Plugin LoaderOptionsPlugin (experimental)
       *
       * See: https://gist.github.com/sokra/27b24881210b56bbaff7
       */
      new LoaderOptionsPlugin({}),

      // ExtractTextPlugin
      // const extractCSS = new ExtractTextPlugin({
      //   filename: '_assets/stylesheets/[name].[id]' + ( isProd ? '.[contenthash]' : '' ) + '.css'
      // });

      // MiniCssExtractPlugin
      // new MiniCssExtractPlugin({
      //   // filename: '[name].css',
      //   filename: '_assets/stylesheets/[name]' + ( isProd ? '.[contenthash]' : '' ) + '.css',
      //   chunkFilename: '_assets/stylesheets/[id]' + ( isProd ? '.[contenthash]' : '' ) + '.css'
      // }),

      new webpack.IgnorePlugin(/^\.\/locale$/, /[^-]moment$/),

      // 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',
        publicPath: METADATA.PUBLIC_PATH,
      }),

      /**
       * StyleLintPlugin
       */
      new StyleLintPlugin({
        configFile: '.stylelintrc',
        syntax: 'less',
        context: 'src',
        files: '**/*.less',
        lintDirtyModulesOnly: false,
        failOnError: false,
        emitErrors: true,
        quiet: false,
      })
    ],

     /**
     * Version 4 webpack runs optimizations for you depending on the chosen mode.
     *
     * The following plugins have been removed from Webpack 4 which were extensively used in previous versions.
     *  - NoEmitOnErrorsPlugin
     *  - ModuleConcatenationPlugin
     *  - NamedModulesPlugin
     *  - CommonsChunkPlugin
     *
     * see: https://webpack.js.org/configuration/optimization/
     */
    optimization: {
      namedModules: true, // NamedModulesPlugin()
      // Keep the runtime chunk seperated to enable long term caching
      // https://twitter.com/wSokra/status/969679223278505985
      runtimeChunk: true,
      splitChunks: { // CommonsChunkPlugin()
        chunks: 'async'
      },
      noEmitOnErrors: true, // NoEmitOnErrorsPlugin
      concatenateModules: true //ModuleConcatenationPlugin
    },

    /**
     * Include polyfills or mocks for various node stuff
     * Description: Node configuration
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: {
      clearImmediate: false,
      crypto: 'empty',
      global: true,
      module: false,
      process: true,
      setImmediate: false
    }
  };

  if (aotMode) {
    config.plugins.push(new ngtools.AotPlugin({
      tsConfigPath: 'tsconfig-aot.json'
      // entryModule: './src/app/app.module#AppModule',
      // genDir: './src/aot'
    }));
  }

  return config;
};
<commit_msg>fix(build): update webpack config to allign with latest webpack<commit_after>/**
 * @author: @AngularClass
 */

const webpack = require('webpack');
const helpers = require('./helpers');
const ngtools = require('@ngtools/webpack');
const branding = require('./branding');
const path = require('path');
const stringify = require('json-stringify');
const fs = require('fs');

/**
 * Webpack Plugins
 */
const autoprefixer = require('autoprefixer');
//const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const IgnorePlugin = require('webpack/lib/IgnorePlugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
// const ngcWebpack = require('ngc-webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ProvidePlugin = require('webpack/lib/ProvidePlugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');

/**
 * Webpack Constants
 */
// const HMR = helpers.hasProcessFlag('hot');
// const AOT = helpers.hasNpmFlag('aot');
const METADATA = {
  baseUrl: '/',
  isDevServer: helpers.isWebpackDevServer(),
  FABRIC8_BRANDING: process.env.FABRIC8_BRANDING || 'fabric8',
  PUBLIC_PATH: process.env.PUBLIC_PATH || '/',
};

/*
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = function (options) {
  const isProd = options.env === 'production';
  const aotMode = false;//options && options.aot !== undefined;
  console.log('The options from the webpack config: ' + stringify(options, null, 2));

  // const entryFile = aotMode ? './src/main.browser.aot.ts' : './src/main.browser.ts';
  // const outPath = aotMode ? 'dist' : 'aot';
  // const devtool = aotMode ? 'source-map' : 'eval-source-map';
  // const srcPath = path.join(__dirname, 'demo', 'src');
  var config = {

    /*
     * Cache generated modules and chunks to improve performance for multiple incremental builds.
     * This is enabled by default in watch mode.
     * You can pass false to disable it.
     *
     * See: http://webpack.github.io/docs/configuration.html#cache
     */
    //cache: false,

    /*
     * The entry point for the bundle
     * Our Angular.js app
     *
     * See: https://webpack.js.org/configuration/entry-context/#entry
     */
    entry: {
      'vendor': './src/vendor.browser.ts',
      'polyfills': './src/polyfills.browser.ts',
      // 'main': aotMode ? './src/main.browser.aot.ts' : './src/main.browser.ts'
      'main': [
        './src/main.browser.ts',
        // workaround for https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/456
        // 'style-loader/lib/addStyles',
        // 'css-loader/lib/css-base',
      ]
    },

    /**
     * Options affecting the resolving of modules.
     *
     * See: https://webpack.js.org/configuration/resolve
     */
    resolve: {

      /**
       * An array that automatically resolve certain extensions.
       * Which is what enables users to leave off the extension when importing.
       *
       * See: https://webpack.js.org/configuration/resolve/#resolve-extensions
       */
      extensions: ['.ts', '.js', '.json']
    },

    /*
     * Options affecting the normal modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#module
     */
    module: {

      rules: [

        /*
         * Typescript loader support for .ts and Angular 2 async routes via .async.ts
         * Replace templateUrl and stylesUrl with require()
         *
         * See: https://github.com/s-panferov/awesome-typescript-loader
         * See: https://github.com/TheLarkInn/angular2-template-loader
         */
        {
          test: /\.ts$/,
          use: aotMode ? [
            '@ngtools/webpack'
          ] : [
              '@angularclass/hmr-loader?pretty=' + !isProd + '&prod=' + isProd,
              'ts-loader',
              'angular2-template-loader',
              'angular2-router-loader'
            ],
          // loaders: '@ngtools/webpack',
          exclude: [/\.(spec|e2e)\.ts$/]
        },

        /**
         * Static analysis linter for TypeScript advanced options configuration
         * Description: An extensible linter for the TypeScript language.
         *
         * See: https://github.com/wbuchwalter/tslint-loader
         */
        {
          test: /\.ts$/,
          enforce: 'pre',
          loader: 'tslint-loader',
          exclude: [
            /node_modules/,
            /src\/a-runtime-console/,
            // /src\/main.browser.ts/,
            // /src\/polyfills.browser.ts/,
            // /src\/vendor.browser.ts/
          ],
          options: {
          //   configuration: {
          //     rules: {
          //       quotemark: [true, 'double']
          //     }
          //   },
          //
            // can specify a custom config file relative to current directory or with absolute path
            // 'tslint-custom.json'
            configFile: "tslint.json",

            // tslint errors are displayed by default as warnings
            // set emitErrors to true to display them as errors
            emitErrors: true,

            // tslint does not interrupt the compilation by default
            // if you want any file with tslint errors to fail
            // set failOnHint to true
            failOnHint: true,

            // enables type checked rules like 'for-in-array'
            // uses tsconfig.json from current working directory
            typeCheck: false,

            // automatically fix linting errors
            fix: false,

            // can specify a custom tsconfig file relative to current directory or with absolute path
            // to be used with type checked rules
            tsConfigFile: 'tsconfig.json',

            // path to directory containing formatter (optional)
            formattersDirectory: 'node_modules/tslint-loader/formatters/',

            // name of your formatter (optional)
            formatter: 'custom',

            // These options are useful if you want to save output to files
            // for your continuous integration server
            fileOutput: {
              // The directory where each file's report is saved
              dir: './lint/',

              // The extension to use for each report's filename. Defaults to 'txt'
              ext: 'xml',

              // If true, all files are removed from the report directory at the beginning of run
              clean: true,

              // A string to include at the top of every report file.
              // Useful for some report formats.
              header: '<?xml version="1.0" encoding="utf-8"?>\n<checkstyle version="5.7">',

              // A string to include at the bottom of every report file.
              // Useful for some report formats.
              footer: '</checkstyle>'
            }
          }
        },

        /**
         * Json loader support for *.json files.
         *
         * See: https://github.com/webpack/json-loader
         */
        {
          test: /\.json$/,
          type: "javascript/auto",
          use: ['json-loader']
        },

        /**
         * HTML Linter
         * Checks all files against .htmlhintrc
         */
        {
          enforce: 'pre',
          test: /\.html$/,
          use: {
            loader: 'htmlhint-loader',
            options: {
              configFile: './.htmlhintrc'
            }
          },
          exclude: [/node_modules/, /src\/a-runtime-console/]
        },

        /**
         * Raw loader support for *.html
         * Returns file content as string
         *
         * See: https://github.com/webpack/raw-loader
         */
        {
          test: /\.html$/,
          use: ['html-loader']
        },

        /**
         * to string and css loader support for *.css files
         * Returns file content as string
         *
         */
        {
          test: /^(?!.*component).*\.css$/,
          use: [
            'style-loader',
            // isProd ? MiniCssExtractPlugin.loader : 'style-loader',
            {
              loader: 'css-loader',
              options: {
                sourceMap: true,
                context: '/'
              },
            },
          ]
        },
        {
          test: /\.component\.css$/,
          use: [
            'to-string-loader',
            {
              loader: 'css-loader',
              options: {
                minimize: true,
                sourceMap: true,
                context: '/'
              }
            }
          ]
        },

        {
          test: /^(?!.*component).*\.less$/,
          use: [
            'style-loader',
            {
              loader: 'css-loader',
              options: {
                minimize: true,
                sourceMap: true,
                context: '/'
              }
            }, {
              loader: 'less-loader',
              options: {
                paths: [
                  path.resolve(__dirname, "../node_modules/patternfly/dist/less"),
                  path.resolve(__dirname, "../node_modules/patternfly/dist/less/dependencies"),
                  path.resolve(__dirname, "../node_modules/patternfly/dist/less/dependencies/bootstrap"),
                  path.resolve(__dirname, "../node_modules/patternfly/dist/less/dependencies/font-awesome"),
                ],
                sourceMap: true
              }
            }
          ]
        }, {
          test: /\.component\.less$/,
          use: [
            'to-string-loader',
            {
              loader: 'css-loader',
              options: {
                minimize: true,
                sourceMap: true,
                context: '/'
              }
            }, {
              loader: 'less-loader',
              options: {
                paths: [
                  path.resolve(__dirname, "../node_modules/patternfly/dist/less"),
                  path.resolve(__dirname, "../node_modules/patternfly/dist/less/dependencies"),
                  path.resolve(__dirname, "../node_modules/patternfly/dist/less/dependencies/bootstrap"),
                  path.resolve(__dirname, "../node_modules/patternfly/dist/less/dependencies/font-awesome"),
                ],
                sourceMap: true
              }
            }
          ]
        },

        /**
         * File loader for supporting fonts, for example, in CSS files.
         */
        {
          test: /\.(woff2|woff|ttf|eot|svg)$/,
          use: {
            loader: 'url-loader',
            options: {
              limit: 3000,
              includePaths: [
                path.resolve(__dirname, "../node_modules/patternfly/dist/fonts/")
              ],
              name: '_assets/fonts/[name]' + (isProd ? '.[hash]' : '') + '.[ext]'
            }
          },
          exclude: [
            path.resolve(__dirname, "../src/assets/images/"),
            /OpenSans.*\.(woff2|woff|ttf|eot|svg)$/ // Exclude loading OpenSans fonts as it will come from CDN
          ]
        },
        {
          test: /\.(jpg|png|svg|gif|jpeg)$/,
          use: {
            loader: 'url-loader',
            options: {
              limit: 3000,
              includePaths: [
                path.resolve(__dirname, "../src/assets/images/")
              ],
              name: '_assets/images/[name]' + (isProd ? '.[hash]' : '') + '.[ext]'
            }
          },
          exclude: path.resolve(__dirname, "../node_modules/patternfly/dist/fonts/")
        }
      ]
    },

    /**
     * Add additional plugins to the compiler.
     *
     * See: http://webpack.github.io/docs/configuration.html#plugins
     */
    plugins: [
      /**
       * Plugin: ForkCheckerPlugin
       * Description: Do type checking in a separate process, so webpack don't need to wait.
       *
       * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
       */
      //new CheckerPlugin(),

      /**
       * Plugin: ContextReplacementPlugin
       * Description: Provides context to Angular's use of System.import
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin
       * See: https://github.com/angular/angular/issues/11580
       */
      new ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        // /angular(\\|\/)core(\\|\/)@angular/,
        /\@angular(\\|\/)core(\\|\/)fesm5/,
        helpers.root('./src')
      ),
      new ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
        helpers.root('src') // location of your src
      ),

      /*
       * Plugin: CopyWebpackPlugin
       * Description: Copy files and directories in webpack.
       *
       * Copies project static assets.
       *
       * See: https://www.npmjs.com/package/copy-webpack-plugin
       */
       /*
       * this needs to be redirected to reside in the _assets/ directory
       */
      new CopyWebpackPlugin([
        {
          from: 'src/meta'
        }
      ]),

      /*
       * Plugin: HtmlWebpackPlugin
       * Description: Simplifies creation of HTML files to serve your webpack bundles.
       * This is especially useful for webpack bundles that include a hash in the filename
       * which changes every compilation.
       *
       * See: https://github.com/ampedandwired/html-webpack-plugin
       */
      new HtmlWebpackPlugin({
        template: 'src/index.ejs',
        title: branding.assets[METADATA.FABRIC8_BRANDING].title.prefix,
        metadata: METADATA
      }),

      /*
       * Plugin: ScriptExtHtmlWebpackPlugin
       * Description: Enhances html-webpack-plugin functionality
       * with different deployment options for your scripts including:
       *
       * See: https://github.com/numical/script-ext-html-webpack-plugin
       */
      new ScriptExtHtmlWebpackPlugin({
        defaultAttribute: 'defer'
      }),

      /*
       * Plugin LoaderOptionsPlugin (experimental)
       *
       * See: https://gist.github.com/sokra/27b24881210b56bbaff7
       */
      new LoaderOptionsPlugin({}),

      // ExtractTextPlugin
      // const extractCSS = new ExtractTextPlugin({
      //   filename: '_assets/stylesheets/[name].[id]' + ( isProd ? '.[contenthash]' : '' ) + '.css'
      // });

      // MiniCssExtractPlugin
      // new MiniCssExtractPlugin({
      //   // filename: '[name].css',
      //   filename: '_assets/stylesheets/[name]' + ( isProd ? '.[contenthash]' : '' ) + '.css',
      //   chunkFilename: '_assets/stylesheets/[id]' + ( isProd ? '.[contenthash]' : '' ) + '.css'
      // }),

      new webpack.IgnorePlugin(/^\.\/locale$/, /[^-]moment$/),

      // 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',
        publicPath: METADATA.PUBLIC_PATH,
      }),

      /**
       * StyleLintPlugin
       */
      new StyleLintPlugin({
        configFile: '.stylelintrc',
        syntax: 'less',
        context: 'src',
        files: '**/*.less',
        lintDirtyModulesOnly: false,
        failOnError: false,
        emitErrors: true,
        quiet: false,
      })
    ],

     /**
     * Version 4 webpack runs optimizations for you depending on the chosen mode.
     *
     * The following plugins have been removed from Webpack 4 which were extensively used in previous versions.
     *  - NoEmitOnErrorsPlugin
     *  - ModuleConcatenationPlugin
     *  - NamedModulesPlugin
     *  - CommonsChunkPlugin
     *
     * see: https://webpack.js.org/configuration/optimization/
     */
    optimization: {
      namedModules: true, // NamedModulesPlugin()
      // Keep the runtime chunk seperated to enable long term caching
      // https://twitter.com/wSokra/status/969679223278505985
      runtimeChunk: true,
      splitChunks: { // CommonsChunkPlugin()
        chunks: 'async'
      },
      noEmitOnErrors: true, // NoEmitOnErrorsPlugin
      concatenateModules: true //ModuleConcatenationPlugin
    },

    /**
     * Include polyfills or mocks for various node stuff
     * Description: Node configuration
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: {
      clearImmediate: false,
      crypto: 'empty',
      global: true,
      module: false,
      process: true,
      setImmediate: false
    }
  };

  if (aotMode) {
    config.plugins.push(new ngtools.AotPlugin({
      tsConfigPath: 'tsconfig-aot.json'
      // entryModule: './src/app/app.module#AppModule',
      // genDir: './src/aot'
    }));
  }

  return config;
};
<|endoftext|>


<commit_before>/**
 * @author: @AngularClass
 */

const webpack = require('webpack');
const helpers = require('./helpers');

/*
 * Webpack Plugins
 */
// problem with copy-webpack-plugin
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;
const HtmlElementsPlugin = require('./html-elements-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

/*
 * Webpack Constants
 */
const METADATA = {
  title: 'Angular2 Webpack Starter by @gdi2290 from @AngularClass',
  baseUrl: '/',
  isDevServer: helpers.isWebpackDevServer()
};

/*
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = {

  /*
   * Static metadata for index.html
   *
   * See: (custom attribute)
   */
  metadata: METADATA,

  /*
   * Cache generated modules and chunks to improve performance for multiple incremental builds.
   * This is enabled by default in watch mode.
   * You can pass false to disable it.
   *
   * See: http://webpack.github.io/docs/configuration.html#cache
   */
   //cache: false,

  /*
   * The entry point for the bundle
   * Our Angular.js app
   *
   * See: http://webpack.github.io/docs/configuration.html#entry
   */
  entry: {

    'polyfills': './src/polyfills.browser.ts',
    'vendor':    './src/vendor.browser.ts',
    'main':      './src/main.browser.ts'

  },

  /*
   * Options affecting the resolving of modules.
   *
   * See: http://webpack.github.io/docs/configuration.html#resolve
   */
  resolve: {

    /*
     * An array of extensions that should be used to resolve modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#resolve-extensions
     */
    extensions: ['', '.ts', '.js', '.css', '.scss'],

    // Make sure root is src
    root: helpers.root('src'),

    // remove other default values
    modulesDirectories: [ 'node_modules', 'bower_components' ],

  },

  /*
   * Options affecting the normal modules.
   *
   * See: http://webpack.github.io/docs/configuration.html#module
   */
  module: {

    /*
     * An array of applied pre and post loaders.
     *
     * See: http://webpack.github.io/docs/configuration.html#module-preloaders-module-postloaders
     */
    preLoaders: [

      /*
       * Tslint loader support for *.ts files
       *
       * See: https://github.com/wbuchwalter/tslint-loader
       */
       // { test: /\.ts$/, loader: 'tslint-loader', exclude: [ helpers.root('node_modules') ] },

      /*
       * Source map loader support for *.js files
       * Extracts SourceMaps for source files that as added as sourceMappingURL comment.
       *
       * See: https://github.com/webpack/source-map-loader
       */
      {
        test: /\.js$/,
        loader: 'source-map-loader',
        exclude: [
          // these packages have problems with their sourcemaps
            helpers.root('node_modules/rxjs'),
            helpers.root('node_modules/ng2-bootstrap'),
            helpers.root('node_modules/ng2-branchy'),
            helpers.root('node_modules/@angular'),
            helpers.root('node_modules/@ngrx'),
            helpers.root('node_modules/@angular2-material'),
        ]
      }

    ],

    /*
     * An array of automatically applied loaders.
     *
     * IMPORTANT: The loaders here are resolved relative to the resource which
     * they are applied to. This means they are not resolved relative to the
     * configuration file.
     * See: http://webpack.github.io/docs/configuration.html#module-loaders
     */
    loaders: [

      /*
       * Typescript loader support for .ts and Angular 2 async routes via .async.ts
       * See: https://github.com/s-panferov/awesome-typescript-loader
       */
      {
        test: /\.ts$/,
        loaders: [ 'awesome-typescript-loader', 'angular2-template-loader' ],
        exclude: [ /\.(spec|e2e)\.ts$/ ]
      },

      /*
       * Json loader support for *.json files.
       * See: https://github.com/webpack/json-loader
       */
      {
        test: /\.json$/,
        loader: 'json-loader'
      },

      /* Raw loader support for *.html and *.css
       * Returns file content as string
       * See: https://github.com/webpack/raw-loader
       */

      {
        test: /\.css$/,
        loader: 'raw-loader'
      },

      {
        test: /\.html$/,
        loader: 'raw-loader',
        exclude: [helpers.root('src/index.html')]
      },

      {
          test: /\.scss$/,
          loaders: [ 'raw-loader', 'sass-loader' ]
      },

      {
          test: /initial\.scss$/,
          loader: ExtractTextPlugin.extract('style-loader', 'css-loader!sass-loader')
      },

      {
          test: /\.woff(2)?(\?v=.+)?$/,
          loader: 'url-loader?limit=10000&mimetype=application/font-woff'
      },

      {
          test: /\.(ttf|eot|svg)(\?v=.+)?$/,
          loader: 'file-loader'
      },

      {
          test: /bootstrap\/dist\/js\/umd\//,
          loader: 'imports?jQuery=jquery'
      }

    ]

  },

  /*
   * Add additional plugins to the compiler.
   *
   * See: http://webpack.github.io/docs/configuration.html#plugins
   */
  plugins: [
    new ExtractTextPlugin('initial.css', {
          allChunks: true
    }),

    /* Plugin: ForkCheckerPlugin
     * Description: Do type checking in a separate process, so webpack don't need to wait.
     * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
     */
    new ForkCheckerPlugin(),

    /* Plugin: OccurenceOrderPlugin
     * Description: Varies the distribution of the ids to get the smallest id length
     * for often used ids.
     * See: https://webpack.github.io/docs/list-of-plugins.html#occurrenceorderplugin
     * See: https://github.com/webpack/docs/wiki/optimization#minimize
     */
    new webpack.optimize.OccurenceOrderPlugin(true),

    /* Plugin: CommonsChunkPlugin
     * Description: Shares common code between the pages.
     * It identifies common modules and put them into a commons chunk.
     * See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
     * See: https://github.com/webpack/docs/wiki/optimization#multi-page-app
     */
    new webpack.optimize.CommonsChunkPlugin({
      name: ['polyfills', 'vendor'].reverse()
    }),

    /*
     * Plugin: CopyWebpackPlugin
     * Description: Copy files and directories in webpack.
     *
     * Copies project static assets.
     *
     * See: https://www.npmjs.com/package/copy-webpack-plugin
     */
    new CopyWebpackPlugin([{
      from: 'src/assets',
      to: 'assets'
    }]),

    /*
     * Plugin: HtmlWebpackPlugin
     * Description: Simplifies creation of HTML files to serve your webpack bundles.
     * This is especially useful for webpack bundles that include a hash in the filename
     * which changes every compilation.
     *
     * See: https://github.com/ampedandwired/html-webpack-plugin
     */
    new HtmlWebpackPlugin({
      template: 'src/index.html',
      chunksSortMode: 'dependency'
    }),

    /*
     * Plugin: HtmlHeadConfigPlugin
     * Description: Generate html tags based on javascript maps.
     *
     * If a publicPath is set in the webpack output configuration, it will be automatically added to
     * href attributes, you can disable that by adding a "=href": false property.
     * You can also enable it to other attribute by settings "=attName": true.
     *
     * The configuration supplied is map between a location (key) and an element definition object (value)
     * The location (key) is then exported to the template under then htmlElements property in webpack configuration.
     *
     * Example:
     *  Adding this plugin configuration
     *  new HtmlElementsPlugin({
     *    headTags: { ... }
     *  })
     *
     *  Means we can use it in the template like this:
     *  <%= webpackConfig.htmlElements.headTags %>
     *
     * Dependencies: HtmlWebpackPlugin
     */
    new HtmlElementsPlugin({
      headTags: require('./head-config.common')
    }),

    new webpack.ProvidePlugin({
      jQuery: 'jquery',
      $: 'jquery',
      jquery: 'jquery',
      'Tether': 'tether',
      'window.Tether': 'tether'
    })

  ],

  /*
   * Include polyfills or mocks for various node stuff
   * Description: Node configuration
   *
   * See: https://webpack.github.io/docs/configuration.html#node
   */
  node: {
    global: 'window',
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false
  }

};

<commit_msg>Borrando commentarios innecesarios<commit_after>/**
 * @author: Paul Márquez <mcromanceva@hotmail.com>
 */

const webpack = require('webpack');
const helpers = require('./helpers');

/**
 * Webpack Plugins
 */
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlElementsPlugin = require('./html-elements-plugin');

/**
 * Webpack Constants
 */
const METADATA = {
  title: 'Presentación Porsche Puerto Vallarta',
  baseUrl: '/',
  isDevServer: helpers.isWebpackDevServer()
};

/**
 * Webpack configuration
 */
module.exports = {

  metadata: METADATA,

  entry: {

    'polyfills': './src/polyfills.browser.ts',
    'vendor':    './src/vendor.browser.ts',
    'main':      './src/main.browser.ts'

  },

  resolve: {

    extensions: [ '', '.js', '.css', '.scss' ],
    root: helpers.root('src'),
    modulesDirectories: [ 'node_modules' ],

  },

  module: {

    preLoaders: [
      { test: /\.js$/, loader: 'source-map-loader' }
    ],

    loaders: [
      { test: /\.json$/, loader: 'json-loader' },
      { test: /\.css$/, loader: 'raw-loader' },
      { test: /\.html$/, loader: 'raw-loader', exclude: [helpers.root('src/index.html')] },
      { test: /\.scss$/, loaders: [ 'raw-loader', 'sass-loader' ] },
      { test: /initial\.scss$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader!sass-loader') },
      { test: /\.woff(2)?(\?v=.+)?$/, loader: 'url-loader?limit=10000&mimetype=application/font-woff' },
      { test: /\.(ttf|eot|svg)(\?v=.+)?$/, loader: 'file-loader' },
      { test: /bootstrap\/dist\/js\/umd\//, loader: 'imports?jQuery=jquery' }
    ]

  },

  plugins: [
    new ExtractTextPlugin('initial.css', { allChunks: true }),
    new webpack.optimize.OccurenceOrderPlugin(true),
    new CopyWebpackPlugin([{ from: 'src/assets', to: 'assets' }]),
    new HtmlWebpackPlugin({ template: 'src/index.html', chunksSortMode: 'dependency' }),
    new HtmlElementsPlugin({ headTags: require('./head-config.common') }),
    new webpack.optimize.CommonsChunkPlugin({
      name: ['polyfills', 'vendor'].reverse()
    }),
    new webpack.ProvidePlugin({
      jQuery: 'jquery',
      $: 'jquery',
      jquery: 'jquery',
    })
  ],

  node: {
    global: 'window',
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false
  }

};
<|endoftext|>


<commit_before>const path = require('path');
const glob = require('glob');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const PurifyPlugin = require('purifycss-webpack');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const postCssInject = require('postcss-inject');
const browsers = require('./browsers');
const babelPreset = require('./babel-preset-webpack');

const source = file => path.resolve(process.cwd(), file);

const injectStyles = cssFilePath => postCssInject({
	cssFilePath,
	injectTo: 'fileStart',
});

const tamiaComponentsPath = source('node_modules/tamia/lib/components');

// CSS Modules locations
const cssModulesPaths = [
	tamiaComponentsPath,
	source('templates'),
];

module.exports = function(scripts, env, options) {
	const isDev = env !== 'production';

	// Generate entries for all scripts
	const entries = scripts.reduce((entries, script) => {
		entries[path.basename(script, '.js')] = './' + script;
		return entries;
	}, {});

	// Load user templates via Webpack to make hot reload and CSS Modules work.
	entries.styles = `${require.resolve('../src/templates-loader')}!`;

	const plugins = [
		new webpack.LoaderOptionsPlugin({
			options: {
				postcss: [
					injectStyles(source('styles/config.pcss')),
					injectStyles(require.resolve('tamia/lib/styles/core.pcss')),
					injectStyles(require.resolve('tamia/lib/styles/config.pcss')),
					require('postcss-extend')(),
					require('postcss-cssnext')({
						browsers,
					}),
				],
			},
		}),
		new ExtractTextPlugin({
			filename: '[name].css',
			allChunks: true,
			ignoreOrder: true,
		}),
		new webpack.DefinePlugin({
			'DEBUG': JSON.stringify(isDev),
			'process.env': {
				NODE_ENV: JSON.stringify(env),
			},
		}),
	];

	if (options.compress) {
		plugins.push(
			new PurifyPlugin({
				paths: glob.sync(source('public/**/*.html')),
				purifyOptions: {
					info: options.verbose,
					rejected: options.verbose,
				},
				verbose: options.verbose,
			}),
			new OptimizeCssAssetsPlugin({
				cssProcessorOptions: {
					discardComments: {
						removeAll: true,
					},
					discardOverridden: true,
					mergeRules: true,
				},
				canPrint: options.verbose,
			})
		);
	}

	return {
		entry: entries,
		devtool: false,
		output: {
			path: source('public/build'),
			publicPath: '/build/',
			filename: '[name].js',
		},
		resolve: {
			extensions: ['.js', '.jsx'],
		},
		plugins,
		module: {
			noParse: /\.min\.js/,
			rules: [
				{
					test: /\.jsx?$/,
					include: [
						tamiaComponentsPath,
						source('js'),
						source('templates'),
					],
					use: [
						{
							loader: 'babel-loader',
							options: {
								babelrc: false,
								presets: [babelPreset(env)],
							},
						},
					],
				},
				{
					test: /\.pcss$/,
					include: cssModulesPaths,
					loader: ExtractTextPlugin.extract({
						fallback: 'style-loader',
						use: [
							{
								loader: 'css-loader',
								query: {
									importLoaders: 1,
									modules: true,
									localIdentName: '[name]--[local]',
								},
							},
							'postcss-loader',
						],
					}),
				},
				{
					test: /\.pcss$/,
					exclude: cssModulesPaths,
					loader: ExtractTextPlugin.extract({
						fallback: 'style-loader',
						use: [
							{
								loader: 'css-loader',
								query: {
									importLoaders: 1,
								},
							},
							'postcss-loader',
						],
					}),
				},
			],
		},
	};
};
<commit_msg>Fix: Module path<commit_after>const path = require('path');
const glob = require('glob');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const PurifyPlugin = require('purifycss-webpack');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const postCssInject = require('postcss-inject');
const browsers = require('./browsers');
const babelPreset = require('./babel-preset-webpack');

const source = file => path.resolve(process.cwd(), file);

const injectStyles = cssFilePath => postCssInject({
	cssFilePath,
	injectTo: 'fileStart',
});

const tamiaComponentsPath = source('node_modules/tamia/lib/components');

// CSS Modules locations
const cssModulesPaths = [
	tamiaComponentsPath,
	source('templates'),
];

module.exports = function(scripts, env, options) {
	const isDev = env !== 'production';

	// Generate entries for all scripts
	const entries = scripts.reduce((entries, script) => {
		entries[path.basename(script, '.js')] = './' + script;
		return entries;
	}, {});

	// Load user templates via Webpack to make hot reload and CSS Modules work.
	entries.styles = `${require.resolve('../lib/templates-loader')}!`;

	const plugins = [
		new webpack.LoaderOptionsPlugin({
			options: {
				postcss: [
					injectStyles(source('styles/config.pcss')),
					injectStyles(require.resolve('tamia/lib/styles/core.pcss')),
					injectStyles(require.resolve('tamia/lib/styles/config.pcss')),
					require('postcss-extend')(),
					require('postcss-cssnext')({
						browsers,
					}),
				],
			},
		}),
		new ExtractTextPlugin({
			filename: '[name].css',
			allChunks: true,
			ignoreOrder: true,
		}),
		new webpack.DefinePlugin({
			'DEBUG': JSON.stringify(isDev),
			'process.env': {
				NODE_ENV: JSON.stringify(env),
			},
		}),
	];

	if (options.compress) {
		plugins.push(
			new PurifyPlugin({
				paths: glob.sync(source('public/**/*.html')),
				purifyOptions: {
					info: options.verbose,
					rejected: options.verbose,
				},
				verbose: options.verbose,
			}),
			new OptimizeCssAssetsPlugin({
				cssProcessorOptions: {
					discardComments: {
						removeAll: true,
					},
					discardOverridden: true,
					mergeRules: true,
				},
				canPrint: options.verbose,
			})
		);
	}

	return {
		entry: entries,
		devtool: false,
		output: {
			path: source('public/build'),
			publicPath: '/build/',
			filename: '[name].js',
		},
		resolve: {
			extensions: ['.js', '.jsx'],
		},
		plugins,
		module: {
			noParse: /\.min\.js/,
			rules: [
				{
					test: /\.jsx?$/,
					include: [
						tamiaComponentsPath,
						source('js'),
						source('templates'),
					],
					use: [
						{
							loader: 'babel-loader',
							options: {
								babelrc: false,
								presets: [babelPreset(env)],
							},
						},
					],
				},
				{
					test: /\.pcss$/,
					include: cssModulesPaths,
					loader: ExtractTextPlugin.extract({
						fallback: 'style-loader',
						use: [
							{
								loader: 'css-loader',
								query: {
									importLoaders: 1,
									modules: true,
									localIdentName: '[name]--[local]',
								},
							},
							'postcss-loader',
						],
					}),
				},
				{
					test: /\.pcss$/,
					exclude: cssModulesPaths,
					loader: ExtractTextPlugin.extract({
						fallback: 'style-loader',
						use: [
							{
								loader: 'css-loader',
								query: {
									importLoaders: 1,
								},
							},
							'postcss-loader',
						],
					}),
				},
			],
		},
	};
};
<|endoftext|>


<commit_before>'use strict';

window.SC_ATTACHED = window.SC_ATTACHED || false;

let currentState = {};
/**
 * Flag indicates now playing track is private.
 * The extension does not scrobble such tracks.
 * @type {Boolean}
 */
let isPrivate = false;

const progressSelector = '.playControls div[role=progressbar]';
const playButtonSelector = '.playControls button.playControl';

/**
 * Regular expression used to split artist and track.
 * There're three different '-' chars in the regexp:
 * hyphen (0x2d), en dash (0x2013), em dash (0x2014).
 * @type {RegExp}
 */
const artistTrackRe = /(.+)\s?[-–—:]\s?(.+)/;

Connector.playerSelector = '.playControls';

Connector.getCurrentState = () => {
	currentState.currentTime = getCurrentTime();
	currentState.isPlaying = isPlaying();
	return currentState;
};

Connector.isScrobblingAllowed = () => !isPrivate;

Connector.filter = MetadataFilter.getYoutubeFilter();

function getCurrentTime() {
	return parseFloat($(progressSelector).attr('aria-valuenow')) / 1000;
}

function isPlaying() {
	return $(playButtonSelector).hasClass('playing');
}

/**
 * Parse metadata and set local letiables
 * @param {Object} metadata Data received from script injected in DOM
 */
function setSongData(metadata) {
	isPrivate = metadata.sharing === 'private';

	if (isPrivate) {
		currentState = {};
		return;
	}

	// Sometimes the artist name is in the track title,
	// e.g. Tokyo Rose - Zender Overdrive by Aphasia Records.
	let match = artistTrackRe.exec(metadata.title);

	// But don't interpret patterns of the form
	// "[Start of title] #1234 - [End of title]" as Artist - Title
	if (match && ! /.*#\d+.*/.test(match[1])) {
		currentState.artist = match[1];
		currentState.track = match[2];
	} else {
		currentState.artist = metadata.user.username;
		currentState.track = metadata.title;
	}

	currentState.duration = Math.floor(metadata.duration / 1000);
	// Use permalink url as the unique id
	currentState.uniqueID = metadata.permalink_url;
	currentState.trackArt = metadata.artwork_url;
}

/**
 * Run at initialisation; add dom script and attach events.
 */
(function() {
	// Exit if already attached.
	if (window.SC_ATTACHED) {
		return;
	}

	// Inject script to extract events from the Soundcloud API event-bus.
	// FIXME: Replace to `chrome.runtime.getURL`.
	let scriptUrl = chrome.extension.getURL('connectors/soundcloud-dom-inject.js');
	Util.injectScriptIntoDocument(scriptUrl);

	// Trigger functions based on message type.
	function eventHandler(e) {
		switch (e.data.type) {
			case 'SC_PLAY':
				setSongData(e.data.metadata);
				break;
			default:
				break;
		}
	}

	// Attach listener for message events.
	window.addEventListener('message', eventHandler);
	window.SC_ATTACHED = true;
}());
<commit_msg>SoundCloud: require spaces between separator<commit_after>'use strict';

window.SC_ATTACHED = window.SC_ATTACHED || false;

let currentState = {};
/**
 * Flag indicates now playing track is private.
 * The extension does not scrobble such tracks.
 * @type {Boolean}
 */
let isPrivate = false;

const progressSelector = '.playControls div[role=progressbar]';
const playButtonSelector = '.playControls button.playControl';

/**
 * Regular expression used to split artist and track.
 * There're three different '-' chars in the regexp:
 * hyphen (0x2d), en dash (0x2013), em dash (0x2014).
 * @type {RegExp}
 */
const artistTrackRe = /(.+)\s[-–—:]\s(.+)/;

Connector.playerSelector = '.playControls';

Connector.getCurrentState = () => {
	currentState.currentTime = getCurrentTime();
	currentState.isPlaying = isPlaying();
	return currentState;
};

Connector.isScrobblingAllowed = () => !isPrivate;

Connector.filter = MetadataFilter.getYoutubeFilter();

function getCurrentTime() {
	return parseFloat($(progressSelector).attr('aria-valuenow')) / 1000;
}

function isPlaying() {
	return $(playButtonSelector).hasClass('playing');
}

/**
 * Parse metadata and set local letiables
 * @param {Object} metadata Data received from script injected in DOM
 */
function setSongData(metadata) {
	isPrivate = metadata.sharing === 'private';

	if (isPrivate) {
		currentState = {};
		return;
	}

	// Sometimes the artist name is in the track title,
	// e.g. Tokyo Rose - Zender Overdrive by Aphasia Records.
	let match = artistTrackRe.exec(metadata.title);

	// But don't interpret patterns of the form
	// "[Start of title] #1234 - [End of title]" as Artist - Title
	if (match && ! /.*#\d+.*/.test(match[1])) {
		currentState.artist = match[1];
		currentState.track = match[2];
	} else {
		currentState.artist = metadata.user.username;
		currentState.track = metadata.title;
	}

	currentState.duration = Math.floor(metadata.duration / 1000);
	// Use permalink url as the unique id
	currentState.uniqueID = metadata.permalink_url;
	currentState.trackArt = metadata.artwork_url;
}

/**
 * Run at initialisation; add dom script and attach events.
 */
(function() {
	// Exit if already attached.
	if (window.SC_ATTACHED) {
		return;
	}

	// Inject script to extract events from the Soundcloud API event-bus.
	// FIXME: Replace to `chrome.runtime.getURL`.
	let scriptUrl = chrome.extension.getURL('connectors/soundcloud-dom-inject.js');
	Util.injectScriptIntoDocument(scriptUrl);

	// Trigger functions based on message type.
	function eventHandler(e) {
		switch (e.data.type) {
			case 'SC_PLAY':
				setSongData(e.data.metadata);
				break;
			default:
				break;
		}
	}

	// Attach listener for message events.
	window.addEventListener('message', eventHandler);
	window.SC_ATTACHED = true;
}());
<|endoftext|>


<commit_before>steal('can/construct',function($){
var isFunction = $.isFunction,
	isArray = $.isArray,
	makeArray = $.makeArray,
/**
 * @page can.Construct.proxy
 * @parent can.Construct
 * @plugin can/construct/plugin
 *
 * Adds a static and prototype proxy method that are
 * useful for creating callback functions that have
 * `this` set correctly.
 *
 *
 * Returns a callback function for a function on this Class.
 * Proxy ensures that 'this' is set appropriately.
 * @codestart
 * can.Construct("MyClass",{
 *     getData: function() {
 *         this.showing = null;
 *         $.get("data.json",this.proxy('gotData'),'json')
 *     },
 *     gotData: function( data ) {
 *         this.showing = data;
 *     }
 * },{});
 * MyClass.showData();
 * @codeend
 *
Currying Arguments

 * Additional arguments to proxy will fill in arguments on the returning function.
 * @codestart
 * can.Construct("MyClass",{
 *    getData: function( callback ) {
 *      $.get("data.json",this.proxy('process',callback),'json');
 *    },
 *    process: function( callback, jsonData ) { //callback is added as first argument
 *        jsonData.processed = true;
 *        callback(jsonData);
 *    }
 * },{});
 * MyClass.getData(showDataFunc)
 * @codeend
 *
Nesting Functions

 * Proxy can take an array of functions to call as
 * the first argument.  When the returned callback function
 * is called each function in the array is passed the return value of the prior function.  This is often used
 * to eliminate currying initial arguments.
 * @codestart
 * can.Construct("MyClass",{
 *    getData: function( callback ) {
 *      //calls process, then callback with value from process
 *      $.get("data.json",this.proxy(['process2',callback]),'json')
 *    },
 *    process2: function( type,jsonData ) {
 *        jsonData.processed = true;
 *        return [jsonData];
 *    }
 * },{});
 * MyClass.getData(showDataFunc);
 * @codeend
 * @param {String|Array} fname If a string, it represents the function to be called.
 * If it is an array, it will call each function in order and pass the return value of the prior function to the
 * next function.
 * @return {Function} the callback function.
 */
proxy = function( funcs ) {

			//args that should be curried
			var args = makeArray(arguments),
				self;

			// get the functions to callback
			funcs = args.shift();

			// if there is only one function, make funcs into an array
			if (!isArray(funcs) ) {
				funcs = [funcs];
			}

			// keep a reference to us in self
			self = this;

			//!steal-remove-start
			for( var i =0; i< funcs.length;i++ ) {
				if(typeof funcs[i] == "string" && !isFunction(this[funcs[i]])){
					throw ("class.js "+( this.fullName || this.Class.fullName)+" does not have a "+funcs[i]+"method!");
				}
			}
			//!steal-remove-end
			return function class_cb() {
				// add the arguments after the curried args
				var cur = args.concat(makeArray(arguments)),
					isString,
					length = funcs.length,
					f = 0,
					func;

				// go through each function to call back
				for (; f < length; f++ ) {
					func = funcs[f];
					if (!func ) {
						continue;
					}

					// set called with the name of the function on self (this is how this.view works)
					isString = typeof func == "string";

					// call the function
					cur = (isString ? self[func] : func).apply(self, cur || []);

					// pass the result to the next function (if there is a next function)
					if ( f < length - 1 ) {
						cur = !isArray(cur) || cur._use_call ? [cur] : cur
					}
				}
				return cur;
			}
		}
	can.Construct.proxy = can.Construct.prototype.proxy = proxy;

});<commit_msg>fix for proxy working with YUI<commit_after>steal('can/construct',function($){
var isFunction = can.isFunction,
	isArray = can.isArray,
	makeArray = can.makeArray,
/**
 * @page can.Construct.proxy
 * @parent can.Construct
 * @plugin can/construct/plugin
 *
 * Adds a static and prototype proxy method that are
 * useful for creating callback functions that have
 * `this` set correctly.
 *
 *
 * Returns a callback function for a function on this Class.
 * Proxy ensures that 'this' is set appropriately.
 * @codestart
 * can.Construct("MyClass",{
 *     getData: function() {
 *         this.showing = null;
 *         $.get("data.json",this.proxy('gotData'),'json')
 *     },
 *     gotData: function( data ) {
 *         this.showing = data;
 *     }
 * },{});
 * MyClass.showData();
 * @codeend
 *
Currying Arguments

 * Additional arguments to proxy will fill in arguments on the returning function.
 * @codestart
 * can.Construct("MyClass",{
 *    getData: function( callback ) {
 *      $.get("data.json",this.proxy('process',callback),'json');
 *    },
 *    process: function( callback, jsonData ) { //callback is added as first argument
 *        jsonData.processed = true;
 *        callback(jsonData);
 *    }
 * },{});
 * MyClass.getData(showDataFunc)
 * @codeend
 *
Nesting Functions

 * Proxy can take an array of functions to call as
 * the first argument.  When the returned callback function
 * is called each function in the array is passed the return value of the prior function.  This is often used
 * to eliminate currying initial arguments.
 * @codestart
 * can.Construct("MyClass",{
 *    getData: function( callback ) {
 *      //calls process, then callback with value from process
 *      $.get("data.json",this.proxy(['process2',callback]),'json')
 *    },
 *    process2: function( type,jsonData ) {
 *        jsonData.processed = true;
 *        return [jsonData];
 *    }
 * },{});
 * MyClass.getData(showDataFunc);
 * @codeend
 * @param {String|Array} fname If a string, it represents the function to be called.
 * If it is an array, it will call each function in order and pass the return value of the prior function to the
 * next function.
 * @return {Function} the callback function.
 */
proxy = function( funcs ) {

			//args that should be curried
			var args = makeArray(arguments),
				self;

			// get the functions to callback
			funcs = args.shift();

			// if there is only one function, make funcs into an array
			if (!isArray(funcs) ) {
				funcs = [funcs];
			}

			// keep a reference to us in self
			self = this;

			//!steal-remove-start
			for( var i =0; i< funcs.length;i++ ) {
				if(typeof funcs[i] == "string" && !isFunction(this[funcs[i]])){
					throw ("class.js "+( this.fullName || this.Class.fullName)+" does not have a "+funcs[i]+"method!");
				}
			}
			//!steal-remove-end
			return function class_cb() {
				// add the arguments after the curried args
				var cur = args.concat(makeArray(arguments)),
					isString,
					length = funcs.length,
					f = 0,
					func;

				// go through each function to call back
				for (; f < length; f++ ) {
					func = funcs[f];
					if (!func ) {
						continue;
					}

					// set called with the name of the function on self (this is how this.view works)
					isString = typeof func == "string";

					// call the function
					cur = (isString ? self[func] : func).apply(self, cur || []);

					// pass the result to the next function (if there is a next function)
					if ( f < length - 1 ) {
						cur = !isArray(cur) || cur._use_call ? [cur] : cur
					}
				}
				return cur;
			}
		}
	can.Construct.proxy = can.Construct.prototype.proxy = proxy;

});<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
import values from 'lodash/object/values';
import any from 'lodash/collection/any';

import fetchUserGroupsAndTransactions from '../actions/users/fetch_groups_and_transactions';
import fetchUserIfNeeded from '../actions/users/fetch_by_id_cached';
import getPreapprovalKeyForUser from '../actions/users/get_preapproval_key';
import confirmPreapprovalKey from '../actions/users/confirm_preapproval_key';
import fetchCards from '../actions/users/fetch_cards';
import fetchUser from '../actions/users/fetch_by_id';
import notify from '../actions/notification/notify';
import resetNotifications from '../actions/notification/reset';

import Content from './Content';
import Header from '../components/Header';
import Group from '../components/Group';
import PaypalReminder from '../components/PaypalReminder';
import ProfileReminder from '../components/ProfileReminder';
import Notification from '../components/Notification';

import nestTransactionsInGroups from '../lib/nest_transactions_in_groups';
import getUniqueValues from '../lib/get_unique_values';
import isAdmin from '../lib/is_admin';
import rejectError from '../lib/reject_error';

export class GroupsList extends Component {
  render() {
    const { users, groups, isLoading } = this.props;

    return (

        <Content isLoading={isLoading}>
          <Notification {...this.props} />
          {reminder.call(this, this.props)}
          {groups.map(group => {
            return <Group {...group} users={users} key={group.id} />
          })}
        </Content>

    );
  }

  componentDidMount() {
    const {
      fetchUserGroupsAndTransactions,
      userid,
      fetchUserIfNeeded,
      confirmPreapprovalKey,
      fetchCards,
      fetchUser,
      query,
      notify
    } = this.props;

    if (userid) {
      fetchUserGroupsAndTransactions(userid)
      .then(({transactions}) => {
        return getUniqueValues(transactions, 'UserId').map(fetchUserIfNeeded);
      });

      fetchCards(userid, {
        service: 'paypal'
      });

      fetchUser(userid);
    }

    if (query.preapprovalKey && query.approvalStatus === 'success') {
      confirmPreapprovalKey(userid, query.preapprovalKey)
      .then(rejectError)
      .catch(error => notify('error', error.message));
    }
  }
}

export function reminder({
  getPreapprovalKeyForUser,
  inProgress,
  query,
  userid,
  showPaypalReminder,
  showProfileReminder
}) {
  if (showPaypalReminder) {
    return (
      <PaypalReminder
        getPreapprovalKey={getPreapprovalKeyForUser.bind(this, userid)}
        inProgress={inProgress}
        approvalStatus={query.approvalStatus} />
    );
  } else if (showProfileReminder) {
    return (
      <ProfileReminder />
    );
  }
}

export default connect(mapStateToProps, {
  fetchUserGroupsAndTransactions,
  fetchUserIfNeeded,
  getPreapprovalKeyForUser,
  confirmPreapprovalKey,
  fetchCards,
  notify,
  fetchUser,
  resetNotifications
})(GroupsList);

export function mapStateToProps({users, session, router, notification}) {
  // Logged in user
  const userid = session.user.id;
  const currentUser = users[userid] || {};
  const { groups, transactions } = currentUser;
  const query = router.location.query;
  const userCards = values(currentUser.cards);
  const hasConfirmedCards = any(userCards, (c) => !!c.confirmedAt);
  const userIsAdmin = isAdmin(values(groups));

  return {
    groups: nestTransactionsInGroups(groups, transactions),
    userid,
    users,
    transactions,
    notification,
    inProgress: users.inProgress,
    query,
    isLoading: !groups,
    showPaypalReminder: userIsAdmin && (!hasConfirmedCards || query.preapprovalKey),
    showProfileReminder: !userIsAdmin && !currentUser.paypalEmail,
    userIsAdmin, // for testing
    hasConfirmedCards // for testing
  };
}
<commit_msg>Skip the list of collectives view if only one collective<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { pushState } from 'redux-router';
import values from 'lodash/object/values';
import any from 'lodash/collection/any';

import fetchUserGroupsAndTransactions from '../actions/users/fetch_groups_and_transactions';
import fetchUserIfNeeded from '../actions/users/fetch_by_id_cached';
import getPreapprovalKeyForUser from '../actions/users/get_preapproval_key';
import confirmPreapprovalKey from '../actions/users/confirm_preapproval_key';
import fetchCards from '../actions/users/fetch_cards';
import fetchUser from '../actions/users/fetch_by_id';
import notify from '../actions/notification/notify';
import resetNotifications from '../actions/notification/reset';

import Content from './Content';
import Header from '../components/Header';
import Group from '../components/Group';
import PaypalReminder from '../components/PaypalReminder';
import ProfileReminder from '../components/ProfileReminder';
import Notification from '../components/Notification';

import nestTransactionsInGroups from '../lib/nest_transactions_in_groups';
import getUniqueValues from '../lib/get_unique_values';
import isAdmin from '../lib/is_admin';
import rejectError from '../lib/reject_error';

export class GroupsList extends Component {
  render() {
    const { users, groups, isLoading } = this.props;

    return (

        <Content isLoading={isLoading}>
          <Notification {...this.props} />
          {reminder.call(this, this.props)}
          {groups.map(group => {
            return <Group {...group} users={users} key={group.id} />
          })}
        </Content>

    );
  }

  componentDidMount() {
    const {
      fetchUserGroupsAndTransactions,
      userid,
      fetchUserIfNeeded,
      confirmPreapprovalKey,
      fetchCards,
      fetchUser,
      query,
      notify
    } = this.props;

    if (userid) {
      fetchUserGroupsAndTransactions(userid)
      .then(({transactions}) => {
        return getUniqueValues(transactions, 'UserId').map(fetchUserIfNeeded);
      });

      fetchCards(userid, {
        service: 'paypal'
      });

      fetchUser(userid);
    }

    if (query.preapprovalKey && query.approvalStatus === 'success') {
      confirmPreapprovalKey(userid, query.preapprovalKey)
      .then(rejectError)
      .catch(error => notify('error', error.message));
    }
  }
}

export function reminder({
  getPreapprovalKeyForUser,
  inProgress,
  query,
  userid,
  showPaypalReminder,
  showProfileReminder,
  groups,
  pushState
}) {

  if (showPaypalReminder) {
    return (
      <PaypalReminder
        getPreapprovalKey={getPreapprovalKeyForUser.bind(this, userid)}
        inProgress={inProgress}
        approvalStatus={query.approvalStatus} />
    );
  } else if (showProfileReminder) {
    return (
      <ProfileReminder />
    );
  } else {
    // If the logged in user has only access to one collective,
    // we skip the list of collectives view and we go straight to the collective view
    if (groups && Object.keys(groups).length == 1) {
      pushState(null, `/groups/${values(groups)[0].id}/transactions`)
    }
  }
}

export default connect(mapStateToProps, {
  fetchUserGroupsAndTransactions,
  fetchUserIfNeeded,
  getPreapprovalKeyForUser,
  confirmPreapprovalKey,
  fetchCards,
  notify,
  fetchUser,
  resetNotifications,
  pushState
})(GroupsList);

export function mapStateToProps({users, session, router, notification}) {
  // Logged in user
  const userid = session.user.id;
  const currentUser = users[userid] || {};
  const { groups, transactions } = currentUser;
  const query = router.location.query;
  const userCards = values(currentUser.cards);
  const hasConfirmedCards = any(userCards, (c) => !!c.confirmedAt);
  const userIsAdmin = isAdmin(values(groups));

  return {
    groups: nestTransactionsInGroups(groups, transactions),
    userid,
    users,
    transactions,
    notification,
    inProgress: users.inProgress,
    query,
    isLoading: !groups,
    showPaypalReminder: userIsAdmin && (!hasConfirmedCards || query.preapprovalKey),
    showProfileReminder: !userIsAdmin && !currentUser.paypalEmail,
    userIsAdmin, // for testing
    hasConfirmedCards // for testing
  };
}
<|endoftext|>