<commit_before>/*!
 * ${copyright}
 */

// Provides control sap.m.Link.
sap.ui.define(['jquery.sap.global', './library', 'sap/ui/core/Control', 'sap/ui/core/EnabledPropagator'],
	function(jQuery, library, Control, EnabledPropagator) {
	"use strict";

	/**
	 * Constructor for a new Link.
	 *
	 * @param {string} [sId] id for the new control, generated automatically if no id is given
	 * @param {object} [mSettings] initial settings for the new control
	 *
	 * @class
	 * A hyperlink control which can be used to trigger actions or to navigate to other applications or web pages.
	 * @extends sap.ui.core.Control
	 * @implements sap.ui.core.IShrinkable
	 *
	 * @author SAP SE
	 * @version ${version}
	 *
	 * @constructor
	 * @public
	 * @since 1.12
	 * @alias sap.m.Link
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var Link = Control.extend("sap.m.Link", /** @lends sap.m.Link.prototype */ { metadata : {

		interfaces : [
			"sap.ui.core.IShrinkable"
		],
		library : "sap.m",
		properties : {

			/**
			 * Link text to be displayed.
			 */
			text : {type : "string", group : "Data", defaultValue : ''},

			/**
			 * Whether the link can be triggered by the user.
			 */
			enabled : {type : "boolean", group : "Behavior", defaultValue : true},

			/**
			 * Options are the standard values for window.open() supported by browsers: _self, _top, _blank, _parent, _search. Alternatively, a frame name can be entered. This property is only used for href URLs.
			 */
			target : {type : "string", group : "Behavior", defaultValue : null},

			/**
			 * Width of the link. When it is set (CSS-size such as % or px), this is the exact size. When left blank, the text defines the size.
			 */
			width : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : null},

			/**
			 * The link target URI. Supports standard hyperlink behavior. If a JavaScript action should be triggered, this should not be set, but instead an event handler for the "press" event should be registered.
			 */
			href : {type : "sap.ui.core.URI", group : "Data", defaultValue : null},

			/**
			 * Whether the link text is allowed to wrap when there is not sufficient space.
			 */
			wrapping : {type : "boolean", group : "Appearance", defaultValue : false},

			/**
			 * Sets the horizontal alignment of the text.
			 * @since 1.28.0
			 */
			textAlign : {type : "sap.ui.core.TextAlign", group : "Appearance", defaultValue : sap.ui.core.TextAlign.Initial},

			/**
			 * This property specifies the element's text directionality with enumerated options. By default, the control inherits text direction from the parent DOM.
			 * @since 1.28.0
			 */
			textDirection : {type : "sap.ui.core.TextDirection", group : "Appearance", defaultValue : sap.ui.core.TextDirection.Inherit},

			/**
			 * Subtle links look more like standard text than like links. They should only be used to help with visual hierarchy between large data lists of important and less important links. Subtle links should not be used in any other usecase.
			 * @since 1.22
			 */
			subtle : {type : "boolean", group : "Behavior", defaultValue : false},

			/**
			 * Set this property to true if the link should appear emphasized.
			 * @since 1.22
			 */
			emphasized : {type : "boolean", group : "Behavior", defaultValue : false}
		},
		associations : {

			/**
			 * Association to controls / ids which describe this control (see WAI-ARIA attribute aria-describedby).
			 */
			ariaDescribedBy: {type: "sap.ui.core.Control", multiple: true, singularName: "ariaDescribedBy"},

			/**
			 * Association to controls / ids which label this control (see WAI-ARIA attribute aria-labelledby).
			 */
			ariaLabelledBy: {type: "sap.ui.core.Control", multiple: true, singularName: "ariaLabelledBy"}
		},
		events : {

			/**
			 * Event is fired when the user triggers the link control.
			 */
			press : {allowPreventDefault : true}
		}
	}});

	EnabledPropagator.call(Link.prototype); // inherit "disabled" state from parent controls

	/**
	 * Also trigger link activation when space is pressed on the focused control
	 */
	Link.prototype.onsapspace = function(oEvent) {
		this._handlePress(oEvent); // this calls any JS event handlers
		// _handlePress() checks the return value of the event handler and prevents default if required or of the Link is disabled
		if (this.getHref() && !oEvent.isDefaultPrevented()) {
			// Normal browser link, the browser does the job. According to the keyboard spec, Space should do the same as Enter/Click.
			// To make the browser REALLY do the same (history, referrer, frames, target,...), create a new "click" event and let the browser "do the needful".

			// first disarm the Space key event
			oEvent.preventDefault(); // prevent any scrolling which the browser might do because from its perspective the Link does not handle the "space" key
			oEvent.setMarked();

			// then create the click event
			var oClickEvent = document.createEvent('MouseEvents');
			oClickEvent.initEvent('click' /* event type */, false, true); // non-bubbling, cancelable
			this.getDomRef().dispatchEvent(oClickEvent);
		}
	};

	/**
	 * Function is called when Link is triggered.
	 *
	 * @param {jQuery.Event} oEvent
	 * @private
	 */
	Link.prototype._handlePress = function(oEvent) {
		if (this.getEnabled()) {
			// mark the event for components that needs to know if the event was handled by the link
			oEvent.setMarked();

			if (!this.firePress() || !this.getHref()) { // fire event and check return value whether default action should be prevented
				oEvent.preventDefault();
			}
		} else { // disabled
			oEvent.preventDefault(); // even prevent URLs from being triggered
		}
	};

	if (sap.ui.Device.support.touch) {
		Link.prototype.ontap = Link.prototype._handlePress;
	} else {
		Link.prototype.onclick = Link.prototype._handlePress;
	}

	Link.prototype.ontouchstart = function(oEvent) {
		if (this.getEnabled()) {
			// for controls which need to know whether they should handle events bubbling from here
			oEvent.setMarked();
		}
	};

	/* override standard setters with direct DOM manipulation */

	Link.prototype.setText = function(sText){
		this.setProperty("text", sText, true);
		sText = this.getProperty("text");
		this.$().text(sText);
		return this;
	};

	Link.prototype.setHref = function(sUri){
		this.setProperty("href", sUri, true);
		sUri = this.getProperty("href");
		this.$().attr("href", sUri);
		return this;
	};

	Link.prototype.setSubtle = function(bSubtle){
		this.setProperty("subtle", bSubtle, true);

		var $this = this.$();
		if ($this.length) { // only when actually rendered
			$this.toggleClass("sapMLnkSubtle", bSubtle);
			if (bSubtle) {
				if (!jQuery.sap.domById(this.getId() + "-linkSubtle")) {
					$this.append("" + this._getLinkDescription("LINK_SUBTLE") + "");
				}
			} else {
				jQuery.sap.byId(this.getId() + "-linkSubtle").remove();
			}
		}
		return this;
	};

	Link.prototype.setEmphasized = function(bEmphasized){
		this.setProperty("emphasized", bEmphasized, true);

		var $this = this.$();
		if ($this.length) { // only when actually rendered
			$this.toggleClass("sapMLnkEmphasized", bEmphasized);
			if (bEmphasized) { // strictly spoken this should only be done when accessibility mode is true. But it is true by default, so not sure it is worth checking...
				if (!jQuery.sap.domById(this.getId() + "-linkEmphasized")) {
					$this.append("" + this._getLinkDescription("LINK_EMPHASIZED") + "");
				}
			} else {
				jQuery.sap.byId(this.getId() + "-linkEmphasized").remove();
			}
		}
		return this;
	};

	Link.prototype.setWrapping = function(bWrapping){
		this.setProperty("wrapping", bWrapping, true);
		this.$().toggleClass("sapMLnkWrapping", bWrapping);
		return this;
	};

	Link.prototype.setEnabled = function(bEnabled){
		if (bEnabled !== this.getProperty("enabled")) { // do nothing when the same value is set again (virtual table scrolling!) - don't use this.getEnabled() because of EnabledPropagator
			this.setProperty("enabled", bEnabled, true);
			var $this = this.$();
			$this.toggleClass("sapMLnkDsbl", !bEnabled);
			if (bEnabled) {
				$this.attr("disabled", false);
				$this.attr("tabindex", "0");
				$this.removeAttr("aria-disabled");
			} else {
				$this.attr("disabled", true);
				$this.attr("tabindex", "-1");
				$this.attr("aria-disabled", true);
			}
		}
		return this;
	};

	Link.prototype.setWidth = function(sWidth){
		this.setProperty("width", sWidth, true);
		this.$().toggleClass("sapMLnkMaxWidth", !sWidth);
		this.$().css("width", sWidth);
		return this;
	};

	Link.prototype.setTarget = function(sTarget){
		this.setProperty("target", sTarget, true);
		if (!sTarget) {
			this.$().removeAttr("target");
		} else {
			this.$().attr("target", sTarget);
		}
		return this;
	};

	/**
	 * Function that translates the resource text.
	 *
	 * @param {String} sKey the resource to be translated
	 * @private
	 * @returns {String} the translated text
	 */
	Link.prototype._getLinkDescription = function(sKey) {
		var oRb = sap.ui.getCore().getLibraryResourceBundle("sap.m");
		var sText = oRb.getText(sKey);
		return sText;
	};

	return Link;

}, /* bExport= */ true);
<commit_msg>[INTERNAL] sap.m.Link documentation update<commit_after>/*!
 * ${copyright}
 */

