<commit_before>var webpack = require('webpack');
var helpers = require('./helpers');

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

/**
 * Webpack Constants
 */
const ENV = process.env.ENV = process.env.NODE_ENV = 'development';
const HMR = helpers.hasProcessFlag('hot');
const METADATA = {
  title: 'Elora',
  baseUrl: '/',
  host: process.env.HOST || 'localhost',
  port: process.env.PORT || 3000,
  ENV: ENV,
  HMR: HMR
};

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

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

  // Switch loaders to debug mode.
  //
  // See: http://webpack.github.io/docs/configuration.html#debug
  debug: true,

  // Developer tool to enhance debugging
  //
  // See: http://webpack.github.io/docs/configuration.html#devtool
  // See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps
  devtool: 'cheap-module-eval-source-map',

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

  // The entry point for the bundle
  // Our Angular.js app
  //
  // See: http://webpack.github.io/docs/configuration.html#entry
  entry: {
    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'main': './src/main.browser.ts',

  },

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

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

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

  },

  // Options affecting the output of the compilation.
  //
  // See: http://webpack.github.io/docs/configuration.html#output
  output: {
    // The output directory as absolute path (required).
    //
    // See: http://webpack.github.io/docs/configuration.html#output-path
    path: helpers.root('build'),

    // Specifies the name of each output file on disk.
    // IMPORTANT: You must not specify an absolute path here!
    //
    // See: http://webpack.github.io/docs/configuration.html#output-filename
    filename: '[name].bundle.js',

    // The filename of the SourceMaps for the JavaScript files.
    // They are inside the output.path directory.
    //
    // See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
    sourceMapFilename: '[name].map',

    // The filename of non-entry chunks as relative path
    // inside the output.path directory.
    //
    // See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
    chunkFilename: '[id].chunk.js'

  },

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

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

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

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

    ],

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

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

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

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

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

      //Load CSS
      {test: /\.css$/, exclude: /node_modules/, loader: 'style-loader!css-loader'},
      {test: /\.scss$/, exclude: /node_modules/, loader: 'style-loader!css-loader!sass-loader'}

    ]

  },

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

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

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

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

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

    // Plugin: DefinePlugin
    // Description: Define free variables.
    // Useful for having development builds with debug logging or adding global constants.
    //
    // Environment helpers
    //
    // See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
    // NOTE: when adding more properties make sure you include them in custom-typings.d.ts
    new webpack.DefinePlugin({'ENV': JSON.stringify(METADATA.ENV), 'HMR': HMR})

  ],

  // Static analysis linter for TypeScript advanced options configuration
  // Description: An extensible linter for the TypeScript language.
  //
  // See: https://github.com/wbuchwalter/tslint-loader
  tslint: {
    emitErrors: false,
    failOnHint: false,
    resourcePath: 'src'
  },

  // Webpack Development Server configuration
  // Description: The webpack-dev-server is a little node.js Express server.
  // The server emits information about the compilation state to the client,
  // which reacts to those events.
  //
  // See: https://webpack.github.io/docs/webpack-dev-server.html
  devServer: {
    port: METADATA.port,
    host: METADATA.host,
    historyApiFallback: true,
    watchOptions: {
      aggregateTimeout: 300,
      poll: 1000
    },
    proxy: {
      '/v1/*' : 'http://localhost:8080',
    }
  },

  // Include polyfills or mocks for various node stuff
  // Description: Node configuration
  //
  // See: https://webpack.github.io/docs/configuration.html#node
  node: {
    global: 'window',
    process: true,
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false
  }
};
<commit_msg>dev build fix<commit_after>var webpack = require('webpack');
var helpers = require('./helpers');

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

/**
 * Webpack Constants
 */
const ENV = process.env.ENV = process.env.NODE_ENV = 'development';
const HMR = helpers.hasProcessFlag('hot');
const METADATA = {
  title: 'Elora',
  baseUrl: '/',
  host: process.env.HOST || 'localhost',
  port: process.env.PORT || 3000,
  ENV: ENV,
  HMR: HMR
};

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

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

  // Switch loaders to debug mode.
  //
  // See: http://webpack.github.io/docs/configuration.html#debug
  debug: true,

  // Developer tool to enhance debugging
  //
  // See: http://webpack.github.io/docs/configuration.html#devtool
  // See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps
  devtool: 'cheap-module-eval-source-map',

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

  // The entry point for the bundle
  // Our Angular.js app
  //
  // See: http://webpack.github.io/docs/configuration.html#entry
  entry: {
    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'main': './src/main.browser.ts',

  },

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

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

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

  },

  // Options affecting the output of the compilation.
  //
  // See: http://webpack.github.io/docs/configuration.html#output
  output: {
    // The output directory as absolute path (required).
    //
    // See: http://webpack.github.io/docs/configuration.html#output-path
    path: helpers.root('build'),

    // Specifies the name of each output file on disk.
    // IMPORTANT: You must not specify an absolute path here!
    //
    // See: http://webpack.github.io/docs/configuration.html#output-filename
    filename: '[name].bundle.js',

    // The filename of the SourceMaps for the JavaScript files.
    // They are inside the output.path directory.
    //
    // See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
    sourceMapFilename: '[name].map',

    // The filename of non-entry chunks as relative path
    // inside the output.path directory.
    //
    // See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
    chunkFilename: '[id].chunk.js'

  },

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

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

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

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

    ],

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

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

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

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

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

      //Load CSS
      {test: /\.css$/, exclude: /node_modules/, loader: 'style-loader!css-loader'},
      {test: /\.scss$/, exclude: /node_modules/, loader: 'style-loader!css-loader!sass-loader'}

    ]

  },

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

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

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

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

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

    // Plugin: DefinePlugin
    // Description: Define free variables.
    // Useful for having development builds with debug logging or adding global constants.
    //
    // Environment helpers
    //
    // See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
    // NOTE: when adding more properties make sure you include them in custom-typings.d.ts
    new webpack.DefinePlugin({'ENV': JSON.stringify(METADATA.ENV), 'HMR': HMR})

  ],

  // Static analysis linter for TypeScript advanced options configuration
  // Description: An extensible linter for the TypeScript language.
  //
  // See: https://github.com/wbuchwalter/tslint-loader
  tslint: {
    emitErrors: false,
    failOnHint: false,
    resourcePath: 'src'
  },

  // Webpack Development Server configuration
  // Description: The webpack-dev-server is a little node.js Express server.
  // The server emits information about the compilation state to the client,
  // which reacts to those events.
  //
  // See: https://webpack.github.io/docs/webpack-dev-server.html
  devServer: {
    port: METADATA.port,
    host: METADATA.host,
    historyApiFallback: true,
    watchOptions: {
      aggregateTimeout: 300,
      poll: 1000
    },
    proxy: {
      '/v1/*' : 'http://localhost:8080',
    }
  },

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


<commit_before>const helpers = require('./helpers');
const path = require('path');
const webpackMerge = require('webpack-merge'); // used to merge webpack configs
const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev

/**
 * Webpack Plugins
 */
const DefinePlugin = require('webpack/lib/DefinePlugin');
const NamedModulesPlugin = require('webpack/lib/NamedModulesPlugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');

/**
 * Webpack Constants
 */
const ENV = process.env.ENV = process.env.NODE_ENV = 'development';
const HOST = process.env.HOST || 'localhost';
const PORT = process.env.PORT || 3000;
const HMR = helpers.hasProcessFlag('hot');
const METADATA = webpackMerge(commonConfig({env: ENV}).metadata, {
  host: HOST,
  port: PORT,
  ENV: ENV,
  HMR: HMR
});
// const distPath = 'dist'
const distPath = '../Store.UI'
/**
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = function (options) {
  return webpackMerge(commonConfig({env: ENV}), {

    /**
     * Developer tool to enhance debugging
     *
     * See: http://webpack.github.io/docs/configuration.html#devtool
     * See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps
     */
    devtool: 'cheap-module-source-map',

    /**
     * Options affecting the output of the compilation.
     *
     * See: http://webpack.github.io/docs/configuration.html#output
     */
    output: {

      /**
       * The output directory as absolute path (required).
       *
       * See: http://webpack.github.io/docs/configuration.html#output-path
       */
      path: helpers.root(distPath),

      /**
       * Specifies the name of each output file on disk.
       * IMPORTANT: You must not specify an absolute path here!
       *
       * See: http://webpack.github.io/docs/configuration.html#output-filename
       */
      filename: 'app/[name].bundle.js',

      /**
       * The filename of the SourceMaps for the JavaScript files.
       * They are inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
       */
      sourceMapFilename: 'app/[name].map',

      /** The filename of non-entry chunks as relative path
       * inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
       */
      chunkFilename: 'app/[id].chunk.js',

      library: 'ac_[name]',
      libraryTarget: 'var',
    },

    plugins: [

      /**
       * Plugin: DefinePlugin
       * Description: Define free variables.
       * Useful for having development builds with debug logging or adding global constants.
       *
       * Environment helpers
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
       */
      // NOTE: when adding more properties, make sure you include them in custom-typings.d.ts
      new DefinePlugin({
        'ENV': JSON.stringify(METADATA.ENV),
        'HMR': METADATA.HMR,
        'process.env': {
          'ENV': JSON.stringify(METADATA.ENV),
          'NODE_ENV': JSON.stringify(METADATA.ENV),
          'HMR': METADATA.HMR,
        }
      }),

      /**
       * Plugin: NamedModulesPlugin (experimental)
       * Description: Uses file names as module name.
       *
       * See: https://github.com/webpack/webpack/commit/a04ffb928365b19feb75087c63f13cadfc08e1eb
       */
      new NamedModulesPlugin(),

      /**
       * Plugin LoaderOptionsPlugin (experimental)
       *
       * See: https://gist.github.com/sokra/27b24881210b56bbaff7
       */
      new LoaderOptionsPlugin({
        debug: true,
        options: {
          context: helpers.root('src'),
          output: {
            path: helpers.root(distPath)
          },

          /**
           * Static analysis linter for TypeScript advanced options configuration
           * Description: An extensible linter for the TypeScript language.
           *
           * See: https://github.com/wbuchwalter/tslint-loader
           */
          tslint: {
            emitErrors: false,
            failOnHint: false,
            resourcePath: 'src'
          }
        }
      })
    ],

    /**
     * Webpack Development Server configuration
     * Description: The webpack-dev-server is a little node.js Express server.
     * The server emits information about the compilation state to the client,
     * which reacts to those events.
     *
     * See: https://webpack.github.io/docs/webpack-dev-server.html
     */
    devServer: {
      port: METADATA.port,
      host: METADATA.host,
      historyApiFallback: {
        index: '/index.html'
      },
      watchOptions: {
        aggregateTimeout: 300,
        poll: 1000
      },
      outputPath: helpers.root(distPath)
    },

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

  });
};
<commit_msg>изменил путь билда проекта<commit_after>const helpers = require('./helpers');
const path = require('path');
const webpackMerge = require('webpack-merge'); // used to merge webpack configs
const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev

