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

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

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

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

/*
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = function (options) {
	isProd = options.env === 'production';
	if (isProd) {
		METADATA.baseUrl = '/a2ws/'
	} else {
    METADATA.baseUrl = '/a2wst/'
  }
	return {
		// required (output.publicPath) by html-elements-plugin below
		output: {
			// some plugins need publicPath (e.g. html-elements-plugin)
			publicPath: METADATA.baseUrl
		},

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

		/*
		 * The entry point for the bundle
		 * Our Angular.js app
		 *
		 * See: http://webpack.github.io/docs/configuration.html#entry
		 */
		entry: {

			'polyfills': './src/polyfills.browser.ts',
			'vendor': './src/vendor.browser.ts',
			'main': './src/main.browser.ts'

		},

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

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

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

		},

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

			rules: [

				/*
				 * Typescript loader support for .ts and Angular 2 async routes via .async.ts
				 * Replace templateUrl and stylesUrl with require()
				 *
				 * See: https://github.com/s-panferov/awesome-typescript-loader
				 * See: https://github.com/TheLarkInn/angular2-template-loader
				 */
				{
					test: /\.ts$/,
					use: [
						'@angularclass/hmr-loader?pretty=' + !isProd + '&prod=' + isProd,
						'awesome-typescript-loader',
						'angular2-template-loader',
						'angular-router-loader'
					],
					exclude: [/\.(spec|e2e)\.ts$/]
				},

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

				// for bootstrap (before other css tests)
				{
					test: /\.css$/,
					loader: ['style-loader', 'css-loader'],
					exclude: helpers.root('src'),
					include: helpers.root('node_modules')
				},

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

				/* Raw loader support for *.html
				 * Returns file content as string
				 *
				 * See: https://github.com/webpack/raw-loader
				 */
				{
					test: /\.html$/,
					// raw-loader vs html-loader
					// http://stackoverflow.com/questions/35400733/webpack-and-angular-html-image-loading
					loaders: [
						"html-loader?" + JSON.stringify({
							attrs: ["img:src"]
						})
					],
					exclude: [helpers.root('src/index.html')]
				},

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

				// for bootstrap
				{test: /\.png$/, loader: "url-loader?limit=100"},
				{test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=1000&mimetype=application/vnd.ms-fontobject"},
				{test: /\.(woff|woff2)$/, loader: "url-loader?limit=1000&mimetype=application/font-woff"},
				{test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=1000&mimetype=application/octet-stream"},
				{
					test: /\.(gif|jpe?g|svg)$/i,
					loaders: [
						// image-webpack-loader chained with the file-loader (equivalent to: file?...!image-webpack?...)
						// [name]-[hash].[ext] will break glyphicon
						// [name].[hash].[ext] and [hash].[name].[ext] are ok but will generate without "[name]."
						'file-loader?hash=sha512&digest=hex&name=[hash].[name].[ext]',
						'image-webpack-loader?bypassOnDebug=true&optimizationLevel=7&interlaced=false'
					]
				}

			],

		},

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

			/*
			 * Plugin: ForkCheckerPlugin
			 * Description: Do type checking in a separate process, so webpack don't need to wait.
			 *
			 * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
			 */
			new ForkCheckerPlugin(),
			/*
			 * Plugin: CommonsChunkPlugin
			 * Description: Shares common code between the pages.
			 * It identifies common modules and put them into a commons chunk.
			 *
			 * See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
			 * See: https://github.com/webpack/docs/wiki/optimization#multi-page-app
			 */
      new CommonsChunkPlugin({
        name: ['polyfills', 'vendor'].reverse()
      }),

      /**
       * +detail module (e.g. detail.css) goes to 0.[hash].chunk.js
       * referred by webpack-runtime.[hash].bundle.js
       * When 0.[hash].chunk.js change than
       * webpack-runtime.[hash].bundle.js also must change.
       * ['webpack-runtime', 'polyfills', 'vendor'].reverse()
       * in above CommonsChunkPlugin doesn't work because will
       * use filename: '[name].[chunkhash].bundle.js' (see webpack.prod.js).
       *
       * https://webpack.github.io/docs/long-term-caching.html#option-1-one-hash-for-the-bundle
       * [hash] generates a hash of all chunks
       * [chunkhash] generates a hash per chunk
       */
      new CommonsChunkPlugin({
        name: 'webpack-runtime',
        filename: '[name].[hash].bundle.js'
      }),

      /**
			 * Plugin: ContextReplacementPlugin
			 * Description: Provides context to Angular's use of System.import
			 *
			 * See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin
			 * See: https://github.com/angular/angular/issues/11580
			 */
			new ContextReplacementPlugin(
				// The (\\|\/) piece accounts for path separators in *nix and Windows
				/angular(\\|\/)core(\\|\/)src(\\|\/)linker/,
				helpers.root('src'), // location of your src
				{
					// your Angular Async Route paths relative to this root directory
				}
			),

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

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

			/*
			 * Plugin: ScriptExtHtmlWebpackPlugin
			 * Description: Enhances html-webpack-plugin functionality
			 * with different deployment options for your scripts including:
			 *
			 * See: https://github.com/numical/script-ext-html-webpack-plugin
			 */
			new ScriptExtHtmlWebpackPlugin({
				defaultAttribute: 'defer'
			}),

			/*
			 * Plugin: HtmlElementsPlugin
			 * Description: Generate html tags based on javascript maps.
			 *
			 * If a publicPath is set in the webpack output configuration, it will be automatically added to
			 * href attributes, you can disable that by adding a "=href": false property.
			 * You can also enable it to other attribute by settings "=attName": true.
			 *
			 * The configuration supplied is map between a location (key) and an element definition object (value)
			 * The location (key) is then exported to the template under then htmlElements property in webpack configuration.
			 *
			 * Example:
			 *  Adding this plugin configuration
			 *  new HtmlElementsPlugin({
			 *    headTags: { ... }
			 *  })
			 *
			 *  Means we can use it in the template like this:
			 *  <%= webpackConfig.htmlElements.headTags %>
			 *
			 * Dependencies: HtmlWebpackPlugin
			 */
			new HtmlElementsPlugin({
				headTags: require('./head-config.common')
			}),

      /**
       * taken from:
       * https://webpack.github.io/docs/long-term-caching.html#get-filenames-from-stats
       */
      //   function() {
      //   this.plugin("done", function(stats) {
      //     require("fs").writeFileSync(
      //       helpers.root("stats.json"),
      //       JSON.stringify(stats.toJson()));
      //   });
      // },

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

			// Fix Angular 2
			new NormalModuleReplacementPlugin(
				/facade(\\|\/)async/,
				helpers.root('node_modules/@angular/core/src/facade/async.js')
			),
			new NormalModuleReplacementPlugin(
				/facade(\\|\/)collection/,
				helpers.root('node_modules/@angular/core/src/facade/collection.js')
			),
			new NormalModuleReplacementPlugin(
				/facade(\\|\/)errors/,
				helpers.root('node_modules/@angular/core/src/facade/errors.js')
			),
			new NormalModuleReplacementPlugin(
				/facade(\\|\/)lang/,
				helpers.root('node_modules/@angular/core/src/facade/lang.js')
			),
			new NormalModuleReplacementPlugin(
				/facade(\\|\/)math/,
				helpers.root('node_modules/@angular/core/src/facade/math.js')
			),
		],

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

	};
}
<commit_msg>polyfills.vendor<commit_after>/**
 * @author: @AngularClass
 */

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

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

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

