<commit_before>import path from 'path';
import process from 'process';
import webpack from "webpack";
import { WebpackManifestPlugin } from "webpack-manifest-plugin";
import MiniCssExtractPlugin from "mini-css-extract-plugin";
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
import TerserPlugin from "terser-webpack-plugin";

// Check for production mode
const PROD = process.env.NODE_ENV === "production";

const src = path.resolve(__dirname, 'web', 'resources');
const dep = path.join(src, 'node_modules');
const dst = path.resolve(__dirname, 'web', 'static');

export default {
    mode: PROD ? "production" : "development",
    // We're creating a web application
    target: 'web',
    context: src,
    entry: {
        'advanced-search': './js/advanced-search.js',
        'balance-chart': './js/balance-chart.js',
        'lazy-load-select': './js/lazy-load-select.js',
        'mac-address-input': './js/mac-address-input.js',
        'confirmable-error': './js/confirmable-error.ts',
        'main': './main.js',
        'navigation': './js/navigation.js',
        'tooltip': './js/tooltip.js',
        'table-fixed-header': './js/table-fixed-header.js',
        'traffic-graph': './js/traffic-graph.js',
        'transaction-chart': './js/transaction-chart.js',
        'transaction-form': './js/transaction-form.js',
        'unlimited-end-date': './js/unlimited-end-date.js',
        'select-multiple-improvement': './js/select-multiple-improvement.js',
        'tab-anchor': './js/tab-anchor.ts',
        'rooms-table': './js/rooms-table.ts',
    },
    output: {
        path: dst,
        filename: `[name].[chunkhash].${PROD ? 'min.js' : 'js'}`,
        hashFunction: 'md5',
        hashDigest: 'hex',
        hashDigestLength: 32,
        pathinfo: !PROD,
    },
    watchOptions: {
        aggregateTimeout: 1000,
        ignored: [
            dep,
        ],
    },
    devtool: PROD ? "source-map" : "eval-source-map",
    resolve: {
        symlinks: false,
        extensions: ['.js', '.ts'],
    },
    optimization: {
        minimizer: [
            // Compress JavaScript
            new TerserPlugin({
                cache: true,
                parallel: true,
                sourceMap: true,
            }),
        ],
        runtimeChunk: {
            name: "main",
        },
        splitChunks: {
            cacheGroups: {
                vendor: {
                    name: "vendor",
                    chunks: "all",
                    enforce: true,
                    test: dep,
                },
            },
        },
    },
    plugins: [
        // Clean the destination
        new CleanWebpackPlugin(),
        // Create stable module IDs
        new webpack.HashedModuleIdsPlugin({
            hashFunction: 'md5',
            hashDigest: 'hex',
            hashDigestLength: 32,
        }),
        // Put CSS into a separate file
        new MiniCssExtractPlugin({
            filename: '[name].[hash].css',
            chunkFilename: '[id].[hash].css',
            allChunks: true,
        }),
        // Generate a manifest file, that maps entries and assets to their
        // output file.
        new ManifestPlugin(),
    ].concat(PROD ? [
        // PROD plugins
    ] : [
        // !PROD plugins
    ]),
    module: {
        rules: [
            // Use the source-map-loader to reuse existing source maps, that
            // are provided by dependencies
            {
                test: /\.[j]sx?$/,  // TODO look at how we can deal with this and typescript
                use: ["source-map-loader"],
                enforce: "pre",
                include: dep,
            },
            {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: dep,
            },
            // Expose our table module as a global variable.
            // Functions from this module are referenced through
            // data-*-attributes for use by bootstrap-table.
            // This is necessary because `bootstrap-table` requires
            // the referenced function to be globally accessible, like
            // `window.fooFormatter`, and does not import it from somewhere.
            {
                test: path.join(src, 'js', 'table.js'),
                use: {
                    loader: "expose-loader",
                    options: {
                        exposes: "table",
                    },
                },
            },
            // Inject jQuery import into bootstrap-datepicker locales
            {
                test: /\.js$/,
                use: {
                    loader: "imports-loader",
                    options: {
                        type: 'commonjs',
                        imports: {
                            'moduleName': 'jquery',
                            'name': 'jQuery',
                        }
                    },
                },
                include: path.join(dep, "bootstrap-datepicker", "dist", "locales"),
            },
            // Transpile modern JavaScript for older browsers.
            {
                test: /\.jsx?$/,
                exclude: dep,
                use: {
                    loader: 'babel-loader',
                    options: {
                        cacheDirectory: true,
                        // Use the recommended preset-env
                        presets: [
                            ['@babel/preset-env', {
                                targets: {
                                    browsers: [
                                        'IE 11',
                                        'FF 52',
                                        'Chrome 49',
                                    ],
                                },
                                // Let webpack handle modules
                                modules: false,
                                forceAllTransforms: PROD,
                            }],
                        ],
                        // Import the babel runtime instead of inlining it in
                        // every file.
                        plugins: [
                            ['@babel/plugin-transform-runtime', {
                                helpers: false,
                                regenerator: true,
                                useESModules: true,
                            }],
                        ],
                    },
                },
            },
            // Handle CSS
            {
                test: /\.css$/,
                use: [
                    {
                        loader: "style-loader",
                    },
                    {
                        loader: MiniCssExtractPlugin.loader,
                    },
                    {
                        loader: "css-loader",
                    },
                ],
            },
            // Handle other assets
            {
                test: [
                    /\.(?:gif|ico|jpg|png|svg)$/, // Images
                    /\.(?:eot|otf|ttf|woff|woff2)$/, // Fonts
                    /\.(?:xml)$/, // static XML initial for openSearch
                ],
                use: {
                    loader: 'file-loader',
                    options: {
                        name: "[path][name].[hash].[ext]",
                        publicPath: './',
                        esModule: false,
                    },
                },
            },
        ],
    },
};
<commit_msg>Don't use `style-loader` and MiniCssExtractPlugin loader together<commit_after>import path from 'path';
import process from 'process';
import webpack from "webpack";
import { WebpackManifestPlugin } from "webpack-manifest-plugin";
import MiniCssExtractPlugin from "mini-css-extract-plugin";
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
import TerserPlugin from "terser-webpack-plugin";

// Check for production mode
const PROD = process.env.NODE_ENV === "production";

const src = path.resolve(__dirname, 'web', 'resources');
const dep = path.join(src, 'node_modules');
const dst = path.resolve(__dirname, 'web', 'static');

export default {
    mode: PROD ? "production" : "development",
    // We're creating a web application
    target: 'web',
    context: src,
    entry: {
        'advanced-search': './js/advanced-search.js',
        'balance-chart': './js/balance-chart.js',
        'lazy-load-select': './js/lazy-load-select.js',
        'mac-address-input': './js/mac-address-input.js',
        'confirmable-error': './js/confirmable-error.ts',
        'main': './main.js',
        'navigation': './js/navigation.js',
        'tooltip': './js/tooltip.js',
        'table-fixed-header': './js/table-fixed-header.js',
        'traffic-graph': './js/traffic-graph.js',
        'transaction-chart': './js/transaction-chart.js',
        'transaction-form': './js/transaction-form.js',
        'unlimited-end-date': './js/unlimited-end-date.js',
        'select-multiple-improvement': './js/select-multiple-improvement.js',
        'tab-anchor': './js/tab-anchor.ts',
        'rooms-table': './js/rooms-table.ts',
    },
    output: {
        path: dst,
        filename: `[name].[chunkhash].${PROD ? 'min.js' : 'js'}`,
        hashFunction: 'md5',
        hashDigest: 'hex',
        hashDigestLength: 32,
        pathinfo: !PROD,
    },
    watchOptions: {
        aggregateTimeout: 1000,
        ignored: [
            dep,
        ],
    },
    devtool: PROD ? "source-map" : "eval-source-map",
    resolve: {
        symlinks: false,
        extensions: ['.js', '.ts'],
    },
    optimization: {
        minimizer: [
            // Compress JavaScript
            new TerserPlugin({
                cache: true,
                parallel: true,
                sourceMap: true,
            }),
        ],
        runtimeChunk: {
            name: "main",
        },
        splitChunks: {
            cacheGroups: {
                vendor: {
                    name: "vendor",
                    chunks: "all",
                    enforce: true,
                    test: dep,
                },
            },
        },
    },
    plugins: [
        // Clean the destination
        new CleanWebpackPlugin(),
        // Create stable module IDs
        new webpack.HashedModuleIdsPlugin({
            hashFunction: 'md5',
            hashDigest: 'hex',
            hashDigestLength: 32,
        }),
        // Put CSS into a separate file
        new MiniCssExtractPlugin({
            filename: '[name].[hash].css',
            chunkFilename: '[id].[hash].css',
            allChunks: true,
        }),
        // Generate a manifest file, that maps entries and assets to their
        // output file.
        new ManifestPlugin(),
    ].concat(PROD ? [
        // PROD plugins
    ] : [
        // !PROD plugins
    ]),
    module: {
        rules: [
            // Use the source-map-loader to reuse existing source maps, that
            // are provided by dependencies
            {
                test: /\.[j]sx?$/,  // TODO look at how we can deal with this and typescript
                use: ["source-map-loader"],
                enforce: "pre",
                include: dep,
            },
            {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: dep,
            },
            // Expose our table module as a global variable.
            // Functions from this module are referenced through
            // data-*-attributes for use by bootstrap-table.
            // This is necessary because `bootstrap-table` requires
            // the referenced function to be globally accessible, like
            // `window.fooFormatter`, and does not import it from somewhere.
            {
                test: path.join(src, 'js', 'table.js'),
                use: {
                    loader: "expose-loader",
                    options: {
                        exposes: "table",
                    },
                },
            },
            // Inject jQuery import into bootstrap-datepicker locales
            {
                test: /\.js$/,
                use: {
                    loader: "imports-loader",
                    options: {
                        type: 'commonjs',
                        imports: {
                            'moduleName': 'jquery',
                            'name': 'jQuery',
                        }
                    },
                },
                include: path.join(dep, "bootstrap-datepicker", "dist", "locales"),
            },
            // Transpile modern JavaScript for older browsers.
            {
                test: /\.jsx?$/,
                exclude: dep,
                use: {
                    loader: 'babel-loader',
                    options: {
                        cacheDirectory: true,
                        // Use the recommended preset-env
                        presets: [
                            ['@babel/preset-env', {
                                targets: {
                                    browsers: [
                                        'IE 11',
                                        'FF 52',
                                        'Chrome 49',
                                    ],
                                },
                                // Let webpack handle modules
                                modules: false,
                                forceAllTransforms: PROD,
                            }],
                        ],
                        // Import the babel runtime instead of inlining it in
                        // every file.
                        plugins: [
                            ['@babel/plugin-transform-runtime', {
                                helpers: false,
                                regenerator: true,
                                useESModules: true,
                            }],
                        ],
                    },
                },
            },
            // Handle CSS
            {
                test: /\.css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    "css-loader",
                ],
            },
            // Handle other assets
            {
                test: [
                    /\.(?:gif|ico|jpg|png|svg)$/, // Images
                    /\.(?:eot|otf|ttf|woff|woff2)$/, // Fonts
                    /\.(?:xml)$/, // static XML initial for openSearch
                ],
                use: {
                    loader: 'file-loader',
                    options: {
                        name: "[path][name].[hash].[ext]",
                        publicPath: './',
                        esModule: false,
                    },
                },
            },
        ],
    },
};
<|endoftext|>