/**
 * Webpack Plugins
 */
const DefinePlugin = require('webpack/lib/DefinePlugin');
const NamedModulesPlugin = require('webpack/lib/NamedModulesPlugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');

/**
 * Webpack Constants
 */
const ENV = process.env.ENV = process.env.NODE_ENV = 'development';
const HOST = process.env.HOST || 'localhost';
const PORT = process.env.PORT || 3000;
const HMR = helpers.hasProcessFlag('hot');
const METADATA = webpackMerge(commonConfig({env: ENV}).metadata, {
  host: HOST,
  port: PORT,
  ENV: ENV,
  HMR: HMR
});
// const distPath = 'dist'
const distPath = '../Store.UI/Content/admin'
/**
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = function (options) {
  return webpackMerge(commonConfig({env: ENV}), {

    /**
     * Developer tool to enhance debugging
     *
     * See: http://webpack.github.io/docs/configuration.html#devtool
     * See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps
     */
    devtool: 'cheap-module-source-map',

    /**
     * Options affecting the output of the compilation.
     *
     * See: http://webpack.github.io/docs/configuration.html#output
     */
    output: {

      /**
       * The output directory as absolute path (required).
       *
       * See: http://webpack.github.io/docs/configuration.html#output-path
       */
      path: helpers.root(distPath),

      /**
       * Specifies the name of each output file on disk.
       * IMPORTANT: You must not specify an absolute path here!
       *
       * See: http://webpack.github.io/docs/configuration.html#output-filename
       */
      filename: 'app/[name].bundle.js',

      /**
       * The filename of the SourceMaps for the JavaScript files.
       * They are inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
       */
      sourceMapFilename: 'app/[name].map',

      /** The filename of non-entry chunks as relative path
       * inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
       */
      chunkFilename: 'app/[id].chunk.js',

      library: 'ac_[name]',
      libraryTarget: 'var',
    },

    plugins: [

      /**
       * Plugin: DefinePlugin
       * Description: Define free variables.
       * Useful for having development builds with debug logging or adding global constants.
       *
       * Environment helpers
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
       */
      // NOTE: when adding more properties, make sure you include them in custom-typings.d.ts
      new DefinePlugin({
        'ENV': JSON.stringify(METADATA.ENV),
        'HMR': METADATA.HMR,
        'process.env': {
          'ENV': JSON.stringify(METADATA.ENV),
          'NODE_ENV': JSON.stringify(METADATA.ENV),
          'HMR': METADATA.HMR,
        }
      }),

      /**
       * Plugin: NamedModulesPlugin (experimental)
       * Description: Uses file names as module name.
       *
       * See: https://github.com/webpack/webpack/commit/a04ffb928365b19feb75087c63f13cadfc08e1eb
       */
      new NamedModulesPlugin(),

      /**
       * Plugin LoaderOptionsPlugin (experimental)
       *
       * See: https://gist.github.com/sokra/27b24881210b56bbaff7
       */
      new LoaderOptionsPlugin({
        debug: true,
        options: {
          context: helpers.root('src'),
          output: {
            path: helpers.root(distPath)
          },

          /**
           * Static analysis linter for TypeScript advanced options configuration
           * Description: An extensible linter for the TypeScript language.
           *
           * See: https://github.com/wbuchwalter/tslint-loader
           */
          tslint: {
            emitErrors: false,
            failOnHint: false,
            resourcePath: 'src'
          }
        }
      })
    ],

    /**
     * Webpack Development Server configuration
     * Description: The webpack-dev-server is a little node.js Express server.
     * The server emits information about the compilation state to the client,
     * which reacts to those events.
     *
     * See: https://webpack.github.io/docs/webpack-dev-server.html
     */
    devServer: {
      port: METADATA.port,
      host: METADATA.host,
      historyApiFallback: {
        index: '/index.html'
      },
      watchOptions: {
        aggregateTimeout: 300,
        poll: 1000
      },
      outputPath: helpers.root(distPath)
    },

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

  });
};
<|endoftext|>


<commit_before>'use strict'
var tape = require('tape')
var txFormat = require('../src/execution/txFormat')
var compiler = require('solc')
var compilerInput = require('../src/helpers/compilerHelper').compilerInput
var executionContext = require('../src/execution/execution-context')

var context
tape('ContractParameters - (TxFormat.buildData) - format input parameters', function (t) {
  var output = compiler.compileStandardWrapper(compilerInput(uintContract))
  output = JSON.parse(output)
  var contract = output.contracts['test.sol']['uintContractTest']
  context = { output, contract }
  var bytecode = '6060604052341561000f57600080fd5b6101058061001e6000396000f300606060405260043610603f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680634b521953146044575b600080fd5b3415604e57600080fd5b608a600480803590602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050608c565b005b8260008190555081600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505050505600a165627a7a72305820d05e3789952dfb3ba575bcb79da62b6e259adbf498ea909031a42b647f7bceb30029'
  t.test('(TxFormat.buildData)', function (st) {
    st.plan(3)
    testWithInput(st, '123123, "0xf7a10e525d4b168f45f74db1b61f63d3e7619ea8", "34"', bytecode + '000000000000000000000000000000000000000000000000000000000001e0f3000000000000000000000000f7a10e525d4b168f45f74db1b61f63d3e7619ea80000000000000000000000000000000000000000000000000000000000000022')
    testWithInput(st, '"123123" , 0xf7a10e525d4b168f45f74db1b61f63d3e7619ea8,   654   ', bytecode + '000000000000000000000000000000000000000000000000000000000001e0f3000000000000000000000000f7a10e525d4b168f45f74db1b61f63d3e7619ea8000000000000000000000000000000000000000000000000000000000000028e')
    // parsing this as javascript number should overflow
    testWithInput(st, '90071992547409910000, 0xf7a10e525d4b168f45f74db1b61f63d3e7619ea8, 0', bytecode + '000000000000000000000000000000000000000000000004e1ffffffffffd8f0000000000000000000000000f7a10e525d4b168f45f74db1b61f63d3e7619ea80000000000000000000000000000000000000000000000000000000000000000')
  })
})

function testWithInput (st, params, expected) {
  txFormat.buildData('uintContractTest', context.contract, context.output.contracts, true, context.contract.abi[0], params, (error, data) => {
    if (error) { return st.fails(error) }
    console.log(data)
    st.equal(data.dataHex, expected)
  }, () => {}, () => {})
}

tape('ContractParameters - (TxFormat.buildData) - link Libraries', function (t) {
  executionContext.setContext('vm')
  var output = compiler.compileStandardWrapper(compilerInput(deploySimpleLib))
  output = JSON.parse(output)
  var contract = output.contracts['test.sol']['testContractLinkLibrary']
  var fakeDeployedContracts = {
    lib1: '0xf7a10e525d4b168f45f74db1b61f63d3e7619e11',
    lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2: '0xf7a10e525d4b168f45f74db1b61f63d3e7619e33',
    testContractLinkLibrary: '0xf7a10e525d4b168f45f74db1b61f63d3e7619e22'
  }
  var udapp = { runTx: (param, callback) => {
    callback(null, {
      result: {
        createdAddress: fakeDeployedContracts[param.data.contractName]
      }
    })
  } } // fake
  context = { output, contract, udapp }
  t.test('(TxFormat.buildData and link library (standard way))', function (st) {
    st.plan(6)
    testLinkLibrary(st, fakeDeployedContracts)
  })
})

function testLinkLibrary (st, fakeDeployedContracts) {
  var deployMsg = ['creation of library test.sol:lib1 pending...',
  'creation of library test.sol:lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2 pending...']
  txFormat.buildData('testContractLinkLibrary', context.contract, context.output.contracts, true, context.contract.abi[0], '', context.udapp
    , (error, data) => {
      if (error) { return st.fails(error) }
      console.log(data)
      var linkedbyteCode = data.dataHex
      var libReference = context.contract.evm.bytecode.linkReferences['test.sol']['lib1']
      st.equal(linkedbyteCode.substr(2 * libReference[0].start, 40), fakeDeployedContracts['lib1'].replace('0x', ''))
      st.equal(linkedbyteCode.substr(2 * libReference[1].start, 40), fakeDeployedContracts['lib1'].replace('0x', ''))

      libReference = context.contract.evm.bytecode.linkReferences['test.sol']['lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2']
      st.equal(linkedbyteCode.substr(2 * libReference[0].start, 40), fakeDeployedContracts['lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2'].replace('0x', ''))
      st.equal(linkedbyteCode.substr(2 * libReference[1].start, 40), fakeDeployedContracts['lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2'].replace('0x', ''))
    }, (msg) => {
      st.equal(msg, deployMsg[0])
      deployMsg.shift()
    }, () => {})
}