// Provides control sap.m.Link.
sap.ui.define(['jquery.sap.global', './library', 'sap/ui/core/Control', 'sap/ui/core/EnabledPropagator'],
	function(jQuery, library, Control, EnabledPropagator) {
	"use strict";

	/**
	 * Constructor for a new Link.
	 *
	 * @param {string} [sId] id for the new control, generated automatically if no id is given
	 * @param {object} [mSettings] initial settings for the new control
	 *
	 * @class
	 * A hyperlink control which can be used to trigger actions or to navigate to other applications or web pages.
	 * @extends sap.ui.core.Control
	 * @implements sap.ui.core.IShrinkable
	 *
	 * @author SAP SE
	 * @version ${version}
	 *
	 * @constructor
	 * @public
	 * @since 1.12
	 * @alias sap.m.Link
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var Link = Control.extend("sap.m.Link", /** @lends sap.m.Link.prototype */ { metadata : {

		interfaces : [
			"sap.ui.core.IShrinkable"
		],
		library : "sap.m",
		properties : {

			/**
			 * Link text to be displayed.
			 */
			text : {type : "string", group : "Data", defaultValue : ''},

			/**
			 * Determines whether the link can be triggered by the user.
			 */
			enabled : {type : "boolean", group : "Behavior", defaultValue : true},

			/**
			 * Options are the standard values for window.open() supported by browsers: _self, _top, _blank, _parent, _search. Alternatively, a frame name can be entered. This property is only used when the href property is set.
			 */
			target : {type : "string", group : "Behavior", defaultValue : null},

			/**
			 * Width of the link (CSS-size such as % or px). When it is set, this is the exact size. When left blank, the text defines the size.
			 */
			width : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : null},

			/**
			 * The link target URI. Supports standard hyperlink behavior. If a JavaScript action should be triggered, this should not be set, but instead an event handler for the "press" event should be registered.
			 */
			href : {type : "sap.ui.core.URI", group : "Data", defaultValue : null},

			/**
			 * Determines whether the link text is allowed to wrap when there is not sufficient space.
			 */
			wrapping : {type : "boolean", group : "Appearance", defaultValue : false},

			/**
			 * Sets the horizontal alignment of the text.
			 * @since 1.28.0
			 */
			textAlign : {type : "sap.ui.core.TextAlign", group : "Appearance", defaultValue : sap.ui.core.TextAlign.Initial},

			/**
			 * This property specifies the element's text directionality with enumerated options. By default, the control inherits text direction from the parent DOM.
			 * @since 1.28.0
			 */
			textDirection : {type : "sap.ui.core.TextDirection", group : "Appearance", defaultValue : sap.ui.core.TextDirection.Inherit},

			/**
			 * Subtle links look more like standard text than like links. They should only be used to help with visual hierarchy between large data lists of important and less important links. Subtle links should not be used in any other use case.
			 * @since 1.22
			 */
			subtle : {type : "boolean", group : "Behavior", defaultValue : false},

			/**
			 * Emphasized links look visually more important than regular links.
			 * @since 1.22
			 */
			emphasized : {type : "boolean", group : "Behavior", defaultValue : false}
		},
		associations : {

			/**
			 * Association to controls / ids which describe this control (see WAI-ARIA attribute aria-describedby).
			 */
			ariaDescribedBy: {type: "sap.ui.core.Control", multiple: true, singularName: "ariaDescribedBy"},

			/**
			 * Association to controls / ids which label this control (see WAI-ARIA attribute aria-labelledby).
			 */
			ariaLabelledBy: {type: "sap.ui.core.Control", multiple: true, singularName: "ariaLabelledBy"}
		},
		events : {

			/**
			 * Event is fired when the user triggers the link control.
			 */
			press : {allowPreventDefault : true}
		}
	}});

	EnabledPropagator.call(Link.prototype); // inherit "disabled" state from parent controls

	/**
	 * Triggers link activation when space key is pressed on the focused control.
	 *
	 * @param {jQuery.Event} oEvent
	 */
	Link.prototype.onsapspace = function(oEvent) {
		this._handlePress(oEvent); // this calls any JS event handlers
		// _handlePress() checks the return value of the event handler and prevents default if required or of the Link is disabled
		if (this.getHref() && !oEvent.isDefaultPrevented()) {
			// Normal browser link, the browser does the job. According to the keyboard spec, Space should do the same as Enter/Click.
			// To make the browser REALLY do the same (history, referrer, frames, target,...), create a new "click" event and let the browser "do the needful".

			// first disarm the Space key event
			oEvent.preventDefault(); // prevent any scrolling which the browser might do because from its perspective the Link does not handle the "space" key
			oEvent.setMarked();

			// then create the click event
			var oClickEvent = document.createEvent('MouseEvents');
			oClickEvent.initEvent('click' /* event type */, false, true); // non-bubbling, cancelable
			this.getDomRef().dispatchEvent(oClickEvent);
		}
	};

	/**
	 * Handler for the "press" event of the link.
	 *
	 * @param {jQuery.Event} oEvent
	 * @private
	 */
	Link.prototype._handlePress = function(oEvent) {
		if (this.getEnabled()) {
			// mark the event for components that needs to know if the event was handled by the link
			oEvent.setMarked();

			if (!this.firePress() || !this.getHref()) { // fire event and check return value whether default action should be prevented
				oEvent.preventDefault();
			}
		} else { // disabled
			oEvent.preventDefault(); // even prevent URLs from being triggered
		}
	};

	if (sap.ui.Device.support.touch) {
		Link.prototype.ontap = Link.prototype._handlePress;
	} else {
		Link.prototype.onclick = Link.prototype._handlePress;
	}

	/**
	 * Handles the touch event on mobile devices.
	 *
	 * @param {jQuery.Event} oEvent
	 */
	Link.prototype.ontouchstart = function(oEvent) {
		if (this.getEnabled()) {
			// for controls which need to know whether they should handle events bubbling from here
			oEvent.setMarked();
		}
	};

	/* override standard setters with direct DOM manipulation */

	Link.prototype.setText = function(sText){
		this.setProperty("text", sText, true);
		sText = this.getProperty("text");
		this.$().text(sText);
		return this;
	};

	Link.prototype.setHref = function(sUri){
		this.setProperty("href", sUri, true);
		sUri = this.getProperty("href");
		this.$().attr("href", sUri);
		return this;
	};

	Link.prototype.setSubtle = function(bSubtle){
		this.setProperty("subtle", bSubtle, true);

		var $this = this.$();
		if ($this.length) { // only when actually rendered
			$this.toggleClass("sapMLnkSubtle", bSubtle);
			if (bSubtle) {
				if (!jQuery.sap.domById(this.getId() + "-linkSubtle")) {
					$this.append("" + this._getLinkDescription("LINK_SUBTLE") + "");
				}
			} else {
				jQuery.sap.byId(this.getId() + "-linkSubtle").remove();
			}
		}
		return this;
	};

	Link.prototype.setEmphasized = function(bEmphasized){
		this.setProperty("emphasized", bEmphasized, true);

		var $this = this.$();
		if ($this.length) { // only when actually rendered
			$this.toggleClass("sapMLnkEmphasized", bEmphasized);
			if (bEmphasized) { // strictly spoken this should only be done when accessibility mode is true. But it is true by default, so not sure it is worth checking...
				if (!jQuery.sap.domById(this.getId() + "-linkEmphasized")) {
					$this.append("" + this._getLinkDescription("LINK_EMPHASIZED") + "");
				}
			} else {
				jQuery.sap.byId(this.getId() + "-linkEmphasized").remove();
			}
		}
		return this;
	};

	Link.prototype.setWrapping = function(bWrapping){
		this.setProperty("wrapping", bWrapping, true);
		this.$().toggleClass("sapMLnkWrapping", bWrapping);
		return this;
	};

	Link.prototype.setEnabled = function(bEnabled){
		if (bEnabled !== this.getProperty("enabled")) { // do nothing when the same value is set again (virtual table scrolling!) - don't use this.getEnabled() because of EnabledPropagator
			this.setProperty("enabled", bEnabled, true);
			var $this = this.$();
			$this.toggleClass("sapMLnkDsbl", !bEnabled);
			if (bEnabled) {
				$this.attr("disabled", false);
				$this.attr("tabindex", "0");
				$this.removeAttr("aria-disabled");
			} else {
				$this.attr("disabled", true);
				$this.attr("tabindex", "-1");
				$this.attr("aria-disabled", true);
			}
		}
		return this;
	};

	Link.prototype.setWidth = function(sWidth){
		this.setProperty("width", sWidth, true);
		this.$().toggleClass("sapMLnkMaxWidth", !sWidth);
		this.$().css("width", sWidth);
		return this;
	};

	Link.prototype.setTarget = function(sTarget){
		this.setProperty("target", sTarget, true);
		if (!sTarget) {
			this.$().removeAttr("target");
		} else {
			this.$().attr("target", sTarget);
		}
		return this;
	};

	/**
	 * Translates a text from the resource bundle.
	 *
	 * @param {String} sKey the resource to be translated
	 * @private
	 * @returns {String} the translated text
	 */
	Link.prototype._getLinkDescription = function(sKey) {
		var oRb = sap.ui.getCore().getLibraryResourceBundle("sap.m");
		var sText = oRb.getText(sKey);
		return sText;
	};

	return Link;

}, /* bExport= */ true);
<|endoftext|>


<commit_before>import { resolve, join, sep } from 'path'
import { createHash } from 'crypto'
import webpack from 'webpack'
import glob from 'glob-promise'
import WriteFilePlugin from 'write-file-webpack-plugin'
import FriendlyErrorsWebpackPlugin from 'friendly-errors-webpack-plugin'
import CaseSensitivePathPlugin from 'case-sensitive-paths-webpack-plugin'
import UglifyJsPlugin from 'uglifyjs-webpack-plugin'
import UnlinkFilePlugin from './plugins/unlink-file-plugin'
import PagesPlugin from './plugins/pages-plugin'
import DynamicChunksPlugin from './plugins/dynamic-chunks-plugin'
import CombineAssetsPlugin from './plugins/combine-assets-plugin'
import getConfig from '../config'
import * as babelCore from 'babel-core'
import findBabelConfig from './babel/find-config'
import rootModuleRelativePath from './root-module-relative-path'

const documentPage = join('pages', '_document.js')
const defaultPages = [
  '_error.js',
  '_document.js'
]
const nextPagesDir = join(__dirname, '..', '..', 'pages')
const nextNodeModulesDir = join(__dirname, '..', '..', '..', 'node_modules')
const interpolateNames = new Map(defaultPages.map((p) => {
  return [join(nextPagesDir, p), `dist/pages/${p}`]
}))

const relativeResolve = rootModuleRelativePath(require)