<commit_before>/**
 * Gruntfile
 *
 * If you created your Sails app with `sails new foo --linker`,
 * the following files will be automatically injected (in order)
 * into the EJS and HTML files in your `views` and `assets` folders.
 *
 * At the top part of this file, you'll find a few of the most commonly
 * configured options, but Sails' integration with Grunt is also fully
 * customizable.  If you'd like to work with your assets differently
 * you can change this file to do anything you like!
 *
 * More information on using Grunt to work with static assets:
 * http://gruntjs.com/configuring-tasks
 */

module.exports = function(grunt) {

  /**
   * CSS files to inject in order
   * (uses Grunt-style wildcard/glob/splat expressions)
   *
   * By default, Sails also supports LESS in development and production.
   * To use SASS/SCSS, Stylus, etc., edit the `sails-linker:devStyles` task
   * below for more options.  For this to work, you may need to install new
   * dependencies, e.g. `npm install grunt-contrib-sass`
   */

  var cssFilesToInject = [
    'linker/**/*.css'
  ];

  /**
   * Javascript files to inject in order
   * (uses Grunt-style wildcard/glob/splat expressions)
   *
   * To use client-side CoffeeScript, TypeScript, etc., edit the
   * `sails-linker:devJs` task below for more options.
   */

  var jsFilesToInject = [

    // Below, as a demonstration, you'll see the built-in dependencies
    // linked in the proper order order

    // Bring in the socket.io client
    'linker/js/socket.io.js',

    // then beef it up with some convenience logic for talking to Sails.js
    'linker/js/sails.io.js',

    // A simpler boilerplate library for getting you up and running w/ an
    // automatic listener for incoming messages from Socket.io.
    'linker/js/app.js',

    // *->    put other dependencies here   <-*

    // All of the rest of your app scripts imported here
    'linker/**/*.js'
  ];

  /**
   * Client-side HTML templates are injected using the sources below
   * The ordering of these templates shouldn't matter.
   * (uses Grunt-style wildcard/glob/splat expressions)
   *
   * By default, Sails uses JST templates and precompiles them into
   * functions for you.  If you want to use jade, handlebars, dust, etc.,
   * edit the relevant sections below.
   */

  var templateFilesToInject = [
    'linker/**/*.html'
  ];

  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  //
  // DANGER:
  //
  // With great power comes great responsibility.
  //
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////

  // Modify css file injection paths to use
  cssFilesToInject = cssFilesToInject.map(function(path) {
    return '.tmp/public/' + path;
  });

  // Modify js file injection paths to use
  jsFilesToInject = jsFilesToInject.map(function(path) {
    return '.tmp/public/' + path;
  });

  templateFilesToInject = templateFilesToInject.map(function(path) {
    return 'assets/' + path;
  });

  // Get path to core grunt dependencies from Sails
  var path = require('path');
  var depsPath = 'node_modules';
  grunt.loadTasks(path.join(depsPath, '/grunt-contrib-clean/tasks'));
  grunt.loadTasks(path.join(depsPath, '/grunt-contrib-copy/tasks'));
  grunt.loadTasks(path.join(depsPath, '/grunt-contrib-concat/tasks'));
  grunt.loadTasks(path.join(depsPath, '/grunt-sails-linker/tasks'));
  grunt.loadTasks(path.join(depsPath, '/grunt-contrib-jst/tasks'));
  grunt.loadTasks(path.join(depsPath, '/grunt-contrib-watch/tasks'));
  grunt.loadTasks(path.join(depsPath, '/grunt-contrib-uglify/tasks'));
  grunt.loadTasks(path.join(depsPath, '/grunt-contrib-cssmin/tasks'));
  grunt.loadTasks(path.join(depsPath, '/grunt-contrib-less/tasks'));
  grunt.loadTasks(path.join(depsPath, '/grunt-contrib-coffee/tasks'));
  grunt.loadTasks(path.join(depsPath, '/grunt-sync/tasks'));

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    copy: {
      dev: {
        files: [{
          expand: true,
          cwd: './assets',
          src: ['**/*'],
          dest: '.tmp/public'
        }]
      },
      build: {
        files: [{
          expand: true,
          cwd: '.tmp/public',
          src: ['**/*'],
          dest: 'www'
        }]
      }
    },

    sync: {
      dev: {
        files: [{
          cwd: './assets',
          src: ['**/*.!(coffee)'],
          dest: '.tmp/public'
        }]
      }
    },

    clean: {
      dev: ['.tmp/public/**'],
      build: ['www']
    },

    jst: {
      dev: {

        // To use other sorts of templates, specify the regexp below:
        // options: {
        //   templateSettings: {
        //     interpolate: /\{\{(.+?)\}\}/g
        //   }
        // },

        files: {
          '.tmp/public/jst.js': templateFilesToInject
        }
      }
    },

    less: {
      dev: {
        files: [{
          expand: true,
          cwd: 'assets/styles/',
          src: ['*.less'],
          dest: '.tmp/public/styles/',
          ext: '.css'
        }, {
          expand: true,
          cwd: 'assets/linker/styles/',
          src: ['*.less'],
          dest: '.tmp/public/linker/styles/',
          ext: '.css'
        }]
      }
    },

    coffee: {
      dev: {
        options: {
          bare: true,
          sourceMap: true,
          sourceRoot: './'
        },
        files: [{
          expand: true,
          cwd: 'assets/js/',
          src: ['**/*.coffee'],
          dest: '.tmp/public/js/',
          ext: '.js'
        }, {
          expand: true,
          cwd: 'assets/linker/js/',
          src: ['**/*.coffee'],
          dest: '.tmp/public/linker/js/',
          ext: '.js'
        }]
      }
    },

    /**
     * Production JS and CSS minification
     */
    concat: {
      js: {
        src: jsFilesToInject,
        dest: '.tmp/public/concat/production.js'
      },
      css: {
        src: cssFilesToInject,
        dest: '.tmp/public/concat/production.css'
      }
    },

    uglify: {
      dist: {
        src: ['.tmp/public/concat/production.js'],
        dest: '.tmp/public/min/production.js'
      }
    },

    cssmin: {
      dist: {
        src: ['.tmp/public/concat/production.css'],
        dest: '.tmp/public/min/production.css'
      }
    },

    /**
     * Automatically injects <link> and <script> tags
     */
    'sails-linker': {

      devJs: {
        options: {
          startTag: '<!--SCRIPTS-->',
          endTag: '<!--SCRIPTS END-->',
          fileTmpl: '<script src="%s"></script>',
          appRoot: '.tmp/public'
        },
        files: {
          '.tmp/public/**/*.html': jsFilesToInject,
          'views/**/*.html': jsFilesToInject,
          'views/**/*.ejs': jsFilesToInject
        }
      },

      prodJs: {
        options: {
          startTag: '<!--SCRIPTS-->',
          endTag: '<!--SCRIPTS END-->',
          fileTmpl: '<script src="%s"></script>',
          appRoot: '.tmp/public'
        },
        files: {
          '.tmp/public/**/*.html': ['.tmp/public/min/production.js'],
          'views/**/*.html': ['.tmp/public/min/production.js'],
          'views/**/*.ejs': ['.tmp/public/min/production.js']
        }
      },

      devStyles: {
        options: {
          startTag: '<!--STYLES-->',
          endTag: '<!--STYLES END-->',
          fileTmpl: '<link rel="stylesheet" href="%s">',
          appRoot: '.tmp/public'
        },

        // cssFilesToInject defined up top
        files: {
          '.tmp/public/**/*.html': cssFilesToInject,
          'views/**/*.html': cssFilesToInject,
          'views/**/*.ejs': cssFilesToInject
        }
      },

      prodStyles: {
        options: {
          startTag: '<!--STYLES-->',
          endTag: '<!--STYLES END-->',
          fileTmpl: '<link rel="stylesheet" href="%s">',
          appRoot: '.tmp/public'
        },
        files: {
          '.tmp/public/index.html': ['.tmp/public/min/production.css'],
          'views/**/*.html': ['.tmp/public/min/production.css'],
          'views/**/*.ejs': ['.tmp/public/min/production.css']
        }
      },

      // Bring in JST template object
      devTpl: {
        options: {
          startTag: '<!--TEMPLATES-->',
          endTag: '<!--TEMPLATES END-->',
          fileTmpl: '<script type="text/javascript" src="%s"></script>',
          appRoot: '.tmp/public'
        },
        files: {
          '.tmp/public/index.html': ['.tmp/public/jst.js'],
          'views/**/*.html': ['.tmp/public/jst.js'],
          'views/**/*.ejs': ['.tmp/public/jst.js']
        }
      }
    },

    watch: {
      api: {

        // API files to watch:
        files: ['api/**/*']
      },
      assets: {

        // Assets to watch:
        files: ['assets/**/*'],

        // When assets are changed:
        tasks: ['syncAssets', 'linkAssets']
      }
    }
  });

  // When Sails is lifted:
  grunt.registerTask('default', [
    'compileAssets',
    'linkAssets',
    'watch'
  ]);

  grunt.registerTask('compileAssets', [
    'clean:dev',
    'jst:dev',
    'less:dev',
    'copy:dev',
    'coffee:dev'
  ]);

  grunt.registerTask('syncAssets', [
    'jst:dev',
    'less:dev',
    'sync:dev',
    'coffee:dev'
  ]);

  grunt.registerTask('linkAssets', [

    // Update link/script/template references in `assets` index.html
    'sails-linker:devJs',
    'sails-linker:devStyles',
    'sails-linker:devTpl'
  ]);

  // Build the assets into a web accessible folder.
  // (handy for phone gap apps, chrome extensions, etc.)
  grunt.registerTask('build', [
    'compileAssets',
    'linkAssets',
    'clean:build',
    'copy:build'
  ]);

  // When sails is lifted in production
  grunt.registerTask('prod', [
    'clean:dev',
    'jst:dev',
    'less:dev',
    'copy:dev',
    'coffee:dev',
    'concat',
    'uglify',
    'cssmin',
    'sails-linker:prodJs',
    'sails-linker:prodStyles',
    'sails-linker:devTpl'
  ]);

};
<commit_msg>added production build task and fixed relative paths to be only used when building<commit_after>/**
 * Gruntfile
 *
 * If you created your Sails app with `sails new foo --linker`,
 * the following files will be automatically injected (in order)
 * into the EJS and HTML files in your `views` and `assets` folders.
 *
 * At the top part of this file, you'll find a few of the most commonly
 * configured options, but Sails' integration with Grunt is also fully
 * customizable.  If you'd like to work with your assets differently
 * you can change this file to do anything you like!
 *
 * More information on using Grunt to work with static assets:
 * http://gruntjs.com/configuring-tasks
 */