var uintContract = `contract uintContractTest {
    uint _tp;
    address _ap;
    function test(uint _t, address _a, uint _i) {
        _tp = _t;
        _ap = _a;
    }
}`

var deploySimpleLib = `pragma solidity ^0.4.4;

library lib1 {
    function getEmpty () {
    }
}

library lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2 {
    function getEmpty () {
    }
}

contract testContractLinkLibrary {
    function get () {
        lib1.getEmpty();
        lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2.getEmpty();
        lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2.getEmpty();
        lib1.getEmpty();
 }
 }`

<commit_msg>fix test<commit_after>'use strict'
var tape = require('tape')
var txFormat = require('../src/execution/txFormat')
var compiler = require('solc')
var compilerInput = require('../src/helpers/compilerHelper').compilerInput
var executionContext = require('../src/execution/execution-context')

var context
tape('ContractParameters - (TxFormat.buildData) - format input parameters', function (t) {
  var output = compiler.compileStandardWrapper(compilerInput(uintContract))
  output = JSON.parse(output)
  var contract = output.contracts['test.sol']['uintContractTest']
  context = { output, contract }
  var bytecode = '6060604052341561000f57600080fd5b6101058061001e6000396000f300606060405260043610603f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680634b521953146044575b600080fd5b3415604e57600080fd5b608a600480803590602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050608c565b005b8260008190555081600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505050505600a165627a7a72305820d05e3789952dfb3ba575bcb79da62b6e259adbf498ea909031a42b647f7bceb30029'
  t.test('(TxFormat.buildData)', function (st) {
    st.plan(3)
    testWithInput(st, '123123, "0xf7a10e525d4b168f45f74db1b61f63d3e7619ea8", "34"', bytecode + '000000000000000000000000000000000000000000000000000000000001e0f3000000000000000000000000f7a10e525d4b168f45f74db1b61f63d3e7619ea80000000000000000000000000000000000000000000000000000000000000022')
    testWithInput(st, '"123123" , 0xf7a10e525d4b168f45f74db1b61f63d3e7619ea8,   654   ', bytecode + '000000000000000000000000000000000000000000000000000000000001e0f3000000000000000000000000f7a10e525d4b168f45f74db1b61f63d3e7619ea8000000000000000000000000000000000000000000000000000000000000028e')
    // parsing this as javascript number should overflow
    testWithInput(st, '90071992547409910000, 0xf7a10e525d4b168f45f74db1b61f63d3e7619ea8, 0', bytecode + '000000000000000000000000000000000000000000000004e1ffffffffffd8f0000000000000000000000000f7a10e525d4b168f45f74db1b61f63d3e7619ea80000000000000000000000000000000000000000000000000000000000000000')
  })
})

function testWithInput (st, params, expected) {
  txFormat.buildData('uintContractTest', context.contract, context.output.contracts, true, context.contract.abi[0], params, (error, data) => {
    if (error) { return st.fails(error) }
    console.log(data)
    st.equal(data.dataHex, expected)
  }, () => {}, () => {})
}

tape('ContractParameters - (TxFormat.buildData) - link Libraries', function (t) {
  executionContext.setContext('vm')
  var output = compiler.compileStandardWrapper(compilerInput(deploySimpleLib))
  output = JSON.parse(output)
  var contract = output.contracts['test.sol']['testContractLinkLibrary']
  var fakeDeployedContracts = {
    lib1: '0xf7a10e525d4b168f45f74db1b61f63d3e7619e11',
    lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2: '0xf7a10e525d4b168f45f74db1b61f63d3e7619e33',
    testContractLinkLibrary: '0xf7a10e525d4b168f45f74db1b61f63d3e7619e22'
  }
  var udapp = { runTx: (param, callback) => {
    callback(null, {
      result: {
        createdAddress: fakeDeployedContracts[param.data.contractName]
      }
    })
  } } // fake
  context = { output, contract, udapp }
  t.test('(TxFormat.buildData and link library (standard way))', function (st) {
    st.plan(6)
    testLinkLibrary(st, fakeDeployedContracts)
  })
})

function testLinkLibrary (st, fakeDeployedContracts) {
  var deployMsg = ['creation of library test.sol:lib1 pending...',
  'creation of library test.sol:lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2 pending...']
  txFormat.buildData('testContractLinkLibrary', context.contract, context.output.contracts, true, context.contract.abi[0], '', (error, data) => {
    if (error) { return st.fails(error) }
    console.log(data)
    var linkedbyteCode = data.dataHex
    var libReference = context.contract.evm.bytecode.linkReferences['test.sol']['lib1']
    st.equal(linkedbyteCode.substr(2 * libReference[0].start, 40), fakeDeployedContracts['lib1'].replace('0x', ''))
    st.equal(linkedbyteCode.substr(2 * libReference[1].start, 40), fakeDeployedContracts['lib1'].replace('0x', ''))

    libReference = context.contract.evm.bytecode.linkReferences['test.sol']['lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2']
    st.equal(linkedbyteCode.substr(2 * libReference[0].start, 40), fakeDeployedContracts['lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2'].replace('0x', ''))
    st.equal(linkedbyteCode.substr(2 * libReference[1].start, 40), fakeDeployedContracts['lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2'].replace('0x', ''))
  }, (msg) => {
    st.equal(msg, deployMsg[0])
    deployMsg.shift()
  }, () => {})
}

var uintContract = `contract uintContractTest {
    uint _tp;
    address _ap;
    function test(uint _t, address _a, uint _i) {
        _tp = _t;
        _ap = _a;
    }
}`

var deploySimpleLib = `pragma solidity ^0.4.4;

library lib1 {
    function getEmpty () {
    }
}

library lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2 {
    function getEmpty () {
    }
}

contract testContractLinkLibrary {
    function get () {
        lib1.getEmpty();
        lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2.getEmpty();
        lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2.getEmpty();
        lib1.getEmpty();
 }
 }`

<|endoftext|>


<commit_before>const fs = require('fs')
const request = require('request')
const FileCookieStore = require('tough-cookie-filestore')
const logger = require('log4js').getLogger()
const Promise = require('bluebird')

const handler = require('./handler')

const { promisify, parseForm, decodeURIForm, encodeURIForm } = handler

/**
 * Request Constructor
 * @param {string} cookiePath cookieJar file path. If undefined, the request won't take any cookie.
 * @param {object} config request config.
 */
function Request(cookiePath, config) {
  const defaultConfig = {
    headers: {
      'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
    },
    gzip: true,
    timeout: 20000,
  }

  const appendConfig = config || {}

  if (cookiePath) {
    const jar = request.jar(new FileCookieStore(cookiePath))
    appendConfig.jar = jar
  }

  this.request = request.defaults(Object.assign(appendConfig, defaultConfig))
  // avoid redirct cycle
  this.maxRedirects = 10
  this.redirects = 0
}

/**
 * Request server with GET method.
 * @param {string} url Request URL.
 * @param {object} params QueryString dictionary object. Axer will automaticlly encode all params value for request.
 * @return {Object} Axer will combine request object and response object and return to developer.
 */
Request.prototype.get = async function(url, params) {
  let _url = url
  if (typeof params === 'object') {
    const qs = encodeURIForm(params)
    _url = `${_url}?${qs}`
  }

  logger.info('GET', _url)
  const res = await promisify(this.request, _url)
  const response = await this.followRedirect(res)
  return response
}

/**
 * Request server with POST method.
 * @param {string} url Request URL.
 * @param {object} form post form. Axer will convert this object to x-www-form-urlencoded formart string.
 * @return {Object} Axer will combine request object and response object and return to developer.
 */
Request.prototype.post = async function(url, form) {
  if (typeof form === 'object') {
    form = decodeURIForm(form)
  }

  if (typeof form === 'string') {
    form = parseForm(form)
  }

  logger.info('POST ', url)
  logger.info('Body:', form)
  const res = await promisify(this.request.post, { url, form })
  const response = await this.followRedirect(res)
  return response
}

/**
 * Download file from server.
 * @param {string} url download url.
 * @param {string} filePath the file's save path.
 * @return {promise} return promise object for conveniently use aync/await.
 */
Request.prototype.download = function(url, filePath) {
  return new Promise((resolve, reject) => {
    if (fs.existsSync(filePath)) {
      resolve(url)
      return
    }
    this.request.get(url)
      .on('response', res => {
        logger.info(`Status: ${res.statusCode}`)
        logger.info(`Content-Type: ${res.headers['content-type']}`)
        logger.info(`Content-Length: ${res.headers['content-length']}`)
      })
      .on('end', () => {
        logger.info(`Download success`)
        resolve(url)
      })
      .on('error', err => {
        logger.error(`Download failed: ${err}`)
        reject(err)
      })
      .pipe(fs.createWriteStream(filePath))
  })
}

Request.prototype.followRedirect = async function (response) {
  if (response.statusCode >= 300 && response.statusCode < 400) {
    if (this.redirects >= this.maxRedirects) {
      throw new Error('Too many redircts, the default max redircts is:' + this.maxRedirects)
    } else {
      this.redirects++
      const url = response.headers.location
      logger.info('Auto Follow:', url)
      const res = await promisify(this.request, url)
      return await this.followRedirect(res)
    }
  } else {
    this.redirects = 0
    return response
  }
}

Request.prototype.upload = function(url, formData) {
  logger.info('POST FormData', url)
  logger.info('Body:', formData)
  const response = promisify(this.request.post, { url, formData })
  return response
}