export default async function createCompiler (dir, { dev = false, quiet = false, buildDir, conf = null } = {}) {
  dir = resolve(dir)
  const config = getConfig(dir, conf)
  const defaultEntries = dev ? [
    join(__dirname, '..', '..', 'client', 'webpack-hot-middleware-client'),
    join(__dirname, '..', '..', 'client', 'on-demand-entries-client')
  ] : []
  const mainJS = dev
    ? require.resolve('../../client/next-dev') : require.resolve('../../client/next')

  let totalPages

  const entry = async () => {
    const entries = {
      'main.js': [
        ...defaultEntries,
        mainJS
      ]
    }

    const pages = await glob('pages/**/*.js', { cwd: dir })
    const devPages = pages.filter((p) => p === 'pages/_document.js' || p === 'pages/_error.js')

    // In the dev environment, on-demand-entry-handler will take care of
    // managing pages.
    if (dev) {
      for (const p of devPages) {
        entries[join('bundles', p)] = [`./${p}?entry`]
      }
    } else {
      for (const p of pages) {
        entries[join('bundles', p)] = [`./${p}?entry`]
      }
    }

    for (const p of defaultPages) {
      const entryName = join('bundles', 'pages', p)
      if (!entries[entryName]) {
        entries[entryName] = [join(nextPagesDir, p) + '?entry']
      }
    }

    totalPages = pages.filter((p) => p !== documentPage).length

    return entries
  }

  const plugins = [
    new webpack.IgnorePlugin(/(precomputed)/, /node_modules.+(elliptic)/),
    new webpack.LoaderOptionsPlugin({
      options: {
        context: dir,
        customInterpolateName (url, name, opts) {
          return interpolateNames.get(this.resourcePath) || url
        }
      }
    }),
    new WriteFilePlugin({
      exitOnErrors: false,
      log: false,
      // required not to cache removed files
      useHashIndex: false
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'commons',
      filename: 'commons.js',
      minChunks (module, count) {
        // In the dev we use on-demand-entries.
        // So, it makes no sense to use commonChunks based on the minChunks count.
        // Instead, we move all the code in node_modules into this chunk.
        // With that, we could gain better performance for page-rebuild process.
        if (dev) {
          return module.context && module.context.indexOf('node_modules') >= 0
        }

        // We need to move react-dom explicitly into common chunks.
        // Otherwise, if some other page or module uses it, it might
        // included in that bundle too.
        if (module.context && module.context.indexOf(`${sep}react-dom${sep}`) >= 0) {
          return true
        }

        // If there are one or two pages, only move modules to common if they are
        // used in all of the pages. Otherwise, move modules used in at-least
        // 1/2 of the total pages into commons.
        if (totalPages <= 2) {
          return count >= totalPages
        }
        return count >= totalPages * 0.5
      }
    }),
    // This chunk contains all the webpack related code. So, all the changes
    // related to that happens to this chunk.
    // It won't touch commons.js and that gives us much better re-build perf.
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      filename: 'manifest.js'
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(dev ? 'development' : 'production')
    }),
    new PagesPlugin(),
    new DynamicChunksPlugin(),
    new CaseSensitivePathPlugin(),
    new webpack.optimize.ModuleConcatenationPlugin()
  ]

  if (dev) {
    plugins.push(
      new webpack.HotModuleReplacementPlugin(),
      new webpack.NoEmitOnErrorsPlugin(),
      new UnlinkFilePlugin()
    )
    if (!quiet) {
      plugins.push(new FriendlyErrorsWebpackPlugin())
    }
  } else {
    plugins.push(new webpack.IgnorePlugin(/react-hot-loader/))
    plugins.push(
      new CombineAssetsPlugin({
        input: ['manifest.js', 'commons.js', 'main.js'],
        output: 'app.js'
      }),
      new UglifyJsPlugin({
        compress: { warnings: false },
        sourceMap: false
      })
    )
  }

  const nodePathList = (process.env.NODE_PATH || '')
    .split(process.platform === 'win32' ? ';' : ':')
    .filter((p) => !!p)

  const mainBabelOptions = {
    cacheDirectory: true,
    presets: []
  }

  const externalBabelConfig = findBabelConfig(dir)
  if (externalBabelConfig) {
    console.log(`> Using external babel configuration`)
    console.log(`> location: "${externalBabelConfig.loc}"`)
    // It's possible to turn off babelrc support via babelrc itself.
    // In that case, we should add our default preset.
    // That's why we need to do this.
    const { options } = externalBabelConfig
    mainBabelOptions.babelrc = options.babelrc !== false
  } else {
    mainBabelOptions.babelrc = false
  }

  // Add our default preset if the no "babelrc" found.
  if (!mainBabelOptions.babelrc) {
    mainBabelOptions.presets.push(require.resolve('./babel/preset'))
  }

  const rules = (dev ? [{
    test: /\.js(\?[^?]*)?$/,
    loader: 'hot-self-accept-loader',
    include: [
      join(dir, 'pages'),
      nextPagesDir
    ]
  }, {
    test: /\.js(\?[^?]*)?$/,
    loader: 'react-hot-loader/webpack',
    exclude: /node_modules/
  }] : [])
  .concat([{
    test: /\.json$/,
    loader: 'json-loader'
  }, {
    test: /\.(js|json)(\?[^?]*)?$/,
    loader: 'emit-file-loader',
    include: [dir, nextPagesDir],
    exclude (str) {
      return /node_modules/.test(str) && str.indexOf(nextPagesDir) !== 0
    },
    options: {
      name: 'dist/[path][name].[ext]',
      // By default, our babel config does not transpile ES2015 module syntax because
      // webpack knows how to handle them. (That's how it can do tree-shaking)
      // But Node.js doesn't know how to handle them. So, we have to transpile them here.
      transform ({ content, sourceMap, interpolatedName }) {
        // Only handle .js files
        if (!(/\.js$/.test(interpolatedName))) {
          return { content, sourceMap }
        }

        const transpiled = babelCore.transform(content, {
          babelrc: false,
          sourceMaps: dev ? 'both' : false,
          // Here we need to resolve all modules to the absolute paths.
          // Earlier we did it with the babel-preset.
          // But since we don't transpile ES2015 in the preset this is not resolving.
          // That's why we need to do it here.
          // See more: https://github.com/zeit/next.js/issues/951
          plugins: [
            [require.resolve('babel-plugin-transform-es2015-modules-commonjs')],
            [
              require.resolve('babel-plugin-module-resolver'),
              {
                alias: {
                  'babel-runtime': relativeResolve('babel-runtime/package'),
                  'next/link': relativeResolve('../../lib/link'),
                  'next/prefetch': relativeResolve('../../lib/prefetch'),
                  'next/css': relativeResolve('../../lib/css'),
                  'next/dynamic': relativeResolve('../../lib/dynamic'),
                  'next/head': relativeResolve('../../lib/head'),
                  'next/document': relativeResolve('../../server/document'),
                  'next/router': relativeResolve('../../lib/router'),
                  'next/error': relativeResolve('../../lib/error'),
                  'styled-jsx/style': relativeResolve('styled-jsx/style')
                }
              }
            ]
          ],
          inputSourceMap: sourceMap
        })

        return {
          content: transpiled.code,
          sourceMap: transpiled.map
        }
      }
    }
  }, {
    loader: 'babel-loader',
    include: nextPagesDir,
    exclude (str) {
      return /node_modules/.test(str) && str.indexOf(nextPagesDir) !== 0
    },
    options: {
      babelrc: false,
      cacheDirectory: true,
      presets: [require.resolve('./babel/preset')]
    }
  }, {
    test: /\.js(\?[^?]*)?$/,
    loader: 'babel-loader',
    include: [dir],
    exclude (str) {
      return /node_modules/.test(str)
    },
    options: mainBabelOptions
  }])

  let webpackConfig = {
    context: dir,
    entry,
    output: {
      path: buildDir ? join(buildDir, '.next') : join(dir, config.distDir),
      filename: '[name]',
      libraryTarget: 'commonjs2',
      publicPath: '/_next/webpack/',
      strictModuleExceptionHandling: true,
      devtoolModuleFilenameTemplate ({ resourcePath }) {
        const hash = createHash('sha1')
        hash.update(Date.now() + '')
        const id = hash.digest('hex').slice(0, 7)

        // append hash id for cache busting
        return `webpack:///${resourcePath}?${id}`
      },
      // This saves chunks with the name given via require.ensure()
      chunkFilename: '[name]'
    },
    resolve: {
      modules: [
        nextNodeModulesDir,
        'node_modules',
        ...nodePathList
      ]
    },
    resolveLoader: {
      modules: [
        nextNodeModulesDir,
        'node_modules',
        join(__dirname, 'loaders'),
        ...nodePathList
      ]
    },
    plugins,
    module: {
      rules
    },
    devtool: dev ? 'cheap-module-inline-source-map' : false,
    performance: { hints: false }
  }

  if (config.webpack) {
    console.log(`> Using "webpack" config function defined in ${config.configOrigin}.`)
    webpackConfig = await config.webpack(webpackConfig, { dev })
  }
  return webpack(webpackConfig)
}
<commit_msg>Webpack's ModuleConcatenationPlugin plugin doesn't work well with HMR. (#2584)<commit_after>import { resolve, join, sep } from 'path'
import { createHash } from 'crypto'
import webpack from 'webpack'
import glob from 'glob-promise'
import WriteFilePlugin from 'write-file-webpack-plugin'
import FriendlyErrorsWebpackPlugin from 'friendly-errors-webpack-plugin'
import CaseSensitivePathPlugin from 'case-sensitive-paths-webpack-plugin'
import UglifyJsPlugin from 'uglifyjs-webpack-plugin'
import UnlinkFilePlugin from './plugins/unlink-file-plugin'
import PagesPlugin from './plugins/pages-plugin'
import DynamicChunksPlugin from './plugins/dynamic-chunks-plugin'
import CombineAssetsPlugin from './plugins/combine-assets-plugin'
import getConfig from '../config'
import * as babelCore from 'babel-core'
import findBabelConfig from './babel/find-config'
import rootModuleRelativePath from './root-module-relative-path'

const documentPage = join('pages', '_document.js')
const defaultPages = [
  '_error.js',
  '_document.js'
]
const nextPagesDir = join(__dirname, '..', '..', 'pages')
const nextNodeModulesDir = join(__dirname, '..', '..', '..', 'node_modules')
const interpolateNames = new Map(defaultPages.map((p) => {
  return [join(nextPagesDir, p), `dist/pages/${p}`]
}))

const relativeResolve = rootModuleRelativePath(require)

export default async function createCompiler (dir, { dev = false, quiet = false, buildDir, conf = null } = {}) {
  dir = resolve(dir)
  const config = getConfig(dir, conf)
  const defaultEntries = dev ? [
    join(__dirname, '..', '..', 'client', 'webpack-hot-middleware-client'),
    join(__dirname, '..', '..', 'client', 'on-demand-entries-client')
  ] : []
  const mainJS = dev
    ? require.resolve('../../client/next-dev') : require.resolve('../../client/next')

  let totalPages

  const entry = async () => {
    const entries = {
      'main.js': [
        ...defaultEntries,
        mainJS
      ]
    }

    const pages = await glob('pages/**/*.js', { cwd: dir })
    const devPages = pages.filter((p) => p === 'pages/_document.js' || p === 'pages/_error.js')

    // In the dev environment, on-demand-entry-handler will take care of
    // managing pages.
    if (dev) {
      for (const p of devPages) {
        entries[join('bundles', p)] = [`./${p}?entry`]
      }
    } else {
      for (const p of pages) {
        entries[join('bundles', p)] = [`./${p}?entry`]
      }
    }

    for (const p of defaultPages) {
      const entryName = join('bundles', 'pages', p)
      if (!entries[entryName]) {
        entries[entryName] = [join(nextPagesDir, p) + '?entry']
      }
    }

    totalPages = pages.filter((p) => p !== documentPage).length

    return entries
  }

  const plugins = [
    new webpack.IgnorePlugin(/(precomputed)/, /node_modules.+(elliptic)/),
    new webpack.LoaderOptionsPlugin({
      options: {
        context: dir,
        customInterpolateName (url, name, opts) {
          return interpolateNames.get(this.resourcePath) || url
        }
      }
    }),
    new WriteFilePlugin({
      exitOnErrors: false,
      log: false,
      // required not to cache removed files
      useHashIndex: false
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'commons',
      filename: 'commons.js',
      minChunks (module, count) {
        // In the dev we use on-demand-entries.
        // So, it makes no sense to use commonChunks based on the minChunks count.
        // Instead, we move all the code in node_modules into this chunk.
        // With that, we could gain better performance for page-rebuild process.
        if (dev) {
          return module.context && module.context.indexOf('node_modules') >= 0
        }

        // We need to move react-dom explicitly into common chunks.
        // Otherwise, if some other page or module uses it, it might
        // included in that bundle too.
        if (module.context && module.context.indexOf(`${sep}react-dom${sep}`) >= 0) {
          return true
        }

        // If there are one or two pages, only move modules to common if they are
        // used in all of the pages. Otherwise, move modules used in at-least
        // 1/2 of the total pages into commons.
        if (totalPages <= 2) {
          return count >= totalPages
        }
        return count >= totalPages * 0.5
      }
    }),
    // This chunk contains all the webpack related code. So, all the changes
    // related to that happens to this chunk.
    // It won't touch commons.js and that gives us much better re-build perf.
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      filename: 'manifest.js'
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(dev ? 'development' : 'production')
    }),
    new PagesPlugin(),
    new DynamicChunksPlugin(),
    new CaseSensitivePathPlugin()
  ]

  if (dev) {
    plugins.push(
      new webpack.HotModuleReplacementPlugin(),
      new webpack.NoEmitOnErrorsPlugin(),
      new UnlinkFilePlugin()
    )
    if (!quiet) {
      plugins.push(new FriendlyErrorsWebpackPlugin())
    }
  } else {
    plugins.push(new webpack.IgnorePlugin(/react-hot-loader/))
    plugins.push(
      new CombineAssetsPlugin({
        input: ['manifest.js', 'commons.js', 'main.js'],
        output: 'app.js'
      }),
      new UglifyJsPlugin({
        compress: { warnings: false },
        sourceMap: false
      })
    )
    plugins.push(new webpack.optimize.ModuleConcatenationPlugin())
  }

  const nodePathList = (process.env.NODE_PATH || '')
    .split(process.platform === 'win32' ? ';' : ':')
    .filter((p) => !!p)

  const mainBabelOptions = {
    cacheDirectory: true,
    presets: []
  }

  const externalBabelConfig = findBabelConfig(dir)
  if (externalBabelConfig) {
    console.log(`> Using external babel configuration`)
    console.log(`> location: "${externalBabelConfig.loc}"`)
    // It's possible to turn off babelrc support via babelrc itself.
    // In that case, we should add our default preset.
    // That's why we need to do this.
    const { options } = externalBabelConfig
    mainBabelOptions.babelrc = options.babelrc !== false
  } else {
    mainBabelOptions.babelrc = false
  }

  // Add our default preset if the no "babelrc" found.
  if (!mainBabelOptions.babelrc) {
    mainBabelOptions.presets.push(require.resolve('./babel/preset'))
  }

  const rules = (dev ? [{
    test: /\.js(\?[^?]*)?$/,
    loader: 'hot-self-accept-loader',
    include: [
      join(dir, 'pages'),
      nextPagesDir
    ]
  }, {
    test: /\.js(\?[^?]*)?$/,
    loader: 'react-hot-loader/webpack',
    exclude: /node_modules/
  }] : [])
  .concat([{
    test: /\.json$/,
    loader: 'json-loader'
  }, {
    test: /\.(js|json)(\?[^?]*)?$/,
    loader: 'emit-file-loader',
    include: [dir, nextPagesDir],
    exclude (str) {
      return /node_modules/.test(str) && str.indexOf(nextPagesDir) !== 0
    },
    options: {
      name: 'dist/[path][name].[ext]',
      // By default, our babel config does not transpile ES2015 module syntax because
      // webpack knows how to handle them. (That's how it can do tree-shaking)
      // But Node.js doesn't know how to handle them. So, we have to transpile them here.
      transform ({ content, sourceMap, interpolatedName }) {
        // Only handle .js files
        if (!(/\.js$/.test(interpolatedName))) {
          return { content, sourceMap }
        }

        const transpiled = babelCore.transform(content, {
          babelrc: false,
          sourceMaps: dev ? 'both' : false,
          // Here we need to resolve all modules to the absolute paths.
          // Earlier we did it with the babel-preset.
          // But since we don't transpile ES2015 in the preset this is not resolving.
          // That's why we need to do it here.
          // See more: https://github.com/zeit/next.js/issues/951
          plugins: [
            [require.resolve('babel-plugin-transform-es2015-modules-commonjs')],
            [
              require.resolve('babel-plugin-module-resolver'),
              {
                alias: {
                  'babel-runtime': relativeResolve('babel-runtime/package'),
                  'next/link': relativeResolve('../../lib/link'),
                  'next/prefetch': relativeResolve('../../lib/prefetch'),
                  'next/css': relativeResolve('../../lib/css'),
                  'next/dynamic': relativeResolve('../../lib/dynamic'),
                  'next/head': relativeResolve('../../lib/head'),
                  'next/document': relativeResolve('../../server/document'),
                  'next/router': relativeResolve('../../lib/router'),
                  'next/error': relativeResolve('../../lib/error'),
                  'styled-jsx/style': relativeResolve('styled-jsx/style')
                }
              }
            ]
          ],
          inputSourceMap: sourceMap
        })

        return {
          content: transpiled.code,
          sourceMap: transpiled.map
        }
      }
    }
  }, {
    loader: 'babel-loader',
    include: nextPagesDir,
    exclude (str) {
      return /node_modules/.test(str) && str.indexOf(nextPagesDir) !== 0
    },
    options: {
      babelrc: false,
      cacheDirectory: true,
      presets: [require.resolve('./babel/preset')]
    }
  }, {
    test: /\.js(\?[^?]*)?$/,
    loader: 'babel-loader',
    include: [dir],
    exclude (str) {
      return /node_modules/.test(str)
    },
    options: mainBabelOptions
  }])

  let webpackConfig = {
    context: dir,
    entry,
    output: {
      path: buildDir ? join(buildDir, '.next') : join(dir, config.distDir),
      filename: '[name]',
      libraryTarget: 'commonjs2',
      publicPath: '/_next/webpack/',
      strictModuleExceptionHandling: true,
      devtoolModuleFilenameTemplate ({ resourcePath }) {
        const hash = createHash('sha1')
        hash.update(Date.now() + '')
        const id = hash.digest('hex').slice(0, 7)

        // append hash id for cache busting
        return `webpack:///${resourcePath}?${id}`
      },
      // This saves chunks with the name given via require.ensure()
      chunkFilename: '[name]'
    },
    resolve: {
      modules: [
        nextNodeModulesDir,
        'node_modules',
        ...nodePathList
      ]
    },
    resolveLoader: {
      modules: [
        nextNodeModulesDir,
        'node_modules',
        join(__dirname, 'loaders'),
        ...nodePathList
      ]
    },
    plugins,
    module: {
      rules
    },
    devtool: dev ? 'cheap-module-inline-source-map' : false,
    performance: { hints: false }
  }

  if (config.webpack) {
    console.log(`> Using "webpack" config function defined in ${config.configOrigin}.`)
    webpackConfig = await config.webpack(webpackConfig, { dev })
  }
  return webpack(webpackConfig)
}
<|endoftext|>


