<commit_before>const webpack = require('webpack')
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: {
    app: [
      'react-hot-loader/patch',
      // activate HMR for React

      'webpack-dev-server/client?http://localhost:3000',
      // bundle the client for webpack-dev-server
      // and connect to the provided endpoint

      'webpack/hot/only-dev-server',
      // bundle the client for hot reloading
      // only- means to only hot reload for successful updates

      path.join(__dirname, './src', './index.tsx'),
    ]
  },
  output: {
    filename: '[name].js',
    path: path.join(__dirname, './dist'),
    publicPath: '/'
  },
  module: {
    rules: [
      {
        enforce: 'pre',
        test: /\.js$/,
        loader: "source-map-loader"
      },
      {
        enforce: 'pre',
        test: /\.tsx?$/,
        use: "source-map-loader"
      },
      {
        test: /\.tsx?$/,
        use: [
          { loader: 'react-hot-loader/webpack' },
          { loader: 'awesome-typescript-loader' },
        ],
        exclude: /node_modules/,
      },
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          use: 'css-loader'
        })
      }
    ]
  },
  resolve: {
    extensions: [".tsx", ".ts", ".js"]
  },
  devtool: 'cheap-module-eval-source-map',
  devServer: {
    hot: true,

    contentBase: path.resolve(__dirname, './dist'),
    // match the output path

    publicPath: '/'
    // match the output `publicPath`
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    // enable HMR globally

    new HtmlWebpackPlugin({
      template: path.join(__dirname, './public', 'index.html')
    }),
    new ExtractTextPlugin('styles.css'),
  ]
};
<commit_msg>cleanup webpack config<commit_after>const webpack = require('webpack')
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: {
    app: [
      'react-hot-loader/patch',
      path.join(__dirname, './src', './index.tsx'),
    ]
  },
  output: {
    filename: '[name].js',
    path: path.join(__dirname, './dist'),
    publicPath: '/'
  },
  module: {
    rules: [
      {
        enforce: 'pre',
        test: /\.js$/,
        loader: "source-map-loader"
      },
      {
        enforce: 'pre',
        test: /\.tsx?$/,
        use: "source-map-loader"
      },
      {
        test: /\.tsx?$/,
        use: [
          { loader: 'react-hot-loader/webpack' },
          { loader: 'awesome-typescript-loader' },
        ],
        exclude: /node_modules/,
      },
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          use: 'css-loader'
        })
      }
    ]
  },
  resolve: {
    extensions: [".tsx", ".ts", ".js"]
  },
  devtool: 'cheap-module-eval-source-map',
  devServer: {
    hot: true,
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
    new HtmlWebpackPlugin({
      template: path.join(__dirname, './public', 'index.html')
    }),
    new ExtractTextPlugin('styles.css'),
  ]
};
<|endoftext|>


<commit_before>const path = require('path');
const ENV = process.env.NODE_ENV;
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const ROOT_DIR = path.resolve(__dirname);
const SRC_DIR = path.resolve(__dirname, 'src');

const BUILD_DIR = path.resolve(__dirname, 'build');
const PLUGINS = [];
const PAGE_ENTRIES = {
  index: path.resolve(SRC_DIR, 'index.js'),
  vendor: [
    'babel-polyfill',
    'react',
    'react-dom',
    'react-router',
  ],
};

if (ENV === 'development') {
  PAGE_ENTRIES['webpack-dev-server'] = 'webpack/hot/dev-server';
}

PLUGINS.push(new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js'));

PLUGINS.push(new HtmlWebpackPlugin({
  inject: 'body',
  template: '!!ejs!src/index.ejs',
  filename: 'index.html',
  chunks: ['vendor', 'index'],
  chunksSortMode: 'dependency',
  environment: process.env.NODE_ENV,
}));

var webpackConfig = {
  entry: PAGE_ENTRIES,
  output: {
    path: BUILD_DIR,
    filename: '[name].js',
  },
  resolve: {
    root: ROOT_DIR,
  },
  module: {
    preLoaders: [
      {
        test: /\.jsx?$/,
        loader: 'eslint',
        include: SRC_DIR,
      },
    ],
    loaders: [
      {
        test: /\.css$/, // Only .css files
        loader: 'style!css?localIdentName=[path][name]---[local]---[hash:base64:5]', // Run both loaders
      },
      {
        test: /\.scss$/,
        loader: 'style!css?module&camelCase&localIdentName=[local]-[hash:5]!sass',
      },
      {
        test: /\.html$/,
        loader: 'html',
      },
      {
        test: /\.json$/,
        loader: 'json',
      },
      {
        test: /\.(png|jpg|gif|woff|svg|eot|ttf|woff2)$/,
        loader: 'file-loader?name=[name]-[hash:8].[ext]!image-webpack',
      },
      {
        test: /\.jsx?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel',
        query: {presets: ['react', 'es2015']}
        // 'babel-loader' is also a legal name to reference
      },
    ],
  },
  plugins: PLUGINS,
  imageWebpackLoader: {
    pngquant: {
      quality: '65-90',
      speed: 4,
    },
  },
};

if (process.env.NODE_ENV === 'production') {
  webpackConfig.plugins = webpackConfig.plugins.concat([
    // define variable available in code
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production'),
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
      },
      output: {
        comments: false,
      },
    }),
  ]);
}

module.exports = webpackConfig;
<commit_msg>add source-map to dev<commit_after>const path = require('path');
const ENV = process.env.NODE_ENV;
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const ROOT_DIR = path.resolve(__dirname);
const SRC_DIR = path.resolve(__dirname, 'src');

const BUILD_DIR = path.resolve(__dirname, 'build');
const PLUGINS = [];
const PAGE_ENTRIES = {
  index: path.resolve(SRC_DIR, 'index.js'),
  vendor: [
    'babel-polyfill',
    'react',
    'react-dom',
    'react-router',
  ],
};

if (ENV === 'development') {
  PAGE_ENTRIES['webpack-dev-server'] = 'webpack/hot/dev-server';
}

PLUGINS.push(new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js'));

PLUGINS.push(new HtmlWebpackPlugin({
  inject: 'body',
  template: '!!ejs!src/index.ejs',
  filename: 'index.html',
  chunks: ['vendor', 'index'],
  chunksSortMode: 'dependency',
  environment: process.env.NODE_ENV,
}));

var webpackConfig = {
  devtool: 'source-map',
  entry: PAGE_ENTRIES,
  output: {
    path: BUILD_DIR,
    filename: '[name].js',
  },
  resolve: {
    root: ROOT_DIR,
  },
  module: {
    preLoaders: [
      {
        test: /\.jsx?$/,
        loader: 'eslint',
        include: SRC_DIR,
      },
    ],
    loaders: [
      {
        test: /\.css$/, // Only .css files
        loader: 'style!css?localIdentName=[path][name]---[local]---[hash:base64:5]', // Run both loaders
      },
      {
        test: /\.scss$/,
        loader: 'style!css?module&camelCase&localIdentName=[local]-[hash:5]!sass',
      },
      {
        test: /\.html$/,
        loader: 'html',
      },
      {
        test: /\.json$/,
        loader: 'json',
      },
      {
        test: /\.(png|jpg|gif|woff|svg|eot|ttf|woff2)$/,
        loader: 'file-loader?name=[name]-[hash:8].[ext]!image-webpack',
      },
      {
        test: /\.jsx?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel',
        query: {presets: ['react', 'es2015']}
        // 'babel-loader' is also a legal name to reference
      },
    ],
  },
  plugins: PLUGINS,
  imageWebpackLoader: {
    pngquant: {
      quality: '65-90',
      speed: 4,
    },
  },
};

if (process.env.NODE_ENV === 'production') {
  webpackConfig.plugins = webpackConfig.plugins.concat([
    // define variable available in code
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production'),
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
      },
      output: {
        comments: false,
      },
    }),
  ]);
}

module.exports = webpackConfig;
<|endoftext|>


<commit_before>var webpack = require('webpack');
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');

var __DEV__ = process.env.NODE_ENV !== 'production';
console.log('**********************************');
console.log(__DEV__ ? 'dev' : 'prod');
console.log('**********************************');

module.exports = {
    devtool: 'eval',
    entry: [
        'webpack-dev-server/client?http://localhost:3000',
        'webpack/hot/only-dev-server',
        './src/index.jsx'
    ],
    output: {
        path: path.join(__dirname, 'build'),
        filename: 'bundle.js',
        publicPath: '/'
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.DefinePlugin({
            __DEV__: JSON.stringify(__DEV__)
        }),
        new HtmlWebpackPlugin({
            title: 'Custom template',
            bodyContent: (function() {
                require("babel/register");
                var react = require('react');
                var App = require('./src/containers/App.jsx');
                var reactHtml = react.renderToString(react.createFactory(App)({}));
                return reactHtml;
            })(),
            template: './src/index.html', // Load a custom template
            inject: 'body' // Inject all scripts into the body
        })
    ],
    module: {
        loaders: [{
            test: /\.jsx?$/,
            loaders: ['react-hot', 'babel'],
            exclude: /node_modules/,
            include: path.join(__dirname, 'src')
        }]
    }
}
<commit_msg>Remove consoles<commit_after>var webpack = require('webpack');
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');

var __DEV__ = process.env.NODE_ENV !== 'production';

module.exports = {
    devtool: 'eval',
    entry: [
        'webpack-dev-server/client?http://localhost:3000',
        'webpack/hot/only-dev-server',
        './src/index.jsx'
    ],
    output: {
        path: path.join(__dirname, 'build'),
        filename: 'bundle.js',
        publicPath: '/'
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.DefinePlugin({
            __DEV__: JSON.stringify(__DEV__)
        }),
        new HtmlWebpackPlugin({
            title: 'Custom template',
            bodyContent: (function() {
                require("babel/register");
                var react = require('react');
                var App = require('./src/containers/App.jsx');
                var reactHtml = react.renderToString(react.createFactory(App)({}));
                return reactHtml;
            })(),
            template: './src/index.html', // Load a custom template
            inject: 'body' // Inject all scripts into the body
        })
    ],
    module: {
        loaders: [{
            test: /\.jsx?$/,
            loaders: ['react-hot', 'babel'],
            exclude: /node_modules/,
            include: path.join(__dirname, 'src')
        }]
    }
}
<|endoftext|>


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

module.exports = {
    devtool: 'source-map',
    entry: [
        './src/index.js',
    ],
    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify('production'),
            },
        }),
    ],
    module: {
        loaders: [{
            test: /\.js$/,
            loader: 'babel-loader',
            include: path.join(__dirname, 'src'),
        },{
            test:/\.js$/,
            loader: 'babel-polyfill',
            include: path.join(__dirname, 'src'),
        }

         /* {
            test: /\.js$/,
            loader: 'eslint-loader',
            include: path.join(__dirname, 'src'),
        } */],
    },
    output: {
        library: 'binary-live-api',
        libraryTarget: 'umd',
        path: 'lib',
        filename: 'binary-live-api.js',
    },
};
<commit_msg>Remove babel-polyfill from webpack<commit_after>const path = require('path');
const webpack = require('webpack');

