<commit_before>//
// as/array
// -------------------------------------------------------------------------------------------------
// Maps an `{a: b}` object to a new array of `{key: a, value: b}` pairs.
//
/**
 * @function asArray
 *
 * @param {Object} object
 *    The object to be mapped.
 *
 * @param {Object} [options]
 * - {Number} [depth=0]
 *    The depth to which the `object`'s tree should be mapped. Set it to `Infinity` to map the
 *    entire tree structure.
 *
 * - {Boolean} [traverseArrays=false]
 *    If set to `true`, arrays will be traversed like pure objects. `[true]` will be mapped to
 *    `[{key: "0", value: true}]`.
 *
 * @returns {Array}
 *    A new array of key-value pairs mapped from the object.
 */
module.exports = function asArray (object, options, _depthLeft) {
  var key, value;

  if (!options) options = {};
  var traverseArrays = options.traverseArrays || false;
  if (_depthLeft === void null && options.depth) _depthLeft = options.depth;

  if (!traverseArrays && object instanceof Array) return object.slice();

  var result = [];
  for (key in object) if (object.hasOwnProperty(key)) {
    value = object[key];
    if (  _depthLeft
       && value !== null && typeof value == "object"
       ) {
      value = asArray(value, options, _depthLeft - 1);
      }
    result.push({key: key, value: value});
    }

  return result;
  };
<commit_msg>Get rid of the option `traverseArrays`<commit_after>//
// as/array
// -------------------------------------------------------------------------------------------------
// Maps an `{a: b}` object to a new array of `{key: a, value: b}` pairs.
//
/**
 * @function asArray
 *
 * @param {Object} object
 *    The object to be mapped.
 *
 * @param {Object} [options]
 * - {Number} [depth=0]
 *    The depth to which the `object`'s tree should be mapped. Set it to `Infinity` to map the
 *    entire tree structure.
 *
 * @returns {Array}
 *    A new array of key-value pairs mapped from the object.
 */
module.exports = function asArray (object, options, _depthLeft) {
  var key, value;

  if (!options) options = {};
  if (_depthLeft === void null && options.depth) _depthLeft = options.depth;

  if (object instanceof Array) return object.slice();

  var result = [];
  for (key in object) if (object.hasOwnProperty(key)) {
    value = object[key];
    if (  _depthLeft
       && value !== null && typeof value == "object"
       ) {
      value = asArray(value, options, _depthLeft - 1);
      }
    result.push({key: key, value: value});
    }

  return result;
  };
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves n<commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no<|endoftext|>


<commit_before>'use strict';