<commit_before>'use strict';

var http    = require('http')
  , fs      = require('fs')
  , PORT    = 6060
  , express = require('express')
  , app     = express()
  , util    = require('util');

/*
 * use ejs to serve static files
 */
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static(__dirname + '/views'));

/*
 * get git log file
 * TODO seperate this into a module
 */
var gitText = {};
fs.readFile('./views/gitlog.txt', 'utf8', function (error, data) {
    if (! error) gitText = { 'content': data };
});

/*
 * read body files for later serving
 */
var bodies = {};
var subjects = {
    projects:   'Personal Projects'
    , about:    'About Me'
    , contact:  'Get in Touch'
    , home:     'Hello'
};
var files = [ 'about', 'projects', 'contact', 'home'];
for (var i = 0; i < files.length; i++) {
    bodies[files[i]] = fs.readFileSync('./views/bodies/body-' + files[i] + '.ejs', 'utf8');
}

/*
 * valid urls
 */
var valid = [ /^\/$/
    , /^\/favicon\.ico$/
    , /^\/body\/[a-z]+$/
    , /^\/robots\.txt$/
    , /^\/getGitLog$/
    , /^\/comp74\/[a-zA-z0-9]/
    , /^\/notes\/[a-zA-Z]*$/
    , /^\/scripts\/[a-zA-Z]*$/
];