/*
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = function (options) {
	isProd = options.env === 'production';
	if (isProd) {
		METADATA.baseUrl = '/a2ws/'
	} else {
    METADATA.baseUrl = '/a2wst/'
  }
	return {
		// required (output.publicPath) by html-elements-plugin below
		output: {
			// some plugins need publicPath (e.g. html-elements-plugin)
			publicPath: METADATA.baseUrl
		},

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

		/*
		 * The entry point for the bundle
		 * Our Angular.js app
		 *
		 * See: http://webpack.github.io/docs/configuration.html#entry
		 */
		entry: {

			// 'polyfills': './src/polyfills.browser.ts',
			// 'vendor': './src/vendor.browser.ts',
      'polyfills.vendor': ['./src/polyfills.browser.ts', './src/vendor.browser.ts'],
			'main': './src/main.browser.ts'

		},

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

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

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

		},

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

			rules: [

				/*
				 * Typescript loader support for .ts and Angular 2 async routes via .async.ts
				 * Replace templateUrl and stylesUrl with require()
				 *
				 * See: https://github.com/s-panferov/awesome-typescript-loader
				 * See: https://github.com/TheLarkInn/angular2-template-loader
				 */
				{
					test: /\.ts$/,
					use: [
						'@angularclass/hmr-loader?pretty=' + !isProd + '&prod=' + isProd,
						'awesome-typescript-loader',
						'angular2-template-loader',
						'angular-router-loader'
					],
					exclude: [/\.(spec|e2e)\.ts$/]
				},

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

				// for bootstrap (before other css tests)
				{
					test: /\.css$/,
					loader: ['style-loader', 'css-loader'],
					exclude: helpers.root('src'),
					include: helpers.root('node_modules')
				},

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

				/* Raw loader support for *.html
				 * Returns file content as string
				 *
				 * See: https://github.com/webpack/raw-loader
				 */
				{
					test: /\.html$/,
					// raw-loader vs html-loader
					// http://stackoverflow.com/questions/35400733/webpack-and-angular-html-image-loading
					loaders: [
						"html-loader?" + JSON.stringify({
							attrs: ["img:src"]
						})
					],
					exclude: [helpers.root('src/index.html')]
				},

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

				// for bootstrap
				{test: /\.png$/, loader: "url-loader?limit=100"},
				{test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=1000&mimetype=application/vnd.ms-fontobject"},
				{test: /\.(woff|woff2)$/, loader: "url-loader?limit=1000&mimetype=application/font-woff"},
				{test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=1000&mimetype=application/octet-stream"},
				{
					test: /\.(gif|jpe?g|svg)$/i,
					loaders: [
						// image-webpack-loader chained with the file-loader (equivalent to: file?...!image-webpack?...)
						// [name]-[hash].[ext] will break glyphicon
						// [name].[hash].[ext] and [hash].[name].[ext] are ok but will generate without "[name]."
						'file-loader?hash=sha512&digest=hex&name=[hash].[name].[ext]',
						'image-webpack-loader?bypassOnDebug=true&optimizationLevel=7&interlaced=false'
					]
				}

			],

		},

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

			/*
			 * Plugin: ForkCheckerPlugin
			 * Description: Do type checking in a separate process, so webpack don't need to wait.
			 *
			 * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
			 */
			new ForkCheckerPlugin(),
			/*
			 * Plugin: CommonsChunkPlugin
			 * Description: Shares common code between the pages.
			 * It identifies common modules and put them into a commons chunk.
			 *
			 * See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
			 * See: https://github.com/webpack/docs/wiki/optimization#multi-page-app
			 */
      new CommonsChunkPlugin({
        // name: ['polyfills', 'vendor'].reverse()
        name: 'polyfills.vendor'
      }),

      /**
       * +detail module (e.g. detail.css) goes to 0.[hash].chunk.js
       * referred by webpack-runtime.[hash].bundle.js
       * When 0.[hash].chunk.js change than
       * webpack-runtime.[hash].bundle.js also must change.
       * ['webpack-runtime', 'polyfills', 'vendor'].reverse()
       * in above CommonsChunkPlugin doesn't work because will
       * use filename: '[name].[chunkhash].bundle.js' (see webpack.prod.js).
       *
       * https://webpack.github.io/docs/long-term-caching.html#option-1-one-hash-for-the-bundle
       * [hash] generates a hash of all chunks
       * [chunkhash] generates a hash per chunk
       */
      new CommonsChunkPlugin({
        name: 'webpack-runtime',
        filename: '[name].[hash].bundle.js'
      }),

      /**
			 * Plugin: ContextReplacementPlugin
			 * Description: Provides context to Angular's use of System.import
			 *
			 * See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin
			 * See: https://github.com/angular/angular/issues/11580
			 */
			new ContextReplacementPlugin(
				// The (\\|\/) piece accounts for path separators in *nix and Windows
				/angular(\\|\/)core(\\|\/)src(\\|\/)linker/,
				helpers.root('src'), // location of your src
				{
					// your Angular Async Route paths relative to this root directory
				}
			),

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

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

			/*
			 * Plugin: ScriptExtHtmlWebpackPlugin
			 * Description: Enhances html-webpack-plugin functionality
			 * with different deployment options for your scripts including:
			 *
			 * See: https://github.com/numical/script-ext-html-webpack-plugin
			 */
			new ScriptExtHtmlWebpackPlugin({
				defaultAttribute: 'defer'
			}),

			/*
			 * Plugin: HtmlElementsPlugin
			 * Description: Generate html tags based on javascript maps.
			 *
			 * If a publicPath is set in the webpack output configuration, it will be automatically added to
			 * href attributes, you can disable that by adding a "=href": false property.
			 * You can also enable it to other attribute by settings "=attName": true.
			 *
			 * The configuration supplied is map between a location (key) and an element definition object (value)
			 * The location (key) is then exported to the template under then htmlElements property in webpack configuration.
			 *
			 * Example:
			 *  Adding this plugin configuration
			 *  new HtmlElementsPlugin({
			 *    headTags: { ... }
			 *  })
			 *
			 *  Means we can use it in the template like this:
			 *  <%= webpackConfig.htmlElements.headTags %>
			 *
			 * Dependencies: HtmlWebpackPlugin
			 */
			new HtmlElementsPlugin({
				headTags: require('./head-config.common')
			}),

      /**
       * taken from:
       * https://webpack.github.io/docs/long-term-caching.html#get-filenames-from-stats
       */
      //   function() {
      //   this.plugin("done", function(stats) {
      //     require("fs").writeFileSync(
      //       helpers.root("stats.json"),
      //       JSON.stringify(stats.toJson()));
      //   });
      // },

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

			// Fix Angular 2
			new NormalModuleReplacementPlugin(
				/facade(\\|\/)async/,
				helpers.root('node_modules/@angular/core/src/facade/async.js')
			),
			new NormalModuleReplacementPlugin(
				/facade(\\|\/)collection/,
				helpers.root('node_modules/@angular/core/src/facade/collection.js')
			),
			new NormalModuleReplacementPlugin(
				/facade(\\|\/)errors/,
				helpers.root('node_modules/@angular/core/src/facade/errors.js')
			),
			new NormalModuleReplacementPlugin(
				/facade(\\|\/)lang/,
				helpers.root('node_modules/@angular/core/src/facade/lang.js')
			),
			new NormalModuleReplacementPlugin(
				/facade(\\|\/)math/,
				helpers.root('node_modules/@angular/core/src/facade/math.js')
			),
		],

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

	};
}
<|endoftext|>


