<commit_before>/*
  Copyright 2009 The Rhizosphere Authors. All Rights Reserved.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

// RHIZODEP=rhizo.model.loader,rhizo.base,rhizo.ui.component,rhizo.jquery,rhizo.ui.gui
namespace('rhizo.bootstrap');

/**
 * Uuid counter to uniquely identify the container of each visualization within
 * the document.
 * @type {number}
 * @private
 */
rhizo.bootstrap.uuids_ = 0;

/**
 * A Bootstrap is the main entry point to start a Rhizosphere visualization.
 * It takes care of loading the data to visualize, create the chrome and other
 * ui elements for the visualization, and bind all the necessary event handlers.
 *
 * @param {HTMLElement} container The HTML element that will contain the
 *     visualization.
 * @param {*} opt_options Visualization-wide configuration options.
 * @param {?function(rhizo.Project)} opt_callback
 *     Optional callback invoked on the visualization is completely initialized.
 *     Receives the rhizo.Project managing the visualization as a parameter.
 * @constructor
 */
rhizo.bootstrap.Bootstrap = function(container, opt_options, opt_callback) {
  this.container_ = container;
  this.deployed_ = false;
  var containerId = $(container).attr('id');
  if (!containerId || containerId.length == 0) {
    // Generates a unique element id for the visualization container if one
    // isn't defined yet.
    // The generated id must be consistent over time (assuming the order of
    // bootstrap calls does not change over time when multiple visualizations
    // are present), since long-lived Rhizosphere state representations are
    // based on this.
    $(container).attr('id', 'rhizo-uuid-' + (rhizo.bootstrap.uuids_++));
  }
  this.options_ = { selectfilter: '.rhizo-model:visible',
                    enableHTML5History: true,
                    enableAnims: true};
  if (opt_options) {
    $.extend(this.options_, opt_options);
  }
  this.ready_callback_ = opt_callback;
};

/**
 * @return {boolean} Whether deployment of models has already occurred or not.
 */
rhizo.bootstrap.Bootstrap.prototype.isDeployed = function() {
  return this.deployed_;
};

/**
 * Performs all the necessary steps to prepare a Rhizosphere visualization, and
 * then tries loading the given datasource and display it.
 *
 * @param {string} opt_resource The URI of the datasource to load and visualize
 *     with Rhizosphere. If null and the bootstrapper is not allowed to
 *     configure itself from URL parameters, this method behaves like prepare().
 * @return {rhizo.Project} The visualization Project through which you can
 *     have programmatic access to the visualization.
 */
rhizo.bootstrap.Bootstrap.prototype.prepareAndDeploy = function(opt_resource) {
  var project = this.prepare();
  this.deploy(opt_resource);
  return project;
};

/**
 * Performs all the necessary steps to prepare a Rhizosphere visualization, up
 * to the point where it can receive the models to display.
 *
 * Use this method in conjunction with deploy() if you want to be in charge
 * of loading the actual models to visualize.
 *
 * @return {rhizo.Project} The visualization Project through which you can
 *     have programmatic access to the visualization.
 */
rhizo.bootstrap.Bootstrap.prototype.prepare = function() {
  // Initialize the GUI, project and template.
  this.gui_ = this.initGui_();
  this.project_ = new rhizo.Project(this.gui_, this.options_);
  this.template_ = this.initTemplate_(this.project_, this.gui_, this.options_);
  this.project_.chromeReady();
  return this.project_;
};

/**
 * Loads the data items to visualize from the given datasource URI and displays
 * them in the Rhizosphere visualization managed by this bootstrapper.
 * The boostrapper must have already been prepared before invoking this method.
 *
 * @param {string} opt_resource The URI of the datasource to load and visualize
 *     with Rhizosphere. If null, and the bootstrapper is allowed to configure
 *     itself from the URL parameters, it'll try to extract the datasource URI
 *     from the URL.
 */
rhizo.bootstrap.Bootstrap.prototype.deploy = function(opt_resource) {
  // Identify if we have to load a Rhizosphere datasource. Either we received
  // this information explicitly or we try finding it in the URL.
  var resource = opt_resource || this.tryInitResourceFromUrl_();

  if (resource) {
    rhizo.model.loader.load(resource,
                            jQuery.proxy(this.deployExplicit, this),
                            this.options_,
                            this.project_.logger());
  }
};

/**
 * Loads the data items to visualize via the given loader instance and displays
 * them in the Rhizosphere visualization managed by this bootstrapper.
 * The boostrapper must have already been prepared before invoking this method.
 *
 * @param {*} loader A model loader as defined in rhizo.model.loader.js
 */
rhizo.bootstrap.Bootstrap.prototype.deployWithLoader = function(loader) {
  loader.load(jQuery.proxy(this.deployExplicit, this),
              this.options_, this.project_.logger());
};

/**
 * Displays the given data items (models) in the Rhizosphere visualization
 * managed by this bootstrapper. The boostrapper must have already been
 * prepared before invoking this method.
 *
 * @param {Array.<*>} models The list of data items to visualize.
 * @param {*} opt_metamodel A descriptor for the attributes and properties that
 *     each model in the visualization has. Can be omitted if the metamodel has
 *     been specified via configuration options.
 * @param {*} opt_renderer A component capable of creating HTML representation
 *     of model instances. Can be omitted if the renderer has been specified via
 *     configuration options.
 */
rhizo.bootstrap.Bootstrap.prototype.deployExplicit = function(models,
                                                              opt_metamodel,
                                                              opt_renderer) {
  this.project_.setMetaModel(this.options_.metamodel || opt_metamodel);
  this.project_.setRenderer(this.options_.renderer || opt_renderer);

  if (this.project_.renderer().getSizeRange ||
      this.project_.renderer().getColorRange) {
    this.template_.addComponent(new rhizo.ui.component.Legend(this.project_,
                                                              this.options_));
  }

  if (this.project_.metaReady()) {
    this.template_.metaReady();
    this.project_.deploy(models);
    this.template_.ready();
  }
  this.gui_.done();
  if (this.ready_callback_) {
    this.ready_callback_(this.project_);
  }
  this.deployed_ = true;
};

/**
 * Identify the platform and device we are running onto.
 * @private
 */
rhizo.bootstrap.Bootstrap.prototype.identifyPlatformAndDevice_ = function() {
  if (this.options_.platform && this.options_.device) {
    return {platform: this.options_.platform,
            device: this.options_.device};
  }
  var ua = navigator.userAgent;
  if (ua.toLowerCase().indexOf('ipad') != -1) {
    return {platform: 'mobile', device: 'ipad'};
  } else if (ua.toLowerCase().indexOf('iphone') != -1) {
    return {platform: 'mobile', device: 'iphone'};
  } else if (ua.toLowerCase().indexOf('android') != -1) {
    return {platform: 'mobile', 'device': 'android'};
  }
  return {platform: 'default', device: 'default'};
};

/**
 * Identifies the best template to use for the visualization.
 * @param {rhizo.ui.gui.GUI} gui
 * @param {*} options
 * @return {function(rhizo.Project):rhizo.ui.component.Template} A factory for
 *     the template to use.
 * @private
 */
rhizo.bootstrap.Bootstrap.prototype.identifyTemplate_ = function(gui, options) {
  if (options.template &&
      options.template in rhizo.ui.component.templates) {
    return rhizo.ui.component.templates[options.template];
  }

  // No specific template has been forced. Select a specific one based on
  // document size and target platform.
  if (gui.isMobile() || gui.isSmall()) {
    return rhizo.ui.component.templates['bottom'];
  }
  return rhizo.ui.component.templates['default'];
};

/**
 * Identifies the platform and device we are running upon and creates a GUI
 * for this project.
 * @return {rhizo.ui.gui.GUI} The project GUI.
 * @private
 */
rhizo.bootstrap.Bootstrap.prototype.initGui_ = function() {
  // Identify the target platform and device we are running onto.
  var platformDevice = this.identifyPlatformAndDevice_();

  // Create the GUI.
  var gui = new rhizo.ui.gui.GUI(this.container_,
                                 platformDevice.platform,
                                 platformDevice.device);
  gui.disableFx(!this.options_.enableAnims);

  // Extends jQuery with all the additional behaviors required by Rhizosphere
  // Disable animations and other performance tunings if needed.
  //
  // TODO(battlehorse): this must happen at the global level, and not locally
  // for every single visualization.
  // See http://code.google.com/p/rhizosphere/issues/detail?id=68.
  rhizo.jquery.init(gui, this.options_.enableAnims, true);

  return gui;
};

/**
 * Initializes the template that will render this project chrome.
 * @param {rhizo.Project} project
 * @param {rhizo.ui.gui.GUI} gui
 * @param {*} options
 * @return {rhizo.ui.component.Template} The project template.
 * @private
 */
rhizo.bootstrap.Bootstrap.prototype.initTemplate_ = function(project,
                                                             gui,
                                                             options) {
  // Identify the target device and template to use.
  var templateFactory = this.identifyTemplate_(gui, options);
  var template = templateFactory(project, options);

  // Get the minimum chrome up and running.
  template.render();
  return template;
};

/**
 * If the bootstrapper is allowed to extract parameters from the document
 * location, tries extracting the URI of the resource to display from the there.
 *
 * @return {string} The URI of the resource to load and display.
 * @private
 */
rhizo.bootstrap.Bootstrap.prototype.tryInitResourceFromUrl_ = function() {
  if (!this.options_.allowConfigFromUrl) {
    this.project_.logger().warn(
        'Sources extraction from url is disabled');
    return null;
  }

  var urlparams = rhizo.util.urlParams();
  var resource = urlparams['source'] || urlparams['src'];
  if (!resource) {
    this.project_.logger().error(
        'Unable to identify datasource from location');
    return null;
  }
  return decodeURIComponent(resource);
};