module.exports = function(grunt) {

  /**
   * CSS files to inject in order
   * (uses Grunt-style wildcard/glob/splat expressions)
   *
   * By default, Sails also supports LESS in development and production.
   * To use SASS/SCSS, Stylus, etc., edit the `sails-linker:devStyles` task
   * below for more options.  For this to work, you may need to install new
   * dependencies, e.g. `npm install grunt-contrib-sass`
   */

  var cssFilesToInject = [
    'linker/**/*.css'
  ];

  /**
   * Javascript files to inject in order
   * (uses Grunt-style wildcard/glob/splat expressions)
   *
   * To use client-side CoffeeScript, TypeScript, etc., edit the
   * `sails-linker:devJs` task below for more options.
   */

  var jsFilesToInject = [

    // Below, as a demonstration, you'll see the built-in dependencies
    // linked in the proper order order

    // Bring in the socket.io client
    'linker/js/socket.io.js',

    // then beef it up with some convenience logic for talking to Sails.js
    'linker/js/sails.io.js',

    // A simpler boilerplate library for getting you up and running w/ an
    // automatic listener for incoming messages from Socket.io.
    'linker/js/app.js',

    // *->    put other dependencies here   <-*

    // All of the rest of your app scripts imported here
    'linker/**/*.js'
  ];

  /**
   * Client-side HTML templates are injected using the sources below
   * The ordering of these templates shouldn't matter.
   * (uses Grunt-style wildcard/glob/splat expressions)
   *
   * By default, Sails uses JST templates and precompiles them into
   * functions for you.  If you want to use jade, handlebars, dust, etc.,
   * edit the relevant sections below.
   */

  var templateFilesToInject = [
    'linker/**/*.html'
  ];

  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  //
  // DANGER:
  //
  // With great power comes great responsibility.
  //
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////

  // Modify css file injection paths to use
  cssFilesToInject = cssFilesToInject.map(function(path) {
    return '.tmp/public/' + path;
  });

  // Modify js file injection paths to use
  jsFilesToInject = jsFilesToInject.map(function(path) {
    return '.tmp/public/' + path;
  });

  templateFilesToInject = templateFilesToInject.map(function(path) {
    return 'assets/' + path;
  });

  // Get path to core grunt dependencies from Sails
  var path = require('path');
  var depsPath = 'node_modules';
  grunt.loadTasks(path.join(depsPath, '/grunt-contrib-clean/tasks'));
  grunt.loadTasks(path.join(depsPath, '/grunt-contrib-copy/tasks'));
  grunt.loadTasks(path.join(depsPath, '/grunt-contrib-concat/tasks'));
  grunt.loadTasks(path.join(depsPath, '/grunt-sails-linker/tasks'));
  grunt.loadTasks(path.join(depsPath, '/grunt-contrib-jst/tasks'));
  grunt.loadTasks(path.join(depsPath, '/grunt-contrib-watch/tasks'));
  grunt.loadTasks(path.join(depsPath, '/grunt-contrib-uglify/tasks'));
  grunt.loadTasks(path.join(depsPath, '/grunt-contrib-cssmin/tasks'));
  grunt.loadTasks(path.join(depsPath, '/grunt-contrib-less/tasks'));
  grunt.loadTasks(path.join(depsPath, '/grunt-contrib-coffee/tasks'));
  grunt.loadTasks(path.join(depsPath, '/grunt-sync/tasks'));

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    copy: {
      dev: {
        files: [{
          expand: true,
          cwd: './assets',
          src: ['**/*'],
          dest: '.tmp/public'
        }]
      },
      build: {
        files: [{
          expand: true,
          cwd: '.tmp/public',
          src: ['**/*'],
          dest: 'www'
        }]
      }
    },

    sync: {
      dev: {
        files: [{
          cwd: './assets',
          src: ['**/*.!(coffee)'],
          dest: '.tmp/public'
        }]
      }
    },

    clean: {
      dev: ['.tmp/public/**'],
      build: ['www']
    },

    jst: {
      dev: {

        // To use other sorts of templates, specify the regexp below:
        // options: {
        //   templateSettings: {
        //     interpolate: /\{\{(.+?)\}\}/g
        //   }
        // },

        files: {
          '.tmp/public/jst.js': templateFilesToInject
        }
      }
    },

    less: {
      dev: {
        files: [{
          expand: true,
          cwd: 'assets/styles/',
          src: ['*.less'],
          dest: '.tmp/public/styles/',
          ext: '.css'
        }, {
          expand: true,
          cwd: 'assets/linker/styles/',
          src: ['*.less'],
          dest: '.tmp/public/linker/styles/',
          ext: '.css'
        }]
      }
    },

    coffee: {
      dev: {
        options: {
          bare: true,
          sourceMap: true,
          sourceRoot: './'
        },
        files: [{
          expand: true,
          cwd: 'assets/js/',
          src: ['**/*.coffee'],
          dest: '.tmp/public/js/',
          ext: '.js'
        }, {
          expand: true,
          cwd: 'assets/linker/js/',
          src: ['**/*.coffee'],
          dest: '.tmp/public/linker/js/',
          ext: '.js'
        }]
      }
    },

    /**
     * Production JS and CSS minification
     */
    concat: {
      js: {
        src: jsFilesToInject,
        dest: '.tmp/public/concat/production.js'
      },
      css: {
        src: cssFilesToInject,
        dest: '.tmp/public/concat/production.css'
      }
    },

    uglify: {
      dist: {
        src: ['.tmp/public/concat/production.js'],
        dest: '.tmp/public/min/production.js'
      }
    },

    cssmin: {
      dist: {
        src: ['.tmp/public/concat/production.css'],
        dest: '.tmp/public/min/production.css'
      }
    },

    /**
     * Automatically injects <link> and <script> tags
     */
    'sails-linker': {

      devJs: {
        options: {
          startTag: '<!--SCRIPTS-->',
          endTag: '<!--SCRIPTS END-->',
          fileTmpl: '<script src="%s"></script>',
          appRoot: '.tmp/public'
        },
        files: {
          '.tmp/public/**/*.html': jsFilesToInject,
          'views/**/*.html': jsFilesToInject,
          'views/**/*.ejs': jsFilesToInject
        }
      },

      devJsRelative: {
        options: {
          startTag: '<!--SCRIPTS-->',
          endTag: '<!--SCRIPTS END-->',
          fileTmpl: '<script src="%s"></script>',
          appRoot: '.tmp/public',
          relative: true
        },
        files: {
          '.tmp/public/**/*.html': jsFilesToInject,
          'views/**/*.html': jsFilesToInject,
          'views/**/*.ejs': jsFilesToInject
        }
      },

      prodJs: {
        options: {
          startTag: '<!--SCRIPTS-->',
          endTag: '<!--SCRIPTS END-->',
          fileTmpl: '<script src="%s"></script>',
          appRoot: '.tmp/public'
        },
        files: {
          '.tmp/public/**/*.html': ['.tmp/public/min/production.js'],
          'views/**/*.html': ['.tmp/public/min/production.js'],
          'views/**/*.ejs': ['.tmp/public/min/production.js']
        }
      },

      prodJsRelative: {
        options: {
          startTag: '<!--SCRIPTS-->',
          endTag: '<!--SCRIPTS END-->',
          fileTmpl: '<script src="%s"></script>',
          appRoot: '.tmp/public',
          relative: true
        },
        files: {
          '.tmp/public/**/*.html': ['.tmp/public/min/production.js'],
          'views/**/*.html': ['.tmp/public/min/production.js'],
          'views/**/*.ejs': ['.tmp/public/min/production.js']
        }
      },

      devStyles: {
        options: {
          startTag: '<!--STYLES-->',
          endTag: '<!--STYLES END-->',
          fileTmpl: '<link rel="stylesheet" href="%s">',
          appRoot: '.tmp/public'
        },

        // cssFilesToInject defined up top
        files: {
          '.tmp/public/**/*.html': cssFilesToInject,
          'views/**/*.html': cssFilesToInject,
          'views/**/*.ejs': cssFilesToInject
        }
      },

      devStylesRelative: {
        options: {
          startTag: '<!--STYLES-->',
          endTag: '<!--STYLES END-->',
          fileTmpl: '<link rel="stylesheet" href="%s">',
          appRoot: '.tmp/public',
          relative: true
        },

        // cssFilesToInject defined up top
        files: {
          '.tmp/public/**/*.html': cssFilesToInject,
          'views/**/*.html': cssFilesToInject,
          'views/**/*.ejs': cssFilesToInject
        }
      },

      prodStyles: {
        options: {
          startTag: '<!--STYLES-->',
          endTag: '<!--STYLES END-->',
          fileTmpl: '<link rel="stylesheet" href="%s">',
          appRoot: '.tmp/public'
        },
        files: {
          '.tmp/public/index.html': ['.tmp/public/min/production.css'],
          'views/**/*.html': ['.tmp/public/min/production.css'],
          'views/**/*.ejs': ['.tmp/public/min/production.css']
        }
      },

      prodStylesRelative: {
        options: {
          startTag: '<!--STYLES-->',
          endTag: '<!--STYLES END-->',
          fileTmpl: '<link rel="stylesheet" href="%s">',
          appRoot: '.tmp/public',
          relative: true
        },
        files: {
          '.tmp/public/index.html': ['.tmp/public/min/production.css'],
          'views/**/*.html': ['.tmp/public/min/production.css'],
          'views/**/*.ejs': ['.tmp/public/min/production.css']
        }
      },

      // Bring in JST template object
      devTpl: {
        options: {
          startTag: '<!--TEMPLATES-->',
          endTag: '<!--TEMPLATES END-->',
          fileTmpl: '<script type="text/javascript" src="%s"></script>',
          appRoot: '.tmp/public'
        },
        files: {
          '.tmp/public/index.html': ['.tmp/public/jst.js'],
          'views/**/*.html': ['.tmp/public/jst.js'],
          'views/**/*.ejs': ['.tmp/public/jst.js']
        }
      }
    },

    watch: {
      api: {

        // API files to watch:
        files: ['api/**/*']
      },
      assets: {

        // Assets to watch:
        files: ['assets/**/*'],

        // When assets are changed:
        tasks: ['syncAssets', 'linkAssets']
      }
    }
  });

  // When Sails is lifted:
  grunt.registerTask('default', [
    'compileAssets',
    'linkAssets',
    'watch'
  ]);

  grunt.registerTask('compileAssets', [
    'clean:dev',
    'jst:dev',
    'less:dev',
    'copy:dev',
    'coffee:dev'
  ]);

  grunt.registerTask('syncAssets', [
    'jst:dev',
    'less:dev',
    'sync:dev',
    'coffee:dev'
  ]);

  grunt.registerTask('linkAssets', [

    // Update link/script/template references in `assets` index.html
    'sails-linker:devJs',
    'sails-linker:devStyles',
    'sails-linker:devTpl'
  ]);

  // Link assets for built assets
  grunt.registerTask('linkAssetsBuild', [
    'sails-linker:devJsRelative',
    'sails-linker:devStylesRelative',
    'sails-linker:devTpl'
  ]);

  // Link assets for production built assets
  grunt.registerTask('linkAssetsBuildProd', [
    'sails-linker:prodJsRelative',
    'sails-linker:prodStylesRelative',
    'sails-linker:devTpl'
  ]);

  // Build the assets into a web accessible folder.
  // (handy for phone gap apps, chrome extensions, etc.)
  grunt.registerTask('build', [
    'compileAssets',
    'linkAssetsBuild',
    'clean:build',
    'copy:build'
  ]);

  // Build the assests into web accessible folder, except minifies all files.
  grunt.registerTask('buildProd', [
    'compileAssets',
    'concat',
    'uglify',
    'cssmin',
    'linkAssetsBuildProd',
    'clean:build',
    'copy:build'
  ]);

  // When sails is lifted in production
  grunt.registerTask('prod', [
    'clean:dev',
    'jst:dev',
    'less:dev',
    'copy:dev',
    'coffee:dev',
    'concat',
    'uglify',
    'cssmin',
    'sails-linker:prodJs',
    'sails-linker:prodStyles',
    'sails-linker:devTpl'
  ]);

};
<|endoftext|>