const webpack                      = require('webpack');
const DefinePlugin                 = require('webpack/lib/DefinePlugin');
const ProvidePlugin                = require('webpack/lib/ProvidePlugin');
const CommonsChunkPlugin           = require('webpack/lib/optimize/CommonsChunkPlugin');
const LoaderOptionsPlugin          = require('webpack/lib/LoaderOptionsPlugin');
const ContextReplacementPlugin     = require('webpack/lib/ContextReplacementPlugin');
const CopyWebpackPlugin            = require('copy-webpack-plugin');
const NamedModulesPlugin           = require('webpack/lib/NamedModulesPlugin');

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 ChunkManifestPlugin          = require('chunk-manifest-webpack-plugin');

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',
    app: './src/main.ts',
    admin: './src/admin.ts'
  },
  resolve: {
    descriptionFiles: ['package.json'],
    extensions: ['.ts', '.js', '.css', '.scss', 'json', '.html'],
    modules: [helpers.root('src'), helpers.root('node_modules')]
  },
  module: {
    rules: [
      {
        enforce: 'pre',
        test: /\.ts$/,
        loader: 'tslint-loader',
        exclude: [/\.(spec|e2e)\.ts$/, /node_modules/]
      },
      {
        test: /\.ts$/,
        loaders: 'awesome-typescript-loader',
        query: {
          forkChecker: true
        },
        exclude: [/\.(spec|e2e)\.ts$/]
      },
      {
        test: /\.ts$/,
        loaders: [
          'angular2-template-loader',
          '@angularclass/hmr-loader'
        ],
        exclude: [/\.(spec|e2e)\.ts$/]
      },
      {
        test: /\.ts$/,
        loaders: [
          'angular-router-loader' // lazy Loading
        ],
        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\//,
              /@angular\/\*\*\/bundles\//]
  },
  plugins: [
    new NamedModulesPlugin(),
    new ManifestPlugin(),
    new InlineManifestWebpackPlugin(), // TODO check if I can remove this
    new CommonsChunkPlugin({
      name: 'polyfills',
      chunks: ['polyfills'],
      // minChunks: Infinity
    }),
    new CommonsChunkPlugin({
      name: 'vendor',
      chunks: ['app', 'admin'],
      minChunks: module => /node_modules\//.test(module.resource)
    }),
    new CommonsChunkPlugin({
      name: ['polyfills', 'vendor'].reverse()
    }),
    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 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
    ),
    // TODO FIXME restore this
    // new ChunkManifestPlugin({
    //   filename: "manifest.json",
    //   manifestVariable: "webpackManifest"
    // }),
    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>cleanup webpack config common<commit_after>'use strict';

const webpack                      = require('webpack');
const DefinePlugin                 = require('webpack/lib/DefinePlugin');
const ProvidePlugin                = require('webpack/lib/ProvidePlugin');
const CommonsChunkPlugin           = require('webpack/lib/optimize/CommonsChunkPlugin');
const LoaderOptionsPlugin          = require('webpack/lib/LoaderOptionsPlugin');
const ContextReplacementPlugin     = require('webpack/lib/ContextReplacementPlugin');
const CopyWebpackPlugin            = require('copy-webpack-plugin');
const NamedModulesPlugin           = require('webpack/lib/NamedModulesPlugin');

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 ChunkManifestPlugin          = require('chunk-manifest-webpack-plugin');

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',
    app: './src/main.ts',
    admin: './src/admin.ts'
  },
  resolve: {
    descriptionFiles: ['package.json'],
    extensions: ['.ts', '.js', '.css', '.scss', 'json', '.html'],
    modules: [helpers.root('src'), helpers.root('node_modules')]
  },
  module: {
    rules: [
      {
        enforce: 'pre',
        test: /\.ts$/,
        loader: 'tslint-loader',
        exclude: [/\.(spec|e2e)\.ts$/, /node_modules/]
      },
      {
        test: /\.ts$/,
        loaders: 'awesome-typescript-loader',
        query: {
          forkChecker: true
        },
        exclude: [/\.(spec|e2e)\.ts$/]
      },
      {
        test: /\.ts$/,
        loaders: [
          'angular2-template-loader',
          '@angularclass/hmr-loader'
        ],
        exclude: [/\.(spec|e2e)\.ts$/]
      },
      {
        test: /\.ts$/,
        loaders: [
          'angular-router-loader' // lazy Loading
        ],
        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\//,
              /@angular\/\*\*\/bundles\//]
  },
  plugins: [
    new NamedModulesPlugin(),
    new ManifestPlugin(),
    new InlineManifestWebpackPlugin(), // TODO check if I can remove this
    new CommonsChunkPlugin({
      name: 'polyfills',
      chunks: ['polyfills'],
      // minChunks: Infinity
    }),
    new CommonsChunkPlugin({
      name: 'vendor',
      chunks: ['app', 'admin'],
      minChunks: module => /node_modules\//.test(module.resource)
    }),
    new CommonsChunkPlugin({
      name: ['polyfills', 'vendor'].reverse()
    }),
    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 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
    ),
    // TODO FIXME restore this
    // new ChunkManifestPlugin({
    //   filename: "manifest.json",
    //   manifestVariable: "webpackManifest"
    // }),
    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');

/**
 * Webpack Plugins
 *
 * problem with copy-webpack-plugin
 */
const AssetsPlugin = require('assets-webpack-plugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const HtmlElementsPlugin = require('./html-elements-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const InlineManifestWebpackPlugin = require('inline-manifest-webpack-plugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const ngcWebpack = require('ngc-webpack');
//const PreloadWebpackPlugin = require('preload-webpack-plugin');

/**
 * Webpack Constants
 */
const HMR = helpers.hasProcessFlag('hot');
const AOT = process.env.BUILD_AOT || helpers.hasNpmFlag('aot');
const METADATA = {
  title: 'Angular2 Webpack Starter by @gdi2290 from @AngularClass',
  baseUrl: '/',
  isDevServer: helpers.isWebpackDevServer(),
  HMR: HMR
};

/**
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = function (options) {
  isProd = options.env === 'production';
  return {

    /**
     * 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',
      'main':      AOT ? './src/main.browser.aot.ts' :
                  './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', '.json'],

      /**
       * An array of directory names to be resolved to the current directory
       */
      modules: [helpers.root('src'), helpers.root('node_modules')],

    },

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

      rules: [

        /**
         * Typescript loader support for .ts
         *
         * Component Template/Style integration using `angular2-template-loader`
         * Angular 2 lazy loading (async routes) via `ng-router-loader`
         *
         * `ng-router-loader` expects vanilla JavaScript code, not TypeScript code. This is why the
         * order of the loader matter.
         *
         * See: https://github.com/s-panferov/awesome-typescript-loader
         * See: https://github.com/TheLarkInn/angular2-template-loader
         * See: https://github.com/shlomiassaf/ng-router-loader
         */
        {
          test: /\.ts$/,
          use: [
            {
              loader: '@angularclass/hmr-loader',
              options: {
                pretty: !isProd,
                prod: isProd
              }
            },
            {
              /**
               *  MAKE SURE TO CHAIN VANILLA JS CODE, I.E. TS COMPILATION OUTPUT.
               */
              loader: 'ng-router-loader',
              options: {
                loader: 'async-import',
                genDir: 'compiled',
                aot: AOT
              }
            },
            {
              loader: 'awesome-typescript-loader',
              options: {
                configFileName: 'tsconfig.webpack.json',
                useCache: !isProd
              }
            },
            {
              loader: 'ngc-webpack',
              options: {
                disable: !AOT,
              }
            },
            {
              loader: 'angular2-template-loader'
            }
          ],
          exclude: [/\.(spec|e2e)\.ts$/]
        },

        /**
         * To string and css loader support for *.css files (from Angular components)
         * Returns file content as string
         *
         */
        {
          test: /\.css$/,
          use: ['to-string-loader', 'css-loader'],
          exclude: [helpers.root('src', 'styles')]
        },

        /**
         * To string and sass loader support for *.scss files (from Angular components)
         * Returns compiled css content as string
         *
         */
        {
          test: /\.scss$/,
          use: ['to-string-loader', 'css-loader', 'sass-loader'],
          exclude: [helpers.root('src', 'styles')]
        },

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

        /**
         * File loader for supporting images, for example, in CSS files.
         */
        {
          test: /\.(jpg|png|gif)$/,
          use: 'file-loader'
        },

        /* File loader for supporting fonts, for example, in CSS files.
        */
        {
          test: /\.(eot|woff2?|svg|ttf)([\?]?.*)$/,
          use: 'file-loader'
        }

      ],

    },

    /**
     * Add additional plugins to the compiler.
     *
     * See: http://webpack.github.io/docs/configuration.html#plugins
     */
    plugins: [
      // Use for DLLs
      // new AssetsPlugin({
      //   path: helpers.root('dist'),
      //   filename: 'webpack-assets.json',
      //   prettyPrint: true
      // }),

      /**
       * Plugin: ForkCheckerPlugin
       * Description: Do type checking in a separate process, so webpack doesn't need to wait.
       *
       * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
       */
      new CheckerPlugin(),
      /**
       * 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 CommonsChunkPlugin({
        name: 'polyfills',
        chunks: ['polyfills']
      }),
      /**
       * This enables tree shaking of the vendor modules
       */
      // new CommonsChunkPlugin({
      //   name: 'vendor',
      //   chunks: ['main'],
      //   minChunks: module => /node_modules/.test(module.resource)
      // }),
      /**
       * Specify the correct order the scripts will be injected in
       */
      // new CommonsChunkPlugin({
      //   name: ['polyfills', 'vendor'].reverse()
      // }),
      // new CommonsChunkPlugin({
      //   name: ['manifest'],
      //   minChunks: Infinity,
      // }),

      /**
       * 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/,
        helpers.root('src'), // location of your src
        {
          /**
           * Your Angular Async Route paths relative to this root directory
           */
        }
      ),

      /**
       * 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' },
        { from: 'src/meta'}
      ],
        isProd ? { ignore: [ 'mock-data/**/*' ] } : undefined
      ),

      /*
       * Plugin: PreloadWebpackPlugin
       * Description: Preload is a web standard aimed at improving
       * performance and granular loading of resources.
       *
       * See: https://github.com/GoogleChrome/preload-webpack-plugin
       */
      //new PreloadWebpackPlugin({
      //  rel: 'preload',
      //  as: 'script',
      //  include: ['polyfills', 'vendor', 'main'].reverse(),
      //  fileBlacklist: ['.css', '.map']
      //}),
      //new PreloadWebpackPlugin({
      //  rel: 'prefetch',
      //  as: 'script',
      //  include: 'asyncChunks'
      //}),

      /**
       * 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({
        sync: /polyfill|vendor/,
        defaultAttribute: 'async',
        preload: [/polyfill|vendor|main/],
        prefetch: [/chunk/]
      }),

      /*
      * 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',
        title: METADATA.title,
        chunksSortMode: 'dependency',
        metadata: METADATA,
        inject: 'body'
      }),

      /**
       * Plugin: HtmlElementsPlugin
       * 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')
      }),

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

      new ngcWebpack.NgcWebpackPlugin({
        /**
         * If false the plugin is a ghost, it will not perform any action.
         * This property can be used to trigger AOT on/off depending on your build target (prod, staging etc...)
         *
         * The state can not change after initializing the plugin.
         * @default true
         */
        disabled: !AOT,
        tsConfig: helpers.root('tsconfig.webpack.json'),
      }),

      /**
       * Plugin: InlineManifestWebpackPlugin
       * Inline Webpack's manifest.js in index.html
       *
       * https://github.com/szrenwei/inline-manifest-webpack-plugin
       */
      new InlineManifestWebpackPlugin(),
    ],

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

  };
}
<commit_msg>chore: reorder ScriptExtHtmlWebpackPlugin (#1858)<commit_after>/**
 * @author: @AngularClass
 */

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

/**
 * Webpack Plugins
 *
 * problem with copy-webpack-plugin
 */
const AssetsPlugin = require('assets-webpack-plugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const HtmlElementsPlugin = require('./html-elements-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const InlineManifestWebpackPlugin = require('inline-manifest-webpack-plugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const ngcWebpack = require('ngc-webpack');
//const PreloadWebpackPlugin = require('preload-webpack-plugin');

/**
 * Webpack Constants
 */
const HMR = helpers.hasProcessFlag('hot');
const AOT = process.env.BUILD_AOT || helpers.hasNpmFlag('aot');
const METADATA = {
  title: 'Angular2 Webpack Starter by @gdi2290 from @AngularClass',
  baseUrl: '/',
  isDevServer: helpers.isWebpackDevServer(),
  HMR: HMR
};

/**
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = function (options) {
  isProd = options.env === 'production';
  return {

    /**
     * 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',
      'main':      AOT ? './src/main.browser.aot.ts' :
                  './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', '.json'],

      /**
       * An array of directory names to be resolved to the current directory
       */
      modules: [helpers.root('src'), helpers.root('node_modules')],

    },

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

      rules: [

        /**
         * Typescript loader support for .ts
         *
         * Component Template/Style integration using `angular2-template-loader`
         * Angular 2 lazy loading (async routes) via `ng-router-loader`
         *
         * `ng-router-loader` expects vanilla JavaScript code, not TypeScript code. This is why the
         * order of the loader matter.
         *
         * See: https://github.com/s-panferov/awesome-typescript-loader
         * See: https://github.com/TheLarkInn/angular2-template-loader
         * See: https://github.com/shlomiassaf/ng-router-loader
         */
        {
          test: /\.ts$/,
          use: [
            {
              loader: '@angularclass/hmr-loader',
              options: {
                pretty: !isProd,
                prod: isProd
              }
            },
            {
              /**
               *  MAKE SURE TO CHAIN VANILLA JS CODE, I.E. TS COMPILATION OUTPUT.
               */
              loader: 'ng-router-loader',
              options: {
                loader: 'async-import',
                genDir: 'compiled',
                aot: AOT
              }
            },
            {
              loader: 'awesome-typescript-loader',
              options: {
                configFileName: 'tsconfig.webpack.json',
                useCache: !isProd
              }
            },
            {
              loader: 'ngc-webpack',
              options: {
                disable: !AOT,
              }
            },
            {
              loader: 'angular2-template-loader'
            }
          ],
          exclude: [/\.(spec|e2e)\.ts$/]
        },

        /**
         * To string and css loader support for *.css files (from Angular components)
         * Returns file content as string
         *
         */
        {
          test: /\.css$/,
          use: ['to-string-loader', 'css-loader'],
          exclude: [helpers.root('src', 'styles')]
        },

        /**
         * To string and sass loader support for *.scss files (from Angular components)
         * Returns compiled css content as string
         *
         */
        {
          test: /\.scss$/,
          use: ['to-string-loader', 'css-loader', 'sass-loader'],
          exclude: [helpers.root('src', 'styles')]
        },

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

        /**
         * File loader for supporting images, for example, in CSS files.
         */
        {
          test: /\.(jpg|png|gif)$/,
          use: 'file-loader'
        },

        /* File loader for supporting fonts, for example, in CSS files.
        */
        {
          test: /\.(eot|woff2?|svg|ttf)([\?]?.*)$/,
          use: 'file-loader'
        }

      ],

    },

    /**
     * Add additional plugins to the compiler.
     *
     * See: http://webpack.github.io/docs/configuration.html#plugins
     */
    plugins: [
      // Use for DLLs
      // new AssetsPlugin({
      //   path: helpers.root('dist'),
      //   filename: 'webpack-assets.json',
      //   prettyPrint: true
      // }),

      /**
       * Plugin: ForkCheckerPlugin
       * Description: Do type checking in a separate process, so webpack doesn't need to wait.
       *
       * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
       */
      new CheckerPlugin(),
      /**
       * 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 CommonsChunkPlugin({
        name: 'polyfills',
        chunks: ['polyfills']
      }),
      /**
       * This enables tree shaking of the vendor modules
       */
      // new CommonsChunkPlugin({
      //   name: 'vendor',
      //   chunks: ['main'],
      //   minChunks: module => /node_modules/.test(module.resource)
      // }),
      /**
       * Specify the correct order the scripts will be injected in
       */
      // new CommonsChunkPlugin({
      //   name: ['polyfills', 'vendor'].reverse()
      // }),
      // new CommonsChunkPlugin({
      //   name: ['manifest'],
      //   minChunks: Infinity,
      // }),

      /**
       * 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/,
        helpers.root('src'), // location of your src
        {
          /**
           * Your Angular Async Route paths relative to this root directory
           */
        }
      ),

      /**
       * 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' },
        { from: 'src/meta'}
      ],
        isProd ? { ignore: [ 'mock-data/**/*' ] } : undefined
      ),

      /*
       * Plugin: PreloadWebpackPlugin
       * Description: Preload is a web standard aimed at improving
       * performance and granular loading of resources.
       *
       * See: https://github.com/GoogleChrome/preload-webpack-plugin
       */
      //new PreloadWebpackPlugin({
      //  rel: 'preload',
      //  as: 'script',
      //  include: ['polyfills', 'vendor', 'main'].reverse(),
      //  fileBlacklist: ['.css', '.map']
      //}),
      //new PreloadWebpackPlugin({
      //  rel: 'prefetch',
      //  as: 'script',
      //  include: 'asyncChunks'
      //}),

      /*
      * 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',
        title: METADATA.title,
        chunksSortMode: 'dependency',
        metadata: METADATA,
        inject: 'body'
      }),

       /**
       * 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({
        sync: /polyfills|vendor/,
        defaultAttribute: 'async',
        preload: [/polyfills|vendor|main/],
        prefetch: [/chunk/]
      }),

      /**
       * Plugin: HtmlElementsPlugin
       * 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')
      }),

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

      new ngcWebpack.NgcWebpackPlugin({
        /**
         * If false the plugin is a ghost, it will not perform any action.
         * This property can be used to trigger AOT on/off depending on your build target (prod, staging etc...)
         *
         * The state can not change after initializing the plugin.
         * @default true
         */
        disabled: !AOT,
        tsConfig: helpers.root('tsconfig.webpack.json'),
      }),

      /**
       * Plugin: InlineManifestWebpackPlugin
       * Inline Webpack's manifest.js in index.html
       *
       * https://github.com/szrenwei/inline-manifest-webpack-plugin
       */
      new InlineManifestWebpackPlugin(),
    ],

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

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