<commit_msg>Adding support for metamodel fragment overrides.<commit_after>
/*
  Copyright 2009 The Rhizosphere Authors. All Rights Reserved.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

// RHIZODEP=rhizo.model.loader,rhizo.base,rhizo.ui.component,rhizo.jquery,rhizo.ui.gui
namespace('rhizo.bootstrap');

/**
 * Uuid counter to uniquely identify the container of each visualization within
 * the document.
 * @type {number}
 * @private
 */
rhizo.bootstrap.uuids_ = 0;

/**
 * A Bootstrap is the main entry point to start a Rhizosphere visualization.
 * It takes care of loading the data to visualize, create the chrome and other
 * ui elements for the visualization, and bind all the necessary event handlers.
 *
 * @param {HTMLElement} container The HTML element that will contain the
 *     visualization. It must have an explicit CSS position set (either
 *     'relative' or 'absolute'). You are free to set its width and height and
 *     Rhizosphere will render itself within the given constraints.
 * @param {*} opt_options Visualization-wide configuration options, as
 *     described at
 *     http://www.rhizospherejs.com/doc/contrib_tables.html#options.
 * @param {?function(rhizo.Project)} opt_callback
 *     Optional callback invoked on the visualization is completely initialized.
 *     Receives the rhizo.Project managing the visualization as a parameter.
 * @constructor
 */
rhizo.bootstrap.Bootstrap = function(container, opt_options, opt_callback) {
  this.container_ = container;
  this.deployed_ = false;
  var containerId = $(container).attr('id');
  if (!containerId || containerId.length == 0) {
    // Generates a unique element id for the visualization container if one
    // isn't defined yet.
    // The generated id must be consistent over time (assuming the order of
    // bootstrap calls does not change over time when multiple visualizations
    // are present), since long-lived Rhizosphere state representations are
    // based on this.
    $(container).attr('id', 'rhizo-uuid-' + (rhizo.bootstrap.uuids_++));
  }
  this.options_ = { selectfilter: '.rhizo-model:visible',
                    enableHTML5History: true,
                    enableAnims: true};
  if (opt_options) {
    $.extend(this.options_, opt_options);
  }
  this.ready_callback_ = opt_callback;
};

/**
 * @return {boolean} Whether deployment of models has already occurred or not.
 */
rhizo.bootstrap.Bootstrap.prototype.isDeployed = function() {
  return this.deployed_;
};

/**
 * Performs all the necessary steps to prepare a Rhizosphere visualization, and
 * then tries loading the given datasource and display it.
 *
 * @param {string} opt_resource The URI of the datasource to load and visualize
 *     with Rhizosphere. If null and the bootstrapper is not allowed to
 *     configure itself from URL parameters, this method behaves like prepare().
 * @return {rhizo.Project} The visualization Project through which you can
 *     have programmatic access to the visualization.
 */
rhizo.bootstrap.Bootstrap.prototype.prepareAndDeploy = function(opt_resource) {
  var project = this.prepare();
  this.deploy(opt_resource);
  return project;
};

/**
 * Performs all the necessary steps to prepare a Rhizosphere visualization, up
 * to the point where it can receive the models to display.
 *
 * Use this method in conjunction with deploy() if you want to be in charge
 * of loading the actual models to visualize.
 *
 * @return {rhizo.Project} The visualization Project through which you can
 *     have programmatic access to the visualization.
 */
rhizo.bootstrap.Bootstrap.prototype.prepare = function() {
  // Initialize the GUI, project and template.
  this.gui_ = this.initGui_();
  this.project_ = new rhizo.Project(this.gui_, this.options_);
  this.template_ = this.initTemplate_(this.project_, this.gui_, this.options_);
  this.project_.chromeReady();
  return this.project_;
};

/**
 * Loads the data items to visualize from the given datasource URI and displays
 * them in the Rhizosphere visualization managed by this bootstrapper.
 * The boostrapper must have already been prepared before invoking this method.
 *
 * @param {string} opt_resource The URI of the datasource to load and visualize
 *     with Rhizosphere. If null, and the bootstrapper is allowed to configure
 *     itself from the URL parameters, it'll try to extract the datasource URI
 *     from the URL.
 */
rhizo.bootstrap.Bootstrap.prototype.deploy = function(opt_resource) {
  // Identify if we have to load a Rhizosphere datasource. Either we received
  // this information explicitly or we try finding it in the URL.
  var resource = opt_resource || this.tryInitResourceFromUrl_();

  if (resource) {
    rhizo.model.loader.load(resource,
                            jQuery.proxy(this.deployExplicit, this),
                            this.options_,
                            this.project_.logger());
  }
};

/**
 * Loads the data items to visualize via the given loader instance and displays
 * them in the Rhizosphere visualization managed by this bootstrapper.
 * The boostrapper must have already been prepared before invoking this method.
 *
 * @param {*} loader A model loader as defined in rhizo.model.loader.js
 */
rhizo.bootstrap.Bootstrap.prototype.deployWithLoader = function(loader) {
  loader.load(jQuery.proxy(this.deployExplicit, this),
              this.options_, this.project_.logger());
};

/**
 * Displays the given data items (models) in the Rhizosphere visualization
 * managed by this bootstrapper. The boostrapper must have already been
 * prepared before invoking this method.
 *
 * @param {Array.<*>} models The list of data items to visualize.
 * @param {*} opt_metamodel A descriptor for the attributes and properties that
 *     each model in the visualization has. Can be omitted if the metamodel has
 *     been specified via configuration options.
 * @param {*} opt_renderer A component capable of creating HTML representation
 *     of model instances. Can be omitted if the renderer has been specified via
 *     configuration options.
 */
rhizo.bootstrap.Bootstrap.prototype.deployExplicit = function(models,
                                                              opt_metamodel,
                                                              opt_renderer) {
  var metamodel = this.options_.metamodel || opt_metamodel;
  if (this.options_.metamodelFragment) {
    $.extend(metamodel, this.options_.metamodelFragment);
  }
  this.project_.setMetaModel(metamodel);
  this.project_.setRenderer(this.options_.renderer || opt_renderer);

  if (this.project_.renderer().getSizeRange ||
      this.project_.renderer().getColorRange) {
    this.template_.addComponent(new rhizo.ui.component.Legend(this.project_,
                                                              this.options_));
  }

  if (this.project_.metaReady()) {
    this.template_.metaReady();
    this.project_.deploy(models);
    this.template_.ready();
  }
  this.gui_.done();
  if (this.ready_callback_) {
    this.ready_callback_(this.project_);
  }
  this.deployed_ = true;
};

/**
 * Identify the platform and device we are running onto.
 * @private
 */
rhizo.bootstrap.Bootstrap.prototype.identifyPlatformAndDevice_ = function() {
  if (this.options_.platform && this.options_.device) {
    return {platform: this.options_.platform,
            device: this.options_.device};
  }
  var ua = navigator.userAgent;
  if (ua.toLowerCase().indexOf('ipad') != -1) {
    return {platform: 'mobile', device: 'ipad'};
  } else if (ua.toLowerCase().indexOf('iphone') != -1) {
    return {platform: 'mobile', device: 'iphone'};
  } else if (ua.toLowerCase().indexOf('android') != -1) {
    return {platform: 'mobile', 'device': 'android'};
  }
  return {platform: 'default', device: 'default'};
};

/**
 * Identifies the best template to use for the visualization.
 * @param {rhizo.ui.gui.GUI} gui
 * @param {*} options
 * @return {function(rhizo.Project):rhizo.ui.component.Template} A factory for
 *     the template to use.
 * @private
 */
rhizo.bootstrap.Bootstrap.prototype.identifyTemplate_ = function(gui, options) {
  if (options.template &&
      options.template in rhizo.ui.component.templates) {
    return rhizo.ui.component.templates[options.template];
  }

  // No specific template has been forced. Select a specific one based on
  // document size and target platform.
  if (gui.isMobile() || gui.isSmall()) {
    return rhizo.ui.component.templates['bottom'];
  }
  return rhizo.ui.component.templates['default'];
};

/**
 * Identifies the platform and device we are running upon and creates a GUI
 * for this project.
 * @return {rhizo.ui.gui.GUI} The project GUI.
 * @private
 */
rhizo.bootstrap.Bootstrap.prototype.initGui_ = function() {
  // Identify the target platform and device we are running onto.
  var platformDevice = this.identifyPlatformAndDevice_();

  // Create the GUI.
  var gui = new rhizo.ui.gui.GUI(this.container_,
                                 platformDevice.platform,
                                 platformDevice.device);
  gui.disableFx(!this.options_.enableAnims);

  // Extends jQuery with all the additional behaviors required by Rhizosphere
  // Disable animations and other performance tunings if needed.
  //
  // TODO(battlehorse): this must happen at the global level, and not locally
  // for every single visualization.
  // See http://code.google.com/p/rhizosphere/issues/detail?id=68.
  rhizo.jquery.init(gui, this.options_.enableAnims, true);

  return gui;
};

/**
 * Initializes the template that will render this project chrome.
 * @param {rhizo.Project} project
 * @param {rhizo.ui.gui.GUI} gui
 * @param {*} options
 * @return {rhizo.ui.component.Template} The project template.
 * @private
 */
rhizo.bootstrap.Bootstrap.prototype.initTemplate_ = function(project,
                                                             gui,
                                                             options) {
  // Identify the target device and template to use.
  var templateFactory = this.identifyTemplate_(gui, options);
  var template = templateFactory(project, options);

  // Get the minimum chrome up and running.
  template.render();
  return template;
};