module.exports = {
    devtool: 'source-map',
    entry: [
        './src/index.js',
    ],
    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify('production'),
            },
        }),
    ],
    module: {
        loaders: [{
            test: /\.js$/,
            loader: 'babel-loader',
            include: path.join(__dirname, 'src'),
        },

         /* {
            test: /\.js$/,
            loader: 'eslint-loader',
            include: path.join(__dirname, 'src'),
        } */],
    },
    output: {
        library: 'binary-live-api',
        libraryTarget: 'umd',
        path: 'lib',
        filename: 'binary-live-api.js',
    },
};
<|endoftext|>


<commit_before>var Webpack = require('./webpack');
var Path = require('path');

var internals = {};
internals.production = process.env.NODE_ENV === 'production';

module.exports = build;

internals.basePath = Path.join(__dirname, 'client');
internals.srcPath = 'src';
internals.outputPath = 'dist';

internals.src = {
    path: Path.join(internals.basePath, internals.srcPath),
    entryPoints: 'js/pages',
    assets: 'assets',
    views: 'views',
};

internals.output = {
    path: Path.join(internals.basePath, internals.outputPath),
    js: 'js',
    views: 'views',
    css: 'css',
    img: 'img',
    fonts: 'fonts'
};

internals.assets = {
    css: 'css',
    fonts: 'fonts',
    img: 'img'
};

internals.views = {
    pages: 'pages',
    partials: 'partials',
    layout: 'layout.hbs'
};

internals.options = {
    plugins: {
        commons: {
            filename: 'commons'
        }
    },
    paths: {
        base: internals.basePath,
        src: internals.src,
        output: internals.output,
        views: internals.views,
        assets: internals.assets
    }
};

module.exports.options = internals.options;

function build() {
    if (internals.production) {
        return Webpack.production(internals.options, module.exports.paths);
    } else {
        return Webpack.dev(internals.options, module.exports.paths);
    }
}
<commit_msg>removed unnecessary webpack config file<commit_after><|endoftext|>


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

module.exports = {
	entry: {
		'lib/react-slide-select': './src/react-slide-select',
		'examples/examples': [
			'./examples/example-custom_children',
			'./examples/example-product',
			'./examples/example-hero'
		]
	},
	output: {
		library: 'SlideSelect',
		libraryTarget: 'umd',
		path: path.resolve(__dirname),
		filename: '[name].js'
	},
	devtool: 'source-map',
	module: {
		loaders: [
			{
				test: /\.jsx$/,
				loader: 'babel',
				exclude: /node_modules/,
				query: {
					presets: ['react', 'es2015']
				}
			}
		]
	},
	externals: [{
		'react': {
			root: 'React',
			commonjs2: 'react',
			commonjs: 'react',
			amd: 'react'
		},
		'react-dom': {
			root: 'ReactDOM',
			commonjs2: 'react-dom',
			commonjs: 'react-dom',
			amd: 'react-dom'
		}
	}],
	resolve: {
		extensions: ['', '.js', '.jsx']
	}
};
<commit_msg>Adjusting webpack.config.js so lib output is external to the examples<commit_after>var webpack = require('webpack');
var path = require('path');

var moduleProps = {
	loaders: [
		{
			test: /\.jsx$/,
			loader: 'babel',
			exclude: /node_modules/,
			query: {
				presets: ['react', 'es2015']
			}
		}
	]
};
var resolveProps = {
	extensions: ['', '.js', '.jsx']
};

module.exports = [
	{
		entry: {
			'lib/react-slide-select': './src/react-slide-select'
		},
		output: {
			library: 'SlideSelect',
			libraryTarget: 'umd',
			path: path.resolve(__dirname),
			filename: '[name].js'
		},
		externals: [{
			'react': {
				root: 'React',
				commonjs2: 'react',
				commonjs: 'react',
				amd: 'react'
			},
			'react-dom': {
				root: 'ReactDOM',
				commonjs2: 'react-dom',
				commonjs: 'react-dom',
				amd: 'react-dom'
			}
		}],
		devtool: 'source-map',
		module: moduleProps,
		resolve: resolveProps
	},
	{
		entry: {
			'examples/examples': [
				'./examples/example-custom_children',
				'./examples/example-product',
				'./examples/example-hero'
			]
		},
		output: {
			path: path.resolve(__dirname),
			filename: '[name].js'
		},
		externals: [{
			'react': 'React',
			'react-dom': 'ReactDOM',
			'../lib/react-slide-select': 'SlideSelect'
		}],
		devtool: 'source-map',
		module: moduleProps,
		resolve: resolveProps
	}
];
<|endoftext|>


<commit_before>const webpack = require('webpack')
const path = require('path')
const browserList = [
  '>1%',
  'last 4 versions',
  'Firefox ESR',
  'not ie < 11'
]
const OfflinePlugin = require('offline-plugin')
const DuplicatePackageCheckerPlugin = require('duplicate-package-checker-webpack-plugin')
const DashboardPlugin = require('webpack-dashboard/plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const autoprefixer = require('autoprefixer')

const nodeEnv = process.env.NODE_ENV || 'development'
const isProduction = nodeEnv === 'production'

const srcPath = path.join(__dirname, './src')
const buildPath = path.join(__dirname, './build')
const publicPath = path.join(__dirname, './public')

// Common plugins
const plugins = [
  new DuplicatePackageCheckerPlugin(),
  new webpack.optimize.CommonsChunkPlugin({
    name: ['libui', 'vendor'],
    minChunks: Infinity,
    filename: '[name]-[hash].js'
  }),
  new webpack.DefinePlugin({
    'process.env': {
      NODE_ENV: JSON.stringify(nodeEnv)
    }
  }),
  new webpack.NamedModulesPlugin(),
  new HtmlWebpackPlugin({
    template: path.join(publicPath, 'index.html'),
    path: buildPath,
    filename: 'index.html',
    inject: true,
    minify: {
      removeComments: true,
      collapseWhitespace: true,
      removeRedundantAttributes: true,
      useShortDoctype: true,
      removeEmptyAttributes: true,
      removeStyleLinkTypeAttributes: true,
      keepClosingSlash: true,
      minifyJS: true,
      minifyCSS: true,
      minifyURLs: true
    }
  }),
  new webpack.LoaderOptionsPlugin({
    options: {
      postcss: [
        autoprefixer({
          browsers: browserList
        })
      ],
      context: publicPath
    }
  })
]

// Common rules
const rules = [
  {
    test: /\.(js|jsx)$/,
    exclude: /node_modules/,
    loader: 'babel-loader',
    query: {
      babelrc: false,
      presets: [
            // A Babel preset that can automatically determine the Babel plugins and polyfills
            // https://github.com/babel/babel-preset-env
        ['env', {
          targets: {
            browsers: browserList
          },
          modules: false,
          useBuiltIns: false,
          debug: false
        }],
        'stage-0',
        'react',
        ...!isProduction ? [] : ['react-optimize']
      ]
    }
  },
  {
    test: /\.(png|gif|jpg|svg)$/,
    include: publicPath,
    use: 'url-loader?limit=20480&name=assets/[name]-[hash].[ext]'
  }
]

if (isProduction) {
  // Production plugins
  plugins.push(
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false
    }),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        screw_ie8: true,
        warnings: false,
        unused: true,
        dead_code: true
      },
      output: {
        comments: false
      }
    }),
    new ExtractTextPlugin('style-[hash].css'),
    new OfflinePlugin({
      externals: [
        'https://blog.zsxsoft.com/favicon.ico',
        'https://static-up.zsxsoft.com/prism-151114/prism.css',
        'https://static-up.zsxsoft.com/blog/css/share.min.css',
        'https://static-up.zsxsoft.com/prism-151114/prism.js',
        'https://static-up.zsxsoft.com/useragent.js/useragent.min.js',
        'https://static-up.zsxsoft.com/blog/player-161116.js',
        'https://static-up.zsxsoft.com/blog/js/social-share.min.js'
      ],
      ServiceWorker: {
        publicPath: 'https://blog.zsxsoft.com/sw.js'
      },
      excludes: [
        '**/.*',
        '/',
        ''
      ]
    })
  )

  // Production rules
  rules.push(
    {
      test: /(\.scss|\.css)$/,
      loader: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: 'css-loader!postcss-loader!sass-loader'
      })
    }
  )
} else {
  // Development plugins
  plugins.push(
    new webpack.HotModuleReplacementPlugin(),
    new DashboardPlugin()
  )

  // Development rules
  rules.push(
    {
      test: /(\.scss|\.css)$/,
      exclude: /node_modules/,
      use: [
        'style-loader',
        // Using source maps breaks urls in the CSS loader
        // https://github.com/webpack/css-loader/issues/232
        // This comment solves it, but breaks testing from a local network
        // https://github.com/webpack/css-loader/issues/232#issuecomment-240449998
        // 'css-loader?sourceMap',
        'css-loader',
        'postcss-loader',
        'sass-loader?sourceMap'
      ]
    }
  )
}

/*
const aliases = isProduction ? {
  'react': 'react-lite',
  'react-dom': 'react-lite',
  'react-tap-event-plugin': 'react-lite/lib/react-tap-event-plugin'
} : {}
*/
const app = []
if (!isProduction) {
  app.push('react-hot-loader/patch')
}
app.push('./index.js')