<commit_before>
import { Mixin, InitialRender } from './ce';
import { triggerEvent } from './events';
import { DisableBehavior } from './disabled';
import { FocusableBehavior } from './focus';

/**
 * Mixin that provides the behavior of a button. This set the role of the
 * element to `button`, add support for disabling it and normalize the
 * keyboard behavior.
 */
export let ButtonBehavior = Mixin(ParentClass => class extends ParentClass.with(DisableBehavior, FocusableBehavior, InitialRender) {
	initialRenderCallback() {
		super.initialRenderCallback();

		// Mark this element as a button
		this.setAttribute('role', 'button');

		/*
		 * Listener that listens for a key press of Enter or Space and
		 * emits a press event.
		 */
		this.addEventListener('keypress', e => {
			switch(e.key) {
				case 'Enter':
				case 'Space':
					e.preventDefault();
					if(! this.disabled) {
						triggerEvent(this, 'click');
					}
			}
		});
	}
});
<commit_msg>Exporting Button as both class and mixin<commit_after>
import { Class, InitialRender } from './ce';
import { triggerEvent } from './events';
import { DisableBehavior } from './disabled';
import { FocusableBehavior } from './focus';

/**
 * Mixin that provides the behavior of a button. This set the role of the
 * element to `button`, add support for disabling it and normalize the
 * keyboard behavior.
 */
export const ButtonBehavior = Class(ParentClass => class extends ParentClass.with(DisableBehavior, FocusableBehavior, InitialRender) {
	initialRenderCallback() {
		super.initialRenderCallback();

		// Mark this element as a button
		this.setAttribute('role', 'button');

		/*
		 * Listener that listens for a key press of Enter or Space and
		 * emits a press event.
		 */
		this.addEventListener('keypress', e => {
			switch(e.key) {
				case 'Enter':
				case ' ':
					e.preventDefault();
					if(! this.disabled) {
						triggerEvent(this, 'click');
					}
			}
		});
	}
});

export const Button = ButtonBehavior;
<|endoftext|>


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

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

/*
 * Webpack Plugins
 */
// problem with copy-webpack-plugin
const AssetsPlugin = require('assets-webpack-plugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;
const HtmlElementsPlugin = require('./html-elements-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');

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

/*
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = function (options) {
  const isProd = options.env === 'production';
  const aotMode = true;//options && options.aot !== undefined;
  console.log('The options from the webpack config: ' + JSON.stringify(options, null, 2));
  // const entryFile = aotMode ? './src/main.browser.aot.ts' : './src/main.browser.ts';
  // const outPath = aotMode ? 'dist' : 'aot';
  // const devtool = aotMode ? 'source-map' : 'eval-source-map';
  // const srcPath = path.join(__dirname, 'demo', 'src');
  var config = {
  // return {

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

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

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

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

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

    },

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

      rules: [

        /*
         * Typescript loader support for .ts and Angular 2 async routes via .async.ts
         * Replace templateUrl and stylesUrl with require()
         *
         * See: https://github.com/s-panferov/awesome-typescript-loader
         * See: https://github.com/TheLarkInn/angular2-template-loader
         */
        {
          test: /\.ts$/,
          loaders: aotMode ? [
            '@ngtools/webpack'
          ] : [
            '@angularclass/hmr-loader?pretty=' + !isProd + '&prod=' + isProd,
            'awesome-typescript-loader',
            'angular2-template-loader',
            'angular2-router-loader'
          ],
          // loaders: '@ngtools/webpack',
          exclude: [/\.(spec|e2e)\.ts$/]
        },

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

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

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

        /* File loader for supporting images, for example, in CSS files.
         */
        {
          test: /\.(jpg|png|gif)$/,
          loader: 'file'
        },
        {
          test: /\.scss$/,
          loaders: ["css-to-string", "css", "sass"]
        },
        {
          test: /manifest.json$/,
          loader: 'file-loader?name=manifest.json!web-app-manifest-loader'
        }
      ]
    },

    /*
     * Add additional plugins to the compiler.
     *
     * See: http://webpack.github.io/docs/configuration.html#plugins
     */
    plugins: [
      /*
       * Plugin: AssetsPlugin
       * Description: Webpack plugin that emits a json file with assets paths.
       * When working with Webpack you might want to generate your bundles with a generated hash in them (for cache busting).
       * This plug-in outputs a json file with the paths of the generated assets so you can find them from somewhere else.
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
       * See: https://github.com/kossnocorp/assets-webpack-plugin
       */
      new AssetsPlugin({
        path: helpers.root('dist'),
        filename: 'webpack-assets.json',
        prettyPrint: true
      }),

      /*
       * Plugin: ForkCheckerPlugin
       * Description: Do type checking in a separate process, so webpack don't need to wait.
       *
       * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
       */
      new ForkCheckerPlugin(),

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

      /*
       * Plugin: ContextReplacementPlugin
       * Description: Provides context to Angular's use of System.import
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin
       * See: https://github.com/angular/angular/issues/11580
       */
      new ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
        helpers.root('src') // location of your src
      ),

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

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

      /*
       * Plugin: ScriptExtHtmlWebpackPlugin
       * Description: Enhances html-webpack-plugin functionality
       * with different deployment options for your scripts including:
       *
       * See: https://github.com/numical/script-ext-html-webpack-plugin
       */
      new ScriptExtHtmlWebpackPlugin({
        defaultAttribute: 'defer'
      }),

      /*
       * Plugin: HtmlElementsPlugin
       * Description: Generate html tags based on javascript maps.
       *
       * If a publicPath is set in the webpack output configuration, it will be automatically added to
       * href attributes, you can disable that by adding a "=href": false property.
       * You can also enable it to other attribute by settings "=attName": true.
       *
       * The configuration supplied is map between a location (key) and an element definition object (value)
       * The location (key) is then exported to the template under then htmlElements property in webpack configuration.
       *
       * Example:
       *  Adding this plugin configuration
       *  new HtmlElementsPlugin({
       *    headTags: { ... }
       *  })
       *
       *  Means we can use it in the template like this:
       *  <%= webpackConfig.htmlElements.headTags %>
       *
       * Dependencies: HtmlWebpackPlugin
       */
      new HtmlElementsPlugin({
        headTags: require('./head-config.common')
      }),

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

    ],

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

  if (aotMode) {
    config.plugins.push(new ngtools.AotPlugin({
      tsConfigPath: 'tsconfig-aot.json',
      // entryModule: './src/app/app.module#AppModule',
      // genDir: './src/aot'
    }));
  }

  return config;
};
<commit_msg>change the title to fabric8<commit_after>/**
 * @author: @AngularClass
 */

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

/*
 * Webpack Plugins
 */
