<commit_before>module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.l = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// identity function for calling harmony imports with the correct context
/******/ 	__webpack_require__.i = function(value) { return value; };

/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};

/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};

/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 7);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

/*
TODO: Make NN ugifly-mangler friendly. In order to do that, we need
to stop using the function.name attribute.

I think we can do that with one change: addNamespace needs to
change to take a name argument: @addNamespace: (name, namespace) ->
 */
var ArtStandardLibCore, Base, Neptune, isExtendedClass, isFunction, isPlainArray, ref,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

__webpack_require__(2);

__webpack_require__(1);

ref = __webpack_require__(5), isFunction = ref.isFunction, isPlainArray = ref.isPlainArray, isExtendedClass = ref.isExtendedClass;

ArtStandardLibCore = null;

Base = (function() {
  var excludedPropNames;

  function Base() {}

  Base.allNamespaces = {};

  Base.getAllNamespacePaths = function() {
    return Object.keys(Base.allNamespaces).sort();
  };

  Base.toString = function() {
    return this.namespacePath;
  };

  Base.inspect = function() {
    return this.namespacePath;
  };

  Base._name = "Base";

  Base.namespacePath = "Neptune.Base";

  Base.namespace = null;

  Base.namespaces = {};

  Base.modules = {};

  Base.getNamespacePath = function() {
    return this.namespacePath;
  };

  Base.getNamespaceNames = function() {
    return Object.keys(this.namespaces).sort();
  };

  Base.getModuleNames = function() {
    return Object.keys(this.modules).sort();
  };

  Base.getNeptuneLib = function() {
    return ArtStandardLibCore || (ArtStandardLibCore = __webpack_require__(4));
  };

  Base.getInspectedObjects = function(includeModules) {
    var name, namespace, obj;
    if (includeModules == null) {
      includeModules = true;
    }
    return (
      obj = {},
      obj["" + this.namespacePath] = this.getNeptuneLib().merge(this.version ? {
        version: this.version
      } : void 0, (function() {
        var ref1, results;
        ref1 = this.namespaces;
        results = [];
        for (name in ref1) {
          namespace = ref1[name];
          results.push(namespace.getInspectedObjects(includeModules));
        }
        return results;
      }).call(this), includeModules && this.getModuleNames().length > 0 ? {
        modules: this.getModuleNames().join(', ')
      } : void 0),
      obj
    );
  };

  Base.getVersions = function() {
    var key, out, recurse, ref1, subNamespace;
    out = {};
    if (this === Neptune) {
      out.version = this.version;
    }
    ref1 = this.namespaces;
    for (key in ref1) {
      subNamespace = ref1[key];
      if (0 < Object.keys(recurse = subNamespace.getVersions()).length) {
        out[key] = recurse;
      }
      if (subNamespace.version != null) {
        (out[key] || (out[key] = {})).version = subNamespace.version;
      }
    }
    return out;
  };

  Base.addNamespace = function(name, namespace) {
    return this.allNamespaces[namespace.namespacePath] = this.namespaces[name] = this[name] = namespace._init(name, this);
  };

  Base.addModules = function(map) {
    var modName, module, name;
    for (name in map) {
      module = map[name];
      this._setChildNamespaceProps(name, module);
      if (isExtendedClass(module) && name !== (modName = module.getName())) {
        console.warn("NN: module name (" + this.namespacePath + "." + name + ") does not match module.exports.getName(): " + modName);
      }
      if (!name.match(/^-/)) {
        this.modules[name] = this[name] = module;
      }
    }
    return this;
  };

  /*
  IN: any combination of objects or arrays
    object: all properties in the object are added to the namespace

    array: [fromObject, property names as one or more strings]
      for propName in every sub-string in args matching: /[0-9a-z_]+/ig
        @_addToNamespace propName, fromObject

      Each string is parsed to find everything that matches: /[0-9a-z_]+/ig
      All resulting property names are concated into a one list.
      Every property in fromObject that matches one of the property-names is added to the namespace.
   */

  Base.includeInNamespace = function() {
    var arg, args, fromObject, i, j, k, l, len, len1, propName, ref1, ref2, v;
    args = arguments.length === 1 && isPlainArray(arguments[0]) ? arguments[0] : arguments;
    for (j = 0, len = args.length; j < len; j++) {
      arg = args[j];
      if (arg) {
        if (isPlainArray(arg)) {
          fromObject = arg[0];
          for (i = k = 1, ref1 = arg.length; 1 <= ref1 ? k < ref1 : k > ref1; i = 1 <= ref1 ? ++k : --k) {
            ref2 = arg[i].match(/[0-9a-z_]+/ig);
            for (l = 0, len1 = ref2.length; l < len1; l++) {
              propName = ref2[l];
              this._addToNamespace(propName, fromObject);
            }
          }
        } else {
          for (propName in arg) {
            v = arg[propName];
            this._addToNamespace(propName, arg);
          }
        }
      }
    }
    return this;
  };

  /*
  Every child of a namespace gets these properties:

    namespace:      pointer to the parent namespace
    namespacePath:  string path from global to child

  NOTE: only modules which return a class or function
    get their namespace-props set.
   */

  Base._setChildNamespaceProps = function(name, child) {
    if (isFunction(child)) {
      if (isFunction(child["class"])) {
        this._setChildNamespaceProps(name, child["class"]);
      }
      child.namespace = this;
      return child.namespacePath = this.namespacePath + "." + name;
    }
  };

  /*
  CoffeeScript classes copy all class props when inheriting,
  but some props need to be unique to each instance. This
  function initializes those props.
   */

  Base._init = function(name, namespace1) {
    this.namespace = namespace1;
    this._name = name;
    this.modules = {};
    this.namespaces = {};
    this.namespace._setChildNamespaceProps(name, this);
    return this;
  };

  excludedPropNames = ["__super__"].concat(Object.keys(Base));

  /*
  Helper for includeInNamespace.
  Add anything to the namespace.

  IN:
    propName:   property name to  value will be assigned to in the namespace (string)
    addingFrom: object
      used for reporting errors if attempting to overwrite an
      existing item.

  EFFECT:
    Only adds value if @[propName] is not already set.
    Otherwise, reports error and continues.

  OUT: value
   */

  Base._addToNamespace = function(propName, addingFrom) {
    var addingFromString, value;
    if (propName === "inspect" && (value = addingFrom[propName]).length > 0) {
      return this[propName] = value;
    }
    if (indexOf.call(excludedPropNames, propName) >= 0) {
      return;
    }
    if (!(value = addingFrom[propName])) {
      return;
    }
    if (this[propName]) {
      if (this[propName] !== value) {
        addingFromString = addingFrom.namespacePath || addingFrom.propName || (Object.keys(addingFrom)).join(', ');
        console.error(this.namespacePath + " already has key: " + propName + ". Adding from: " + addingFromString);
      }
      return this[propName];
    } else {
      return this[propName] = value;
    }
  };

  return Base;

})();

module.exports = global.Neptune || (global.Neptune = Neptune = (function(superClass) {
  extend(Neptune, superClass);

  function Neptune() {
    return Neptune.__super__.constructor.apply(this, arguments);
  }

  Neptune.Base = Base;

  Neptune.namespacePath = "Neptune";

  Neptune.namespace = null;

  Neptune.isNamespace = function(klass) {
    return (klass != null ? klass.prototype : void 0) instanceof Base;
  };

  Neptune.isNode = __webpack_require__(6);

  Neptune.version = (__webpack_require__(3)).version;

  return Neptune;

})(Base));

Base.namespace = Neptune;

/***/ }),
/* 1 */
/***/ (function(module, exports) {

if ((function() {}).name == null) {
  Object.defineProperty(global.Function.prototype, 'name', {
    get: function() {
      var matches, name;
      name = (matches = this.toString().match(/^\s*function\s*([^\s(]+)/)) ? matches[1] : "";
      Object.defineProperty(this, 'name', {
        value: name
      });
      return name;
    }
  });
}

global.Function.prototype.getName = function() {
  return this._name || this.name || "anonymousFunction";
};

global.Function.prototype.hasName = function() {
  return !!(this._name || this.name);
};

/***/ }),
/* 2 */
/***/ (function(module, exports) {

var g;

g = typeof window !== "undefined" && window !== null ? window : typeof self !== "undefined" && self !== null ? self : global;

g.self || (g.self = g);

g.global || (g.global = g);

/***/ }),
/* 3 */
/***/ (function(module, exports) {

module.exports = {
	"author": "Shane Brinkman-Davis Delamore, Imikimi LLC",
	"bin": {
		"neptune-namespaces": "./nn",
		"nn": "./nn"
	},
	"dependencies": {
		"art-class-system": "^1.0.1",
		"art-standard-lib": "^1.1.0",
		"art-testbench": "^1.0.0",
		"case-sensitive-paths-webpack-plugin": "^1.1.4",
		"coffee-loader": "^0.7.2",
		"coffee-script": "^1.12.3",
		"colors": "^1.1.2",
		"commander": "^2.9.0",
		"css-loader": "^0.26.1",
		"detect-node": "^2.0.3",
		"fs-promise": "^1.0.0",
		"glob-promise": "^3.1.0",
		"json-loader": "^0.5.4",
		"neptune-namespaces": "^1.9.1",
		"script-loader": "^0.7.0",
		"style-loader": "^0.13.1",
		"webpack": "^2.2.1",
		"webpack-dev-server": "^2.3.0",
		"webpack-merge": "^3.0.0"
	},
	"description": "Generate index.coffee and namespace.coffee files from directory structures",
	"devDependencies": {
		"chai": "^3.5.0",
		"mocha": "^2.5.3"
	},
	"license": "ISC",
	"name": "neptune-namespaces",
	"scripts": {
		"build": "webpack --progress",
		"start": "webpack-dev-server --hot --inline --progress",
		"test": "nn -s;mocha -u tdd --compilers coffee:coffee-script/register"
	},
	"version": "1.10.3"
};

/***/ }),
/* 4 */
/***/ (function(module, exports) {

module.exports = require("art-standard-lib/Core");

/***/ }),
/* 5 */
/***/ (function(module, exports) {

module.exports = require("art-standard-lib/Types");

/***/ }),
/* 6 */
/***/ (function(module, exports) {

module.exports = require("detect-node");

/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(0);

/***/ })
/******/ ]);<commit_msg>BUILD<commit_after>module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.l = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// identity function for calling harmony imports with the correct context
/******/ 	__webpack_require__.i = function(value) { return value; };

/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};

/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};

/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 7);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

/*
TODO: Make NN ugifly-mangler friendly. In order to do that, we need
to stop using the function.name attribute.

I think we can do that with one change: addNamespace needs to
change to take a name argument: @addNamespace: (name, namespace) ->
 */
var ArtStandardLibCore, Base, Neptune, isExtendedClass, isFunction, isPlainArray, ref,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

__webpack_require__(2);

__webpack_require__(1);