/**
 * If the bootstrapper is allowed to extract parameters from the document
 * location, tries extracting the URI of the resource to display from the there.
 *
 * @return {string} The URI of the resource to load and display.
 * @private
 */
rhizo.bootstrap.Bootstrap.prototype.tryInitResourceFromUrl_ = function() {
  if (!this.options_.allowConfigFromUrl) {
    this.project_.logger().warn(
        'Sources extraction from url is disabled');
    return null;
  }

  var urlparams = rhizo.util.urlParams();
  var resource = urlparams['source'] || urlparams['src'];
  if (!resource) {
    this.project_.logger().error(
        'Unable to identify datasource from location');
    return null;
  }
  return decodeURIComponent(resource);
};

<|endoftext|>


<commit_before>'use strict';

/*
var cl = console.log;
console.log = function(){
  console.trace();
  cl.apply(console,arguments);
};
*/

// Requires meanio .

process.env.NODE_CONFIG_DIR = './config/env';

var mean = require('meanio');

var cluster = require('cluster');

var deferred = require('q').defer();

var compression = require('compression');

var express = require('express');

var app = express();

app.use(compression());

app.use('/', express.static(__dirname + '/'));

app.use(express.static('public'));

app.use(express.static('bower_components'));

app.get('/', function (req, res) {

  res.sendFile(path.join(__dirname + "/index.html"));

});

app.listen(process.env.PORT || 5000, function () {

  console.log('Example app listening on port 5000!');

});

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use(bodyParser.json());

var mandrill = require('node-mandrill')(process.env.MANDRILL_API);

app.post('/api/queryLog/:name:email:subject:message', function (req, res) {

var name = req.body.email;

  mandrill('/messages/send', {

    message: {
        to: [{email: 'udigitalmedia@hotmail.com', name: req.body.name}],
        from_email: req.body.email,
        subject: req.body.subject,
        text: req.body.message
    }

}, function(error, response)

{
    //uh oh, there was an error
    if (error) console.log( JSON.stringify(error) );

    else console.log(response);

     var response = {"firstName":name, "lastName":"Doe"} ;

    res.json(response);

});

});

module.exports = deferred.promise;
<commit_msg>fixes<commit_after>'use strict';

/*
var cl = console.log;
console.log = function(){
  console.trace();
  cl.apply(console,arguments);
};
*/

// Requires meanio .

process.env.NODE_CONFIG_DIR = './config/env';

var mean = require('meanio');

var cluster = require('cluster');

var deferred = require('q').defer();

var compression = require('compression');

var express = require('express');

var app = express();

app.use(compression());

app.use('/', express.static(__dirname + '/'));

app.use(express.static('public'));

app.use(express.static('bower_components'));

app.get('/', function (req, res) {

  res.sendFile(path.join(__dirname + "/index.html"));

});

app.listen(process.env.PORT || 5000, function () {

  console.log('Example app listening on port 5000!');

});

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));

app.use(bodyParser.json());

var mandrill_client = require('node-mandrill')('fix_HqmjREpZnCAHR_Dhaw');

app.post('/api/queryLog/:name:email:subject:message', function (req, res) {

var name = req.body.email;

var message = {
    "html": "
Example HTML content
",
    "text": req.body.message,
    "subject": req.body.subject,
    "from_email": "info@unifieddigitalmedia.co.uk",
    "from_name": req.body.name,
    "to": [{
            "email": "udigitallondon@hotmail.com",
            "name": "Recipient Name",
            "type": "to"
        }],
    "headers": {
        "Reply-To": "message.reply@example.com"
    },
    "important": false,
    "track_opens": null,
    "track_clicks": null,
    "auto_text": null,
    "auto_html": null,
    "inline_css": null,
    "url_strip_qs": null,
    "preserve_recipients": null,
    "view_content_link": null,
    "bcc_address": "message.bcc_address@example.com",
    "tracking_domain": null,
    "signing_domain": null,
    "return_path_domain": null,
    "merge": true,
    "merge_language": "mailchimp",
    "global_merge_vars": [{
            "name": "merge1",
            "content": "merge1 content"
        }],
    "merge_vars": [{
            "rcpt": "recipient.email@example.com",
            "vars": [{
                    "name": "merge2",
                    "content": "merge2 content"
                }]
        }],
    "tags": [
        "password-resets"
    ],
    "subaccount": "customer-123",
    "google_analytics_domains": [
        "example.com"
    ],
    "google_analytics_campaign": "message.from_email@example.com",
    "metadata": {
        "website": "www.example.com"
    },
    "recipient_metadata": [{
            "rcpt": "recipient.email@example.com",
            "values": {
                "user_id": 123456
            }
        }],
    "attachments": [{
            "type": "text/plain",
            "name": "myfile.txt",
            "content": "ZXhhbXBsZSBmaWxl"
        }],
    "images": [{
            "type": "image/png",
            "name": "IMAGECID",
            "content": "ZXhhbXBsZSBmaWxl"
        }]
};
var async = false;
var ip_pool = "Main Pool";
var send_at = "2016-07-23 12:01:00";

mandrill_client.messages.send({"message": message}, function(result) {

    console.log(result);

    res.end();
    /*
    [{
            "email": "recipient.email@example.com",
            "status": "sent",
            "reject_reason": "hard-bounce",
            "_id": "abc123abc123abc123abc123abc123"
        }]
    */
}, function(e) {
    // Mandrill returns the error as an object with name and message keys
    console.log('A mandrill error occurred: ' + e.name + ' - ' + e.message);
    // A mandrill error occurred: Unknown_Subaccount - No subaccount exists with the id 'customer-123'
     res.end();
});

});

module.exports = deferred.promise;
<|endoftext|>