module.exports = {
  devtool: !isProduction ? 'eval' : 'source-map',
  context: srcPath,
  entry: {
    vendor: [
      'react', 'react-dom', 'offline-plugin/runtime',
      'react-router-dom' // 'react-lite',
    ],
    libui: [
      'material-ui/List', 'material-ui/Drawer', 'material-ui/Divider',
      'material-ui/Card', 'material-ui/FlatButton', 'material-ui/FloatingActionButton', 'material-ui/Avatar',
      'material-ui/RaisedButton', 'material-ui/TextField',
      'material-ui/styles', 'material-ui/utils/colorManipulator',
      'material-ui/internal/TouchRipple', 'react-tap-event-plugin',
      'style-it', 'chroma-js', 'dynamics.js', 'rc-queue-anim', 'trianglify'
//      'fastclick'
    ],
    js: app
  },
  output: {
    path: buildPath,
    publicPath: isProduction ? 'https://static-up.zsxsoft.com/blog/' : '/',
    filename: 'app-[hash].js'
  },
  module: {
    rules
  },
  resolve: {
    // alias: aliases,
    extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js', '.jsx'],
    modules: [
      path.resolve(__dirname, 'node_modules'),
      srcPath
    ]
  },
  plugins,
  devServer: {
    contentBase: './public',
    historyApiFallback: true,
    port: 3000,
    compress: isProduction,
    inline: !isProduction,
    hot: !isProduction,
    host: '0.0.0.0',
    stats: {
      assets: true,
      children: false,
      chunks: false,
      hash: false,
      modules: false,
      publicPath: false,
      timings: true,
      version: false,
      warnings: true,
      colors: {
        green: '\u001b[32m'
      }
    }
  },
  node: {
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    Buffer: false,
    crypto: false
  }
}
<commit_msg>Use [chunkhash] instead of [hash]<commit_after>const webpack = require('webpack')
const path = require('path')
const browserList = [
  '>1%',
  'last 4 versions',
  'Firefox ESR',
  'not ie < 11'
]
const OfflinePlugin = require('offline-plugin')
const DuplicatePackageCheckerPlugin = require('duplicate-package-checker-webpack-plugin')
const DashboardPlugin = require('webpack-dashboard/plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const autoprefixer = require('autoprefixer')

const nodeEnv = process.env.NODE_ENV || 'development'
const isProduction = nodeEnv === 'production'

const srcPath = path.join(__dirname, './src')
const buildPath = path.join(__dirname, './build')
const publicPath = path.join(__dirname, './public')

// Common plugins
const plugins = [
  new DuplicatePackageCheckerPlugin(),
  new webpack.optimize.CommonsChunkPlugin({
    name: ['libui', 'vendor'],
    minChunks: Infinity,
    filename: '[name].[chunkhash].js'
  }),
  new webpack.DefinePlugin({
    'process.env': {
      NODE_ENV: JSON.stringify(nodeEnv)
    }
  }),
  new webpack.NamedModulesPlugin(),
  new HtmlWebpackPlugin({
    template: path.join(publicPath, 'index.html'),
    path: buildPath,
    filename: 'index.html',
    inject: true,
    minify: {
      removeComments: true,
      collapseWhitespace: true,
      removeRedundantAttributes: true,
      useShortDoctype: true,
      removeEmptyAttributes: true,
      removeStyleLinkTypeAttributes: true,
      keepClosingSlash: true,
      minifyJS: true,
      minifyCSS: true,
      minifyURLs: true
    }
  }),
  new webpack.LoaderOptionsPlugin({
    options: {
      postcss: [
        autoprefixer({
          browsers: browserList
        })
      ],
      context: publicPath
    }
  })
]

// Common rules
const rules = [
  {
    test: /\.(js|jsx)$/,
    exclude: /node_modules/,
    loader: 'babel-loader',
    query: {
      babelrc: false,
      presets: [
            // A Babel preset that can automatically determine the Babel plugins and polyfills
            // https://github.com/babel/babel-preset-env
        ['env', {
          targets: {
            browsers: browserList
          },
          modules: false,
          useBuiltIns: false,
          debug: false
        }],
        'stage-0',
        'react',
        ...!isProduction ? [] : ['react-optimize']
      ]
    }
  },
  {
    test: /\.(png|gif|jpg|svg)$/,
    include: publicPath,
    use: 'url-loader?limit=20480&name=assets/[name].[hash].[ext]'
  }
]

if (isProduction) {
  // Production plugins
  plugins.push(
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false
    }),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        screw_ie8: true,
        warnings: false,
        unused: true,
        dead_code: true
      },
      output: {
        comments: false
      }
    }),
    new ExtractTextPlugin('style-[hash].css'),
    new OfflinePlugin({
      externals: [
        'https://blog.zsxsoft.com/favicon.ico',
        'https://static-up.zsxsoft.com/prism-151114/prism.css',
        'https://static-up.zsxsoft.com/blog/css/share.min.css',
        'https://static-up.zsxsoft.com/prism-151114/prism.js',
        'https://static-up.zsxsoft.com/useragent.js/useragent.min.js',
        'https://static-up.zsxsoft.com/blog/player-161116.js',
        'https://static-up.zsxsoft.com/blog/js/social-share.min.js'
      ],
      ServiceWorker: {
        publicPath: 'https://blog.zsxsoft.com/sw.js',
        navigateFallbackURL: 'https://blog.zsxsoft.com/',
        minify: true
      },
      excludes: [
        '**/.*',
        '/',
        ''
      ]
    })
  )

  // Production rules
  rules.push(
    {
      test: /(\.scss|\.css)$/,
      loader: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: 'css-loader!postcss-loader!sass-loader'
      })
    }
  )
} else {
  // Development plugins
  plugins.push(
    new webpack.HotModuleReplacementPlugin(),
    new DashboardPlugin()
  )

  // Development rules
  rules.push(
    {
      test: /(\.scss|\.css)$/,
      exclude: /node_modules/,
      use: [
        'style-loader',
        // Using source maps breaks urls in the CSS loader
        // https://github.com/webpack/css-loader/issues/232
        // This comment solves it, but breaks testing from a local network
        // https://github.com/webpack/css-loader/issues/232#issuecomment-240449998
        // 'css-loader?sourceMap',
        'css-loader',
        'postcss-loader',
        'sass-loader?sourceMap'
      ]
    }
  )
}

/*
const aliases = isProduction ? {
  'react': 'react-lite',
  'react-dom': 'react-lite',
  'react-tap-event-plugin': 'react-lite/lib/react-tap-event-plugin'
} : {}
*/
const app = []
if (!isProduction) {
  app.push('react-hot-loader/patch')
}
app.push('./index.js')

module.exports = {
  devtool: !isProduction ? 'eval' : 'source-map',
  context: srcPath,
  entry: {
    vendor: [
      'react', 'react-dom', 'offline-plugin/runtime',
      'react-router-dom' // 'react-lite',
    ],
    libui: [
      'material-ui/List', 'material-ui/Drawer', 'material-ui/Divider',
      'material-ui/Card', 'material-ui/FlatButton', 'material-ui/FloatingActionButton', 'material-ui/Avatar',
      'material-ui/RaisedButton', 'material-ui/TextField',
      'material-ui/styles', 'material-ui/utils/colorManipulator',
      'material-ui/internal/TouchRipple', 'react-tap-event-plugin',
      'style-it', 'chroma-js', 'dynamics.js', 'rc-queue-anim', 'trianglify'
//      'fastclick'
    ],
    js: app
  },
  output: {
    path: buildPath,
    publicPath: isProduction ? 'https://static-up.zsxsoft.com/blog/' : '/',
    filename: 'app.[chunkhash].js'
  },
  module: {
    rules
  },
  resolve: {
    // alias: aliases,
    extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js', '.jsx'],
    modules: [
      path.resolve(__dirname, 'node_modules'),
      srcPath
    ]
  },
  plugins,
  devServer: {
    contentBase: './public',
    historyApiFallback: true,
    port: 3000,
    compress: isProduction,
    inline: !isProduction,
    hot: !isProduction,
    host: '0.0.0.0',
    stats: {
      assets: true,
      children: false,
      chunks: false,
      hash: false,
      modules: false,
      publicPath: false,
      timings: true,
      version: false,
      warnings: true,
      colors: {
        green: '\u001b[32m'
      }
    }
  },
  node: {
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    Buffer: false,
    crypto: false
  }
}
<|endoftext|>


<commit_before>/*global module, process*/
/*eslint no-use-before-define:0 */

var webpack = require('webpack');
var webpackDevServer = require('webpack-dev-server');
var path = require('path');

// Support for extra commandline arguments
var argv = require('optimist')
            //--env=XXX: sets a global ENV variable (i.e. window.ENV='XXX')
            .alias('e','env').default('e','dev')
            .argv;

var config = {
  context: path.join(__dirname, 'src'),
  entry: {'bundle': './main'},
  output:{
    path: path.join(__dirname, 'dist'),
    filename: '[name].js',
    publicPath: isDevServer() ? '/' : ''
  },
  devServer: {
    publicPath: '/'
  },
  reload: isDevServer() ? 'localhost' : null,
  module:{
    loaders:[
      { test: /\.es6$/,             loader: 'babel-loader'},
      { test: /\.json$/,            loader: 'json-loader' },
      { test: /\.css$/,             loader: 'style-loader!css-loader' },
      { test: /\.less$/,            loader: 'style-loader!css-loader!less-loader' },
      { test: /\.(png|jpg|gif)$/,   loader: 'url-loader?limit=5000&name=[path][name].[ext]&context=./src' },
      { test: /\.(eot|ttf|otf|woff)$/,loader: 'file-loader?name=[path][name].[ext]&context=./src' },
      { test: /\.svg$/,             loader: 'file-loader?name=[path][name].[ext]&context=./src' },
      { test: /index\.html$/,       loader: 'file-loader?name=[path][name].[ext]&context=./src' }
    ]
  },
  resolve: {
    alias: {
      'famous-flex': 'famous-flex/src'
    }
  },
  plugins:[
    new webpack.DefinePlugin({
      VERSION: JSON.stringify(require('./package.json').version),
      ENV: JSON.stringify(argv.env)
    })
  ]
};

function isDevServer() {
  return process.argv.join('').indexOf('webpack-dev-server') > -1;
}

module.exports = config;
<commit_msg>Removed webpack warning when compiling dist/autolayout.js<commit_after>/*global module, process*/
/*eslint no-use-before-define:0 */

var webpack = require('webpack');
var webpackDevServer = require('webpack-dev-server');
var path = require('path');

// Support for extra commandline arguments
var argv = require('optimist')
            //--env=XXX: sets a global ENV variable (i.e. window.ENV='XXX')
            .alias('e','env').default('e','dev')
            .argv;

var config = {
  context: path.join(__dirname, 'src'),
  entry: {'bundle': './main'},
  output:{
    path: path.join(__dirname, 'dist'),
    filename: '[name].js',
    publicPath: isDevServer() ? '/' : ''
  },
  devServer: {
    publicPath: '/'
  },
  reload: isDevServer() ? 'localhost' : null,
  module:{
    loaders:[
      { test: /\.es6$/,             loader: 'babel-loader'},
      { test: /\.json$/,            loader: 'json-loader' },
      { test: /\.css$/,             loader: 'style-loader!css-loader' },
      { test: /\.less$/,            loader: 'style-loader!css-loader!less-loader' },
      { test: /\.(png|jpg|gif)$/,   loader: 'url-loader?limit=5000&name=[path][name].[ext]&context=./src' },
      { test: /\.(eot|ttf|otf|woff)$/,loader: 'file-loader?name=[path][name].[ext]&context=./src' },
      { test: /\.svg$/,             loader: 'file-loader?name=[path][name].[ext]&context=./src' },
      { test: /index\.html$/,       loader: 'file-loader?name=[path][name].[ext]&context=./src' }
    ],
    noParse: [
      /dist\/autolayout\.js$/
    ]
  },
  resolve: {
    alias: {
      'famous-flex': 'famous-flex/src'
    }
  },
  plugins:[
    new webpack.DefinePlugin({
      VERSION: JSON.stringify(require('./package.json').version),
      ENV: JSON.stringify(argv.env)
    })
  ]
};

function isDevServer() {
  return process.argv.join('').indexOf('webpack-dev-server') > -1;
}

module.exports = config;
<|endoftext|>