ref = __webpack_require__(5), isFunction = ref.isFunction, isPlainArray = ref.isPlainArray, isExtendedClass = ref.isExtendedClass;

ArtStandardLibCore = null;

Base = (function() {
  var excludedPropNames;

  function Base() {}

  Base.allNamespaces = {};

  Base.getAllNamespacePaths = function() {
    return Object.keys(Base.allNamespaces).sort();
  };

  Base.toString = function() {
    return this.namespacePath;
  };

  Base.inspect = function() {
    return this.namespacePath;
  };

  Base._name = "Base";

  Base.namespacePath = "Neptune.Base";

  Base.namespace = null;

  Base.namespaces = {};

  Base.modules = {};

  Base.getNamespacePath = function() {
    return this.namespacePath;
  };

  Base.getNamespaceNames = function() {
    return Object.keys(this.namespaces).sort();
  };

  Base.getModuleNames = function() {
    return Object.keys(this.modules).sort();
  };

  Base.getNeptuneLib = function() {
    return ArtStandardLibCore || (ArtStandardLibCore = __webpack_require__(4));
  };

  Base.getInspectedObjects = function(includeModules) {
    var name, namespace, obj;
    if (includeModules == null) {
      includeModules = true;
    }
    return (
      obj = {},
      obj["" + this.namespacePath] = this.getNeptuneLib().merge(this.version ? {
        version: this.version
      } : void 0, (function() {
        var ref1, results;
        ref1 = this.namespaces;
        results = [];
        for (name in ref1) {
          namespace = ref1[name];
          results.push(namespace.getInspectedObjects(includeModules));
        }
        return results;
      }).call(this), includeModules && this.getModuleNames().length > 0 ? {
        modules: this.getModuleNames().join(', ')
      } : void 0),
      obj
    );
  };

  Base.getVersions = function() {
    var key, out, recurse, ref1, subNamespace;
    out = {};
    if (this === Neptune) {
      out.version = this.version;
    }
    ref1 = this.namespaces;
    for (key in ref1) {
      subNamespace = ref1[key];
      if (0 < Object.keys(recurse = subNamespace.getVersions()).length) {
        out[key] = recurse;
      }
      if (subNamespace.version != null) {
        (out[key] || (out[key] = {})).version = subNamespace.version;
      }
    }
    return out;
  };

  Base.addNamespace = function(name, namespace) {
    return this.allNamespaces[namespace.namespacePath] = this.namespaces[name] = this[name] = namespace._init(name, this);
  };

  Base.addModules = function(map) {
    var modName, module, name;
    for (name in map) {
      module = map[name];
      this._setChildNamespaceProps(name, module);
      if (isExtendedClass(module) && name !== (modName = module.getName())) {
        console.warn("NN: module name (" + this.namespacePath + "." + name + ") does not match module.exports.getName(): " + modName);
      }
      if (!name.match(/^-/)) {
        this.modules[name] = this[name] = module;
      }
    }
    return this;
  };

  /*
  IN: any combination of objects or arrays
    object: all properties in the object are added to the namespace

    array: [fromObject, property names as one or more strings]
      for propName in every sub-string in args matching: /[0-9a-z_]+/ig
        @_addToNamespace propName, fromObject

      Each string is parsed to find everything that matches: /[0-9a-z_]+/ig
      All resulting property names are concated into a one list.
      Every property in fromObject that matches one of the property-names is added to the namespace.
   */

  Base.includeInNamespace = function() {
    var arg, args, fromObject, i, j, k, l, len, len1, propName, ref1, ref2, v;
    args = arguments.length === 1 && isPlainArray(arguments[0]) ? arguments[0] : arguments;
    for (j = 0, len = args.length; j < len; j++) {
      arg = args[j];
      if (arg) {
        if (isPlainArray(arg)) {
          fromObject = arg[0];
          for (i = k = 1, ref1 = arg.length; 1 <= ref1 ? k < ref1 : k > ref1; i = 1 <= ref1 ? ++k : --k) {
            ref2 = arg[i].match(/[0-9a-z_]+/ig);
            for (l = 0, len1 = ref2.length; l < len1; l++) {
              propName = ref2[l];
              this._addToNamespace(propName, fromObject);
            }
          }
        } else {
          for (propName in arg) {
            v = arg[propName];
            this._addToNamespace(propName, arg);
          }
        }
      }
    }
    return this;
  };

  /*
  Every child of a namespace gets these properties:

    namespace:      pointer to the parent namespace
    namespacePath:  string path from global to child

  NOTE: only modules which return a class or function
    get their namespace-props set.
   */

  Base._setChildNamespaceProps = function(name, child) {
    if (isFunction(child)) {
      if (isFunction(child["class"])) {
        this._setChildNamespaceProps(name, child["class"]);
      }
      child.namespace = this;
      return child.namespacePath = this.namespacePath + "." + name;
    }
  };

  /*
  CoffeeScript classes copy all class props when inheriting,
  but some props need to be unique to each instance. This
  function initializes those props.
   */

  Base._init = function(name, namespace1) {
    this.namespace = namespace1;
    this._name = name;
    this.modules = {};
    this.namespaces = {};
    this.namespace._setChildNamespaceProps(name, this);
    return this;
  };

  excludedPropNames = ["__super__"].concat(Object.keys(Base));

  /*
  Helper for includeInNamespace.
  Add anything to the namespace.

  IN:
    propName:   property name to  value will be assigned to in the namespace (string)
    addingFrom: object
      used for reporting errors if attempting to overwrite an
      existing item.

  EFFECT:
    Only adds value if @[propName] is not already set.
    Otherwise, reports error and continues.

  OUT: value
   */

  Base._addToNamespace = function(propName, addingFrom) {
    var addingFromString, value;
    if (propName === "inspect" && (value = addingFrom[propName]).length > 0) {
      return this[propName] = value;
    }
    if (indexOf.call(excludedPropNames, propName) >= 0) {
      return;
    }
    if (!(value = addingFrom[propName])) {
      return;
    }
    if (this[propName]) {
      if (this[propName] !== value) {
        addingFromString = addingFrom.namespacePath || addingFrom.propName || (Object.keys(addingFrom)).join(', ');
        console.error(this.namespacePath + " already has key: " + propName + ". Adding from: " + addingFromString);
      }
      return this[propName];
    } else {
      return this[propName] = value;
    }
  };

  return Base;

})();

module.exports = global.Neptune || (global.Neptune = Neptune = (function(superClass) {
  extend(Neptune, superClass);

  function Neptune() {
    return Neptune.__super__.constructor.apply(this, arguments);
  }

  Neptune.Base = Base;

  Neptune.namespacePath = "Neptune";

  Neptune.namespace = null;

  Neptune.isNamespace = function(klass) {
    return (klass != null ? klass.prototype : void 0) instanceof Base;
  };

  Neptune.isNode = __webpack_require__(6);

  Neptune.version = (__webpack_require__(3)).version;

  return Neptune;

})(Base));

Base.namespace = Neptune;

/***/ }),
/* 1 */
/***/ (function(module, exports) {

if ((function() {}).name == null) {
  Object.defineProperty(global.Function.prototype, 'name', {
    get: function() {
      var matches, name;
      name = (matches = this.toString().match(/^\s*function\s*([^\s(]+)/)) ? matches[1] : "";
      Object.defineProperty(this, 'name', {
        value: name
      });
      return name;
    }
  });
}

global.Function.prototype.getName = function() {
  return this._name || this.name || "anonymousFunction";
};

global.Function.prototype.hasName = function() {
  return !!(this._name || this.name);
};

/***/ }),
/* 2 */
/***/ (function(module, exports) {

var g;

g = typeof window !== "undefined" && window !== null ? window : typeof self !== "undefined" && self !== null ? self : global;

g.self || (g.self = g);

g.global || (g.global = g);

/***/ }),
/* 3 */
/***/ (function(module, exports) {

module.exports = {
	"author": "Shane Brinkman-Davis Delamore, Imikimi LLC",
	"bin": {
		"neptune-namespaces": "./nn",
		"nn": "./nn"
	},
	"dependencies": {
		"art-class-system": "^1.0.1",
		"art-standard-lib": "^1.1.0",
		"art-testbench": "^1.0.0",
		"case-sensitive-paths-webpack-plugin": "^1.1.4",
		"coffee-loader": "^0.7.2",
		"coffee-script": "^1.12.3",
		"colors": "^1.1.2",
		"commander": "^2.9.0",
		"css-loader": "^0.26.1",
		"detect-node": "^2.0.3",
		"fs-promise": "^1.0.0",
		"glob-promise": "^3.1.0",
		"json-loader": "^0.5.4",
		"neptune-namespaces": "^1.9.1",
		"script-loader": "^0.7.0",
		"style-loader": "^0.13.1",
		"webpack": "^2.2.1",
		"webpack-dev-server": "^2.3.0",
		"webpack-merge": "^3.0.0"
	},
	"description": "Generate index.coffee and namespace.coffee files from directory structures",
	"devDependencies": {
		"chai": "^3.5.0",
		"mocha": "^2.5.3"
	},
	"license": "ISC",
	"name": "neptune-namespaces",
	"scripts": {
		"build": "webpack --progress",
		"start": "webpack-dev-server --hot --inline --progress",
		"test": "nn -s;mocha -u tdd --compilers coffee:coffee-script/register"
	},
	"version": "2.0.0"
};

/***/ }),
/* 4 */
/***/ (function(module, exports) {

module.exports = require("art-standard-lib/Core");

/***/ }),
/* 5 */
/***/ (function(module, exports) {

module.exports = require("art-standard-lib/Types");

/***/ }),
/* 6 */
/***/ (function(module, exports) {

module.exports = require("detect-node");

/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(0);

/***/ })
/******/ ]);<|endoftext|>


<commit_before>/* The following line (global) is for JSLint */
/*global console, document, DetectFlashVer, GetSwfVer, ResistorActivity */

/*
 * Common initial setup for SPARKS activities
 */

// Create a dummy console.log when not run in Firebug
if (typeof console == 'undefined') {
    var console = { log: function() {} };
    //var console = { log: alert };
}
var debug = function(x) { console.log(x); };

// Setup a global namespace to store page variables
jQuery.sparks = {};

// Parse the page params so things can be customized
var value = null;

value = jQuery.url.param("model_height");
console.log('value=' + value);
jQuery.sparks.modelHeight = value != undefined ? value : '635';

jQuery.sparks.debug = jQuery.url.param("debug") != undefined;
jQuery.sparks.debug_mode = jQuery.url.param("debug_mode");

$(document).ready(function() {
    //checkFlashVersion();

    // In some cases (e.g. IE) Flash is loaded before document ready,
    // making initActivity() fail because activity isn't set up.
    // So for now creating activity in initActivity

    //jQuery.sparks.activity = new ResistorActivity();
    //jQuery.sparks.activity.initDocument();
});

