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

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

/**
 * Webpack Plugins
 */
var CopyWebpackPlugin = require('copy-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;

/**
 * Webpack Constants
 */
const METADATA = {
  title: 'Angular2 Webpack Starter by @gdi2990 from @AngularClass',
  baseUrl: '/'
};

/**
 * 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.ts',
    'vendor': './src/vendor.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'],

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

    // 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/@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$/,
        loader: 'awesome-typescript-loader',
        exclude: [/\.(spec|e2e)\.ts$/]
      },

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

      // Raw loader support for *.css files
      // Returns file content as string
      //
      // See: https://github.com/webpack/raw-loader
      {
        test: /\.css$/,
        loader: 'raw-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: helpers.reverse(['polyfills', 'vendor', 'main']),
      minChunks: Infinity
    }),

    // 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: 'none'
    })

  ],

  // Include polyfills or mocks for various node stuff
  // Description: Node configuration
  //
  // See: https://webpack.github.io/docs/configuration.html#node
  node: {
    global: 'window',
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false
  },
};
<commit_msg>fix(webpack.common): correct package sort<commit_after>/**
 * @author: @AngularClass
 */

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

/**
 * Webpack Plugins
 */
var CopyWebpackPlugin = require('copy-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;

/**
 * Webpack Constants
 */
const METADATA = {
  title: 'Angular2 Webpack Starter by @gdi2990 from @AngularClass',
  baseUrl: '/'
};

/**
 * 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.ts',
    'vendor': './src/vendor.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'],

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

    // 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/@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$/,
        loader: 'awesome-typescript-loader',
        exclude: [/\.(spec|e2e)\.ts$/]
      },

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

      // Raw loader support for *.css files
      // Returns file content as string
      //
      // See: https://github.com/webpack/raw-loader
      {
        test: /\.css$/,
        loader: 'raw-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: helpers.reverse(['polyfills', 'vendor', 'main']),
      minChunks: Infinity
    }),

    // 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: helpers.packageSort(['polyfills', 'vendor', 'main'])
    })

  ],

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


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var webpack = require('webpack');
var StatsPlugin = require('stats-webpack-plugin');
var CompressionPlugin = require('compression-webpack-plugin');
var NameAllModulesPlugin = require('name-all-modules-plugin');
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
var WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');

var ROOT_PATH = path.resolve(__dirname, '..');
var IS_PRODUCTION = process.env.NODE_ENV === 'production';
var IS_DEV_SERVER = process.argv[1].indexOf('webpack-dev-server') !== -1;
var DEV_SERVER_HOST = process.env.DEV_SERVER_HOST || 'localhost';
var DEV_SERVER_PORT = parseInt(process.env.DEV_SERVER_PORT, 10) || 3808;
var DEV_SERVER_LIVERELOAD = process.env.DEV_SERVER_LIVERELOAD !== 'false';
var WEBPACK_REPORT = process.env.WEBPACK_REPORT;

var config = {
  // because sqljs requires fs.
  node: {
    fs: "empty"
  },
  context: path.join(ROOT_PATH, 'app/assets/javascripts'),
  entry: {
    balsamiq_viewer:      './blob/balsamiq_viewer.js',
    blob:                 './blob_edit/blob_bundle.js',
    boards:               './boards/boards_bundle.js',
    common:               './commons/index.js',
    common_vue:           ['vue', './vue_shared/common_vue.js'],
    common_d3:            ['d3'],
    cycle_analytics:      './cycle_analytics/cycle_analytics_bundle.js',
    commit_pipelines:     './commit/pipelines/pipelines_bundle.js',
    deploy_keys:          './deploy_keys/index.js',
    diff_notes:           './diff_notes/diff_notes_bundle.js',
    environments:         './environments/environments_bundle.js',
    environments_folder:  './environments/folder/environments_folder_bundle.js',
    filtered_search:      './filtered_search/filtered_search_bundle.js',
    graphs:               './graphs/graphs_bundle.js',
    group:                './group.js',
    groups_list:          './groups_list.js',
    issue_show:           './issue_show/index.js',
    locale:               './locale/index.js',
    main:                 './main.js',
    merge_conflicts:      './merge_conflicts/merge_conflicts_bundle.js',
    monitoring:           './monitoring/monitoring_bundle.js',
    network:              './network/network_bundle.js',
    notebook_viewer:      './blob/notebook_viewer.js',
    pdf_viewer:           './blob/pdf_viewer.js',
    pipelines:            './pipelines/index.js',
    pipelines_details:     './pipelines/pipeline_details_bundle.js',
    profile:              './profile/profile_bundle.js',
    protected_branches:   './protected_branches/protected_branches_bundle.js',
    protected_tags:       './protected_tags',
    sidebar:              './sidebar/sidebar_bundle.js',
    schedule_form:        './pipeline_schedules/pipeline_schedule_form_bundle.js',
    schedules_index:      './pipeline_schedules/pipeline_schedules_index_bundle.js',
    snippet:              './snippet/snippet_bundle.js',
    sketch_viewer:        './blob/sketch_viewer.js',
    stl_viewer:           './blob/stl_viewer.js',
    terminal:             './terminal/terminal_bundle.js',
    u2f:                  ['vendor/u2f'],
    users:                './users/users_bundle.js',
    raven:                './raven/index.js',
    vue_merge_request_widget: './vue_merge_request_widget/index.js',
    test:                 './test.js',
  },

  output: {
    path: path.join(ROOT_PATH, 'public/assets/webpack'),
    publicPath: '/assets/webpack/',
    filename: IS_PRODUCTION ? '[name].[chunkhash].bundle.js' : '[name].bundle.js',
    chunkFilename: IS_PRODUCTION ? '[name].[chunkhash].chunk.js' : '[name].chunk.js',
  },

  devtool: 'cheap-module-source-map',

  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|vendor\/assets)/,
        loader: 'babel-loader',
      },
      {
        test: /\.vue$/,
        loader: 'vue-loader',
      },
      {
        test: /\.svg$/,
        loader: 'raw-loader',
      },
      {
        test: /\.(gif|png)$/,
        loader: 'url-loader',
        options: { limit: 2048 },
      },
      {
        test: /\.(worker\.js|pdf|bmpr)$/,
        exclude: /node_modules/,
        loader: 'file-loader',
      },
      {
        test: /locale\/\w+\/(.*)\.js$/,
        loader: 'exports-loader?locales',
      },
    ]
  },

  plugins: [
    // manifest filename must match config.webpack.manifest_filename
    // webpack-rails only needs assetsByChunkName to function properly
    new StatsPlugin('manifest.json', {
      chunkModules: false,
      source: false,
      chunks: false,
      modules: false,
      assets: true
    }),

    // prevent pikaday from including moment.js
    new webpack.IgnorePlugin(/moment/, /pikaday/),

    // fix legacy jQuery plugins which depend on globals
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
    }),

    // assign deterministic module ids
    new webpack.NamedModulesPlugin(),
    new NameAllModulesPlugin(),

    // assign deterministic chunk ids
    new webpack.NamedChunksPlugin((chunk) => {
      if (chunk.name) {
        return chunk.name;
      }
      return chunk.modules.map((m) => {
        var chunkPath = m.request.split('!').pop();
        return path.relative(m.context, chunkPath);
      }).join('_');
    }),

    // create cacheable common library bundle for all vue chunks
    new webpack.optimize.CommonsChunkPlugin({
      name: 'common_vue',
      chunks: [
        'boards',
        'commit_pipelines',
        'cycle_analytics',
        'deploy_keys',
        'diff_notes',
        'environments',
        'environments_folder',
        'filtered_search',
        'issue_show',
        'merge_conflicts',
        'notebook_viewer',
        'pdf_viewer',
        'pipelines',
        'pipelines_details',
        'schedule_form',
        'schedules_index',
        'sidebar',
        'vue_merge_request_widget',
      ],
      minChunks: function(module, count) {
        return module.resource && (/vue_shared/).test(module.resource);
      },
    }),

    // create cacheable common library bundle for all d3 chunks
    new webpack.optimize.CommonsChunkPlugin({
      name: 'common_d3',
      chunks: [
        'graphs',
        'users',
        'monitoring',
      ],
    }),

    // create cacheable common library bundles
    new webpack.optimize.CommonsChunkPlugin({
      names: ['main', 'common', 'runtime'],
    }),

    // locale common library
    new webpack.optimize.CommonsChunkPlugin({
      name: 'locale',
      chunks: [
        'cycle_analytics',
      ],
    }),
  ],

  resolve: {
    extensions: ['.js'],
    alias: {
      '~':              path.join(ROOT_PATH, 'app/assets/javascripts'),
      'emojis':         path.join(ROOT_PATH, 'fixtures/emojis'),
      'empty_states':   path.join(ROOT_PATH, 'app/views/shared/empty_states'),
      'icons':          path.join(ROOT_PATH, 'app/views/shared/icons'),
      'images':         path.join(ROOT_PATH, 'app/assets/images'),
      'vendor':         path.join(ROOT_PATH, 'vendor/assets/javascripts'),
      'vue$':           'vue/dist/vue.esm.js',
    }
  }
}

if (IS_PRODUCTION) {
  config.devtool = 'source-map';
  config.plugins.push(
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true
    }),
    new webpack.DefinePlugin({
      'process.env': { NODE_ENV: JSON.stringify('production') }
    }),
    new CompressionPlugin({
      asset: '[path].gz[query]',
    })
  );
}

if (IS_DEV_SERVER) {
  config.devtool = 'cheap-module-eval-source-map';
  config.devServer = {
    host: DEV_SERVER_HOST,
    port: DEV_SERVER_PORT,
    headers: { 'Access-Control-Allow-Origin': '*' },
    stats: 'errors-only',
    inline: DEV_SERVER_LIVERELOAD
  };
  config.output.publicPath = '//' + DEV_SERVER_HOST + ':' + DEV_SERVER_PORT + config.output.publicPath;
  config.plugins.push(
    // watch node_modules for changes if we encounter a missing module compile error
    new WatchMissingNodeModulesPlugin(path.join(ROOT_PATH, 'node_modules'))
  );
}

if (WEBPACK_REPORT) {
  config.plugins.push(
    new BundleAnalyzerPlugin({
      analyzerMode: 'static',
      generateStatsFile: true,
      openAnalyzer: false,
      reportFilename: path.join(ROOT_PATH, 'webpack-report/index.html'),
      statsFilename: path.join(ROOT_PATH, 'webpack-report/stats.json'),
    })
  );
}

module.exports = config;
<commit_msg>Add Prometheus Metrics Bundle<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var webpack = require('webpack');
var StatsPlugin = require('stats-webpack-plugin');
var CompressionPlugin = require('compression-webpack-plugin');
var NameAllModulesPlugin = require('name-all-modules-plugin');
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
var WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');

var ROOT_PATH = path.resolve(__dirname, '..');
var IS_PRODUCTION = process.env.NODE_ENV === 'production';
var IS_DEV_SERVER = process.argv[1].indexOf('webpack-dev-server') !== -1;
var DEV_SERVER_HOST = process.env.DEV_SERVER_HOST || 'localhost';
var DEV_SERVER_PORT = parseInt(process.env.DEV_SERVER_PORT, 10) || 3808;
var DEV_SERVER_LIVERELOAD = process.env.DEV_SERVER_LIVERELOAD !== 'false';
var WEBPACK_REPORT = process.env.WEBPACK_REPORT;

var config = {
  // because sqljs requires fs.
  node: {
    fs: "empty"
  },
  context: path.join(ROOT_PATH, 'app/assets/javascripts'),
  entry: {
    balsamiq_viewer:      './blob/balsamiq_viewer.js',
    blob:                 './blob_edit/blob_bundle.js',
    boards:               './boards/boards_bundle.js',
    common:               './commons/index.js',
    common_vue:           ['vue', './vue_shared/common_vue.js'],
    common_d3:            ['d3'],
    cycle_analytics:      './cycle_analytics/cycle_analytics_bundle.js',
    commit_pipelines:     './commit/pipelines/pipelines_bundle.js',
    deploy_keys:          './deploy_keys/index.js',
    diff_notes:           './diff_notes/diff_notes_bundle.js',
    environments:         './environments/environments_bundle.js',
    environments_folder:  './environments/folder/environments_folder_bundle.js',
    filtered_search:      './filtered_search/filtered_search_bundle.js',
    graphs:               './graphs/graphs_bundle.js',
    group:                './group.js',
    groups_list:          './groups_list.js',
    issue_show:           './issue_show/index.js',
    locale:               './locale/index.js',
    main:                 './main.js',
    merge_conflicts:      './merge_conflicts/merge_conflicts_bundle.js',
    monitoring:           './monitoring/monitoring_bundle.js',
    network:              './network/network_bundle.js',
    notebook_viewer:      './blob/notebook_viewer.js',
    pdf_viewer:           './blob/pdf_viewer.js',
    pipelines:            './pipelines/index.js',
    pipelines_details:     './pipelines/pipeline_details_bundle.js',
    profile:              './profile/profile_bundle.js',
    prometheus_metrics:   './prometheus_metrics',
    protected_branches:   './protected_branches/protected_branches_bundle.js',
    protected_tags:       './protected_tags',
    sidebar:              './sidebar/sidebar_bundle.js',
    schedule_form:        './pipeline_schedules/pipeline_schedule_form_bundle.js',
    schedules_index:      './pipeline_schedules/pipeline_schedules_index_bundle.js',
    snippet:              './snippet/snippet_bundle.js',
    sketch_viewer:        './blob/sketch_viewer.js',
    stl_viewer:           './blob/stl_viewer.js',
    terminal:             './terminal/terminal_bundle.js',
    u2f:                  ['vendor/u2f'],
    users:                './users/users_bundle.js',
    raven:                './raven/index.js',
    vue_merge_request_widget: './vue_merge_request_widget/index.js',
    test:                 './test.js',
  },

  output: {
    path: path.join(ROOT_PATH, 'public/assets/webpack'),
    publicPath: '/assets/webpack/',
    filename: IS_PRODUCTION ? '[name].[chunkhash].bundle.js' : '[name].bundle.js',
    chunkFilename: IS_PRODUCTION ? '[name].[chunkhash].chunk.js' : '[name].chunk.js',
  },

  devtool: 'cheap-module-source-map',

  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|vendor\/assets)/,
        loader: 'babel-loader',
      },
      {
        test: /\.vue$/,
        loader: 'vue-loader',
      },
      {
        test: /\.svg$/,
        loader: 'raw-loader',
      },
      {
        test: /\.(gif|png)$/,
        loader: 'url-loader',
        options: { limit: 2048 },
      },
      {
        test: /\.(worker\.js|pdf|bmpr)$/,
        exclude: /node_modules/,
        loader: 'file-loader',
      },
      {
        test: /locale\/\w+\/(.*)\.js$/,
        loader: 'exports-loader?locales',
      },
    ]
  },

  plugins: [
    // manifest filename must match config.webpack.manifest_filename
    // webpack-rails only needs assetsByChunkName to function properly
    new StatsPlugin('manifest.json', {
      chunkModules: false,
      source: false,
      chunks: false,
      modules: false,
      assets: true
    }),

    // prevent pikaday from including moment.js
    new webpack.IgnorePlugin(/moment/, /pikaday/),

    // fix legacy jQuery plugins which depend on globals
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
    }),

    // assign deterministic module ids
    new webpack.NamedModulesPlugin(),
    new NameAllModulesPlugin(),

    // assign deterministic chunk ids
    new webpack.NamedChunksPlugin((chunk) => {
      if (chunk.name) {
        return chunk.name;
      }
      return chunk.modules.map((m) => {
        var chunkPath = m.request.split('!').pop();
        return path.relative(m.context, chunkPath);
      }).join('_');
    }),

    // create cacheable common library bundle for all vue chunks
    new webpack.optimize.CommonsChunkPlugin({
      name: 'common_vue',
      chunks: [
        'boards',
        'commit_pipelines',
        'cycle_analytics',
        'deploy_keys',
        'diff_notes',
        'environments',
        'environments_folder',
        'filtered_search',
        'issue_show',
        'merge_conflicts',
        'notebook_viewer',
        'pdf_viewer',
        'pipelines',
        'pipelines_details',
        'schedule_form',
        'schedules_index',
        'sidebar',
        'vue_merge_request_widget',
      ],
      minChunks: function(module, count) {
        return module.resource && (/vue_shared/).test(module.resource);
      },
    }),

    // create cacheable common library bundle for all d3 chunks
    new webpack.optimize.CommonsChunkPlugin({
      name: 'common_d3',
      chunks: [
        'graphs',
        'users',
        'monitoring',
      ],
    }),

    // create cacheable common library bundles
    new webpack.optimize.CommonsChunkPlugin({
      names: ['main', 'common', 'runtime'],
    }),

    // locale common library
    new webpack.optimize.CommonsChunkPlugin({
      name: 'locale',
      chunks: [
        'cycle_analytics',
      ],
    }),
  ],

  resolve: {
    extensions: ['.js'],
    alias: {
      '~':              path.join(ROOT_PATH, 'app/assets/javascripts'),
      'emojis':         path.join(ROOT_PATH, 'fixtures/emojis'),
      'empty_states':   path.join(ROOT_PATH, 'app/views/shared/empty_states'),
      'icons':          path.join(ROOT_PATH, 'app/views/shared/icons'),
      'images':         path.join(ROOT_PATH, 'app/assets/images'),
      'vendor':         path.join(ROOT_PATH, 'vendor/assets/javascripts'),
      'vue$':           'vue/dist/vue.esm.js',
    }
  }
}

if (IS_PRODUCTION) {
  config.devtool = 'source-map';
  config.plugins.push(
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true
    }),
    new webpack.DefinePlugin({
      'process.env': { NODE_ENV: JSON.stringify('production') }
    }),
    new CompressionPlugin({
      asset: '[path].gz[query]',
    })
  );
}

if (IS_DEV_SERVER) {
  config.devtool = 'cheap-module-eval-source-map';
  config.devServer = {
    host: DEV_SERVER_HOST,
    port: DEV_SERVER_PORT,
    headers: { 'Access-Control-Allow-Origin': '*' },
    stats: 'errors-only',
    inline: DEV_SERVER_LIVERELOAD
  };
  config.output.publicPath = '//' + DEV_SERVER_HOST + ':' + DEV_SERVER_PORT + config.output.publicPath;
  config.plugins.push(
    // watch node_modules for changes if we encounter a missing module compile error
    new WatchMissingNodeModulesPlugin(path.join(ROOT_PATH, 'node_modules'))
  );
}

if (WEBPACK_REPORT) {
  config.plugins.push(
    new BundleAnalyzerPlugin({
      analyzerMode: 'static',
      generateStatsFile: true,
      openAnalyzer: false,
      reportFilename: path.join(ROOT_PATH, 'webpack-report/index.html'),
      statsFilename: path.join(ROOT_PATH, 'webpack-report/stats.json'),
    })
  );
}

module.exports = config;
<|endoftext|>


<commit_before>  // globals: soundManager, key, window
  function Beatbar() {
    // Private variables
    var self = this,
        sm = soundManager,
        cursorLocation = 0, // current location of pointer in the bar
        lastPageX = 0,
        playerState,
        PLAYING = 0,
        STOPPED = 1,
        PAUSED = 2,
        lastUpdatedAt = 0,
        location = window.location,
        isWindowInFocus = true, // tracks the focus of player window
        progressString = '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~',
        progressStringLength = progressString.length,
        loadingString = progressString.replace(/~/gi,'='),
        playControl = {
          0: '~||~', // playing
          1: '~(>~', // paused
          2: '~(>~'  // stopped
        },
        previousControl = '~~|<)~',
        nextControl = '~(>|~~',
        separator = '|',
        playerStringLength = progressStringLength +
          playControl[0].length +
          previousControl.length +
          nextControl.length +
          separator.length,
        screenWidth = $(document).width(),
        delta = Math.floor(screenWidth/(playerStringLength*2)),
        vu = '~~~~~~~~~~',
        dummyPlayerString = previousControl +
          playControl[0] +
          nextControl +
          separator +
          progressString;

    // Configuration options
    // Default config object is defined here
    // This can be overridden by User
    this.config = {
      usePeakData: true,
      cursorChar: 'O', // caracter for representing mouse position in beatbar
      progressChar: 'o', // character for showing progress of the current song
      playlist: []
    };

    // Contains the current sound object
    this.sound = {};

    // Contains all created sound objects
    this.playlist = {};

    // Bind events on document click, mousemove and other keyboard shortcuts
    this.bindEvents = function() {
      $(document).ready(function() {
        $(document).click(self.clickHandler);
        $(document).bind('mousemove',self.mouseMoveHandler);
        $(window).resize(self.windowResizeHandler);
        // Don't render player if the window is not in focus
        $(window).focus(function() {
            isWindowInFocus = true;
          }).blur(function() {
            isWindowInFocus = false;
          });
        // Keybindings
        key('n, j', function(){
          self.playNext();
        });
        key('p, k', function(){
          self.playPrevious();
        });
        key('space', function(){
          self.togglePlay();
        });
        key('right', function(){
          self.seekForward();
        });
        key('left', function(){
          self.seekBackward();
        });
        key('home 0', function(){
          self.seekToBeginning();
        });
        key('up', function(){
          self.increaseVolume();
        });
        key('down', function(){
          self.decreaseVolume();
        });
      });
    };

    // Click event handler
    // Get the x coordinate of the click from event object
    // translate it into URL string index
    // according to the value of index
    // perform different functions
    this.clickHandler = function(e) {
      var location = self.translatePointerLocation(e);
      if (location > 2 && location < 5){
        self.playPrevious();
      } else if (location > 6 && location < 9){
        self.togglePlay();
      } else if (location > 10 && location < 14){
        self.playNext();
      } else if (location > 16) {
        self.seekTo(location);
      }
    };

    // Set screenWidth and delta when the window is resized
    this.windowResizeHandler = function(e) {
      screenWidth = $(document).width();
      delta = Math.floor(screenWidth/(playerStringLength*2));
      sm._writeDebug('Screen resized. New values:');
      sm._writeDebug('screenWidth: ' + screenWidth);
      sm._writeDebug('delta: '+ delta);
    };

    // Toggle play and pause for the current sound object
    this.togglePlay = function() {
      switch (playerState){
        case PLAYING:
          self.sound.pause();
          break;
        case PAUSED:
          self.sound.resume();
          break;
        case STOPPED:
          self.sound.play();
          break;
        default:
          // throw exception
          sm._writeDebug('Something bad happened');
      }
    };

    // Handler for progress section
    //   Translates the location into time in milliseconds
    //   then sets the position of current sound object to
    //   translated time
    // Parameters:
    //   location (Integer) - index of character in the URL bar
    //
    this.seekTo = function(location) {
      // @todo due to integer division, the location is not calculated correctly
      self.sound.setPosition(((location - 16.1)/progressStringLength)*self.sound.durationEstimate);
    };

    // Seeks the current sound object forward by specified time
    // Parameters:
    //   seekBy (Integer) - time in milliseconds by which the sound should
    //     be seeked forward. Default 5000
    this.seekForward = function(seekBy){
      seekBy = seekBy || 5000;
      self.sound.setPosition(self.sound.position + seekBy);
    };

    // Seeks the current sound object forward by specified time
    // Parameters:
    //   seekBy (Integer) - time in milliseconds by which the sound should
    //   be seeked backward. Default 5000
    this.seekBackward = function(seekBy){
      seekBy = seekBy || 5000;
      self.sound.setPosition(self.sound.position - seekBy);
    };

    // Seeks the position of current sound object to beginning of the sound
    this.seekToBeginning = function(){
      self.sound.setPosition(0);
    };

    // Increase the volume of current sound object by the specified amount
    //   on a scale of 0-100
    // Parameters:
    //   increaseBy (Integer) - volume to be increased by specified percentage
    this.increaseVolume = function(increaseBy){
      increaseBy = increaseBy || 10;
      if (self.sound.volume <= 100 - increaseBy){
        self.sound.setVolume(self.sound.volume + increaseBy);
      }
    };

    // Decrease the volume of current sound object by the specified amount
    //   on a scale of 0-100
    // Parameters:
    //   decreaseBy (Integer) - volume to be decreased by specified percentage
    this.decreaseVolume = function(decreaseBy){
      decreaseBy = decreaseBy || 10;
      if (self.sound.volume >= decreaseBy){
        self.sound.setVolume(self.sound.volume - decreaseBy);
      }
    };

    // handlers for sound events
    // @todo refactor to use playState of soundObject
    // @todo id3 data show
    this.events = {
      play: function(e) {
        playerState = PLAYING;
        self.renderPlayer();
      },
      stop: function(e) {
        playerState = STOPPED;
        self.renderPlayer();
      },
      pause: function(e) {
        playerState = PAUSED;
        self.renderPlayer();
      },
      resume: function(e) {
        playerState = PLAYING;
        self.renderPlayer();
      },
      finish: function(e) {
        self.playNext();
        self.renderPlayer();
      },
      // @todo throttle settings
      whileloading: function(e) {
        self.renderPlayer();
      },
      onload: function(e) {
        if (self.sound.readyState == 2) {
          //failed to load
          self.renderPlayer();
        }
      },
      whileplaying: function(e) {
        //throttle for whileplaying calls
        var d = new Date();
        if (d - lastUpdatedAt > 50){
          lastUpdatedAt = d;
          self.renderPlayer();
        }
      },
      id3: function(){
      }
    };

    // Handle mouse move event
    this.mouseMoveHandler = function(e) {
      // Dont excessively call renderPlayer on mousemove event
      // lastPageX - cached mouse pointer position on last move and render
      if (e.pageX > lastPageX + delta || e.pageX < lastPageX - delta) {
        lastPageX = e.pageX;
        // change cursor location
        cursorLocation = self.translatePointerLocation(e);
        self.renderPlayer();
      }
    };

    // Main method responsible for rendering the player in address bar
    this.renderPlayer = function() {
      if (!isWindowInFocus) {
        return;
      }
      var controlString = self.renderControlString(),
        errorMessage = 'Failed to load the sound. Security / 404 / Bad format',
        playerString;
      // show error if there is a failure
      if (self.sound.readyState == 2){
        playerString = controlString + separator + '[' +
          errorMessage + ']';
      } else {
        var progress = self.renderProgressString(),
          timeString = self.renderTimeString();
        // dont write vuString if usePeakData not supported
        if (self.config.usePeakData) {
          vuString = vu.slice(0, Math.floor(self.sound.peakData.left * 10));
        } else {
          vuString = '';
        }
        playerString = controlString + separator + progress + separator +
          timeString + separator + vuString;
      }
      location.replace('#' + playerString.substr(0, cursorLocation) +
        self.config.cursorChar +
        playerString.substr(cursorLocation + self.config.cursorChar.length));
    };

    // Returns controls string
    this.renderControlString = function() {
      return previousControl + playControl[playerState] + nextControl;
    };

    // Returns progress string
    // @todo rework the logic below
    this.renderProgressString = function() {
      var location = Math.floor((self.sound.position/self.sound.durationEstimate)*progressStringLength),
        loaded = Math.floor((self.sound.bytesLoaded/self.sound.bytesTotal)*progressStringLength),
        string = loadingString.substr(0,loaded) + progressString.substr(loaded);
      return string.substr(0, location) +
        self.config.progressChar +
        string.substr(location + self.config.progressChar.length);
    };

    // Returns the remaining time string
    // @todo cache time for one second
    this.renderTimeString = function() {
      var timeLeft = self.sound.durationEstimate - self.sound.position;
      return '[-' + self.getTime(timeLeft) + ']';
    };

    // Translates mouse pointer location into player string cursor
    this.translatePointerLocation = function(e) {
      return Math.floor((e.pageX/screenWidth)*playerStringLength);
    };

    // create soudnManager sound object
    //   and returns it
    // @todo refactor to use getSoundById() here
    this.createSound = function(id, url) {
      var thisSound;
      // if id exist in self.playlist, return the corresponding sound object
      // already created
      if (self.playlist[id]){
        thisSound = self.playlist[id];
      } else {
        // create sound
        thisSound = sm.createSound({
          id:'awesome'+id,
          url:url,
          onplay:self.events.play,
          onstop:self.events.stop,
          onpause:self.events.pause,
          onresume:self.events.resume,
          onfinish:self.events.finish,
          whileloading:self.events.whileloading,
          whileplaying:self.events.whileplaying,
          onid3:self.events.id3,
          onload:self.events.onload,
          autoPlay: false
        });
        self.playlist[id] = thisSound;
      }
      return thisSound;
    };

    // Play the next sound object in the playlist and return it
    this.playNext = function(){
      var next;
      if (self.playlist.currentlyPlaying + 1 >= self.config.playlist.length){
        next = 0;
      } else {
        next = self.playlist.currentlyPlaying + 1;
      }
      return self.playById(next);
    };

    // Play the previous sound object in the playlist and return it
    this.playPrevious = function(){
      // get previous
      var previous;
      if (self.playlist.currentlyPlaying - 1 < 0){
        previous = self.config.playlist.length - 1;
      } else {
        previous = self.playlist.currentlyPlaying - 1;
      }
      return self.playById(previous);
    };

    // Play the sound object with id as id
    // Parameters:
    //   id (Integer) - playlist id of the sound object to be played
    this.playById = function(id){
      if (self.sound.sID) {
        self.sound.stop();
        self.sound.unload();
      }
      if (self.config.playlist[id]) {
        self.playlist.currentlyPlaying = id;
        self.sound = self.createSound(id, self.config.playlist[id]);
        self.sound.play();
        return self.sound;
      }
    };

    // converts milliseconds into human readable form
    // @todo variable names
    this.getTime = function(milliseconds){
      var seconds = Math.floor(milliseconds/1000),
          minutes = Math.floor(seconds/60);
      seconds = seconds - (minutes*60);
      return minutes + ':' + (seconds < 10 ? '0' + seconds : seconds);
    };

    // Initialize the player
    this.init = function (config) {
      var sound;
      if (config) {
        $.extend(this.config, config);
      }

      // Check if flash version is greate than 9
      // if yes, then set sm.defaultOptions.usePeakData to true

      if (sm.flashVersion >= 9) {
        sm.defaultOptions.usePeakData = this.config.usePeakData;
      }

      self.playById(0);
      self.bindEvents();
    };

  }<commit_msg>prevent default on keypress events<commit_after>  // globals: soundManager, key, window
  function Beatbar() {
    // Private variables
    var self = this,
        sm = soundManager,
        cursorLocation = 0, // current location of pointer in the bar
        lastPageX = 0,
        playerState,
        PLAYING = 0,
        STOPPED = 1,
        PAUSED = 2,
        lastUpdatedAt = 0,
        location = window.location,
        isWindowInFocus = true, // tracks the focus of player window
        progressString = '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~',
        progressStringLength = progressString.length,
        loadingString = progressString.replace(/~/gi,'='),
        playControl = {
          0: '~||~', // playing
          1: '~(>~', // paused
          2: '~(>~'  // stopped
        },
        previousControl = '~~|<)~',
        nextControl = '~(>|~~',
        separator = '|',
        playerStringLength = progressStringLength +
          playControl[0].length +
          previousControl.length +
          nextControl.length +
          separator.length,
        screenWidth = $(document).width(),
        delta = Math.floor(screenWidth/(playerStringLength*2)),
        vu = '~~~~~~~~~~',
        dummyPlayerString = previousControl +
          playControl[0] +
          nextControl +
          separator +
          progressString;

    // Configuration options
    // Default config object is defined here
    // This can be overridden by User
    this.config = {
      usePeakData: true,
      cursorChar: 'O', // caracter for representing mouse position in beatbar
      progressChar: 'o', // character for showing progress of the current song
      playlist: []
    };

    // Contains the current sound object
    this.sound = {};

    // Contains all created sound objects
    this.playlist = {};

    // Bind events on document click, mousemove and other keyboard shortcuts
    this.bindEvents = function() {
      $(document).ready(function() {
        $(document).click(self.clickHandler);
        $(document).bind('mousemove',self.mouseMoveHandler);
        $(window).resize(self.windowResizeHandler);
        // Don't render player if the window is not in focus
        $(window).focus(function() {
            isWindowInFocus = true;
          }).blur(function() {
            isWindowInFocus = false;
          });
        // Keybindings
        key('n, j', function(){
          self.playNext();
        });
        key('p, k', function(){
          self.playPrevious();
        });
        key('space', function(e){
          e.preventDefault();
          self.togglePlay();
        });
        key('right', function(){
          self.seekForward();
        });
        key('left', function(){
          self.seekBackward();
        });
        key('home 0', function(){
          self.seekToBeginning();
        });
        key('up', function(e){
          e.preventDefault();
          self.increaseVolume();
        });
        key('down', function(e){
          e.preventDefault();
          self.decreaseVolume();
        });
      });
    };

    // Click event handler
    // Get the x coordinate of the click from event object
    // translate it into URL string index
    // according to the value of index
    // perform different functions
    this.clickHandler = function(e) {
      var location = self.translatePointerLocation(e);
      if (location > 2 && location < 5){
        self.playPrevious();
      } else if (location > 6 && location < 9){
        self.togglePlay();
      } else if (location > 10 && location < 14){
        self.playNext();
      } else if (location > 16) {
        self.seekTo(location);
      }
    };

    // Set screenWidth and delta when the window is resized
    this.windowResizeHandler = function(e) {
      screenWidth = $(document).width();
      delta = Math.floor(screenWidth/(playerStringLength*2));
      sm._writeDebug('Screen resized. New values:');
      sm._writeDebug('screenWidth: ' + screenWidth);
      sm._writeDebug('delta: '+ delta);
    };

    // Toggle play and pause for the current sound object
    this.togglePlay = function() {
      switch (playerState){
        case PLAYING:
          self.sound.pause();
          break;
        case PAUSED:
          self.sound.resume();
          break;
        case STOPPED:
          self.sound.play();
          break;
        default:
          // throw exception
          sm._writeDebug('Something bad happened');
      }
    };

    // Handler for progress section
    //   Translates the location into time in milliseconds
    //   then sets the position of current sound object to
    //   translated time
    // Parameters:
    //   location (Integer) - index of character in the URL bar
    //
    this.seekTo = function(location) {
      // @todo due to integer division, the location is not calculated correctly
      self.sound.setPosition(((location - 16.1)/progressStringLength)*self.sound.durationEstimate);
    };

    // Seeks the current sound object forward by specified time
    // Parameters:
    //   seekBy (Integer) - time in milliseconds by which the sound should
    //     be seeked forward. Default 5000
    this.seekForward = function(seekBy){
      seekBy = seekBy || 5000;
      self.sound.setPosition(self.sound.position + seekBy);
    };

    // Seeks the current sound object forward by specified time
    // Parameters:
    //   seekBy (Integer) - time in milliseconds by which the sound should
    //   be seeked backward. Default 5000
    this.seekBackward = function(seekBy){
      seekBy = seekBy || 5000;
      self.sound.setPosition(self.sound.position - seekBy);
    };

    // Seeks the position of current sound object to beginning of the sound
    this.seekToBeginning = function(){
      self.sound.setPosition(0);
    };

    // Increase the volume of current sound object by the specified amount
    //   on a scale of 0-100
    // Parameters:
    //   increaseBy (Integer) - volume to be increased by specified percentage
    this.increaseVolume = function(increaseBy){
      increaseBy = increaseBy || 10;
      if (self.sound.volume <= 100 - increaseBy){
        self.sound.setVolume(self.sound.volume + increaseBy);
      }
    };

    // Decrease the volume of current sound object by the specified amount
    //   on a scale of 0-100
    // Parameters:
    //   decreaseBy (Integer) - volume to be decreased by specified percentage
    this.decreaseVolume = function(decreaseBy){
      decreaseBy = decreaseBy || 10;
      if (self.sound.volume >= decreaseBy){
        self.sound.setVolume(self.sound.volume - decreaseBy);
      }
    };

    // handlers for sound events
    // @todo refactor to use playState of soundObject
    // @todo id3 data show
    this.events = {
      play: function(e) {
        playerState = PLAYING;
        self.renderPlayer();
      },
      stop: function(e) {
        playerState = STOPPED;
        self.renderPlayer();
      },
      pause: function(e) {
        playerState = PAUSED;
        self.renderPlayer();
      },
      resume: function(e) {
        playerState = PLAYING;
        self.renderPlayer();
      },
      finish: function(e) {
        self.playNext();
        self.renderPlayer();
      },
      // @todo throttle settings
      whileloading: function(e) {
        self.renderPlayer();
      },
      onload: function(e) {
        if (self.sound.readyState == 2) {
          //failed to load
          self.renderPlayer();
        }
      },
      whileplaying: function(e) {
        //throttle for whileplaying calls
        var d = new Date();
        if (d - lastUpdatedAt > 50){
          lastUpdatedAt = d;
          self.renderPlayer();
        }
      },
      id3: function(){
      }
    };

    // Handle mouse move event
    this.mouseMoveHandler = function(e) {
      // Dont excessively call renderPlayer on mousemove event
      // lastPageX - cached mouse pointer position on last move and render
      if (e.pageX > lastPageX + delta || e.pageX < lastPageX - delta) {
        lastPageX = e.pageX;
        // change cursor location
        cursorLocation = self.translatePointerLocation(e);
        self.renderPlayer();
      }
    };

    // Main method responsible for rendering the player in address bar
    this.renderPlayer = function() {
      if (!isWindowInFocus) {
        return;
      }
      var controlString = self.renderControlString(),
        errorMessage = 'Failed to load the sound. Security / 404 / Bad format',
        playerString;
      // show error if there is a failure
      if (self.sound.readyState == 2){
        playerString = controlString + separator + '[' +
          errorMessage + ']';
      } else {
        var progress = self.renderProgressString(),
          timeString = self.renderTimeString();
        // dont write vuString if usePeakData not supported
        if (self.config.usePeakData) {
          vuString = vu.slice(0, Math.floor(self.sound.peakData.left * 10));
        } else {
          vuString = '';
        }
        playerString = controlString + separator + progress + separator +
          timeString + separator + vuString;
      }
      location.replace('#' + playerString.substr(0, cursorLocation) +
        self.config.cursorChar +
        playerString.substr(cursorLocation + self.config.cursorChar.length));
    };

    // Returns controls string
    this.renderControlString = function() {
      return previousControl + playControl[playerState] + nextControl;
    };

    // Returns progress string
    // @todo rework the logic below
    this.renderProgressString = function() {
      var location = Math.floor((self.sound.position/self.sound.durationEstimate)*progressStringLength),
        loaded = Math.floor((self.sound.bytesLoaded/self.sound.bytesTotal)*progressStringLength),
        string = loadingString.substr(0,loaded) + progressString.substr(loaded);
      return string.substr(0, location) +
        self.config.progressChar +
        string.substr(location + self.config.progressChar.length);
    };

    // Returns the remaining time string
    // @todo cache time for one second
    this.renderTimeString = function() {
      var timeLeft = self.sound.durationEstimate - self.sound.position;
      return '[-' + self.getTime(timeLeft) + ']';
    };

    // Translates mouse pointer location into player string cursor
    this.translatePointerLocation = function(e) {
      return Math.floor((e.pageX/screenWidth)*playerStringLength);
    };

    // create soudnManager sound object
    //   and returns it
    // @todo refactor to use getSoundById() here
    this.createSound = function(id, url) {
      var thisSound;
      // if id exist in self.playlist, return the corresponding sound object
      // already created
      if (self.playlist[id]){
        thisSound = self.playlist[id];
      } else {
        // create sound
        thisSound = sm.createSound({
          id:'awesome'+id,
          url:url,
          onplay:self.events.play,
          onstop:self.events.stop,
          onpause:self.events.pause,
          onresume:self.events.resume,
          onfinish:self.events.finish,
          whileloading:self.events.whileloading,
          whileplaying:self.events.whileplaying,
          onid3:self.events.id3,
          onload:self.events.onload,
          autoPlay: false
        });
        self.playlist[id] = thisSound;
      }
      return thisSound;
    };

    // Play the next sound object in the playlist and return it
    this.playNext = function(){
      var next;
      if (self.playlist.currentlyPlaying + 1 >= self.config.playlist.length){
        next = 0;
      } else {
        next = self.playlist.currentlyPlaying + 1;
      }
      return self.playById(next);
    };

    // Play the previous sound object in the playlist and return it
    this.playPrevious = function(){
      // get previous
      var previous;
      if (self.playlist.currentlyPlaying - 1 < 0){
        previous = self.config.playlist.length - 1;
      } else {
        previous = self.playlist.currentlyPlaying - 1;
      }
      return self.playById(previous);
    };

    // Play the sound object with id as id
    // Parameters:
    //   id (Integer) - playlist id of the sound object to be played
    this.playById = function(id){
      if (self.sound.sID) {
        self.sound.stop();
        self.sound.unload();
      }
      if (self.config.playlist[id]) {
        self.playlist.currentlyPlaying = id;
        self.sound = self.createSound(id, self.config.playlist[id]);
        self.sound.play();
        return self.sound;
      }
    };

    // converts milliseconds into human readable form
    // @todo variable names
    this.getTime = function(milliseconds){
      var seconds = Math.floor(milliseconds/1000),
          minutes = Math.floor(seconds/60);
      seconds = seconds - (minutes*60);
      return minutes + ':' + (seconds < 10 ? '0' + seconds : seconds);
    };

    // Initialize the player
    this.init = function (config) {
      var sound;
      if (config) {
        $.extend(this.config, config);
      }

      // Check if flash version is greate than 9
      // if yes, then set sm.defaultOptions.usePeakData to true

      if (sm.flashVersion >= 9) {
        sm.defaultOptions.usePeakData = this.config.usePeakData;
      }

      self.playById(0);
      self.bindEvents();
    };

  }<|endoftext|>


<commit_before>const path = require('path');
const rimraf = require('rimraf');
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const SuppressExtractedStyleScriptChunks = require('./plugins/SuppressExtractedStyleScriptChunks');
const {ROOT, SRC, PROD_MODE} = require('./helper');
const devServer = require('./devServer');
const entryUtils = require('./entryUtils');
const spritesmithConfig = require('./spritesmithConfig');

rimraf.sync(path.resolve(ROOT, 'dist'), require('fs'), false);

module.exports = {
  mode: process.env.NODE_ENV,

  entry: {
    ...entryUtils.CSS_ENTRIES,
    ...entryUtils.JS_ENTRIES,
  },

  devtool: PROD_MODE ? false : 'inline-source-map',

  devServer: devServer.options,

  output: {
    path: path.resolve(ROOT, 'dist'),
    filename: `[name]${PROD_MODE ? '.[contenthash]' : ''}.js`,
    chunkFilename: `[name]${PROD_MODE ? '.[contenthash]' : ''}.js`,
    sourceMapFilename: '[file].map',
  },

  resolve: {
    extensions: ['.js', '.vue'],
    modules: [SRC, path.resolve(ROOT, 'node_modules')],
    alias: {
      '@src': SRC,
      '@css': path.resolve(SRC, 'css'),
      '@assets': path.resolve(SRC, 'assets'),
      '@components': path.resolve(SRC, 'components'),
      'vue$': 'vue/dist/vue.esm.js',
    }
  },

  optimization: {
    runtimeChunk: {name: 'js/runtime'},
    splitChunks: {
      cacheGroups: {
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors/vendors',
          chunks: 'initial',
          priority: -10,
          minChunks: 3,
          enforce: true
        },
        components: {
          test: /[\\/](components|node_modules)[\\/].*\.vue$/,
          name: 'components/components',
          chunks: 'initial',
          priority: -5,
          enforce: true
        }
      }
    }
  },

  module: {
    rules: [
      {
        test: /\.js$/,
        use: [
          'cache-loader',
          {
            loader: 'thread-loader',
            options: {
              workers: require('os').cpus().length - 1,
            },
          },
          {
            loader: 'babel-loader'
          }
        ]
      },
      {
        test: /\.vue$/,
        use: [
          {
            loader: 'vue-loader',
            options: {
              productionMode: PROD_MODE,
              // default config
              transformAssetUrls: {
                video: ['src', 'poster'],
                source: 'src',
                img: 'src',
                image: ['xlink:href', 'href'],
                use: ['xlink:href', 'href']
              }
            }
          }
        ]
      },
      {
        test: /\.html$/,
        use: [
          'html-loader',
          {
            loader: path.resolve(ROOT, 'config/loaders/nunjucks-loader.js'),
            options: {
              searchPaths: [path.resolve(SRC, 'templates')],
              options: {
                tags: {
                  variableStart: '<$',
                  variableEnd: '$>',
                }
              },
              context: {}
            }
          }
        ]
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/,
        use: [{
          loader: 'url-loader',
          options: {
            esModule: false,
            limit: 1,
            name: '[path][name].[contenthash].[ext]',
            outputPath: url => url.replace(/^src[\\/]/, '')
          }
        }]
      },
      {
        test: /\.(eot|woff2?|ttf)([\?]?.*)$/,
        use: [{
          loader: 'file-loader',
          options: {
            esModule: false,
            name: '[path][name].[contenthash].[ext]',
            outputPath: url => url.replace(/^src[\\/]/, '')
          }
        }]
      },
      {
        test: /\.(s[ac]|c)ss$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              hmr: !PROD_MODE,
              reloadAll: true,
              publicPath: '../',
            }
          },
          'css-loader',
          'postcss-loader',
          'sass-loader',
        ]
      }
    ]
  },

  plugins: [
    new VueLoaderPlugin(),
    new MiniCssExtractPlugin({
      filename: `[name]${PROD_MODE ? '.[contenthash]' : ''}.css`,
      chunkFilename: `[name]${PROD_MODE ? '.[contenthash]' : ''}.css`
    }),
    ...entryUtils.HTML_ENTRIES_PLUGINS,
    ...spritesmithConfig,
  ].concat(!PROD_MODE ? [] : [
    new SuppressExtractedStyleScriptChunks(),
  ])

}
<commit_msg>update<commit_after>const path = require('path');
const rimraf = require('rimraf');
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const SuppressExtractedStyleScriptChunks = require('./plugins/SuppressExtractedStyleScriptChunks');
const {ROOT, SRC, PROD_MODE} = require('./helper');
const devServer = require('./devServer');
const entryUtils = require('./entryUtils');
const spritesmithConfig = require('./spritesmithConfig');

rimraf.sync(path.resolve(ROOT, 'dist'), require('fs'), false);

module.exports = {
  mode: process.env.NODE_ENV,

  entry: {
    ...entryUtils.CSS_ENTRIES,
    ...entryUtils.JS_ENTRIES,
  },

  devtool: PROD_MODE ? false : 'inline-source-map',

  devServer: devServer.options,

  output: {
    path: path.resolve(ROOT, 'dist'),
    filename: `[name]${PROD_MODE ? '.[contenthash]' : ''}.js`,
    chunkFilename: `[name]${PROD_MODE ? '.[contenthash]' : ''}.js`,
    sourceMapFilename: '[file].map',
  },

  resolve: {
    extensions: ['.js', '.vue'],
    modules: [SRC, path.resolve(ROOT, 'node_modules')],
    alias: {
      '@src': SRC,
      '@css': path.resolve(SRC, 'css'),
      '@assets': path.resolve(SRC, 'assets'),
      '@components': path.resolve(SRC, 'components'),
      'vue$': 'vue/dist/vue.esm.js',
    }
  },

  optimization: {
    runtimeChunk: {name: 'js/runtime'},
    splitChunks: {
      cacheGroups: {
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors/vendors',
          chunks: 'initial',
          priority: -10,
          minChunks: 3,
          enforce: true
        },
        components: {
          test: /[\\/](components|node_modules)[\\/].*\.(vue|s?[ac]ss)$/,
          name: 'components/components',
          chunks: 'initial',
          priority: -5,
          enforce: true
        }
      }
    }
  },

  module: {
    rules: [
      {
        test: /\.js$/,
        use: [
          'cache-loader',
          {
            loader: 'thread-loader',
            options: {
              workers: require('os').cpus().length - 1,
            },
          },
          {
            loader: 'babel-loader'
          }
        ]
      },
      {
        test: /\.vue$/,
        use: [
          {
            loader: 'vue-loader',
            options: {
              productionMode: PROD_MODE,
              // default config
              transformAssetUrls: {
                video: ['src', 'poster'],
                source: 'src',
                img: 'src',
                image: ['xlink:href', 'href'],
                use: ['xlink:href', 'href']
              }
            }
          }
        ]
      },
      {
        test: /\.html$/,
        use: [
          'html-loader',
          {
            loader: path.resolve(ROOT, 'config/loaders/nunjucks-loader.js'),
            options: {
              searchPaths: [path.resolve(SRC, 'templates')],
              options: {
                tags: {
                  variableStart: '<$',
                  variableEnd: '$>',
                }
              },
              context: {}
            }
          }
        ]
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/,
        use: [{
          loader: 'url-loader',
          options: {
            esModule: false,
            limit: 1,
            name: '[path][name].[contenthash].[ext]',
            outputPath: url => url.replace(/^src[\\/]/, '')
          }
        }]
      },
      {
        test: /\.(eot|woff2?|ttf)([\?]?.*)$/,
        use: [{
          loader: 'file-loader',
          options: {
            esModule: false,
            name: '[path][name].[contenthash].[ext]',
            outputPath: url => url.replace(/^src[\\/]/, '')
          }
        }]
      },
      {
        test: /\.(s[ac]|c)ss$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              hmr: !PROD_MODE,
              reloadAll: true,
              publicPath: '../',
            }
          },
          'css-loader',
          'postcss-loader',
          'sass-loader',
        ]
      }
    ]
  },

  plugins: [
    new VueLoaderPlugin(),
    new MiniCssExtractPlugin({
      filename: `[name]${PROD_MODE ? '.[contenthash]' : ''}.css`,
      chunkFilename: `[name]${PROD_MODE ? '.[contenthash]' : ''}.css`
    }),
    ...entryUtils.HTML_ENTRIES_PLUGINS,
    ...spritesmithConfig,
  ].concat(!PROD_MODE ? [] : [
    new SuppressExtractedStyleScriptChunks(),
  ])

}
<|endoftext|>


<commit_before>// Note: You must restart bin/webpack-dev-server for changes to take effect

const webpack = require('webpack');
const { basename, dirname, join, relative, resolve, sep } = require('path');
const { sync } = require('glob');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const extname = require('path-complete-extname');
const { env, settings, themes, output, loadersDir } = require('./configuration.js');
const localePackPaths = require('./generateLocalePacks');

const extensionGlob = `**/*{${settings.extensions.join(',')}}*`;
const entryPath = join(settings.source_path, settings.source_entry_path);
const packPaths = sync(join(entryPath, extensionGlob));
const entryPacks = [...packPaths, ...localePackPaths].filter(path => path !== join(entryPath, 'custom.js'));

const themePaths = Object.keys(themes).reduce(
  (themePaths, name) => {
    themePaths[name] = resolve(join(settings.source_path, themes[name]));
    return themePaths;
  }, {});

module.exports = {
  entry: Object.assign(
    entryPacks.reduce(
      (map, entry) => {
        const localMap = map;
        let namespace = relative(join(entryPath), dirname(entry));
        if (namespace === join('..', '..', '..', 'tmp', 'packs')) {
          namespace = ''; // generated by generateLocalePacks.js
        }
        localMap[join(namespace, basename(entry, extname(entry)))] = resolve(entry);
        return localMap;
      }, {}
    ), themePaths
  ),

  output: {
    filename: '[name].js',
    chunkFilename: '[name].js',
    path: output.path,
    publicPath: output.publicPath,
  },

  module: {
    rules: sync(join(loadersDir, '*.js')).map(loader => require(loader)),
  },

  plugins: [
    new webpack.EnvironmentPlugin(JSON.parse(JSON.stringify(env))),
    new webpack.NormalModuleReplacementPlugin(
      /^history\//, (resource) => {
        // temporary fix for https://github.com/ReactTraining/react-router/issues/5576
        // to reduce bundle size
        resource.request = resource.request.replace(/^history/, 'history/es');
      }
    ),
    new ExtractTextPlugin(env.NODE_ENV === 'production' ? '[name]-[hash].css' : '[name].css'),
    new ManifestPlugin({
      publicPath: output.publicPath,
      writeToFileEmit: true,
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'common',
      minChunks: (module, count) => {
        const reactIntlPathRegexp = new RegExp(`node_modules\\${sep}react-intl`);

        if (module.resource && reactIntlPathRegexp.test(module.resource)) {
          // skip react-intl because it's useless to put in the common chunk,
          // e.g. because "shared" modules between zh-TW and zh-CN will never
          // be loaded together
          return false;
        }

        return count >= 2;
      },
    }),
  ],

  resolve: {
    extensions: settings.extensions,
    modules: [
      resolve(settings.source_path),
      'node_modules',
    ],
  },

  resolveLoader: {
    modules: ['node_modules'],
  },

  node: {
    // Called by http-link-header in an API we never use, increases
    // bundle size unnecessarily
    Buffer: false,
  },
};
<commit_msg>Use contenthash for ExtractTextWebpackPlugin (#5462)<commit_after>// Note: You must restart bin/webpack-dev-server for changes to take effect

const webpack = require('webpack');
const { basename, dirname, join, relative, resolve, sep } = require('path');
const { sync } = require('glob');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const extname = require('path-complete-extname');
const { env, settings, themes, output, loadersDir } = require('./configuration.js');
const localePackPaths = require('./generateLocalePacks');

const extensionGlob = `**/*{${settings.extensions.join(',')}}*`;
const entryPath = join(settings.source_path, settings.source_entry_path);
const packPaths = sync(join(entryPath, extensionGlob));
const entryPacks = [...packPaths, ...localePackPaths].filter(path => path !== join(entryPath, 'custom.js'));

const themePaths = Object.keys(themes).reduce(
  (themePaths, name) => {
    themePaths[name] = resolve(join(settings.source_path, themes[name]));
    return themePaths;
  }, {});

module.exports = {
  entry: Object.assign(
    entryPacks.reduce(
      (map, entry) => {
        const localMap = map;
        let namespace = relative(join(entryPath), dirname(entry));
        if (namespace === join('..', '..', '..', 'tmp', 'packs')) {
          namespace = ''; // generated by generateLocalePacks.js
        }
        localMap[join(namespace, basename(entry, extname(entry)))] = resolve(entry);
        return localMap;
      }, {}
    ), themePaths
  ),

  output: {
    filename: '[name].js',
    chunkFilename: '[name].js',
    path: output.path,
    publicPath: output.publicPath,
  },

  module: {
    rules: sync(join(loadersDir, '*.js')).map(loader => require(loader)),
  },

  plugins: [
    new webpack.EnvironmentPlugin(JSON.parse(JSON.stringify(env))),
    new webpack.NormalModuleReplacementPlugin(
      /^history\//, (resource) => {
        // temporary fix for https://github.com/ReactTraining/react-router/issues/5576
        // to reduce bundle size
        resource.request = resource.request.replace(/^history/, 'history/es');
      }
    ),
    new ExtractTextPlugin(env.NODE_ENV === 'production' ? '[name]-[contenthash].css' : '[name].css'),
    new ManifestPlugin({
      publicPath: output.publicPath,
      writeToFileEmit: true,
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'common',
      minChunks: (module, count) => {
        const reactIntlPathRegexp = new RegExp(`node_modules\\${sep}react-intl`);

        if (module.resource && reactIntlPathRegexp.test(module.resource)) {
          // skip react-intl because it's useless to put in the common chunk,
          // e.g. because "shared" modules between zh-TW and zh-CN will never
          // be loaded together
          return false;
        }

        return count >= 2;
      },
    }),
  ],

  resolve: {
    extensions: settings.extensions,
    modules: [
      resolve(settings.source_path),
      'node_modules',
    ],
  },

  resolveLoader: {
    modules: ['node_modules'],
  },

  node: {
    // Called by http-link-header in an API we never use, increases
    // bundle size unnecessarily
    Buffer: false,
  },
};
<|endoftext|>


<commit_before>const fs = require('fs')
const inquirer = require('inquirer')
const semver = require('semver')
const pkg = require('./package.json')
const manifest = require('./shells/chrome/manifest.json')

const curVersion = pkg.version

;(async () => {
  const { newVersion } = await inquirer.prompt([{
    type: 'input',
    name: 'newVersion',
    message: `Please provide a version (current: ${curVersion}):`,
  }])

  if (!semver.valid(newVersion)) {
    console.error(`Invalid version: ${newVersion}`)
    process.exit(1)
  }

  if (semver.lt(newVersion, curVersion)) {
    console.error(`New version (${newVersion}) cannot be lower than current version (${curVersion}).`)
    process.exit(1)
  }

  const { yes } = await inquirer.prompt([{
    name: 'yes',
    message: `Release ${newVersion}?`,
    type: 'confirm'
  }])

  if (yes) {
    const isBeta = newVersion.includes('beta')
    pkg.version = newVersion
    if (isBeta) {
      const [, baseVersion, betaVersion] = /(.*)-beta\.(\w+)/.exec(newVersion)
      manifest.version = `${baseVersion}.${betaVersion}`
      applyIcons(manifest, '-beta')
    } else {
      manifest.version = newVersion
      applyIcons(manifest)
    }

    fs.writeFileSync('./package.json', JSON.stringify(pkg, null, 2))
    fs.writeFileSync('./shells/chrome/manifest.json', JSON.stringify(manifest, null, 2))
  } else {
    process.exit(1)
  }
})()

function applyIcons (manifest, suffix = '') {
  [16, 48, 128].forEach(size => {
    manifest.icons[size] = `icons/${size}${suffix}.png`
  })
}
<commit_msg>fix(release): version_name<commit_after>const fs = require('fs')
const inquirer = require('inquirer')
const semver = require('semver')
const pkg = require('./package.json')
const manifest = require('./shells/chrome/manifest.json')

const curVersion = pkg.version

;(async () => {
  const { newVersion } = await inquirer.prompt([{
    type: 'input',
    name: 'newVersion',
    message: `Please provide a version (current: ${curVersion}):`,
  }])

  if (!semver.valid(newVersion)) {
    console.error(`Invalid version: ${newVersion}`)
    process.exit(1)
  }

  if (semver.lt(newVersion, curVersion)) {
    console.error(`New version (${newVersion}) cannot be lower than current version (${curVersion}).`)
    process.exit(1)
  }

  const { yes } = await inquirer.prompt([{
    name: 'yes',
    message: `Release ${newVersion}?`,
    type: 'confirm'
  }])

  if (yes) {
    const isBeta = newVersion.includes('beta')
    pkg.version = newVersion
    if (isBeta) {
      const [, baseVersion, betaVersion] = /(.*)-beta\.(\w+)/.exec(newVersion)
      manifest.version = `${baseVersion}.${betaVersion}`
      manifest.version_name = `${baseVersion} beta ${betaVersion}`
      applyIcons(manifest, '-beta')
    } else {
      manifest.version = newVersion
      manifest.version_name = newVersion
      applyIcons(manifest)
    }

    fs.writeFileSync('./package.json', JSON.stringify(pkg, null, 2))
    fs.writeFileSync('./shells/chrome/manifest.json', JSON.stringify(manifest, null, 2))
  } else {
    process.exit(1)
  }
})()

function applyIcons (manifest, suffix = '') {
  [16, 48, 128].forEach(size => {
    manifest.icons[size] = `icons/${size}${suffix}.png`
  })
}
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');

var po = require('../../pageobjects/pageobjects.js');
var fixtures = require('../../fixtures/fixtures');
var arrayAssert = require('../arrayAssert')();
var devApi = require('../devApi')();
var common = require('../common');

describe('edit hub view', function () {
    var hubEditPage = po.hubEditPage({});
    var hubViewPage = po.hubViewPage({});

    var facFull = fixtures.facilitiesFixture.dummies.facFull;
    var facCar = fixtures.facilitiesFixture.dummies.facCar;
    var contact = fixtures.facilitiesFixture.contact;
    var operator = fixtures.facilitiesFixture.operator;

    var facilityFactory = fixtures.facilityFactory;

    function assertFacilityNamesInAnyOrder(facilitiesTable, expected) {
        expect(facilitiesTable.isDisplayed()).toBe(true);
        arrayAssert.assertInAnyOrder(facilitiesTable.getNames(), expected);
    }

    describe('new hub', function () {
        beforeEach(function () {
            devApi.resetAll();
            devApi.loginAs('ADMIN');
            hubEditPage.get();
        });

        it('initially no errors exist', function () {
            expect(hubEditPage.hasNoValidationErrors()).toBe(true);
        });

        it('required error is shown only for edited fields', function () {
            hubEditPage.setNameFi("foo");
            hubEditPage.setNameFi("");
            hubEditPage.setNameEn("bar"); // to focus out from name fi, TODO refactor
            expect(hubEditPage.isNameFiRequiredError()).toBe(true);
            expect(hubEditPage.isNameSvRequiredError()).toBe(false);
            expect(hubEditPage.isNameEnRequiredError()).toBe(false);
            expect(hubEditPage.isLocationRequiredError()).toBe(false);
        });

        it('required errors are shown for all required fields if user submits empty form without editing', function() {
            hubEditPage.save();
            expect(hubEditPage.getViolations()).toEqual([{ path: "Alue", message: "tarkista pakolliset tiedot ja syötteiden muoto" }]);
            expect(hubEditPage.isNameFiRequiredError()).toBe(true);
            expect(hubEditPage.isNameSvRequiredError()).toBe(true);
            expect(hubEditPage.isNameEnRequiredError()).toBe(true);
            expect(hubEditPage.isLocationRequiredError()).toBe(true);
        });

        describe('name', function () {
            it('is required in all languages', function () {
                hubEditPage.setName("Hub name");
                hubEditPage.setNameFi("");
                expect(hubEditPage.isNameFiRequiredError()).toBe(true);
                expect(hubEditPage.isNameSvRequiredError()).toBe(false);
                expect(hubEditPage.isNameEnRequiredError()).toBe(false);

                hubEditPage.setName("Hub name");
                hubEditPage.setNameSv("");
                expect(hubEditPage.isNameFiRequiredError()).toBe(false);
                expect(hubEditPage.isNameSvRequiredError()).toBe(true);
                expect(hubEditPage.isNameEnRequiredError()).toBe(false);

                hubEditPage.setName("Hub name");
                hubEditPage.setNameEn("");
                expect(hubEditPage.isNameFiRequiredError()).toBe(false);
                expect(hubEditPage.isNameSvRequiredError()).toBe(false);
                expect(hubEditPage.isNameEnRequiredError()).toBe(true);
            });

            it('max length is 255', function () {
                var max = new Array(255+1).join("x");
                var tooLong = max + "y";
                hubEditPage.setName(tooLong);
                expect(hubEditPage.getNameFi()).toEqual(max);
                expect(hubEditPage.getNameSv()).toEqual(max);
                expect(hubEditPage.getNameEn()).toEqual(max);
            });
        });

        describe('location', function () {
            it('is required, error is cleared after location is selected', function () {
                hubEditPage.setName("Hub name");
                hubEditPage.save();
                expect(hubEditPage.isLocationRequiredError()).toBe(true);

                hubEditPage.setLocation({ x: 165, y: 165 });
                expect(hubEditPage.hasNoValidationErrors()).toBe(true);
            });
        });

        it('with address and without facilities', function() {
            hubEditPage.setName("Hub name");
            hubEditPage.setStreetAddress(["katu", "gata", "street"]);
            hubEditPage.setPostalCode("00100");
            hubEditPage.setCity(["kaupunki", "stad", "city"]);
            hubEditPage.setLocation({x: 165, y: 165});
            expect(hubEditPage.facilitiesTable.isDisplayed()).toBe(false);

            hubEditPage.save();
            expect(hubViewPage.isDisplayed()).toBe(true);
            hubViewPage.toEditView();
            expect(hubEditPage.getName()).toEqual(["Hub name", "Hub name", "Hub name"]);
            expect(hubEditPage.getStreetAddress()).toEqual(["katu", "gata", "street"]);
            expect(hubEditPage.getPostalCode()).toBe("00100");
            expect(hubEditPage.getCity()).toEqual(["kaupunki", "stad", "city"]);
        });

        describe('with facilities', function() {
            beforeEach(function () {
                devApi.resetAll({facilities: [facFull, facCar], contacts: [contact], operators: [operator]});
                devApi.loginAs('ADMIN');
                hubEditPage.get();
            });

            it('create', function () {
                hubEditPage.setName("Hub name");
                expect(hubEditPage.facilitiesTable.isDisplayed()).toBe(false);

                hubEditPage.toggleFacility(facFull);
                hubEditPage.toggleFacility(facCar);
                hubEditPage.setLocation({x: 165, y: 165});
                assertFacilityNamesInAnyOrder(hubEditPage.facilitiesTable, [facFull.name, facCar.name]);

                hubEditPage.save();
                expect(hubViewPage.isDisplayed()).toBe(true);
            });
        });
    });

    if (!common.isOsx) {
        describe('hub with facilities', function () {
            var hub;
            var facilityNameOrder = common.facilityNameOrder;

            beforeEach(function () {
                hub = fixtures.hubsFixture.westend.copy();
                var fproto = facFull;
                var xdelta = fproto.locationInput.w + 5;
                var n = 0;
                var facilityCreator = function () {
                    return fproto.copyHorizontallyInDefaultZoom(n++ * xdelta);
                };
                var facilities = facilityFactory.facilitiesFromCreator(facilityCreator, facilityNameOrder);

                var f1LeftTop = [280, 155];
                _.forEach(facilities, function (f, idx) {
                    f.locationInput.offset = { x: f1LeftTop[0] + idx * xdelta, y: f1LeftTop[1] }
                });

                hub.location.coordinates = facilities[0].coordinatesFromTopLeft({ x: 30, y: 30 });
                hub.setFacilities(facilities);
                devApi.resetAll({facilities: hub.facilities, hubs: [hub], contacts: [contact], operators: [operator]});
            });

            it('facility can be removed from hub', function () {
                hubEditPage.get(hub.id);
                expect(hubEditPage.facilitiesTable.getSize()).toEqual(9);

                hubEditPage.toggleFacility(hub.facilities[0]);
                expect(hubEditPage.facilitiesTable.isDisplayed()).toBe(true);
                expect(hubEditPage.facilitiesTable.getSize()).toEqual(8);

                hubEditPage.save();
                expect(hubViewPage.isDisplayed()).toBe(true);
                expect(hubViewPage.facilitiesTable.getSize()).toBe(8);
            });

            it('when removing facilities, facility table is updated and order is maintained', function () {
                hubEditPage.get(hub.id);
                expect(hubEditPage.facilitiesTable.getSize()).toEqual(9);

                _.forEach(hub.facilities, function (f, idx) {
                    hubEditPage.toggleFacility(f);
                    if (idx < hub.facilities.length - 1) {
                        expect(hubEditPage.facilitiesTable.isDisplayed()).toBe(true);
                        arrayAssert.assertInOrder(hubEditPage.facilitiesTable.getNames(), facilityNameOrder, { allowSkip: true });
                    }
                });
            });
        });
    }
});
<commit_msg>fix(tests): add login to hub edit spec<commit_after>'use strict';

var _ = require('lodash');

var po = require('../../pageobjects/pageobjects.js');
var fixtures = require('../../fixtures/fixtures');
var arrayAssert = require('../arrayAssert')();
var devApi = require('../devApi')();
var common = require('../common');

describe('edit hub view', function () {
    var hubEditPage = po.hubEditPage({});
    var hubViewPage = po.hubViewPage({});

    var facFull = fixtures.facilitiesFixture.dummies.facFull;
    var facCar = fixtures.facilitiesFixture.dummies.facCar;
    var contact = fixtures.facilitiesFixture.contact;
    var operator = fixtures.facilitiesFixture.operator;

    var facilityFactory = fixtures.facilityFactory;

    function assertFacilityNamesInAnyOrder(facilitiesTable, expected) {
        expect(facilitiesTable.isDisplayed()).toBe(true);
        arrayAssert.assertInAnyOrder(facilitiesTable.getNames(), expected);
    }

    describe('new hub', function () {
        beforeEach(function () {
            devApi.resetAll();
            devApi.loginAs('ADMIN');
            hubEditPage.get();
        });

        it('initially no errors exist', function () {
            expect(hubEditPage.hasNoValidationErrors()).toBe(true);
        });

        it('required error is shown only for edited fields', function () {
            hubEditPage.setNameFi("foo");
            hubEditPage.setNameFi("");
            hubEditPage.setNameEn("bar"); // to focus out from name fi, TODO refactor
            expect(hubEditPage.isNameFiRequiredError()).toBe(true);
            expect(hubEditPage.isNameSvRequiredError()).toBe(false);
            expect(hubEditPage.isNameEnRequiredError()).toBe(false);
            expect(hubEditPage.isLocationRequiredError()).toBe(false);
        });

        it('required errors are shown for all required fields if user submits empty form without editing', function() {
            hubEditPage.save();
            expect(hubEditPage.getViolations()).toEqual([{ path: "Alue", message: "tarkista pakolliset tiedot ja syötteiden muoto" }]);
            expect(hubEditPage.isNameFiRequiredError()).toBe(true);
            expect(hubEditPage.isNameSvRequiredError()).toBe(true);
            expect(hubEditPage.isNameEnRequiredError()).toBe(true);
            expect(hubEditPage.isLocationRequiredError()).toBe(true);
        });

        describe('name', function () {
            it('is required in all languages', function () {
                hubEditPage.setName("Hub name");
                hubEditPage.setNameFi("");
                expect(hubEditPage.isNameFiRequiredError()).toBe(true);
                expect(hubEditPage.isNameSvRequiredError()).toBe(false);
                expect(hubEditPage.isNameEnRequiredError()).toBe(false);

                hubEditPage.setName("Hub name");
                hubEditPage.setNameSv("");
                expect(hubEditPage.isNameFiRequiredError()).toBe(false);
                expect(hubEditPage.isNameSvRequiredError()).toBe(true);
                expect(hubEditPage.isNameEnRequiredError()).toBe(false);

                hubEditPage.setName("Hub name");
                hubEditPage.setNameEn("");
                expect(hubEditPage.isNameFiRequiredError()).toBe(false);
                expect(hubEditPage.isNameSvRequiredError()).toBe(false);
                expect(hubEditPage.isNameEnRequiredError()).toBe(true);
            });

            it('max length is 255', function () {
                var max = new Array(255+1).join("x");
                var tooLong = max + "y";
                hubEditPage.setName(tooLong);
                expect(hubEditPage.getNameFi()).toEqual(max);
                expect(hubEditPage.getNameSv()).toEqual(max);
                expect(hubEditPage.getNameEn()).toEqual(max);
            });
        });

        describe('location', function () {
            it('is required, error is cleared after location is selected', function () {
                hubEditPage.setName("Hub name");
                hubEditPage.save();
                expect(hubEditPage.isLocationRequiredError()).toBe(true);

                hubEditPage.setLocation({ x: 165, y: 165 });
                expect(hubEditPage.hasNoValidationErrors()).toBe(true);
            });
        });

        it('with address and without facilities', function() {
            hubEditPage.setName("Hub name");
            hubEditPage.setStreetAddress(["katu", "gata", "street"]);
            hubEditPage.setPostalCode("00100");
            hubEditPage.setCity(["kaupunki", "stad", "city"]);
            hubEditPage.setLocation({x: 165, y: 165});
            expect(hubEditPage.facilitiesTable.isDisplayed()).toBe(false);

            hubEditPage.save();
            expect(hubViewPage.isDisplayed()).toBe(true);
            hubViewPage.toEditView();
            expect(hubEditPage.getName()).toEqual(["Hub name", "Hub name", "Hub name"]);
            expect(hubEditPage.getStreetAddress()).toEqual(["katu", "gata", "street"]);
            expect(hubEditPage.getPostalCode()).toBe("00100");
            expect(hubEditPage.getCity()).toEqual(["kaupunki", "stad", "city"]);
        });

        describe('with facilities', function() {
            beforeEach(function () {
                devApi.resetAll({facilities: [facFull, facCar], contacts: [contact], operators: [operator]});
                devApi.loginAs('ADMIN');
                hubEditPage.get();
            });

            it('create', function () {
                hubEditPage.setName("Hub name");
                expect(hubEditPage.facilitiesTable.isDisplayed()).toBe(false);

                hubEditPage.toggleFacility(facFull);
                hubEditPage.toggleFacility(facCar);
                hubEditPage.setLocation({x: 165, y: 165});
                assertFacilityNamesInAnyOrder(hubEditPage.facilitiesTable, [facFull.name, facCar.name]);

                hubEditPage.save();
                expect(hubViewPage.isDisplayed()).toBe(true);
            });
        });
    });

    if (!common.isOsx) {
        describe('hub with facilities', function () {
            var hub;
            var facilityNameOrder = common.facilityNameOrder;

            beforeEach(function () {
                hub = fixtures.hubsFixture.westend.copy();
                var fproto = facFull;
                var xdelta = fproto.locationInput.w + 5;
                var n = 0;
                var facilityCreator = function () {
                    return fproto.copyHorizontallyInDefaultZoom(n++ * xdelta);
                };
                var facilities = facilityFactory.facilitiesFromCreator(facilityCreator, facilityNameOrder);

                var f1LeftTop = [280, 155];
                _.forEach(facilities, function (f, idx) {
                    f.locationInput.offset = { x: f1LeftTop[0] + idx * xdelta, y: f1LeftTop[1] }
                });

                hub.location.coordinates = facilities[0].coordinatesFromTopLeft({ x: 30, y: 30 });
                hub.setFacilities(facilities);
                devApi.resetAll({facilities: hub.facilities, hubs: [hub], contacts: [contact], operators: [operator]});
                devApi.loginAs('ADMIN');
            });

            it('facility can be removed from hub', function () {
                hubEditPage.get(hub.id);
                expect(hubEditPage.facilitiesTable.getSize()).toEqual(9);

                hubEditPage.toggleFacility(hub.facilities[0]);
                expect(hubEditPage.facilitiesTable.isDisplayed()).toBe(true);
                expect(hubEditPage.facilitiesTable.getSize()).toEqual(8);

                hubEditPage.save();
                expect(hubViewPage.isDisplayed()).toBe(true);
                expect(hubViewPage.facilitiesTable.getSize()).toBe(8);
            });

            it('when removing facilities, facility table is updated and order is maintained', function () {
                hubEditPage.get(hub.id);
                expect(hubEditPage.facilitiesTable.getSize()).toEqual(9);

                _.forEach(hub.facilities, function (f, idx) {
                    hubEditPage.toggleFacility(f);
                    if (idx < hub.facilities.length - 1) {
                        expect(hubEditPage.facilitiesTable.isDisplayed()).toBe(true);
                        arrayAssert.assertInOrder(hubEditPage.facilitiesTable.getNames(), facilityNameOrder, { allowSkip: true });
                    }
                });
            });
        });
    }
});
<|endoftext|>


<commit_before>var fmt = require('fmt');
var awssum = require('awssum');
var amazon = awssum.load('amazon/amazon');
var Sqs = awssum.load('amazon/sqs').Sqs;

var env             = process.env;
var accessKeyId     = env.ACCESS_KEY_ID;
var secretAccessKey = env.SECRET_ACCESS_KEY;
var awsAccountId    = env.AWS_ACCOUNT_ID;

var sqs = new Sqs(accessKeyId, secretAccessKey, awsAccountId, amazon.US_EAST_1);

fmt.field('Region', sqs.region() );
fmt.field('EndPoint', sqs.host() );
fmt.field('AccessKeyId', sqs.accessKeyId() );
fmt.field('SecretAccessKey', sqs.secretAccessKey().substr(0, 3) + '...' );
fmt.field('AwsAccountId', sqs.awsAccountId() );

var options = {
    QueueName    : 'my-queue',
    Id           : [ 'janelle', 'lucy', 'sarah' ],
    MessageBody  : [ 'janelle', 'lucy', 'sarah' ],
    DelaySeconds : [ undefined, undefined, 20 ],
};

sqs.SendMessageBatch(options, function(err, data) {
    fmt.msg("Sending a message batch to a queue - expecting success");
    fmt.dump(err, 'Error');
    fmt.dump(data, 'Data');
});
<commit_msg>Update examples/amazon/sqs/send-message-batch.js<commit_after>var fmt = require('fmt');
var awssum = require('awssum');
var amazon = awssum.load('amazon/amazon');
var Sqs = awssum.load('amazon/sqs').Sqs;

var env             = process.env;
var accessKeyId     = env.ACCESS_KEY_ID;
var secretAccessKey = env.SECRET_ACCESS_KEY;
var awsAccountId    = env.AWS_ACCOUNT_ID;

var sqs = new Sqs({
      'accessKeyId' : accessKeyId,
      'secretAccessKey' : secretAccessKey,
      'region' : amazon.US_EAST_1,
      'awsAccountId': awsAccountId
    });

fmt.field('Region', sqs.region() );
fmt.field('EndPoint', sqs.host() );
fmt.field('AccessKeyId', sqs.accessKeyId() );
fmt.field('SecretAccessKey', sqs.secretAccessKey().substr(0, 3) + '...' );
fmt.field('AwsAccountId', sqs.awsAccountId() );

var options = {
    QueueName    : 'my-queue',
    Id           : [ 'janelle', 'lucy', 'sarah' ],
    MessageBody  : [ 'janelle', 'lucy', 'sarah' ],
    DelaySeconds : [ undefined, undefined, 20 ],
};

sqs.SendMessageBatch(options, function(err, data) {
    fmt.msg("Sending a message batch to a queue - expecting success");
    fmt.dump(err, 'Error');
    fmt.dump(data, 'Data');
});
<|endoftext|>