/*
 * read some submodules' files for later serving
 */
var reader  = require('./face-read.js');
var notes = {};
reader.read('./views/notes', function (result) {
    notes = result;
});
var scripts = {};
reader.read('./views/scripts', function (result) {
    scripts = result;
}, { extension: 'sh' });

/*
 * XXX COMP74-branch related
 *   get nullstudent's public repositories for later serving
 */
var Repo = require('./CPA2016/repo.js')(process.argv[2]);
var list = [];
app.get('/comp74', function (req, res, next) {
    res.render('comp74.ejs', {
        subject: 'COMP74 - Github API',
    });
});
app.get('/comp74/git-list', function (req, res, next) {
    console.log('fetching new git-list');
    Repo.list(function (r) {
        list = r;
        res.status(200).json({
            data: {
                content: list
            }
        });
    });
});
app.get('/comp74/git-create', function (req, res, next) {
    console.log(req.query.createMe);
    var createName = req.query.createMe.name || 'null';
    var createDesc = req.query.createMe.desc || 'null';
    var result = {};
    Repo.create(createName, createDesc, function (response) {
        console.log(response);
        if (response.statusCode === 200) {
            result = {
                status: 200,
                message: 'Created repository'
            };
        } else {
            result = {
                status: 400,
                message: 'Could not create this repository'
            };
        }

        console.log('result==', result);
        res.status(response.statusCode).json({
            data: result
        });
    });
});
app.get('/comp74/git-rm', function (req, res, next) {
    console.log(req.query.deleteMe);
    var deleteMe =  req.query.deleteMe;
    var result = {};

    if (deleteMe.match(/gq|CPA2016/)) {
        result = {
            status: 400,
            message: 'Not allowed to delete this repository'
        };
        send(result);

    } else if (! deleteMe.match(/gq|CPA2016/)) {
        Repo.delete(deleteMe, function (response) {
            result = response;
            send(result);
        });
    } else {
        res.end(501);
    }

    function send(result) {
        res.status(result.status).json({
            data: {
                status: result.status,
                message: result.message
            }
        });
    }
});

/*
 * HTTP request routers
 */
app.all('/*', function (req, res, next) {
    res.setHeader('X-Powered-By', 'Maisy');
    if (validConnection(req.path)) {
        // TODO put this in validConnection
        if (req.method !== 'GET') {
            res.end('403');
        } else {
            next();
        }
    } else {
        console.error('Invalid path "%s"', req.path);
        // TODO add proper 404 page
        res.end('404');
    }
    logConnection(req); // TODO log fact of bad conn attempt

});

app.get('/', function (req, res, next) {
	res.render('index.ejs', {
        debug: false,
        subject: 'Hello',
        content: bodies['home']
    });
});
app.get('/body/:which', function (req, res, next) {
    var which = req.params.which;

    res.status(200).json({
        data: {
            subject: subjects[which],
            content: bodies[which]
        }
    });
});
app.get('/robots.txt', function (req, res) {
    res.type('text/plain');
    res.send('#011000100110010101100101011100000010'
    + '00000110001001101111011011110111000000100001'
    + '\nUser-agent: *\nDisallow: /');
});
app.get('/getGitLog', function (req, res) {
    res.send(gitText);
});

app.get('/notes', function (req, res) {
    res.render('notes.ejs', {
        subject: 'Some Notes',
        titles: Object.keys(notes),
        notes: notes
    });
});
app.get('/notes/:which', function (req, res) {
    var which = req.params.which;
    res.setHeader('Content-Type', 'text/plain');
    res.send((notes[which]) || '404');
});

app.get('/scripts', function (req, res) {
    res.render('scripts.ejs', {
        subject: 'Some Scripts',
        titles: Object.keys(scripts),
        scripts: scripts
    });
});
app.get('/scripts/:which', function (req, res) {
    var which = req.params.which;
    res.setHeader('Content-Type', 'text/plain');
    res.send((scripts[which]) || '404');
});

/*
 * listen on port 6060 (rerouted from 80)
 */
app.listen(PORT, function () {
	console.log('facer listening on port', PORT);
});

function validConnection(path) {
    var result = false;
    valid.forEach(function (r) {
        if (path.match(r) !== null) {
            result = true;
        }
    });
    return result;
}

function logConnection(req) {

    console.log(req.path);

    var now = new Date();
    var info = util.format('[%s (%s)]:\t%s,\t%s,\t%s',
      now.toDateString(), now.toLocaleTimeString(),  req.method, req.ip, req.path);
    info += '\n';
    fs.appendFile('logs/connect.log', info, function (error) {
        if (error) throw new Error(("Error writing to file: " + error));
    });
    if (typeof req.path === 'undefined') {
        console.error('undefined ip', req.route);
    }
}
<commit_msg>Remove usage of CPA2016<commit_after>'use strict';

var http    = require('http')
  , fs      = require('fs')
  , PORT    = 6060
  , express = require('express')
  , app     = express()
  , util    = require('util');

/*
 * use ejs to serve static files
 */
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static(__dirname + '/views'));

/*
 * get git log file
 * TODO seperate this into a module
 */
var gitText = {};
fs.readFile('./views/gitlog.txt', 'utf8', function (error, data) {
    if (! error) gitText = { 'content': data };
});

/*
 * read body files for later serving
 */
var bodies = {};
var subjects = {
    projects:   'Personal Projects'
    , about:    'About Me'
    , contact:  'Get in Touch'
    , home:     'Hello'
};
var files = [ 'about', 'projects', 'contact', 'home'];
for (var i = 0; i < files.length; i++) {
    bodies[files[i]] = fs.readFileSync('./views/bodies/body-' + files[i] + '.ejs', 'utf8');
}

/*
 * valid urls
 */
var valid = [ /^\/$/
    , /^\/favicon\.ico$/
    , /^\/body\/[a-z]+$/
    , /^\/robots\.txt$/
    , /^\/getGitLog$/
    , /^\/comp74\/[a-zA-z0-9]/
    , /^\/notes\/[a-zA-Z]*$/
    , /^\/scripts\/[a-zA-Z]*$/
];

/*
 * read some submodules' files for later serving
 */
var reader  = require('./face-read.js');
var notes = {};
reader.read('./views/notes', function (result) {
    notes = result;
});
var scripts = {};
reader.read('./views/scripts', function (result) {
    scripts = result;
}, { extension: 'sh' });

/*
 * HTTP request routers
 */
app.all('/*', function (req, res, next) {
    res.setHeader('X-Powered-By', 'Maisy');
    if (validConnection(req.path)) {
        // TODO put this in validConnection
        if (req.method !== 'GET') {
            res.end('403');
        } else {
            next();
        }
    } else {
        console.error('Invalid path "%s"', req.path);
        // TODO add proper 404 page
        res.end('404');
    }
    logConnection(req); // TODO log fact of bad conn attempt

});

app.get('/', function (req, res, next) {
	res.render('index.ejs', {
        debug: false,
        subject: 'Hello',
        content: bodies['home']
    });
});
app.get('/body/:which', function (req, res, next) {
    var which = req.params.which;

    res.status(200).json({
        data: {
            subject: subjects[which],
            content: bodies[which]
        }
    });
});
app.get('/robots.txt', function (req, res) {
    res.type('text/plain');
    res.send('#011000100110010101100101011100000010'
    + '00000110001001101111011011110111000000100001'
    + '\nUser-agent: *\nDisallow: /');
});
app.get('/getGitLog', function (req, res) {
    res.send(gitText);
});

app.get('/notes', function (req, res) {
    res.render('notes.ejs', {
        subject: 'Some Notes',
        titles: Object.keys(notes),
        notes: notes
    });
});
app.get('/notes/:which', function (req, res) {
    var which = req.params.which;
    res.setHeader('Content-Type', 'text/plain');
    res.send((notes[which]) || '404');
});

app.get('/scripts', function (req, res) {
    res.render('scripts.ejs', {
        subject: 'Some Scripts',
        titles: Object.keys(scripts),
        scripts: scripts
    });
});
app.get('/scripts/:which', function (req, res) {
    var which = req.params.which;
    res.setHeader('Content-Type', 'text/plain');
    res.send((scripts[which]) || '404');
});

/*
 * listen on port 6060 (rerouted from 80)
 */
app.listen(PORT, function () {
	console.log('facer listening on port', PORT);
});

function validConnection(path) {
    var result = false;
    valid.forEach(function (r) {
        if (path.match(r) !== null) {
            result = true;
        }
    });
    return result;
}

function logConnection(req) {

    console.log(req.path);

    var now = new Date();
    var info = util.format('[%s (%s)]:\t%s,\t%s,\t%s',
      now.toDateString(), now.toLocaleTimeString(),  req.method, req.ip, req.path);
    info += '\n';
    fs.appendFile('logs/connect.log', info, function (error) {
        if (error) throw new Error(("Error writing to file: " + error));
    });
    if (typeof req.path === 'undefined') {
        console.error('undefined ip', req.route);
    }
}
<|endoftext|>


<commit_before>const Mi5Module = require('./../models/mi5-module');
let module1 = new Mi5Module('module1',undefined, {port: 4841});
let skill1 = module1.addSkill('skill1');
let param1 = skill1.addInputParameter("distance", "Double", 2);
let param2 = skill1.addInputParameter("height", "Double", 2);
let param3 = skill1.addOutputParameter("weight", "Double", 2);
let variab = module1.addStateVariable("weight", "Double", 2);

module1.on("Idle", function(){
  console.log('You are now in idle mode');
});
module1.on("Resetting", function(){
  //
});

//let module2 = new Mi5Module('module2');