<commit_before>const {resolve} = require('path');
const {
  DefinePlugin,
  NamedModulesPlugin,
  HashedModuleIdsPlugin,
  HotModuleReplacementPlugin,
  NoEmitOnErrorsPlugin,
  optimize: {
    CommonsChunkPlugin,
    ModuleConcatenationPlugin,
  },
} = require('webpack');
const {BundleAnalyzerPlugin} = require('webpack-bundle-analyzer');
const CleanPlugin = require('clean-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const HTMLPlugin = require('html-webpack-plugin');
const BabelMinifyPlugin = require('babel-minify-webpack-plugin');
const OptimizeJSPlugin = require('optimize-js-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const OfflinePlugin = require('offline-plugin');

const {extract} = ExtractTextPlugin;

const src = 'src';
const dest = 'app';
const clean = [dest];
const copy = [
  {
    from: 'static',
  },
];

module.exports = ({dev} = {}) => {
  const env = dev ? 'development' : 'production';

  return {
    devtool: dev ? 'eval-source-map' : 'hidden-source-map',
    entry: {
      main: [
        ...dev ? ['react-hot-loader/patch'] : [],
        `./${src}/index.jsx`,
      ],
      main2: [
        ...dev ? ['react-hot-loader/patch'] : [],
        `./${src}/index.jsx`,
      ],
    },
    output: {
      path: resolve(__dirname, dest),
      filename: `[name]${dev ? '' : '.[chunkhash]'}.js`,
    },
    module: {
      rules: [
        {
          test: /\.jsx?$/,
          include: resolve(__dirname, src),
          loader: 'babel-loader',
          options: {
            cacheDirectory: dev,
            forceEnv: env,
          },
        },
        {
          test: /\.css$/,
          include: resolve(__dirname, src),
          use: extract({
            fallback: 'style-loader',
            use: [
              {
                loader: 'css-loader',
                options: {
                  sourceMap: true,
                  modules: true,
                  localIdentName: '[path][name]__[local]--[hash:base64:5]',
                },
              },
            ],
          }),
        },
      ],
    },
    plugins: [
      new CleanPlugin(clean),
      new CopyPlugin(copy),
      new HTMLPlugin({
        template: `${src}/template.ejs`,
        inject: false,
        minify: {
          removeComments: true,
          collapseWhitespace: true,
          minifyCSS: true,
          minifyJS: true,
        },
      }),
      new ExtractTextPlugin({
        filename: '[name].[contenthash].css',
        allChunks: true,
        disable: dev,
      }),
      new DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify(env),
      }),
      new CommonsChunkPlugin({
        name: 'vendor',
        minChunks(module) {
          return module.context && module.context.includes('node_modules');
        },
      }),
      new CommonsChunkPlugin({
        name: 'manifest',
        minChunks: Infinity,
      }),
      ...dev
        ? [
          new NamedModulesPlugin(),
          new HotModuleReplacementPlugin(),
          new BundleAnalyzerPlugin({
            analyzerHost: '0.0.0.0',
            openAnalyzer: false,
          }),
        ]
        : [
          new HashedModuleIdsPlugin(),
          new NoEmitOnErrorsPlugin(),
          new ModuleConcatenationPlugin(),
          new BabelMinifyPlugin(),
          new OptimizeJSPlugin(),
          new OfflinePlugin(),
        ],
    ],
    resolve: {
      extensions: ['.js', '.jsx', '.json'],
    },
  };
};
<commit_msg>Remove accidentally added changes<commit_after>const {resolve} = require('path');
const {
  DefinePlugin,
  NamedModulesPlugin,
  HashedModuleIdsPlugin,
  HotModuleReplacementPlugin,
  NoEmitOnErrorsPlugin,
  optimize: {
    CommonsChunkPlugin,
    ModuleConcatenationPlugin,
  },
} = require('webpack');
const {BundleAnalyzerPlugin} = require('webpack-bundle-analyzer');
const CleanPlugin = require('clean-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const HTMLPlugin = require('html-webpack-plugin');
const BabelMinifyPlugin = require('babel-minify-webpack-plugin');
const OptimizeJSPlugin = require('optimize-js-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const OfflinePlugin = require('offline-plugin');

const {extract} = ExtractTextPlugin;

const src = 'src';
const dest = 'app';
const clean = [dest];
const copy = [
  {
    from: 'static',
  },
];

module.exports = ({dev} = {}) => {
  const env = dev ? 'development' : 'production';

  return {
    devtool: dev ? 'eval-source-map' : 'hidden-source-map',
    entry: [
      ...dev ? ['react-hot-loader/patch'] : [],
      `./${src}/index.jsx`,
    ],
    output: {
      path: resolve(__dirname, dest),
      filename: `[name]${dev ? '' : '.[chunkhash]'}.js`,
    },
    module: {
      rules: [
        {
          test: /\.jsx?$/,
          include: resolve(__dirname, src),
          loader: 'babel-loader',
          options: {
            cacheDirectory: dev,
            forceEnv: env,
          },
        },
        {
          test: /\.css$/,
          include: resolve(__dirname, src),
          use: extract({
            fallback: 'style-loader',
            use: [
              {
                loader: 'css-loader',
                options: {
                  sourceMap: true,
                  modules: true,
                  localIdentName: '[path][name]__[local]--[hash:base64:5]',
                },
              },
            ],
          }),
        },
      ],
    },
    plugins: [
      new CleanPlugin(clean),
      new CopyPlugin(copy),
      new HTMLPlugin({
        template: `${src}/template.ejs`,
        inject: false,
        minify: {
          removeComments: true,
          collapseWhitespace: true,
          minifyCSS: true,
          minifyJS: true,
        },
      }),
      new ExtractTextPlugin({
        filename: '[name].[contenthash].css',
        allChunks: true,
        disable: dev,
      }),
      new DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify(env),
      }),
      new CommonsChunkPlugin({
        name: 'vendor',
        minChunks(module) {
          return module.context && module.context.includes('node_modules');
        },
      }),
      new CommonsChunkPlugin({
        name: 'manifest',
        minChunks: Infinity,
      }),
      ...dev
        ? [
          new NamedModulesPlugin(),
          new HotModuleReplacementPlugin(),
          new BundleAnalyzerPlugin({
            analyzerHost: '0.0.0.0',
            openAnalyzer: false,
          }),
        ]
        : [
          new HashedModuleIdsPlugin(),
          new NoEmitOnErrorsPlugin(),
          new ModuleConcatenationPlugin(),
          new BabelMinifyPlugin(),
          new OptimizeJSPlugin(),
          new OfflinePlugin(),
        ],
    ],
    resolve: {
      extensions: ['.js', '.jsx', '.json'],
    },
  };
};
<|endoftext|>


<commit_before>/* generate sources */

const fs = require('fs')
const path = require('path')

const APP_CONFIG = require('./config.json')
const EXTENSION_PATH = './extensions/'
const GENSRC_HEADER = '/* this file was generated by webpack.config.js */\n\n'
const GENSRC_PATH = './gensrc';
const DEV_MODE = process.env.NODE_ENV !== 'production' && process.argv.indexOf('-p') === -1

const COMMON_MONGO_TYPES = ['String', 'Int', 'ID', 'Float', 'Boolean']

function GenSourceCode(options) {
    this.compiled = false
}

GenSourceCode.prototype.apply = function (compiler) {
    compiler.plugin("compile", function (p) {
        if (this.compiled) return
        this.compiled = true

        /* generete source code */
        console.log('Generating source code')

        try {
            deleteFolderRecursive(path.resolve(__dirname, GENSRC_PATH))
            fs.mkdirSync(GENSRC_PATH)
        } catch (err) {
            if (err.code !== 'EEXIST') throw err
        }

        const exteionsion = fs.readdirSync(EXTENSION_PATH)

        let clientContent = GENSRC_HEADER, serverContent = GENSRC_HEADER, manifestJson = {}

        exteionsion.forEach(file => {
            if (fs.statSync(EXTENSION_PATH + file).isDirectory()) {
                if (APP_CONFIG.extensions) {
                    const ext = APP_CONFIG.extensions[file]
                    if (ext && ext.active) {

                        if (fs.existsSync(EXTENSION_PATH + file + '/extension.json')) {
                            manifestJson[file] = JSON.parse(fs.readFileSync(EXTENSION_PATH + file + '/extension.json', 'utf8'));
                        } else {
                            manifestJson[file] = {name: file}
                        }

                        if (fs.existsSync(EXTENSION_PATH + file + '/build.json')) {
                            const buildOptions = require(EXTENSION_PATH + file + '/build.json')
                            manifestJson[file].options = buildOptions
                            gensrcExtension(file, buildOptions)
                        }

                        if (manifestJson[file].options && manifestJson[file].options.types) {

                            manifestJson[file].options.types.forEach(type => {

                                type.fields = type.fields.map(field => {
                                    if (field.type && COMMON_MONGO_TYPES.indexOf(field.type) < 0) {
                                        // this is a type reference
                                        field.reference = true
                                    }
                                    return field
                                })

                            })

                        }

                        /*if (fs.existsSync(extensionFolder + file + '/build.js')) {
                         const extensionBuild = require(extensionFolder + file + '/build.js')
                         const buildOptions = extensionBuild()
                         gensrcExtension(file,buildOptions)
                         }*/

                        if (fs.existsSync(EXTENSION_PATH + file + '/client.js')) {
                            clientContent += `import '.${EXTENSION_PATH}${file}/client.js'\n`
                        }
                        if (fs.existsSync(EXTENSION_PATH + file + '/server.js')) {
                            serverContent += `import '.${EXTENSION_PATH}${file}/server.js'\n`
                        }

                    }
                }
            }
        })

        const manifestStr = `${GENSRC_HEADER}const extensions=${JSON.stringify(manifestJson, null, 4)}\nexport default extensions`

        fs.writeFile(GENSRC_PATH + "/extensions.js", manifestStr, function (err) {
            if (err) {
                return console.log(err)
            }
        })

        fs.writeFile(GENSRC_PATH + "/extensions-client.js", clientContent, function (err) {
            if (err) {
                return console.log(err)
            }
        })
        fs.writeFile(GENSRC_PATH + "/extensions-server.js", serverContent, function (err) {
            if (err) {
                return console.log(err)
            }
        })

        /* generate config */
        const o ={DEV_MODE}
        let configContent = `${GENSRC_HEADER}export default ${JSON.stringify({...APP_CONFIG.options,...o})}\n`

       /* Object.keys(APP_CONFIG.options).forEach(k => {

            const item = APP_CONFIG.options[k]
            configContent += `export const ${k}=${JSON.stringify(item)}\n`

        })*/

        fs.writeFile(GENSRC_PATH + "/config.js", configContent, function (err) {
            if (err) {
                return console.log(err)
            }
        })

        /* ui */
        gensrcUi()

    })

}