<commit_before>;(function() {

	var $scope = {};

	// As soon as the page has loaded, parse it
	parsePage();

	// If text was found, enable quick access
	if($scope.parseResults) {
		chrome.storage.sync.get(['quickAccessGlobal', 'quickAccessBlacklist'], function(res) {

			injectHTML();
			setupEventListeners();
			estimateParseTime();

			var blacklist = res.quickAccessBlacklist || [],
				isBlacklisted = blacklist.includes( window.location.hostname );

			if(res.quickAccessGlobal === false || isBlacklisted) {
				console.log(blacklist)
				$scope.quickAccessContainer.classList.add('hidden');
			}

		})
	}

	function injectHTML() {
		var html = '';

		html += '
';

		html += 	'';
		html +=			'
Read with Readio,
';
		html +=	 		'

';
		html +=		'';

		html += 	'';
		html +=			'
Open editor to paste text
';
		html +=	 		'

';
		html +=		'';

		html += 	'';
		html +=			'
Disable quick access buttons
';
		html +=	 		'

';
		html += 	'';

		html += '
';

		html += '
';
		html += 	'
';
		html +=	 		'
Hide quick access buttons
';
		html +=	 		'
';
		html +=	 			'All websites';
		html +=	 			' or ';
		html +=	 			''+ window.location.hostname +'';
		html +=	 			' or ';
		html +=	 			'cancel';
		html +=	 		'
';
		html += 	'
';
		html += '
';

		document.body.insertAdjacentHTML('afterbegin', html);
	}

	function estimateParseTime() {

		chrome.storage.sync.get('wpm', function(res) {
			var timeContainer = document.getElementById('sr-read-time-container'),

				words = $scope.parseResults.textContent.split(/\s+/g),
				wordCount = words.length,
				wpmOpt = res.wpm || 300, // Assuming 300 is default wpm

				wpm = (wordCount/wpmOpt) * 1.2, // Add 20% words, magic number to be more correct
				wpmRound = Math.floor(wpm),
				text = '';

			if(wpmRound < 1) {
				text = '<1 min';
			} else {
				text = wpmRound + ' min';
			}

			timeContainer.innerHTML = text;
		});
	}

	function setupEventListeners() {
		$scope.quickAccessContainer = document.getElementById('sr-qa-container');

		$scope.readBtn = document.getElementById('sr-qa-trigger-read');
		$scope.editBtn = document.getElementById('sr-qa-trigger-edit');
		$scope.disableDialogTrigger = document.getElementById('sr-qa-trigger-hide');

		$scope.disableEverywhereBtn = document.getElementById('sr-hide-qa-everywhere-button');
		$scope.disableJustHereBtn = document.getElementById('sr-hide-qa-justhere-button');

		$scope.dialogs = document.querySelectorAll('.sr-dialog-container');
		$scope.dialogCloseTriggers = document.querySelectorAll('.sr-dialog-close');

		$scope.quickAccessDisableDialog = document.getElementById('sr-hide-qa-dialog');

		$scope.disableEverywhereBtn.onclick = function() {
			chrome.storage.sync.set({ quickAccessGlobal : false });
			$scope.quickAccessContainer.classList.add('hidden');
			hideDialogs();
		}

		$scope.disableJustHereBtn.onclick = function() {
			addToBlacklist();
			$scope.quickAccessContainer.classList.add('hidden');
			hideDialogs();
		}

		$scope.dialogs.forEach(function(d) {
			d.onclick = function(e) {
				if( e.target.classList.contains('sr-dialog-container') ) {
					d.classList.remove('visible');
				}
			}
		});

		$scope.dialogCloseTriggers.forEach(function(t) {
			t.onclick = function(e) {
				hideDialogs();
			}
		});

		function hideDialogs() {
			$scope.dialogs.forEach(function(d) {
				d.classList.remove('visible');
			});
		}

		// Make button visible on load
		setTimeout(function() {
			$scope.readBtn.className += ' visible';
		}, 20);

		// Read page
		$scope.readBtn.onclick = function(e) {
			e.preventDefault();
			requestRead();
		};

		// Request edit
		$scope.editBtn.onclick = function(e) {
			e.preventDefault();
			requestEditor();
		}

		// Request blacklist
		$scope.disableDialogTrigger.onclick = function(e) {
			e.preventDefault();

			$scope.quickAccessDisableDialog.classList.add('visible');
		}
	}

	function parsePage() {
		var doc = window.document.cloneNode(true),
			loc = document.location,
			uri = {
			  spec: loc.href,
			  host: loc.host,
			  prePath: loc.protocol + "//" + loc.host,
			  scheme: loc.protocol.substr(0, loc.protocol.indexOf(":")),
			  pathBase: loc.protocol + "//" + loc.host + loc.pathname.substr(0, loc.pathname.lastIndexOf("/") + 1)
			},
			result;

		result =  new Readability(uri, doc).parse();

		if(result) {
			$scope.parseResults = result;
			return result;
		}

		return false;
	}

	function requestRead() {

		// Send parsed text
		chrome.extension.sendMessage({
			action: 'requestRead',
			text: $scope.parseResults.content
		});
	}

	function requestEditor() {

		// Send parsed text
		chrome.extension.sendMessage({
			action: 'requestEdit'
		});
	}

	function addToBlacklist() {
		chrome.storage.sync.get('quickAccessBlacklist', function(res) {
			var blacklist = res.quickAccessBlacklist || [],
				currDomain = window.location.hostname;

			if( !blacklist.includes(currDomain) ) {
				blacklist.push(currDomain);
				chrome.storage.sync.set({ quickAccessBlacklist: blacklist });
			}
		});
	}

	function removeFromBlacklist() {
		chrome.storage.sync.get('quickAccessBlacklist', function(res) {
			var blacklist = res.quickAccessBlacklist || [],
				currDomain = window.location.hostname,
				currDomIndex = blacklist.indexOf(currDomain);

			if( currDomIndex !== -1 ) {
				blacklist.splice(currDomIndex, 1);
				chrome.storage.sync.set({ quickAccessBlacklist: blacklist });
			}
		});
	}

	// Communication with background script
	chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {

		// To prevent double injection of contentscript
		if(request.action === 'ping') {
			sendResponse({
				message: true
			});

		// When text is requested
		} else if(request.action === 'getParseData') {

			// $scope.parseResults was created on load
			if(!$scope.parseResults) {
				alert("Can't find any content to read.")
				return false;
			}

			sendResponse($scope.parseResults.content);

		} else if(request.action === 'showQuickAccess') {
			$scope.quickAccessContainer.classList.remove('hidden');

		} else if(request.action === 'hideQuickAccess') {
			$scope.quickAccessContainer.classList.add('hidden');

		} else if(request.action === 'readPage') {
			requestRead();

		}
	});

})();<commit_msg>Content script now opens editor if no readable text was found<commit_after>;(function() {

	var $scope = {};

	// As soon as the page has loaded, parse it
	parsePage();

	// If text was found, enable quick access
	if($scope.parseResults) {
		chrome.storage.sync.get(['quickAccessGlobal', 'quickAccessBlacklist'], function(res) {

			injectHTML();
			setupEventListeners();
			estimateParseTime();

			var blacklist = res.quickAccessBlacklist || [],
				isBlacklisted = blacklist.includes( window.location.hostname );

			if(res.quickAccessGlobal === false || isBlacklisted) {
				console.log(blacklist)
				$scope.quickAccessContainer.classList.add('hidden');
			}

		})
	}

	function injectHTML() {
		var html = '';

		html += '
';

		html += 	'';
		html +=			'
Read with Readio,
';
		html +=	 		'

';
		html +=		'';

		html += 	'';
		html +=			'
Open editor to paste text
';
		html +=	 		'

';
		html +=		'';

		html += 	'';
		html +=			'
Disable quick access buttons
';
		html +=	 		'

';
		html += 	'';

		html += '
';

		html += '
';
		html += 	'
';
		html +=	 		'
Hide quick access buttons
';
		html +=	 		'
';
		html +=	 			'All websites';
		html +=	 			' or ';
		html +=	 			''+ window.location.hostname +'';
		html +=	 			' or ';
		html +=	 			'cancel';
		html +=	 		'
';
		html += 	'
';
		html += '
';

		document.body.insertAdjacentHTML('afterbegin', html);
	}

	function estimateParseTime() {

		chrome.storage.sync.get('wpm', function(res) {
			var timeContainer = document.getElementById('sr-read-time-container'),

				words = $scope.parseResults.textContent.split(/\s+/g),
				wordCount = words.length,
				wpmOpt = res.wpm || 300, // Assuming 300 is default wpm

				wpm = (wordCount/wpmOpt) * 1.2, // Add 20% words, magic number to be more correct
				wpmRound = Math.floor(wpm),
				text = '';

			if(wpmRound < 1) {
				text = '<1 min';
			} else {
				text = wpmRound + ' min';
			}

			timeContainer.innerHTML = text;
		});
	}

	function setupEventListeners() {
		$scope.quickAccessContainer = document.getElementById('sr-qa-container');

		$scope.readBtn = document.getElementById('sr-qa-trigger-read');
		$scope.editBtn = document.getElementById('sr-qa-trigger-edit');
		$scope.disableDialogTrigger = document.getElementById('sr-qa-trigger-hide');

		$scope.disableEverywhereBtn = document.getElementById('sr-hide-qa-everywhere-button');
		$scope.disableJustHereBtn = document.getElementById('sr-hide-qa-justhere-button');

		$scope.dialogs = document.querySelectorAll('.sr-dialog-container');
		$scope.dialogCloseTriggers = document.querySelectorAll('.sr-dialog-close');

		$scope.quickAccessDisableDialog = document.getElementById('sr-hide-qa-dialog');

		$scope.disableEverywhereBtn.onclick = function() {
			chrome.storage.sync.set({ quickAccessGlobal : false });
			$scope.quickAccessContainer.classList.add('hidden');
			hideDialogs();
		}

		$scope.disableJustHereBtn.onclick = function() {
			addToBlacklist();
			$scope.quickAccessContainer.classList.add('hidden');
			hideDialogs();
		}

		$scope.dialogs.forEach(function(d) {
			d.onclick = function(e) {
				if( e.target.classList.contains('sr-dialog-container') ) {
					d.classList.remove('visible');
				}
			}
		});

		$scope.dialogCloseTriggers.forEach(function(t) {
			t.onclick = function(e) {
				hideDialogs();
			}
		});

		function hideDialogs() {
			$scope.dialogs.forEach(function(d) {
				d.classList.remove('visible');
			});
		}

		// Make button visible on load
		setTimeout(function() {
			$scope.readBtn.className += ' visible';
		}, 20);

		// Read page
		$scope.readBtn.onclick = function(e) {
			e.preventDefault();
			requestRead();
		};

		// Request edit
		$scope.editBtn.onclick = function(e) {
			e.preventDefault();
			requestEditor();
		}

		// Request blacklist
		$scope.disableDialogTrigger.onclick = function(e) {
			e.preventDefault();

			$scope.quickAccessDisableDialog.classList.add('visible');
		}
	}

	function parsePage() {
		var doc = window.document.cloneNode(true),
			loc = document.location,
			uri = {
			  spec: loc.href,
			  host: loc.host,
			  prePath: loc.protocol + "//" + loc.host,
			  scheme: loc.protocol.substr(0, loc.protocol.indexOf(":")),
			  pathBase: loc.protocol + "//" + loc.host + loc.pathname.substr(0, loc.pathname.lastIndexOf("/") + 1)
			},
			result;

		result =  new Readability(uri, doc).parse();

		if(result) {
			$scope.parseResults = result;
			return result;
		}

		return false;
	}

	function requestRead() {

		// If we found text to read, send it
		if($scope.parseResults && $scope.parseResults.content) {

			// Send parsed text
			chrome.extension.sendMessage({
				action: 'requestRead',
				text: $scope.parseResults.content
			});

		// Otherwise open editor
		} else {
			chrome.extension.sendMessage({
				action: 'requestEdit'
			});
		}
	}

	function requestEditor() {

		// Send parsed text
		chrome.extension.sendMessage({
			action: 'requestEdit'
		});
	}

	function addToBlacklist() {
		chrome.storage.sync.get('quickAccessBlacklist', function(res) {
			var blacklist = res.quickAccessBlacklist || [],
				currDomain = window.location.hostname;

			if( !blacklist.includes(currDomain) ) {
				blacklist.push(currDomain);
				chrome.storage.sync.set({ quickAccessBlacklist: blacklist });
			}
		});
	}

	function removeFromBlacklist() {
		chrome.storage.sync.get('quickAccessBlacklist', function(res) {
			var blacklist = res.quickAccessBlacklist || [],
				currDomain = window.location.hostname,
				currDomIndex = blacklist.indexOf(currDomain);

			if( currDomIndex !== -1 ) {
				blacklist.splice(currDomIndex, 1);
				chrome.storage.sync.set({ quickAccessBlacklist: blacklist });
			}
		});
	}

	// Communication with background script
	chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {

		// To prevent double injection of contentscript
		if(request.action === 'ping') {
			sendResponse({
				message: true
			});

		// When text is requested
		} else if(request.action === 'getParseData') {

			// $scope.parseResults was created on load
			if(!$scope.parseResults) {
				alert("Can't find any content to read.")
				return false;
			}

			sendResponse($scope.parseResults.content);

		} else if(request.action === 'showQuickAccess') {
			$scope.quickAccessContainer.classList.remove('hidden');

		} else if(request.action === 'hideQuickAccess') {
			$scope.quickAccessContainer.classList.add('hidden');

		} else if(request.action === 'readPage') {
			requestRead();

		}
	});

})();<|endoftext|>