// problem with copy-webpack-plugin
const AssetsPlugin = require('assets-webpack-plugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;
const HtmlElementsPlugin = require('./html-elements-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');

/*
 * Webpack Constants
 */
const HMR = helpers.hasProcessFlag('hot');
const METADATA = {
  title: 'Fabric8',
  baseUrl: '/',
  isDevServer: helpers.isWebpackDevServer()
};

/*
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = function (options) {
  const isProd = options.env === 'production';
  const aotMode = true;//options && options.aot !== undefined;
  console.log('The options from the webpack config: ' + JSON.stringify(options, null, 2));
  // const entryFile = aotMode ? './src/main.browser.aot.ts' : './src/main.browser.ts';
  // const outPath = aotMode ? 'dist' : 'aot';
  // const devtool = aotMode ? 'source-map' : 'eval-source-map';
  // const srcPath = path.join(__dirname, 'demo', 'src');
  var config = {
  // return {

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

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

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

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

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

    },

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

      rules: [

        /*
         * Typescript loader support for .ts and Angular 2 async routes via .async.ts
         * Replace templateUrl and stylesUrl with require()
         *
         * See: https://github.com/s-panferov/awesome-typescript-loader
         * See: https://github.com/TheLarkInn/angular2-template-loader
         */
        {
          test: /\.ts$/,
          loaders: aotMode ? [
            '@ngtools/webpack'
          ] : [
            '@angularclass/hmr-loader?pretty=' + !isProd + '&prod=' + isProd,
            'awesome-typescript-loader',
            'angular2-template-loader',
            'angular2-router-loader'
          ],
          // loaders: '@ngtools/webpack',
          exclude: [/\.(spec|e2e)\.ts$/]
        },

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

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

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

        /* File loader for supporting images, for example, in CSS files.
         */
        {
          test: /\.(jpg|png|gif)$/,
          loader: 'file'
        },
        {
          test: /\.scss$/,
          loaders: ["css-to-string", "css", "sass"]
        },
        {
          test: /manifest.json$/,
          loader: 'file-loader?name=manifest.json!web-app-manifest-loader'
        }
      ]
    },

    /*
     * Add additional plugins to the compiler.
     *
     * See: http://webpack.github.io/docs/configuration.html#plugins
     */
    plugins: [
      /*
       * Plugin: AssetsPlugin
       * Description: Webpack plugin that emits a json file with assets paths.
       * When working with Webpack you might want to generate your bundles with a generated hash in them (for cache busting).
       * This plug-in outputs a json file with the paths of the generated assets so you can find them from somewhere else.
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
       * See: https://github.com/kossnocorp/assets-webpack-plugin
       */
      new AssetsPlugin({
        path: helpers.root('dist'),
        filename: 'webpack-assets.json',
        prettyPrint: true
      }),

      /*
       * Plugin: ForkCheckerPlugin
       * Description: Do type checking in a separate process, so webpack don't need to wait.
       *
       * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
       */
      new ForkCheckerPlugin(),

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

      /*
       * Plugin: ContextReplacementPlugin
       * Description: Provides context to Angular's use of System.import
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin
       * See: https://github.com/angular/angular/issues/11580
       */
      new ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
        helpers.root('src') // location of your src
      ),

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

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

      /*
       * Plugin: ScriptExtHtmlWebpackPlugin
       * Description: Enhances html-webpack-plugin functionality
       * with different deployment options for your scripts including:
       *
       * See: https://github.com/numical/script-ext-html-webpack-plugin
       */
      new ScriptExtHtmlWebpackPlugin({
        defaultAttribute: 'defer'
      }),

      /*
       * Plugin: HtmlElementsPlugin
       * Description: Generate html tags based on javascript maps.
       *
       * If a publicPath is set in the webpack output configuration, it will be automatically added to
       * href attributes, you can disable that by adding a "=href": false property.
       * You can also enable it to other attribute by settings "=attName": true.
       *
       * The configuration supplied is map between a location (key) and an element definition object (value)
       * The location (key) is then exported to the template under then htmlElements property in webpack configuration.
       *
       * Example:
       *  Adding this plugin configuration
       *  new HtmlElementsPlugin({
       *    headTags: { ... }
       *  })
       *
       *  Means we can use it in the template like this:
       *  <%= webpackConfig.htmlElements.headTags %>
       *
       * Dependencies: HtmlWebpackPlugin
       */
      new HtmlElementsPlugin({
        headTags: require('./head-config.common')
      }),

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

    ],

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

  if (aotMode) {
    config.plugins.push(new ngtools.AotPlugin({
      tsConfigPath: 'tsconfig-aot.json',
      // entryModule: './src/app/app.module#AppModule',
      // genDir: './src/aot'
    }));
  }

  return config;
};
<|endoftext|>


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

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