<commit_before>const path = require('path');
const webpack = require('webpack');

const distPath = path.join(__dirname, 'dist');
const srcPath = path.join(__dirname, 'src');
const env = process.env.NODE_ENV || 'development';
const minified = env === 'development' ? '' : '.min';
const exclude = [/node_modules/];

const config = {
  context: srcPath,

  entry: {
    reduxReuse: ['reduxReuse'],
  },

  output: {
    path: distPath,
    filename: `[name]${minified}.js`,
    library: ['reduxReuse', '[name]'],
    libraryTarget: 'umd',
  },

  resolve: {
    root: [srcPath]
  },

  module: {
    preloaders: [
      {
        test: /\.js$/,
        loader: 'eslint',
        exclude
      }
    ],

    loaders: [
      {
        test: /\.js$/,
        loader: 'babel',
        exclude
      }
    ]
  },
};

module.exports = [
  config,
  {
    ...config,
    entry: { reduxReuse: 'reduxReuse' },
    output: {
      ...config.output,
      filename: `reduxReuse${minified}.js`,
      library: 'reduxReuse',
    },
  }
];
<commit_msg>Fix webpack config to ensure it outputs a correct umd bundle<commit_after>const path = require('path');
const webpack = require('webpack');

const distPath = path.join(__dirname, 'dist');
const srcPath = path.join(__dirname, 'src');
const env = process.env.NODE_ENV || 'development';
const minified = env === 'development' ? '' : '.min';
const exclude = [/node_modules/];

const config = {
  context: srcPath,

  entry: { reduxReuse: 'reduxReuse' },

  output: {
    path: distPath,
    filename: `reduxReuse${minified}.js`,
    library: 'reduxReuse',
    libraryTarget: 'umd',
  },

  resolve: {
    root: [srcPath]
  },

  module: {
    preloaders: [
      {
        test: /\.js$/,
        loader: 'eslint',
        exclude
      }
    ],

    loaders: [
      {
        test: /\.js$/,
        loader: 'babel',
        exclude
      }
    ]
  },
};

module.exports = config;
<|endoftext|>


<commit_before>'use strict';
import Webpack from 'webpack';
import Merge from 'webpack-merge';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import HTMLWebpackPlugin from 'html-webpack-plugin';
import Path from 'path';
import PostCSS from './postcss.config';

const isProdEnv = (process.env.NODE_EV === 'production');
  console.log(`Node environment:\t${isProdEnv}`);

const VENDOR_LIBS = [
  'body-parser',
  'bson',
  'cloudinary',
  'jquery',
  'lodash',
  'react',
  'react-dom',
  'react-redux',
  'react-router',
  'react-router-redux',
  'redux',
  'redux-thunk'
];

const BASE_CONFIG = {
  entry: {
    // 'webpack/hot/dev-server',
    bundle: Path.resolve(__dirname, 'src/Routes'),
    vendor: VENDOR_LIBS
  },
  output: {
    path: Path.join(__dirname, 'dist'),
    filename: '[name].[hash].js'
    // publicPath: '/'
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/i,
        exclude: /(node_modules|bower_components)/,
        use: 'babel'
      }, {
        test: /\.css$/i,
        loader: ExtractTextPlugin.extract({
          fallback: 'style',
          use: 'css'
        })
      }, {
        test: /\.(scss|sass)$/i,
        loaders: ExtractTextPlugin.extract({
          fallback: 'style',
          use: ['css', 'postcss', 'sass']
        })
        // [
        //   'style',
        //   'css',
        //   'autoprefixer?browsers=last 3 versions',
        //   'sass?outputStyle=expanded'
        // ]
      }, {
        test: /\.json$/i,
        use: 'json'
      }, {
        test: /\.(bmp|gif|jpe?g|png|svg|ttif)$/i,
        use: [
          // {
          //   loader: 'url',
          //   options: { limit: 40000 }
          // },
          'file?name=/images/[name].[ext]',
          'image-webpack'
        ]
      }, {
        test: /\.(pdf|doc[mstx]?|ppt[mstx]?|od[fpst])$/i,
        use: 'file?name=/docs/[name].[ext]'
      }
    ]
  },
  plugins: [
    new Webpack.optimize.CommonsChunkPlugin({
      names: ['vendor', 'manifest'],
      minChunks: Infinity
    }),
    new Webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV)
      }
    }),
    new Webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false,
      options: {
        postcss: { PostCSS }
      }
    }),
    new ExtractTextPlugin('styles.css'),
    new HTMLWebpackPlugin({
      template: 'assets/index.html'
    })
  ],
  node: {
    console: false,
    fs: 'empty',
    net: 'empty',
    tls: 'empty'
  },
  cache: true,
  watch: true,
  devtool: `${isProdEnv ? 'inline' : 'cheap-eval'}-source-map`,
  // devtool: 'source-map',
  resolve: {
    extensions: ['.js', '.jsx']
  },
  resolveLoader: {
    moduleExtensions: ['-loader']
  }
};

const DEV_SERVER = {
  plugins: [
    new Webpack.HotModuleReplacementPlugin()
  ],
  devServer: {
    // contentBase: __dirname,
    historyApiFallback: true,
    host: 'localhost',
    hot: true,
    inline: true,
    noInfo: false,
    port: 3000
  },
  stats: {
    assets: true,
    children: false,
    chunks: false,
    colors: {
      bold: '\u001b[1m',
      cyan: '\u001b[1m\u001b[36m',
      green: '\u001b[1m\u001b[32m',
      magenta: '\u001b[1m\u001b[35m',
      red: '\u001b[1m\u001b[31m',
      yellow: '\u001b[1m\u001b[33m'
    },
    errorDetails: true,
    hash: false,
    modules: false,
    publicPath: false,
    reasons: true,
    timings: true,
    version: false,
    warnings: true
  }
};

const AGGREGATE_CONFIG = isProdEnv
  ? BASE_CONFIG
  : Merge(BASE_CONFIG, DEV_SERVER);

export default AGGREGATE_CONFIG;

//     new Webpack.optimize.DedupePlugin(),
//     new Webpack.optimize.UglifyJsPlugin({
//       compress: { warnings: false },
//       output: { comments: false },
//       sourceMap: false
//     })
<commit_msg>config (Webpack): Employ the dotenv-webpack plugin<commit_after>'use strict';
import Webpack from 'webpack';
import Merge from 'webpack-merge';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import HTMLWebpackPlugin from 'html-webpack-plugin';
import Path from 'path';
import PostCSS from './postcss.config';
import DotEnv from 'dotenv-webpack';

// const appEnv = (process.env.NODE_ENV || 'dev');
const isProdEnv = (process.env.NODE_ENV === 'production');
  console.log(`Node Environment:\t${process.env.NODE_ENV}`);

const VENDOR_LIBS = [
  'body-parser',
  'bson',
  'cloudinary',
  'jquery',
  'lodash',
  'react',
  'react-dom',
  'react-redux',
  'react-router',
  'react-router-redux',
  'redux',
  'redux-thunk'
];

const BASE_CONFIG = {
  entry: {
    // 'webpack/hot/dev-server',
    bundle: Path.resolve(__dirname, 'src/Routes'),
    vendor: VENDOR_LIBS
  },
  output: {
    path: Path.join(__dirname, 'dist'),
    filename: '[name].[hash].js'
    // publicPath: '/'
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/i,
        exclude: /(node_modules|bower_components)/,
        use: 'babel'
      }, {
        test: /\.css$/i,
        loader: ExtractTextPlugin.extract({
          fallback: 'style',
          use: 'css'
        })
      }, {
        test: /\.(scss|sass)$/i,
        loaders: ExtractTextPlugin.extract({
          fallback: 'style',
          use: ['css', 'postcss', 'sass']
        })
        // [
        //   'style',
        //   'css',
        //   'autoprefixer?browsers=last 3 versions',
        //   'sass?outputStyle=expanded'
        // ]
      }, {
        test: /\.json$/i,
        use: 'json'
      }, {
        test: /\.(bmp|gif|jpe?g|png|svg|ttif)$/i,
        use: [
          // {
          //   loader: 'url',
          //   options: { limit: 40000 }
          // },
          'file?name=/images/[name].[ext]',
          'image-webpack'
        ]
      }, {
        test: /\.(pdf|doc[mstx]?|ppt[mstx]?|od[fpst])$/i,
        use: 'file?name=/docs/[name].[ext]'
      }
    ]
  },
  plugins: [
    // Configure and read in local environment variables:
    new DotEnv({
      path: './.env'
    }),
    new Webpack.optimize.CommonsChunkPlugin({
      names: ['vendor', 'manifest'],
      minChunks: Infinity
    }),
    new Webpack.DefinePlugin({
      // 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')

      // 'process.env': {
      //   NODE_ENV: JSON.stringify(process.env.NODE_ENV)
      // }
    }),
    new Webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false,
      options: {
        postcss: { PostCSS }
      }
    }),
    new ExtractTextPlugin('styles.css'),
    new HTMLWebpackPlugin({
      template: 'assets/index.html'
    })
  ],
  node: {
    console: false,
    fs: 'empty',
    net: 'empty',
    tls: 'empty'
  },
  cache: true,
  watch: true,
  devtool: `${isProdEnv ? 'inline' : 'cheap-eval'}-source-map`,
  resolve: {
    extensions: ['.js', '.jsx']
  },
  resolveLoader: {
    moduleExtensions: ['-loader']
  }
};