module.exports = Request
<commit_msg>download can overwrite original file<commit_after>const fs = require('fs')
const request = require('request')
const FileCookieStore = require('tough-cookie-filestore')
const logger = require('log4js').getLogger()
const Promise = require('bluebird')

const handler = require('./handler')

const { promisify, parseForm, decodeURIForm, encodeURIForm } = handler

/**
 * Request Constructor
 * @param {string} cookiePath cookieJar file path. If undefined, the request won't take any cookie.
 * @param {object} config request config.
 */
function Request(cookiePath, config) {
  const defaultConfig = {
    headers: {
      'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
    },
    gzip: true,
    timeout: 20000,
  }

  const appendConfig = config || {}

  if (cookiePath) {
    const jar = request.jar(new FileCookieStore(cookiePath))
    appendConfig.jar = jar
  }

  this.request = request.defaults(Object.assign(appendConfig, defaultConfig))
  // avoid redirct cycle
  this.maxRedirects = 10
  this.redirects = 0
}

/**
 * Request server with GET method.
 * @param {string} url Request URL.
 * @param {object} params QueryString dictionary object. Axer will automaticlly encode all params value for request.
 * @return {Object} Axer will combine request object and response object and return to developer.
 */
Request.prototype.get = async function(url, params) {
  let _url = url
  if (typeof params === 'object') {
    const qs = encodeURIForm(params)
    _url = `${_url}?${qs}`
  }

  logger.info('GET', _url)
  const res = await promisify(this.request, _url)
  const response = await this.followRedirect(res)
  return response
}

/**
 * Request server with POST method.
 * @param {string} url Request URL.
 * @param {object} form post form. Axer will convert this object to x-www-form-urlencoded formart string.
 * @return {Object} Axer will combine request object and response object and return to developer.
 */
Request.prototype.post = async function(url, form) {
  if (typeof form === 'object') {
    form = decodeURIForm(form)
  }

  if (typeof form === 'string') {
    form = parseForm(form)
  }

  logger.info('POST ', url)
  logger.info('Body:', form)
  const res = await promisify(this.request.post, { url, form })
  const response = await this.followRedirect(res)
  return response
}

/**
 * Download file from server.
 * @param {string} url download url.
 * @param {string} filePath the file's save path.
 * @return {promise} return promise object for conveniently use aync/await.
 */
Request.prototype.download = function(url, filePath) {
  return new Promise((resolve, reject) => {
    this.request.get(url)
      .on('response', res => {
        logger.info(`Status: ${res.statusCode}`)
        logger.info(`Content-Type: ${res.headers['content-type']}`)
        logger.info(`Content-Length: ${res.headers['content-length']}`)
      })
      .on('end', () => {
        logger.info(`Download success`)
        resolve(url)
      })
      .on('error', err => {
        logger.error(`Download failed: ${err}`)
        reject(err)
      })
      .pipe(fs.createWriteStream(filePath))
  })
}

Request.prototype.followRedirect = async function (response) {
  if (response.statusCode >= 300 && response.statusCode < 400) {
    if (this.redirects >= this.maxRedirects) {
      throw new Error('Too many redircts, the default max redircts is:' + this.maxRedirects)
    } else {
      this.redirects++
      const url = response.headers.location
      logger.info('Auto Follow:', url)
      const res = await promisify(this.request, url)
      return await this.followRedirect(res)
    }
  } else {
    this.redirects = 0
    return response
  }
}

Request.prototype.upload = function(url, formData) {
  logger.info('POST FormData', url)
  logger.info('Body:', formData)
  const response = promisify(this.request.post, { url, formData })
  return response
}

module.exports = Request
<|endoftext|>


<commit_before>
var changeRole = function(creep, role) {
    if (creep.memory.tenured == true) {
        creep.say('⚡ ' + role);
    } else {
        //creep.memory.role = role;
        creep.say('🔄 ' + role);
        //creep.memory.upgrading = false;
        //require('role.' + role).run(creep, undefined);
    }
}

var roleUpgrader = {
    run: function(creep, stageController) {
        var m = creep.memory;

        if(m.upgrading && creep.carry.energy == 0) {
            m.upgrading = false;
            creep.say('🔄 refill');
	    }
	    if(!m.upgrading && creep.carry.energy == creep.carryCapacity) {
	        m.upgrading = true;
	        creep.say('⚡ upgrade');
	    }

	    if(m.upgrading) {
            if(creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                creep.moveTo(creep.room.controller, {visualizePathStyle: {stroke: '#ffffff'}});
            }
        } else {
            var sources = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => {
                        return (structure.structureType == STRUCTURE_CONTAINER || structure.structureType == STRUCTURE_STORAGE) &&
                            structure.store[RESOURCE_ENERGY] >= 50;
                    }
            });
            if (sources.length === 0) {
                sources = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => {
                        return (structure.structureType == STRUCTURE_EXTENSION || structure.structureType == STRUCTURE_SPAWN) &&
                            structure.energy >= 50;
                    }
                });
            }

            if (sources.length === 0 ) {
                return creep.memory.role = 'lost';
                console.error('upgrader got out of room');
            }
            var err;
            var source = creep.pos.findClosestByRange(sources);
            if (source.structureType == STRUCTURE_CONTAINER || source.structureType == STRUCTURE_STORAGE) {
                err = creep.withdraw(source, RESOURCE_ENERGY);
            } else {
                err = source.transferEnergy(creep, creep.carryCapacity);
            }
            if(err == ERR_NOT_IN_RANGE) {
                creep.moveTo(source, {visualizePathStyle: {stroke: '#ffaa00'}});
            } else if (err == ERR_NOT_ENOUGH_ENERGY) {
                changeRole(creep, 'harvester');
            }
        }
	}
};

module.exports = roleUpgrader;<commit_msg>remove unnecessary code, listing changes<commit_after>var s = require('shared');
var roleUpgrader = {
    run: function(creep, stageController) {
        var m = creep.memory;

        if(m.upgrading && creep.carry.energy === 0) {
            m.upgrading = false;
            creep.say('🔄 refill');
        }
        if(!m.upgrading && creep.carry.energy == creep.carryCapacity) {
            m.upgrading = true;
            creep.say('⚡ upgrade');
        }

        if(m.upgrading) {
            if(creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                creep.moveTo(creep.room.controller, {visualizePathStyle: {stroke: '#ffffff'}});
            }
        } else {
            var sources = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => {
                        return (structure.structureType == STRUCTURE_CONTAINER || structure.structureType == STRUCTURE_STORAGE) &&
                            structure.store[RESOURCE_ENERGY] >= 50;
                    }
            });
            if (sources.length === 0) {
                sources = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => {
                        return (structure.structureType == STRUCTURE_EXTENSION || structure.structureType == STRUCTURE_SPAWN) &&
                            structure.energy >= 50;
                    }
                });
            }

            if (sources.length === 0 ) {
                console.error('upgrader got out of room');
                creep.memory.role = 'lost';
                return;
            }
            var err;
            var source = creep.pos.findClosestByRange(sources);
            if (source.structureType == STRUCTURE_CONTAINER || source.structureType == STRUCTURE_STORAGE) {
                err = creep.withdraw(source, RESOURCE_ENERGY);
            } else {
                err = source.transferEnergy(creep, creep.carryCapacity);
            }
            if(err == ERR_NOT_IN_RANGE) {
                creep.moveTo(source, {visualizePathStyle: {stroke: '#ffaa00'}});
            }
            // else if (err == ERR_NOT_ENOUGH_ENERGY) {
            //     changeRole(creep, 'harvester');
            // }
        }
    }
};

module.exports = roleUpgrader;<|endoftext|>


<commit_before>import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import pkg from './package.json';

export default [
	// browser-friendly UMD build
	{
		input: 'src/cookie.js',
		output: {
			name: 'cookie',
			file: pkg.browser,
			format: 'umd'
		},
		plugins: [
			resolve(), // so Rollup can find `ms`
			commonjs() // so Rollup can convert `ms` to an ES module
		]
	},

	// CommonJS (for Node) and ES module (for bundlers) build.
	// (We could have three entries in the configuration array
	// instead of two, but it's quicker to generate multiple
	// builds from a single configuration where possible, using
	// an array for the `output` option, where we can specify
	// `file` and `format` for each target)
	{
		input: 'src/cookie.js',
		external: ['ms'],
		output: [
			{ file: pkg.main, format: 'cjs' },
			{ file: pkg.module, format: 'es' }
		]
	}
];
<commit_msg>Add UMD minified build in rollup<commit_after>import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import { terser } from 'rollup-plugin-terser';
import pkg from './package.json';

export default [
  // browser-friendly UMD build
  {
    input: 'src/cookie.js',
    output: {
      name: 'cookie',
      file: pkg.browser,
      format: 'umd'
    },
    plugins: [
      resolve(), // so Rollup can find `ms`
      commonjs() // so Rollup can convert `ms` to an ES module
    ]
  },

  // CommonJS (for Node) and ES module (for bundlers) build.
  // (We could have three entries in the configuration array
  // instead of two, but it's quicker to generate multiple
  // builds from a single configuration where possible, using
  // an array for the `output` option, where we can specify
  // `file` and `format` for each target)
  {
    input: 'src/cookie.js',
    external: ['ms'],
    output: [
      { file: pkg.main, format: 'cjs' },
      { file: pkg.module, format: 'es' }
    ]
  },

  // browser-friendly UMD minified build
  {
    input: 'src/cookie.js',
    output: {
      name: 'cookie',
      file: 'dist/cookie.umd.min.js',
      format: 'umd',
    },
    plugins: [
      resolve(), // so Rollup can find `ms`
      commonjs(), // so Rollup can convert `ms` to an ES module
      terser() // mangler/compressor toolkit
    ]
  },
];
<|endoftext|>