function gensrcUi() {

    /* generate ui source */
    if (APP_CONFIG.ui) {

        const gendirUi = GENSRC_PATH + '/ui'
        try {
            fs.mkdirSync(gendirUi)
        } catch (err) {
            if (err.code !== 'EEXIST') throw err
        }

        fs.writeFile(gendirUi + "/variables.less", '', function (err) {
            if (err) {
                return console.log(err)
            }
        })

        APP_CONFIG.ui.forEach((ui) => {
            let gendirUiName = gendirUi
            if (ui.name) {
                gendirUiName += '/' + ui.name
                try {
                    fs.mkdirSync(gendirUiName)
                } catch (err) {
                    if (err.code !== 'EEXIST') throw err
                }
            }

            let uiContentIconsHooks = ''
            let uiContentIcons = `import React from 'react'\nimport Hook from 'util/hook'\n`
            let uiContent = `${GENSRC_HEADER}export * from 'client/components/ui/impl/${ui.impl || 'material'}/index'\nexport * from './icons'\n`

            if (ui.icons) {
                if (ui.impl === 'material') {
                    uiContentIcons += "import IconButton from 'material-ui/IconButton'\n"
                }

                //https://github.com/mui-org/material-ui/tree/v1-beta/packages/material-ui-icons/src
                ui.icons.forEach(icon => {
                    if (ui.impl === 'material') {
                        uiContentIcons += `
import ${icon}Icon from 'material-ui-icons/${icon}'
export {${icon}Icon}

export const ${icon}IconButton = ({...rest}) => {
    return <IconButton{...rest} >
        <${icon}Icon />
    </IconButton>
}
`
                        uiContentIconsHooks += `components['${icon}Icon'] = ${icon}Icon\ncomponents['${icon}IconButton'] = ${icon}IconButton\n`

                    }
                })
            }
            uiContentIcons += `Hook.on('JsonDom', ({components}) => {\n${uiContentIconsHooks}})`

            fs.writeFile(gendirUiName + '/icons.js', uiContentIcons, function (err) {
                if (err) {
                    return console.log(err)
                }
            })
            fs.writeFile(gendirUiName + "/index.js", uiContent, function (err) {
                if (err) {
                    return console.log(err)
                }
            })
        })
    }
}

function gensrcExtension(name, options) {
    if (!options) return

    const gendir = EXTENSION_PATH + name + '/' + GENSRC_PATH
    try {
        deleteFolderRecursive(path.resolve(__dirname, gendir))
        fs.mkdirSync(gendir)
    } catch (err) {
        if (err.code !== 'EEXIST') throw err
    }

    if (options && options.types) {

        let schema = GENSRC_HEADER + 'export default `\n'
        let resolver = GENSRC_HEADER + `import {ObjectId} from 'mongodb'\nimport {pubsub} from 'api/subscription'\nimport {withFilter} from 'graphql-subscriptions'\n`
        resolver += `import GenericResolver from 'api/resolver/generic/genericResolver'\n\nexport default db => ({\n`
        options.types.forEach((type) => {
            const nameStartLower = type.name.charAt(0).toLowerCase() + type.name.slice(1)
            schema += 'type ' + type.name + '{\n'
            schema += '\t_id: ID!\n\tcreatedBy: UserPublic!\n\tstatus: String\n'

            let mutationFields = '', resolverFields = '', refResolvers = '', refResolversObjectId = ''

            type.fields.forEach((field) => {
                const type = (field.type || 'String')
                let isRef = false

                if (COMMON_MONGO_TYPES.indexOf(type) < 0) {
                    // it might be a reference so we only need to store the ID
                    isRef = true
                    if (refResolvers !== '') refResolvers += ','
                    if (refResolversObjectId !== '') refResolversObjectId += ','
                    refResolvers += field.name
                    if (field.multi) {
                        refResolversObjectId += field.name + ':' + '(' + field.name + '?' + field.name + '.reduce((o,id) => {o.push(ObjectId(id)); return o},[]):' + field.name + ')'

                    } else {
                        refResolversObjectId += field.name + ':' + '(' + field.name + '?' + 'ObjectId(' + field.name + '):' + field.name + ')'
                    }
                }

                if (mutationFields !== '') mutationFields += ','
                if (resolverFields !== '') resolverFields += ','

                mutationFields += field.name + ':' + (field.multi ? '[' : '') + (isRef ? 'ID' : type) + (field.multi ? ']' : '')
                resolverFields += '\'' + field.name + (isRef ? '$' + (field.multi ? '[' : '') + type + (field.multi ? ']' : '') : '') + '\''

                schema += '\t' + field.name + ':' + (field.multi ? '[' : '') + type + (field.multi ? ']' : '') + '\n'
            })

            schema += '}\n\n'

            schema += 'type ' + type.name + 'Result {\n\tresults: [' + type.name + ']\n\toffset: Int\n\tlimit: Int\n\ttotal: Int\n}\n\n'

            // Maybe it is better to return only a Status instead of the whole type when create, update or delete is performed
            schema += 'type ' + type.name + 'Status {\n\t_id: ID!\n\tstatus: String\n}\n\n'

            schema += 'type Query {\n\t' + nameStartLower + 's(sort: String, limit: Int=10, offset: Int=0, page: Int=0, filter: String): ' + type.name + 'Result\n}\n\n'

            schema += 'type Mutation {\n'
            schema += '\tcreate' + type.name + ' (' + mutationFields + '):' + type.name + 'Status\n'
            schema += '\tupdate' + type.name + ' (_id: ID!' + (mutationFields.length > 0 ? ',' : '') + mutationFields + '):' + type.name + 'Status\n'
            schema += '\tdelete' + type.name + ' (_id: ID!):' + type.name + 'Status\n'
            schema += '}\n\n'

            schema += 'type ' + type.name + 'SubscribeResult {\n\tdata:' + type.name + '\n\taction: String\n}\n\n'

            schema += 'type Subscription {\n'
            schema += '    subscribe' + type.name + ': ' + type.name + 'SubscribeResult\n'
            schema += '}\n\n'

            resolver += `   ${nameStartLower}s: async ({sort, limit, offset, page, filter}, {context}) => {
        return await GenericResolver.entities(db, context, '${type.name}', [${resolverFields}], {limit, offset, page, filter, sort})
    },
    create${type.name}: async ({...rest,${refResolvers}}, {context}) => {
        pubsub.publish('subscribe${type.name}', {userId:context.id,subscribe${type.name}: {action: 'create',data:{...rest}}})
        return await GenericResolver.createEnity(db, context, '${type.name}', {...rest,${refResolversObjectId}})
    },
    update${type.name}: async ({...rest,${refResolvers}}, {context}) => {
        pubsub.publish('subscribe${type.name}', {userId:context.id,subscribe${type.name}: {action: 'update', data: {...rest}}})
        return GenericResolver.updateEnity(db, context, '${type.name}', {...rest,${refResolversObjectId}})
    },
    delete${type.name}: async ({_id}, {context}) => {
         pubsub.publish('subscribe${type.name}', {userId:context.id,subscribe${type.name}: {action: 'delete', data: {_id}}})
        return GenericResolver.deleteEnity(db, context, '${type.name}', {_id})
    },
    subscribe${type.name}: withFilter(() => pubsub.asyncIterator('subscribe${type.name}'),
		(payload, context) => {
            if( payload ) {
                //return payload.userId === context.id
                return true
            }
		}
	),\n`

        })
        schema += '`\n'
        resolver += `})`

        fs.writeFile(gendir + "/schema.js", schema, function (err) {
            if (err) {
                console.log(err)
            }
        })
        fs.writeFile(gendir + "/resolver.js", resolver, function (err) {
            if (err) {
                console.log(err)
            }
        })

    }

}

const deleteFolderRecursive = function (path) {
    if (fs.existsSync(path)) {
        fs.readdirSync(path).forEach(function (file, index) {
            var curPath = path + "/" + file
            if (fs.lstatSync(curPath).isDirectory()) { // recurse
                deleteFolderRecursive(curPath)
            } else { // delete file
                console.log('delete file ' + curPath)
                fs.unlinkSync(curPath)
            }
        });
        fs.rmdirSync(path)
    }
}

module.exports = GenSourceCode
<commit_msg>Small improvements<commit_after>/* generate sources */

const fs = require('fs')
const path = require('path')

const APP_CONFIG = require('./config.json')
const EXTENSION_PATH = './extensions/'
const GENSRC_HEADER = '/* this file was generated by webpack.config.js */\n\n'
const GENSRC_PATH = './gensrc';
const DEV_MODE = process.env.NODE_ENV !== 'production' && process.argv.indexOf('-p') === -1

const COMMON_MONGO_TYPES = ['String', 'Int', 'ID', 'Float', 'Boolean']

function GenSourceCode(options) {
    this.compiled = false
}

GenSourceCode.prototype.apply = function (compiler) {
    compiler.plugin("compile", function (p) {
        if (this.compiled) return
        this.compiled = true

        /* generete source code */
        console.log('Generating source code')

        try {
            deleteFolderRecursive(path.resolve(__dirname, GENSRC_PATH))
            fs.mkdirSync(GENSRC_PATH)
        } catch (err) {
            if (err.code !== 'EEXIST') throw err
        }

        const exteionsion = fs.readdirSync(EXTENSION_PATH)

        let clientContent = GENSRC_HEADER, serverContent = GENSRC_HEADER, manifestJson = {}

        exteionsion.forEach(file => {
            if (fs.statSync(EXTENSION_PATH + file).isDirectory()) {
                if (APP_CONFIG.extensions) {
                    const ext = APP_CONFIG.extensions[file]
                    if (ext && ext.active) {

                        if (fs.existsSync(EXTENSION_PATH + file + '/extension.json')) {
                            manifestJson[file] = JSON.parse(fs.readFileSync(EXTENSION_PATH + file + '/extension.json', 'utf8'));
                        } else {
                            manifestJson[file] = {name: file}
                        }

                        if (fs.existsSync(EXTENSION_PATH + file + '/build.json')) {
                            const buildOptions = require(EXTENSION_PATH + file + '/build.json')
                            manifestJson[file].options = buildOptions
                            gensrcExtension(file, buildOptions)
                        }

                        if (manifestJson[file].options && manifestJson[file].options.types) {

                            manifestJson[file].options.types.forEach(type => {

                                type.fields = type.fields.map(field => {
                                    if (field.type && COMMON_MONGO_TYPES.indexOf(field.type) < 0) {
                                        // this is a type reference
                                        field.reference = true
                                    }
                                    return field
                                })

                            })

                        }

                        /*if (fs.existsSync(extensionFolder + file + '/build.js')) {
                         const extensionBuild = require(extensionFolder + file + '/build.js')
                         const buildOptions = extensionBuild()
                         gensrcExtension(file,buildOptions)
                         }*/

                        if (fs.existsSync(EXTENSION_PATH + file + '/client.js')) {
                            clientContent += `import '.${EXTENSION_PATH}${file}/client.js'\n`
                        }
                        if (fs.existsSync(EXTENSION_PATH + file + '/server.js')) {
                            serverContent += `import '.${EXTENSION_PATH}${file}/server.js'\n`
                        }

                    }
                }
            }
        })

        const manifestStr = `${GENSRC_HEADER}const extensions=${JSON.stringify(manifestJson, null, 4)}\nexport default extensions`

        fs.writeFile(GENSRC_PATH + "/extensions.js", manifestStr, function (err) {
            if (err) {
                return console.log(err)
            }
        })

        fs.writeFile(GENSRC_PATH + "/extensions-client.js", clientContent, function (err) {
            if (err) {
                return console.log(err)
            }
        })
        fs.writeFile(GENSRC_PATH + "/extensions-server.js", serverContent, function (err) {
            if (err) {
                return console.log(err)
            }
        })

        /* generate config */
        const o ={DEV_MODE}
        let configContent = `${GENSRC_HEADER}export default ${JSON.stringify(Object.assign({},APP_CONFIG.options,o))}\n`

       /* Object.keys(APP_CONFIG.options).forEach(k => {

            const item = APP_CONFIG.options[k]
            configContent += `export const ${k}=${JSON.stringify(item)}\n`

        })*/

        fs.writeFile(GENSRC_PATH + "/config.js", configContent, function (err) {
            if (err) {
                return console.log(err)
            }
        })

        /* ui */
        gensrcUi()

    })

}