const DEV_SERVER = {
  plugins: [
    new Webpack.HotModuleReplacementPlugin()
  ],
  devServer: {
    // contentBase: __dirname,
    historyApiFallback: true,
    host: 'localhost',
    hot: true,
    inline: true,
    noInfo: false,
    port: 3000
  },
  stats: {
    assets: true,
    children: false,
    chunks: false,
    colors: {
      bold: '\u001b[1m',
      cyan: '\u001b[1m\u001b[36m',
      green: '\u001b[1m\u001b[32m',
      magenta: '\u001b[1m\u001b[35m',
      red: '\u001b[1m\u001b[31m',
      yellow: '\u001b[1m\u001b[33m'
    },
    errorDetails: true,
    hash: false,
    modules: false,
    publicPath: false,
    reasons: true,
    timings: true,
    version: false,
    warnings: true
  }
};

const AGGREGATE_CONFIG = isProdEnv
  ? BASE_CONFIG
  : Merge(BASE_CONFIG, DEV_SERVER);

export default AGGREGATE_CONFIG;

//     new Webpack.optimize.DedupePlugin(),
//     new Webpack.optimize.UglifyJsPlugin({
//       compress: { warnings: false },
//       output: { comments: false },
//       sourceMap: false
//     })
<|endoftext|>


<commit_before>import webpack from 'webpack'
import path from 'path'

const env = process.env.WEBPACK_ENV

const library_name = 'react-time-ago'
let output_file

const plugins = []

if (env === 'build')
{
  plugins.push(new webpack.optimize.UglifyJsPlugin
  ({
    minimize  : true,
    sourceMap : true
  }))

  output_file = `${library_name}.min.js`
}
else
{
  output_file = `${library_name}.js`
}

const config =
{
  entry: path.join(__dirname, 'tooltip/index.js'),
  devtool: 'source-map',
  output:
  {
    path           : path.join(__dirname, '/bundle'),
    filename       : output_file,
    library        : 'ReactTimeAgo',
    libraryTarget  : 'umd',
    umdNamedDefine : true
  },
  module:
  {
    loaders:
    [{
      test    : /(\.js)$/,
      loader  : 'babel-loader',
      exclude : /node_modules/
    }, {
      test    : /(\.json)$/,
      loader  : 'json-loader'
    }]
  },
  externals:
  {
    // Use external version of React
    "react"     : "React",
    "react-dom" : "ReactDOM",

    "javascript-time-ago" : 'javascript-time-ago'
  },
  plugins
}

module.exports = config<commit_msg>Update webpack.config.babel.js<commit_after>import webpack from 'webpack'
import path from 'path'

const env = process.env.WEBPACK_ENV

const library_name = 'react-time-ago'
let output_file

const plugins = []

if (env === 'build')
{
  plugins.push(new webpack.optimize.UglifyJsPlugin
  ({
    minimize  : true,
    sourceMap : true
  }))

  output_file = `${library_name}.min.js`
}
else
{
  output_file = `${library_name}.js`
}

const config =
{
  entry: path.join(__dirname, 'index.js'),
  devtool: 'source-map',
  output:
  {
    path           : path.join(__dirname, '/bundle'),
    filename       : output_file,
    library        : 'ReactTimeAgo',
    libraryTarget  : 'umd',
    umdNamedDefine : true
  },
  module:
  {
    loaders:
    [{
      test    : /(\.js)$/,
      loader  : 'babel-loader',
      exclude : /node_modules/
    }, {
      test    : /(\.json)$/,
      loader  : 'json-loader'
    }]
  },
  externals:
  {
    // Use external version of React
    "react"     : "React",
    "react-dom" : "ReactDOM",

    "javascript-time-ago" : 'javascript-time-ago'
  },
  plugins
}

module.exports = config<|endoftext|>


<commit_before>'use strict';

var autoprefixer = require('autoprefixer');
var ChildCompilerLoaderListPlugin = require(
  'child-compiler-loader-list-webpack-plugin'
);
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWepbackPlugin = require('html-webpack-plugin');
var OfflinePlugin = require('offline-plugin');
var UglifyJsPlugin = require('webpack').optimize.UglifyJsPlugin;

// This is used to extract the css into a separate stylesheet. We do that only
// for production builds so development builds can make use of hot module
// replacement and faster builds (extracting takes time).
//
// Multiple extractions could be done, as one option a critical section of css
// could be extracted and with a small plugin to HtmlWebpackPlugin, inlined
// into the output html.
var mainCssExtraction = new ExtractTextPlugin('[contenthash].css');

var loaders = [
    {
      test: /\.jsx?$/,
      exclude: /node_modules/,
      loader: 'babel-loader',
    },
    // Autoload style files named like an included jsx file.
    {
      test: /\.jsx$/,
      exclude: /node_modules/,
      loader: 'baggage-loader?[file].styl',
    },
    {
      test: /\.styl$/,
      loader: mainCssExtraction.extract(
        'style-loader',
        'css-loader!postcss-loader!stylus-loader'
      ),
    },
    {
      test: /\.(png|webm|svg)$/,
      loader: 'file-loader',
    },
    {
      test: /\.json$/,
      loader: 'json-loader',
    },
    {
      test: /[/\\]soundjs/,
      loader: 'exports-loader?createjs!script-loader',
    },
];

module.exports = {
  context: __dirname,
  entry: {
    main: './src',
  },
  output: {
    path: 'dist',
    filename: '[hash].js',
  },
  module: {
    loaders: loaders,
  },
  resolve: {
    modulesDirectories: ['node_modules', 'vendor'],
    extensions: ['', '.min.js', '.js', '.jsx'],
  },
  resolveLoaders: {
    modulesDirectories: ['node_modules', 'web_loaders'],
  },
  postcss: function() {
    return [autoprefixer];
  },
  plugins: [
    mainCssExtraction,
    new OfflinePlugin({
      caches: {
        main: ['index.html', '*'],
      },
      updateStrategy: 'changed',
      // scope is any subdirectory the deployed files will be under.
      // scope: '/rwd-game-boiler/',
    }),
    new ChildCompilerLoaderListPlugin({
      test: /html-webpack-plugin/,
      loaders: loaders
      .filter(function(loader) {return loader.test.source !== '\\.styl$';})
      .concat({
        test: /\.styl$/,
        loader: 'css-loader/locals!stylus-loader',
      }),
    }),
    new HtmlWepbackPlugin({
      filename: 'index.html',
      template: './src/index.bake.html',
      inject: 'body',
      chunks: ['main'],
    }),
    new UglifyJsPlugin(),
  ],
};
<commit_msg>Setup react to build for production, without invariants<commit_after>'use strict';

var autoprefixer = require('autoprefixer');
var ChildCompilerLoaderListPlugin = require(
  'child-compiler-loader-list-webpack-plugin'
);
var DefinePlugin = require('webpack').DefinePlugin;
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWepbackPlugin = require('html-webpack-plugin');
var OfflinePlugin = require('offline-plugin');
var UglifyJsPlugin = require('webpack').optimize.UglifyJsPlugin;

// This is used to extract the css into a separate stylesheet. We do that only
// for production builds so development builds can make use of hot module
// replacement and faster builds (extracting takes time).
//
// Multiple extractions could be done, as one option a critical section of css
// could be extracted and with a small plugin to HtmlWebpackPlugin, inlined
// into the output html.
var mainCssExtraction = new ExtractTextPlugin('[contenthash].css');

var loaders = [
    {
      test: /\.jsx?$/,
      exclude: /node_modules/,
      loader: 'babel-loader',
    },
    // Autoload style files named like an included jsx file.
    {
      test: /\.jsx$/,
      exclude: /node_modules/,
      loader: 'baggage-loader?[file].styl',
    },
    {
      test: /\.styl$/,
      loader: mainCssExtraction.extract(
        'style-loader',
        'css-loader!postcss-loader!stylus-loader'
      ),
    },
    {
      test: /\.(png|webm|svg)$/,
      loader: 'file-loader',
    },
    {
      test: /\.json$/,
      loader: 'json-loader',
    },
    {
      test: /[/\\]soundjs/,
      loader: 'exports-loader?createjs!script-loader',
    },
];

module.exports = {
  context: __dirname,
  entry: {
    main: './src',
  },
  output: {
    path: 'dist',
    filename: '[hash].js',
  },
  module: {
    loaders: loaders,
  },
  resolve: {
    modulesDirectories: ['node_modules', 'vendor'],
    extensions: ['', '.min.js', '.js', '.jsx'],
  },
  resolveLoaders: {
    modulesDirectories: ['node_modules', 'web_loaders'],
  },
  postcss: function() {
    return [autoprefixer];
  },
  plugins: [
    mainCssExtraction,
    new DefinePlugin({
      'process.env.NODE_ENV': '"production"',
    }),
    new OfflinePlugin({
      caches: {
        main: ['index.html', '*'],
      },
      updateStrategy: 'changed',
      // scope is any subdirectory the deployed files will be under.
      // scope: '/rwd-game-boiler/',
    }),
    new ChildCompilerLoaderListPlugin({
      test: /html-webpack-plugin/,
      loaders: loaders
      .filter(function(loader) {return loader.test.source !== '\\.styl$';})
      .concat({
        test: /\.styl$/,
        loader: 'css-loader/locals!stylus-loader',
      }),
    }),
    new HtmlWepbackPlugin({
      filename: 'index.html',
      template: './src/index.bake.html',
      inject: 'body',
      chunks: ['main'],
    }),
    new UglifyJsPlugin(),
  ],
};
<|endoftext|>


<commit_before>/*globals $, GOVUK, suchi */
/*jslint
 white: true,
 browser: true */