module.exports = {
  entry: {
    ...entryUtils.CSS_ENTRIES,
    ...entryUtils.JS_ENTRIES,
  },

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

  devServer: devServer.options,

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

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

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

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

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

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

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

module.exports = {
  entry: {
    ...entryUtils.CSS_ENTRIES,
    ...entryUtils.JS_ENTRIES,
  },

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

  devServer: devServer.options,

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

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

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

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

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

}
<|endoftext|>


<commit_before>'use strict';

/*global N*/

// internal
var rnd = require('../../rnd');

////////////////////////////////////////////////////////////////////////////////

var PREFIX      = 'sess:';
var SESSION_TTL = 2 * 60 * 60;  // Session timeout in seconds

//  initSession(env) -> Void
//  - env (Object): Request environment (`this` context of handlers)
//
//  Creates new session (based on browser preferences, or on users's profile).
//
function initSession(env) {
  var req = (env.origin.http || env.origin.rpc).req;

  req.sid = rnd();
  env.extras.setCookie('sid', req.sid, {
    maxAge: SESSION_TTL,
    path:   '/'
  });

  // prefill session
  env.session = {
    ip: req.connection.remoteAddress
  };

  return env.session;
}

//  getSession(sid, callback(err, sess)) -> Void
//  - sid (String): Session ID
//  - callback (Function): Executed once session was retreived
//
//  Retreives session from redis backend
//
function getSession(sid, callback) {
  N.components.redis.get(PREFIX + sid, function (err, data) {
    if (err) {
      callback(err);
      return;
    }

    if (!data) {
      callback();
      return;
    }

    try {
      data = JSON.parse(data.toString());
    } catch (err) {
      callback(err);
      return;
    }

    callback(null, data);
  });
}

//  setSession(sid, sess, callback(err)) -> Void
//  - sid (String): Session ID
//  - sess (Object|Null): Session data
//
//  Saves or removes (if `sess === null`) session from Redis backend
//
function setSession(sid, sess) {
  if (!sess) {
    N.components.redis.del(PREFIX + sid);
    return;
  }

  N.components.redis.setex(PREFIX + sid, SESSION_TTL, JSON.stringify(sess));
}

////////////////////////////////////////////////////////////////////////////////

// Filter middleware that loads session
//
N.filters.before('', { weight: -80 }, function load_session(params, callback) {
  var env = this, req = (env.origin.http || env.origin.rpc).req;

  if (!req || -1 < env.skip.indexOf('sessions')) {
    callback();
    return;
  }

  //
  // Get Session ID
  //

  req.sid = req.cookies.sid;

  //
  // If no session ID, init new session
  //

  if (!req.sid) {
    initSession(env);
    callback();
    return;
  }

  //
  // Load existing session
  //

  env.extras.puncher.start('Session load');

  getSession(req.sid, function (err, sess) {
    env.extras.puncher.stop();

    if (err) {
      callback(err);
      return;
    }

    // get restored session (if exists and ip is same as in request) or init new
    env.session = (sess && req.connection.remoteAddress === sess.ip) ? sess
                : initSession(env);

    callback();
  });
});

// Filter middleware that saves session
//
N.filters.ensure('', { weight: 90 }, function save_session(params, callback) {
  var env = this, req = (this.origin.http || this.origin.rpc).req;

  if (!req || !req.sid || -1 < env.skip.indexOf('sessions')) {
    callback();
    return;
  }

  setSession(req.sid, this.session);
  callback();
});
<commit_msg>Fix sessions filter<commit_after>'use strict';

/*global N*/

// internal
var rnd = require('../../rnd');

////////////////////////////////////////////////////////////////////////////////

var PREFIX      = 'sess:';
var SESSION_TTL = 2 * 60 * 60;  // Session timeout in seconds

//  initSession(env) -> Void
//  - env (Object): Request environment (`this` context of handlers)
//
//  Creates new session (based on browser preferences, or on users's profile).
//
function initSession(env) {
  var req = (env.origin.http || env.origin.rpc).req;

  req.sid = rnd();
  env.extras.setCookie('sid', req.sid, {
    maxAge: SESSION_TTL,
    path:   '/'
  });

  // prefill session
  env.session = {
    ip: req.connection.remoteAddress
  };

  return env.session;
}

//  getSession(sid, callback(err, sess)) -> Void
//  - sid (String): Session ID
//  - callback (Function): Executed once session was retreived
//
//  Retreives session from redis backend
//
function getSession(sid, callback) {
  N.runtime.redis.get(PREFIX + sid, function (err, data) {
    if (err) {
      callback(err);
      return;
    }

    if (!data) {
      callback();
      return;
    }

    try {
      data = JSON.parse(data.toString());
    } catch (err) {
      callback(err);
      return;
    }

    callback(null, data);
  });
}

//  setSession(sid, sess, callback(err)) -> Void
//  - sid (String): Session ID
//  - sess (Object|Null): Session data
//
//  Saves or removes (if `sess === null`) session from Redis backend
//
function setSession(sid, sess) {
  if (!sess) {
    N.runtime.redis.del(PREFIX + sid);
    return;
  }

  N.runtime.redis.setex(PREFIX + sid, SESSION_TTL, JSON.stringify(sess));
}

////////////////////////////////////////////////////////////////////////////////

// Filter middleware that loads session
//
N.filters.before('', { weight: -80 }, function load_session(params, callback) {
  var env = this, req = (env.origin.http || env.origin.rpc).req;

  if (!req || -1 < env.skip.indexOf('sessions')) {
    callback();
    return;
  }

  //
  // Get Session ID
  //

  req.sid = req.cookies.sid;

  //
  // If no session ID, init new session
  //

  if (!req.sid) {
    initSession(env);
    callback();
    return;
  }

  //
  // Load existing session
  //

  env.extras.puncher.start('Session load');

  getSession(req.sid, function (err, sess) {
    env.extras.puncher.stop();

    if (err) {
      callback(err);
      return;
    }

    // get restored session (if exists and ip is same as in request) or init new
    env.session = (sess && req.connection.remoteAddress === sess.ip) ? sess
                : initSession(env);

    callback();
  });
});

// Filter middleware that saves session
//
N.filters.ensure('', { weight: 90 }, function save_session(params, callback) {
  var env = this, req = (this.origin.http || this.origin.rpc).req;

  if (!req || !req.sid || -1 < env.skip.indexOf('sessions')) {
    callback();
    return;
  }

  setSession(req.sid, this.session);
  callback();
});
<|endoftext|>


<commit_before>/* Puppy specific stuff */

$().ready(function() {
	// Style tables - from strapdown.js
	$('table').addClass('table table-striped table-bordered');

	// update date
	var d = new Date(document.lastModified);
	$("#last-updated").html(d.toDateString());

	// contributors list
	var f = location.pathname;
	var i = f.lastIndexOf("/");
	f = f.substring(i+1);
	if (f == "") f += "index.html";
	f = f.replace(".html",".md");
	//console.log(f);

	// This makes use of Github API. If hosted else where, this needs to change
	var user = "puppylinux-woof-CE";
	var repo = "puppylinux-woof-CE.github.io";
	user = "jamesbond3142"; // TEST
	repo = "jamesbond3142.github.io"; // TEST
	$().get('https://api.github.com/repos/'+user+'/'+repo+'/commits?path='+f,
	function(data) {
		var o = JSON.parse(data);
		var s = {};
		// collect all the unique names.
		for (var i in o) {
			var n = o[i].commit.author.name;
			s[n] = n;
		}
		//console.log(s);
		o = "";
		for (var n in s) {
			o += ", " + n;
		}
		if (o.length>2) o = o.substring(2);
		//console.log(o);
		$("#contributors").html(o);

	}, false, true);
});

<commit_msg>Remove test repo references<commit_after>/* Puppy specific stuff */

$().ready(function() {
	// Style tables - from strapdown.js
	$('table').addClass('table table-striped table-bordered');

	// update date
	var d = new Date(document.lastModified);
	$("#last-updated").html(d.toDateString());

	// contributors list
	var f = location.pathname;
	var i = f.lastIndexOf("/");
	f = f.substring(i+1);
	if (f == "") f += "index.html";
	f = f.replace(".html",".md");
	//console.log(f);

	// This makes use of Github API. If hosted else where, this needs to change
	var user = "puppylinux-woof-CE";
	var repo = "puppylinux-woof-CE.github.io";
	$().get('https://api.github.com/repos/'+user+'/'+repo+'/commits?path='+f,
	function(data) {
		var o = JSON.parse(data);
		var s = {};
		// collect all the unique names.
		for (var i in o) {
			var n = o[i].commit.author.name;
			s[n] = n;
		}
		//console.log(s);
		o = "";
		for (var n in s) {
			o += ", " + n;
		}
		if (o.length>2) o = o.substring(2);
		//console.log(o);
		$("#contributors").html(o);

	}, false, true);
});

<|endoftext|>


<commit_before>var GEOM_UTIL = require("./util");
var UTIL = require("../util");
var PROJ = require("../proj");

var jts = Packages.com.vividsolutions.jts;
var geotools = Packages.org.geotools;
var CRS = geotools.referencing.CRS;
var GeometryTX = geotools.geometry.jts.GeometryCoordinateSequenceTransformer;
var prepFactory = new jts.geom.prep.PreparedGeometryFactory();
var _getMethod = GEOM_UTIL._getMethod;
var _prepConfig = GEOM_UTIL._prepConfig;

var arrayRepr = function(array) {
    var str;
    if (array.map) {
        str = "[" + array.map(arrayRepr).join(", ") + "]";
    } else {
        str = array;
    }
    return str;
}

var sameProjection = function(source, other) {
    if (source.projection && other.projection && !source.projection.equals(other.projection)) {
        other = other.transform(source.projection);
    }
    return other;
};

/** api: (define)
 *  module = geom
 *  class = Geometry
 */
var Geometry = UTIL.extend(Object, {

    /** private: property[_geometry]
     *  ``jts.geom.Geometry``
     */
    _geometry: undefined,

    /** private: property[cache]
     *  ``Object``
     */
    cache: null,

    /** api: constructor
     *  .. class:: Geometry
     *
     *      A Geometry instance should not be created directly.
     *      Create an instance of a Geometry subclass instead.
     */
    constructor: function Geometry(config) {
        this.cache = {};
        config = _prepConfig(config);
        if (config.coordinates) {
            this._geometry = this._create(config.coordinates);
        }
        if (config.projection) {
            this.projection = config.projection;
        }
    },

    /** private: method[_create]
     *  :arg coords: ``Array`` A coordinates array.
     *
     *  Create a JTS geometry from an array of coordinates.  Must be implemented
     *  by a subclass.
     */
    _create: function(coords) {
        throw new Error("Geometry subclass must implement _create.");
    },

    /** api: property[projection]
     *  :class:`proj.Projection`
     *  Optional projection for the geometry.  If this is set, it is assumed
     *  that the geometry coordinates are in the corresponding coordinate
     *  reference system.  Use the :meth:`transform` method to transform a
     *  geometry from one coordinate reference system to another.
     */
    get projection() {
        return this.cache.projection;
    },
    set projection(projection) {
        if (projection) {
            if (!(projection instanceof PROJ.Projection)) {
                projection = new PROJ.Projection(projection);
            }
            // clear anything else in the cache
            this.cache = {projection: projection};
        }
    },

    /** api: method[transform]
     *  :arg to: :class:`proj.Projection`
     *  :returns: :class:`geom.Geometry`
     *
     *  Transform coordinates of this geometry to the given projection.  The
     *  :attr:`projection` of this geometry must be set before calling this
     *  method.  Returns a new geometry.
     */
    transform: function(to) {
        var from = this.projection;
        if (!from) {
            throw "Projection must be set before calling transform.";
        }
        if (typeof to == "string") {
            to = new PROJ.Projection(to);
        }
        var gt = new GeometryTX();
        gt.mathTransform = CRS.findMathTransform(from._projection, to._projection);
        var _geometry = gt.transform(this._geometry);
        var transformed = Geometry.from_(_geometry);
        transformed.projection = to;
        return transformed;
    },

    /** api: method[prepare]
     *  :returns: :class:`geom.Geometry`
     *
     *  Prepare a geometry for multiple spatial operations.  Preparing optimizes
     *  the geometry for multiple calls to :meth:`contains`, :meth:`coveredBy`,
     *  :meth:`covers`, :meth:`crosses`, :meth:`disjoint`, :meth:`intersects`,
     *  :meth:`overlaps`, :meth:`touches`, and :meth:`within`.
     */
    prepare: function() {
        if (!this.prepared) {
            this._geometry = prepFactory.create(this._geometry);
        }
        return this;
    },

    /** api: property[prepared]
     *  ``Boolean``
     *  This is a prepared geometry.  See :meth:`prepare`.
     */
    get prepared() {
        return this._geometry instanceof jts.geom.prep.PreparedGeometry;
    },

    /** api: property[coordinates]
     *  ``Array``
     *  The geometry's coordinates array.
     */
    get coordinates() {
        return this._extractCoordinates(this._geometry);
    },

    /** api: property[bounds]
     *  :class:`geom.Bounds`
     *  The bounds defined by minimum and maximum x and y values in this geometry.
     */
    get bounds() {
        if (!this.cache.bounds) {
            var _bounds = _getMethod(this._geometry, "getEnvelopeInternal")();
            var bounds = GEOM_UTIL.create({
                type: "Bounds",
                minx: Number(_bounds.getMinX()), maxx: Number(_bounds.getMaxX()),
                miny: Number(_bounds.getMinY()), maxy: Number(_bounds.getMaxY()),
                projection: this.projection
            });
            this.cache.bounds = bounds;
        }
        return this.cache.bounds;
    },

    /** private: method[extractCoordinates]
     *  :returns: ``Array`` An array of coordinates.
     *
     *  Generate an array of coordinates for the geometry.
     */
    _extractCoordinates: function() {
        throw new Error("Geometry subclasses must implement _extractCoordinates.");
    },

    /** private: method[toFullString]
     *  :returns: ``String``
     *
     *  The Well-Known Text representation of the geometry.
     */
    toFullString: function() {
        return arrayRepr(this.coordinates);
    },

    /** api: property[json]
     *  ``String``
     *  The JSON representation of the geometry (see http://geojson.org).
     */
    get json() {
        return JSON.stringify(this.config);
    },

    /** private: property[config]
     *  ``Object``
     */
    get config() {
        return {
            type: this.constructor.name,
            coordinates: this.coordinates
        };
    },

    /** api: property[centroid]
     *  ``geom.Point``
     *  The centroid of this geometry.
     */
    get centroid() {
        var _point = this._geometry.getCentroid();
        var point = Geometry.from_(_point);
        point.projection = this.projection;
        return point;
    },

    /** api: method[buffer]
     *  :arg dist: ``Number`` Width of buffer.  May be positive, negative, or
     *      zero.
     *  :arg segs: ``Number`` Integer number of quadrant segments for circular
     *      arcs.  Default is 8.
     *  :arg caps: ``Number`` One of :data:`BUFFER_CAP_ROUND`,
     *      :data:`BUFFER_CAP_BUTT`, or :data:`BUFFER_CAP_SQUARE`.  Default
     *      is :data:`BUFFER_CAP_ROUND`.
     *  :returns: :class:`geom.Geometry`
     *
     *  Construct a goemetry that buffers this geometry by the given width.
     */
    buffer: function(dist, segs, caps) {
        if (segs === undefined) {
            segs = 8;
        } else {
            segs |= 0;
        }
        if (caps === undefined) {
            caps = GEOM_UTIL.BUFFER_CAP_ROUND;
        }
        var geometry = Geometry.from_(_getMethod(this._geometry, "buffer")(dist, segs, caps));
        geometry.projection = this.projection;
        return geometry;
    },

    /** api: method[distance]
     *  :arg geometry: :class:`geom.Geometry`
     *  :returns: ``Number``
     *
     *  Returns the minimum distance between this and the supplied geometry.
     */
    distance: function(geometry) {
        geometry = sameProjection(this, geometry);
        return _getMethod(this._geometry, "distance")(geometry._geometry);
    },

    /** api: property[area]
     *  ``Number``
     *  The geometry area.
     */
    get area() {
        return _getMethod(this._geometry, "getArea")();
    },

    /** api: property[length]
     *  ``Number``
     *  The geometry length.
     */
    get length() {
        return _getMethod(this._geometry, "getLength")();
    }

});

var constructive = [
    /** api: method[clone]
     *  :returns: :class:`geom.Geometry`
     *
     *  Creates a complete copy of this geometry.
     */
    "clone",

    /** api: method[convexHull]
     *  :returns: :class:`geom.Geometry`
     *
     *  Computes the smallest convex :class:`Polygon` that contains this
     *  geometry.
     */
    "convexHull",

    /** api: method[difference]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: :class:`geom.Geometry`
     *
     *  Creates a geometry made up of all the points in this geometry that are
     *  not in the other geometry.
     */
    "difference",

    /** api: method[getBoundary]
     *  :returns: :class:`geom.Geometry`
     *
     *  Returns the boundary, or an empty geometry of appropriate dimension if
     *  this geometry is empty.
     */
    "getBoundary",

    /** api: method[getEnvelope]
     *  :returns: :class:`geom.Geometry`
     *
     *  Returns this geometry's bounding box.
     */
    "getEnvelope",

    /** api: method[intersection]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: :class:`geom.Geometry`
     *
     *  Creates a geometry representing all the points shared by this geometry
     *  and the other.
     */
    "intersection",

    /** api: method[symDifference]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: :class:`geom.Geometry`
     *
     *  Creates a geometry representing all the points in this geometry but not
     *  in the other plus all the points in the other but not in this geometry.
     */
    "symDifference",

    /** api: method[symDifference]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: :class:`geom.Geometry`
     *
     *  Creates a geometry representing all the points in this geometry but not
     *  in the other plus all the points in the other but not in this geometry.
     */
    "union"
];
constructive.forEach(function(method) {
    Geometry.prototype[method] = function() {
        var _geometry;
        if (arguments.length) {
            _geometry = _getMethod(this._geometry, method)(sameProjection(this, arguments[0])._geometry);
        } else {
            _geometry = _getMethod(this._geometry, method)();
        }
        var geometry = Geometry.from_(_geometry);
        geometry.projection = this.projection;
        return geometry;
    };
});

var unary = [
    /** api: method[isEmpty]
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry is empty.
     */
    "isEmpty",

    /** api: method[isRectangle]
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry is a rectangle.
     */
    "isRectangle",

    /** api: method[isSimple]
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry is simple.
     */
    "isSimple",

    /** api: method[isValid]
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry is valid.
     */
    "isValid"
];
unary.forEach(function(method) {
    Geometry.prototype[method] = function() {
        return Boolean(_getMethod(this._geometry, method)());
    };
});

var binary = [
    /** api: method[contains]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry contains the other geometry (without boundaries
     *  touching).
     */
    "contains",

    /** api: method[coveredBy]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry is covered by other geometry.
     */
    "coveredBy",

    /** api: method[covers]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry covers the other geometry.
     */
    "covers",

    /** api: method[crosses]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry crosses the other geometry.
     */
    "crosses",

    /** api: method[disjoint]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry is disjoint to the other geometry.
     */
    "disjoint",

    /** api: method[equals]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: ``Boolean``
     *
     *  Geometries are considered equal if they share at least one point in
     *  common and if no point of either geometry lies in the exterior of the
     *  other.
     */
    "equals",

    /** api: method[equalsExact]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry is exactly equal to the other geometry.
     */
    "equalsExact",

    /** api: method[overlaps]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry overlaps the other geometry.
     */
    "overlaps",

    /** api: method[intersects]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry intersects the other geometry.
     */
    "intersects",

    /** api: method[touches]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry `only` touches the other geometry.
     */
    "touches",

    /** api: method[within]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry is within the other geometry.  This is the
     *  inverse of :meth:`contains`.
     */
    "within"
];
binary.forEach(function(method) {
    Geometry.prototype[method] = function(g) {
        return Boolean(_getMethod(this._geometry, method)(sameProjection(this, g)._geometry));
    }
});

/** private: staticproperty[_factory]
 *  ``jts.geom.GeometryFactory``
 *  A jts geometry factory.
 */
Geometry._factory = new jts.geom.GeometryFactory();

/** private: staticmethod[from_]
 *  :arg geometry: ``jts.geom.Geometry`` A JTS geometry object.
 *  :returns: :class`Geometry`
 *
 *  Create a geoscript geometry object from a JTS geometry object.
 */
Geometry.from_ = function(_geometry) {
    var name = String(_getMethod(_geometry, "getGeometryType")());
    var g = GEOM_UTIL.create({type: name});
    g._geometry = _geometry;
    return g;
};

exports.Geometry = Geometry;
<commit_msg>One fewer instanceof.<commit_after>var GEOM_UTIL = require("./util");
var UTIL = require("../util");
var PROJ = require("../proj");

var jts = Packages.com.vividsolutions.jts;
var geotools = Packages.org.geotools;
var CRS = geotools.referencing.CRS;
var GeometryTX = geotools.geometry.jts.GeometryCoordinateSequenceTransformer;
var prepFactory = new jts.geom.prep.PreparedGeometryFactory();
var _getMethod = GEOM_UTIL._getMethod;
var _prepConfig = GEOM_UTIL._prepConfig;

var arrayRepr = function(array) {
    var str;
    if (array.map) {
        str = "[" + array.map(arrayRepr).join(", ") + "]";
    } else {
        str = array;
    }
    return str;
}

var sameProjection = function(source, other) {
    if (source.projection && other.projection && !source.projection.equals(other.projection)) {
        other = other.transform(source.projection);
    }
    return other;
};

/** api: (define)
 *  module = geom
 *  class = Geometry
 */
var Geometry = UTIL.extend(Object, {

    /** private: property[_geometry]
     *  ``jts.geom.Geometry``
     */
    _geometry: undefined,

    /** private: property[cache]
     *  ``Object``
     */
    cache: null,

    /** api: constructor
     *  .. class:: Geometry
     *
     *      A Geometry instance should not be created directly.
     *      Create an instance of a Geometry subclass instead.
     */
    constructor: function Geometry(config) {
        this.cache = {};
        config = _prepConfig(config);
        if (config.coordinates) {
            this._geometry = this._create(config.coordinates);
        }
        if (config.projection) {
            this.projection = config.projection;
        }
    },

    /** private: method[_create]
     *  :arg coords: ``Array`` A coordinates array.
     *
     *  Create a JTS geometry from an array of coordinates.  Must be implemented
     *  by a subclass.
     */
    _create: function(coords) {
        throw new Error("Geometry subclass must implement _create.");
    },

    /** api: property[projection]
     *  :class:`proj.Projection`
     *  Optional projection for the geometry.  If this is set, it is assumed
     *  that the geometry coordinates are in the corresponding coordinate
     *  reference system.  Use the :meth:`transform` method to transform a
     *  geometry from one coordinate reference system to another.
     */
    get projection() {
        return this.cache.projection;
    },
    set projection(projection) {
        if (projection) {
            if (typeof projection == "string") {
                projection = new PROJ.Projection(projection);
            }
            // clear anything else in the cache
            this.cache = {projection: projection};
        }
    },

    /** api: method[transform]
     *  :arg to: :class:`proj.Projection`
     *  :returns: :class:`geom.Geometry`
     *
     *  Transform coordinates of this geometry to the given projection.  The
     *  :attr:`projection` of this geometry must be set before calling this
     *  method.  Returns a new geometry.
     */
    transform: function(to) {
        var from = this.projection;
        if (!from) {
            throw "Projection must be set before calling transform.";
        }
        if (typeof to == "string") {
            to = new PROJ.Projection(to);
        }
        var gt = new GeometryTX();
        gt.mathTransform = CRS.findMathTransform(from._projection, to._projection);
        var _geometry = gt.transform(this._geometry);
        var transformed = Geometry.from_(_geometry);
        transformed.projection = to;
        return transformed;
    },

    /** api: method[prepare]
     *  :returns: :class:`geom.Geometry`
     *
     *  Prepare a geometry for multiple spatial operations.  Preparing optimizes
     *  the geometry for multiple calls to :meth:`contains`, :meth:`coveredBy`,
     *  :meth:`covers`, :meth:`crosses`, :meth:`disjoint`, :meth:`intersects`,
     *  :meth:`overlaps`, :meth:`touches`, and :meth:`within`.
     */
    prepare: function() {
        if (!this.prepared) {
            this._geometry = prepFactory.create(this._geometry);
        }
        return this;
    },

    /** api: property[prepared]
     *  ``Boolean``
     *  This is a prepared geometry.  See :meth:`prepare`.
     */
    get prepared() {
        return this._geometry instanceof jts.geom.prep.PreparedGeometry;
    },

    /** api: property[coordinates]
     *  ``Array``
     *  The geometry's coordinates array.
     */
    get coordinates() {
        return this._extractCoordinates(this._geometry);
    },

    /** api: property[bounds]
     *  :class:`geom.Bounds`
     *  The bounds defined by minimum and maximum x and y values in this geometry.
     */
    get bounds() {
        if (!this.cache.bounds) {
            var _bounds = _getMethod(this._geometry, "getEnvelopeInternal")();
            var bounds = GEOM_UTIL.create({
                type: "Bounds",
                minx: Number(_bounds.getMinX()), maxx: Number(_bounds.getMaxX()),
                miny: Number(_bounds.getMinY()), maxy: Number(_bounds.getMaxY()),
                projection: this.projection
            });
            this.cache.bounds = bounds;
        }
        return this.cache.bounds;
    },

    /** private: method[extractCoordinates]
     *  :returns: ``Array`` An array of coordinates.
     *
     *  Generate an array of coordinates for the geometry.
     */
    _extractCoordinates: function() {
        throw new Error("Geometry subclasses must implement _extractCoordinates.");
    },

    /** private: method[toFullString]
     *  :returns: ``String``
     *
     *  The Well-Known Text representation of the geometry.
     */
    toFullString: function() {
        return arrayRepr(this.coordinates);
    },

    /** api: property[json]
     *  ``String``
     *  The JSON representation of the geometry (see http://geojson.org).
     */
    get json() {
        return JSON.stringify(this.config);
    },

    /** private: property[config]
     *  ``Object``
     */
    get config() {
        return {
            type: this.constructor.name,
            coordinates: this.coordinates
        };
    },

    /** api: property[centroid]
     *  ``geom.Point``
     *  The centroid of this geometry.
     */
    get centroid() {
        var _point = this._geometry.getCentroid();
        var point = Geometry.from_(_point);
        point.projection = this.projection;
        return point;
    },

    /** api: method[buffer]
     *  :arg dist: ``Number`` Width of buffer.  May be positive, negative, or
     *      zero.
     *  :arg segs: ``Number`` Integer number of quadrant segments for circular
     *      arcs.  Default is 8.
     *  :arg caps: ``Number`` One of :data:`BUFFER_CAP_ROUND`,
     *      :data:`BUFFER_CAP_BUTT`, or :data:`BUFFER_CAP_SQUARE`.  Default
     *      is :data:`BUFFER_CAP_ROUND`.
     *  :returns: :class:`geom.Geometry`
     *
     *  Construct a goemetry that buffers this geometry by the given width.
     */
    buffer: function(dist, segs, caps) {
        if (segs === undefined) {
            segs = 8;
        } else {
            segs |= 0;
        }
        if (caps === undefined) {
            caps = GEOM_UTIL.BUFFER_CAP_ROUND;
        }
        var geometry = Geometry.from_(_getMethod(this._geometry, "buffer")(dist, segs, caps));
        geometry.projection = this.projection;
        return geometry;
    },

    /** api: method[distance]
     *  :arg geometry: :class:`geom.Geometry`
     *  :returns: ``Number``
     *
     *  Returns the minimum distance between this and the supplied geometry.
     */
    distance: function(geometry) {
        geometry = sameProjection(this, geometry);
        return _getMethod(this._geometry, "distance")(geometry._geometry);
    },

    /** api: property[area]
     *  ``Number``
     *  The geometry area.
     */
    get area() {
        return _getMethod(this._geometry, "getArea")();
    },

    /** api: property[length]
     *  ``Number``
     *  The geometry length.
     */
    get length() {
        return _getMethod(this._geometry, "getLength")();
    }

});

var constructive = [
    /** api: method[clone]
     *  :returns: :class:`geom.Geometry`
     *
     *  Creates a complete copy of this geometry.
     */
    "clone",

    /** api: method[convexHull]
     *  :returns: :class:`geom.Geometry`
     *
     *  Computes the smallest convex :class:`Polygon` that contains this
     *  geometry.
     */
    "convexHull",

    /** api: method[difference]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: :class:`geom.Geometry`
     *
     *  Creates a geometry made up of all the points in this geometry that are
     *  not in the other geometry.
     */
    "difference",

    /** api: method[getBoundary]
     *  :returns: :class:`geom.Geometry`
     *
     *  Returns the boundary, or an empty geometry of appropriate dimension if
     *  this geometry is empty.
     */
    "getBoundary",

    /** api: method[getEnvelope]
     *  :returns: :class:`geom.Geometry`
     *
     *  Returns this geometry's bounding box.
     */
    "getEnvelope",

    /** api: method[intersection]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: :class:`geom.Geometry`
     *
     *  Creates a geometry representing all the points shared by this geometry
     *  and the other.
     */
    "intersection",

    /** api: method[symDifference]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: :class:`geom.Geometry`
     *
     *  Creates a geometry representing all the points in this geometry but not
     *  in the other plus all the points in the other but not in this geometry.
     */
    "symDifference",

    /** api: method[symDifference]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: :class:`geom.Geometry`
     *
     *  Creates a geometry representing all the points in this geometry but not
     *  in the other plus all the points in the other but not in this geometry.
     */
    "union"
];
constructive.forEach(function(method) {
    Geometry.prototype[method] = function() {
        var _geometry;
        if (arguments.length) {
            _geometry = _getMethod(this._geometry, method)(sameProjection(this, arguments[0])._geometry);
        } else {
            _geometry = _getMethod(this._geometry, method)();
        }
        var geometry = Geometry.from_(_geometry);
        geometry.projection = this.projection;
        return geometry;
    };
});

var unary = [
    /** api: method[isEmpty]
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry is empty.
     */
    "isEmpty",

    /** api: method[isRectangle]
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry is a rectangle.
     */
    "isRectangle",

    /** api: method[isSimple]
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry is simple.
     */
    "isSimple",

    /** api: method[isValid]
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry is valid.
     */
    "isValid"
];
unary.forEach(function(method) {
    Geometry.prototype[method] = function() {
        return Boolean(_getMethod(this._geometry, method)());
    };
});

var binary = [
    /** api: method[contains]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry contains the other geometry (without boundaries
     *  touching).
     */
    "contains",

    /** api: method[coveredBy]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry is covered by other geometry.
     */
    "coveredBy",

    /** api: method[covers]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry covers the other geometry.
     */
    "covers",

    /** api: method[crosses]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry crosses the other geometry.
     */
    "crosses",

    /** api: method[disjoint]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry is disjoint to the other geometry.
     */
    "disjoint",

    /** api: method[equals]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: ``Boolean``
     *
     *  Geometries are considered equal if they share at least one point in
     *  common and if no point of either geometry lies in the exterior of the
     *  other.
     */
    "equals",

    /** api: method[equalsExact]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry is exactly equal to the other geometry.
     */
    "equalsExact",

    /** api: method[overlaps]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry overlaps the other geometry.
     */
    "overlaps",

    /** api: method[intersects]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry intersects the other geometry.
     */
    "intersects",

    /** api: method[touches]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry `only` touches the other geometry.
     */
    "touches",

    /** api: method[within]
     *  :arg other: :class:`geom.Geometry`
     *  :returns: ``Boolean``
     *
     *  Tests if this geometry is within the other geometry.  This is the
     *  inverse of :meth:`contains`.
     */
    "within"
];
binary.forEach(function(method) {
    Geometry.prototype[method] = function(g) {
        return Boolean(_getMethod(this._geometry, method)(sameProjection(this, g)._geometry));
    }
});

/** private: staticproperty[_factory]
 *  ``jts.geom.GeometryFactory``
 *  A jts geometry factory.
 */
Geometry._factory = new jts.geom.GeometryFactory();

/** private: staticmethod[from_]
 *  :arg geometry: ``jts.geom.Geometry`` A JTS geometry object.
 *  :returns: :class`Geometry`
 *
 *  Create a geoscript geometry object from a JTS geometry object.
 */
Geometry.from_ = function(_geometry) {
    var name = String(_getMethod(_geometry, "getGeometryType")());
    var g = GEOM_UTIL.create({type: name});
    g._geometry = _geometry;
    return g;
};

exports.Geometry = Geometry;
<|endoftext|>