<commit_before>import fs from 'fs';
import replace from 'rollup-plugin-replace';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import json from 'rollup-plugin-json';
import sucrase from 'rollup-plugin-sucrase';
import typescript from 'rollup-plugin-typescript';
import pkg from './package.json';

const is_publish = !!process.env.PUBLISH;

const ts_plugin = is_publish
	? typescript({
		include: 'src/**',
		typescript: require('typescript')
	})
	: sucrase({
		transforms: ['typescript']
	});

const external = id => id.startsWith('svelte/');

export default [
	/* compiler.js */
	{
		input: 'src/compiler/index.ts',
		plugins: [
			replace({
				__VERSION__: pkg.version
			}),
			resolve(),
			commonjs({
				include: ['node_modules/**']
			}),
			json(),
			ts_plugin
		],
		output: {
			file: 'compiler.js',
			format: is_publish ? 'umd' : 'cjs',
			name: 'svelte',
			sourcemap: true,
		},
		external: is_publish
			? []
			: id => id === 'acorn' || id === 'magic-string' || id.startsWith('css-tree')
	},

	/* runtime */
	{
		input: `src/runtime/index.ts`,
		output: [
			{
				file: `index.mjs`,
				format: 'esm',
				paths: id => id.startsWith('svelte/') && `${id.replace('svelte', '.')}`
			},
			{
				file: `index.js`,
				format: 'cjs',
				paths: id => id.startsWith('svelte/') && `${id.replace('svelte', '.')}`
			}
		],
		external,
		plugins: [ts_plugin]
	},

	...fs.readdirSync('src/runtime')
		.filter(dir => fs.statSync(`src/runtime/${dir}`).isDirectory())
		.map(dir => ({
			input: `src/runtime/${dir}/index.ts`,
			output: [
				{
					file: `${dir}/index.mjs`,
					format: 'esm',
					paths: id => id.startsWith('svelte/') && `${id.replace('svelte', '..')}`
				},
				{
					file: `${dir}/index.js`,
					format: 'cjs',
					paths: id => id.startsWith('svelte/') && `${id.replace('svelte', '..')}`
				}
			],
			external,
			plugins: [
				ts_plugin,
				dir === 'internal' && {
					generateBundle(options, bundle) {
						const mod = bundle['internal.mjs'];
						if (mod) {
							fs.writeFileSync('src/compile/internal-exports.ts', `// This file is automatically generated\nexport default new Set(${JSON.stringify(mod.exports)});`);
						}
					}
				}
			]
		}))
];
<commit_msg>fix build order<commit_after>import fs from 'fs';
import replace from 'rollup-plugin-replace';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import json from 'rollup-plugin-json';
import sucrase from 'rollup-plugin-sucrase';
import typescript from 'rollup-plugin-typescript';
import pkg from './package.json';

const is_publish = !!process.env.PUBLISH;

const ts_plugin = is_publish
	? typescript({
		include: 'src/**',
		typescript: require('typescript')
	})
	: sucrase({
		transforms: ['typescript']
	});

const external = id => id.startsWith('svelte/');

export default [
	/* runtime */
	{
		input: `src/runtime/index.ts`,
		output: [
			{
				file: `index.mjs`,
				format: 'esm',
				paths: id => id.startsWith('svelte/') && `${id.replace('svelte', '.')}`
			},
			{
				file: `index.js`,
				format: 'cjs',
				paths: id => id.startsWith('svelte/') && `${id.replace('svelte', '.')}`
			}
		],
		external,
		plugins: [ts_plugin]
	},

	...fs.readdirSync('src/runtime')
		.filter(dir => fs.statSync(`src/runtime/${dir}`).isDirectory())
		.map(dir => ({
			input: `src/runtime/${dir}/index.ts`,
			output: [
				{
					file: `${dir}/index.mjs`,
					format: 'esm',
					paths: id => id.startsWith('svelte/') && `${id.replace('svelte', '..')}`
				},
				{
					file: `${dir}/index.js`,
					format: 'cjs',
					paths: id => id.startsWith('svelte/') && `${id.replace('svelte', '..')}`
				}
			],
			external,
			plugins: [
				ts_plugin,
				dir === 'internal' && {
					generateBundle(options, bundle) {
						const mod = bundle['index.mjs'];
						if (mod) {
							fs.writeFileSync('src/compiler/compile/internal-exports.ts', `// This file is automatically generated\nexport default new Set(${JSON.stringify(mod.exports)});`);
						}
					}
				}
			]
		})),

	/* compiler.js */
	{
		input: 'src/compiler/index.ts',
		plugins: [
			replace({
				__VERSION__: pkg.version
			}),
			resolve(),
			commonjs({
				include: ['node_modules/**']
			}),
			json(),
			ts_plugin
		],
		output: {
			file: 'compiler.js',
			format: is_publish ? 'umd' : 'cjs',
			name: 'svelte',
			sourcemap: true,
		},
		external: is_publish
			? []
			: id => id === 'acorn' || id === 'magic-string' || id.startsWith('css-tree')
	}
];
<|endoftext|>


<commit_before>import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import babel from 'rollup-plugin-babel'
import uglify from 'rollup-plugin-uglify'
import vue from 'rollup-plugin-vue'
import packageInfo from './package.json'

// const isDev = process.env.NODE_ENV === 'development'

function baseConfig() {
  return {
    output: {
      format: 'umd',
    },
    plugins: [
      resolve({
        jsnext: true,
        main: true,
        browser: true,
      }),
      commonjs({
        extensions: [
          '.js',
          '.jsx',
          '.json',
          '.vue'
        ],
      }),
    ],
    banner: `/*!\n * Name: ${packageInfo.name}\n * Version: ${packageInfo.version}\n * Author: ${packageInfo.author}\n */`,
    sourcemap: true,
  }
}

let config = baseConfig()
config.input = 'src/index.js'
config.output.file = 'dist/vue-upload-component.js'
config.output.name = 'VueUploadComponent'
config.plugins.push(
  vue({
    autoStyles: false,
    css: true,
  }),
  babel()
)

let configMin = baseConfig()
configMin.input = 'src/index.js'
configMin.output.file = 'dist/vue-upload-component.min.js'
configMin.output.name = 'VueUploadComponent'
configMin.plugins.push(
  vue({
    autoStyles: false,
    css: true,
  }),
  babel(),
  uglify({
    output: {
      comments: /^!/,
    }
  })
)

let configPart = baseConfig()
configPart.input = 'src/index.js'
configPart.output.file = 'dist/vue-upload-component.part.js'
configPart.output.name = 'VueUploadComponent'
configPart.plugins.push(
  vue({
    autoStyles: false,
    css: 'dist/vue-upload-component.part.css',
  }),
  babel()
)

module.exports = [
  config,
  configMin,
  configPart,
]
<commit_msg>fix build<commit_after>import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import babel from 'rollup-plugin-babel'
import uglify from 'rollup-plugin-uglify'
import vue from 'rollup-plugin-vue'
import packageInfo from './package.json'

// const isDev = process.env.NODE_ENV === 'development'

function baseConfig() {
  return {
    output: {
      format: 'umd',
    },
    plugins: [
      resolve({
        jsnext: true,
        main: true,
        browser: true,
      }),
      commonjs({
        extensions: [
          '.js',
          '.jsx',
          '.json',
          // '.vue'
        ],
      }),
    ],
    banner: `/*!\n * Name: ${packageInfo.name}\n * Version: ${packageInfo.version}\n * Author: ${packageInfo.author}\n */`,
    sourcemap: true,
  }
}

let config = baseConfig()
config.input = 'src/index.js'
config.output.file = 'dist/vue-upload-component.js'
config.output.name = 'VueUploadComponent'
config.plugins.push(
  vue({
    autoStyles: false,
    css: true,
  }),
  babel()
)

let configMin = baseConfig()
configMin.input = 'src/index.js'
configMin.output.file = 'dist/vue-upload-component.min.js'
configMin.output.name = 'VueUploadComponent'
configMin.plugins.push(
  vue({
    autoStyles: false,
    css: true,
  }),
  babel(),
  uglify({
    output: {
      comments: /^!/,
    }
  })
)

let configPart = baseConfig()
configPart.input = 'src/index.js'
configPart.output.file = 'dist/vue-upload-component.part.js'
configPart.output.name = 'VueUploadComponent'
configPart.plugins.push(
  vue({
    autoStyles: false,
    css: 'dist/vue-upload-component.part.css',
  }),
  babel()
)

module.exports = [
  config,
  configMin,
  configPart,
]
<|endoftext|>


<commit_before>import resolve from 'rollup-plugin-node-resolve';
import { uglify } from 'rollup-plugin-uglify';

// TODO:
// Look at: https://medium.com/js-imaginea/comparing-bundlers-webpack-rollup-parcel-f8f5dc609cfd

const plugins = [resolve()];

if (process.env.ROLLUP_UGLIFY === 'true') {
    plugins.push(uglify());
}

export default {
    input: 'lib/es6/index.js',
    output: {
        name: 'Floaty',
        format: 'umd',
        globals: {
            'react': 'React',
            'react-dom': 'ReactDOM'
        },
        exports: 'named'
    },
    external: ['react', 'react-dom'],
    plugins
};
<commit_msg>Added another link<commit_after>import resolve from 'rollup-plugin-node-resolve';
import { uglify } from 'rollup-plugin-uglify';

// TODO:
// Look at: https://medium.com/js-imaginea/comparing-bundlers-webpack-rollup-parcel-f8f5dc609cfd
// OR:
// https://www.npmjs.com/package/rollup-plugin-uglify-es