$(function() {
  "use strict";
  function browserWarning() {
    var container = $('

'),
        text = $('
For a safer, faster, better experience online you should upgrade your browser.
'),
        findMoreLink = $('Find out more about browsers'),
        closeLink = $('Close');

    return container.append(text.append(findMoreLink, closeLink));
  }

  // we don't show the message when the cookie warning is also there
  if (GOVUK.cookie('seen_cookie_message')) {
    if (suchi.isOld(navigator.userAgent)) {
      if(GOVUK.cookie('govuk_not_first_visit') !== null && GOVUK.cookie('govuk_browser_upgrade_dismissed') === null){
        var $prompt = browserWarning();
        $('#global-cookie-message').after($prompt);
        $prompt.show();
        $prompt.on("click", ".dismiss", function(e) {
          $prompt.hide();
          // the warning is dismissable for 2 weeks
          GOVUK.cookie('govuk_browser_upgrade_dismissed', 'yes', { days: 14 });
        });
      }
    }

    // We're not showing the message on first visit
    GOVUK.cookie('govuk_not_first_visit', 'yes', { days: 28 });
  }
});
<commit_msg>Update browser help link<commit_after>/*globals $, GOVUK, suchi */
/*jslint
 white: true,
 browser: true */

$(function() {
  "use strict";
  function browserWarning() {
    var container = $('

'),
        text = $('
For a safer, faster, better experience online you should upgrade your browser.
'),
        findMoreLink = $('Find out more about browsers'),
        closeLink = $('Close');

    return container.append(text.append(findMoreLink, closeLink));
  }

  // we don't show the message when the cookie warning is also there
  if (GOVUK.cookie('seen_cookie_message')) {
    if (suchi.isOld(navigator.userAgent)) {
      if(GOVUK.cookie('govuk_not_first_visit') !== null && GOVUK.cookie('govuk_browser_upgrade_dismissed') === null){
        var $prompt = browserWarning();
        $('#global-cookie-message').after($prompt);
        $prompt.show();
        $prompt.on("click", ".dismiss", function(e) {
          $prompt.hide();
          // the warning is dismissable for 2 weeks
          GOVUK.cookie('govuk_browser_upgrade_dismissed', 'yes', { days: 14 });
        });
      }
    }

    // We're not showing the message on first visit
    GOVUK.cookie('govuk_not_first_visit', 'yes', { days: 28 });
  }
});
<|endoftext|>


<commit_before>// Webpack configuration to use with the build task.

var webpack = require('webpack');

module.exports = {

  // Create also a "lib" chunk with common libraries, e.g. react.
  entry: {
    lib: ['react'],
    main: './app/client/main'
  },

  output: {
    path: './build/app/public/js',
    publicPath: '/js/',
    filename: 'main.js'
  },

  plugins: [
    new webpack.DefinePlugin({
      "process.env": {
        "NODE_ENV": JSON.stringify("production") // This has effect on the react lib size
      }
    }),
    new webpack.optimize.CommonsChunkPlugin('lib', 'lib.js'),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    })
  ],

  resolve: {
    extensions: ['', '.js', '.jsx']
  },

  module: {
    loaders: [{
      test: /\.jsx$/,
      loaders: ['jsx']
    }]
  },

  externals: {
    // Showdown is not is node_modules,
    // so we tell Webpack to resolve it to a global
    // 'showdown': 'window.Showdown'
  }
};<commit_msg>Add react-router to the library<commit_after>// Webpack configuration to use with the build task.

var webpack = require('webpack');

module.exports = {

  // Create also a "lib" chunk with common libraries, e.g. react.
  entry: {
    lib: ['react', 'react-router'],
    main: './app/client/main'
  },

  output: {
    path: './build/app/public/js',
    publicPath: '/js/',
    filename: 'main.js'
  },

  plugins: [
    new webpack.DefinePlugin({
      "process.env": {
        "NODE_ENV": JSON.stringify("production") // This has effect on the react lib size
      }
    }),
    new webpack.optimize.CommonsChunkPlugin('lib', 'lib.js'),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    })
  ],

  resolve: {
    extensions: ['', '.js', '.jsx']
  },

  module: {
    loaders: [{
      test: /\.jsx$/, loaders: ['jsx']
    }]
  },

  externals: {}
};<|endoftext|>


<commit_before>var cakeWamp = window.cakeWamp || {};

/**
 * Array with the subscriptions to keep track off and auto (re)subscribe when (re)connected
 * @type Array
 */
cakeWamp.subscriptions = [];

/**
 * Array with onconnect listeners
 * @type Array
 */
cakeWamp.onconnectListeners = [];

/**
 * Array with onhangup listeners
 * @type Array
 */
cakeWamp.onhangupListeners = [];

cakeWamp.connect = function() {
    ab.connect(wsuri, function(session) {
        cakeWamp.session = session;

        cakeWamp.onconnect();
    }, function(code, reason) {
        cakeWamp.onhangup(code, reason);
    }, cakeWamp.options);
};

cakeWamp.onconnect = function() {
    cakeWamp.session.subscribe('Rachet.connection.keepAlive', function (topic, event) {});

    for (var i in cakeWamp.onconnectListeners) {
        cakeWamp.onconnectListeners[i](cakeWamp.session);
    }

    for (var i in cakeWamp.subscriptions) {
        cakeWamp.session.subscribe(cakeWamp.subscriptions[i].topic, cakeWamp.subscriptions[i].callback);
    }
};

cakeWamp.onhangup = function(code, reason) {
    for (var i in cakeWamp.onhangupListeners) {
        cakeWamp.onhangupListeners[i](code, reason);
    }
};

/**
 * Wrapper around AB's session.call method
 */
cakeWamp.call = function() {
    cakeWamp.session.call.apply(cakeWamp.session, arguments);
};

/**
 * Wrapper around AB's session.subscribe method
 */
cakeWamp.subscribe = function() {
    cakeWamp.subscriptions.push({
        topic: arguments[0],
        callback: arguments[1]
    });

    if (cakeWamp.session && cakeWamp.session._websocket_connected) {
        cakeWamp.session.subscribe.apply(cakeWamp.session, arguments);
    }
};

/**
 * Wrapper around AB's session.unsubscribe method
 */
cakeWamp.unsubscribe = function() {
    cakeWamp.session.unsubscribe.apply(cakeWamp.session, arguments);
};

/**
 * Wrapper around AB's session.publish method
 */
cakeWamp.publish = function() {
    cakeWamp.session.publish.apply(cakeWamp.session, arguments);
};

cakeWamp.connect();<commit_msg>Added missing docblocks for callabcks and connection function(calls)<commit_after>var cakeWamp = window.cakeWamp || {};

/**
 * Array with the subscriptions to keep track off and auto (re)subscribe when (re)connected
 * @type Array
 */
cakeWamp.subscriptions = [];

/**
 * Array with onconnect listeners
 * @type Array
 */
cakeWamp.onconnectListeners = [];

/**
 * Array with onhangup listeners
 * @type Array
 */
cakeWamp.onhangupListeners = [];

/**
 * connect to the websocket server and call onconnect and onhangup callbacks when they occur
 *
 * @returns void
 */
cakeWamp.connect = function() {
    ab.connect(wsuri, function(session) {
        cakeWamp.session = session;

        cakeWamp.onconnect();
    }, function(code, reason) {
        cakeWamp.onhangup(code, reason);
    }, cakeWamp.options);
};

/**
 * onhangup callback notifies all listeners about a succesful connection
 *
 * @returns void
 */
cakeWamp.onconnect = function() {
    cakeWamp.session.subscribe('Rachet.connection.keepAlive', function (topic, event) {});

    for (var i in cakeWamp.onconnectListeners) {
        cakeWamp.onconnectListeners[i](cakeWamp.session);
    }

    for (var i in cakeWamp.subscriptions) {
        cakeWamp.session.subscribe(cakeWamp.subscriptions[i].topic, cakeWamp.subscriptions[i].callback);
    }
};

/**
 * onhangup callback notifies all listeners about a hangup
 *
 * @param int code hangup code
 * @param string reason hangup text reason
 * @returns void
 */
cakeWamp.onhangup = function(code, reason) {
    for (var i in cakeWamp.onhangupListeners) {
        cakeWamp.onhangupListeners[i](code, reason);
    }
};

/**
 * Wrapper around AB's session.call method
 */
cakeWamp.call = function() {
    cakeWamp.session.call.apply(cakeWamp.session, arguments);
};

/**
 * Wrapper around AB's session.subscribe method
 */
cakeWamp.subscribe = function() {
    cakeWamp.subscriptions.push({
        topic: arguments[0],
        callback: arguments[1]
    });

    if (cakeWamp.session && cakeWamp.session._websocket_connected) {
        cakeWamp.session.subscribe.apply(cakeWamp.session, arguments);
    }
};

/**
 * Wrapper around AB's session.unsubscribe method
 */
cakeWamp.unsubscribe = function() {
    cakeWamp.session.unsubscribe.apply(cakeWamp.session, arguments);
};

/**
 * Wrapper around AB's session.publish method
 */
cakeWamp.publish = function() {
    cakeWamp.session.publish.apply(cakeWamp.session, arguments);
};

/**
 * Connect to the websocket server
 */
cakeWamp.connect();<|endoftext|>


<commit_before>Skull.UI_helper = {
  setupResponsiveIframes: function($container) {
    this.$container = $container;
    this.$iframes = $("iframe[src^='//player.vimeo.com'], iframe[src^='//www.youtube.com']");
    this.$iframes.each(function() {
      if (!$(this).data('aspectRatio')) {
        var height = this.height || $(this).height(),
            width = this.width || $(this).width();
        $(this)
          .data('aspectRatio', height / width)
          .removeAttr('height')
          .removeAttr('width');
      }
    });
    this.windowResize();
    //Prevents wrong container width calculation
    setTimeout(function(){
      this.updateIframeSize();
    },0);
  },

  windowResize: function() {
    var that = this;
    $(window).resize(function() {
      that.updateIframeSize();
    });
  },

  updateIframeSize: function() {
    var newWidth = this.$container.width();
    if (newWidth) {
      this.$iframes.each(function() {
        var $el = $(this);
        $el
          .width(newWidth)
          .height(newWidth * $el.data('aspectRatio'));
      });
    } else {
      this.$iframes.each(function() {
        $(this)
          .removeAttr('height')
          .removeAttr('width');
      });
    }
  }

}
<commit_msg>Fixes JS for iframe resize<commit_after>Skull.UI_helper = {
  setupResponsiveIframes: function($container) {
    var that = this;
    this.$container = $container;
    this.$iframes = $("iframe[src^='//player.vimeo.com'], iframe[src^='//www.youtube.com']");
    this.$iframes.each(function() {
      if (!$(this).data('aspectRatio')) {
        var height = this.height || $(this).height(),
            width = this.width || $(this).width();
        $(this)
          .data('aspectRatio', height / width)
          .removeAttr('height')
          .removeAttr('width');
      }
    });
    this.windowResize();
    //Prevents wrong container width calculation
    setTimeout(function(){
      that.updateIframeSize();
    },0);
  },

  windowResize: function() {
    var that = this;
    $(window).resize(function() {
      that.updateIframeSize();
    });
  },

  updateIframeSize: function() {
    var newWidth = this.$container.width();
    if (newWidth) {
      this.$iframes.each(function() {
        var $el = $(this);
        $el
          .width(newWidth)
          .height(newWidth * $el.data('aspectRatio'));
      });
    } else {
      this.$iframes.each(function() {
        $(this)
          .removeAttr('height')
          .removeAttr('width');
      });
    }
  }

}
<|endoftext|>