/*
 * 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', '.json'],

    // Make sure root is src
    root: helpers.root('src'),
    alias: {
      'common': helpers.root('./src/app/common/index.ts'),
      'loading.css': helpers.root('./src/assets/css/loading.css')
    },

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

  },

  /*
   * 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/@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'
      },
      {
        test: /\.scss$/,
        loader: `raw!postcss!sass?outputStyle=expanded&includePaths[]=${helpers.root('src/styles')}/`
      },
      /*
       * to string and css loader support for *.css files
       * Returns file content as string
       *
       */
      {
        test: /\.css$/,
        loaders: ['to-string-loader', 'css-loader']
      },

      /* Raw loader support for *.html
       * Returns file content as string
       *
       * See: https://github.com/webpack/raw-loader
       */
      {
        test: /\.html$/,
        loader: 'raw-loader',
        exclude: [helpers.root('src/index.html')]
      }

    ]

  },

  /*
   * 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 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')
    }),

  ],

  /*
   * 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',
    process: true,
    module: false,
    clearImmediate: false,
    setImmediate: false
  }

};
<commit_msg>小莫的个人网站<commit_after>/**
 * @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');

/*
 * Webpack Constants
 */
const METADATA = {
  title: '小莫的个人网站',
  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', '.json'],

    // Make sure root is src
    root: helpers.root('src'),
    alias: {
      'common': helpers.root('./src/app/common/index.ts'),
      'loading.css': helpers.root('./src/assets/css/loading.css')
    },

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

  },

  /*
   * 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/@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'
      },
      {
        test: /\.scss$/,
        loader: `raw!postcss!sass?outputStyle=expanded&includePaths[]=${helpers.root('src/styles')}/`
      },
      /*
       * to string and css loader support for *.css files
       * Returns file content as string
       *
       */
      {
        test: /\.css$/,
        loaders: ['to-string-loader', 'css-loader']
      },

      /* Raw loader support for *.html
       * Returns file content as string
       *
       * See: https://github.com/webpack/raw-loader
       */
      {
        test: /\.html$/,
        loader: 'raw-loader',
        exclude: [helpers.root('src/index.html')]
      }

    ]

  },

  /*
   * 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 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')
    }),

  ],

  /*
   * 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',
    process: true,
    module: false,
    clearImmediate: false,
    setImmediate: false
  }

};
<|endoftext|>


<commit_before>
var webpack = require('webpack')

var bannerText = `/**
* @name JSON Editor
* @description JSON Schema Based Editor
* This library is the continuation of jdorn's great work (see also https://github.com/jdorn/json-editor/issues/800)
* @version {{ VERSION }}
* @author Jeremy Dorn
* @see https://github.com/jdorn/json-editor/
* @see https://github.com/json-editor/json-editor
* @license MIT
* @example see README.md and docs/ for requirements, examples and usage info
*/`
module.exports = {
  entry: {
    // 'polyfills': './src/polyfills.ts',
    'jsoneditor': './src/core.js'
  },
  resolve: {
    extensions: ['.js']
  },
  module: {

    rules: [
      // {
      //   enforce: 'pre',
      //   test: /\.js$/,
      //   exclude: /node_modules/,
      //   loader: `eslint-loader`,
      //   options: {
      //     // configFile: helpers.root('config/.eslintrc')
      //   },
      // },
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader'
        ]
      }
    ]
  },
  plugins: [
    new webpack.BannerPlugin(bannerText.replace('{{ VERSION }}', JSON.stringify(require('../package.json').version)))
  ]
}
<commit_msg>Re-enabled Webpack Eslint rule enforcement<commit_after>
var webpack = require('webpack')

var bannerText = `/**
* @name JSON Editor
* @description JSON Schema Based Editor
* This library is the continuation of jdorn's great work (see also https://github.com/jdorn/json-editor/issues/800)
* @version {{ VERSION }}
* @author Jeremy Dorn
* @see https://github.com/jdorn/json-editor/
* @see https://github.com/json-editor/json-editor
* @license MIT
* @example see README.md and docs/ for requirements, examples and usage info
*/`
module.exports = {
  entry: {
    // 'polyfills': './src/polyfills.ts',
    'jsoneditor': './src/core.js'
  },
  resolve: {
    extensions: ['.js']
  },
  module: {

    rules: [
      {
        enforce: 'pre',
        test: /\.js$/,
        exclude: /node_modules/,
        loader: `eslint-loader`,
        options: {
          fix: true
        }
      },
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader'
        ]
      }
    ]
  },
  plugins: [
    new webpack.BannerPlugin(bannerText.replace('{{ VERSION }}', JSON.stringify(require('../package.json').version)))
  ]
}
<|endoftext|>


<commit_before>'use babel';

import TreeViewSearchBar from '../lib/tree-view-search-bar';

// describe("TreeViewSearchBar", function() {
// });

// import MyTestPlugin from '../lib/my-test-plugin';
//
// describe("MyTestPlugin", function() {
//   var editor,
//       ref,
//       workspaceElement;
//
//   beforeEach(function() {
//     workspaceElement = atom.views.getView(atom.workspace);
//     jasmine.attachToDOM(workspaceElement);
//     waitsForPromise(function() { return atom.workspace.open('sample.js'); });
//
//     runs(function() {
//       editor = atom.workspace.getActiveTextEditor();
//       editor.setText("This is the file content");
//     });
//     waitsForPromise(function() {
//       return atom.packages.activatePackage('minimap');
//     });
//     return waitsForPromise(function() {
//       return atom.packages.activatePackage('my-test-plugin');
//     });
//   });
//   describe("with an open editor that have a minimap", function() {
//     it("lives", function() {
//       expect('life').toBe('easy');
//     });
//   });
// });
<commit_msg>update spec<commit_after>'use babel';

import DEV from '../lib/module/dev';
// import TreeViewSearchBar from '../lib/main';

describe('TreeViewSearchBar', () => {
    it('Publish', () => {
        expect(DEV).toBe(false);
    });
});

// import MyTestPlugin from '../lib/my-test-plugin';
//
// describe("MyTestPlugin", function() {
//   var editor,
//       ref,
//       workspaceElement;
//
//   beforeEach(function() {
//     workspaceElement = atom.views.getView(atom.workspace);
//     jasmine.attachToDOM(workspaceElement);
//     waitsForPromise(function() { return atom.workspace.open('sample.js'); });
//
//     runs(function() {
//       editor = atom.workspace.getActiveTextEditor();
//       editor.setText("This is the file content");
//     });
//     waitsForPromise(function() {
//       return atom.packages.activatePackage('minimap');
//     });
//     return waitsForPromise(function() {
//       return atom.packages.activatePackage('my-test-plugin');
//     });
//   });
//   describe("with an open editor that have a minimap", function() {
//     it("lives", function() {
//       expect('life').toBe('easy');
//     });
//   });
// });
<|endoftext|>


<commit_before>const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const helpers = require('./helpers');
const precss = require('precss');
const autoprefixer = require('autoprefixer')

module.exports = {
  entry: {
    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'app': './src/main.ts'
  },

  resolve: {
    extensions: ['.webpack.js', '.wep.js', '.js', '.ts']
  },

  stats: {
    colors: true,
    reasons: true
  },

  module: {
    rules: [
      {
        test: /\.ts$/,
        loaders: [
          'ts-loader',
          'angular2-template-loader'
        ],
        exclude: [/\.(spec|e2e)\.ts$/]
      },
      // {
      //   test: /\.html$/,
      //   loader: 'html-loader'
      // },
      {
        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
        loader: 'file-loader?name=assets/[name].[hash].[ext]'
      },
      // {
      //   test: /\.(css|scss)$/,
      //   loaders: ['to-string-loader', 'css-loader', 'sass-loader'],
      //   include: helpers.root('src', 'app'),
      // },
      // { test: /\.css$/,
      //   exclude: [helpers.root('src', 'app')],
      //   use: ExtractTextPlugin.extract({
      //     fallback: 'style-loader',
      //     use: [
      //       { loader: 'css-loader', query: { modules: true, sourceMaps: true } },
      //       { loader: 'postcss-loader'  }
      //     ]
      //   })
      // },
      // {
      //   test: /\.css$/,
      //   include: [helpers.root('src', 'app')],
      //   use: [
      //     { loader: 'raw-loader' },
      //     { loader: 'postcss-loader' }
      //   ]
      // },

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

      /*
       * to string and css loader support for *.css files
       * Returns file content as string
       *
       */
      {
        test: /\.css$/,
        loaders: ['to-string-loader', 'css-loader']
      },

      {
        test: /\.scss$/,
        loaders: ["css-to-string-loader", "css-loader", "sass-loader"]
      },
      // {
      //   test: /(\.css|\.scss)$/,
      //   exclude: [helpers.root('src', 'app')],
      //   use: ExtractTextPlugin
      //     .extract({
      //       // fallback: 'style-loader',
      //       use: [
      //         // { loader: 'to-string-loader'},
      //         { loader: 'css-loader',
      //           options: {
      //             modules: true,
      //             sourceMaps: true,
      //             importLoaders: true,
      //             // localIdentName: "[name]__[local]___[hash:base64:5]"
      //           }
      //         },
      //         { loader: 'postcss-loader',
      //           options: {
      //             plugins: function () {
      //               return [
      //                 require("autoprefixer")
      //               ];
      //             }
      //           }
      //         },
      //         { loader: 'sass-loader',
      //           options: {
      //             sourceMaps: true
      //           }
      //         }
      //       ]
      //     })
      // },
      // {
      //   test: /(\.css|\.scss)$/,
      //   include: [helpers.root('src', 'app')],
      //   use: [
      //     { loader: 'raw-loader' },
      //     { loader: 'postcss-loader' },
      //     { loader: 'sass-loader', options: { sourceMaps: true } }
      //   ]
      // }

      // {
      //   test: /\.css$/,
      //   include: helpers.root('src', 'app'),
      //   loader: 'raw-loader!postcss-loader'
      // },
      // {
      //   test: /\.scss$/,
      //   include: helpers.root('src', 'app'),
      //   loaders: ['raw-loader', 'css-loader', 'postcss-loader', 'sass-loader']
      // }
    ]
  },

  plugins: [
    // require('postcss-import')(),
    // require('autoprefixer')(),

    new webpack.optimize.CommonsChunkPlugin({
      name: ['app', 'vendor', 'polyfills']
    }),

    /**
     * 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 webpack.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 HtmlWebpackPlugin({
      template: 'src/index.html'
    })
  ],

  // postcss: function () {
  //     return [precss, autoprefixer({ browsers: ['last 2 versions'] })];
  // }
};
<commit_msg>reset the webpack loaders<commit_after>const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const helpers = require('./helpers');
const precss = require('precss');
const autoprefixer = require('autoprefixer')

module.exports = {
  entry: {
    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'app': './src/main.ts'
  },

  resolve: {
    extensions: ['.webpack.js', '.wep.js', '.js', '.ts']
  },

  stats: {
    colors: true,
    reasons: true
  },

  module: {
    rules: [
      {
        test: /\.ts$/,
        loaders: [
          'ts-loader',
          'angular2-template-loader'
        ],
        exclude: [/\.(spec|e2e)\.ts$/]
      },
      {
        test: /\.html$/,
        loader: 'html-loader'
      },
      {
        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
        loader: 'file-loader?name=assets/[name].[hash].[ext]'
      },
      // {
      //   test: /\.(css|scss)$/,
      //   loaders: ['to-string-loader', 'css-loader', 'sass-loader'],
      //   include: helpers.root('src', 'app'),
      // },
      // { test: /\.css$/,
      //   exclude: [helpers.root('src', 'app')],
      //   use: ExtractTextPlugin.extract({
      //     fallback: 'style-loader',
      //     use: [
      //       { loader: 'css-loader', query: { modules: true, sourceMaps: true } },
      //       { loader: 'postcss-loader'  }
      //     ]
      //   })
      // },
      // {
      //   test: /\.css$/,
      //   include: [helpers.root('src', 'app')],
      //   use: [
      //     { loader: 'raw-loader' },
      //     { loader: 'postcss-loader' }
      //   ]
      // },

      {
        test: /(\.css|\.scss)$/,
        exclude: [helpers.root('src', 'app')],
        use: ExtractTextPlugin
          .extract({
            // fallback: 'style-loader',
            use: [
              // { loader: 'to-string-loader'},
              { loader: 'css-loader',
                options: {
                  modules: true,
                  sourceMaps: true,
                  importLoaders: true,
                  // localIdentName: "[name]__[local]___[hash:base64:5]"
                }
              },
              { loader: 'postcss-loader',
                options: {
                  plugins: function () {
                    return [
                      require("autoprefixer")
                    ];
                  }
                }
              },
              { loader: 'sass-loader',
                options: {
                  sourceMaps: true
                }
              }
            ]
          })
      },
      {
        test: /(\.css|\.scss)$/,
        include: [helpers.root('src', 'app')],
        use: [
          { loader: 'raw-loader' },
          { loader: 'postcss-loader' },
          { loader: 'sass-loader', options: { sourceMaps: true } }
        ]
      }
      // {
      //   test: /\.css$/,
      //   include: helpers.root('src', 'app'),
      //   loader: 'raw-loader!postcss-loader'
      // },
      // {
      //   test: /\.scss$/,
      //   include: helpers.root('src', 'app'),
      //   loaders: ['raw-loader', 'css-loader', 'postcss-loader', 'sass-loader']
      // }
    ]
  },

  plugins: [
    // require('postcss-import')(),
    // require('autoprefixer')(),

    new webpack.optimize.CommonsChunkPlugin({
      name: ['app', 'vendor', 'polyfills']
    }),

    /**
     * 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 webpack.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 HtmlWebpackPlugin({
      template: 'src/index.html'
    })
  ],

  // postcss: function () {
  //     return [precss, autoprefixer({ browsers: ['last 2 versions'] })];
  // }
};
<|endoftext|>


<commit_before>jasmine.getFixtures().fixturesPath = 'specs/fixtures';

describe('Settings initialization', function() {
  beforeEach(function() {
    loadFixtures('example.html');
  });

  it('default settings', function() {
    var dtr = $('#map-canvas').drawTheRoute();

    expect(dtr.settings.zoom).toEqual(14);
    expect(dtr.settings.center).toEqual([-15.7941454, -47.88254789999996]);
    expect(dtr.settings.attachToRoad).toEqual(true);
    expect(dtr.settings.lineColor).toEqual('#FF0000');
    expect(dtr.settings.nodes).toEqual([]);
  });

  it('can receive settings', function() {
    var dtr = $('#map-canvas').drawTheRoute({
      zoom: 10,
      center: [-14.44, -47.88],
      attachToRoad: false,
      lineColor: 'blue',
      nodes: [
        [-15.79,-47.89],[-15.70,-47.87]
      ],
    });

    expect(dtr.settings.zoom).toEqual(10);
    expect(dtr.settings.center).toEqual([-14.44, -47.88]);
    expect(dtr.settings.attachToRoad).toEqual(false);
    expect(dtr.settings.lineColor).toEqual('blue');
    expect(dtr.settings.nodes).toEqual([[-15.79,-47.89],[-15.70,-47.87]]);
  });
});

describe('Google Maps Objects Initialization', function () {
  beforeEach(function() {
    loadFixtures('example.html');

    this.dtr = $('#map-canvas').drawTheRoute();
  });

  it('with default map center object', function () {
    expect(this.dtr.map.center.k).toEqual(-15.7941454);
    expect(this.dtr.map.center.B).toEqual(-47.88254789999996);
  });

  it('with default map zoom object (delegated to settings#zoom)', function () {
    expect(this.dtr.map.zoom).toEqual(14);
  });

  it('has map mapTypeId', function () {
    expect(this.dtr.map.zoom).toEqual(14);
  });

  it('has directionsService object', function () {
    expect(this.dtr.directionsService).toEqual(jasmine.any(Object));
  });

  it('has directionsDisplay object', function () {
    expect(this.dtr.directionsDisplay).toEqual(jasmine.any(Object));
  });

  it('has markers list', function () {
    expect(this.dtr.markers).toEqual([]);
  });
});

describe('Nodes object functions', function () {
  beforeEach(function() {
    loadFixtures('example.html');

    this.dtr = $('#map-canvas').drawTheRoute();

    this.dtr.nodes.elements = [1, 3, 4]
  });

  describe('last', function () {
    it('without params', function () {
      expect(this.dtr.nodes.last()).toEqual(4)
    });

    it('with params', function () {
      expect(this.dtr.nodes.last(2)).toEqual(3)
    });
  });

  it('first', function () {
    expect(this.dtr.nodes.first()).toEqual(1)
  });

  it('all', function () {
    expect(this.dtr.nodes.all()).toEqual([1, 3, 4])
  });

  it('waypoints', function () {
    expect(this.dtr.nodes.waypoints()).toEqual([3, 4])
  });

  it('push', function () {
    this.dtr.nodes.push(10);

    expect(this.dtr.nodes.elements).toEqual([1, 3, 4, 10])
  });

  it('pop', function () {
    this.dtr.nodes.pop();

    expect(this.dtr.nodes.elements).toEqual([1, 3])
  });
});<commit_msg>adding semicolons<commit_after>jasmine.getFixtures().fixturesPath = 'specs/fixtures';

describe('Settings initialization', function() {
  beforeEach(function() {
    loadFixtures('example.html');
  });

  it('default settings', function() {
    var dtr = $('#map-canvas').drawTheRoute();

    expect(dtr.settings.zoom).toEqual(14);
    expect(dtr.settings.center).toEqual([-15.7941454, -47.88254789999996]);
    expect(dtr.settings.attachToRoad).toEqual(true);
    expect(dtr.settings.lineColor).toEqual('#FF0000');
    expect(dtr.settings.nodes).toEqual([]);
  });

  it('can receive settings', function() {
    var dtr = $('#map-canvas').drawTheRoute({
      zoom: 10,
      center: [-14.44, -47.88],
      attachToRoad: false,
      lineColor: 'blue',
      nodes: [
        [-15.79,-47.89],[-15.70,-47.87]
      ],
    });

    expect(dtr.settings.zoom).toEqual(10);
    expect(dtr.settings.center).toEqual([-14.44, -47.88]);
    expect(dtr.settings.attachToRoad).toEqual(false);
    expect(dtr.settings.lineColor).toEqual('blue');
    expect(dtr.settings.nodes).toEqual([[-15.79,-47.89],[-15.70,-47.87]]);
  });
});

describe('Google Maps Objects Initialization', function () {
  beforeEach(function() {
    loadFixtures('example.html');

    this.dtr = $('#map-canvas').drawTheRoute();
  });

  it('with default map center object', function () {
    expect(this.dtr.map.center.k).toEqual(-15.7941454);
    expect(this.dtr.map.center.B).toEqual(-47.88254789999996);
  });

  it('with default map zoom object (delegated to settings#zoom)', function () {
    expect(this.dtr.map.zoom).toEqual(14);
  });

  it('has map mapTypeId', function () {
    expect(this.dtr.map.zoom).toEqual(14);
  });

  it('has directionsService object', function () {
    expect(this.dtr.directionsService).toEqual(jasmine.any(Object));
  });

  it('has directionsDisplay object', function () {
    expect(this.dtr.directionsDisplay).toEqual(jasmine.any(Object));
  });

  it('has markers list', function () {
    expect(this.dtr.markers).toEqual([]);
  });
});

describe('Nodes object functions', function () {
  beforeEach(function() {
    loadFixtures('example.html');

    this.dtr = $('#map-canvas').drawTheRoute();

    this.dtr.nodes.elements = [1, 3, 4];
  });

  describe('last', function () {
    it('without params', function () {
      expect(this.dtr.nodes.last()).toEqual(4);
    });

    it('with params', function () {
      expect(this.dtr.nodes.last(2)).toEqual(3);
    });
  });

  it('first', function () {
    expect(this.dtr.nodes.first()).toEqual(1);
  });

  it('all', function () {
    expect(this.dtr.nodes.all()).toEqual([1, 3, 4]);
  });

  it('waypoints', function () {
    expect(this.dtr.nodes.waypoints()).toEqual([3, 4]);
  });

  it('push', function () {
    this.dtr.nodes.push(10);

    expect(this.dtr.nodes.elements).toEqual([1, 3, 4, 10]);
  });

  it('pop', function () {
    this.dtr.nodes.pop();

    expect(this.dtr.nodes.elements).toEqual([1, 3]);
  });
});
<|endoftext|>


<commit_before>(function($, window, undefined){
    $.widget( "epilgrim.sessionTimeoutHandler", {
        options: {
            // default options
            title :                  'Session Timeout',
            message :                'Your session is about to expire.',
            keepAliveUrl :           'keepAlive.php',
            retrieveTimeLeftUrl :    'retrieveTimeLeft.php',
            redirUrl :               false,
            logoutUrl :              'logout.php',
            defaultSessionTime:       false,
            warnWhenLeft :            300000,
            checkTimeBeforeRedirect:  true,
            checkTimeBeforePopup:     false,
            errorGettingSessionTimeLeft:  'There was an error retrieving session information from the server. Session could be timed out',
            modalId:                 'sessionTimeout-dialog',

            // callbacks
            logOutNow: function(event, data){
                window.location = data.plugin.options.logoutUrl;
            },
            redirectNow: function(event, data){
                window.location = data.plugin.options.redirUrl;
            },
            stayConnected: function(event, data){
                data.plugin.modal.dialog('close');
                data.plugin._trigger(
                    'getSessionTimeLeft',
                    null,
                    {
                        plugin: data.plugin,
                        updateSession: true,
                        callback: $.proxy(
                            function(time){
                                this.initializeTimers(time);
                            }, data.plugin)
                    }
                );
            },
            getSessionTimeLeft: function ( event, data ){
                var action = data.updateSession ? data.plugin.options.keepAliveUrl : data.plugin.options.retrieveTimeLeftUrl;
                var self = data.plugin;
                $.ajax({
                    context: self,
                    dataType: "json",
                    url: action,
                    success: function (time){
                        var timeLeft = time * 1000;
                        data.callback.call(self, timeLeft);
                        if(timeLeft > this.options.warnWhenLeft){//greater than 500ms close the popup
                            this.modal.dialog('close');
                        }
                    },
                    error: function(){
                        alert(self.options.errorGettingSessionTimeLeft);
                    }
                });
            }
        },
        // the constructor
        _create: function() {
            // Create timeout warning dialog
            this.dialogTimer = null;

            // timer for redirecting
            this.redirectTimer = null;

            if (this.options.redirUrl == false){
                this.options.redirUrl = this.options.logoutUrl;
            }

            this._createModal();

            this.initializeTimers(this.options.defaultSessionTime);
        },
        _createModal: function(){
            var self = this;
            this.modal = jQuery('<div/>', {
                id: this.options.modalId,
                title: this.options.title,
                text: this.options.message
            });
            this.modal.appendTo(this.element);

            this.modal.dialog({
                autoOpen: false,
                width: 400,
                modal: true,
                closeOnEscape: false,
                open: function(event, ui) { $(".ui-dialog-titlebar-close", this.modal).hide(); },
                buttons: {
                    // Button one - takes user to logout URL
                    "Log Out Now": function() {
                        self._trigger('logOutNow', null, { plugin: self });
                    },
                    // Button two - closes dialog and makes call to keep-alive URL
                    "Stay Connected": function() {
                        self._trigger('stayConnected', null, { plugin: self });
                    }
                }
            });
        },
        _destroy: function() {
            // remove generated elements
            this.modal.remove();

        },
        _dialogTimer: function(action, time ){
            switch(action) {
                case 'start':
                    this.dialogTimer = setTimeout($.proxy(this._dialogHandler, this), time);
                    break;
                case 'stop':
                    clearTimeout(this.dialogTimer);
                    break;
                case 'restart':
                    this._dialogTimer('stop');
                    this._dialogTimer('start', time);
                    break;
            }
        },
        _redirectTimer: function(action, time ){
            switch(action) {
                case 'start':
                    this.redirectTimer = setTimeout($.proxy(this._redirectHandler, this), time);
                    break;
                case 'stop':
                    clearTimeout(this.redirectTimer);
                    break;
                case 'restart':
                    this._redirectTimer('stop');
                    this._redirectTimer('start', time);
                    break;
            }
        },
        _dialogHandler: function(){
            if(this.options.checkTimeBeforePopup){
                 this._trigger('getSessionTimeLeft', null, {plugin: this, updateSession: false, callback: function(time){
                    if (time <= 60000){
                        this.modal.dialog('open');
                    } else {
                        this.initializeTimers(time);
                    }
                }});
            }else{
                this.modal.dialog('open');
            }
        },
        _redirectHandler: function(){
            if (this.options.checkTimeBeforeRedirect){
                this._trigger('getSessionTimeLeft', null, {plugin: this, updateSession: false, callback: function(time){
                    if (time <= 0){
                        this._trigger('redirectNow', null, {plugin: this});
                    } else {
                        this.initializeTimers(time);
                    }
                }});
            } else {
                this._trigger('redirectNow', null, {plugin: this});
            }
        },
        _setTimers: function (time){
            var action;

            action = this.dialogTimer === null ? 'start' : 'restart';
            this._dialogTimer( action, (time - this.options.warnWhenLeft));

            action = this.redirectTimer === null ? 'start' : 'restart';
            this._redirectTimer ( action, time);
        },
        initializeTimers: function (time){
            if ( time === false){
                // if no time variable was passed, get it from the server
                 this._trigger('getSessionTimeLeft', null, {plugin: this, updateSession: false, callback: this._setTimers});
            } else {
                // when time variable passed, set it
                this._setTimers(time);
            }
        }
    });
})(jQuery, window);
<commit_msg>fixed line endings<commit_after>(function($, window, undefined){
    $.widget( "epilgrim.sessionTimeoutHandler", {
        options: {
            // default options
            title :                  'Session Timeout',
            message :                'Your session is about to expire.',
            keepAliveUrl :           'keepAlive.php',
            retrieveTimeLeftUrl :    'retrieveTimeLeft.php',
            redirUrl :               false,
            logoutUrl :              'logout.php',
            defaultSessionTime:       false,
            warnWhenLeft :            300000,
            checkTimeBeforeRedirect:  true,
            checkTimeBeforePopup:     false,
            errorGettingSessionTimeLeft:  'There was an error retrieving session information from the server. Session could be timed out',
            modalId:                 'sessionTimeout-dialog',

            // callbacks
            logOutNow: function(event, data){
                window.location = data.plugin.options.logoutUrl;
            },
            redirectNow: function(event, data){
                window.location = data.plugin.options.redirUrl;
            },
            stayConnected: function(event, data){
                data.plugin.modal.dialog('close');
                data.plugin._trigger(
                    'getSessionTimeLeft',
                    null,
                    {
                        plugin: data.plugin,
                        updateSession: true,
                        callback: $.proxy(
                            function(time){
                                this.initializeTimers(time);
                            }, data.plugin)
                    }
                );
            },
            getSessionTimeLeft: function ( event, data ){
                var action = data.updateSession ? data.plugin.options.keepAliveUrl : data.plugin.options.retrieveTimeLeftUrl;
                var self = data.plugin;
                $.ajax({
                    context: self,
                    dataType: "json",
                    url: action,
                    success: function (time){
                        var timeLeft = time * 1000;
                        data.callback.call(self, timeLeft);
                        if(timeLeft > this.options.warnWhenLeft){//greater than 500ms close the popup
                            this.modal.dialog('close');
                        }
                    },
                    error: function(){
                        alert(self.options.errorGettingSessionTimeLeft);
                    }
                });
            }
        },
        // the constructor
        _create: function() {
            // Create timeout warning dialog
            this.dialogTimer = null;

            // timer for redirecting
            this.redirectTimer = null;

            if (this.options.redirUrl == false){
                this.options.redirUrl = this.options.logoutUrl;
            }

            this._createModal();

            this.initializeTimers(this.options.defaultSessionTime);
        },
        _createModal: function(){
            var self = this;
            this.modal = jQuery('<div/>', {
                id: this.options.modalId,
                title: this.options.title,
                text: this.options.message
            });
            this.modal.appendTo(this.element);

            this.modal.dialog({
                autoOpen: false,
                width: 400,
                modal: true,
                closeOnEscape: false,
                open: function(event, ui) { $(".ui-dialog-titlebar-close", this.modal).hide(); },
                buttons: {
                    // Button one - takes user to logout URL
                    "Log Out Now": function() {
                        self._trigger('logOutNow', null, { plugin: self });
                    },
                    // Button two - closes dialog and makes call to keep-alive URL
                    "Stay Connected": function() {
                        self._trigger('stayConnected', null, { plugin: self });
                    }
                }
            });
        },
        _destroy: function() {
            // remove generated elements
            this.modal.remove();

        },
        _dialogTimer: function(action, time ){
            switch(action) {
                case 'start':
                    this.dialogTimer = setTimeout($.proxy(this._dialogHandler, this), time);
                    break;
                case 'stop':
                    clearTimeout(this.dialogTimer);
                    break;
                case 'restart':
                    this._dialogTimer('stop');
                    this._dialogTimer('start', time);
                    break;
            }
        },
        _redirectTimer: function(action, time ){
            switch(action) {
                case 'start':
                    this.redirectTimer = setTimeout($.proxy(this._redirectHandler, this), time);
                    break;
                case 'stop':
                    clearTimeout(this.redirectTimer);
                    break;
                case 'restart':
                    this._redirectTimer('stop');
                    this._redirectTimer('start', time);
                    break;
            }
        },
        _dialogHandler: function(){
            if(this.options.checkTimeBeforePopup){
                 this._trigger('getSessionTimeLeft', null, {plugin: this, updateSession: false, callback: function(time){
                    if (time <= 60000){
                        this.modal.dialog('open');
                    } else {
                        this.initializeTimers(time);
                    }
                }});
            }else{
                this.modal.dialog('open');
            }
        },
        _redirectHandler: function(){
            if (this.options.checkTimeBeforeRedirect){
                this._trigger('getSessionTimeLeft', null, {plugin: this, updateSession: false, callback: function(time){
                    if (time <= 0){
                        this._trigger('redirectNow', null, {plugin: this});
                    } else {
                        this.initializeTimers(time);
                    }
                }});
            } else {
                this._trigger('redirectNow', null, {plugin: this});
            }
        },
        _setTimers: function (time){
            var action;

            action = this.dialogTimer === null ? 'start' : 'restart';
            this._dialogTimer( action, (time - this.options.warnWhenLeft));

            action = this.redirectTimer === null ? 'start' : 'restart';
            this._redirectTimer ( action, time);
        },
        initializeTimers: function (time){
            if ( time === false){
                // if no time variable was passed, get it from the server
                 this._trigger('getSessionTimeLeft', null, {plugin: this, updateSession: false, callback: this._setTimers});
            } else {
                // when time variable passed, set it
                this._setTimers(time);
            }
        }
    });
})(jQuery, window);
<|endoftext|>


<commit_before>/**
 * class-component.js v5.5.0
 * author: Yoshiya Hinosawa ( http://github.com/kt3k )
 * license: MIT
 */
'use strict';

var $ = jQuery;

var reSpaces = / +/;

var Actor = require('./lib/Actor');
var Coelement = require('./lib/Coelement');
var subclass = require('subclassjs');

var ClassComponentManager = require('./lib/ClassComponentManager');

require('./lib/fn.cc');

/**
 * The main namespace for class component module.
 */
var cc = {};

cc.__manager__ = new ClassComponentManager();

/**
 Registers a class component of the given name using the given defining function.

 See README.md for details.

 @param {String} className The class name
 @param {Function} definingFunction The class definition
 */
cc.register = function (name, definingFunction) {

    if (typeof name !== 'string') {

        throw new Error('`name` of a class component has to be a string');

    }

    if (typeof definingFunction !== 'function') {

        throw new Error('`definingFunction` of a class component has to be a function');

    }

    cc.__manager__.register(name, definingFunction);

    $(document).ready(function () {

        cc.__manager__.init(name);

    });

};

/**
 * Initialized the all class components of the given names and returns of the promise of all initialization.
 *
 * @param {String[]|String} arguments
 * @return {Object<HTMLElement[]>}
 */
cc.init = function (classNames, elem) {

    if (classNames == null) {

        cc.__manager__.initAll(elem);

        return;

    }

    if (typeof classNames === 'string') {

        classNames = classNames.split(reSpaces);

    }

    return classNames.map(function (className) {

        return cc.__manager__.init(className, elem);

    });

};

/**
 * Assign a class as the accompanying coelement of the class component
 *
 * @param {String} className
 * @param {Function} DefiningClass
 */
cc.assign = function (className, DefiningClass) {

    DefiningClass.coelementName = className;

    cc.register(className, function (elem) {

        var coelement = new DefiningClass(elem);

        elem.data('__coelement:' + DefiningClass.coelementName, coelement);

    });

};

/**
 * The decorator for class assignment.
 *
 * @example
 *   @Component('foo')
 *   class Foo extends Bar {
 *     ...
 *   }
 *
 * The above is the same as:
 *
 * @example
 *   class Foo extends Bar {
 *   }
 *
 *   $.cc.assign('foo', Foo)
 *
 * @param {String} className The class name
 * @return {Function}
 */
cc.Component = function (className) {

    // This is the actual decorator
    return function (Cls) {

        cc.assign(className, Cls)

    };

};

// Exports subclass.
cc.subclass = subclass;

// Exports Actor.
cc.Actor = Actor;

// Exports Actor.
cc.Coelement = Coelement;

// Exports the main namespace
$.cc = cc;

module.exports = cc;
<commit_msg>Rename decorator, manage double loading<commit_after>/**
 * class-component.js v5.5.0
 * author: Yoshiya Hinosawa ( http://github.com/kt3k )
 * license: MIT
 */
'use strict';

var $ = jQuery;

var reSpaces = / +/;

var Actor = require('./lib/Actor');
var Coelement = require('./lib/Coelement');
var subclass = require('subclassjs');

var ClassComponentManager = require('./lib/ClassComponentManager');

require('./lib/fn.cc');

/**
 * Creats the module object.
 *
 * @return {Object}
 */
var createModuleObject = function () {

    /**
     * The main namespace for class component module.
     */
    var cc = {};

    cc.__manager__ = new ClassComponentManager();

    /**
     Registers a class component of the given name using the given defining function.

     See README.md for details.

     @param {String} className The class name
     @param {Function} definingFunction The class definition
     */
    cc.register = function (name, definingFunction) {

        if (typeof name !== 'string') {

            throw new Error('`name` of a class component has to be a string');

        }

        if (typeof definingFunction !== 'function') {

            throw new Error('`definingFunction` of a class component has to be a function');

        }

        cc.__manager__.register(name, definingFunction);

        $(document).ready(function () {

            cc.__manager__.init(name);

        });

    };

    /**
     * Initialized the all class components of the given names and returns of the promise of all initialization.
     *
     * @param {String[]|String} arguments
     * @return {Object<HTMLElement[]>}
     */
    cc.init = function (classNames, elem) {

        if (classNames == null) {

            cc.__manager__.initAll(elem);

            return;

        }

        if (typeof classNames === 'string') {

            classNames = classNames.split(reSpaces);

        }

        return classNames.map(function (className) {

            return cc.__manager__.init(className, elem);

        });

    };

    /**
     * Assign a class as the accompanying coelement of the class component
     *
     * @param {String} className
     * @param {Function} DefiningClass
     */
    cc.assign = function (className, DefiningClass) {

        DefiningClass.coelementName = className;

        cc.register(className, function (elem) {

            var coelement = new DefiningClass(elem);

            elem.data('__coelement:' + DefiningClass.coelementName, coelement);

        });

    };

    /**
     * The decorator for class assignment.
     *
     * @example
     *   @$.cc.component('foo')
     *   class Foo extends Bar {
     *     ...
     *   }
     *
     * The above is the same as:
     *
     * @example
     *   class Foo extends Bar {
     *   }
     *
     *   $.cc.assign('foo', Foo)
     *
     * @param {String} className The class name
     * @return {Function}
     */
    cc.component = function (className) {

        // This is the actual decorator
        return function (Cls) {

            cc.assign(className, Cls)

        };

    };

    // Exports subclass.
    cc.subclass = subclass;

    // Exports Actor.
    cc.Actor = Actor;

    // Exports Actor.
    cc.Coelement = Coelement;

    return cc;

};

// If the cc is not set, then create one.
if ($.cc == null) {

    $.cc = createModuleObject()

}

module.exports = $.cc;
<|endoftext|>