<commit_before>const express = require('express')
const request = require('request')
const bodyParser = require('body-parser')
const path = require('path')

const app = express()
const port = process.env.PORT || 3000
const token = process.env.TOKEN || 'null'

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))

let wanted = require('./wanted.js')
let hint = require('./hint.js')
let map = require('./map.js')

let chanel =
`章魚單車頻道：4747
御魂拾層頻道：1010
碎片挑戰頻道：818 (桃花/鐮鼬)
覺醒材料頻道：886
懸賞交換頻道：1700`
let help =
`懸賞 大天狗 - 顯示大天狗的分布情形
線索 蒲公英 - 顯示線索為蒲公英的目標，多個線索請以空白分隔
副本 第六章 - 顯示副本第六章的分布與金錢經驗掉落
圖鑑 螢草 - 顯示螢草的圖鑑資料
頻道 - 顯示特定用途的頻道代碼
留言 Bug - 對開發者留下訊息，例如報錯
幫助 - 顯示本訊息`
let autoReply =
`已將您的留言紀錄，但開發者不一定會回覆，請見諒`
let cmdNotFound =
`無法辨識指令，輸入 幫助 查看哪些指令可以用`

app.post('/in', (req, res) => {
  let data = req.body
  if (data.object === 'page') {
    data.entry.forEach((entry) => {
      entry.messaging.forEach((event) => {
        if (event.message) {
          let reply = looker(event.message.text)
          reply.forEach((msg) => {
            sendMsg(event.sender.id, msg)
          })
        } else { console.log(' Error ') }
      })
    })
  }
  res.sendStatus(200)
})

app.get('/pp.html', (req, res) => {
  res.sendFile(path.join(__dirname, 'pp.html'))
})

app.get('/in', (req, res) => {
  if (req.query['hub.mode'] === 'subscribe') {
    if (req.query['hub.verify_token'] === 'YalaBomm') res.send(req.query['hub.challenge'])
    else res.status(403)
  }
})

app.all('/', (req, res) => {
  res.sendStatus(403)
})

function looker (input) {
  let spilt = input.match(/\S+/g)
  let reply = []
  switch (spilt[0]) {
    case '幫助':
      reply = reply.concat(help)
      break
    case '懸賞':
      reply = reply.concat(wanted[spilt[1]] || '查無資料，請確定目標名稱正確，查詢線索請使用 線索 (條件)')
      break
    case '副本':
      reply = reply.concat(mapLooker(spilt) || '查無資料，請確定目標名稱正確')
      break
    case '圖鑑':
      reply = reply.concat(illLooker(spilt[1]))
      break
    case '線索':
      reply = reply.concat(wantedLooker(spilt))
      break
    case '頻道':
      reply = reply.concat(chanel)
      break
    case '留言':
      comment(input)
      reply = reply.concat(autoReply)
      break
    default:
      reply = reply.concat(cmdNotFound)
  }
  return reply
}

function wantedLooker (dex) {
  let result = []
  dex.splice(0, 1)
  if (dex[0]) {
    let mat = hint[dex[0]]
    if (dex.length > 1) {
      dex.forEach((clue) => {
        let tmp = hint[clue]
        mat.forEach((sp) => {
          if (!(sp in tmp)) { mat.splice(mat.indexOf(sp), 1) }
        })
      })
    }
    result = result.concat('查詢結果為: ' + (mat.join(',') || '無資料'))
    if (mat.length === 1) { result = result.concat(wanted[mat[0]]) }
  } else { result = result.concat('沒有給予條件') }
  return result
}

let chint = '一二三四五六七八九十'

function mapLooker (dex) {
  let result = []
  dex.splice(0, 1)
  if (dex[0]) {
    let mapID
    map.alias.forEach((alias) => {
      if (dex[0] in alias) {
        mapID = alias[0]
      }
    })
    if (!mapID) {
      map.alias.forEach((alias) => {
        (function () {
          alias.forEach((name) => {
            if (dex[0].match(name)) {
              mapID = alias[0]
              if (isNaN(dex[1])) {
                mapID += dex[1]
              console.log(mapID)
              } else {
                mapID += chint.indexOf(dex[1]) + 1
              }
              return 0
            }
          })
        })()
      })
    }
    result = result.concat(map.data[mapID] || '查無資料，若查詢御魂請以空白間隔層數（如：御魂 10），秘聞尚無資料')
  } else {
    result = result.concat('沒有給予條件')
  }
  return result
}

function illLooker (dex) {
  let result = []
  dex.splice(0, 1)
  if (dex[0]) {
    result = result.concat(ill[dex[0]] || '查無資料，請輸入式神全名（大天狗 ✔；狗狗 ✗)')
  } else {
    result = result.concat('沒有給予條件')
  }
  return result
}

function sendMsg (sender, message, isImg = false) {
  request({
    uri: 'https://graph.facebook.com/v2.6/me/messages',
    qs: { access_token: token },
    method: 'POST',
    json: {
      recipient: { id: sender },
      message: isImg ? {attachment: { type: 'image', payload: message }} : { text: message }
    }
  })
}

function comment (input) {
  sendMsg(process.env.DEVID, input)
}

app.listen(port, () => { console.log(`Listening to ${port}`) })
<commit_msg>Fixed Map<commit_after>const express = require('express')
const request = require('request')
const bodyParser = require('body-parser')
const path = require('path')

const app = express()
const port = process.env.PORT || 3000
const token = process.env.TOKEN || 'null'

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))

let wanted = require('./wanted.js')
let hint = require('./hint.js')
let map = require('./map.js')

let chanel =
`章魚單車頻道：4747
御魂拾層頻道：1010
碎片挑戰頻道：818 (桃花/鐮鼬)
覺醒材料頻道：886
懸賞交換頻道：1700`
let help =
`懸賞 大天狗 - 顯示大天狗的分布情形
線索 蒲公英 - 顯示線索為蒲公英的目標，多個線索請以空白分隔
副本 第六章 - 顯示副本第六章的分布與金錢經驗掉落
圖鑑 螢草 - 顯示螢草的圖鑑資料
頻道 - 顯示特定用途的頻道代碼
留言 Bug - 對開發者留下訊息，例如報錯
幫助 - 顯示本訊息`
let autoReply =
`已將您的留言紀錄，但開發者不一定會回覆，請見諒`
let cmdNotFound =
`無法辨識指令，輸入 幫助 查看哪些指令可以用`

app.post('/in', (req, res) => {
  let data = req.body
  if (data.object === 'page') {
    data.entry.forEach((entry) => {
      entry.messaging.forEach((event) => {
        if (event.message) {
          let reply = looker(event.message.text)
          reply.forEach((msg) => {
            sendMsg(event.sender.id, msg)
          })
        } else { console.log(' Error ') }
      })
    })
  }
  res.sendStatus(200)
})

app.get('/pp.html', (req, res) => {
  res.sendFile(path.join(__dirname, 'pp.html'))
})

app.get('/in', (req, res) => {
  if (req.query['hub.mode'] === 'subscribe') {
    if (req.query['hub.verify_token'] === 'YalaBomm') res.send(req.query['hub.challenge'])
    else res.status(403)
  }
})

app.all('/', (req, res) => {
  res.sendStatus(403)
})

function looker (input) {
  let spilt = input.match(/\S+/g)
  let reply = []
  switch (spilt[0]) {
    case '幫助':
      reply = reply.concat(help)
      break
    case '懸賞':
      reply = reply.concat(wanted[spilt[1]] || '查無資料，請確定目標名稱正確，查詢線索請使用 線索 (條件)')
      break
    case '副本':
      reply = reply.concat(mapLooker(spilt) || '查無資料，請確定目標名稱正確')
      break
    case '圖鑑':
      reply = reply.concat(illLooker(spilt[1]))
      break
    case '線索':
      reply = reply.concat(wantedLooker(spilt))
      break
    case '頻道':
      reply = reply.concat(chanel)
      break
    case '留言':
      comment(input)
      reply = reply.concat(autoReply)
      break
    default:
      reply = reply.concat(cmdNotFound)
  }
  return reply
}

function wantedLooker (dex) {
  let result = []
  dex.splice(0, 1)
  if (dex[0]) {
    let mat = hint[dex[0]]
    if (dex.length > 1) {
      dex.forEach((clue) => {
        let tmp = hint[clue]
        mat.forEach((sp) => {
          if (!(sp in tmp)) { mat.splice(mat.indexOf(sp), 1) }
        })
      })
    }
    result = result.concat('查詢結果為: ' + (mat.join(',') || '無資料'))
    if (mat.length === 1) { result = result.concat(wanted[mat[0]]) }
  } else { result = result.concat('沒有給予條件') }
  return result
}

let chint = '一二三四五六七八九十'

function mapLooker (dex) {
  let result = []
  dex.splice(0, 1)
  if (dex[0]) {
    let mapID
    map.alias.forEach((alias) => {
      if (dex[0] in alias) {
        mapID = alias[0]
      }
    })
    if (!mapID) {
      map.alias.forEach((alias) => {
        (function () {
          alias.forEach((name) => {
            if (dex[0].match(name)) {
              mapID = alias[0]
              if (!isNaN(dex[1])) {
                mapID += dex[1]
              } else {
                mapID += chint.indexOf(dex[1]) + 1
              }
              return 0
            }
          })
        })()
      })
    }
    result = result.concat(map.data[mapID] || '查無資料，若查詢御魂請以空白間隔層數（如：御魂 10），秘聞尚無資料')
  } else {
    result = result.concat('沒有給予條件')
  }
  return result
}