<commit_before>Slipmat.Models.Record = Backbone.Model.extend({

  urlRoot: "api/records",

  parse: function (payload) {
    var record = this;

    var associations = [
      "artist",
      "label"
    ];

    var attributes = [
      "image",
      "country",
      "tracks",
      "comments",
      "contributors",
      "in_collection",
      "in_wantlist"
    ];

    associations.forEach(function (association) {
      if (payload[association]) {
        record[association]().set(payload[association]);
        delete payload[association];
      }
    });

    attributes.forEach(function (attribute) {
      if (payload[attribute]) {
        record["_" + attribute] = payload[attribute];
        delete payload[attribute];
      }
    });

    return payload;
  },

  image: function () {
    if (!this._image) {
      this._image = Slipmat.defaultRecordImg;
    }
    return this._image;
  },

  artist: function () {
    if (!this._artist) {
      this._artist = new Slipmat.Models.Artist();
    }
    return this._artist;
  },

  label: function () {
    if (!this._label) {
      this._label = new Slipmat.Models.Label();
    }
    return this._label;
  },

  country: function () {
    this._country = this._country || [];
    return this._country;
  },

  tracks: function () {
    this._tracks = this._tracks || [];
    return this._tracks;
  },

  comments: function () {
    this._comments = this._comments || [];
    return this._comments;
  },

  contributors: function () {
    this._contributors = this._contributors || [];
    return this._contributors;
  },

  inCollection: function () {
    this._in_collection = this._in_collection || [];
    return this._in_collection;
  },

  inWantlist: function () {
    this._in_wantlist = this._in_wantlist || [];
    return this._in_wantlist;
  }

});
<commit_msg>Integrate genre association with Backbone Record model<commit_after>Slipmat.Models.Record = Backbone.Model.extend({

  urlRoot: "api/records",

  parse: function (payload) {
    var record = this;

    var associations = [
      "artist",
      "label"
    ];

    var attributes = [
      "image",
      "country",
      "genres",
      "tracks",
      "comments",
      "contributors",
      "in_collection",
      "in_wantlist"
    ];

    associations.forEach(function (association) {
      if (payload[association]) {
        record[association]().set(payload[association]);
        delete payload[association];
      }
    });

    attributes.forEach(function (attribute) {
      if (payload[attribute]) {
        record["_" + attribute] = payload[attribute];
        delete payload[attribute];
      }
    });

    return payload;
  },

  image: function () {
    if (!this._image) {
      this._image = Slipmat.defaultRecordImg;
    }
    return this._image;
  },

  artist: function () {
    if (!this._artist) {
      this._artist = new Slipmat.Models.Artist();
    }
    return this._artist;
  },

  label: function () {
    if (!this._label) {
      this._label = new Slipmat.Models.Label();
    }
    return this._label;
  },

  country: function () {
    this._country = this._country || [];
    return this._country;
  },

  genres: function () {
    this._genres = this._genres || [];
    return this._genres;
  },

  tracks: function () {
    this._tracks = this._tracks || [];
    return this._tracks;
  },

  comments: function () {
    this._comments = this._comments || [];
    return this._comments;
  },

  contributors: function () {
    this._contributors = this._contributors || [];
    return this._contributors;
  },

  inCollection: function () {
    this._in_collection = this._in_collection || [];
    return this._in_collection;
  },

  inWantlist: function () {
    this._in_wantlist = this._in_wantlist || [];
    return this._in_wantlist;
  }

});
<|endoftext|>


<commit_before>(function(Modules) {
  "use strict";

  var queues = {};
  var dd = new diffDOM();
  var timer;

  var getRenderer = $component => response => function() {
    var component = $component.get(0);
    var updated = $(response[$component.data('key')]).get(0);
    var diff = dd.diff(component, updated);
    dd.apply(
      component, diff
    );
  };

  var getQueue = resource => (
    queues[resource] = queues[resource] || []
  );

  var flushQueue = function(queue, response) {
    while(queue.length) queue.shift()(response);
  };

  var clearQueue = queue => (queue.length = 0);

  var poll = function(renderer, resource, queue, interval) {

    if (queue.push(renderer) === 1) $.ajax(
      resource
    ).done(
      response => flushQueue(queue, response)
    ).fail(
      () => clearQueue(queue)
    );

    timer = setTimeout(
      () => poll(...arguments), interval
    );

  };

  Modules.UpdateContent = function() {

    this.start = component => poll(
      getRenderer($(component)),
      $(component).data('resource'),
      getQueue($(component).data('resource')),
      ($(component).data('interval-seconds') || 1.5) * 1000
    );

  };

})(window.GOVUK.Modules);
<commit_msg>Revert "Stop AJAX updater consuming ever-increasing memory"<commit_after>(function(Modules) {
  "use strict";

  var queues = {};
  var dd = new diffDOM();

  var getRenderer = $component => response => dd.apply(
    $component.get(0),
    dd.diff($component.get(0), $(response[$component.data('key')]).get(0))
  );

  var getQueue = resource => (
    queues[resource] = queues[resource] || []
  );

  var flushQueue = function(queue, response) {
    while(queue.length) queue.shift()(response);
  };

  var clearQueue = queue => (queue.length = 0);

  var poll = function(renderer, resource, queue, interval) {

    if (queue.push(renderer) === 1) $.ajax(
      resource
    ).done(
      response => flushQueue(queue, response)
    ).fail(
      () => clearQueue(queue)
    );

    setTimeout(
      () => poll(...arguments), interval
    );

  };

  Modules.UpdateContent = function() {

    this.start = component => poll(
      getRenderer($(component)),
      $(component).data('resource'),
      getQueue($(component).data('resource')),
      ($(component).data('interval-seconds') || 1.5) * 1000
    );

  };

})(window.GOVUK.Modules);
<|endoftext|>


<commit_before>/*global window: true, $: true */

/**
 * bootstrapped kanso code,
 * required before the commonjs environment is available.
 */

(function (exports) {

    exports.moduleCache = {};

    exports.getBaseURL = function () {
        var re = new RegExp('(.*\\/_rewrite).*$');
        var match = re.exec(window.location.pathname);
        if (match) {
            return match[1];
        }
        return '';
    };

    exports.getURL = function () {
        if (window.location.hash) {
            return window.location.hash.substr(1);
        }
        var re = new RegExp('\\/_rewrite(.*)$');
        var match = re.exec(window.location.pathname);
        if (match) {
            return match[1] || '/';
        }
        return window.location.pathname || '/';
    };

    exports.normalizePath = function (p) {
        var path = [];
        var parts = p.split('/');
        for (var i = 0; i < parts.length; i += 1) {
            if (parts[i] === '..') {
                path.pop();
            }
            else if (parts[i] !== '.') {
                path.push(parts[i]);
            }
        }
        return path.join('/');
    };

    exports.getPropertyPath = function (obj, p) {
        // normalize to remove unessecary . and .. from paths
        var parts = exports.normalizePath(p).split('/');

        // if path is empty, return the root object
        if (!p) {
            return obj;
        }

        // loop through all parts of the path, throwing an exception
        // if a property doesn't exist
        var a = obj;
        for (var i = 0; i < parts.length; i += 1) {
            var x = parts[i];
            if (a[x] === undefined) {
                throw new Error('Invalid path: ' + p);
            }
            a = a[x];
        }
        return a;
    };

    exports.require = function (path) {
        if (!exports.design_doc) {
            throw new Error('no design doc loaded');
        }
        // TODO: normalize path after resolving relative to current module
        if (!exports.moduleCache[path]) {
            var module = {exports: {}};
            var fn = eval('(function (module, exports, require) {' +
                exports.getPropertyPath(exports.design_doc, path) +
            '});');
            // TODO: create require with current path defined in closure,
            // instead of passing kanso.require
            fn(module, module.exports, exports.require);
            exports.moduleCache[path] = module.exports;
        }
        return exports.moduleCache[path];
    };

    if (typeof require === 'undefined') {
        // make require available globally, unless already in a commonjs
        // environment
        this.require = exports.require;
    }

    exports.init = function () {
        // fetch design_doc and handle current URL
        $.getJSON(exports.getBaseURL() + '/_designdoc', function (data) {
            exports.design_doc = data;

            // load the rest of the kanso module
            var kanso = exports.require('kanso');
            for (var k in kanso) {
                if (kanso.hasOwnProperty(k)) {
                    exports[k] = kanso[k];
                }
            }

            // if using a URL with hash-state, but client supports replaceState,
            // then switch to replaceState instead.
            if (window.location.hash && window.history.replaceState) {
                window.history.replaceState(
                    {}, window.title, exports.getBaseURL() + exports.getURL()
                );
            }

            exports.handle(exports.design_doc, exports.getURL());

            $('a').live('click', function (ev) {
                var url = $(this).attr('href');
                // TODO: test for external / internal urls
                ev.preventDefault();
                exports.handle(exports.design_doc, url);
                exports.setURL(url);
            });

            window.onpopstate = function (ev) {
                exports.handle(exports.design_doc, exports.getURL());
            };
        });
    };

}((typeof exports === 'undefined') ? this.kanso = {}: module.exports));
<commit_msg>create require functions in context of current module<commit_after>/*global window: true, $: true */

/**
 * bootstrapped kanso code,
 * required before the commonjs environment is available.
 */

(function (exports) {

    exports.moduleCache = {};

    exports.getBaseURL = function () {
        var re = new RegExp('(.*\\/_rewrite).*$');
        var match = re.exec(window.location.pathname);
        if (match) {
            return match[1];
        }
        return '';
    };

    exports.getURL = function () {
        if (window.location.hash) {
            return window.location.hash.substr(1);
        }
        var re = new RegExp('\\/_rewrite(.*)$');
        var match = re.exec(window.location.pathname);
        if (match) {
            return match[1] || '/';
        }
        return window.location.pathname || '/';
    };

    exports.normalizePath = function (p) {
        var path = [];
        var parts = p.split('/');
        for (var i = 0; i < parts.length; i += 1) {
            if (parts[i] === '..') {
                path.pop();
            }
            else if (parts[i] !== '.') {
                path.push(parts[i]);
            }
        }
        return path.join('/');
    };

    exports.getPropertyPath = function (obj, p) {
        // normalize to remove unessecary . and .. from paths
        var parts = exports.normalizePath(p).split('/');

        // if path is empty, return the root object
        if (!p) {
            return obj;
        }

        // loop through all parts of the path, throwing an exception
        // if a property doesn't exist
        var a = obj;
        for (var i = 0; i < parts.length; i += 1) {
            var x = parts[i];
            if (a[x] === undefined) {
                throw new Error('Invalid path: ' + p);
            }
            a = a[x];
        }
        return a;
    };

    exports.createRequire = function (current) {
        return function (target) {
            if (!exports.design_doc) {
                throw new Error('no design doc loaded');
            }
            var path;
            if (target.charAt(0) === '.') {
                path = exports.normalizePath(current + '/' + target);
            }
            else {
                path = exports.normalizePath(target);
            }
            if (!exports.moduleCache[path]) {
                var module = {exports: {}};
                var fn = eval('(function (module, exports, require) {' +
                    exports.getPropertyPath(exports.design_doc, path) +
                '});');
                fn(module, module.exports, exports.createRequire(path));
                exports.moduleCache[path] = module.exports;
            }
            return exports.moduleCache[path];
        };
    };

    if (typeof require === 'undefined') {
        // make require available globally, unless already in a commonjs
        // environment
        this.require = exports.createRequire('');
    }

    exports.init = function () {
        // fetch design_doc and handle current URL
        $.getJSON(exports.getBaseURL() + '/_designdoc', function (data) {
            exports.design_doc = data;

            // load the rest of the kanso module
            var kanso = require('kanso');
            for (var k in kanso) {
                if (kanso.hasOwnProperty(k)) {
                    exports[k] = kanso[k];
                }
            }

            // if using a URL with hash-state, but client supports replaceState,
            // then switch to replaceState instead.
            if (window.location.hash && window.history.replaceState) {
                window.history.replaceState(
                    {}, window.title, exports.getBaseURL() + exports.getURL()
                );
            }

            exports.handle(exports.design_doc, exports.getURL());

            $('a').live('click', function (ev) {
                var url = $(this).attr('href');
                // TODO: test for external / internal urls
                ev.preventDefault();
                exports.handle(exports.design_doc, url);
                exports.setURL(url);
            });

            window.onpopstate = function (ev) {
                exports.handle(exports.design_doc, exports.getURL());
            };
        });
    };

}((typeof exports === 'undefined') ? this.kanso = {}: module.exports));
<|endoftext|>