/*
 * This function gets called from Flash after Flash has set up the external
 * interface. Therefore all code that sends messages to Flash should be
 * initiated from this function.
 */
function initActivity() {
//function onFlashLoad() {
    console.log('ENTER initActivity');

    var activity = new ResistorActivity();
    activity.initDocument();
    activity.onFlashDone();

    var dataService = new RestDS(null, null, '/sparks_models/');
    activity.setDataService(dataService);

    jQuery.sparks.activity = activity;
}

function checkFlashVersion() {
    var major = 10;
    var minor = 0;
    var revision = 31;

    if (!DetectFlashVer(10, 0, 33)) {
        var msg = 'This activity requires Flash version ';
        msg += major + '.' + minor + '.' + revision + '. ';

        $('body').html('
' + msg + '
');
    }
    document.write('
Flash version: ' + GetSwfVer() + '
');
}

<commit_msg>RestDS checks for session cookie 'put_path'<commit_after>/* The following line (global) is for JSLint */
/*global console, document, DetectFlashVer, GetSwfVer, ResistorActivity */

/*
 * Common initial setup for SPARKS activities
 */

// Create a dummy console.log when not run in Firebug
if (typeof console == 'undefined') {
    var console = { log: function() {} };
    //var console = { log: alert };
}
var debug = function(x) { console.log(x); };

// Setup a global namespace to store page variables
jQuery.sparks = {};

// Parse the page params so things can be customized
var value = null;

value = jQuery.url.param("model_height");
console.log('value=' + value);
jQuery.sparks.modelHeight = value != undefined ? value : '635';

jQuery.sparks.debug = jQuery.url.param("debug") != undefined;
jQuery.sparks.debug_mode = jQuery.url.param("debug_mode");

$(document).ready(function() {
    //checkFlashVersion();

    // In some cases (e.g. IE) Flash is loaded before document ready,
    // making initActivity() fail because activity isn't set up.
    // So for now creating activity in initActivity

    //jQuery.sparks.activity = new ResistorActivity();
    //jQuery.sparks.activity.initDocument();
});

/*
 * This function gets called from Flash after Flash has set up the external
 * interface. Therefore all code that sends messages to Flash should be
 * initiated from this function.
 */
function initActivity() {
//function onFlashLoad() {
    console.log('ENTER initActivity');

    var activity = new ResistorActivity();
    activity.initDocument();
    activity.onFlashDone();

    var put_path = readCookie('put_path') ||  '/sparks_models/';
    var dataService = new RestDS(null, null, put_path);
    activity.setDataService(dataService);

    jQuery.sparks.activity = activity;
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function checkFlashVersion() {
    var major = 10;
    var minor = 0;
    var revision = 31;

    if (!DetectFlashVer(10, 0, 33)) {
        var msg = 'This activity requires Flash version ';
        msg += major + '.' + minor + '.' + revision + '. ';

        $('body').html('
' + msg + '
');
    }
    document.write('
Flash version: ' + GetSwfVer() + '
');
}

<|endoftext|>


<commit_before>(function($) {
  $.widget('pageflow.page', {
    _create: function() {
      this.configuration = this.element.data('configuration') || this.options.configuration;
      this.index = this.options.index;

      this.element.addClass(this.configuration.transition || "fade");

      this.preloaded = false;
      this.reinit();
    },

    reinit: function() {
      this.pageType = pageflow.pageType.get(this.element.data('template'));
      this.element.data('pageType', this.pageType);

      this.content = this.element.find('.scroller');
      this.content.scroller();
      this.content.hideTextOnSwipe();

      this._triggerPageTypeHook('enhance');
    },

    reactivate: function() {
      if (this.element.hasClass('active')) {
        this.content.scroller('enable');
        this.content.scroller('resetPosition');
        this.content.scroller('afterAnimationHook');

        this._triggerPageTypeHook('activating');
        this._triggerDelayedPageTypeHook('activated');
      }
    },

    cleanup: function() {
      this._triggerPageTypeHook('deactivating');
      this._triggerDelayedPageTypeHook('deactivated');
    },

    refreshScroller: function() {
      this.content.scroller('refresh');
    },

    resize: function() {
      this._triggerPageTypeHook('resize');
    },

    activateAsLandingPage: function() {
      this.element.addClass('active');

      this.content.scroller('enable');
      this.content.scroller('resetPosition');
      this.content.scroller('afterAnimationHook');

      this._trigger('activate', null, {page: this});
      this._triggerPageTypeHook('activating');
      this._triggerDelayedPageTypeHook('activated');

      this.prepareTimeout = setTimeout(_.bind(this.triggerPrepareNextPage, this), this.prepareNextPageTimeout());
    },

    prepare: function() {
      this._triggerPageTypeHook('prepare');
    },

    prepareNextPageTimeout: function() {
      return this.pageType.prepareNextPageTimeout;
    },

    preload: function() {
      var page = this;

      if (!this.preloaded) {
        this.preloaded = true;

        return $.when(this._triggerPageTypeHook('preload')).then(function() {
          page._trigger('preloaded');
        });
      }
    },

    activate: function(options) {
      options = options || {};

      this.element
        .removeClass('animate-out-forwards animate-out-backwards')
        .addClass('animate-in-' + options.direction);

      setTimeout(_.bind(function() {
        this.element.addClass('active');
      }, this), 5);

      setTimeout(_.bind(function() {
        this.content.scroller('enable');
        this.content.scroller('afterAnimationHook');
        this.element.removeClass('animate-in-forwards animate-in-backwards');

        this._triggerDelayedPageTypeHook('activated');
      }, this), 1100);

      this.content.scroller('resetPosition', {position: options.position});
      this._trigger('activate', null, {page: this});
      this._triggerPageTypeHook('activating');

      this.prepareTimeout = setTimeout(_.bind(this.triggerPrepareNextPage, this), this.prepareNextPageTimeout());
    },

    deactivate: function(options) {
      this.element
        .removeClass('active animate-in-forwards animate-in-backwards')
        .addClass('animate-out-' + options.direction);

      setTimeout(_.bind(function() {
        this.element.removeClass('animate-out-forwards animate-out-backwards');
        this._triggerPageTypeHook('deactivated');
      }, this), 1100);

      this.content.scroller('disable');
      this._trigger('deactivate');
      this._triggerPageTypeHook('deactivating');

      clearTimeout(this.prepareTimeout);
    },

    _triggerDelayedPageTypeHook: function(name) {
      var that = this;
      var handle = pageflow.manualStart.wait(function() {
        that._triggerPageTypeHook(name);
      });

      this.element.one('deactivate', function() {
        handle.cancel();
      });
    },

    _triggerPageTypeHook: function(name) {
      return this.pageType[name](this.element, this.configuration);
    },

    triggerPrepareNextPage: function() {
      if($(this.element).next(".page").length > 0) {
        $(this.element).next(".page").page('prepare', {});
      }
    }
  });
}(jQuery));<commit_msg>Add configuration Method to Page jQuery Widget<commit_after>(function($) {
  $.widget('pageflow.page', {
    _create: function() {
      this.configuration = this.element.data('configuration') || this.options.configuration;
      this.index = this.options.index;

      this.element.addClass(this.configuration.transition || "fade");

      this.preloaded = false;
      this.reinit();
    },

    getConfiguration: function() {
      return this.configuration;
    },

    reinit: function() {
      this.pageType = pageflow.pageType.get(this.element.data('template'));
      this.element.data('pageType', this.pageType);

      this.content = this.element.find('.scroller');
      this.content.scroller();
      this.content.hideTextOnSwipe();

      this._triggerPageTypeHook('enhance');
    },

    reactivate: function() {
      if (this.element.hasClass('active')) {
        this.content.scroller('enable');
        this.content.scroller('resetPosition');
        this.content.scroller('afterAnimationHook');

        this._triggerPageTypeHook('activating');
        this._triggerDelayedPageTypeHook('activated');
      }
    },

    cleanup: function() {
      this._triggerPageTypeHook('deactivating');
      this._triggerDelayedPageTypeHook('deactivated');
    },

    refreshScroller: function() {
      this.content.scroller('refresh');
    },

    resize: function() {
      this._triggerPageTypeHook('resize');
    },

    activateAsLandingPage: function() {
      this.element.addClass('active');

      this.content.scroller('enable');
      this.content.scroller('resetPosition');
      this.content.scroller('afterAnimationHook');

      this._trigger('activate', null, {page: this});
      this._triggerPageTypeHook('activating');
      this._triggerDelayedPageTypeHook('activated');

      this.prepareTimeout = setTimeout(_.bind(this.triggerPrepareNextPage, this), this.prepareNextPageTimeout());
    },

    prepare: function() {
      this._triggerPageTypeHook('prepare');
    },

    prepareNextPageTimeout: function() {
      return this.pageType.prepareNextPageTimeout;
    },

    preload: function() {
      var page = this;

      if (!this.preloaded) {
        this.preloaded = true;

        return $.when(this._triggerPageTypeHook('preload')).then(function() {
          page._trigger('preloaded');
        });
      }
    },

    activate: function(options) {
      options = options || {};

      this.element
        .removeClass('animate-out-forwards animate-out-backwards')
        .addClass('animate-in-' + options.direction);

      setTimeout(_.bind(function() {
        this.element.addClass('active');
      }, this), 5);

      setTimeout(_.bind(function() {
        this.content.scroller('enable');
        this.content.scroller('afterAnimationHook');
        this.element.removeClass('animate-in-forwards animate-in-backwards');

        this._triggerDelayedPageTypeHook('activated');
      }, this), 1100);

      this.content.scroller('resetPosition', {position: options.position});
      this._trigger('activate', null, {page: this});
      this._triggerPageTypeHook('activating');

      this.prepareTimeout = setTimeout(_.bind(this.triggerPrepareNextPage, this), this.prepareNextPageTimeout());
    },

    deactivate: function(options) {
      this.element
        .removeClass('active animate-in-forwards animate-in-backwards')
        .addClass('animate-out-' + options.direction);

      setTimeout(_.bind(function() {
        this.element.removeClass('animate-out-forwards animate-out-backwards');
        this._triggerPageTypeHook('deactivated');
      }, this), 1100);

      this.content.scroller('disable');
      this._trigger('deactivate');
      this._triggerPageTypeHook('deactivating');

      clearTimeout(this.prepareTimeout);
    },

    _triggerDelayedPageTypeHook: function(name) {
      var that = this;
      var handle = pageflow.manualStart.wait(function() {
        that._triggerPageTypeHook(name);
      });

      this.element.one('deactivate', function() {
        handle.cancel();
      });
    },

    _triggerPageTypeHook: function(name) {
      return this.pageType[name](this.element, this.configuration);
    },

    triggerPrepareNextPage: function() {
      if($(this.element).next(".page").length > 0) {
        $(this.element).next(".page").page('prepare', {});
      }
    }
  });
}(jQuery));<|endoftext|>


<commit_before>var quantum = require('quantum-js')
var html = require('quantum-html')
var api = require('quantum-api')
var version = require('quantum-version')
var template = require('quantum-template')
var changelog = require('quantum-changelog')

var hexagon = require('hexagon-js')

var Promise = require('bluebird')
var path = require('path')
var fs = Promise.promisifyAll(require('fs-extra'))
var util = require('./util')
var versions = require('../content/versions.json')
var latestVersion = versions[versions.length - 1]

var glob = Promise.promisify(require('glob'))
var Progress = require('progress')
var chalk = require('chalk')
var watch = require('quantum-watch')
var flatten = require('flatten')
var liveServer = require('live-server')

try {
  var privateConfig = require('../config.json')
} catch (e) {
  var privateConfig = {}
}

function buildMetaData () {
  var modules = util.moduleList().then(function (moduleNames) {
    var res = {}
    return Promise.all(moduleNames.map(function (moduleName) {
      return fs.readJsonAsync(path.join(util.toModuleDir(moduleName), 'module.json'))
        .then(function (meta) {
          res[moduleName] = meta
        })
    })).then(function () {
      return res
    })
  })

  return fs.readJsonAsync(path.join(util.root, 'content', 'versions.json'))
    .then(function (versions) {
      return Promise.props({
        versions: versions,
        latest: versions[versions.length - 1],
        modules: modules
      })
    }).then(function (meta) {
    return fs.writeJsonAsync(path.join('target', 'meta.json'), meta)
  })

}

function createBuilds () {
  // create the dx-prefixed and hx-prefixed builds for the latest version of hexagon
  var buildList = [
    { dest: 'target/resources/hexagon/' + latestVersion, embedAssets: true },
    { dest: 'target/resources/hexagon/docs', prefix: 'dx', embedAssets: true }
  ]
  return progressSequence('Building Hexagon', chalk.cyan('='), buildList, function (opts) { return hexagon.build(opts) })
}

function buildHexagon (force) { // XXX: do this in the postinstall npm script
  if (force) return createBuilds()
  return fs.accessAsync('target/resources/hexagon/' + latestVersion + '/hexagon.css', fs.F_OK)
    .then(function () {
      console.log(chalk.cyan('Skipping Hexagon Build (Already Exists)'))
    })
    // Hexagon build doesn't already exist
    .catch(createBuilds)
}

// copies the static resources to the target directory
function copyResources () {
  return Promise.all([
    fs.copyAsync('node_modules/font-awesome/css/', 'target/resources/font-awesome/css/'),
    fs.copyAsync('node_modules/font-awesome/fonts/', 'target/resources/font-awesome/fonts/'),
    fs.copyAsync('content/resources/', 'target/resources/'),
    fs.copyAsync('server/', 'target/')
  ])
}

function getTemplateVariables () {
  return Promise.props({
    version: latestVersion,
    versionList: fs.readJsonAsync(path.join(util.root, 'content/versions.json')),
    modules: util.moduleList()
  })
}

function progressSequence (desc, completeStyle, list, func) {
  var bar = new Progress(desc + ' :current/:total [:bar] :percent :etas', { total: list.length, width: 50, complete: completeStyle})
  bar.tick(0)
  return Promise.all(list)
    .map(function (f) {
      return func(f)
        .then(function (res) {
          bar.tick()
          return res
        })
    }, {concurrency: 5})
}

function getOptions () {
  function filenameModifier (filename, version) {
    var baseName = path.basename(filename)
    var moduleName = path.basename(path.dirname(filename))
    return path.join('docs', version, moduleName, baseName)
  }

  var apiOptions = util.moduleList().then(function (modules) {
    var types = {
      'Array': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array',
      'Boolean': 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean',
      'Date': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date',
      'Element': 'https://developer.mozilla.org/en/docs/Web/API/Element',
      'Function': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function',
      'HTMLElement': 'https://developer.mozilla.org/en/docs/Web/API/HTMLElement',
      'Node': 'https://developer.mozilla.org/en/docs/Web/API/Node',
      'Number': 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number',
      'Object': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object',
      'String': 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String',
      'SVGElement': 'https://developer.mozilla.org/en/docs/Web/API/SVGElement'
    }

    modules.forEach(function (moduleId) {
      var moduleType = moduleId.split('-').map(function (part) {
        return part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()
      }).join('')
      types[moduleType] = '../' + moduleId
    })

    return {
      types: types
    }
  })

  var changelogOptions = {
    targetVersions: versions,
    milestoneUrl: privateConfig.milestoneUrl || 'https://github.com/ocadotechnology/hexagonjs/milestones/',
    issueUrl: privateConfig.issueUrl || 'https://github.com/ocadotechnology/hexagonjs/issues/'
  }

  var versionOptions = {
    filenameModifier: filenameModifier,
    versions: versions,
    unmergable: ['examples', 'description', 'extra'],
    taggable: ['prototype', 'constructor', 'function', 'method', 'property', 'returns', 'class', 'extraclass', 'childclass']
  }

  var htmlTransforms = Promise.props({
    html: html.transforms,
    api: apiOptions.then(api),
    changelog: changelog(changelogOptions).transforms,
    docs: require('../transforms/transforms')
  })

  return Promise.props({
    changelogOptions: changelogOptions,
    versionOptions: versionOptions,
    htmlTransforms: htmlTransforms
  })
}

function buildPages () {
  return watch('content/pages/**/index.um', { base: 'content/pages'}, function (objs) {
    var start = Date.now()
    return Promise.all([getTemplateVariables(), getOptions()]).spread(function (templateVariables, options) {
      return progressSequence('Building pages', chalk.green('='), objs, function (obj) {
        return Promise.resolve(obj)
          .then(template({variables: options.templateVariables}))
          .then(changelog(options.changelogOptions))
          .then(version(options.versionOptions))
          .then(function (res) { return Array.isArray(res) ? res : [res] })
          .then(flatten)
          .map(function (file) {
            if (file.filename.indexOf('modules') > -1) {
              file.filename = file.filename.replace('modules', 'docs')
            }
            return file
          })
          .map(html(options.htmlTransforms))
          .map(html.stringify())
          .map(function (file) {
            if (file.filename.indexOf('docs') === 0) {
              var v = file.filename.split('/')[1]
              file.content = file.content.split('__version__').join(v)
            }
            return file
          })
          .map(quantum.write('target'))
      })
    }).then(function () {
      var diff = (Date.now() - start)
      var mins = (diff - diff % 60000) / 60000
      var sec = (diff - (diff - diff % 60000)) / 1000
      console.log(chalk.blue('Done!', mins + 'm', sec + 's'))
    })
  })
    .then(function (fun) {
      return fun()
    })

}

function startServer () {
  liveServer.start({
    port: 9000,
    root: 'target',
    wait: 50,
    open: false
  })
}

if (process.argv[2] === 'build-hexagon') {
  buildHexagon(true)
} else {
  buildHexagon(false)
    .then(copyResources)
    .then(buildMetaData)
    .then(buildPages)
    .then(startServer)
}
<commit_msg>update template variables in build<commit_after>var quantum = require('quantum-js')
var html = require('quantum-html')
var api = require('quantum-api')
var version = require('quantum-version')
var template = require('quantum-template')
var changelog = require('quantum-changelog')

var hexagon = require('hexagon-js')

var Promise = require('bluebird')
var path = require('path')
var fs = Promise.promisifyAll(require('fs-extra'))
var util = require('./util')
var versions = require('../content/versions.json')
var latestVersion = versions[versions.length - 1]

var glob = Promise.promisify(require('glob'))
var Progress = require('progress')
var chalk = require('chalk')
var watch = require('quantum-watch')
var flatten = require('flatten')
var liveServer = require('live-server')

try {
  var privateConfig = require('../config.json')
} catch (e) {
  var privateConfig = {}
}

function buildMetaData () {
  var modules = util.moduleList().then(function (moduleNames) {
    var res = {}
    return Promise.all(moduleNames.map(function (moduleName) {
      return fs.readJsonAsync(path.join(util.toModuleDir(moduleName), 'module.json'))
        .then(function (meta) {
          res[moduleName] = meta
        })
    })).then(function () {
      return res
    })
  })

  return fs.readJsonAsync(path.join(util.root, 'content', 'versions.json'))
    .then(function (versions) {
      return Promise.props({
        versions: versions,
        latest: versions[versions.length - 1],
        modules: modules
      })
    }).then(function (meta) {
    return fs.writeJsonAsync(path.join('target', 'meta.json'), meta)
  })

}

function createBuilds () {
  // create the dx-prefixed and hx-prefixed builds for the latest version of hexagon
  var buildList = [
    { dest: 'target/resources/hexagon/' + latestVersion, embedAssets: true },
    { dest: 'target/resources/hexagon/docs', prefix: 'dx', embedAssets: true }
  ]
  return progressSequence('Building Hexagon', chalk.cyan('='), buildList, function (opts) { return hexagon.build(opts) })
}

function buildHexagon (force) { // XXX: do this in the postinstall npm script
  if (force) return createBuilds()
  return fs.accessAsync('target/resources/hexagon/' + latestVersion + '/hexagon.css', fs.F_OK)
    .then(function () {
      console.log(chalk.cyan('Skipping Hexagon Build (Already Exists)'))
    })
    // Hexagon build doesn't already exist
    .catch(createBuilds)
}

// copies the static resources to the target directory
function copyResources () {
  return Promise.all([
    fs.copyAsync('node_modules/font-awesome/css/', 'target/resources/font-awesome/css/'),
    fs.copyAsync('node_modules/font-awesome/fonts/', 'target/resources/font-awesome/fonts/'),
    fs.copyAsync('content/resources/', 'target/resources/'),
    fs.copyAsync('server/', 'target/')
  ])
}

function getTemplateVariables () {
  return Promise.props({
    version: latestVersion,
    versionList: fs.readJsonAsync(path.join(util.root, 'content/versions.json')),
    modules: util.moduleList()
  })
}

function progressSequence (desc, completeStyle, list, func) {
  var bar = new Progress(desc + ' :current/:total [:bar] :percent :etas', { total: list.length, width: 50, complete: completeStyle})
  bar.tick(0)
  return Promise.all(list)
    .map(function (f) {
      return func(f)
        .then(function (res) {
          bar.tick()
          return res
        })
    }, {concurrency: 5})
}

function getOptions () {
  function filenameModifier (filename, version) {
    var baseName = path.basename(filename)
    var moduleName = path.basename(path.dirname(filename))
    return path.join('docs', version, moduleName, baseName)
  }

  var apiOptions = util.moduleList().then(function (modules) {
    var types = {
      'Array': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array',
      'Boolean': 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean',
      'Date': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date',
      'Element': 'https://developer.mozilla.org/en/docs/Web/API/Element',
      'Function': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function',
      'HTMLElement': 'https://developer.mozilla.org/en/docs/Web/API/HTMLElement',
      'Node': 'https://developer.mozilla.org/en/docs/Web/API/Node',
      'Number': 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number',
      'Object': 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object',
      'String': 'https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String',
      'SVGElement': 'https://developer.mozilla.org/en/docs/Web/API/SVGElement'
    }

    modules.forEach(function (moduleId) {
      var moduleType = moduleId.split('-').map(function (part) {
        return part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()
      }).join('')
      types[moduleType] = '../' + moduleId
    })

    return {
      types: types
    }
  })

  var changelogOptions = {
    targetVersions: versions,
    milestoneUrl: privateConfig.milestoneUrl || 'https://github.com/ocadotechnology/hexagonjs/milestones/',
    issueUrl: privateConfig.issueUrl || 'https://github.com/ocadotechnology/hexagonjs/issues/'
  }

  var versionOptions = {
    filenameModifier: filenameModifier,
    versions: versions,
    unmergable: ['examples', 'description', 'extra'],
    taggable: ['prototype', 'constructor', 'function', 'method', 'property', 'returns', 'class', 'extraclass', 'childclass']
  }

  var htmlTransforms = Promise.props({
    html: html.transforms,
    api: apiOptions.then(api),
    changelog: changelog(changelogOptions).transforms,
    docs: require('../transforms/transforms')
  })

  return Promise.props({
    changelogOptions: changelogOptions,
    versionOptions: versionOptions,
    htmlTransforms: htmlTransforms
  })
}

function buildPages () {
  return watch('content/pages/**/index.um', { base: 'content/pages'}, function (objs) {
    var start = Date.now()
    return Promise.all([getTemplateVariables(), getOptions()]).spread(function (templateVariables, options) {
      return progressSequence('Building pages', chalk.green('='), objs, function (obj) {
        return Promise.resolve(obj)
          .then(template({variables: templateVariables}))
          .then(changelog(options.changelogOptions))
          .then(version(options.versionOptions))
          .then(function (res) { return Array.isArray(res) ? res : [res] })
          .then(flatten)
          .map(function (file) {
            if (file.filename.indexOf('modules') > -1) {
              file.filename = file.filename.replace('modules', 'docs')
            }
            return file
          })
          .map(html(options.htmlTransforms))
          .map(html.stringify())
          .map(function (file) {
            if (file.filename.indexOf('docs') === 0) {
              var v = file.filename.split('/')[1]
              file.content = file.content.split('__version__').join(v)
            }
            return file
          })
          .map(quantum.write('target'))
      })
    }).then(function () {
      var diff = (Date.now() - start)
      var mins = (diff - diff % 60000) / 60000
      var sec = (diff - (diff - diff % 60000)) / 1000
      console.log(chalk.blue('Done!', mins + 'm', sec + 's'))
    })
  })
    .then(function (fun) {
      return fun()
    })

}

function startServer () {
  liveServer.start({
    port: 9000,
    root: 'target',
    wait: 50,
    open: false
  })
}

if (process.argv[2] === 'build-hexagon') {
  buildHexagon(true)
} else {
  buildHexagon(false)
    .then(copyResources)
    .then(buildMetaData)
    .then(buildPages)
    .then(startServer)
}
<|endoftext|>


<commit_before>import _ from 'lodash';
import React from 'react';
import GenericLoader from '../components/GenericLoader';
import ExperimentalBanner from '../components/ExperimentalBanner';
import {apiFetchJson} from '../helpers/apiFetchJson';
import ProfileBarChart from '../student_profile/ProfileBarChart.js';
import * as Routes from '../helpers/Routes';

const style = {
  container: {
    margin: 30
  },
  studentRow: {
    marginBottom: 30,
  },
  profileBarChartStyles: {
    title: {
      fontSize: 20
    },
    container: {
      width: '100%',
      margin: '10px auto',
      position: 'relative'
    },
    chartHeight: 220,
  },
  a: {
    fontSize: 24
  }
};

class IsServiceWorking extends React.Component {

  constructor(props) {
    super(props);

    this.fetchIsServiceWorkingData = this.fetchIsServiceWorkingData.bind(this);
    this.renderPage = this.renderPage.bind(this);
  }

  render() {
    return (

        <ExperimentalBanner />
        <GenericLoader
          promiseFn={this.fetchIsServiceWorkingData}
          render={this.renderPage} />

    );
  }

  fetchIsServiceWorkingData() {
    const url = `/api/is_service_working_json`;
    return apiFetchJson(url);
  }

  renderPage(json) {
    return (

        {this.renderStudents(json)}

    );
  }

  renderServicePhaselines(services) {
    return services.map(function (service) {
      return { momentUTC: moment.utc(service.date_started), text: 'Started' };
    }, this);
  }

  renderStudents(json) {
    const chartData = json.chart_data;
    const sortedData = _.sortBy(chartData, (datum) => {
      return datum.services[0].date_started;
    }).reverse();

    return sortedData.map((datum) => {
      const student = datum.student;
      const services = datum.services;
      const servicePhaselines = this.renderServicePhaselines(services);

      return (

            {student.first_name} {student.last_name}

          <ProfileBarChart
            events={datum.absences}
            titleText="Absences"
            monthsBack={8}
            phaselines={servicePhaselines}
            hideBackToTop={true}
            styles={style.profileBarChartStyles} />

      );
    }, this);

  }

}

IsServiceWorking.propTypes = {
  serializedData: React.PropTypes.object.isRequired,
}

export default IsServiceWorking;
<commit_msg>Show earlier service start dates first<commit_after>import _ from 'lodash';
import React from 'react';
import GenericLoader from '../components/GenericLoader';
import ExperimentalBanner from '../components/ExperimentalBanner';
import {apiFetchJson} from '../helpers/apiFetchJson';
import ProfileBarChart from '../student_profile/ProfileBarChart.js';
import * as Routes from '../helpers/Routes';

const style = {
  container: {
    margin: 30
  },
  studentRow: {
    marginBottom: 30,
  },
  profileBarChartStyles: {
    title: {
      fontSize: 20
    },
    container: {
      width: '100%',
      margin: '10px auto',
      position: 'relative'
    },
    chartHeight: 220,
  },
  a: {
    fontSize: 24
  }
};

class IsServiceWorking extends React.Component {

  constructor(props) {
    super(props);

    this.fetchIsServiceWorkingData = this.fetchIsServiceWorkingData.bind(this);
    this.renderPage = this.renderPage.bind(this);
  }

  render() {
    return (

        <ExperimentalBanner />
        <GenericLoader
          promiseFn={this.fetchIsServiceWorkingData}
          render={this.renderPage} />

    );
  }

  fetchIsServiceWorkingData() {
    const url = `/api/is_service_working_json`;
    return apiFetchJson(url);
  }

  renderPage(json) {
    return (

        {this.renderStudents(json)}

    );
  }

  renderServicePhaselines(services) {
    return services.map(function (service) {
      return { momentUTC: moment.utc(service.date_started), text: 'Started' };
    }, this);
  }

  renderStudents(json) {
    const chartData = json.chart_data;
    const sortedData = _.sortBy(chartData, datum => {
      return datum.services[0].date_started;
    });

    return sortedData.map((datum) => {
      const student = datum.student;
      const services = datum.services;
      const servicePhaselines = this.renderServicePhaselines(services);

      return (

            {student.first_name} {student.last_name}

          <ProfileBarChart
            events={datum.absences}
            titleText="Absences"
            monthsBack={8}
            phaselines={servicePhaselines}
            hideBackToTop={true}
            styles={style.profileBarChartStyles} />

      );
    }, this);

  }

}

IsServiceWorking.propTypes = {
  serializedData: React.PropTypes.object.isRequired,
}

export default IsServiceWorking;
<|endoftext|>


<commit_before>import React from 'react';
import ProfileBarChart from '../student_profile/ProfileBarChart.js';

class IsServiceWorking extends React.Component {

  render() {
    return (

        {this.renderStudents()}

    );
  }

  renderStudents() {
    const {serializedData} = this.props;
    const chartData = serializedData.chartData;

    return chartData.map((datum) => {
      const student = datum.student;

      return (

{student.first_name} {student.last_name}

          <ProfileBarChart
            events={this.props.absences}
            titleText="Absences"
            monthsBack={48} />

      );
    });

  }

}

IsServiceWorking.propTypes = {
  serializedData: React.PropTypes.object.isRequired,
}

export default IsServiceWorking;
<commit_msg>We only want the past year-ish<commit_after>import React from 'react';
import ProfileBarChart from '../student_profile/ProfileBarChart.js';

class IsServiceWorking extends React.Component {

  render() {
    return (

        {this.renderStudents()}

    );
  }

  renderStudents() {
    const {serializedData} = this.props;
    const chartData = serializedData.chartData;

    return chartData.map((datum) => {
      const student = datum.student;

      return (

{student.first_name} {student.last_name}

          <ProfileBarChart
            events={this.props.absences}
            titleText="Absences"
            monthsBack={8} />

      );
    });

  }

}

IsServiceWorking.propTypes = {
  serializedData: React.PropTypes.object.isRequired,
}

export default IsServiceWorking;
<|endoftext|>


<commit_before>angular.module("OpenHq").factory('apiTokenInterceptor', function() {
    var myInterceptor = {
      request: function(request) {
        request.headers["Authorization"] = 'Token token="'+ window.apiToken +'"';
        return request;
      }
    };
    return myInterceptor;
})
.config(function($httpProvider) {
    $httpProvider.interceptors.push('apiTokenInterceptor');
});
<commit_msg>tweak<commit_after>angular.module("OpenHq").factory('apiTokenInterceptor', function() {
    return {
      request: function(request) {
        request.headers["Authorization"] = 'Token token="'+ window.apiToken +'"';
        return request;
      }
    };
})
.config(function($httpProvider) {
    $httpProvider.interceptors.push('apiTokenInterceptor');
});
<|endoftext|>


<commit_before>/**
 * @file poll command
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license MIT
 */

let activeChannels = {};

exports.exec = async (Bastion, message, args) => {
  try {
    if (args.length < 1 || !/^(.+( ?; ?.+[^;])+)$/i.test(args.join(' '))) {
      /**
      * The command was ran with invalid parameters.
      * @fires commandUsage
      */
      return Bastion.emit('commandUsage', message, this.help);
    }
    args = args.join(' ').split(';');

    if (!activeChannels.hasOwnProperty(message.channel.id)) {
      activeChannels[message.channel.id] = {};
      activeChannels[message.channel.id].usersVoted = [];

      let answers = [];
      for (let i = 1; i < args.length; i++) {
        answers.push({
          name: `${i}.`,
          value: `${args[i]}`,
          inline: true
        });
      }

      let pollStatus = await message.channel.send({
        embed: {
          color: Bastion.colors.BLUE,
          title: 'Poll started',
          description: `A poll has been started by ${message.author}.\n\n**${args[0]}**`,
          fields: answers,
          footer: {
            text: 'Vote by typing the corresponding number of the option.'
          }
        }
      });

      const votes = message.channel.createMessageCollector(
        m => (!m.author.bot && parseInt(m.content) > 0 && parseInt(m.content) < args.length && !activeChannels[message.channel.id].usersVoted.includes(m.author.id)) || ((m.author === message.author || m.author.id === message.guild.ownerID) && m.content === `${message.guild.prefix[0]}endpoll`),
        { time: 6 * 60 * 60 * 1000 }
      );

      votes.on('collect', (msg, votes) => {
        if (msg.content === `${message.guild.prefix[0]}endpoll`) {
          return votes.stop();
        }
        if (msg.deletable) {
          msg.delete().catch(e => {
            Bastion.log.error(e);
          });
        }
        msg.channel.send({
          embed: {
            description: `Thank you, ${msg.author}, for voting.`,
            footer: {
              text: `${votes.collected.size} votes in total.`
            }
          }
        }).then(m => {
          activeChannels[message.channel.id].usersVoted.push(msg.author.id);
          m.delete(5000).catch(e => {
            Bastion.log.error(e);
          });
        });
      });

      votes.on('end', (pollRes, reason) => {
        pollRes = pollRes.map(r => r.content);
        if (reason === 'user') {
          pollRes.splice(pollRes.indexOf(`${message.guild.prefix[0]}endpoll`), 1);
        }
        pollRes = pollRes.filter(res => parseInt(res) && parseInt(res) > 0 && parseInt(res) < args.length);
        if (pollRes.length === 0) {
          return message.channel.send({
            embed: {
              color: Bastion.colors.RED,
              title: 'Poll Ended',
              description: 'Unfortunately, no votes were given.'
            }
          }).then(() => {
            pollStatus.delete().catch(e => {
              Bastion.log.error(e);
            });
            delete activeChannels[message.channel.id];
          }).catch(e => {
            Bastion.log.error(e);
          });
        }

        for (let i = args.length - 1; i > 0; i--) {
          pollRes.unshift(i);
        }
        let count = {};
        for (let i = 0; i < pollRes.length; i++) {
          count[pollRes[i]] = count[pollRes[i]] ? count[pollRes[i]] + 1 : 1;
        }
        let result = [];
        for (let i = 1; i < args.length; i++) {
          result.push({
            name: args[i],
            value: `${((count[Object.keys(count)[i - 1]] - 1) / (pollRes.length - (args.length - 1))) * 100}%`,
            inline: true
          });
        }

        message.channel.send({
          embed: {
            color: Bastion.colors.BLUE,
            title: 'Poll Ended',
            description: `Poll results for **${args[0]}**`,
            fields: result
          }
        }).then(() => {
          pollStatus.delete().catch(e => {
            Bastion.log.error(e);
          });
          delete activeChannels[message.channel.id];
        }).catch(e => {
          Bastion.log.error(e);
        });
      });
    }
    else {
      /**
      * Error condition is encountered.
      * @fires error
      */
      return Bastion.emit('error', Bastion.strings.error(message.guild.language, 'busy'), Bastion.strings.error(message.guild.language, 'isEventInUse', true, 'poll'), message.channel);
    }
  }
  catch (e) {
    Bastion.log.error(e);
  }
};

exports.config = {
  aliases: [],
  enabled: true
};

exports.help = {
  name: 'poll',
  botPermission: '',
  userTextPermission: 'MANAGE_MESSAGES',
  userVoicePermission: '',
  usage: 'poll <question>;<option1>;<option2>[;<option3>[...]]',
  example: [ 'poll Which is the game of the week?;Call of Duty©: Infinity Warfare;Tom Clancy\'s Ghost Recon© Wildlands;Watch Dogs 2' ]
};
<commit_msg>improvements to poll; using Channel to store poll data<commit_after>/**
 * @file poll command
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license MIT
 */

exports.exec = async (Bastion, message, args) => {
  try {
    if (args.length < 1 || !/^(.+( ?; ?.+[^;])+)$/i.test(args.join(' '))) {
      /**
      * The command was ran with invalid parameters.
      * @fires commandUsage
      */
      return Bastion.emit('commandUsage', message, this.help);
    }
    args = args.join(' ').split(';');

    if (!message.channel.hasOwnProperty('poll')) {
      message.channel.poll = {};
      message.channel.poll.usersVoted = [];

      let answers = [];
      for (let i = 1; i < args.length; i++) {
        answers.push({
          name: `${i}.`,
          value: `${args[i]}`,
          inline: true
        });
      }

      let pollStatus = await message.channel.send({
        embed: {
          color: Bastion.colors.BLUE,
          title: 'Poll started',
          description: `A poll has been started by ${message.author}.\n\n**${args[0]}**`,
          fields: answers,
          footer: {
            text: 'Vote by typing the corresponding number of the option.'
          }
        }
      });

      message.channel.poll.collector = message.channel.createMessageCollector(
        m => (!m.author.bot && parseInt(m.content) > 0 && parseInt(m.content) < args.length && !message.channel.poll.usersVoted.includes(m.author.id)) || ((m.author === message.author || m.author.id === message.guild.ownerID) && m.content === `${message.guild.prefix[0]}endpoll`),
        { time: 6 * 60 * 60 * 1000 }
      );

      message.channel.poll.collector.on('collect', (msg, votes) => {
        if (msg.content === `${message.guild.prefix[0]}endpoll`) {
          return votes.stop();
        }
        if (msg.deletable) {
          msg.delete().catch(e => {
            Bastion.log.error(e);
          });
        }
        msg.channel.send({
          embed: {
            description: `Thank you, ${msg.author}, for voting.`,
            footer: {
              text: `${votes.collected.size} votes in total.`
            }
          }
        }).then(m => {
          message.channel.poll.usersVoted.push(msg.author.id);
          m.delete(5000).catch(e => {
            Bastion.log.error(e);
          });
        });
      });

      message.channel.poll.collector.on('end', (pollRes, reason) => {
        pollRes = pollRes.map(r => r.content);
        if (reason === 'user') {
          pollRes.splice(pollRes.indexOf(`${message.guild.prefix[0]}endpoll`), 1);
        }
        pollRes = pollRes.filter(res => parseInt(res) && parseInt(res) > 0 && parseInt(res) < args.length);
        if (pollRes.length === 0) {
          return message.channel.send({
            embed: {
              color: Bastion.colors.RED,
              title: 'Poll Ended',
              description: 'Unfortunately, no votes were given.'
            }
          }).then(() => {
            pollStatus.delete().catch(e => {
              Bastion.log.error(e);
            });
            delete message.channel.poll;
          }).catch(e => {
            Bastion.log.error(e);
          });
        }

        for (let i = args.length - 1; i > 0; i--) {
          pollRes.unshift(i);
        }
        let count = {};
        for (let i = 0; i < pollRes.length; i++) {
          count[pollRes[i]] = count[pollRes[i]] ? count[pollRes[i]] + 1 : 1;
        }
        let result = [];
        for (let i = 1; i < args.length; i++) {
          result.push({
            name: args[i],
            value: `${((count[Object.keys(count)[i - 1]] - 1) / (pollRes.length - (args.length - 1))) * 100}%`,
            inline: true
          });
        }

        message.channel.send({
          embed: {
            color: Bastion.colors.BLUE,
            title: 'Poll Ended',
            description: `Poll results for **${args[0]}**`,
            fields: result
          }
        }).then(() => {
          pollStatus.delete().catch(e => {
            Bastion.log.error(e);
          });
          delete message.channel.poll;
        }).catch(e => {
          Bastion.log.error(e);
        });
      });
    }
    else {
      /**
      * Error condition is encountered.
      * @fires error
      */
      return Bastion.emit('error', Bastion.strings.error(message.guild.language, 'busy'), Bastion.strings.error(message.guild.language, 'isEventInUse', true, 'poll'), message.channel);
    }
  }
  catch (e) {
    Bastion.log.error(e);
  }
};

exports.config = {
  aliases: [],
  enabled: true
};

exports.help = {
  name: 'poll',
  botPermission: '',
  userTextPermission: 'MANAGE_MESSAGES',
  userVoicePermission: '',
  usage: 'poll <question>;<option1>;<option2>[;<option3>[...]]',
  example: [ 'poll Which is the game of the week?;Call of Duty©: Infinity Warfare;Tom Clancy\'s Ghost Recon© Wildlands;Watch Dogs 2' ]
};
<|endoftext|>


<commit_before>const fs = require('fs-extra');
const buildPath = __dirname;
const projectPath = buildPath.split('/').slice(0, -1).join('/');
const packageJsonPath = `${projectPath}/package.json`;
const weeJsonPath = `${projectPath}/wee.json`;
const config = require(weeJsonPath);
const sourcePath = `${projectPath}/${config.paths.source}`;
const rootPath = `${projectPath}/${config.paths.root}`;
const assetsPath = `${rootPath}/${config.paths.assets}`;
const modulesPath = `${projectPath}/node_modules`;

module.exports = {
	project: projectPath,
	packageJson: packageJsonPath,
	wee: weeJsonPath,
	temp: `${buildPath}/temp`,
	build: buildPath,
	root: rootPath,
	source: sourcePath,
	assets: assetsPath,
	styles: `${sourcePath}/styles`,
	scripts: `${sourcePath}/scripts`,
	components: `${sourcePath}/components`,
	images: `${sourcePath}/images`,
	fonts: `${sourcePath}/fonts`,
	output: {
		styles: `${assetsPath}/styles`,
		scripts: `${assetsPath}/scripts`,
		images: `${assetsPath}/images`,
		fonts: `${assetsPath}/fonts`
	},
	nodeModules: modulesPath,
	weeCore: `${modulesPath}/wee-core`
};<commit_msg>Remove unneeded paths<commit_after>const fs = require('fs-extra');
const buildPath = __dirname;
const projectPath = buildPath.split('/').slice(0, -1).join('/');
const packageJsonPath = `${projectPath}/package.json`;
const weeJsonPath = `${projectPath}/wee.json`;
const config = require(weeJsonPath);
const sourcePath = `${projectPath}/${config.paths.source}`;
const rootPath = `${projectPath}/${config.paths.root}`;
const assetsPath = `${rootPath}/${config.paths.assets}`;
const modulesPath = `${projectPath}/node_modules`;

module.exports = {
	project: projectPath,
	packageJson: packageJsonPath,
	wee: weeJsonPath,
	temp: `${buildPath}/temp`,
	build: buildPath,
	root: rootPath,
	source: sourcePath,
	assets: assetsPath,
	styles: `${sourcePath}/styles`,
	scripts: `${sourcePath}/scripts`,
	components: `${sourcePath}/components`,
	images: `${sourcePath}/images`,
	output: {
		styles: `${assetsPath}/styles`,
		scripts: `${assetsPath}/scripts`,
		images: `${assetsPath}/images`,
		fonts: `${assetsPath}/fonts`
	},
	nodeModules: modulesPath,
	weeCore: `${modulesPath}/wee-core`
};
<|endoftext|>


<commit_before>/*
 * The webapp module provides support for building web applications in RingoJS.
 */

// import modules
require('core/object');
require('core/string');

include('ringo/webapp/request');
include('ringo/webapp/response');

var fileutils = require('ringo/fileutils');
var engine = require('ringo/engine');
var Server = require('ringo/httpserver').Server;

export('start', 'stop', 'getConfig', 'getServer', 'handleRequest');

var server;
var log = require('ringo/logging').getLogger(module.id);

module.shared = true;

/**
 * Handler function called by the JSGI servlet.
 *
 * @param env the JSGI environment argument
 */
function handleRequest(env) {
    // get config and apply it to req, res
    var configId = env['ringo.config'] || 'config';
    var config = getConfig(configId);
    if (log.isDebugEnabled()){
        log.debug('got config: ' + config.toSource());
    }

    // set req in webapp env module
    var webenv = require('ringo/webapp/env');
    var req = new Request(env);
    var res = null;
    webenv.setRequest(req);

    req.charset = config.charset || 'utf8';

    // URI-decode path-info
    req.pathInfo = decodeURI(req.pathInfo);
    // remember current scriptname as application root as scriptName will be
    // set to actual script by resolveInConfig().
    req.rootPath = req.scriptName;

    try {
        return resolveInConfig(req, config, configId);
    } catch (e if e.redirect) {
        return new RedirectResponse(e.redirect);
    }
}

function resolveInConfig(req, config, configId) {
    if (log.isDebugEnabled()) {
        log.debug('resolving path ' + req.pathInfo);
    }
    // set the root context path on which this app is mounted in the config module
    req.rootPath = req.scriptName;
    config.rootPath = req.rootPath + "/";
    // set config property in webapp env module
    var webenv = require('ringo/webapp/env');
    webenv.pushConfig(config, configId);

    if (!Array.isArray(config.urls)) {
        log.info("No URL mapping defined (urls is " + config.urls + "), throwing 404.");
        throw {notfound: true};
    }

    var path = req.pathInfo.replace(/^\/+|\/+$/g, "");

    for each (var urlEntry in config.urls) {
        if (!Array.isArray(urlEntry) || urlEntry.length < 2) {
            log.info("Ignoring unsupported URL mapping: " + urlEntry);
            continue;
        }
        if (log.isDebugEnabled()) {
            log.debug("checking url line: " + urlEntry);
        }
        var match = getPattern(urlEntry).exec(path);
        if (log.isDebugEnabled()) {
            log.debug("got match: " + match);
        }

        if (match) {
            var moduleId = resolveId(configId, urlEntry);
            var module = getModule(moduleId);
            if (log.isDebugEnabled()) {
                log.debug("module: " + module);
            }
            // move matching path fragment from PATH_INFO to SCRIPT_NAME
            req.appendToScriptName(match[0]);
            // prepare action arguments, adding regexp capture groups if any
            var args = [req].concat(match.slice(1));
            // lookup action in module
            var action = getAction(req, module, urlEntry, args);
            // log.debug("got action: " + action);
            if (typeof action == "function") {
                var res = action.apply(module, args);
                if (res && typeof res.close === 'function') {
                    return res.close();
                }
                return res;
            } else if (Array.isArray(module.urls)) {
                return resolveInConfig(req, module, moduleId);
            } else {
                log.error("Unable to resolve action for : " + action);
            }
        }
    }
    throw { notfound: true };
}

function getPattern(spec) {
    var pattern = spec[0];
    if (typeof pattern == "string") {
        if (pattern.startsWith("/"))
            pattern = pattern.replace("/", "^");
        pattern = spec[0] = new RegExp(pattern);
    } else if (!(pattern instanceof RegExp)) {
        throw Error("Pattern must be a regular expression or string");
    }
    return pattern;
}

function resolveId(parent, spec) {
    var moduleId = spec[1];
    if (typeof moduleId == "string") {
        return fileutils.resolveRelative(parent, moduleId);
    } else {
        return moduleId;
    }
}

function getModule(moduleId) {
    if (typeof moduleId == "string") {
        return require(moduleId);
    } else if (!(moduleId instanceof Object)) {
        throw Error("Module must be a string or object");
    }
    return moduleId;
}

function getAction(req, module, urlconf, args) {
    var path = splitPath(req.pathInfo);
    var action;
    // if url-conf has a hard-coded action name use it
    var name = urlconf[2];
    if (typeof module === "function") {
        action = module;
    } else {
        if (!name) {
            // action name is not defined in url mapping, try to get it from the request path
            name = path[0];
            if (name) {
                action = module[name.replace(/\./g, "_")];
                if (typeof action == "function") {
                    // If the request path contains additional elements check whether the
                    // candidate function has formal arguments to take them
                    if (path.length <= 1 || args.length + path.length - 1 <= action.length) {
                        req.appendToScriptName(name);
                        Array.prototype.push.apply(args, path.slice(1));
                        return action;
                    }
                }
            }
            // no matching action, fall back to "index"
            name = "index";
        }
        action = module[name];
    }
    if (typeof action == "function") {
        // insert predefined arguments if defined in url-conf
        if (urlconf.length > 3) {
            var spliceArgs = [1, 0].concat(urlconf.slice(3));
            Array.prototype.splice.apply(args, spliceArgs);
        }
        if (path.length == 0 || args.length + path.length <= action.length) {
            if (args.slice(1).join('').length == 0) {
                req.checkTrailingSlash();
            }
            Array.prototype.push.apply(args, path);
            return action;
        }
    }
    return null;
}

function splitPath(path) {
    //remove leading and trailing slashes and split
    var array = path.replace(/^\/+|\/+$/g, "").split(/\/+/);
    return array.length == 1 && array[0] == "" ? [] : array;
}

/**
 * Try to load the configuration module.
 * @param configModuleName optional module name, default is 'config'
 */
function getConfig(configModuleName) {
    configModuleName = configModuleName || 'config';
    return require(configModuleName);
}

/**
 * Start the web server using the given config module, or the
 * default "config" module if called without argument.
 */
function start(moduleId) {
    // start jetty http server
    moduleId = moduleId || 'config';
    var config = getConfig(moduleId);
    var httpConfig = Object.merge(config.httpConfig || {}, {
        moduleName: moduleId,
        functionName: "app"
    });

    server = new Server(httpConfig);
    server.start();
}

/**
 * Stop the web server.
 */
function stop() {
    // stop jetty HTTP server
    server.stop();
}

/**
 * Get the server instance.
 */
function getServer() {
    return server;
}

if (require.main == module) {
    for (var i = 1; i < system.args.length; i++) {
        var arg = system.args[i];
        if (arg.indexOf('-') == 0) {
            break;
        }
        engine.addRepository(arg);
    }
    log.info('Set up module path: ' + engine.getRepositories());
    start();
}
<commit_msg>Avoid redirecting to trailing slash uri unless necessary<commit_after>/*
 * The webapp module provides support for building web applications in RingoJS.
 */

// import modules
require('core/object');
require('core/string');

include('ringo/webapp/request');
include('ringo/webapp/response');

var fileutils = require('ringo/fileutils');
var engine = require('ringo/engine');
var Server = require('ringo/httpserver').Server;

export('start', 'stop', 'getConfig', 'getServer', 'handleRequest');

var server;
var log = require('ringo/logging').getLogger(module.id);

module.shared = true;

/**
 * Handler function called by the JSGI servlet.
 *
 * @param env the JSGI environment argument
 */
function handleRequest(env) {
    // get config and apply it to req, res
    var configId = env['ringo.config'] || 'config';
    var config = getConfig(configId);
    if (log.isDebugEnabled()){
        log.debug('got config: ' + config.toSource());
    }

    // set req in webapp env module
    var webenv = require('ringo/webapp/env');
    var req = new Request(env);
    var res = null;
    webenv.setRequest(req);

    req.charset = config.charset || 'utf8';

    // URI-decode path-info
    req.pathInfo = decodeURI(req.pathInfo);
    // remember current scriptname as application root as scriptName will be
    // set to actual script by resolveInConfig().
    req.rootPath = req.scriptName;

    try {
        return resolveInConfig(req, config, configId);
    } catch (e if e.redirect) {
        return new RedirectResponse(e.redirect);
    }
}

function resolveInConfig(req, config, configId) {
    if (log.isDebugEnabled()) {
        log.debug('resolving path ' + req.pathInfo);
    }
    // set the root context path on which this app is mounted in the config module
    req.rootPath = req.scriptName;
    config.rootPath = req.rootPath + "/";
    // set config property in webapp env module
    var webenv = require('ringo/webapp/env');
    webenv.pushConfig(config, configId);

    if (!Array.isArray(config.urls)) {
        log.info("No URL mapping defined (urls is " + config.urls + "), throwing 404.");
        throw {notfound: true};
    }

    var path = req.pathInfo.replace(/^\/+|\/+$/g, "");

    for each (var urlEntry in config.urls) {
        if (!Array.isArray(urlEntry) || urlEntry.length < 2) {
            log.info("Ignoring unsupported URL mapping: " + urlEntry);
            continue;
        }
        if (log.isDebugEnabled()) {
            log.debug("checking url line: " + urlEntry);
        }
        var match = getPattern(urlEntry).exec(path);
        if (log.isDebugEnabled()) {
            log.debug("got match: " + match);
        }

        if (match) {
            var moduleId = resolveId(configId, urlEntry);
            var module = getModule(moduleId);
            if (log.isDebugEnabled()) {
                log.debug("module: " + module);
            }
            // move matching path fragment from PATH_INFO to SCRIPT_NAME
            req.appendToScriptName(match[0]);
            // prepare action arguments, adding regexp capture groups if any
            var args = [req].concat(match.slice(1));
            // lookup action in module
            var action = getAction(req, module, urlEntry, args);
            // log.debug("got action: " + action);
            if (typeof action == "function") {
                var res = action.apply(module, args);
                if (res && typeof res.close === 'function') {
                    return res.close();
                }
                return res;
            } else if (Array.isArray(module.urls)) {
                return resolveInConfig(req, module, moduleId);
            } else {
                log.error("Unable to resolve action for : " + action);
            }
        }
    }
    throw { notfound: true };
}

function getPattern(spec) {
    var pattern = spec[0];
    if (typeof pattern == "string") {
        if (pattern.startsWith("/"))
            pattern = pattern.replace("/", "^");
        pattern = spec[0] = new RegExp(pattern);
    } else if (!(pattern instanceof RegExp)) {
        throw Error("Pattern must be a regular expression or string");
    }
    return pattern;
}

function resolveId(parent, spec) {
    var moduleId = spec[1];
    if (typeof moduleId == "string") {
        return fileutils.resolveRelative(parent, moduleId);
    } else {
        return moduleId;
    }
}

function getModule(moduleId) {
    if (typeof moduleId == "string") {
        return require(moduleId);
    } else if (!(moduleId instanceof Object)) {
        throw Error("Module must be a string or object");
    }
    return moduleId;
}

function getAction(req, module, urlconf, args) {
    var path = splitPath(req.pathInfo);
    var action;
    // if url-conf has a hard-coded action name use it
    var name = urlconf[2];
    if (typeof module === "function") {
        action = module;
    } else {
        if (!name) {
            // action name is not defined in url mapping, try to get it from the request path
            name = path[0];
            if (name) {
                action = module[name.replace(/\./g, "_")];
                if (typeof action == "function") {
                    // If the request path contains additional elements check whether the
                    // candidate function has formal arguments to take them
                    if (path.length <= 1 || args.length + path.length - 1 <= action.length) {
                        req.appendToScriptName(name);
                        Array.prototype.push.apply(args, path.slice(1));
                        return action;
                    }
                }
            }
            // no matching action, fall back to "index"
            name = "index";
        }
        action = module[name];
    }
    if (typeof action == "function") {
        // insert predefined arguments if defined in url-conf
        if (urlconf.length > 3) {
            var spliceArgs = [1, 0].concat(urlconf.slice(3));
            Array.prototype.splice.apply(args, spliceArgs);
        }
        if (path.length == 0 || args.length + path.length <= action.length) {
            if (path.length == 0 && args.slice(1).join('').length == 0) {
                req.checkTrailingSlash();
            }
            Array.prototype.push.apply(args, path);
            return action;
        }
    }
    return null;
}

function splitPath(path) {
    //remove leading and trailing slashes and split
    var array = path.replace(/^\/+|\/+$/g, "").split(/\/+/);
    return array.length == 1 && array[0] == "" ? [] : array;
}

/**
 * Try to load the configuration module.
 * @param configModuleName optional module name, default is 'config'
 */
function getConfig(configModuleName) {
    configModuleName = configModuleName || 'config';
    return require(configModuleName);
}

/**
 * Start the web server using the given config module, or the
 * default "config" module if called without argument.
 */
function start(moduleId) {
    // start jetty http server
    moduleId = moduleId || 'config';
    var config = getConfig(moduleId);
    var httpConfig = Object.merge(config.httpConfig || {}, {
        moduleName: moduleId,
        functionName: "app"
    });

    server = new Server(httpConfig);
    server.start();
}

/**
 * Stop the web server.
 */
function stop() {
    // stop jetty HTTP server
    server.stop();
}

/**
 * Get the server instance.
 */
function getServer() {
    return server;
}

if (require.main == module) {
    for (var i = 1; i < system.args.length; i++) {
        var arg = system.args[i];
        if (arg.indexOf('-') == 0) {
            break;
        }
        engine.addRepository(arg);
    }
    log.info('Set up module path: ' + engine.getRepositories());
    start();
}
<|endoftext|>


<commit_before>'use strict';

var chalk = require('chalk');
var exec = require('child_process').exec;
var fs = require('fs');
var path = require('path');
var prompt = require('prompt');
var rimraf = require('rimraf');

var themeDirectory = path.basename(path.resolve(__dirname, '..'));

var schema = {
    properties: {
        name: {
            default: themeDirectory,
            description: chalk.gray('  Name'),
            required: true,
        },
        description: {
            description: chalk.gray('  Description'),
            required: false,
        },
        author: {
            description: chalk.gray('  Author'),
            required: false,
        },
        url: {
            description: chalk.gray('  Application URL'),
            required: true,
        },
        cleanup: {
            before: function(value) {
                return Boolean(value.match(/^[Yy](.*)/));
            },
            default: 'y',
            description: chalk.gray('  Remove setup command (y/n)'),
            message: 'Answer must be yes or no',
            pattern: /^[YyNn](.*)*/,
            required: true,
        },
    },
};

//
// if they haven't removed our repo yet, offer to do it for them
//
var isVuetoberRepository;
try {
    var gitConfig = fs.readFileSync(path.resolve(__dirname, '../.git/config'), 'utf8');
    isVuetoberRepository = Boolean(gitConfig.match(/github\.com[\/:]scottbedard\/oc-vuetober-theme/g));
} catch (err) {
    isVuetoberRepository = false;
}

if (isVuetoberRepository) {
    schema.properties.cleanupGit = {
        before: function(value) {
            return Boolean(value.match(/^[Yy](.*)/));
        },
        default: 'y',
        description: chalk.gray('  Remove git repository (y/n)'),
        pattern: /^[YyNn](.*)*/,
        required: true,
    };
}

//
// start the setup prompt
//
console.log (chalk.white('  Setup a new Vuetober theme'));
console.log ();

prompt.message = false;
prompt.start();

//
// process the answers the user provided
//
prompt.get(schema, function (err, result) {
    if (err) {
        console.log ();
        console.log ();
        console.log (chalk.red('  Setup canceled'));
        return;
    }

    // create our theme.yaml file
    var theme =
        'name: \'' + result.name + '\'\n' +
        'description: \'' + result.description + '\'\n' +
        'author: \'' + result.author + '\'';

    fs.writeFileSync(path.resolve(__dirname, '../theme.yaml'), theme);

    // update our dev-server to use the correct url and directory
    var devServer = fs.readFileSync(path.resolve(__dirname, './dev-server.js'), 'utf8')
        .replace(/oc-vuetober-theme/g, themeDirectory)
        .replace(/http:\/\/vuetober\.october\.dev/g, result.url);

    fs.writeFileSync(path.resolve(__dirname, './dev-server.js'), devServer);

    // update the asset path to use the correct directory
    var configIndex = fs.readFileSync(path.resolve(__dirname, '../config/index.js'), 'utf8')
        .replace(/oc-vuetober-theme/g, themeDirectory);

    fs.writeFileSync(path.resolve(__dirname, '../config/index.js'), configIndex);

    // remove the setup command
    if (result.cleanup) {
        var setupPath = path.resolve(__dirname, 'setup.js');
        var packageJson = fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf8')
            .replace('"setup": "node build/setup.js",\n    ', '');

        fs.writeFileSync(path.resolve(__dirname, '../package.json'), packageJson);
        rimraf.sync(setupPath);
    }

    // remove the old git repository
    if (result.cleanupGit) {
        rimraf.sync(path.resolve(__dirname, '../.git'));
    }

    // instruct october to use our new theme
    var cmd = 'php artisan theme:use ' + themeDirectory + ' --force';
    exec(cmd, { cwd: path.resolve('../../') }, function(error, stdout, stderr) {

        // show the success message
        console.log ();
        console.log (chalk.green('  Vuetober set up complete, time to build something amazing!'));
        console.log ();
        console.log (chalk.gray('  You\'ll need to run the following command before viewing your theme in the browser.'));
        console.log ();
        console.log (chalk.gray('  $ npm run build'));
    });
});
<commit_msg>Add a helpful error message to install dependencies<commit_after>'use strict';

//
// check if node modules have been installed, and if
// not give the user a some help installing them.
//
try {
    var chalk = require('chalk');
    var exec = require('child_process').exec;
    var fs = require('fs');
    var path = require('path');
    var prompt = require('prompt');
    var rimraf = require('rimraf');
} catch(e) {
    console.log('You must run the following command before setting up your theme.');
    console.log();
    console.log('$ npm install');

    return;
}

var themeDirectory = path.basename(path.resolve(__dirname, '..'));

var schema = {
    properties: {
        name: {
            default: themeDirectory,
            description: chalk.gray('  Name'),
            required: true,
        },
        description: {
            description: chalk.gray('  Description'),
            required: false,
        },
        author: {
            description: chalk.gray('  Author'),
            required: false,
        },
        url: {
            description: chalk.gray('  Application URL'),
            required: true,
        },
        cleanup: {
            before: function(value) {
                return Boolean(value.match(/^[Yy](.*)/));
            },
            default: 'y',
            description: chalk.gray('  Remove setup command (y/n)'),
            message: 'Answer must be yes or no',
            pattern: /^[YyNn](.*)*/,
            required: true,
        },
    },
};

//
// if they haven't removed our repo yet, offer to do it for them
//
var isVuetoberRepository;
try {
    var gitConfig = fs.readFileSync(path.resolve(__dirname, '../.git/config'), 'utf8');
    isVuetoberRepository = Boolean(gitConfig.match(/github\.com[\/:]scottbedard\/oc-vuetober-theme/g));
} catch (err) {
    isVuetoberRepository = false;
}

if (isVuetoberRepository) {
    schema.properties.cleanupGit = {
        before: function(value) {
            return Boolean(value.match(/^[Yy](.*)/));
        },
        default: 'y',
        description: chalk.gray('  Remove git repository (y/n)'),
        pattern: /^[YyNn](.*)*/,
        required: true,
    };
}

//
// start the setup prompt
//
console.log (chalk.white('  Setup a new Vuetober theme'));
console.log ();

prompt.message = false;
prompt.start();

//
// process the answers the user provided
//
prompt.get(schema, function (err, result) {
    if (err) {
        console.log ();
        console.log ();
        console.log (chalk.red('  Setup canceled'));
        return;
    }

    // create our theme.yaml file
    var theme =
        'name: \'' + result.name + '\'\n' +
        'description: \'' + result.description + '\'\n' +
        'author: \'' + result.author + '\'';

    fs.writeFileSync(path.resolve(__dirname, '../theme.yaml'), theme);

    // update our dev-server to use the correct url and directory
    var devServer = fs.readFileSync(path.resolve(__dirname, './dev-server.js'), 'utf8')
        .replace(/oc-vuetober-theme/g, themeDirectory)
        .replace(/http:\/\/vuetober\.october\.dev/g, result.url);

    fs.writeFileSync(path.resolve(__dirname, './dev-server.js'), devServer);

    // update the asset path to use the correct directory
    var configIndex = fs.readFileSync(path.resolve(__dirname, '../config/index.js'), 'utf8')
        .replace(/oc-vuetober-theme/g, themeDirectory);

    fs.writeFileSync(path.resolve(__dirname, '../config/index.js'), configIndex);

    // remove the setup command
    if (result.cleanup) {
        var setupPath = path.resolve(__dirname, 'setup.js');
        var packageJson = fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf8')
            .replace('"setup": "node build/setup.js",\n    ', '');

        fs.writeFileSync(path.resolve(__dirname, '../package.json'), packageJson);
        rimraf.sync(setupPath);
    }

    // remove the old git repository
    if (result.cleanupGit) {
        rimraf.sync(path.resolve(__dirname, '../.git'));
    }

    // instruct october to use our new theme
    var cmd = 'php artisan theme:use ' + themeDirectory + ' --force';
    exec(cmd, { cwd: path.resolve('../../') }, function(error, stdout, stderr) {

        // show the success message
        console.log ();
        console.log (chalk.green('  Vuetober set up complete, time to build something amazing!'));
        console.log ();
        console.log (chalk.gray('  You\'ll need to run the following command before viewing your theme in the browser.'));
        console.log ();
        console.log (chalk.gray('  $ npm run build'));
    });
});
<|endoftext|>