function gensrcUi() {

    /* generate ui source */
    if (APP_CONFIG.ui) {

        const gendirUi = GENSRC_PATH + '/ui'
        try {
            fs.mkdirSync(gendirUi)
        } catch (err) {
            if (err.code !== 'EEXIST') throw err
        }

        fs.writeFile(gendirUi + "/variables.less", '', function (err) {
            if (err) {
                return console.log(err)
            }
        })

        APP_CONFIG.ui.forEach((ui) => {
            let gendirUiName = gendirUi
            if (ui.name) {
                gendirUiName += '/' + ui.name
                try {
                    fs.mkdirSync(gendirUiName)
                } catch (err) {
                    if (err.code !== 'EEXIST') throw err
                }
            }

            let uiContentIconsHooks = ''
            let uiContentIcons = `import React from 'react'\nimport Hook from 'util/hook'\n`
            let uiContent = `${GENSRC_HEADER}export * from 'client/components/ui/impl/${ui.impl || 'material'}/index'\nexport * from './icons'\n`

            if (ui.icons) {
                if (ui.impl === 'material') {
                    uiContentIcons += "import IconButton from 'material-ui/IconButton'\n"
                }

                //https://github.com/mui-org/material-ui/tree/v1-beta/packages/material-ui-icons/src
                ui.icons.forEach(icon => {
                    if (ui.impl === 'material') {
                        uiContentIcons += `
import ${icon}Icon from 'material-ui-icons/${icon}'
export {${icon}Icon}

export const ${icon}IconButton = ({...rest}) => {
    return <IconButton{...rest} >
        <${icon}Icon />
    </IconButton>
}
`
                        uiContentIconsHooks += `components['${icon}Icon'] = ${icon}Icon\ncomponents['${icon}IconButton'] = ${icon}IconButton\n`

                    }
                })
            }
            uiContentIcons += `Hook.on('JsonDom', ({components}) => {\n${uiContentIconsHooks}})`

            fs.writeFile(gendirUiName + '/icons.js', uiContentIcons, function (err) {
                if (err) {
                    return console.log(err)
                }
            })
            fs.writeFile(gendirUiName + "/index.js", uiContent, function (err) {
                if (err) {
                    return console.log(err)
                }
            })
        })
    }
}

function gensrcExtension(name, options) {
    if (!options) return

    const gendir = EXTENSION_PATH + name + '/' + GENSRC_PATH
    try {
        deleteFolderRecursive(path.resolve(__dirname, gendir))
        fs.mkdirSync(gendir)
    } catch (err) {
        if (err.code !== 'EEXIST') throw err
    }

    if (options && options.types) {

        let schema = GENSRC_HEADER + 'export default `\n'
        let resolver = GENSRC_HEADER + `import {ObjectId} from 'mongodb'\nimport {pubsub} from 'api/subscription'\nimport {withFilter} from 'graphql-subscriptions'\n`
        resolver += `import GenericResolver from 'api/resolver/generic/genericResolver'\n\nexport default db => ({\n`
        options.types.forEach((type) => {
            const nameStartLower = type.name.charAt(0).toLowerCase() + type.name.slice(1)
            schema += 'type ' + type.name + '{\n'
            schema += '\t_id: ID!\n\tcreatedBy: UserPublic!\n\tstatus: String\n'

            let mutationFields = '', resolverFields = '', refResolvers = '', refResolversObjectId = ''

            type.fields.forEach((field) => {
                const type = (field.type || 'String')
                let isRef = false

                if (COMMON_MONGO_TYPES.indexOf(type) < 0) {
                    // it might be a reference so we only need to store the ID
                    isRef = true
                    if (refResolvers !== '') refResolvers += ','
                    if (refResolversObjectId !== '') refResolversObjectId += ','
                    refResolvers += field.name
                    if (field.multi) {
                        refResolversObjectId += field.name + ':' + '(' + field.name + '?' + field.name + '.reduce((o,id) => {o.push(ObjectId(id)); return o},[]):' + field.name + ')'

                    } else {
                        refResolversObjectId += field.name + ':' + '(' + field.name + '?' + 'ObjectId(' + field.name + '):' + field.name + ')'
                    }
                }

                if (mutationFields !== '') mutationFields += ','
                if (resolverFields !== '') resolverFields += ','

                mutationFields += field.name + ':' + (field.multi ? '[' : '') + (isRef ? 'ID' : type) + (field.multi ? ']' : '')
                resolverFields += '\'' + field.name + (isRef ? '$' + (field.multi ? '[' : '') + type + (field.multi ? ']' : '') : '') + '\''

                schema += '\t' + field.name + ':' + (field.multi ? '[' : '') + type + (field.multi ? ']' : '') + '\n'
            })

            schema += '}\n\n'

            schema += 'type ' + type.name + 'Result {\n\tresults: [' + type.name + ']\n\toffset: Int\n\tlimit: Int\n\ttotal: Int\n}\n\n'

            // Maybe it is better to return only a Status instead of the whole type when create, update or delete is performed
            schema += 'type ' + type.name + 'Status {\n\t_id: ID!\n\tstatus: String\n}\n\n'

            schema += 'type Query {\n\t' + nameStartLower + 's(sort: String, limit: Int=10, offset: Int=0, page: Int=0, filter: String): ' + type.name + 'Result\n}\n\n'

            schema += 'type Mutation {\n'
            schema += '\tcreate' + type.name + ' (' + mutationFields + '):' + type.name + 'Status\n'
            schema += '\tupdate' + type.name + ' (_id: ID!' + (mutationFields.length > 0 ? ',' : '') + mutationFields + '):' + type.name + 'Status\n'
            schema += '\tdelete' + type.name + ' (_id: ID!):' + type.name + 'Status\n'
            schema += '}\n\n'

            schema += 'type ' + type.name + 'SubscribeResult {\n\tdata:' + type.name + '\n\taction: String\n}\n\n'

            schema += 'type Subscription {\n'
            schema += '    subscribe' + type.name + ': ' + type.name + 'SubscribeResult\n'
            schema += '}\n\n'

            resolver += `   ${nameStartLower}s: async ({sort, limit, offset, page, filter}, {context}) => {
        return await GenericResolver.entities(db, context, '${type.name}', [${resolverFields}], {limit, offset, page, filter, sort})
    },
    create${type.name}: async ({...rest,${refResolvers}}, {context}) => {
        pubsub.publish('subscribe${type.name}', {userId:context.id,subscribe${type.name}: {action: 'create',data:{...rest}}})
        return await GenericResolver.createEnity(db, context, '${type.name}', {...rest,${refResolversObjectId}})
    },
    update${type.name}: async ({...rest,${refResolvers}}, {context}) => {
        pubsub.publish('subscribe${type.name}', {userId:context.id,subscribe${type.name}: {action: 'update', data: {...rest}}})
        return GenericResolver.updateEnity(db, context, '${type.name}', {...rest,${refResolversObjectId}})
    },
    delete${type.name}: async ({_id}, {context}) => {
         pubsub.publish('subscribe${type.name}', {userId:context.id,subscribe${type.name}: {action: 'delete', data: {_id}}})
        return GenericResolver.deleteEnity(db, context, '${type.name}', {_id})
    },
    subscribe${type.name}: withFilter(() => pubsub.asyncIterator('subscribe${type.name}'),
		(payload, context) => {
            if( payload ) {
                //return payload.userId === context.id
                return true
            }
		}
	),\n`

        })
        schema += '`\n'
        resolver += `})`

        fs.writeFile(gendir + "/schema.js", schema, function (err) {
            if (err) {
                console.log(err)
            }
        })
        fs.writeFile(gendir + "/resolver.js", resolver, function (err) {
            if (err) {
                console.log(err)
            }
        })

    }

}

const deleteFolderRecursive = function (path) {
    if (fs.existsSync(path)) {
        fs.readdirSync(path).forEach(function (file, index) {
            var curPath = path + "/" + file
            if (fs.lstatSync(curPath).isDirectory()) { // recurse
                deleteFolderRecursive(curPath)
            } else { // delete file
                console.log('delete file ' + curPath)
                fs.unlinkSync(curPath)
            }
        });
        fs.rmdirSync(path)
    }
}

module.exports = GenSourceCode
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import Paper from 'material-ui/Paper'
import CircularProgress from 'material-ui/CircularProgress'
import RaisedButton from 'material-ui/RaisedButton';
import FontIcon from 'material-ui/FontIcon';
import { Link } from 'react-router'
import Statistics from '../Statistics/Statistics'
import './Home.css'

class Home extends Component {
  constructor(props) {
    super(props)
    this.state = {data: undefined}
    this.getData()
  }

  getData() {
    if (!this.state.data) {
      return fetch(`https://inspire.data.gouv.fr/api/datasets/metrics`)
        .then((response) => response.json())
        .then((data) => {
          this.setState({data})
        })
        .catch((err) => {
          console.error(err)
        })
      }
  }

  render() {
    const loader =  <CircularProgress size={1.5} />
    const notMatchingAnymore = this.state.data ? <Statistics value={this.state.data.notMatchingAnymore} label="Warning" color="red" icon="warning sign" /> : loader
    const published = this.state.data ? <Statistics value={this.state.data.published.public + this.state.data.published.private} label="Catalogs" color="green" icon="database"/> : loader
    const notPublishedYet = this.state.data ? <Statistics value={this.state.data.notPublishedYet} label="Work In Progress" color="yellow" icon="hourglass half"/> : loader

    const style = {
      width: 250,
      height: 250,
      padding: 20,
      margin: 20,
      textAlign: 'center',
      display: 'inline-block',
    };

    return (

            Inspire

            Votre organisation gère des données géographiques avec des outils compatibles Inspire et souhaite les rendre disponibles sans effort sur data.gouv.fr.

          <Link to="catalogs">
            <RaisedButton label="Catalogs" primary={true}  icon={<FontIcon className="muidocs-icon-custom-github" />} />
          </Link>

        <Paper style={style} rounded={true} zDepth={1}>

Need Attention

          {notMatchingAnymore}
        </Paper>

        <Paper style={style} rounded={true} zDepth={1}>

Dataset

          {published}
        </Paper>

        <Paper style={style} rounded={true} zDepth={1}>

Awaiting Publication

          {notPublishedYet}
        </Paper>

    )
  }
}