<commit_before>function AnnotationsEventsController(annotations_controller) {

    this.DUMMY_TOOL = 'dummy_tool';
    this.IMAGE_MARKING_TOOL = 'image_marker';

    this.annotation_controller = annotations_controller;
    this.initialized_tools = {};

    this._bind_switch = function(switch_id, tool_label) {
        $("#" + switch_id).bind(
            'click',
            {'events_controller': this, 'tool_label': tool_label},
            function(event) {
                event.data.events_controller.activateTool(event.data.tool_label);
            }
        );
    };

    // Create a tool that simply ignores mouse events, this will be used, for example, to avoid
    // events propagation when capturing events on Shapes
    this.initializeDummyTool = function() {
        if (! (this.DUMMY_TOOL in this.initialized_tools)) {
            this.initialized_tools[this.DUMMY_TOOL] = new paper.Tool();
        }
    };

    this.initializeImageMarkingTool = function(marker_size, markers_limit, switch_id) {
        // by default, initialize dummy tool
        this.initializeDummyTool();

        if(! (this.IMAGE_MARKING_TOOL in this.initialized_tools)) {

            AnnotationsController.prototype.markers_counter = 0;

            if ((typeof markers_limit !== 'undefined') || (markers_limit > 0)) {
                AnnotationsController.prototype.max_markers_count = markers_limit;
            } else {
                AnnotationsController.prototype.max_markers_count = 0;
            }

            AnnotationsController.prototype._check_markers_limit = function() {
                if (this.max_markers_count > 0 && (this.markers_counter >= this.max_markers_count))
                    return false;
                return true;
            };

            AnnotationsController.prototype.removeMarker = function(marker_id) {
                var deleted = this.deleteShape(marker_id);
                if (deleted === true) {
                    this.markers_counter -= 1;
                }
            };

            AnnotationsController.prototype.addMarker = function(event) {
                var add_new_marker = this._check_markers_limit();
                if (add_new_marker === true) {
                    console.log('Adding marker');
                    var img_x = event.point.x + this.x_offset;
                    var img_y = event.point.y + this.y_offset;
                    var shape_id = this._getShapeId('marker');
                    this.drawCircle(shape_id, img_x, img_y, event.marker_radius, undefined, true);
                    this.markers_counter += 1;
                    $(document).trigger('marker_created', [shape_id]);
                }
            };

            var marking_tool = new paper.Tool();

            marking_tool.annotations_controller = this.annotation_controller;
            marking_tool.marker_size = marker_size;

            marking_tool.onMouseDown = function(event) {
                event.marker_radius = this.marker_size / 2;
                this.annotations_controller.addMarker(event);
            };

            this.initialized_tools[this.IMAGE_MARKING_TOOL] = marking_tool;

            if (typeof switch_id !== 'undefined') {
                this._bind_switch(switch_id, this.IMAGE_MARKING_TOOL);
            }
        } else {
            console.warn('Tool "' + this.IMAGE_MARKING_TOOL + '" already initialized');
        }
    };

    this.activateTool = function(tool_label, disable_events_on_shapes) {
        if (tool_label in this.initialized_tools) {
            var sh_ev_off = (typeof disable_events_on_shapes === 'undefined') ? true : disable_events_on_shapes;
            if (sh_ev_off === true)
                this.annotation_controller.disableEventsOnShapes();
            var tool = this.initialized_tools[tool_label];
            tool.activate();
            this.annotation_controller.enableMouseEvents();
        } else {
            console.warn('Tool ' + tool_label + ' not initialized');
        }
    };
}
<commit_msg>trigger an event when a marker is deleted<commit_after>function AnnotationsEventsController(annotations_controller) {

    this.DUMMY_TOOL = 'dummy_tool';
    this.IMAGE_MARKING_TOOL = 'image_marker';

    this.annotation_controller = annotations_controller;
    this.initialized_tools = {};

    this._bind_switch = function(switch_id, tool_label) {
        $("#" + switch_id).bind(
            'click',
            {'events_controller': this, 'tool_label': tool_label},
            function(event) {
                event.data.events_controller.activateTool(event.data.tool_label);
            }
        );
    };

    // Create a tool that simply ignores mouse events, this will be used, for example, to avoid
    // events propagation when capturing events on Shapes
    this.initializeDummyTool = function() {
        if (! (this.DUMMY_TOOL in this.initialized_tools)) {
            this.initialized_tools[this.DUMMY_TOOL] = new paper.Tool();
        }
    };

    this.initializeImageMarkingTool = function(marker_size, markers_limit, switch_id) {
        // by default, initialize dummy tool
        this.initializeDummyTool();

        if(! (this.IMAGE_MARKING_TOOL in this.initialized_tools)) {

            AnnotationsController.prototype.markers_counter = 0;

            if ((typeof markers_limit !== 'undefined') || (markers_limit > 0)) {
                AnnotationsController.prototype.max_markers_count = markers_limit;
            } else {
                AnnotationsController.prototype.max_markers_count = 0;
            }

            AnnotationsController.prototype._check_markers_limit = function() {
                if (this.max_markers_count > 0 && (this.markers_counter >= this.max_markers_count))
                    return false;
                return true;
            };

            AnnotationsController.prototype.removeMarker = function(marker_id) {
                var deleted = this.deleteShape(marker_id);
                if (deleted === true) {
                    this.markers_counter -= 1;
                    $(document).trigger('marker_deleted', [marker_id]);
                }
            };

            AnnotationsController.prototype.addMarker = function(event) {
                var add_new_marker = this._check_markers_limit();
                if (add_new_marker === true) {
                    console.log('Adding marker');
                    var img_x = event.point.x + this.x_offset;
                    var img_y = event.point.y + this.y_offset;
                    var shape_id = this._getShapeId('marker');
                    this.drawCircle(shape_id, img_x, img_y, event.marker_radius, undefined, true);
                    this.markers_counter += 1;
                    $(document).trigger('marker_created', [shape_id]);
                }
            };

            var marking_tool = new paper.Tool();

            marking_tool.annotations_controller = this.annotation_controller;
            marking_tool.marker_size = marker_size;

            marking_tool.onMouseDown = function(event) {
                event.marker_radius = this.marker_size / 2;
                this.annotations_controller.addMarker(event);
            };

            this.initialized_tools[this.IMAGE_MARKING_TOOL] = marking_tool;

            if (typeof switch_id !== 'undefined') {
                this._bind_switch(switch_id, this.IMAGE_MARKING_TOOL);
            }
        } else {
            console.warn('Tool "' + this.IMAGE_MARKING_TOOL + '" already initialized');
        }
    };

    this.activateTool = function(tool_label, disable_events_on_shapes) {
        if (tool_label in this.initialized_tools) {
            var sh_ev_off = (typeof disable_events_on_shapes === 'undefined') ? true : disable_events_on_shapes;
            if (sh_ev_off === true)
                this.annotation_controller.disableEventsOnShapes();
            var tool = this.initialized_tools[tool_label];
            tool.activate();
            this.annotation_controller.enableMouseEvents();
        } else {
            console.warn('Tool ' + tool_label + ' not initialized');
        }
    };
}
<|endoftext|>


<commit_before>App.LoadingWidgetView = Em.View.extend({
  template: Ember.Handlebars.compile('Loading{{view._ticker}}'),

  tickerChar: '.',
  tickerLength: 3,

  _ticker: '',

  didInsertElement: Em.aliasMethod('schedule'),
  schedule: function(){
    Ember.run.later(this,
      Em.$.proxy(this.tick, this),
      750
    );
  },

  tick: function(){
    if (this.get('isDestroyed') || this.get('isDestroying')){ return; }

    var _ticker = this.get('_ticker'),
        tickerLength = this.get('tickerLength'),
        tickerChar = this.get('tickerChar'),

        state = (_ticker.length + 1) % (tickerLength + 1),
        ticker = Array(state + 1).join(tickerChar);

    this.set('_ticker', ticker);
    this.schedule();
  },
});
<commit_msg>Cleanup disjoined git mv<commit_after><|endoftext|>


<commit_before>/* eslint-disable */
import React from 'react';
import { configure, addDecorator, addParameters } from '@storybook/react';
import { withNotes } from '@storybook/addon-notes';
import { withKnobs } from '@storybook/addon-knobs';
import { INITIAL_VIEWPORTS } from '@storybook/addon-viewport';

import DataUtil from '../src/utils/DataUtil';

addParameters({
  viewport: {
    viewports: {
      ...INITIAL_VIEWPORTS,
    },
  },
});

addDecorator(withNotes);
addDecorator(withKnobs);

let data;
try {
  // eslint-disable-next-line global-require, import/no-unresolved
  data = require('../local/blip-input.json');
} catch (e) {
  data = [];
}

const patientId = 'abc123';
const dataUtil = new DataUtil();
dataUtil.addData(data, patientId);

const props = {
  dataUtil,
  patientId,
};

addDecorator(storyFn => (

{storyFn(props)}

));

function loadStories() {
  const context = require.context('../stories', true, /.js$/); // Load .js files in /storybook
  context.keys().forEach(context);
}

configure(loadStories, module);
<commit_msg>Update data stories to use datasets from private export tool<commit_after>/* eslint-disable */
import React from 'react';
import { configure, addDecorator, addParameters } from '@storybook/react';
import { withNotes } from '@storybook/addon-notes';
import { withKnobs } from '@storybook/addon-knobs';
import { INITIAL_VIEWPORTS } from '@storybook/addon-viewport';

import DataUtil from '../src/utils/DataUtil';

addParameters({
  viewport: {
    viewports: {
      ...INITIAL_VIEWPORTS,
    },
  },
});

addDecorator(withNotes);
addDecorator(withKnobs);

let data;
try {
  // eslint-disable-next-line global-require, import/no-unresolved
  data = _.flatten(_.map(require('../local/data.json'), v => v.data));
} catch (e) {
  data = { data: [] };
}

const patientId = 'abc123';
const dataUtil = new DataUtil();
dataUtil.addData(data, patientId);

const props = {
  dataUtil,
  patientId,
};

addDecorator(storyFn => (

{storyFn(props)}

));

function loadStories() {
  const context = require.context('../stories', true, /.js$/); // Load .js files in /storybook
  context.keys().forEach(context);
}

configure(loadStories, module);
<|endoftext|>