module1.onAny(function(event, value) {
  console.log('event: '+event, ' value: '+value);
});<commit_msg>add second module<commit_after>const Mi5Module = require('./../models/mi5-module');
let module1 = new Mi5Module('module1',undefined, {port: 4841});
let module2 = new Mi5Module('module2',undefined, {port: 4841});
let skill1 = module1.addSkill('skill1');
let param1 = skill1.addInputParameter("distance", "Double", 2);
let param2 = skill1.addInputParameter("height", "Double", 2);
let param3 = skill1.addOutputParameter("weight", "Double", 2);
let variab = module1.addStateVariable("weight", "Double", 2);

module1.on("Idle", function(){
  console.log('You are now in idle mode');
});
module1.on("Resetting", function(){
  //
});

//let module2 = new Mi5Module('module2');

module1.onAny(function(event, value) {
  console.log('event: '+event, ' value: '+value);
});<|endoftext|>


<commit_before>dbs_inputDate = function(pId) {
	$(pId + " input").focusin(function(e){
		$(this).select();
	});

	$(pId + " > .-container > .dbs_input-data").focusin(function(){
		$(this).addClass("dbs_input-data-FOCUS");
	});

	$(pId + " > .-container > .dbs_input-data > .-day").focusout(function(){
		var xV = dbsfaces.inputDate.getInputDateDay($(this));
		$(this).val(xV);
	});
	$(pId + " > .-container > .dbs_input-data > .-month").focusout(function(){
		var xV = dbsfaces.inputDate.getInputDateMonth($(this));
		$(this).val(xV);
	});
	$(pId + " > .-container > .dbs_input-data > .-year").focusout(function(){
		var xV = dbsfaces.inputDate.getInputDateYear($(this));
		$(this).val(xV);
	});
	$(pId + " > .-container > .dbs_input-data > .-hour").focusout(function(){
		var xV = dbsfaces.inputDate.getInputDateHour($(this));
		$(this).val(xV);
	});
	$(pId + " > .-container > .dbs_input-data > .-minute").focusout(function(){
		var xV = dbsfaces.inputDate.getInputDateMinute($(this));
		$(this).val(xV);
	});
	$(pId + " > .-container > .dbs_input-data > .-second").focusout(function(){
		var xV = dbsfaces.inputDate.getInputDateSecond($(this));
		$(this).val(xV);
	});

	$(pId + " > .-container > .dbs_input-data").focusout(function(){
		$(this).removeClass("dbs_input-data-FOCUS");
		if (dbsfaces.inputDate.getIsValid($(this).parent())==""){
			$(this).addClass("-error");
		}else{
			$(this).removeClass("-error");
		}
	});

	$(pId + " > .-container > .dbs_input-data > input").keydown(function(e){
		var xC = "";
		//Ignora tecla se não for uma tecla válida para o campo de data
		if (!dbsfaces.inputDate.isValidKey(e)){
			e.preventDefault();
			return false;
		}

		//Ignora valor digitado se a data não for válida
		var xS = $(this).get(0).selectionEnd - $(this).get(0).selectionStart;
		var xV = String.fromCharCode(e.keyCode);
		if (xS == 0 &&
			dbsfaces.number.isNumber(String.fromCharCode(e.keyCode))){
			var xD = dbsfaces.inputDate.getInputDateDay($(this));
			var xM = dbsfaces.inputDate.getInputDateMonth($(this));
			var xY = dbsfaces.inputDate.getInputDateYear($(this));
			if ($(this).hasClass("-day")){
				xD = xD + xV;
			}else if ($(this).hasClass("-month")){
				xM = xM + xV;
			}
			var xDate = dbsfaces.date.isDate(xY, xM, xD, 0, 0, 0);
			if (xDate == "" && xD != ""  && xM != ""  && xY != ""){
				e.preventDefault();
				return;
			}
		}

		//Pula para o próximo campo de input
		if (e.keyCode == 9 &&
			!e.shiftKey){
			//Desabilitador até verificar se é bom ter está opção
			//$(this).parent().children("input").last().focusNextInputField();
			return;
		//puda para o próximo campo dento da data com a BARRA
		}else if (e.keyCode == 191){
			xC = $(this).nextAll("input:first");
			e.preventDefault();
			return;
		}
		//Se foi configurado um novo campo para receber o foco, pula para ele
		if (xC.length){
			e.preventDefault();
			xC.focus().select();
			return;
		}

		var xAdd = 0;
		//Adiciona data quando pressionado seta para cima
		if (e.keyCode == 38){
			xAdd = 1;
		//Subtrai data quando pressionado seta para baixo
		}else if (e.keyCode == 40){
			xAdd = -1;
		}
		if (xAdd != 0){
			if ($(this).hasClass("-day")){
				dbsfaces.inputDate.addDate($(this), "day", xAdd);
			}else if ($(this).hasClass("-month")){
				dbsfaces.inputDate.addDate($(this), "month", xAdd);
			}else if ($(this).hasClass("-year")){
				dbsfaces.inputDate.addDate($(this), "year", xAdd);
			}
		}
	});

	$(pId + " > .-container > .dbs_input-data > input").keyup(function(e){
		var xC = "";
		var xS = $(this).get(0).selectionEnd - $(this).get(0).selectionStart;
		//Pula para o próximo campo(mes ou ano) da data caso e campo atual esteja completo
		if (xS == 0 &&
			dbsfaces.number.isNumber(String.fromCharCode(e.keyCode))){
			var xL = $(this).val().length;
			//Se estiver completo com os dois digitos, pula
			if (xL == 2){
				var xC = $(this).nextAll("input:first");
			}
		}
		//Volta o campo quando digitado a seta para esquerda
		if (e.keyCode == 37 &&
			!e.shiftKey){
			xC = $(this).prevAll("input:first");
		//Avança para o próximo campo quando digitado a seta para direita
		}else if ((e.keyCode == 39  &&
				  !e.shiftKey) ||
				  e.which == 47){
			xC = $(this).nextAll("input:first");
		}
		//Se foi configurado um novo campo para receber o foco, pula para ele
		if (xC.length){
			e.preventDefault();
			xC.focus().select();
		}
	});
}

dbsfaces.inputDate = {
	isValidKey: function(e){
		if (e.altKey ||
			e.ctrlKey){
			return false;
		}
		if (e.keyCode == 9 ||
			e.keyCode == 8 ||
			e.keyCode == 13 ||
			e.keyCode == 37 ||
			e.keyCode == 38 ||
			e.keyCode == 39 ||
			e.keyCode == 40 ||
			e.keyCode == 47 ||
			e.keyCode == 191 ||
			(!e.shiftKey && dbsfaces.number.isNumber(String.fromCharCode(e.keyCode))) ){
			return true;
		}
		return false;
	},

	addDate: function(pId, pField, pAdd){
		var xId = pId.parent();
		var xD = parseInt(dbsfaces.inputDate.getInputDateDay(pId),10);
		var xM = parseInt(dbsfaces.inputDate.getInputDateMonth(pId),10);
		var xY = parseInt(dbsfaces.inputDate.getInputDateYear(pId),10);
		if (pField == "day"){
			xD = xD + pAdd;
		}else if (pField == "month"){
			xM = xM + pAdd;
		}else if (pField == "year"){
			xY = xY + pAdd;
		}
		var xDate = dbsfaces.date.isDate(xY, xM, xD, 0, 0, 0);
		if (xDate != ""){
			if (pField == "day"){
				$(xId).children(".-day").val(xD);
			}else if (pField == "month"){
				$(xId).children(".-month").val(xM);
			}else if (pField == "year"){
				$(xId).children(".-year").val(xY);
			}
		}
	},

	getInputDateValue: function(pId){
		var xId = $(pId).find(".dbs_input-data > .-day");
		var xD = dbsfaces.inputDate.getInputDateDay(xId);
		var xM = dbsfaces.inputDate.getInputDateMonth(xId);
		var xY = dbsfaces.inputDate.getInputDateYear(xId);
		var xDate = dbsfaces.date.isDate(xY, xM, xD, 0, 0, 0);
		return xDate;
	},

	getIsValid: function(pId){
		var xId = $(pId).find(".dbs_input-data > .-day");
		var xD = dbsfaces.inputDate.getInputDateDay(xId);
		var xM = dbsfaces.inputDate.getInputDateMonth(xId);
		var xY = dbsfaces.inputDate.getInputDateYear(xId);
		if (xD == "" &&
			xM == "" &&
			xY == ""){
			return true;
		}else{
			var xDate = dbsfaces.inputDate.getInputDateValue(pId);
			if (xDate == ""){
				return false;
			}else{
				return true;
			}
		}
	},

	getInputDateDay: function(pId){
		var xId = pId.parent();
		var xV = $(xId).children(".-day").val();
//		if (xV!=""){
//			if (dbsfaces.number.isNumber(xV)){
//				xV = parseInt(xV,10);
//				if (xV < 10){
//					xV = "0" + xV;
//				}
//			}else{
//				xV = "";
//			}
//		}
//		return xV;
		return dbsfaces.inputDate.leadingZero(xV);
	},

	getInputDateMonth: function(pId){
		var xId = pId.parent();
		var xV = $(xId).children(".-month").val();
//		if (xV!=""){
//			if (dbsfaces.number.isNumber(xV)){
//				xV = parseInt(xV,10);
//				if (xV < 10){
//					xV = "0" + xV;
//				}
//			}else{
//				xV = "";
//			}
//		}
//		return xV;
		return dbsfaces.inputDate.leadingZero(xV);
	},

	getInputDateYear: function(pId){
		var xId = pId.parent();
		var xV = $(xId).children(".-year").val();
		if (xV!=""){
			if (dbsfaces.number.isNumber(xV)){
				xV = parseInt(xV,10);
				if (xV < 70){
					xV = xV + 2000;
				}else if (xV < 100){
					xV = xV + 1900;
				}else if (xV < 1000){
					xV = xV + 2000;
				}
			}else{
				xV = "";
			}
		}
		return xV;
	},

	getInputDateHour: function(pId){
		var xId = pId.parent();
		var xV = $(xId).children(".-hour").val();
//		if (xV!=""){
//			if (dbsfaces.number.isNumber(xV)){
//				xV = parseInt(xV,10);
//				if (xV < 10){
//					xV = "0" + xV;
//				}
//			}else{
//				xV = "";
//			}
//		}
//		return xV;
		return dbsfaces.inputDate.leadingZero(xV);
	},

	getInputDateMinute: function(pId){
		var xId = pId.parent();
		var xV = $(xId).children(".-minute").val();
//		if (xV!=""){
//			if (dbsfaces.number.isNumber(xV)){
//				xV = parseInt(xV,10);
//				if (xV < 10){
//					xV = "0" + xV;
//				}
//			}else{
//				xV = "";
//			}
//		}
		return dbsfaces.inputDate.leadingZero(xV);
	},

	getInputDateSecond: function(pId){
		var xId = pId.parent();
		var xV = $(xId).children(".-second").val();
//		if (xV!=""){
//			if (dbsfaces.number.isNumber(xV)){
//				xV = parseInt(xV,10);
//				if (xV < 10){
//					xV = "0" + xV;
//				}
//			}else{
//				xV = "";
//			}
//		}
		return dbsfaces.inputDate.leadingZero(xV);
	},

	leadingZero: function(pValue){
		if (pValue != ""){
			if (dbsfaces.number.isNumber(pValue)){
				pValue = parseInt(pValue,10);
				if (pValue < 10){
					pValue = "0" + pValue;
				}
			}else{
				pValue = "";
			}
		}
		return pValue;
	}
}