const plugins = [resolve()];

if (process.env.ROLLUP_UGLIFY === 'true') {
    plugins.push(uglify());
}

export default {
    input: 'lib/es6/index.js',
    output: {
        name: 'Floaty',
        format: 'umd',
        globals: {
            'react': 'React',
            'react-dom': 'ReactDOM'
        },
        exports: 'named'
    },
    external: ['react', 'react-dom'],
    plugins
};
<|endoftext|>


<commit_before>import fs from 'fs';
import nodeResolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import memory from 'rollup-plugin-memory';
import babel from 'rollup-plugin-babel';

let babelRc = JSON.parse(fs.readFileSync('./.babelrc'));
babelRc.presets[0][1].modules = false;

let entry = process.env.ENTRY || 'index';

export default {
	entry: 'src/'+entry+'.js',
	exports: 'default',
	useStrict: false,
	external: ['preact'],
	plugins: [
		memory({
			path: 'src/'+entry+'.js',
			contents: "export { default } from './"+entry+"';"
		}),
		nodeResolve({
			skip: ['preact'],
			main: true
		}),
		commonjs(),
		babel({
			babelrc: false,
			comments: false,
			exclude: [],
			presets: babelRc.presets,
			plugins: babelRc.plugins
		})
	]
};
<commit_msg>Remove old rollup config<commit_after><|endoftext|>


<commit_before>import resolve from 'rollup-plugin-node-resolve'
import babel from 'rollup-plugin-babel'
import commonjs from 'rollup-plugin-commonjs'
import vue from 'rollup-plugin-vue'
import uglify from 'rollup-plugin-uglify'
import sass from 'rollup-plugin-sass';
import autoprefixer from 'autoprefixer'
import postcss from 'postcss'
import csso from 'postcss-csso';
import { minify } from 'uglify-es'

const isProduction = process.env.NODE_ENV === `production`
const isDevelopment = process.env.NODE_ENV === `development`

function createConfig(entry, output, name) {

  const libPath = (isDevelopment
        ? `dist/${output}.js`
        : `dist/${output}.min.js`)

  const babelConfig = {
    'compact': false,
    'babelrc': false,
    'presets': [
      [
        // env preset https://github.com/babel/babel-preset-env
        'env',
        // let rollup take care of modules
        { 'modules': false }
      ]
    ],
    'plugins': [
      // let rollup bundle helpers once
      // see https://github.com/rollup/rollup-plugin-babel#helpers
      'external-helpers'
    ]
  }

  const sassConfig = {
    include: [ '**/*.css', '**/*.scss' ],
    options: {includePaths: ['node_modules']},
    processor: css => postcss((isDevelopment
                        ? [autoprefixer()]
                        : [autoprefixer(), csso()]))
                      .process(css)
                      .then(result => result.css)
  }

  if (isProduction) {
    sassConfig.output = `dist/${output}.min.css`
  } else {
    sassConfig.insert = true
  }

  const config = {
    input: entry,
    output: {
      file: libPath,
      format: 'umd',
      name: name
    },
    external: ['vue'],
    plugins: [
      vue ({ autoStyles: false, styleToImports: true }),
      resolve({ jsnext: true, main: true, browser: true }),
      sass(sassConfig),
      babel(babelConfig),
      commonjs (),
    ],
    sourcemap: isDevelopment ? 'inline' : true,
    onwarn
  }

  if (isProduction) {
    config.plugins.push(uglify({}, minify))
  }
  return config
}

export default [
  createConfig('components/entry.js', 'index', 'VueMDCAdapter'),
  createConfig('components/button/entry.js', 'button/index', 'VueMDCButton'),
  createConfig('components/card/entry.js', 'card/index', 'VueMDCCard'),
  createConfig('components/checkbox/entry.js', 'checkbox/index', 'VueMDCCheckbox'),
  createConfig('components/dialog/entry.js', 'dialog/index', 'VueMDCDialog'),
  createConfig('components/drawer/entry.js', 'drawer/index', 'VueMDCDrawer'),
  createConfig('components/fab/entry.js', 'fab/index', 'VueMDCFab'),
  createConfig('components/grid-list/entry.js', 'grid-list/index', 'VueMDCGridList'),
  createConfig('components/icon-toggle/entry.js', 'icon-toggle/index', 'VueMDCIconToggle'),
  createConfig('components/icon/entry.js', 'icon/index', 'VueMDCIcon'),
  createConfig('components/layout-app/entry.js', 'layout-app/index', 'VueMDCLayoutApp'),
  createConfig('components/layout-grid/entry.js', 'layout-grid/index', 'VueMDCLayoutGrid'),
  createConfig('components/linear-progress/entry.js', 'linear-progress/index', 'VueMDCLinearProgress'),
  createConfig('components/list/entry.js', 'list/index', 'VueMDCList'),
  createConfig('components/menu/entry.js', 'menu/index', 'VueMDCMenu'),
  createConfig('components/radio/entry.js', 'radio/index', 'VueMDCRadio'),
  createConfig('components/select/entry.js', 'select/index', 'VueMDCSelect'),
  createConfig('components/slider/entry.js', 'slider/index', 'VueMDCSlider'),
  createConfig('components/snackbar/entry.js', 'snackbar/index', 'VueMDCSnackbar'),
  createConfig('components/switch/entry.js', 'switch/index', 'VueMDCSwitch'),
  createConfig('components/tabs/entry.js', 'tabs/index', 'VueMDCTabs'),
  createConfig('components/textfield/entry.js', 'texfield/index', 'VueMDCTextfield'),
  createConfig('components/toolbar/entry.js', 'toolbar/index', 'VueMDCToolbar'),
  createConfig('components/typography/entry.js', 'typography/index', 'VueMDCTypography'),
]

function onwarn (warning) {

  // skip certain warnings
  if (warning.code == 'NON_EXISTENT_EXPORT') {
    if (warning.name == 'MDCIconToggleAdapter') return;
  }

  // console.warn everything else
  console.log(warning);
  console.warn(warning.message);
}
<commit_msg>chore(dist): chore(dist): distributionss shoud have banners<commit_after>import resolve from 'rollup-plugin-node-resolve'
import babel from 'rollup-plugin-babel'
import commonjs from 'rollup-plugin-commonjs'
import vue from 'rollup-plugin-vue'
import uglify from 'rollup-plugin-uglify'
import sass from 'rollup-plugin-sass';
import autoprefixer from 'autoprefixer'
import postcss from 'postcss'
import csso from 'postcss-csso';
import { minify } from 'uglify-es'
import pkg from './package.json';

const isProduction = process.env.NODE_ENV === `production`
const isDevelopment = process.env.NODE_ENV === `development`

function createConfig(entry, module, name) {

  const output = module ? module +'/index' : 'index'
  const banner = `/**
  * @module vue-mdc-adapter{{module}} {{version}}
  * @exports {{name}}
  * @copyright (c) 2017-present, Sebastien Tasson
  * @license https://opensource.org/licenses/MIT
  * @implements {{dependencies}}
  * @requires {{peerDependencies}}
  * @see https://github.com/stasson/vue-mdc-adapter
  */`
  .replace('{{module}}', module || '')
  .replace('{{name}}', name)
  .replace('{{version}}', pkg.version)
  .replace('{{dependencies}}', JSON.stringify(pkg.dependencies))
  .replace('{{peerDependencies}}', JSON.stringify(pkg.peerDependencies))

  const libPath = (isDevelopment
        ? `dist/${output}.js`
        : `dist/${output}.min.js`)

  const babelConfig = {
    'compact': false,
    'babelrc': false,
    'presets': [
      [
        // env preset https://github.com/babel/babel-preset-env
        'env',
        // let rollup take care of modules
        { 'modules': false }
      ]
    ],
    'plugins': [
      // let rollup bundle helpers once
      // see https://github.com/rollup/rollup-plugin-babel#helpers
      'external-helpers'
    ]
  }

  const sassConfig = {
    include: [ '**/*.css', '**/*.scss' ],
    options: {includePaths: ['node_modules']},
    processor: css => postcss((isDevelopment
                        ? [autoprefixer()]
                        : [autoprefixer(), csso()]))
                      .process(css)
                      .then(result => result.css)
  }

  if (isProduction) {
    sassConfig.output = `dist/${output}.min.css`
  } else {
    sassConfig.insert = true
  }

  const config = {
    input: entry,
    output: {
      file: libPath,
      format: 'umd',
      name: name
    },
    external: ['vue'],
    plugins: [
      vue ({ autoStyles: false, styleToImports: true }),
      resolve({ jsnext: true, main: true, browser: true }),
      sass(sassConfig),
      babel(babelConfig),
      commonjs(),
    ],
    banner,
    sourcemap: isDevelopment ? 'inline' : true,
    onwarn
  }

  if (isProduction) {
    config.plugins.push(uglify({
      output: {
        comments: function(node, comment) {
            var text = comment.value;
            var type = comment.type;
            if (type == "comment2") {
                // multiline comment
                return /@preserve|@license|@cc_on/i.test(text);
            }
        }
      }
    }, minify))
  }
  return config
}