function illLooker (dex) {
  let result = []
  dex.splice(0, 1)
  if (dex[0]) {
    result = result.concat(ill[dex[0]] || '查無資料，請輸入式神全名（大天狗 ✔；狗狗 ✗)')
  } else {
    result = result.concat('沒有給予條件')
  }
  return result
}

function sendMsg (sender, message, isImg = false) {
  request({
    uri: 'https://graph.facebook.com/v2.6/me/messages',
    qs: { access_token: token },
    method: 'POST',
    json: {
      recipient: { id: sender },
      message: isImg ? {attachment: { type: 'image', payload: message }} : { text: message }
    }
  })
}

function comment (input) {
  sendMsg(process.env.DEVID, input)
}

app.listen(port, () => { console.log(`Listening to ${port}`) })
<|endoftext|>


<commit_before>'use strict';

// Create HTTP server and proxy

var express = require('express');
var proxy   = require('http-proxy').createProxyServer({});
var app     = express();

// Initialize constants

var oneDay   = 86400000;

// Set routes

app.use('/app',             express.static(__dirname + '/app'));
app.use('/scbd-templates',  express.static(__dirname + '/app/libs/scbd-angularjs-controls/scbd-templates'));
app.use('/cbd-forums',      express.static(__dirname + '/app/libs/cbd-forums'));
app.use('/favicon.ico',     express.static(__dirname + '/favicon.ico', { maxAge: oneDay }));

app.all('/app/*', function(req, res) { res.status(404).send(); } );

app.get('/app/absPDFViewer/*'   , function(req, res) {
	res.sendFile(__dirname + '/app/absPDFViewer/absPermitPrint.html');
});

// app.all('/api/v2013/documents/*', function(req, res) { proxy.web(req, res, { target: 'http://192.168.78.193', secure: false } ); } );
app.all('/api/*', (req, res) => proxy.web(req, res, { target: 'https://api.cbddev.xyz', changeOrigin: true }));

// Configure index.html

app.get('/*', function (req, res) {
    res.cookie('VERSION', process.env.VERSION);
    res.sendFile(__dirname + '/app/template.html');
});

// Start server

app.listen(process.env.PORT || 2010, function () {
	console.log('Server listening on %j', this.address());
});

proxy.on('error', function(err) {
}); // ignore proxy errors

process.on('SIGTERM', ()=>process.exit());
<commit_msg>use secured false for dev api (temp)<commit_after>'use strict';

// Create HTTP server and proxy

var express = require('express');
var proxy   = require('http-proxy').createProxyServer({});
var app     = express();

// Initialize constants

var oneDay   = 86400000;

// Set routes

app.use('/app',             express.static(__dirname + '/app'));
app.use('/scbd-templates',  express.static(__dirname + '/app/libs/scbd-angularjs-controls/scbd-templates'));
app.use('/cbd-forums',      express.static(__dirname + '/app/libs/cbd-forums'));
app.use('/favicon.ico',     express.static(__dirname + '/favicon.ico', { maxAge: oneDay }));

app.all('/app/*', function(req, res) { res.status(404).send(); } );

app.get('/app/absPDFViewer/*'   , function(req, res) {
	res.sendFile(__dirname + '/app/absPDFViewer/absPermitPrint.html');
});

// app.all('/api/v2013/documents/*', function(req, res) { proxy.web(req, res, { target: 'http://192.168.78.193', secure: false } ); } );
app.all('/api/*', (req, res) => proxy.web(req, res, { target: 'https://api.cbddev.xyz', changeOrigin: true, secure:false }));

// Configure index.html

app.get('/*', function (req, res) {
    res.cookie('VERSION', process.env.VERSION);
    res.sendFile(__dirname + '/app/template.html');
});

// Start server

app.listen(process.env.PORT || 2010, function () {
	console.log('Server listening on %j', this.address());
});

proxy.on('error', function(err) {
}); // ignore proxy errors

process.on('SIGTERM', ()=>process.exit());
<|endoftext|>


<commit_before><commit_msg>Linked c++ api<commit_after>'use strict';

module.exports = require('bindings')('addon');
<|endoftext|>


<commit_before>var eslint = require('eslint');
var through = require('through');
var error = console.error.bind(console);

function lint(file, options) {
    options = options || {};

    var cli = new eslint.CLIEngine(options);
    var formatter = cli.getFormatter(options.formatter || __dirname + '/node_modules/eslint-friendly-formatter');
    var data = '';

    function write(buf) {
        data += buf;
    }

    function end() {
        var results = cli.executeOnText(data, file).results;

        if (results.length && results.some(function (r) { return r.errorCount || r.warningCount; })) {
            error(formatter(results));
        }

        var errorResults = eslint.CLIEngine.getErrorResults(results);
        if (errorResults.length && !options.continuous) {
            this.emit('error', 'eslintify: linting error(s) detected.');
        }

        this.queue(data);
        this.queue(null);
    }

    if (typeof file !== 'string' || file.lastIndexOf('.') === -1) {
        return through();
    }

    var givenExtension = file.slice(file.lastIndexOf('.') + 1, file.length);
    var supportedExtensions = ['js', 'jsx', 'es6'];

    if (options.extension) { supportedExtensions = supportedExtensions.concat(options.extension); }
    if (options.extensions) { supportedExtensions = supportedExtensions.concat(options.extensions); }

    if (supportedExtensions.indexOf(givenExtension) !== -1) {
        return through(write, end);
    }

    return through();
}

module.exports = lint;
<commit_msg>Fix formatter resolution<commit_after>var eslint = require('eslint');
var through = require('through');
var error = console.error.bind(console);

function lint(file, options) {
    options = options || {};

    var cli = new eslint.CLIEngine(options);
    var formatter = cli.getFormatter(options.formatter || require.resolve('eslint-friendly-formatter'));
    var data = '';

    function write(buf) {
        data += buf;
    }

    function end() {
        var results = cli.executeOnText(data, file).results;

        if (results.length && results.some(function (r) { return r.errorCount || r.warningCount; })) {
            error(formatter(results));
        }

        var errorResults = eslint.CLIEngine.getErrorResults(results);
        if (errorResults.length && !options.continuous) {
            this.emit('error', 'eslintify: linting error(s) detected.');
        }

        this.queue(data);
        this.queue(null);
    }

    if (typeof file !== 'string' || file.lastIndexOf('.') === -1) {
        return through();
    }

    var givenExtension = file.slice(file.lastIndexOf('.') + 1, file.length);
    var supportedExtensions = ['js', 'jsx', 'es6'];

    if (options.extension) { supportedExtensions = supportedExtensions.concat(options.extension); }
    if (options.extensions) { supportedExtensions = supportedExtensions.concat(options.extensions); }

    if (supportedExtensions.indexOf(givenExtension) !== -1) {
        return through(write, end);
    }

    return through();
}

module.exports = lint;
<|endoftext|>


<commit_before>var express = require('express');
var request = require('request');
var apiUrl = "https://apps.ininsca.com";

var app = express();
app.use('/api', function (req, res) {
    var url = apiUrl + req.url;
    req.pipe(request(url)).pipe(res);
});

var server = app.listen(3000, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log('Example app listening at http://%s:%s', host, port);
});
<commit_msg>setup server to pass ui requests to broccoli server, easier than setting up static resource hosting with file watching in the server<commit_after>var express = require('express');
var request = require('request');
var apiUrl = "https://apps.ininsca.com";
var uiUrl = "http://localhost:4200";

var app = express();
app.use('/api', function (req, res) {
    var url = apiUrl + req.url;
    req.pipe(request(url)).pipe(res);
});
app.use('/ui', function (req, res) {
    var url = uiUrl + req.url;
    req.pipe(request(url)).pipe(res);
});

var server = app.listen(3000, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log('Example app listening at http://%s:%s', host, port);
});
<|endoftext|>


<commit_before>if (typeof(factmint) === "undefined") window['factmint'] = {};
factmint.mock = function(object, tools) {
  var mock = new Function();
  mock._invocationCounts = {};
  mock._invocationCallbacks = {};
  mock._readCounts = {};
  mock._readCallbacks = {};
  mock._changeCounts = {};
  mock._writeCallbacks = {};
  mock._methods = [];
  mock._members = [];

  var registerMember = function(memberName) {
    console.log("MOCK [DEBUG] - registering member " + memberName);

    mock._readCounts[memberName] = 0;
    mock._changeCounts[memberName] = 0;

    mock.__defineGetter__(memberName, function() {
      console.log("MOCK [INFO] - getting " + memberName);

      mock._readCounts[memberName]++;

      if (mock._readCallbacks[memberName] instanceof Function) {
        mock._readCallbacks[memberName](object[memberName]);
      }

      return object[memberName];
    });
    mock.__defineSetter__(memberName, function(newValue) {
      console.log("MOCK [INFO] - setting " + memberName);

      if (object[memberName] != newValue) {
        mock._changeCounts[memberName]++;
      }

      if (mock._writeCallbacks[memberName] instanceof Function) {
        mock._writeCallbacks[memberName](newValue);
      }

      object[memberName] = newValue;
    });
  };

  var registerMethod = function(methodName) {
    console.log("MOCK [DEBUG] - registering method " + methodName);

    mock._invocationCounts[methodName] = {
      all: 0,
      arguments: {}
    };

    mock[methodName] = function() {
      console.log("MOCK [INFO] - Verifying execution of " + methodName);

      var result = object[methodName].apply(object, arguments);
      mock._invocationCounts[methodName].all++;

      var argumentsKey = JSON.stringify(arguments);
      if (! mock._invocationCounts[methodName][argumentsKey]) {
        mock._invocationCounts[methodName][argumentsKey] = 1;
      } else {
        mock._invocationCounts[methodName][argumentsKey]++;
      }

      if (mock._invocationCallbacks[methodName] instanceof Function) {
        mock._invocationCallbacks[methodName](result, mock._invocationCounts[methodName]);
      }
    };
  };

  for (var member in object) {
    if (object[member] instanceof Function) {
      registerMethod(member);
      mock._methods.push(member);
    } else {
      registerMember(member);
      mock._members.push(member);
    }
  }

  return mock;
};