export default Home
<commit_msg>Increase zDepth of Home Paper<commit_after>import React, { Component } from 'react'
import Paper from 'material-ui/Paper'
import CircularProgress from 'material-ui/CircularProgress'
import RaisedButton from 'material-ui/RaisedButton';
import FontIcon from 'material-ui/FontIcon';
import { Link } from 'react-router'
import Statistics from '../Statistics/Statistics'
import './Home.css'

class Home extends Component {
  constructor(props) {
    super(props)
    this.state = {data: undefined}
    this.getData()
  }

  getData() {
    if (!this.state.data) {
      return fetch(`https://inspire.data.gouv.fr/api/datasets/metrics`)
        .then((response) => response.json())
        .then((data) => {
          this.setState({data})
        })
        .catch((err) => {
          console.error(err)
        })
      }
  }

  render() {
    const loader =  <CircularProgress size={1.5} />
    const notMatchingAnymore = this.state.data ? <Statistics value={this.state.data.notMatchingAnymore} label="Warning" color="red" icon="warning sign" /> : loader
    const published = this.state.data ? <Statistics value={this.state.data.published.public + this.state.data.published.private} label="Catalogs" color="green" icon="database"/> : loader
    const notPublishedYet = this.state.data ? <Statistics value={this.state.data.notPublishedYet} label="Work In Progress" color="yellow" icon="hourglass half"/> : loader

    const style = {
      width: 250,
      height: 250,
      padding: 20,
      margin: 20,
      textAlign: 'center',
      display: 'inline-block',
    };

    return (

            Inspire

            Votre organisation gère des données géographiques avec des outils compatibles Inspire et souhaite les rendre disponibles sans effort sur data.gouv.fr.

          <Link to="catalogs">
            <RaisedButton label="Catalogs" primary={true}  icon={<FontIcon className="muidocs-icon-custom-github" />} />
          </Link>

        <Paper style={style} rounded={true} zDepth={2}>

Need Attention

          {notMatchingAnymore}
        </Paper>

        <Paper style={style} rounded={true} zDepth={2}>

Dataset

          {published}
        </Paper>

        <Paper style={style} rounded={true} zDepth={2}>

Awaiting Publication

          {notPublishedYet}
        </Paper>

    )
  }
}

export default Home
<|endoftext|>


<commit_before>'use strict';

const Lambda = require('./Lambda');
const AuthorizerLambda = require('./AuthorizerLambda');

/**
 * Handles API Gateway HTTP Event
 */
class HttpEvent {

  /**
   * Constructor
   *
   * @param {Object} serverless
   * @param {String} functionName
   * @param {Object} httpEventObj
   */
  constructor(serverless, functionName, httpEventObj) {
    this.serverless = serverless;
    this.functionName = functionName;
    let httpEvent = httpEventObj;

    // Endpoint can be a string eg "GET sub/resource"
    if (typeof httpEvent === 'string') {
      const endpointString = httpEvent.split(' ');
      httpEvent = {};
      httpEvent.method = endpointString[0].toLowerCase();
      httpEvent.path = endpointString[1].toLowerCase();
    }

    // These will check against invalid configuration
    if (!httpEvent.method) {
      throw new Error(`Endpoint for λ ${functionName} has no method`);
    }
    if (!httpEvent.path) {
      throw new Error(`Endpoint for λ ${functionName} has no path`);
    }

    // Express.js has 'all()' method for handling any of http methods
    // in aws the method is called 'ANY'
    if (httpEvent.method.toLowerCase() === 'any') {
      this.httpMethod = 'all';
    } else {
      this.httpMethod = httpEvent.method.toLowerCase();
    }

    // Rewrite APIG path parameters to express.js format
    // eg /resource/{id} => /resource/:id
    this.httpPath = `/${httpEvent.path.replace(/{/g, ':').replace(/}/g, '')}`;

    // Validate authorizer if provided
    if (httpEvent.authorizer) {
      // Validate authorizer's configuration
      if (typeof httpEvent.authorizer.name !== 'string' || httpEvent.authorizer.name.length < 1) {
        throw new Error(`Invalid authorizer name for λ ${functionName}`);
      }
      if (typeof httpEvent.authorizer.identitySource !== 'string') {
        throw new Error(`Invalid identitySource for λ ${functionName}`);
      }
      if (httpEvent.authorizer.identitySource.length < 1) {
        throw new Error(`Invalid identitySource for λ ${functionName}`);
      }
      if (httpEvent.authorizer.identitySource.indexOf('method.request.header.') !== 0) {
        throw new Error(`Expected method.request.header.* in identitySource for λ ${functionName}`);
      }

      this.authorizer = httpEvent.authorizer;
    }
  }

  /**
   * Get HTTP method (eg. "get" "post" etc..)
   *
   * @returns {string|*}
   */
  getHttpMethod() {
    return this.httpMethod;
  }

  /**
   * Get HTTP path (eg. "resource/sub-resource" etc..)
   *
   * @returns {string|*}
   */
  getHttpPath() {
    return this.httpPath;
  }

  /**
   * Serverless function handler
   *
   * @param {String} handler
   */
  setFunctionHandler(handler) {
    this.handlerPath = handler.split('.')[0];
    this.handlerName = handler.split('/').pop().split('.')[1];
    this.functionPath = `${process.cwd()}/${this.handlerPath}`;
  }

  /**
   * Route express.js request via serverless handler
   *
   * @param {Object} request
   * @param {Object} response
   */
  route(request, response) {
    const stage = this.serverless.service.provider.stage || 'dev';
    const env = this.serverless.service.provider.environment || {}; // TODO: Merge with function obj
    const lambda = new Lambda(this.functionPath, this.handlerName, env);

    const event = lambda.buildEventFromRequest(request, stage);
    const context = lambda.buildContext();
    const callback = (failure, result) => {
      if (failure) {
        const errorMessage = JSON.stringify(failure);
        this.serverless.cli.log(`λ ${this.functionName} returned error: ${errorMessage}`);
      }

      // Lambda did not fail but also did not succeed
      if (!result || typeof result !== 'object') {
        response
          .status(500)
          .send('Internal server error');
        return;
      }

      const headers = result.headers || {};

      // APIG defaults 'Content-Type' if not provided
      if (!headers['Content-Type'] && !headers['content-type']) {
        headers['Content-Type'] = 'application/json';
      }

      response.status(result.statusCode || 200);
      response.set(headers);

      if (result.body) {
        response.send(result.body);
      } else {
        response.end();
      }
    };

    // Create authorize function if the endpoint requires it
    if (this.authorizer) {
      const authorizer = new AuthorizerLambda(this.serverless, this.authorizer);
      const authorizerEvent = authorizer.buildEventFromRequest(request);
      const authorizerContext = authorizer.buildContext();

      if (authorizerEvent === null) {
        response
          .status(403)
          .set({ 'Content-Type': 'application/json' })
          .send(JSON.stringify({ message: 'Unauthorized' }));
        return;
      }

      authorizer.authorize(authorizerEvent, authorizerContext, (err, res) => {
        if (err) {
          // This is the default returned by APIG in case of authentication failure
          this.serverless.cli.log(`Auth λ ${this.functionName} ERROR: ${err}`);
          response
            .status(403)
            .set({ 'Content-Type': 'application/json' })
            .send(JSON.stringify({ message: 'Unauthorized' }));
        } else if (typeof res.principalId !== 'string' && typeof res.principalId !== 'number') {
          this.serverless.cli.log(`Auth λ ${this.functionName} returned invalid principalId`);
          response
            .status(403)
            .set({ 'Content-Type': 'application/json' })
            .send(JSON.stringify({ message: 'Unauthorized' }));
        } else {
          event.requestContext.authorizer = {};

          // APIG allows to pass through additional string variables in 'context'
          if (typeof res.context === 'object') {
            Object.keys(res.context).forEach((key) => {
              event.requestContext.authorizer[`${key}`] = `${res.context[key]}`;
            });
          }

          // APIG always parses principalId to string
          event.requestContext.authorizer.principalId = `${res.principalId}`;

          // Call the function authorizers
          try {
            lambda.invoke(event, context, callback);
          } catch (e) {
            this.serverless.cli.log(e);
            response
              .status(500)
              .send(`λ ${this.functionName} Caught ERROR: ${e.message}`);
          }
        }
      });
    } else {
      // Call the function w/o authorizers
      try {
        lambda.invoke(event, context, callback);
      } catch (e) {
        this.serverless.cli.log(e);
        response
          .status(500)
          .send(`λ ${this.functionName} Caught ERROR: ${e.message}`);
      }
    }
  }
}

module.exports = HttpEvent;
<commit_msg>Set AWS_PROFILE is provided in serverless provider.profile<commit_after>'use strict';

const Lambda = require('./Lambda');
const AuthorizerLambda = require('./AuthorizerLambda');

/**
 * Handles API Gateway HTTP Event
 */
class HttpEvent {

  /**
   * Constructor
   *
   * @param {Object} serverless
   * @param {String} functionName
   * @param {Object} httpEventObj
   */
  constructor(serverless, functionName, httpEventObj) {
    this.serverless = serverless;
    this.functionName = functionName;
    let httpEvent = httpEventObj;

    // Endpoint can be a string eg "GET sub/resource"
    if (typeof httpEvent === 'string') {
      const endpointString = httpEvent.split(' ');
      httpEvent = {};
      httpEvent.method = endpointString[0].toLowerCase();
      httpEvent.path = endpointString[1].toLowerCase();
    }

    // These will check against invalid configuration
    if (!httpEvent.method) {
      throw new Error(`Endpoint for λ ${functionName} has no method`);
    }
    if (!httpEvent.path) {
      throw new Error(`Endpoint for λ ${functionName} has no path`);
    }

    // Express.js has 'all()' method for handling any of http methods
    // in aws the method is called 'ANY'
    if (httpEvent.method.toLowerCase() === 'any') {
      this.httpMethod = 'all';
    } else {
      this.httpMethod = httpEvent.method.toLowerCase();
    }

    // Rewrite APIG path parameters to express.js format
    // eg /resource/{id} => /resource/:id
    this.httpPath = `/${httpEvent.path.replace(/{/g, ':').replace(/}/g, '')}`;

    // Validate authorizer if provided
    if (httpEvent.authorizer) {
      // Validate authorizer's configuration
      if (typeof httpEvent.authorizer.name !== 'string' || httpEvent.authorizer.name.length < 1) {
        throw new Error(`Invalid authorizer name for λ ${functionName}`);
      }
      if (typeof httpEvent.authorizer.identitySource !== 'string') {
        throw new Error(`Invalid identitySource for λ ${functionName}`);
      }
      if (httpEvent.authorizer.identitySource.length < 1) {
        throw new Error(`Invalid identitySource for λ ${functionName}`);
      }
      if (httpEvent.authorizer.identitySource.indexOf('method.request.header.') !== 0) {
        throw new Error(`Expected method.request.header.* in identitySource for λ ${functionName}`);
      }

      this.authorizer = httpEvent.authorizer;
    }
  }