export default [
  createConfig('components/entry.js', undefined, 'VueMDCAdapter'),
  createConfig('components/button/entry.js', 'button', 'VueMDCButton'),
  createConfig('components/card/entry.js', 'card', 'VueMDCCard'),
  createConfig('components/checkbox/entry.js', 'checkbox', 'VueMDCCheckbox'),
  createConfig('components/dialog/entry.js', 'dialog', 'VueMDCDialog'),
  createConfig('components/drawer/entry.js', 'drawer', 'VueMDCDrawer'),
  createConfig('components/fab/entry.js', 'fab', 'VueMDCFab'),
  createConfig('components/grid-list/entry.js', 'grid-list', 'VueMDCGridList'),
  createConfig('components/icon-toggle/entry.js', 'icon-toggle', 'VueMDCIconToggle'),
  createConfig('components/icon/entry.js', 'icon', 'VueMDCIcon'),
  createConfig('components/layout-app/entry.js', 'layout-app', 'VueMDCLayoutApp'),
  createConfig('components/layout-grid/entry.js', 'layout-grid', 'VueMDCLayoutGrid'),
  createConfig('components/linear-progress/entry.js', 'linear-progress', 'VueMDCLinearProgress'),
  createConfig('components/list/entry.js', 'list', 'VueMDCList'),
  createConfig('components/menu/entry.js', 'menu', 'VueMDCMenu'),
  createConfig('components/radio/entry.js', 'radio', 'VueMDCRadio'),
  createConfig('components/select/entry.js', 'select', 'VueMDCSelect'),
  createConfig('components/slider/entry.js', 'slider', 'VueMDCSlider'),
  createConfig('components/snackbar/entry.js', 'snackbar', 'VueMDCSnackbar'),
  createConfig('components/switch/entry.js', 'switch', 'VueMDCSwitch'),
  createConfig('components/tabs/entry.js', 'tabs', 'VueMDCTabs'),
  createConfig('components/textfield/entry.js', 'texfield', 'VueMDCTextfield'),
  createConfig('components/toolbar/entry.js', 'toolbar', 'VueMDCToolbar'),
  createConfig('components/typography/entry.js', 'typography', 'VueMDCTypography'),
]

function onwarn (warning) {

  // skip certain warnings
  if (warning.code == 'NON_EXISTENT_EXPORT') {
    if (warning.name == 'MDCIconToggleAdapter') return;
  }

  // console.warn everything else
  console.log(warning);
  console.warn(warning.message);
}
<|endoftext|>


<commit_before>import fs from "fs";
import typescript from "@rollup/plugin-typescript";
import { terser } from "rollup-plugin-terser";

const licenseHeader = fs.readFileSync("src/license_header.txt", { encoding: "utf8" });