factmint.verify = function(mock) {
  var verify = {};

  mock._members.forEach(function(memberName) {
    verify[memberName] = {
      hasBeenRead: function(comparison) {
        if (comparison instanceof Function) {
          return comparison(mock._readCounts[memberName]);
        } else if (typeof(comparison) == "number") {
          return (comparison == mock._readCounts[memberName]);
        } else if (! comparison) {
          return mock._readCounts[memberName] > 0;
        }
      },
      checkGets: function(callback) {
        mock._readCallbacks[memberName] = callback;
      },
      hasBeenChanged: function(comparison) {
        if (comparison instanceof Function) {
          return comparison(mock._changeCounts[memberName]);
        } else if (typeof(comparison) == "number") {
          return (comparison == mock._changeCounts[memberName]);
        } else if (! comparison) {
          return mock._changeCounts[memberName] > 0;
        }
      },
      checkSets: function(callback) {
        mock._writeCallbacks[memberName] = callback;
      }
    };
  });

  mock._methods.forEach(function(methodName) {
    verify[methodName] = {
      hasBeenInvoked: function(comparison) {
        if (comparison instanceof Function) {
          return comparison(mock._invocationCounts[methodName].all);
        } else if (typeof(comparison) == "number") {
          return (comparison == mock._invocationCounts[methodName].all);
        } else if (! comparison) {
          return mock._invocationCounts[methodName].all > 0;
        }
      },
      withArguments: function() {
		var invocationArguments = JSON.stringify(arguments);
        return {
          hasBeenInvoked: function(comparison) {
            if (comparison instanceof Function) {
              return comparison(mock._invocationCounts[methodName][invocationArguments]);
            } else if (typeof(comparison) == "number") {
              if (comparison == 0 && typeof(mock._invocationCounts[methodName][invocationArguments]) === "undefined") {
                return true;
              }

              return (comparison == mock._invocationCounts[methodName][invocationArguments]);
            } else if (! comparison) {
              return mock._invocationCounts[methodName][invocationArguments] > 0;
            }
          }
        }
      },
      checkInvocations: function(callback) {
        mock._invocationCallbacks[methodName] = callback;
      }
    };
  });

  return verify;
}
<commit_msg>Returned the return value of mocked methods - it was being swallowed<commit_after>if (typeof(factmint) === "undefined") window['factmint'] = {};
factmint.mock = function(object, tools) {
  var mock = new Function();
  mock._invocationCounts = {};
  mock._invocationCallbacks = {};
  mock._readCounts = {};
  mock._readCallbacks = {};
  mock._changeCounts = {};
  mock._writeCallbacks = {};
  mock._methods = [];
  mock._members = [];

  var registerMember = function(memberName) {
    console.log("MOCK [DEBUG] - registering member " + memberName);

    mock._readCounts[memberName] = 0;
    mock._changeCounts[memberName] = 0;

    mock.__defineGetter__(memberName, function() {
      console.log("MOCK [INFO] - getting " + memberName);

      mock._readCounts[memberName]++;

      if (mock._readCallbacks[memberName] instanceof Function) {
        mock._readCallbacks[memberName](object[memberName]);
      }

      return object[memberName];
    });
    mock.__defineSetter__(memberName, function(newValue) {
      console.log("MOCK [INFO] - setting " + memberName);

      if (object[memberName] != newValue) {
        mock._changeCounts[memberName]++;
      }

      if (mock._writeCallbacks[memberName] instanceof Function) {
        mock._writeCallbacks[memberName](newValue);
      }

      object[memberName] = newValue;
    });
  };

  var registerMethod = function(methodName) {
    console.log("MOCK [DEBUG] - registering method " + methodName);

    mock._invocationCounts[methodName] = {
      all: 0,
      arguments: {}
    };

    mock[methodName] = function() {
      console.log("MOCK [INFO] - Verifying execution of " + methodName);

      var result = object[methodName].apply(object, arguments);
      mock._invocationCounts[methodName].all++;

      var argumentsKey = JSON.stringify(arguments);
      if (! mock._invocationCounts[methodName][argumentsKey]) {
        mock._invocationCounts[methodName][argumentsKey] = 1;
      } else {
        mock._invocationCounts[methodName][argumentsKey]++;
      }

      if (mock._invocationCallbacks[methodName] instanceof Function) {
        mock._invocationCallbacks[methodName](result, mock._invocationCounts[methodName]);
      }

      return result;
    };
  };

  for (var member in object) {
    if (object[member] instanceof Function) {
      registerMethod(member);
      mock._methods.push(member);
    } else {
      registerMember(member);
      mock._members.push(member);
    }
  }

  return mock;
};

factmint.verify = function(mock) {
  var verify = {};

  mock._members.forEach(function(memberName) {
    verify[memberName] = {
      hasBeenRead: function(comparison) {
        if (comparison instanceof Function) {
          return comparison(mock._readCounts[memberName]);
        } else if (typeof(comparison) == "number") {
          return (comparison == mock._readCounts[memberName]);
        } else if (! comparison) {
          return mock._readCounts[memberName] > 0;
        }
      },
      checkGets: function(callback) {
        mock._readCallbacks[memberName] = callback;
      },
      hasBeenChanged: function(comparison) {
        if (comparison instanceof Function) {
          return comparison(mock._changeCounts[memberName]);
        } else if (typeof(comparison) == "number") {
          return (comparison == mock._changeCounts[memberName]);
        } else if (! comparison) {
          return mock._changeCounts[memberName] > 0;
        }
      },
      checkSets: function(callback) {
        mock._writeCallbacks[memberName] = callback;
      }
    };
  });

  mock._methods.forEach(function(methodName) {
    verify[methodName] = {
      hasBeenInvoked: function(comparison) {
        if (comparison instanceof Function) {
          return comparison(mock._invocationCounts[methodName].all);
        } else if (typeof(comparison) == "number") {
          return (comparison == mock._invocationCounts[methodName].all);
        } else if (! comparison) {
          return mock._invocationCounts[methodName].all > 0;
        }
      },
      withArguments: function() {
		var invocationArguments = JSON.stringify(arguments);
        return {
          hasBeenInvoked: function(comparison) {
            if (comparison instanceof Function) {
              return comparison(mock._invocationCounts[methodName][invocationArguments]);
            } else if (typeof(comparison) == "number") {
              if (comparison == 0 && typeof(mock._invocationCounts[methodName][invocationArguments]) === "undefined") {
                return true;
              }

              return (comparison == mock._invocationCounts[methodName][invocationArguments]);
            } else if (! comparison) {
              return mock._invocationCounts[methodName][invocationArguments] > 0;
            }
          }
        }
      },
      checkInvocations: function(callback) {
        mock._invocationCallbacks[methodName] = callback;
      }
    };
  });

  return verify;
}
<|endoftext|>


<commit_before>'use strict';

var isFunction   = require('es5-ext/lib/Function/is-function')
  , d            = require('es5-ext/lib/Object/descriptor')
  , forEach      = require('es5-ext/lib/Object/for-each')
  , startsWith   = require('es5-ext/lib/String/prototype/starts-with')
  , nameRe       = require('./name-re')
  , RelTransport = require('./rel-transport')

  , create = Object.create, defineProperty = Object.defineProperty
  , defineProperties = Object.defineProperties
  , getOwnPropertyNames = Object.getOwnPropertyNames
  , getPrototypeOf = Object.getPrototypeOf

  , Relation, RelSetItem, define, abstractLock, Plain, propsValidator;

propsValidator = function (obj, props, cb, errors, prefix) {
	var error;
	forEach(props, function (value, name) {
		if ((error = cb.call(obj, name, value))) {
			if (!errors) errors = {};
			errors[(prefix || '') + name] = error;
		}
	});
	return errors;
};