  /**
   * Get HTTP method (eg. "get" "post" etc..)
   *
   * @returns {string|*}
   */
  getHttpMethod() {
    return this.httpMethod;
  }

  /**
   * Get HTTP path (eg. "resource/sub-resource" etc..)
   *
   * @returns {string|*}
   */
  getHttpPath() {
    return this.httpPath;
  }

  /**
   * Serverless function handler
   *
   * @param {String} handler
   */
  setFunctionHandler(handler) {
    this.handlerPath = handler.split('.')[0];
    this.handlerName = handler.split('/').pop().split('.')[1];
    this.functionPath = `${process.cwd()}/${this.handlerPath}`;
  }

  /**
   * Route express.js request via serverless handler
   *
   * @param {Object} request
   * @param {Object} response
   */
  route(request, response) {
    const stage = this.serverless.service.provider.stage || 'dev';
    const env = this.serverless.service.provider.environment || {}; // TODO: Merge with function obj
    if (this.serverless.service.provider.profile) {
      env.AWS_PROFILE = this.serverless.service.provider.profile;
    }

    const lambda = new Lambda(this.functionPath, this.handlerName, env);
    const event = lambda.buildEventFromRequest(request, stage);
    const context = lambda.buildContext();
    const callback = (failure, result) => {
      if (failure) {
        const errorMessage = JSON.stringify(failure);
        this.serverless.cli.log(`λ ${this.functionName} returned error: ${errorMessage}`);
      }

      // Lambda did not fail but also did not succeed
      if (!result || typeof result !== 'object') {
        response
          .status(500)
          .send('Internal server error');
        return;
      }

      const headers = result.headers || {};

      // APIG defaults 'Content-Type' if not provided
      if (!headers['Content-Type'] && !headers['content-type']) {
        headers['Content-Type'] = 'application/json';
      }

      response.status(result.statusCode || 200);
      response.set(headers);

      if (result.body) {
        response.send(result.body);
      } else {
        response.end();
      }
    };

    // Create authorize function if the endpoint requires it
    if (this.authorizer) {
      const authorizer = new AuthorizerLambda(this.serverless, this.authorizer);
      const authorizerEvent = authorizer.buildEventFromRequest(request);
      const authorizerContext = authorizer.buildContext();

      if (authorizerEvent === null) {
        response
          .status(403)
          .set({ 'Content-Type': 'application/json' })
          .send(JSON.stringify({ message: 'Unauthorized' }));
        return;
      }

      authorizer.authorize(authorizerEvent, authorizerContext, (err, res) => {
        if (err) {
          // This is the default returned by APIG in case of authentication failure
          this.serverless.cli.log(`Auth λ ${this.functionName} ERROR: ${err}`);
          response
            .status(403)
            .set({ 'Content-Type': 'application/json' })
            .send(JSON.stringify({ message: 'Unauthorized' }));
        } else if (typeof res.principalId !== 'string' && typeof res.principalId !== 'number') {
          this.serverless.cli.log(`Auth λ ${this.functionName} returned invalid principalId`);
          response
            .status(403)
            .set({ 'Content-Type': 'application/json' })
            .send(JSON.stringify({ message: 'Unauthorized' }));
        } else {
          event.requestContext.authorizer = {};

          // APIG allows to pass through additional string variables in 'context'
          if (typeof res.context === 'object') {
            Object.keys(res.context).forEach((key) => {
              event.requestContext.authorizer[`${key}`] = `${res.context[key]}`;
            });
          }

          // APIG always parses principalId to string
          event.requestContext.authorizer.principalId = `${res.principalId}`;

          // Call the function authorizers
          try {
            lambda.invoke(event, context, callback);
          } catch (e) {
            this.serverless.cli.log(e);
            response
              .status(500)
              .send(`λ ${this.functionName} Caught ERROR: ${e.message}`);
          }
        }
      });
    } else {
      // Call the function w/o authorizers
      try {
        lambda.invoke(event, context, callback);
      } catch (e) {
        this.serverless.cli.log(e);
        response
          .status(500)
          .send(`λ ${this.functionName} Caught ERROR: ${e.message}`);
      }
    }
  }
}

module.exports = HttpEvent;
<|endoftext|>


<commit_before>/**
 *  Copyright (c) 2014-2015, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 */

import { Seq } from './Seq'
import { Collection } from './Collection'
import { OrderedMap } from './OrderedMap'
import { List } from './List'
import { Map } from './Map'
import { Stack } from './Stack'
import { OrderedSet } from './OrderedSet'
import { Set } from './Set'
import { Record } from './Record'
import { Range } from './Range'
import { Repeat } from './Repeat'
import { is } from './is'
import { fromJS } from './fromJS'
import { Iterable } from './IterableImpl'

export default {

  Iterable: Iterable,

  Seq: Seq,
  Collection: Collection,
  Map: Map,
  OrderedMap: OrderedMap,
  List: List,
  Stack: Stack,
  Set: Set,
  OrderedSet: OrderedSet,

  Record: Record,
  Range: Range,
  Repeat: Repeat,

  is: is,
  fromJS: fromJS

};

export {
	Iterable,

	Seq,
	Collection,
	Map,
	OrderedMap,
	List,
	Stack,
	Set,
	OrderedSet,

	Record,
	Range,
	Repeat,

	is,
	fromJS
}
<commit_msg>export hash function (#1041)<commit_after>/**
 *  Copyright (c) 2014-2015, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 */

import { Seq } from './Seq'
import { Collection } from './Collection'
import { OrderedMap } from './OrderedMap'
import { List } from './List'
import { Map } from './Map'
import { Stack } from './Stack'
import { OrderedSet } from './OrderedSet'
import { Set } from './Set'
import { Record } from './Record'
import { Range } from './Range'
import { Repeat } from './Repeat'
import { is } from './is'
import { fromJS } from './fromJS'
import { hash } from './Hash'
import { Iterable } from './IterableImpl'

export default {

  Iterable: Iterable,

  Seq: Seq,
  Collection: Collection,
  Map: Map,
  OrderedMap: OrderedMap,
  List: List,
  Stack: Stack,
  Set: Set,
  OrderedSet: OrderedSet,

  Record: Record,
  Range: Range,
  Repeat: Repeat,

  is: is,
  fromJS: fromJS,
  hash: hash

};

export {
  Iterable,

  Seq,
  Collection,
  Map,
  OrderedMap,
  List,
  Stack,
  Set,
  OrderedSet,

  Record,
  Range,
  Repeat,

  is,
  fromJS,
  hash
}
<|endoftext|>


<commit_before>import React from 'react';

export default class InputLink extends React.Component {

  static propTypes = {
    children: React.PropTypes.oneOfType([
      React.PropTypes.node,
      React.PropTypes.element
    ]),
    wrapper: React.PropTypes.object,
    wrapperClassName: React.PropTypes.string,
    wrapperStyle: React.PropTypes.string
  }

  constructor(props) {
    super(props);
    this.state = { width: 1, height: 1 };
  }

  componentDidMount() {
    this.computeChildrenSize();
  }

  computeChildrenSize = () => {
    const childrenWrapper = this.refs.childrenWrapper.nodeType === 1 ?
      this.refs.childrenWrapper :
      this.refs.childrenWrapper.getDOMNode();
    const { clientWidth, clientHeight } = childrenWrapper;
    if (clientWidth !== this.state.width || clientHeight !== this.state.height) {
      this.setState({
        height: clientHeight,
        width: clientWidth
      });
    }
  }

  getInputStyle = () => {
    return {
      ...this.props.style,
      paddingRight: this.state.width,
      width: '100%',
      boxSizing: 'border-box'
    };
  }

  getChildrenStyle = () => {
    return {
      position: 'absolute',
      top: '50%',
      right: 0,
      marginTop: -1 * (this.state.height / 2)
    };
  }

  render() {
    const {
      children,
      wrapper = {}, wrapperClassName, wrapperStyle,
      ...inputProps
    } = this.props;

    const wrapperProps = {
      ...wrapper,
      className: wrapper.className || wrapperClassName,
      style: {
        ...(wrapper.style || wrapperStyle),
        position: 'relative'
      }
    };

    return (

        <input {...inputProps} style={this.getInputStyle()} />

          {children}

    );
  }

  componentDidUpdate() {
    this.computeChildrenSize();
  }

}
<commit_msg>remove wrapperClassName and wrapperStyle<commit_after>import React from 'react';

export default class InputLink extends React.Component {

  static propTypes = {
    children: React.PropTypes.oneOfType([
      React.PropTypes.node,
      React.PropTypes.element
    ]),
    wrapper: React.PropTypes.object
  }

  static defaultProps = {
    wrapper: {}
  }

  constructor(props) {
    super(props);
    this.state = { width: 1, height: 1 };
  }

  componentDidMount() {
    this.computeChildrenSize();
  }

  computeChildrenSize = () => {
    const childrenWrapper = this.refs.childrenWrapper.nodeType === 1 ?
      this.refs.childrenWrapper :
      this.refs.childrenWrapper.getDOMNode();
    const { clientWidth, clientHeight } = childrenWrapper;
    if (clientWidth !== this.state.width || clientHeight !== this.state.height) {
      this.setState({
        height: clientHeight,
        width: clientWidth
      });
    }
  }

  getInputStyle = () => {
    return {
      ...this.props.style,
      paddingRight: this.state.width,
      width: '100%',
      boxSizing: 'border-box'
    };
  }

  getChildrenStyle = () => {
    return {
      position: 'absolute',
      top: '50%',
      right: 0,
      marginTop: -1 * (this.state.height / 2)
    };
  }

  render() {
    const {
      children,
      wrapper,
      ...inputProps
    } = this.props;

    const wrapperProps = {
      ...wrapper,
      style: {
        ...wrapper.style,
        position: 'relative'
      }
    };

    return (

        <input {...inputProps} style={this.getInputStyle()} />

          {children}

    );
  }

  componentDidUpdate() {
    this.computeChildrenSize();
  }

}
<|endoftext|>


<commit_before>import { colorSample } from './_helpers';

export default class PartyPipe {
  constructor(attributes) {
    this.height = attributes.pipe.height;
    this.width = attributes.pipe.width;
    this.x = attributes.pipe.x;
    this.y = 0;
    this.color = colorSample(attributes.colors);
    this.speed = attributes.pipe.speed;
  }

  render(state){
    state.context.fillStyle = this.color;
    state.context.fillRect(this.x -= this.speed, this.y, this.width, this.height);
  }
}
<commit_msg>fix party pipe color<commit_after>import { colorSample } from './_helpers';

export default class PartyPipe {
  constructor(attributes) {
    this.height = attributes.pipe.height;
    this.width = attributes.pipe.width;
    this.x = attributes.pipe.x;
    this.y = 0;
    this.color = attributes.pipe.color;
    this.speed = attributes.pipe.speed;
  }

  render(state){
    state.context.fillStyle = this.color;
    state.context.fillRect(this.x -= this.speed, this.y, this.width, this.height);
  }
}
<|endoftext|>