export default [
  {
    input: "src/sha.ts",
    output: {
      name: "jsSHA",
      banner: licenseHeader,
      format: "umd",
      sourcemap: true,
      dir: "dist",
      entryFileNames: "[name].umd.js"
    },
    plugins: [
      typescript({ lib: ["es6"], target: "es3" }),
      terser({
        sourcemap: true,
        compress: { inline: false },
        output: { comments: /BSD/ },
        mangle: { properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC"] } },
      }),
    ],
  },
  {
    input: "src/sha1.ts",
    output: {
      name: "jsSHA",
      banner: licenseHeader,
      format: "umd",
      sourcemap: true,
      dir: "dist",
      entryFileNames: "[name].umd.js"
    },
    plugins: [
      typescript({ lib: ["es6"], target: "es3" }),
      terser({
        sourcemap: true,
        compress: { inline: false },
        output: { comments: /BSD/ },
        mangle: { properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC"] } },
      }),
    ],
  },
  {
    input: "src/sha256.ts",
    output: {
      name: "jsSHA",
      banner: licenseHeader,
      format: "umd",
      sourcemap: true,
      dir: "dist",
      entryFileNames: "[name].umd.js"
    },
    plugins: [
      typescript({ lib: ["es6"], target: "es3" }),
      terser({
        sourcemap: true,
        compress: { inline: false },
        output: { comments: /BSD/ },
        mangle: { properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC"] } },
      }),
    ],
  },
  {
    input: "src/sha512.ts",
    output: {
      name: "jsSHA",
      banner: licenseHeader,
      format: "umd",
      sourcemap: true,
      dir: "dist",
      entryFileNames: "[name].umd.js"
    },
    plugins: [
      typescript({ lib: ["es6"], target: "es3" }),
      terser({
        sourcemap: true,
        compress: { inline: false },
        output: { comments: /BSD/ },
        mangle: { properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC"] } },
      }),
    ],
  },
  {
    input: "src/sha3.ts",
    output: {
      name: "jsSHA",
      banner: licenseHeader,
      format: "umd",
      sourcemap: true,
      dir: "dist",
      entryFileNames: "[name].umd.js"
    },
    plugins: [
      typescript({ lib: ["es6"], target: "es3" }),
      terser({
        sourcemap: true,
        compress: { inline: false },
        output: { comments: /BSD/ },
        mangle: { properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC"] } },
      }),
    ],
  },
];
<commit_msg>Cut down on the number of sourcemaps<commit_after>import fs from "fs";
import typescript from "@rollup/plugin-typescript";
import { terser } from "rollup-plugin-terser";

const licenseHeader = fs.readFileSync("src/license_header.txt", { encoding: "utf8" });

export default [
  {
    input: "src/sha.ts",
    output: {
      name: "jsSHA",
      banner: licenseHeader,
      format: "umd",
      sourcemap: true,
      dir: "dist",
      entryFileNames: "[name].umd.js"
    },
    plugins: [
      typescript({ lib: ["es6"], target: "es3" }),
      terser({
        sourcemap: true,
        compress: { inline: false },
        output: { comments: /BSD/ },
        mangle: { properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC"] } },
      }),
    ],
  },
  {
    input: "src/sha1.ts",
    output: {
      name: "jsSHA",
      banner: licenseHeader,
      format: "umd",
      dir: "dist",
      entryFileNames: "[name].umd.js"
    },
    plugins: [
      typescript({ lib: ["es6"], target: "es3" }),
      terser({
        compress: { inline: false },
        output: { comments: /BSD/ },
        mangle: { properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC"] } },
      }),
    ],
  },
  {
    input: "src/sha256.ts",
    output: {
      name: "jsSHA",
      banner: licenseHeader,
      format: "umd",
      dir: "dist",
      entryFileNames: "[name].umd.js"
    },
    plugins: [
      typescript({ lib: ["es6"], target: "es3" }),
      terser({
        compress: { inline: false },
        output: { comments: /BSD/ },
        mangle: { properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC"] } },
      }),
    ],
  },
  {
    input: "src/sha512.ts",
    output: {
      name: "jsSHA",
      banner: licenseHeader,
      format: "umd",
      dir: "dist",
      entryFileNames: "[name].umd.js"
    },
    plugins: [
      typescript({ lib: ["es6"], target: "es3" }),
      terser({
        compress: { inline: false },
        output: { comments: /BSD/ },
        mangle: { properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC"] } },
      }),
    ],
  },
  {
    input: "src/sha3.ts",
    output: {
      name: "jsSHA",
      banner: licenseHeader,
      format: "umd",
      dir: "dist",
      entryFileNames: "[name].umd.js"
    },
    plugins: [
      typescript({ lib: ["es6"], target: "es3" }),
      terser({
        compress: { inline: false },
        output: { comments: /BSD/ },
        mangle: { properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC"] } },
      }),
    ],
  },
];
<|endoftext|>


<commit_before>const path = require('path');
const fs = require('fs');
const chalk = require('chalk');
const log = console.log; // eslint-disable-line

const multi_entry = require('rollup-plugin-multi-entry');
const commonjs = require('rollup-plugin-commonjs');
const node_resolve = require('rollup-plugin-node-resolve');
const postcss = require('rollup-plugin-postcss');
const buble = require('rollup-plugin-buble');
const { terser } = require('rollup-plugin-terser');
const vue = require('rollup-plugin-vue');
const frappe_html = require('./frappe-html-plugin');
const less_loader = require('./less-loader');

const production = process.env.FRAPPE_ENV === 'production';

const {
	apps_list,
	assets_path,
	bench_path,
	get_public_path,
	get_app_path,
	get_build_json,
	get_options_for_scss
} = require('./rollup.utils');

function get_rollup_options(output_file, input_files) {
	if (output_file.endsWith('.js')) {
		return get_rollup_options_for_js(output_file, input_files);
	} else if(output_file.endsWith('.css')) {
		return get_rollup_options_for_css(output_file, input_files);
	}
}

function get_rollup_options_for_js(output_file, input_files) {

	const node_resolve_paths = [].concat(
		// node_modules of apps directly importable
		apps_list.map(app => path.resolve(get_app_path(app), '../node_modules')).filter(fs.existsSync),
		// import js file of any app if you provide the full path
		apps_list.map(app => path.resolve(get_app_path(app), '..')).filter(fs.existsSync)
	);

	const plugins = [
		// enables array of inputs
		multi_entry(),
		// .html -> .js
		frappe_html(),
		// ignore css imports
		ignore_css(),
		// .vue -> .js
		vue.default(),
		// ES6 -> ES5
		buble({
			objectAssign: 'Object.assign',
			transforms: {
				dangerousForOf: true,
				classes: false
			},
			exclude: [path.resolve(bench_path, '**/*.css'), path.resolve(bench_path, '**/*.less')]
		}),
		commonjs(),
		node_resolve({
			customResolveOptions: {
				paths: node_resolve_paths
			}
		}),
		production && terser()
	];

	return {
		inputOptions: {
			input: input_files,
			plugins: plugins,
			context: 'window',
			external: ['jquery'],
			onwarn({ code, message, loc, frame }) {
				// skip warnings
				if (['EVAL', 'SOURCEMAP_BROKEN', 'NAMESPACE_CONFLICT'].includes(code)) return;

				if ('UNRESOLVED_IMPORT' === code) {
					log(chalk.yellow.underline(code), ':', message);
					const command = chalk.yellow('bench setup requirements');
					log(`Cannot find some dependencies. You may have to run "${command}" to install them.`);
					log();
					return;
				}

				if (loc) {
					log(`${loc.file} (${loc.line}:${loc.column}) ${message}`);
					if (frame) log(frame);
				} else {
					log(chalk.yellow.underline(code), ':', message);
				}
			}
		},
		outputOptions: {
			file: path.resolve(assets_path, output_file),
			format: 'iife',
			name: 'Rollup',
			globals: {
				'jquery': 'window.jQuery'
			},
			sourcemap: true
		}
	};
}

function get_rollup_options_for_css(output_file, input_files) {
	const output_path = path.resolve(assets_path, output_file);
	const starts_with_css = output_file.startsWith('css/');

	const plugins = [
		// enables array of inputs
		multi_entry(),
		// less -> css
		postcss({
			plugins: [
				starts_with_css ? require('autoprefixer')() : null,
				starts_with_css && production ? require('cssnano')({ preset: 'default' }) : null
			].filter(Boolean),
			extract: output_path,
			loaders: [less_loader],
			use: [
				['less', {
					// import other less/css files starting from these folders
					paths: [
						path.resolve(get_public_path('frappe'), 'less')
					]
				}],
				['sass', {
					...get_options_for_scss(),
					outFile: output_path,
					sourceMapContents: true
				}]
			],
			include: [
				path.resolve(bench_path, '**/*.less'),
				path.resolve(bench_path, '**/*.scss'),
				path.resolve(bench_path, '**/*.css')
			],
			sourceMap: starts_with_css && !production
		})
	];

	return {
		inputOptions: {
			input: input_files,
			plugins: plugins,
			onwarn(warning) {
				// skip warnings
				if (['EMPTY_BUNDLE'].includes(warning.code)) return;

				// console.warn everything else
				log(chalk.yellow.underline(warning.code), ':', warning.message);
				log(warning);
			}
		},
		outputOptions: {
			// this file is always empty, remove it later?
			file: path.resolve(assets_path, `css/rollup.manifest.css`),
			format: 'cjs'
		}
	};
}

function get_options(file, app="frappe") {
	const build_json = get_build_json(app);
	if (!build_json) return [];

	return Object.keys(build_json)
		.map(output_file => {
			if (output_file === file) {
				if (output_file.startsWith('concat:')) return null;
				const input_files = build_json[output_file]
					.map(input_file => {
						let prefix = get_app_path(app);
						if (input_file.startsWith('node_modules/')) {
							prefix = path.resolve(get_app_path(app), '..');
						}
						return path.resolve(prefix, input_file);
					});
				return Object.assign(
					get_rollup_options(output_file, input_files), {
						output_file
					});
			}
		})
		.filter(Boolean);
}

function get_options_for(app) {
	const build_json = get_build_json(app);
	if (!build_json) return [];

	return Object.keys(build_json)
		.map(output_file => {
			if (output_file.startsWith('concat:')) return null;

			const input_files = build_json[output_file]
				.map(input_file => {
					let prefix = get_app_path(app);
					if (input_file.startsWith('node_modules/')) {
						prefix = path.resolve(get_app_path(app), '..');
					}
					return path.resolve(prefix, input_file);
				});
			return Object.assign(
				get_rollup_options(output_file, input_files), {
					output_file
				});
		})
		.filter(Boolean);
}

function ignore_css() {
	return {
		name: 'ignore-css',
		transform(code, id) {
			if (!['.css', '.scss', '.sass', '.less'].some(ext => id.endsWith(ext))) {
				return null;
			}

			return `
				// ignored ${id}
			`;
		}
	};
};

module.exports = {
	get_options_for,
	get_options
};
<commit_msg>fix: Support single file builds in build.json<commit_after>const path = require('path');
const fs = require('fs');
const chalk = require('chalk');
const log = console.log; // eslint-disable-line

const multi_entry = require('rollup-plugin-multi-entry');
const commonjs = require('rollup-plugin-commonjs');
const node_resolve = require('rollup-plugin-node-resolve');
const postcss = require('rollup-plugin-postcss');
const buble = require('rollup-plugin-buble');
const { terser } = require('rollup-plugin-terser');
const vue = require('rollup-plugin-vue');
const frappe_html = require('./frappe-html-plugin');
const less_loader = require('./less-loader');

const production = process.env.FRAPPE_ENV === 'production';

const {
	apps_list,
	assets_path,
	bench_path,
	get_public_path,
	get_app_path,
	get_build_json,
	get_options_for_scss
} = require('./rollup.utils');

function get_rollup_options(output_file, input_files) {
	if (output_file.endsWith('.js')) {
		return get_rollup_options_for_js(output_file, input_files);
	} else if(output_file.endsWith('.css')) {
		return get_rollup_options_for_css(output_file, input_files);
	}
}

function get_rollup_options_for_js(output_file, input_files) {

	const node_resolve_paths = [].concat(
		// node_modules of apps directly importable
		apps_list.map(app => path.resolve(get_app_path(app), '../node_modules')).filter(fs.existsSync),
		// import js file of any app if you provide the full path
		apps_list.map(app => path.resolve(get_app_path(app), '..')).filter(fs.existsSync)
	);

	const plugins = [
		// enables array of inputs
		multi_entry(),
		// .html -> .js
		frappe_html(),
		// ignore css imports
		ignore_css(),
		// .vue -> .js
		vue.default(),
		// ES6 -> ES5
		buble({
			objectAssign: 'Object.assign',
			transforms: {
				dangerousForOf: true,
				classes: false
			},
			exclude: [path.resolve(bench_path, '**/*.css'), path.resolve(bench_path, '**/*.less')]
		}),
		commonjs(),
		node_resolve({
			customResolveOptions: {
				paths: node_resolve_paths
			}
		}),
		production && terser()
	];

	return {
		inputOptions: {
			input: input_files,
			plugins: plugins,
			context: 'window',
			external: ['jquery'],
			onwarn({ code, message, loc, frame }) {
				// skip warnings
				if (['EVAL', 'SOURCEMAP_BROKEN', 'NAMESPACE_CONFLICT'].includes(code)) return;

				if ('UNRESOLVED_IMPORT' === code) {
					log(chalk.yellow.underline(code), ':', message);
					const command = chalk.yellow('bench setup requirements');
					log(`Cannot find some dependencies. You may have to run "${command}" to install them.`);
					log();
					return;
				}

				if (loc) {
					log(`${loc.file} (${loc.line}:${loc.column}) ${message}`);
					if (frame) log(frame);
				} else {
					log(chalk.yellow.underline(code), ':', message);
				}
			}
		},
		outputOptions: {
			file: path.resolve(assets_path, output_file),
			format: 'iife',
			name: 'Rollup',
			globals: {
				'jquery': 'window.jQuery'
			},
			sourcemap: true
		}
	};
}

function get_rollup_options_for_css(output_file, input_files) {
	const output_path = path.resolve(assets_path, output_file);
	const starts_with_css = output_file.startsWith('css/');

	const plugins = [
		// enables array of inputs
		multi_entry(),
		// less -> css
		postcss({
			plugins: [
				starts_with_css ? require('autoprefixer')() : null,
				starts_with_css && production ? require('cssnano')({ preset: 'default' }) : null
			].filter(Boolean),
			extract: output_path,
			loaders: [less_loader],
			use: [
				['less', {
					// import other less/css files starting from these folders
					paths: [
						path.resolve(get_public_path('frappe'), 'less')
					]
				}],
				['sass', {
					...get_options_for_scss(),
					outFile: output_path,
					sourceMapContents: true
				}]
			],
			include: [
				path.resolve(bench_path, '**/*.less'),
				path.resolve(bench_path, '**/*.scss'),
				path.resolve(bench_path, '**/*.css')
			],
			sourceMap: starts_with_css && !production
		})
	];

	return {
		inputOptions: {
			input: input_files,
			plugins: plugins,
			onwarn(warning) {
				// skip warnings
				if (['EMPTY_BUNDLE'].includes(warning.code)) return;

				// console.warn everything else
				log(chalk.yellow.underline(warning.code), ':', warning.message);
				log(warning);
			}
		},
		outputOptions: {
			// this file is always empty, remove it later?
			file: path.resolve(assets_path, `css/rollup.manifest.css`),
			format: 'cjs'
		}
	};
}

function get_options(file, app="frappe") {
	const build_json = get_build_json(app);
	if (!build_json) return [];

	return Object.keys(build_json)
		.map(output_file => {
			if (output_file === file) {
				if (output_file.startsWith('concat:')) return null;
				const input_files = build_json[output_file]
					.map(input_file => {
						let prefix = get_app_path(app);
						if (input_file.startsWith('node_modules/')) {
							prefix = path.resolve(get_app_path(app), '..');
						}
						return path.resolve(prefix, input_file);
					});
				return Object.assign(
					get_rollup_options(output_file, input_files), {
						output_file
					});
			}
		})
		.filter(Boolean);
}

function get_options_for(app) {
	const build_json = get_build_json(app);
	if (!build_json) return [];

	return Object.keys(build_json)
		.map(output_file => {
			if (output_file.startsWith('concat:')) return null;

			let files = build_json[output_file];
			if (typeof files === 'string') {
				files = [files];
			}
			const input_files = files
				.map(input_file => {
					let prefix = get_app_path(app);
					if (input_file.startsWith('node_modules/')) {
						prefix = path.resolve(get_app_path(app), '..');
					}
					return path.resolve(prefix, input_file);
				});
			return Object.assign(
				get_rollup_options(output_file, input_files), {
					output_file
				});
		})
		.filter(Boolean);
}

function ignore_css() {
	return {
		name: 'ignore-css',
		transform(code, id) {
			if (!['.css', '.scss', '.sass', '.less'].some(ext => id.endsWith(ext))) {
				return null;
			}

			return `
				// ignored ${id}
			`;
		}
	};
};

module.exports = {
	get_options_for,
	get_options
};
<|endoftext|>