<commit_msg>habilitação do teclado númerico lateral<commit_after>dbs_inputDate = function(pId) {
	$(pId + " input").focusin(function(e){
		$(this).select();
	});

	$(pId + " > .-container > .dbs_input-data").focusin(function(){
		$(this).addClass("dbs_input-data-FOCUS");
	});

	$(pId + " > .-container > .dbs_input-data > .-day").focusout(function(){
		var xV = dbsfaces.inputDate.getInputDateDay($(this));
		$(this).val(xV);
	});
	$(pId + " > .-container > .dbs_input-data > .-month").focusout(function(){
		var xV = dbsfaces.inputDate.getInputDateMonth($(this));
		$(this).val(xV);
	});
	$(pId + " > .-container > .dbs_input-data > .-year").focusout(function(){
		var xV = dbsfaces.inputDate.getInputDateYear($(this));
		$(this).val(xV);
	});
	$(pId + " > .-container > .dbs_input-data > .-hour").focusout(function(){
		var xV = dbsfaces.inputDate.getInputDateHour($(this));
		$(this).val(xV);
	});
	$(pId + " > .-container > .dbs_input-data > .-minute").focusout(function(){
		var xV = dbsfaces.inputDate.getInputDateMinute($(this));
		$(this).val(xV);
	});
	$(pId + " > .-container > .dbs_input-data > .-second").focusout(function(){
		var xV = dbsfaces.inputDate.getInputDateSecond($(this));
		$(this).val(xV);
	});

	$(pId + " > .-container > .dbs_input-data").focusout(function(){
		$(this).removeClass("dbs_input-data-FOCUS");
		if (dbsfaces.inputDate.getIsValid($(this).parent())==""){
			$(this).addClass("-error");
		}else{
			$(this).removeClass("-error");
		}
	});

	$(pId + " > .-container > .dbs_input-data > input").keydown(function(e){
		var xC = "";
		//Ignora tecla se não for uma tecla válida para o campo de data
		if (!dbsfaces.inputDate.isValidKey(e)){
			e.preventDefault();
			return false;
		}

		//Ignora valor digitado se a data não for válida
		var xS = $(this).get(0).selectionEnd - $(this).get(0).selectionStart;
		var xV = String.fromCharCode(e.keyCode);
		if (xS == 0 &&
			dbsfaces.number.isNumber(String.fromCharCode(e.keyCode))){
			var xD = dbsfaces.inputDate.getInputDateDay($(this));
			var xM = dbsfaces.inputDate.getInputDateMonth($(this));
			var xY = dbsfaces.inputDate.getInputDateYear($(this));
			if ($(this).hasClass("-day")){
				xD = xD + xV;
			}else if ($(this).hasClass("-month")){
				xM = xM + xV;
			}
			var xDate = dbsfaces.date.isDate(xY, xM, xD, 0, 0, 0);
			if (xDate == "" && xD != ""  && xM != ""  && xY != ""){
				e.preventDefault();
				return;
			}
		}

		//Pula para o próximo campo de input
		if (e.keyCode == 9 &&
			!e.shiftKey){
			//Desabilitador até verificar se é bom ter está opção
			//$(this).parent().children("input").last().focusNextInputField();
			return;
		//puda para o próximo campo dento da data com a BARRA
		}else if (e.keyCode == 191){
			xC = $(this).nextAll("input:first");
			e.preventDefault();
			return;
		}
		//Se foi configurado um novo campo para receber o foco, pula para ele
		if (xC.length){
			e.preventDefault();
			xC.focus().select();
			return;
		}

		var xAdd = 0;
		//Adiciona data quando pressionado seta para cima
		if (e.keyCode == 38){
			xAdd = 1;
		//Subtrai data quando pressionado seta para baixo
		}else if (e.keyCode == 40){
			xAdd = -1;
		}
		if (xAdd != 0){
			if ($(this).hasClass("-day")){
				dbsfaces.inputDate.addDate($(this), "day", xAdd);
			}else if ($(this).hasClass("-month")){
				dbsfaces.inputDate.addDate($(this), "month", xAdd);
			}else if ($(this).hasClass("-year")){
				dbsfaces.inputDate.addDate($(this), "year", xAdd);
			}
		}
	});

	$(pId + " > .-container > .dbs_input-data > input").keyup(function(e){
		var xC = "";
		var xS = $(this).get(0).selectionEnd - $(this).get(0).selectionStart;
		//Pula para o próximo campo(mes ou ano) da data caso e campo atual esteja completo
		if (xS == 0 &&
			dbsfaces.number.isNumber(String.fromCharCode(e.keyCode))){
			var xL = $(this).val().length;
			//Se estiver completo com os dois digitos, pula
			if (xL == 2){
				var xC = $(this).nextAll("input:first");
			}
		}
		//Volta o campo quando digitado a seta para esquerda
		if (e.keyCode == 37 &&
			!e.shiftKey){
			xC = $(this).prevAll("input:first");
		//Avança para o próximo campo quando digitado a seta para direita
		}else if ((e.keyCode == 39  &&
				  !e.shiftKey) ||
				  e.which == 47){
			xC = $(this).nextAll("input:first");
		}
		//Se foi configurado um novo campo para receber o foco, pula para ele
		if (xC.length){
			e.preventDefault();
			xC.focus().select();
		}
	});
}

dbsfaces.inputDate = {
	isValidKey: function(e){
		if (e.altKey ||
			e.ctrlKey){
			return false;
		}
		if (e.keyCode == 9 ||
			e.keyCode == 8 ||
			e.keyCode == 13 ||
			e.keyCode == 37 ||
			e.keyCode == 38 ||
			e.keyCode == 39 ||
			e.keyCode == 40 ||
			e.keyCode == 47 ||
			e.keyCode == 191 ||
			e.keyCode == 110 ||
			(e.keyCode >= 96 && e.keyCode <= 105) ||
			(!e.shiftKey && dbsfaces.number.isNumber(String.fromCharCode(e.keyCode))) ){
			return true;
		}
		return false;
	},

	addDate: function(pId, pField, pAdd){
		var xId = pId.parent();
		var xD = parseInt(dbsfaces.inputDate.getInputDateDay(pId),10);
		var xM = parseInt(dbsfaces.inputDate.getInputDateMonth(pId),10);
		var xY = parseInt(dbsfaces.inputDate.getInputDateYear(pId),10);
		if (pField == "day"){
			xD = xD + pAdd;
		}else if (pField == "month"){
			xM = xM + pAdd;
		}else if (pField == "year"){
			xY = xY + pAdd;
		}
		var xDate = dbsfaces.date.isDate(xY, xM, xD, 0, 0, 0);
		if (xDate != ""){
			if (pField == "day"){
				$(xId).children(".-day").val(xD);
			}else if (pField == "month"){
				$(xId).children(".-month").val(xM);
			}else if (pField == "year"){
				$(xId).children(".-year").val(xY);
			}
		}
	},

	getInputDateValue: function(pId){
		var xId = $(pId).find(".dbs_input-data > .-day");
		var xD = dbsfaces.inputDate.getInputDateDay(xId);
		var xM = dbsfaces.inputDate.getInputDateMonth(xId);
		var xY = dbsfaces.inputDate.getInputDateYear(xId);
		var xDate = dbsfaces.date.isDate(xY, xM, xD, 0, 0, 0);
		return xDate;
	},

	getIsValid: function(pId){
		var xId = $(pId).find(".dbs_input-data > .-day");
		var xD = dbsfaces.inputDate.getInputDateDay(xId);
		var xM = dbsfaces.inputDate.getInputDateMonth(xId);
		var xY = dbsfaces.inputDate.getInputDateYear(xId);
		if (xD == "" &&
			xM == "" &&
			xY == ""){
			return true;
		}else{
			var xDate = dbsfaces.inputDate.getInputDateValue(pId);
			if (xDate == ""){
				return false;
			}else{
				return true;
			}
		}
	},

	getInputDateDay: function(pId){
		var xId = pId.parent();
		var xV = $(xId).children(".-day").val();
//		if (xV!=""){
//			if (dbsfaces.number.isNumber(xV)){
//				xV = parseInt(xV,10);
//				if (xV < 10){
//					xV = "0" + xV;
//				}
//			}else{
//				xV = "";
//			}
//		}
//		return xV;
		return dbsfaces.inputDate.leadingZero(xV);
	},

	getInputDateMonth: function(pId){
		var xId = pId.parent();
		var xV = $(xId).children(".-month").val();
//		if (xV!=""){
//			if (dbsfaces.number.isNumber(xV)){
//				xV = parseInt(xV,10);
//				if (xV < 10){
//					xV = "0" + xV;
//				}
//			}else{
//				xV = "";
//			}
//		}
//		return xV;
		return dbsfaces.inputDate.leadingZero(xV);
	},

	getInputDateYear: function(pId){
		var xId = pId.parent();
		var xV = $(xId).children(".-year").val();
		if (xV!=""){
			if (dbsfaces.number.isNumber(xV)){
				xV = parseInt(xV,10);
				if (xV < 70){
					xV = xV + 2000;
				}else if (xV < 100){
					xV = xV + 1900;
				}else if (xV < 1000){
					xV = xV + 2000;
				}
			}else{
				xV = "";
			}
		}
		return xV;
	},

	getInputDateHour: function(pId){
		var xId = pId.parent();
		var xV = $(xId).children(".-hour").val();
//		if (xV!=""){
//			if (dbsfaces.number.isNumber(xV)){
//				xV = parseInt(xV,10);
//				if (xV < 10){
//					xV = "0" + xV;
//				}
//			}else{
//				xV = "";
//			}
//		}
//		return xV;
		return dbsfaces.inputDate.leadingZero(xV);
	},

	getInputDateMinute: function(pId){
		var xId = pId.parent();
		var xV = $(xId).children(".-minute").val();
//		if (xV!=""){
//			if (dbsfaces.number.isNumber(xV)){
//				xV = parseInt(xV,10);
//				if (xV < 10){
//					xV = "0" + xV;
//				}
//			}else{
//				xV = "";
//			}
//		}
		return dbsfaces.inputDate.leadingZero(xV);
	},

	getInputDateSecond: function(pId){
		var xId = pId.parent();
		var xV = $(xId).children(".-second").val();
//		if (xV!=""){
//			if (dbsfaces.number.isNumber(xV)){
//				xV = parseInt(xV,10);
//				if (xV < 10){
//					xV = "0" + xV;
//				}
//			}else{
//				xV = "";
//			}
//		}
		return dbsfaces.inputDate.leadingZero(xV);
	},

	leadingZero: function(pValue){
		if (pValue != ""){
			if (dbsfaces.number.isNumber(pValue)){
				pValue = parseInt(pValue,10);
				if (pValue < 10){
					pValue = "0" + pValue;
				}
			}else{
				pValue = "";
			}
		}
		return pValue;
	}
}