module.exports = Plain = defineProperties(function () {}, {
	create: d('c', function (constructor, nsProps, objProps) {
		var error, isAbstract = abstractLock;
		abstractLock = false;

		// Normalize arguments
		if (!isFunction(constructor)) {
			objProps = nsProps;
			nsProps = constructor;
			constructor = null;
		}

		// Validate
		if (nsProps) {
			error = this.validatePropertiesNew(nsProps);
			if (!isAbstract) {
				error = this.validateUndefinedNew(nsProps, error && error.subErrors);
			}
		}
		if (objProps) {
			error = this.prototype.validatePropertiesNew(objProps,
				error && error.subErrors, 'prototype.');
		}
		if (error) throw error;

		// Construct & Return
		if (!constructor) constructor = eval('(' + String(this) + ')');
		constructor.__proto__ = this;
		constructor.prototype = create(this.prototype);
		defineProperty(constructor.prototype, 'constructor', d(constructor));

		if (nsProps) {
			forEach(nsProps, function (value, name) {
				constructor.set(name, value);
			});
		}
		if (objProps) {
			forEach(objProps, function (value, name) {
				this.set(name, value);
			}, constructor.prototype);
		}
		return constructor;
	}),
	abstract: d('c', function (name, constructor, nsProps, objProps) {
		abstractLock = true;
		try {
			return this.create.apply(this, arguments);
		} finally {
			abstractLock = false;
		}
	}),
	set: d('c', function (name, value) {
		if (!nameRe.test(name)) {
			throw new Error("'" + name + "' is not valid property name");
		}

		if ((name in this) && (('_$' + name) in this)) { //jslint: skip
			// Defined value, set directly
			return (this[name] = value);
		}
		return define(this, name, value);
	}),
	setMany: d('c', function (props) {
		var error = this.validateProperties(props);
		if (error) throw error;
		forEach(props, function (value, name) { this.set(name, value); }, this);
	}),
	validateProperty: d('c', function (name, value) {
		var relName;
		if (!nameRe.test(name)) {
			return new Error("'" + name + "' is not valid property name");
		}

		if (value instanceof RelTransport) {
			return value.validate();
		} else if ((name in this) && //jslint: skip
				((relName = ('_$' + name)) in this)) {
			// Defined value
			if (value === undefined) {
				if (this.hasOwnProperty(relName)) return this[relName].validate(value);
				if (this[relName].required && (this[relName]._value == null)) {
					return new TypeError(value + " is not a value");
				}
			}
			return this[relName].validate(value);
		}
	}),
	validateProperties: d('c', function (props, errors) {
		var error;
		errors = propsValidator(this, props, this.validateProperty, errors);
		if (errors) {
			error = new TypeError("Invalid properties data");
			error.subErrors = errors;
			return error;
		}
	}),
	validateUndefinedNew: d('c', function (props, errors) {
		var prop, proto = this, done = {}, iterate, error, propName;
		iterate = function (name) {
			if (done[name]) return;
			done[name] = true;
			if (!startsWith.call(name, '_$') ||
					(props && props.hasOwnProperty(propName = name.slice(2)) &&
						(props[propName] != null))) {
				return;
			}
			prop = proto[name];
			if (!prop || !prop._$required) return;
			if (prop._$required._value && (prop._value == null)) {
				if (!errors) errors = {};
				errors[propName] =
					new TypeError("Missing value for '" + propName + "'");
			}
		};
		while (proto !== Object.prototype) {
			getOwnPropertyNames(proto).forEach(iterate);
			proto = getPrototypeOf(proto);
		}
		if (errors) {
			error = new TypeError("Invalid properties data");
			error.subErrors = errors;
			return error;
		}
	}),
	validatePropertiesNew: d('c', function (props, errors, prefix) {
		var error;
		errors = propsValidator(this, props, function (name, value) {
			var relName;
			if (value === undefined) {
				if (!nameRe.test(name)) {
					return new Error("'" + name + "' is not valid property name");
				}
				if (this[relName = '_$' + name] && this[relName].required &&
						(this[relName]._value == null)) {
					return new TypeError(value + " is not a value");
				}
			} else {
				return this.validateProperty(name, value);
			}
		}, errors, prefix);
		if (errors) {
			error = new TypeError("Invalid properties data");
			error.subErrors = errors;
			return error;
		}
	})
});
defineProperties(Plain.prototype, {
	set: d('c', Plain.set),
	validateProperty: d('c', Plain.validateProperty),
	setMany: d('c', Plain.setMany),
	validateProperties: d('c', Plain.validateProperties),
	validatePropertiesNew: d('c', Plain.validatePropertiesNew),
	validateUndefinedNew: d('c', Plain.validateUndefinedNew)
});

// Define relation
Relation = require('./relation');

define = require('./define');

define(Relation.prototype, 'required');
define(Relation.prototype, 'multiple');
Relation.prototype._required.value = false;
Relation.prototype._required.required = true;
Relation.prototype._multiple.value = false;
Relation.prototype._multiple.required = true;
RelSetItem = require('./rel-set-item');
define(RelSetItem.prototype, 'order');
<commit_msg>Consistency and readability<commit_after>'use strict';

var isFunction   = require('es5-ext/lib/Function/is-function')
  , d            = require('es5-ext/lib/Object/descriptor')
  , forEach      = require('es5-ext/lib/Object/for-each')
  , startsWith   = require('es5-ext/lib/String/prototype/starts-with')
  , nameRe       = require('./name-re')
  , RelTransport = require('./rel-transport')

  , create = Object.create, defineProperty = Object.defineProperty
  , defineProperties = Object.defineProperties
  , getOwnPropertyNames = Object.getOwnPropertyNames
  , getPrototypeOf = Object.getPrototypeOf

  , Relation, RelSetItem, define, abstractLock, Plain, propsValidator;

propsValidator = function (obj, props, cb, errors, prefix) {
	var error;
	forEach(props, function (value, name) {
		if ((error = cb.call(obj, name, value))) {
			if (!errors) errors = {};
			errors[(prefix || '') + name] = error;
		}
	});
	return errors;
};

module.exports = Plain = defineProperties(function () {}, {
	create: d('c', function (constructor, nsProps, objProps) {
		var error, isAbstract = abstractLock;
		abstractLock = false;

		// Normalize arguments
		if (!isFunction(constructor)) {
			objProps = nsProps;
			nsProps = constructor;
			constructor = null;
		}

		// Validate
		if (nsProps) {
			error = this.validatePropertiesNew(nsProps);
			if (!isAbstract) {
				error = this.validateUndefinedNew(nsProps, error && error.subErrors);
			}
		}
		if (objProps) {
			error = this.prototype.validatePropertiesNew(objProps,
				error && error.subErrors, 'prototype.');
		}
		if (error) throw error;

		// Construct & Return
		if (!constructor) constructor = eval('(' + String(this) + ')');
		constructor.__proto__ = this;
		constructor.prototype = create(this.prototype);
		defineProperty(constructor.prototype, 'constructor', d(constructor));

		if (nsProps) {
			forEach(nsProps, function (value, name) {
				this.set(name, value);
			}, constructor);
		}
		if (objProps) {
			forEach(objProps, function (value, name) {
				this.set(name, value);
			}, constructor.prototype);
		}
		return constructor;
	}),
	abstract: d('c', function (name, constructor, nsProps, objProps) {
		abstractLock = true;
		try {
			return this.create.apply(this, arguments);
		} finally {
			abstractLock = false;
		}
	}),
	set: d('c', function (name, value) {
		if (!nameRe.test(name)) {
			throw new Error("'" + name + "' is not valid property name");
		}

		if ((name in this) && (('_$' + name) in this)) { //jslint: skip
			// Defined value, set directly
			return (this[name] = value);
		}
		return define(this, name, value);
	}),
	setMany: d('c', function (props) {
		var error = this.validateProperties(props);
		if (error) throw error;
		forEach(props, function (value, name) { this.set(name, value); }, this);
	}),
	validateProperty: d('c', function (name, value) {
		var relName;
		if (!nameRe.test(name)) {
			return new Error("'" + name + "' is not valid property name");
		}

		if (value instanceof RelTransport) {
			return value.validate();
		} else if ((name in this) && //jslint: skip
				((relName = ('_$' + name)) in this)) {
			// Defined value
			if (value === undefined) {
				if (this.hasOwnProperty(relName)) return this[relName].validate(value);
				if (this[relName].required && (this[relName]._value == null)) {
					return new TypeError(value + " is not a value");
				}
			}
			return this[relName].validate(value);
		}
	}),
	validateProperties: d('c', function (props, errors) {
		var error;
		errors = propsValidator(this, props, this.validateProperty, errors);
		if (errors) {
			error = new TypeError("Invalid properties data");
			error.subErrors = errors;
			return error;
		}
	}),
	validateUndefinedNew: d('c', function (props, errors) {
		var prop, proto = this, done = {}, iterate, error, propName;
		iterate = function (name) {
			if (done[name]) return;
			done[name] = true;
			if (!startsWith.call(name, '_$') ||
					(props && props.hasOwnProperty(propName = name.slice(2)) &&
						(props[propName] != null))) {
				return;
			}
			prop = proto[name];
			if (!prop || !prop._$required) return;
			if (prop._$required._value && (prop._value == null)) {
				if (!errors) errors = {};
				errors[propName] =
					new TypeError("Missing value for '" + propName + "'");
			}
		};
		while (proto !== Object.prototype) {
			getOwnPropertyNames(proto).forEach(iterate);
			proto = getPrototypeOf(proto);
		}
		if (errors) {
			error = new TypeError("Invalid properties data");
			error.subErrors = errors;
			return error;
		}
	}),
	validatePropertiesNew: d('c', function (props, errors, prefix) {
		var error;
		errors = propsValidator(this, props, function (name, value) {
			var relName;
			if (value === undefined) {
				if (!nameRe.test(name)) {
					return new Error("'" + name + "' is not valid property name");
				}
				if (this[relName = '_$' + name] && this[relName].required &&
						(this[relName]._value == null)) {
					return new TypeError(value + " is not a value");
				}
			} else {
				return this.validateProperty(name, value);
			}
		}, errors, prefix);
		if (errors) {
			error = new TypeError("Invalid properties data");
			error.subErrors = errors;
			return error;
		}
	})
});
defineProperties(Plain.prototype, {
	set: d('c', Plain.set),
	validateProperty: d('c', Plain.validateProperty),
	setMany: d('c', Plain.setMany),
	validateProperties: d('c', Plain.validateProperties),
	validatePropertiesNew: d('c', Plain.validatePropertiesNew),
	validateUndefinedNew: d('c', Plain.validateUndefinedNew)
});

// Define relation
Relation = require('./relation');

define = require('./define');

define(Relation.prototype, 'required');
define(Relation.prototype, 'multiple');
Relation.prototype._required.value = false;
Relation.prototype._required.required = true;
Relation.prototype._multiple.value = false;
Relation.prototype._multiple.required = true;
RelSetItem = require('./rel-set-item');
define(RelSetItem.prototype, 'order');
<|endoftext|>