<|endoftext|>


<commit_before>/*eslint no-undef: "error"*/
/*eslint-env node*/

// requires
const {database,
       secret}      = require('./config');
const express       = require('express');
const app           = express();
const mongoose      = require('mongoose');
const User          = require('./models/user');
const passport      = require('passport');

// mongodb database connection
mongoose.connect(database);

// middleware
app.use(require('body-parser').json());
app.use(require('body-parser')());
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('morgan')('dev'));
app.set('view engine', 'ejs');

// passport.js authorization
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

// settings
app.set('superSecret', secret);
app.use(require('express-session')({ secret: secret }));
app.use(passport.initialize());
app.use(passport.session());

// static files
app.use('/js', express.static(__dirname + '/views/assets/js'));
app.use('/css', express.static(__dirname + '/views/assets/css'));
app.use('/mde', express.static(__dirname + '/views/assets/simplemde/dist'));

// main routes
app.use('/notes', require('./routes/notes'));
app.use('/', require('./routes/primary'));

app.listen(8080);
console.log('8080 is the magic port! I hope.');<commit_msg>Fix path fetching<commit_after>/* eslint no-undef: "error" */
/* eslint-env node */

// requires
const {database,
       secret} = require('./config');
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const User = require('./models/user');
const passport = require('passport');
const path = require('path');

// mongodb database connection
mongoose.connect(database);

// middleware
app.use(require('body-parser').json());
app.use(require('body-parser')());
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('morgan')('dev'));
app.set('view engine', 'ejs');

// passport.js authorization
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

// settings
app.set('superSecret', secret);
app.use(require('express-session')({ secret: secret }));
app.use(passport.initialize());
app.use(passport.session());

// static files
app.use('/js', express.static(path.resolve(__dirname, '/views/assets/js')));
app.use('/css', express.static(path.resolve(__dirname, '/views/assets/css')));
app.use('/mde', express.static(path.resolve(__dirname, '/views/assets/simplemde/dist')));

// main routes
app.use('/notes', require('./routes/notes'));
app.use('/', require('./routes/primary'));

app.listen(8080);
console.log('8080 is the magic port! I hope.');
<|endoftext|>


<commit_before>/**
/*               M O D E L _ V I E W E R . J S
 * BRL-CAD
 *
 * Copyright (c) 1995-2013 United States Government as represented by
 * the U.S. Army Research Laboratory.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this file; see the file named COPYING for more
 * information.
 */

/** @file OGV/client/views/model_viewer.js
 * Renders model into modelViewer.html
 * Loads the model after the template has been rendered
 */

Template.modelViewer.rendered = function()
{
    console.log("rendered");
    model = this.data;
    modelName = model.name;

    init();
    animate();
}

/**
 * Initializes the model viewer
 */

function init()
{
    /**
     * Setting Up the scene:
     * Grabs the model-container div from template into a variable
     * named container, and sets up the scene
     */
    container = document.getElementById('model-container');
    camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
    camera.position.z = 500;

    scene = new THREE.Scene();

    /**
     * Light up the scene
     */

    ambient = new THREE.AmbientLight(0x555555);
    scene.add(ambient);
    directionalLight = new THREE.PointLight(0xaaaaaa);
    directionalLight.position = camera.position;
    scene.add(directionalLight);

    /** Axes */
    axes = new THREE.AxisHelper(10000);
    scene.add(axes);

    /** Grid */
    grid = new THREE.GridHelper(300, 10);
    scene.add(grid);

    /**
     * Loader Managerial tasks
     */

    manager = new THREE.LoadingManager();
    manager.onProgress = function(item, loaded, total)
    {
	console.log(item, loaded, total);
    };

    /**
     * Adds the model to the viewer aka loads OBJ files
     * using OBJ-Loader
     */

    loader = new THREE.OBJLoader(manager);

    /**
     * Adds material to the model, which hence controls
     * how the model shall look
     */

    loader.load( '/' + modelName, function(object) {
	var OBJMaterial = new THREE.MeshPhongMaterial({color: 0xeeeeee});
	object.traverse(function(child) {
	    if (child instanceof THREE.Mesh) {
		child.material  = OBJMaterial;
	   }
	});

	object.position.y = - 80;
	scene.add(object);
    });

    /**
     * Renders the model, using renderer and assigns size to it
     */

    renderer = window.WebGLRenderingContext ? new THREE.WebGLRenderer() : new THREE.CanvasRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setClearColor(0x555555, 1);
    container.appendChild(renderer.domElement);

    /**
     * orbitControls for zoom in/ zoom out and other basic controls
     */
    controls = new THREE.OrbitControls( camera, renderer.domElement );
    controls.addEventListener( 'change', animate );

    window.addEventListener( 'resize', onWindowResize, false );1

}

/**
 * when window resizes, the size of modelviewer needs to resize
 */
function onWindowResize()
{

    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize(window.innerWidth, window.innerHeight);

    render();
}

function render()
{
    renderer.render(scene, camera);
}

function animate()
{
    requestAnimationFrame( animate );
    render();

}

<commit_msg>added canvas renderer support<commit_after>/**
/*               M O D E L _ V I E W E R . J S
 * BRL-CAD
 *
 * Copyright (c) 1995-2013 United States Government as represented by
 * the U.S. Army Research Laboratory.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this file; see the file named COPYING for more
 * information.
 */

/** @file OGV/client/views/model_viewer.js
 * Renders model into modelViewer.html
 * Loads the model after the template has been rendered
 */

Template.modelViewer.rendered = function()
{
    console.log("rendered");
    model = this.data;
    modelName = model.name;

    init();
    animate();
}

/**
 * Initializes the model viewer
 */

function init()
{
    /**
     * Setting Up the scene:
     * Grabs the model-container div from template into a variable
     * named container, and sets up the scene
     */
    container = document.getElementById('model-container');
    camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
    camera.position.z = 500;

    scene = new THREE.Scene();

    /**
     * Light up the scene
     */

    ambient = new THREE.AmbientLight(0x555555);
    scene.add(ambient);
    directionalLight = new THREE.PointLight(0xaaaaaa);
    directionalLight.position = camera.position;
    scene.add(directionalLight);

    /** Axes */
    axes = new THREE.AxisHelper(10000);
    scene.add(axes);

    /** Grid */
    grid = new THREE.GridHelper(300, 10);
    scene.add(grid);

    /**
     * Loader Managerial tasks
     */

    manager = new THREE.LoadingManager();
    manager.onProgress = function(item, loaded, total)
    {
	console.log(item, loaded, total);
    };

    /**
     * Adds the model to the viewer aka loads OBJ files
     * using OBJ-Loader
     */

    loader = new THREE.OBJLoader(manager);

    /**
     * Adds material to the model, which hence controls
     * how the model shall look
     */

    loader.load( '/' + modelName, function(object) {
	var OBJMaterial = new THREE.MeshPhongMaterial({color: 0xeeeeee});
	object.traverse(function(child) {
	    if (child instanceof THREE.Mesh) {
		child.material  = OBJMaterial;
	   }
	});

	object.position.y = - 80;
	scene.add(object);
    });

    /**
     * If webgl is there then use it otherwise use canvas
     */
    if (Detector.webgl) {
	renderer = new THREE.WebGLRenderer({antialias:true});
    } else {
	renderer = new THREE.CanvasRenderer();
    }

    /**
     * Sets size and color to renderer
     */
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setClearColor(0x555555, 1);
    container.appendChild(renderer.domElement);

    /**
     * orbitControls for zoom in/ zoom out and other basic controls
     */
    controls = new THREE.OrbitControls(camera, renderer.domElement);
    controls.addEventListener('change', render);

    window.addEventListener('resize', onWindowResize, false);

}

/**
 * when window resizes, the size of modelviewer needs to resize
 */
function onWindowResize()
{

    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize(window.innerWidth, window.innerHeight);

    render();
}

function render()
{
    renderer.render(scene, camera);
}

function animate()
{
    requestAnimationFrame( animate );
    render();

}
<|endoftext|>