<commit_before>"use strict";

var userAgent = window.navigator.userAgent;
var isSafari = userAgent.match(/iPad/i) || userAgent.match(/iPhone/i);

var hideTimeout = false;
function showDrawer(percent)
{
	$('#drawer-overlay').css('opacity', percent*0.75);

	if(hideTimeout)
	{
		clearTimeout(hideTimeout);
		hideTimeout = false;
	}

	if(percent == 0)
		hideTimeout = setTimeout(function() {
			$('#drawer-overlay').css('visibility', 'hidden');
			$('#drawer').css('visibility', 'hidden');
		}, 500);
	else
	{
		$('#drawer-overlay').css('visibility', 'visible');
		$('#drawer').css('visibility', 'visible');
	}

	var t = 300 * (percent-1);
	$("#drawer").css("-webkit-transform", "translateX("+t+"px)");
	$("#drawer").css("transform", "translateX("+t+"px)");
}

var drawerShown = false;

function resetDrawer()
{
	$('#drawer-overlay').css('opacity', "");
	$('#drawer-overlay').css('visibility', "");
	$("#drawer").css("-webkit-transform", "");
	$("#drawer").css("transform", "");
	$("#drawer").css("visibility", "");

	drawerShown = false;
}

var touchDown = false;
var touchDragging = false;
var touchDownX = 0;
var touchDownY = 0;
var touchDiffX = 0;
var touchTime = 0;

//Returns true if drawer should be always visible (not in mobile mode)
function drawerAlwaysVisible() {
	return window.innerWidth >= 768;
}

function startTouchDragging()
{
	touchDragging = true;
	$("#drawer").addClass("dragging");
	$("#drawer-overlay").addClass("dragging");
}

function stopTouchDragging()
{
	touchDragging = false;
	$("#drawer").removeClass("dragging");
	$("#drawer-overlay").removeClass("dragging");
}

$(document).ready(function() {
	$('#drawer-overlay').bind('click', function() {
		drawerShown = false;
		showDrawer(0.0);
	});
	$('#drawer-toggle').bind('click', function() {
		drawerShown = !drawerShown;
		if (drawerShown)
			showDrawer(1.0);
		else
			showDrawer(0.0);
		return false;
	});

	$(window).on('resize', function(){
		if(drawerAlwaysVisible())
			resetDrawer();
	});

	document.addEventListener('touchstart', function(event) {
		if(drawerAlwaysVisible()) return;
		// On Safari edge-swipe is used for back navigation.
		// So, in case of Safari I don't require edge-swiping, any swiping will do.
		// If you have a better alternative, please let me know!
		if(event.touches[0].pageX < 30 || isSafari || drawerShown)
		{
			touchDown = true;
			touchDownX = event.touches[0].pageX;
			touchDownY = event.touches[0].pageY;
			touchTime = +new Date();
			if(drawerShown)
			{
				touchDiffX = 300-event.touches[0].pageX;
				if(touchDiffX < 0) touchDiffX = 0;
			}
			else
				touchDiffX = 0;
		}
	}, false);
	document.addEventListener('touchmove', function(event) {
		if(drawerAlwaysVisible()) return;
		if(touchDown) //TODO IMPROVE
		{
			var dx = event.changedTouches[0].pageX-touchDownX;
			var dy = event.changedTouches[0].pageY-touchDownY;
			if( Math.abs(dx) > Math.abs(dy))
			{
				startTouchDragging();
				touchDragging = true;
			}
		}
		if(touchDragging)
		{
			var x = (event.changedTouches[0].pageX + touchDiffX)/300.0;
			if(x < 0.0) x = 0.0;
			if(x > 1.0) x = 1.0;
			showDrawer(x);
			event.preventDefault();
		}
	}, false);
	document.addEventListener('touchend', function(event) {
		touchDown = false;
		if(touchDragging)
		{
			stopTouchDragging();
			var now = +new Date();
			var elapsed = now - touchTime;
			var dx = event.changedTouches[0].pageX-touchDownX;

			var speed = dx/elapsed;
			if(elapsed > 500) speed = 0;

			if((event.changedTouches[0].pageX + touchDiffX + speed*200) > (drawerShown?225:75))
			{
				showDrawer(1.0);
				drawerShown = true;
			}
			else
			{
				showDrawer(0.0);
				drawerShown = false;
			}
		}
	}, false);

});
<commit_msg>Port NSMBHD mobile layout fix<commit_after>"use strict";

var userAgent = window.navigator.userAgent;
var isSafari = userAgent.match(/iPad/i) || userAgent.match(/iPhone/i);

var hideTimeout = false;
function showDrawer(percent)
{
	$('#drawer-overlay').css('opacity', percent*0.75);

	if(hideTimeout)
	{
		clearTimeout(hideTimeout);
		hideTimeout = false;
	}

	if(percent == 0)
		hideTimeout = setTimeout(function() {
			$('#drawer-overlay').css('visibility', 'hidden');
			$('#drawer').css('visibility', 'hidden');
		}, 500);
	else
	{
		$('#drawer-overlay').css('visibility', 'visible');
		$('#drawer').css('visibility', 'visible');
	}

	var t = 300 * (percent-1);
	$("#drawer").css("-webkit-transform", "translateX("+t+"px)");
	$("#drawer").css("transform", "translateX("+t+"px)");
}

var drawerShown = false;

function resetDrawer()
{
	$('#drawer-overlay').css('opacity', "");
	$('#drawer-overlay').css('visibility', "");
	$("#drawer").css("-webkit-transform", "");
	$("#drawer").css("transform", "");
	$("#drawer").css("visibility", "");

	drawerShown = false;
}

var touchDown = false;
var touchDragging = false;
var touchDownX = 0;
var touchDownY = 0;
var touchDiffX = 0;
var touchTime = 0;

//Returns true if drawer should be always visible (not in mobile mode)
function drawerAlwaysVisible() {
	return window.innerWidth >= 768;
}

function startTouchDragging()
{
	touchDragging = true;
	$("#drawer").addClass("dragging");
	$("#drawer-overlay").addClass("dragging");
}

function stopTouchDragging()
{
	touchDragging = false;
	$("#drawer").removeClass("dragging");
	$("#drawer-overlay").removeClass("dragging");
}

$(document).ready(function() {
	$('#drawer-overlay').bind('click', function() {
		drawerShown = false;
		showDrawer(0.0);
	});
	$('#drawer-toggle').bind('click', function() {
		drawerShown = !drawerShown;
		if (drawerShown)
			showDrawer(1.0);
		else
			showDrawer(0.0);
		return false;
	});

	$(window).on('resize', function(){
		if(drawerAlwaysVisible())
			resetDrawer();
	});

	document.addEventListener('touchstart', function(event) {
		if(drawerAlwaysVisible()) return;
		// On Safari edge-swipe is used for back navigation.
		// So, in case of Safari you can't open the sidebar with edge swiping.
		if((event.touches[0].pageX < 30 && !isSafari) || drawerShown)
		{
			touchDown = true;
			touchDownX = event.touches[0].pageX;
			touchDownY = event.touches[0].pageY;
			touchTime = +new Date();
			if(drawerShown)
			{
				touchDiffX = 300-event.touches[0].pageX;
				if(touchDiffX < 0) touchDiffX = 0;
			}
			else
				touchDiffX = 0;
		}
	}, false);
	document.addEventListener('touchmove', function(event) {
		if(drawerAlwaysVisible()) return;
		if(touchDown) //TODO IMPROVE
		{
			var dx = event.changedTouches[0].pageX-touchDownX;
			var dy = event.changedTouches[0].pageY-touchDownY;
			if( Math.abs(dx) > Math.abs(dy))
			{
				startTouchDragging();
				touchDragging = true;
			}
		}
		if(touchDragging)
		{
			var x = (event.changedTouches[0].pageX + touchDiffX)/300.0;
			if(x < 0.0) x = 0.0;
			if(x > 1.0) x = 1.0;
			showDrawer(x);
			event.preventDefault();
		}
	}, false);
	document.addEventListener('touchend', function(event) {
		touchDown = false;
		if(touchDragging)
		{
			stopTouchDragging();
			var now = +new Date();
			var elapsed = now - touchTime;
			var dx = event.changedTouches[0].pageX-touchDownX;

			var speed = dx/elapsed;
			if(elapsed > 500) speed = 0;

			if((event.changedTouches[0].pageX + touchDiffX + speed*200) > (drawerShown?225:75))
			{
				showDrawer(1.0);
				drawerShown = true;
			}
			else
			{
				showDrawer(0.0);
				drawerShown = false;
			}
		}
	}, false);

});
<|endoftext|>


<commit_before>/* jshint ignore:start */

define('{{MODULE_PREFIX}}/config/environment', [], function() {
  var metaName = '{{MODULE_PREFIX}}/config/environment';
  var rawConfig = jQuery('meta[name="' + metaName + '"]').attr('content');
  var config = JSON.parse(unescape(rawConfig));

  return { 'default': config };
});

if (runningTests) {
  require('{{MODULE_PREFIX}}/tests/test-helper');
} else {
  require('{{MODULE_PREFIX}}/app')['default'].create({{APP_CONFIG}});
}

/* jshint ignore:end */
<commit_msg>Using Ember.$ instead of global jQuery<commit_after>/* jshint ignore:start */

define('{{MODULE_PREFIX}}/config/environment', ['ember'], function(Ember) {
  var metaName = '{{MODULE_PREFIX}}/config/environment';
  var rawConfig = Ember.$('meta[name="' + metaName + '"]').attr('content');
  var config = JSON.parse(unescape(rawConfig));

  return { 'default': config };
});

if (runningTests) {
  require('{{MODULE_PREFIX}}/tests/test-helper');
} else {
  require('{{MODULE_PREFIX}}/app')['default'].create({{APP_CONFIG}});
}

/* jshint ignore:end */
<|endoftext|>


<commit_before>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2014, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

var common = require('./common.js');
var parsing = require('./parsing.js');

var builder = require('../objectBuilder')();
builder.setDefaults({source: 'carelink'});

var isBrowser = typeof window !== 'undefined';
var debug = isBrowser ? require('./bows')('ChangeTime parser') : console.log;

var RAW_VALUES = 'Raw-Values';

var RV_KEYS = {
  NEW_TIME: 'NEW_TIME'
};

module.exports = function () {
  var parser = common.makeParser(
    {
      ChangeTime: [
        common.makeCommonVals(),
        {
          timestamp: parsing.asNumber([RAW_VALUES, RV_KEYS.NEW_TIME])
        }
      ],
      ChangeTimeGH: [
        common.makeCommonVals(),
        {
          timestamp: parsing.asNumber([RAW_VALUES, RV_KEYS.NEW_TIME])
        }
      ]
    }
  );

  return function (changes, datum) {
    var parsed = parser(datum);
    if (parsed != null) {
      var newDate = new Date(parsed.timestamp);
      /**
       * This is a pretty ugly hack to filter out completely spurious time changes that
       * appear in the data when the battery is left out for too long.
       * The strategy is to filter out any time change to a date where the year is
       * less than the current year minus one. So, for example, since I'm writing this in 2015,
       * any time changes to any date in 2013 or earlier will be filtered out.
       * (Since we only pull 6 months of CareLink data at a time, this seems reasonably secure.)
       *
       * Depending on the model of device, the time changes do not always go to the same date.
       * For example, some devices "reset" to 2008-01-01T00:00:00 and some to 2012-01-01...
       * (The 2012 resets also do not always go to midnight but I've seen to T00:02:00 and T00:05:00)
       */
      if (newDate.getUTCFullYear() < (new Date().getUTCFullYear() - 1)) {
        debug('Excluding time change to', newDate.toISOString().slice(0,-5), 'as spurious.');
        return;
      }
      var timeChange = builder.makeDeviceMetaTimeChange()
        .with_change({
          from: parsed.deviceTime,
          to: newDate.toISOString().slice(0,-5),
          agent: 'manual'
        })
        .with_deviceTime(parsed.deviceTime)
        .with_payload({
          NEW_TIME: parsed.timestamp
        })
        .set('deviceId', parsed.deviceId)
        .set('index', parsed.index)
        .set('jsDate', newDate)
        .set('model', parsed.model)
        // TODO: delete after conclusion of Jaeb study
        .set('jaebPayload', parsed.jaebPayload);
        // TODO: end deletion
      changes.push(timeChange);
    }
    else {
      throw new Error('Error parsing `ChangeTime` row!');
    }
  };
};
<commit_msg>fix path on a require, oops<commit_after>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2014, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

var common = require('./common.js');
var parsing = require('./parsing.js');

var builder = require('../objectBuilder')();
builder.setDefaults({source: 'carelink'});

var isBrowser = typeof window !== 'undefined';
var debug = isBrowser ? require('../bows')('ChangeTime parser') : console.log;

var RAW_VALUES = 'Raw-Values';

var RV_KEYS = {
  NEW_TIME: 'NEW_TIME'
};

module.exports = function () {
  var parser = common.makeParser(
    {
      ChangeTime: [
        common.makeCommonVals(),
        {
          timestamp: parsing.asNumber([RAW_VALUES, RV_KEYS.NEW_TIME])
        }
      ],
      ChangeTimeGH: [
        common.makeCommonVals(),
        {
          timestamp: parsing.asNumber([RAW_VALUES, RV_KEYS.NEW_TIME])
        }
      ]
    }
  );

  return function (changes, datum) {
    var parsed = parser(datum);
    if (parsed != null) {
      var newDate = new Date(parsed.timestamp);
      /**
       * This is a pretty ugly hack to filter out completely spurious time changes that
       * appear in the data when the battery is left out for too long.
       * The strategy is to filter out any time change to a date where the year is
       * less than the current year minus one. So, for example, since I'm writing this in 2015,
       * any time changes to any date in 2013 or earlier will be filtered out.
       * (Since we only pull 6 months of CareLink data at a time, this seems reasonably secure.)
       *
       * Depending on the model of device, the time changes do not always go to the same date.
       * For example, some devices "reset" to 2008-01-01T00:00:00 and some to 2012-01-01...
       * (The 2012 resets also do not always go to midnight but I've seen to T00:02:00 and T00:05:00)
       */
      if (newDate.getUTCFullYear() < (new Date().getUTCFullYear() - 1)) {
        debug('Excluding time change to', newDate.toISOString().slice(0,-5), 'as spurious.');
        return;
      }
      var timeChange = builder.makeDeviceMetaTimeChange()
        .with_change({
          from: parsed.deviceTime,
          to: newDate.toISOString().slice(0,-5),
          agent: 'manual'
        })
        .with_deviceTime(parsed.deviceTime)
        .with_payload({
          NEW_TIME: parsed.timestamp
        })
        .set('deviceId', parsed.deviceId)
        .set('index', parsed.index)
        .set('jsDate', newDate)
        .set('model', parsed.model)
        // TODO: delete after conclusion of Jaeb study
        .set('jaebPayload', parsed.jaebPayload);
        // TODO: end deletion
      changes.push(timeChange);
    }
    else {
      throw new Error('Error parsing `ChangeTime` row!');
    }
  };
};
<|endoftext|>


<commit_before>var enums = require('../constants/odata_enums');
var lbConstants = require('../constants/loopback_constants');
var metadata_1 = require("../base/metadata/metadata");
var oDataServerConfig;
function _setConfig(config) {
    oDataServerConfig = config;
}
function _getBaseURL(req) {
    return req.protocol + '://' + req.hostname +
        ':' + req.app.get('port') + '/' + oDataServerConfig.odataPrefix;
}
function _getRequestType(req) {
    var retValue = enums.GetRequestTypeEnum.UNDEFINED;
    var param0 = req.params[0];
    if (req.params[0] === '')
        retValue = enums.GetRequestTypeEnum.SERVICE;
    else {
        var arrParams = param0.split('/');
        if (param0.toUpperCase() === "$METADATA") {
            retValue = enums.GetRequestTypeEnum.METADATA;
        }
        else if (arrParams[arrParams.length - 1] === '$count') {
            retValue = enums.GetRequestTypeEnum.COLLECTION_COUNT;
        }
        else if (_isRequestCollection(req)) {
            retValue = enums.GetRequestTypeEnum.COLLECTION;
        }
        else if (_isRequestEntity(req)) {
            retValue = enums.GetRequestTypeEnum.ENTITY;
        }
        else {
        }
    }
    return retValue;
}
function _isRequestCollection(req) {
    var retValue = false;
    var reqParts = /^([^/(]+)(?:[(](.*)[)])?(?:[/]([A-Za-z]+))?/g.exec(req.params[0]);
    var models = req.app.models();
    models.forEach(function (model) {
        var plural = _getPluralForModel(model);
        if (plural === reqParts[1]) {
            if (reqParts[2] && reqParts[3]) {
                var modelRel = model.definition.settings.relations;
                if (modelRel && modelRel[reqParts[3]] && modelRel[reqParts[3]].type === lbConstants.LB_REL_HASMANY) {
                    retValue = true;
                }
                else {
                }
            }
            else if (!reqParts[2]) {
                retValue = true;
            }
            else {
            }
        }
    });
    return retValue;
}
function _isRequestEntity(req) {
    var retValue = false;
    var reqParts = /^([^/(]+)(?:[(](.*)[)])?(?:[/]([A-Za-z]+))?/g.exec(req.params[0]);
    var models = req.app.models();
    models.forEach(function (model) {
        var plural = _getPluralForModel(model);
        if (plural === reqParts[1]) {
            if (reqParts[2] && reqParts[3]) {
                var modelRel = model.definition.settings.relations;
                if (modelRel && modelRel[reqParts[3]] && (modelRel[reqParts[3]].type === lbConstants.LB_REL_BELONGSTO || modelRel[reqParts[3]].type === lbConstants.LB_REL_HASONE)) {
                    retValue = true;
                }
                else {
                }
            }
            else if (reqParts[2]) {
                retValue = true;
            }
            else {
            }
        }
    });
    return retValue;
}
function _getPluralForModel(model) {
    var plural = model.definition.settings.plural;
    if (!plural) {
        plural = model.definition.name + 's';
    }
    return plural;
}
function _getIdFromUrlParameter(param0) {
    console.log("'_getIdFromUrlParameter' is DEPRECATED! Please use '_getIdByPropertyType' instead.");
    var retValue = param0.substring(param0.indexOf('(') + 1, param0.indexOf(')'));
    if (retValue.startsWith("'") || retValue.startsWith("\"")) {
        retValue = retValue.substring(1, retValue.length - 1);
    }
    if (retValue.endsWith('M')) {
        retValue = retValue.substr(0, retValue.length - 1);
    }
    return retValue;
}
function _getIdByPropertyType(sRawId, property) {
    var id;
    switch (metadata_1.Metadata.prototype._convertType(property)) {
        case "Edm.String":
            id = (/^['](.*)[']$/g.exec(sRawId) || [undefined, undefined])[1];
            break;
        case "Edm.Decimal":
            id = /^[0-9]+.[0-9]+/g.exec(sRawId)[0];
            break;
        default:
            id = sRawId;
            break;
    }
    return id;
}
function _getRequestModelClass(models, requestUri) {
    var reqParts = /^([^/(]+)(?:[(](.*)[)])?(?:[/]([A-Za-z]+))?/g.exec(requestUri);
    if (!reqParts[3]) {
        return new Promise(function (resolve, reject) {
            _getModelClass(models, reqParts[1]).then(function (ModelClass) {
                var sRequestId = _getIdByPropertyType(reqParts[2], ModelClass.definition._ids[0].property);
                resolve({ modelClass: ModelClass, foreignKeyFilter: undefined, requestId: sRequestId });
            });
        });
    }
    else {
        return new Promise(function (resolve, reject) {
            _getModelClass(models, reqParts[1]).then(function (BaseModelClass) {
                var modelProps = BaseModelClass.definition.properties;
                var modelRel = BaseModelClass.settings.relations;
                if (modelRel && modelRel[reqParts[3]]) {
                    var oFilter = {}, sForeignKey = modelRel[reqParts[3]].foreignKey;
                    if (sForeignKey == "") {
                        sForeignKey = reqParts[3] + "Id";
                    }
                    var sRequestId = _getIdByPropertyType(reqParts[2], BaseModelClass.definition._ids[0].property);
                    switch (modelRel[reqParts[3]].type) {
                        case lbConstants.LB_REL_HASMANY:
                            oFilter[sForeignKey] = sRequestId;
                            if (!oFilter[sForeignKey]) {
                                reject("Invalid id");
                            }
                            else {
                                _getModelClass(models, modelRel[reqParts[3]].model).then(function (ModelClass) {
                                    resolve({ modelClass: ModelClass, foreignKeyFilter: oFilter, requestId: sRequestId });
                                });
                            }
                            break;
                        case lbConstants.LB_REL_BELONGSTO:
                            BaseModelClass.findById(sRequestId, function (error, instance) {
                                if (instance) {
                                    oFilter["_id"] = instance[sForeignKey];
                                    _getModelClass(models, modelRel[reqParts[3]].model).then(function (ModelClass) {
                                        resolve({ modelClass: ModelClass, foreignKeyFilter: oFilter, requestId: sRequestId });
                                    });
                                }
                                else {
                                    reject("Entity not found!");
                                }
                            });
                            break;
                    }
                }
                else {
                    resolve(BaseModelClass);
                }
            });
        });
    }
}
function _getModelClass(models, className) {
    return new Promise(function (resolve, reject) {
        var ModelClass;
        if (className.indexOf('(') !== -1) {
            className = className.substr(0, className.indexOf('('));
        }
        else {
            ModelClass = models[className];
        }
        if (!ModelClass) {
            for (var modelStr in models) {
                var model = models[modelStr];
                if (model.definition.settings.plural === className) {
                    ModelClass = model;
                    break;
                }
                else {
                    var plural = model.definition.name + 's';
                    if (plural === className) {
                        ModelClass = model;
                        break;
                    }
                }
            }
            ;
        }
        resolve(ModelClass);
    });
}
module.exports = {
    setConfig: _setConfig,
    getBaseURL: _getBaseURL,
    getRequestType: _getRequestType,
    getIdFromUrlParameter: _getIdFromUrlParameter,
    getPluralForModel: _getPluralForModel,
    getModelClass: _getModelClass,
    getRequestModelClass: _getRequestModelClass,
    getIdByPropertyType: _getIdByPropertyType
};
//# sourceMappingURL=odata_common.js.map<commit_msg>Add support for enclosed ' ' parameters in MongoDB<commit_after>var enums = require('../constants/odata_enums');
var lbConstants = require('../constants/loopback_constants');
var metadata_1 = require("../base/metadata/metadata");
var oDataServerConfig;
function _setConfig(config) {
    oDataServerConfig = config;
}
function _getBaseURL(req) {
    return req.protocol + '://' + req.hostname +
        ':' + req.app.get('port') + '/' + oDataServerConfig.odataPrefix;
}
function _getRequestType(req) {
    var retValue = enums.GetRequestTypeEnum.UNDEFINED;
    var param0 = req.params[0];
    if (req.params[0] === '')
        retValue = enums.GetRequestTypeEnum.SERVICE;
    else {
        var arrParams = param0.split('/');
        if (param0.toUpperCase() === "$METADATA") {
            retValue = enums.GetRequestTypeEnum.METADATA;
        }
        else if (arrParams[arrParams.length - 1] === '$count') {
            retValue = enums.GetRequestTypeEnum.COLLECTION_COUNT;
        }
        else if (_isRequestCollection(req)) {
            retValue = enums.GetRequestTypeEnum.COLLECTION;
        }
        else if (_isRequestEntity(req)) {
            retValue = enums.GetRequestTypeEnum.ENTITY;
        }
        else {
        }
    }
    return retValue;
}
function _isRequestCollection(req) {
    var retValue = false;
    var reqParts = /^([^/(]+)(?:[(](.*)[)])?(?:[/]([A-Za-z]+))?/g.exec(req.params[0]);
    var models = req.app.models();
    models.forEach(function (model) {
        var plural = _getPluralForModel(model);
        if (plural === reqParts[1]) {
            if (reqParts[2] && reqParts[3]) {
                var modelRel = model.definition.settings.relations;
                if (modelRel && modelRel[reqParts[3]] && modelRel[reqParts[3]].type === lbConstants.LB_REL_HASMANY) {
                    retValue = true;
                }
                else {
                }
            }
            else if (!reqParts[2]) {
                retValue = true;
            }
            else {
            }
        }
    });
    return retValue;
}
function _isRequestEntity(req) {
    var retValue = false;
    var reqParts = /^([^/(]+)(?:[(](.*)[)])?(?:[/]([A-Za-z]+))?/g.exec(req.params[0]);
    var models = req.app.models();
    models.forEach(function (model) {
        var plural = _getPluralForModel(model);
        if (plural === reqParts[1]) {
            if (reqParts[2] && reqParts[3]) {
                var modelRel = model.definition.settings.relations;
                if (modelRel && modelRel[reqParts[3]] && (modelRel[reqParts[3]].type === lbConstants.LB_REL_BELONGSTO || modelRel[reqParts[3]].type === lbConstants.LB_REL_HASONE)) {
                    retValue = true;
                }
                else {
                }
            }
            else if (reqParts[2]) {
                retValue = true;
            }
            else {
            }
        }
    });
    return retValue;
}
function _getPluralForModel(model) {
    var plural = model.definition.settings.plural;
    if (!plural) {
        plural = model.definition.name + 's';
    }
    return plural;
}
function _getIdFromUrlParameter(param0) {
    console.log("'_getIdFromUrlParameter' is DEPRECATED! Please use '_getIdByPropertyType' instead.");
    var retValue = param0.substring(param0.indexOf('(') + 1, param0.indexOf(')'));
    if (retValue.startsWith("'") || retValue.startsWith("\"")) {
        retValue = retValue.substring(1, retValue.length - 1);
    }
    if (retValue.endsWith('M')) {
        retValue = retValue.substr(0, retValue.length - 1);
    }
    return retValue;
}
function _getIdByPropertyType(sRawId, property) {
    var id;
    switch (metadata_1.Metadata.prototype._convertType(property)) {
        case "Edm.String":
            id = (/^['](.*)[']$/g.exec(sRawId) || [undefined, undefined])[1];
            break;
        case "Edm.Decimal":
            id = /^[0-9]+.[0-9]+/g.exec(sRawId)[0];
            break;
        default:
            if (property.generated === true) {
                if (sRawId.charAt(0) === "'") {
                    id = (/^['](.*)[']$/g.exec(sRawId) || [undefined, undefined])[1];
                }
            }
            else {
                id = sRawId;
            }
            break;
    }
    return id;
}
function _getRequestModelClass(models, requestUri) {
    var reqParts = /^([^/(]+)(?:[(](.*)[)])?(?:[/]([A-Za-z]+))?/g.exec(requestUri);
    if (!reqParts[3]) {
        return new Promise(function (resolve, reject) {
            _getModelClass(models, reqParts[1]).then(function (ModelClass) {
                var sRequestId = _getIdByPropertyType(reqParts[2], ModelClass.definition._ids[0].property);
                resolve({ modelClass: ModelClass, foreignKeyFilter: undefined, requestId: sRequestId });
            });
        });
    }
    else {
        return new Promise(function (resolve, reject) {
            _getModelClass(models, reqParts[1]).then(function (BaseModelClass) {
                var modelProps = BaseModelClass.definition.properties;
                var modelRel = BaseModelClass.settings.relations;
                if (modelRel && modelRel[reqParts[3]]) {
                    var oFilter = {}, sForeignKey = modelRel[reqParts[3]].foreignKey;
                    if (sForeignKey == "") {
                        sForeignKey = reqParts[3] + "Id";
                    }
                    var sRequestId = _getIdByPropertyType(reqParts[2], BaseModelClass.definition._ids[0].property);
                    switch (modelRel[reqParts[3]].type) {
                        case lbConstants.LB_REL_HASMANY:
                            oFilter[sForeignKey] = sRequestId;
                            if (!oFilter[sForeignKey]) {
                                reject("Invalid id");
                            }
                            else {
                                _getModelClass(models, modelRel[reqParts[3]].model).then(function (ModelClass) {
                                    resolve({ modelClass: ModelClass, foreignKeyFilter: oFilter, requestId: sRequestId });
                                });
                            }
                            break;
                        case lbConstants.LB_REL_BELONGSTO:
                            BaseModelClass.findById(sRequestId, function (error, instance) {
                                if (instance) {
                                    oFilter["_id"] = instance[sForeignKey];
                                    _getModelClass(models, modelRel[reqParts[3]].model).then(function (ModelClass) {
                                        resolve({ modelClass: ModelClass, foreignKeyFilter: oFilter, requestId: sRequestId });
                                    });
                                }
                                else {
                                    reject("Entity not found!");
                                }
                            });
                            break;
                    }
                }
                else {
                    resolve(BaseModelClass);
                }
            });
        });
    }
}
function _getModelClass(models, className) {
    return new Promise(function (resolve, reject) {
        var ModelClass;
        if (className.indexOf('(') !== -1) {
            className = className.substr(0, className.indexOf('('));
        }
        else {
            ModelClass = models[className];
        }
        if (!ModelClass) {
            for (var modelStr in models) {
                var model = models[modelStr];
                if (model.definition.settings.plural === className) {
                    ModelClass = model;
                    break;
                }
                else {
                    var plural = model.definition.name + 's';
                    if (plural === className) {
                        ModelClass = model;
                        break;
                    }
                }
            }
            ;
        }
        resolve(ModelClass);
    });
}
module.exports = {
    setConfig: _setConfig,
    getBaseURL: _getBaseURL,
    getRequestType: _getRequestType,
    getIdFromUrlParameter: _getIdFromUrlParameter,
    getPluralForModel: _getPluralForModel,
    getModelClass: _getModelClass,
    getRequestModelClass: _getRequestModelClass,
    getIdByPropertyType: _getIdByPropertyType
};
//# sourceMappingURL=odata_common.js.map
<|endoftext|>


<commit_before>var Behaviors = require('./../behaviors/behaviors');
var ControlFlow = require('./../control-flow/control-flow');
var DataStore = require('./../data-store/data-store');
var Events = require('./../events/events');
var FamousConnector = require('./../famous-connector/famous-connector');
var States = require('./../states/states');
var Timelines = require('./../timelines/timelines');
var Tree = require('./../tree/tree');
var UID = require('framework-utilities/uid');
var VirtualDOM = require('./../virtual-dom/virtual-dom');
var BehaviorRouter = require('./../behaviors/behavior-router');

var NODE_UID_PREFIX = 'node';
var YIELD_KEY = '$yield';
var REPEAT_INFO_KEY = 'repeat-info';
var CONTROL_FLOW_ACTION_KEY = 'control-flow-action';
var CREATE_KEY = 'create';
var DELETE_KEY = 'delete';
var INDEX_KEY = '$index';
var REPEAT_PAYLOAD_KEY = '$repeatPayload';

function Component(domNode, surrogateRoot, parent) {
    this.name = domNode.tagName.toLowerCase();
    this.uid = VirtualDOM.getUID(domNode);
    this.definition = DataStore.getModule(this.name);
    this.surrogateRoot = surrogateRoot;
    this.tree = new Tree(domNode, this.definition.tree, parent.tree.rootNode);
    this.famousNode = FamousConnector.addChild(parent.famousNode);
    this.behaviors = new Behaviors(this.definition.behaviors);
    this.controlFlow = new ControlFlow(this.behaviors.getBehaviorList());
    this.blockControlFlow = false;
    this.events = new Events(this.definition.events, this.name, this.getRootNode());
    this.states = new States(this.definition.states);
    this.timelines = new Timelines(this.definition.timelines);

    DataStore.registerComponent(this.uid, this);

    this.setEventListeners();
    this.initialize();
}

Component.prototype.handleBehaviorUpdate = function handleBehaviorUpdate(behavior) {
    BehaviorRouter.route(behavior, this);
};

Component.prototype.processDynamicRepeat = function processDynamicRepeat(behavior) {
    var expandedBlueprint = this.tree.getExpandedBlueprint();
    this.controlFlow.processRepeatBehavior(
        behavior, expandedBlueprint, this.uid
    );

    this.processControlFlowMessages();
}

Component.prototype.processDynamicIf = function processDynamicIf(behavior) {
    var expandedBlueprint = this.tree.getExpandedBlueprint();
    var blueprint = this.tree.getBlueprint();

    this.controlFlow.processIfBehavior(
        behavior, blueprint, expandedBlueprint, this.uid
    );

    this.processControlFlowMessages();
}

Component.prototype.processControlFlowMessages = function processControlFlowMessages() {
    var expandedBlueprint = this.tree.getExpandedBlueprint();
    var nodes = VirtualDOM.queryAttribute(expandedBlueprint, CONTROL_FLOW_ACTION_KEY);
    var newComponentCreated = false;
    var result;
    for (var i = 0; i < nodes.length; i++) {
        result = Component.processControlFlowMessage(nodes[i]);
        if (!newComponentCreated) {
            newComponentCreated = result;
        }
        nodes[i].removeAttribute(CONTROL_FLOW_ACTION_KEY);
    }

    // Trigger a global change from the parent to trigger behaviors that effect the
    // newly created elements
    if (newComponentCreated) {
        this.triggerGlobalChange(true);
    }
}

Component.processControlFlowMessage = function processControlFlowMessage(node) {
    var info = node.getAttribute(CONTROL_FLOW_ACTION_KEY);
    if (info) {
        info = JSON.parse(info);
        if (info.message === CREATE_KEY) {
            var baseNode = VirtualDOM.clone(node);
            VirtualDOM.removeChildNodes(baseNode);
            baseNode.removeAttribute(CONTROL_FLOW_ACTION_KEY);
            childComponent = new Component(baseNode, node, DataStore.getComponent(info.parentUID));
            return childComponent;
        }
        else if (info.message === DELETE_KEY) {
            var component = DataStore.getComponent(VirtualDOM.getUID(node));
            component.remove();
        }
    }
    return null;
}

Component.prototype.initialize = function initialize() {
    var self = this;

    this.processControlFlow(this.uid);

    this.behaviors.eachListItem(function(item) {
        self.states.createBehaviorListener(item);
    });

    this.events.initializeDescendantEvents(this.tree.getExpandedBlueprint(), this.uid);

    this.processDOMMessages();
    this.tree.stripExpandedBlueprintMessages();
    this.triggerGlobalChange(true); // Block dynamic control flow to avoid double processing
}

Component.prototype.processDOMMessages = function processDOMMessages() {
    var node = this.getRootNode();
    var messageStr = node.getAttribute(REPEAT_INFO_KEY);
    var index;
    var repeatInfo;
    if (messageStr) {
        var messageObj = JSON.parse(messageStr);
        index = messageObj[INDEX_KEY];
        repeatPayload = messageObj[REPEAT_PAYLOAD_KEY];
        this.events.sendMessages(repeatPayload, this.uid);
        node.removeAttribute(REPEAT_INFO_KEY);
    }
    else {
        index = 0;
        repeatPayload = null;
    }

    this.states.set(INDEX_KEY, index);
    this.states.set(REPEAT_PAYLOAD_KEY, repeatPayload);
}

Component.prototype.triggerGlobalChange = function triggerGlobalChange(blockControlFlow) {
    if (blockControlFlow) {
        this.blockControlFlow = true;
        this.states.triggerGlobalChange();
        this.blockControlFlow = false;
    }
    else {
        this.states.triggerGlobalChange();
    }
}

Component.prototype.processControlFlow = function processControlFlow(uid) {
    this.controlFlow.processSelfContainedFlows(this.tree.getBlueprint(), uid);

    // Check for default '$yield' overwrite via public events to minimize
    // ControlFlow's concerns
    if (this.events.getPublicEvent(YIELD_KEY)) {
        this.events.triggerPublicEvent(YIELD_KEY, {
            surrogateRoot: this.surrogateRoot
        }, this.uid);
    }
    else {
        this.controlFlow.processParentDefinedFlows(
            this.tree.getExpandedBlueprint(), this.surrogateRoot
        );
    }

    this.tree.getRootNode().removeAttribute(CONTROL_FLOW_ACTION_KEY);
}

Component.prototype.updateChildren = function updateChildren(childrenRoot) {
    var self = this;
    this.tree.setChildrenRoot(childrenRoot);

    var baseNode;
    this.tree.eachChild(function(node) {
        baseNode = VirtualDOM.clone(node);
        VirtualDOM.removeChildNodes(baseNode);
        childComponent = new Component(baseNode, node, self);
    });
}

Component.prototype.setEventListeners = function setEventListeners() {
    this.controlFlow.on('setExpandedBlueprint', this.tree.setExpandedBlueprint.bind(this.tree));
    this.controlFlow.on('setChildrenRoot', this.updateChildren.bind(this));
    this.states.on('behavior-update', this.handleBehaviorUpdate.bind(this));
}

Component.prototype.sendMessage = function sendMessage(key, message) {
    this.events.sendMessage(key, message, this.uid);
}

Component.prototype.getRootNode = function getRootNode() {
    return this.tree.rootNode;
}

Component.prototype.getParentComponent = function getParentComponent() {
    return DataStore.getComponent(VirtualDOM.getParentUID(this.getRootNode()));
}

Component.prototype.remove = function remove() {
    var parentComponent = this.getParentComponent();

    var rootNode = this.tree.getRootNode();
    if (rootNode.parentNode) {
        rootNode.parentNode.removeChild(rootNode);
    }

    var parentExpandedBlueprint = parentComponent.tree.getExpandedBlueprint();
    var targetNode = VirtualDOM.getNodeByUID(parentExpandedBlueprint, this.uid);
    // Target node may not be in parent's expanded blueprint if it was yielded
    // in by a grandparent
    if (targetNode) {
        parentExpandedBlueprint.removeChild(targetNode);
    }

    parentComponent.famousNode.removeChild(this.famousNode);

    // TODO --> Remove all listeners
    // TODO --> Recursively remove any children
    // TODO --> Remove from DataStore
}

Component.executeComponent = function executeComponent(name, selector) {
    // Shim tree to match Component Constructor API
    var wrapperNode = VirtualDOM.create('parent-tree:' + name);
    var topLevelTree = new Tree(wrapperNode, '', VirtualDOM.getBaseNode());

    var baseNode = VirtualDOM.create(name);
    VirtualDOM.setUID(baseNode, UID.generate(NODE_UID_PREFIX));

    return new Component(baseNode, null, {
        tree: topLevelTree,
        famousNode: FamousConnector.createRoot(selector)
    });
};

module.exports = Component;
<commit_msg>wip: pass in states to timelines<commit_after>var Behaviors = require('./../behaviors/behaviors');
var ControlFlow = require('./../control-flow/control-flow');
var DataStore = require('./../data-store/data-store');
var Events = require('./../events/events');
var FamousConnector = require('./../famous-connector/famous-connector');
var States = require('./../states/states');
var Timelines = require('./../timelines/timelines');
var Tree = require('./../tree/tree');
var UID = require('framework-utilities/uid');
var VirtualDOM = require('./../virtual-dom/virtual-dom');
var BehaviorRouter = require('./../behaviors/behavior-router');

var NODE_UID_PREFIX = 'node';
var YIELD_KEY = '$yield';
var REPEAT_INFO_KEY = 'repeat-info';
var CONTROL_FLOW_ACTION_KEY = 'control-flow-action';
var CREATE_KEY = 'create';
var DELETE_KEY = 'delete';
var INDEX_KEY = '$index';
var REPEAT_PAYLOAD_KEY = '$repeatPayload';

function Component(domNode, surrogateRoot, parent) {
    this.name = domNode.tagName.toLowerCase();
    this.uid = VirtualDOM.getUID(domNode);
    this.definition = DataStore.getModule(this.name);
    this.surrogateRoot = surrogateRoot;
    this.tree = new Tree(domNode, this.definition.tree, parent.tree.rootNode);
    this.famousNode = FamousConnector.addChild(parent.famousNode);
    this.behaviors = new Behaviors(this.definition.behaviors);
    this.controlFlow = new ControlFlow(this.behaviors.getBehaviorList());
    this.blockControlFlow = false;
    this.events = new Events(this.definition.events, this.name, this.getRootNode());
    this.states = new States(this.definition.states);
    this.timelines = new Timelines(this.definition.timelines, this.states);

    DataStore.registerComponent(this.uid, this);

    this.setEventListeners();
    this.initialize();
}

Component.prototype.handleBehaviorUpdate = function handleBehaviorUpdate(behavior) {
    BehaviorRouter.route(behavior, this);
};

Component.prototype.processDynamicRepeat = function processDynamicRepeat(behavior) {
    var expandedBlueprint = this.tree.getExpandedBlueprint();
    this.controlFlow.processRepeatBehavior(
        behavior, expandedBlueprint, this.uid
    );

    this.processControlFlowMessages();
}

Component.prototype.processDynamicIf = function processDynamicIf(behavior) {
    var expandedBlueprint = this.tree.getExpandedBlueprint();
    var blueprint = this.tree.getBlueprint();

    this.controlFlow.processIfBehavior(
        behavior, blueprint, expandedBlueprint, this.uid
    );

    this.processControlFlowMessages();
}

Component.prototype.processControlFlowMessages = function processControlFlowMessages() {
    var expandedBlueprint = this.tree.getExpandedBlueprint();
    var nodes = VirtualDOM.queryAttribute(expandedBlueprint, CONTROL_FLOW_ACTION_KEY);
    var newComponentCreated = false;
    var result;
    for (var i = 0; i < nodes.length; i++) {
        result = Component.processControlFlowMessage(nodes[i]);
        if (!newComponentCreated) {
            newComponentCreated = result;
        }
        nodes[i].removeAttribute(CONTROL_FLOW_ACTION_KEY);
    }

    // Trigger a global change from the parent to trigger behaviors that effect the
    // newly created elements
    if (newComponentCreated) {
        this.triggerGlobalChange(true);
    }
}

Component.processControlFlowMessage = function processControlFlowMessage(node) {
    var info = node.getAttribute(CONTROL_FLOW_ACTION_KEY);
    if (info) {
        info = JSON.parse(info);
        if (info.message === CREATE_KEY) {
            var baseNode = VirtualDOM.clone(node);
            VirtualDOM.removeChildNodes(baseNode);
            baseNode.removeAttribute(CONTROL_FLOW_ACTION_KEY);
            childComponent = new Component(baseNode, node, DataStore.getComponent(info.parentUID));
            return childComponent;
        }
        else if (info.message === DELETE_KEY) {
            var component = DataStore.getComponent(VirtualDOM.getUID(node));
            component.remove();
        }
    }
    return null;
}

Component.prototype.initialize = function initialize() {
    var self = this;

    this.processControlFlow(this.uid);

    this.behaviors.eachListItem(function(item) {
        self.states.createBehaviorListener(item);
    });

    this.events.initializeDescendantEvents(this.tree.getExpandedBlueprint(), this.uid);

    this.processDOMMessages();
    this.tree.stripExpandedBlueprintMessages();
    this.triggerGlobalChange(true); // Block dynamic control flow to avoid double processing
}

Component.prototype.processDOMMessages = function processDOMMessages() {
    var node = this.getRootNode();
    var messageStr = node.getAttribute(REPEAT_INFO_KEY);
    var index;
    var repeatInfo;
    if (messageStr) {
        var messageObj = JSON.parse(messageStr);
        index = messageObj[INDEX_KEY];
        repeatPayload = messageObj[REPEAT_PAYLOAD_KEY];
        this.events.sendMessages(repeatPayload, this.uid);
        node.removeAttribute(REPEAT_INFO_KEY);
    }
    else {
        index = 0;
        repeatPayload = null;
    }

    this.states.set(INDEX_KEY, index);
    this.states.set(REPEAT_PAYLOAD_KEY, repeatPayload);
}

Component.prototype.triggerGlobalChange = function triggerGlobalChange(blockControlFlow) {
    if (blockControlFlow) {
        this.blockControlFlow = true;
        this.states.triggerGlobalChange();
        this.blockControlFlow = false;
    }
    else {
        this.states.triggerGlobalChange();
    }
}

Component.prototype.processControlFlow = function processControlFlow(uid) {
    this.controlFlow.processSelfContainedFlows(this.tree.getBlueprint(), uid);

    // Check for default '$yield' overwrite via public events to minimize
    // ControlFlow's concerns
    if (this.events.getPublicEvent(YIELD_KEY)) {
        this.events.triggerPublicEvent(YIELD_KEY, {
            surrogateRoot: this.surrogateRoot
        }, this.uid);
    }
    else {
        this.controlFlow.processParentDefinedFlows(
            this.tree.getExpandedBlueprint(), this.surrogateRoot
        );
    }

    this.tree.getRootNode().removeAttribute(CONTROL_FLOW_ACTION_KEY);
}

Component.prototype.updateChildren = function updateChildren(childrenRoot) {
    var self = this;
    this.tree.setChildrenRoot(childrenRoot);

    var baseNode;
    this.tree.eachChild(function(node) {
        baseNode = VirtualDOM.clone(node);
        VirtualDOM.removeChildNodes(baseNode);
        childComponent = new Component(baseNode, node, self);
    });
}

Component.prototype.setEventListeners = function setEventListeners() {
    this.controlFlow.on('setExpandedBlueprint', this.tree.setExpandedBlueprint.bind(this.tree));
    this.controlFlow.on('setChildrenRoot', this.updateChildren.bind(this));
    this.states.on('behavior-update', this.handleBehaviorUpdate.bind(this));
}

Component.prototype.sendMessage = function sendMessage(key, message) {
    this.events.sendMessage(key, message, this.uid);
}

Component.prototype.getRootNode = function getRootNode() {
    return this.tree.rootNode;
}

Component.prototype.getParentComponent = function getParentComponent() {
    return DataStore.getComponent(VirtualDOM.getParentUID(this.getRootNode()));
}

Component.prototype.remove = function remove() {
    var parentComponent = this.getParentComponent();

    var rootNode = this.tree.getRootNode();
    if (rootNode.parentNode) {
        rootNode.parentNode.removeChild(rootNode);
    }

    var parentExpandedBlueprint = parentComponent.tree.getExpandedBlueprint();
    var targetNode = VirtualDOM.getNodeByUID(parentExpandedBlueprint, this.uid);
    // Target node may not be in parent's expanded blueprint if it was yielded
    // in by a grandparent
    if (targetNode) {
        parentExpandedBlueprint.removeChild(targetNode);
    }

    parentComponent.famousNode.removeChild(this.famousNode);

    // TODO --> Remove all listeners
    // TODO --> Recursively remove any children
    // TODO --> Remove from DataStore
}

Component.executeComponent = function executeComponent(name, selector) {
    // Shim tree to match Component Constructor API
    var wrapperNode = VirtualDOM.create('parent-tree:' + name);
    var topLevelTree = new Tree(wrapperNode, '', VirtualDOM.getBaseNode());

    var baseNode = VirtualDOM.create(name);
    VirtualDOM.setUID(baseNode, UID.generate(NODE_UID_PREFIX));

    return new Component(baseNode, null, {
        tree: topLevelTree,
        famousNode: FamousConnector.createRoot(selector)
    });
};

module.exports = Component;
<|endoftext|>


<commit_before>let toposort = require('toposort');
let async = require('async');

let Compiler = require('./compiler.js');
let utils = require('../utils/utils.js');

// TODO: create a contract object

class ContractsManager {
  constructor(options) {
    this.contractFiles = options.contractFiles;
    this.contractsConfig = options.contractsConfig;
    this.contracts = {};
    this.logger = options.logger;
    this.plugins = options.plugins;
    this.contractDependencies = {};
    this.gasLimit = options.gasLimit;
  }

  build(done) {
    let self = this;
    async.waterfall([
      function compileContracts(callback) {
        let compiler = new Compiler({plugins: self.plugins, logger: self.logger});
        compiler.compile_contracts(self.contractFiles, function (err, compiledObject) {
          self.compiledContracts = compiledObject;
          callback(err);
        });
      },
      function prepareContractsFromConfig(callback) {
        let className, contract;
        for (className in self.contractsConfig.contracts) {
          contract = self.contractsConfig.contracts[className];

          contract.className = className;
          contract.args = contract.args || [];

          self.contracts[className] = contract;
        }
        callback();
      },
      function prepareContractsFromCompilation(callback) {
        let className, compiledContract, contractConfig, contract;
        for (className in self.compiledContracts) {
          compiledContract = self.compiledContracts[className];
          contractConfig = self.contractsConfig.contracts[className];

          contract = self.contracts[className] || {className: className, args: []};

          contract.code = compiledContract.code;
          contract.runtimeBytecode = compiledContract.runtimeBytecode;
          contract.realRuntimeBytecode = (contract.realRuntimeBytecode || contract.runtimeBytecode);
          contract.swarmHash = compiledContract.swarmHash;
          contract.gasEstimates = compiledContract.gasEstimates;
          contract.functionHashes = compiledContract.functionHashes;
          contract.abiDefinition = compiledContract.abiDefinition;
          contract.filename = compiledContract.filename;

          contract.gas = (contractConfig && contractConfig.gas) || self.contractsConfig.gas || 'auto';
          //self.adjustGas(contract);

          contract.gasPrice = contract.gasPrice || self.contractsConfig.gasPrice;
          contract.type = 'file';
          contract.className = className;

          self.contracts[className] = contract;
        }
        callback();
      },
      function setDeployIntention(callback) {
        let className, contract;
        for (className in self.contracts) {
          contract = self.contracts[className];
          contract.deploy = (contract.deploy === undefined) || contract.deploy;
          if (contract.code === "") {
            self.logger.info("assuming " + className + " to be an interface");
            contract.deploy = false;
          }
        }
        callback();
      },
      /*eslint complexity: ["error", 11]*/
      function dealWithSpecialConfigs(callback) {
        let className, contract, parentContractName, parentContract;
        let dictionary = Object.keys(self.contracts);

        for (className in self.contracts) {
          contract = self.contracts[className];

          if (contract.instanceOf === undefined) {
            continue;
          }

          parentContractName = contract.instanceOf;
          parentContract = self.contracts[parentContractName];

          if (parentContract === className) {
            self.logger.error(className + ": instanceOf is set to itself");
            continue;
          }

          if (parentContract === undefined) {
            self.logger.error(className + ": couldn't find instanceOf contract " + parentContractName);
            let suggestion = utils.proposeAlternative(parentContractName, dictionary, [className, parentContractName]);
            if (suggestion) {
              self.logger.warn('did you mean "' + suggestion + '"?');
            }
            continue;
          }

          if (parentContract.args && parentContract.args.length > 0 && ((contract.args && contract.args.length === 0) || contract.args === undefined)) {
            contract.args = parentContract.args;
          }

          if (contract.code !== undefined) {
            self.logger.error(className + " has code associated to it but it's configured as an instanceOf " + parentContractName);
          }

          contract.code = parentContract.code;
          contract.runtimeBytecode = parentContract.runtimeBytecode;
          contract.gasEstimates = parentContract.gasEstimates;
          contract.functionHashes = parentContract.functionHashes;
          contract.abiDefinition = parentContract.abiDefinition;

          contract.gas = contract.gas || parentContract.gas;
          contract.gasPrice = contract.gasPrice || parentContract.gasPrice;
          contract.type = 'instance';

        }
        callback();
      },
      function removeContractsWithNoCode(callback) {
        let className, contract;
        let dictionary = Object.keys(self.contracts);
        for (className in self.contracts) {
          contract = self.contracts[className];

          if (contract.code === undefined) {
            self.logger.error(className + " has no code associated");
            let suggestion = utils.proposeAlternative(className, dictionary, [className]);
            if (suggestion) {
              self.logger.warn('did you mean "' + suggestion + '"?');
            }
            delete self.contracts[className];
          }
        }
        self.logger.trace(self.contracts);
        callback();
      },
      function determineDependencies(callback) {
        let className, contract;
        for (className in self.contracts) {
          contract = self.contracts[className];

          // look in code for dependencies
          let libMatches = (contract.code.match(/\:(.*?)(?=_)/g) || []);
          for (let match of libMatches) {
              self.contractDependencies[className] = self.contractDependencies[className] || [];
              self.contractDependencies[className].push(match.substr(1));
          }

          // look in arguments for dependencies
          if (contract.args === []) continue;
          let ref = contract.args;
          for (let j = 0; j < ref.length; j++) {
            let arg = ref[j];
            if (arg[0] === "$") {
              self.contractDependencies[className] = self.contractDependencies[className] || [];
              self.contractDependencies[className].push(arg.substr(1));
            }
          }

          // look in onDeploy for dependencies
          if (contract.onDeploy === [] || contract.onDeploy === undefined) continue;
          let regex = /\$\w+/g;
          contract.onDeploy.map((cmd) => {
            cmd.replace(regex, (match) => {
              self.contractDependencies[className] = self.contractDependencies[className] || [];
              self.contractDependencies[className].push(match.substr(1));
            });
          });
        }
        callback();
      }
    ], function (err, _result) {
      if (err) {
        self.logger.error("Error Compiling/Building contracts: " + err);
      }
      self.logger.trace("finished".underline);
      done(err, self);
    });
  }

  getContract(className) {
    return this.contracts[className];
  }

  sortContracts(contractList) {
    let converted_dependencies = [], i;

    for (let contract in this.contractDependencies) {
      let dependencies = this.contractDependencies[contract];
      for (i = 0; i < dependencies.length; i++) {
        converted_dependencies.push([contract, dependencies[i]]);
      }
    }

    let orderedDependencies;

    try {
      orderedDependencies =  toposort(converted_dependencies.filter((x) => x[0] != x[1])).reverse();
    } catch(e) {
      this.logger.error(("Error: " + e.message).red);
      this.logger.error("there are two or more contracts that depend on each other in a cyclic manner".bold.red);
      this.logger.error("Embark couldn't determine which one to deploy first".red);
      throw new Error("CyclicDependencyError");
      //process.exit(0);
    }

    let newList = contractList.sort(function (a, b) {
      let order_a = orderedDependencies.indexOf(a.className);
      let order_b = orderedDependencies.indexOf(b.className);
      return order_a - order_b;
    });

    return newList;
  }

  // TODO: should be built contracts
  listContracts() {
    let contracts = [];
    for (let className in this.contracts) {
      let contract = this.contracts[className];
      contracts.push(contract);
    }
    return this.sortContracts(contracts);
  }

  contractsState() {
    let data = [];

    for (let className in this.contracts) {
      let contract = this.contracts[className];

      let contractData;

      if (contract.deploy === false) {
        contractData = [
          className.green,
          'Interface or set to not deploy'.green,
          "\t\tn/a".green
        ];
      } else if (contract.error) {
        contractData = [
          className.green,
          (contract.error).split("\n")[0].replace(/Error: /g, '').substring(0, 32).red,
          '\t\tError'.red
        ];
      } else {
        contractData = [
          className.green,
          (contract.deployedAddress || '...').green,
          ((contract.deployedAddress !== undefined) ? "\t\tDeployed".green : "\t\tPending".magenta)
        ];
      }

      data.push(contractData);
    }

    return data;
  }

  //adjustGas(contract) {
  //  let maxGas, adjustedGas;
  //  if (contract.gas === 'auto') {
  //    if (contract.deploy || contract.deploy === undefined) {
  //      if (contract.gasEstimates.creation !== undefined) {
  //        // TODO: should sum it instead
  //        maxGas = Math.max(contract.gasEstimates.creation[0], contract.gasEstimates.creation[1], 500000);
  //      } else {
  //        maxGas = 500000;
  //      }
  //    } else {
  //      maxGas = 500000;
  //    }
  //    // TODO: put a check so it doesn't go over the block limit
  //    adjustedGas = Math.round(maxGas * 1.40);
  //    adjustedGas += 25000;
  //    contract.gas = adjustedGas;
  //    if (this.gasLimit && this.gasLimit > contract.gas) {
  //      contract.gas = this.gasLimit;
  //    }
  //  }
  //}
}

module.exports = ContractsManager;
<commit_msg>remove old code<commit_after>let toposort = require('toposort');
let async = require('async');

let Compiler = require('./compiler.js');
let utils = require('../utils/utils.js');

// TODO: create a contract object

class ContractsManager {
  constructor(options) {
    this.contractFiles = options.contractFiles;
    this.contractsConfig = options.contractsConfig;
    this.contracts = {};
    this.logger = options.logger;
    this.plugins = options.plugins;
    this.contractDependencies = {};
    this.gasLimit = options.gasLimit;
  }

  build(done) {
    let self = this;
    async.waterfall([
      function compileContracts(callback) {
        let compiler = new Compiler({plugins: self.plugins, logger: self.logger});
        compiler.compile_contracts(self.contractFiles, function (err, compiledObject) {
          self.compiledContracts = compiledObject;
          callback(err);
        });
      },
      function prepareContractsFromConfig(callback) {
        let className, contract;
        for (className in self.contractsConfig.contracts) {
          contract = self.contractsConfig.contracts[className];

          contract.className = className;
          contract.args = contract.args || [];

          self.contracts[className] = contract;
        }
        callback();
      },
      function prepareContractsFromCompilation(callback) {
        let className, compiledContract, contractConfig, contract;
        for (className in self.compiledContracts) {
          compiledContract = self.compiledContracts[className];
          contractConfig = self.contractsConfig.contracts[className];

          contract = self.contracts[className] || {className: className, args: []};

          contract.code = compiledContract.code;
          contract.runtimeBytecode = compiledContract.runtimeBytecode;
          contract.realRuntimeBytecode = (contract.realRuntimeBytecode || contract.runtimeBytecode);
          contract.swarmHash = compiledContract.swarmHash;
          contract.gasEstimates = compiledContract.gasEstimates;
          contract.functionHashes = compiledContract.functionHashes;
          contract.abiDefinition = compiledContract.abiDefinition;
          contract.filename = compiledContract.filename;

          contract.gas = (contractConfig && contractConfig.gas) || self.contractsConfig.gas || 'auto';

          contract.gasPrice = contract.gasPrice || self.contractsConfig.gasPrice;
          contract.type = 'file';
          contract.className = className;

          self.contracts[className] = contract;
        }
        callback();
      },
      function setDeployIntention(callback) {
        let className, contract;
        for (className in self.contracts) {
          contract = self.contracts[className];
          contract.deploy = (contract.deploy === undefined) || contract.deploy;
          if (contract.code === "") {
            self.logger.info("assuming " + className + " to be an interface");
            contract.deploy = false;
          }
        }
        callback();
      },
      /*eslint complexity: ["error", 11]*/
      function dealWithSpecialConfigs(callback) {
        let className, contract, parentContractName, parentContract;
        let dictionary = Object.keys(self.contracts);

        for (className in self.contracts) {
          contract = self.contracts[className];

          if (contract.instanceOf === undefined) {
            continue;
          }

          parentContractName = contract.instanceOf;
          parentContract = self.contracts[parentContractName];

          if (parentContract === className) {
            self.logger.error(className + ": instanceOf is set to itself");
            continue;
          }

          if (parentContract === undefined) {
            self.logger.error(className + ": couldn't find instanceOf contract " + parentContractName);
            let suggestion = utils.proposeAlternative(parentContractName, dictionary, [className, parentContractName]);
            if (suggestion) {
              self.logger.warn('did you mean "' + suggestion + '"?');
            }
            continue;
          }

          if (parentContract.args && parentContract.args.length > 0 && ((contract.args && contract.args.length === 0) || contract.args === undefined)) {
            contract.args = parentContract.args;
          }

          if (contract.code !== undefined) {
            self.logger.error(className + " has code associated to it but it's configured as an instanceOf " + parentContractName);
          }

          contract.code = parentContract.code;
          contract.runtimeBytecode = parentContract.runtimeBytecode;
          contract.gasEstimates = parentContract.gasEstimates;
          contract.functionHashes = parentContract.functionHashes;
          contract.abiDefinition = parentContract.abiDefinition;

          contract.gas = contract.gas || parentContract.gas;
          contract.gasPrice = contract.gasPrice || parentContract.gasPrice;
          contract.type = 'instance';

        }
        callback();
      },
      function removeContractsWithNoCode(callback) {
        let className, contract;
        let dictionary = Object.keys(self.contracts);
        for (className in self.contracts) {
          contract = self.contracts[className];

          if (contract.code === undefined) {
            self.logger.error(className + " has no code associated");
            let suggestion = utils.proposeAlternative(className, dictionary, [className]);
            if (suggestion) {
              self.logger.warn('did you mean "' + suggestion + '"?');
            }
            delete self.contracts[className];
          }
        }
        self.logger.trace(self.contracts);
        callback();
      },
      function determineDependencies(callback) {
        let className, contract;
        for (className in self.contracts) {
          contract = self.contracts[className];

          // look in code for dependencies
          let libMatches = (contract.code.match(/\:(.*?)(?=_)/g) || []);
          for (let match of libMatches) {
              self.contractDependencies[className] = self.contractDependencies[className] || [];
              self.contractDependencies[className].push(match.substr(1));
          }

          // look in arguments for dependencies
          if (contract.args === []) continue;
          let ref = contract.args;
          for (let j = 0; j < ref.length; j++) {
            let arg = ref[j];
            if (arg[0] === "$") {
              self.contractDependencies[className] = self.contractDependencies[className] || [];
              self.contractDependencies[className].push(arg.substr(1));
            }
          }

          // look in onDeploy for dependencies
          if (contract.onDeploy === [] || contract.onDeploy === undefined) continue;
          let regex = /\$\w+/g;
          contract.onDeploy.map((cmd) => {
            cmd.replace(regex, (match) => {
              self.contractDependencies[className] = self.contractDependencies[className] || [];
              self.contractDependencies[className].push(match.substr(1));
            });
          });
        }
        callback();
      }
    ], function (err, _result) {
      if (err) {
        self.logger.error("Error Compiling/Building contracts: " + err);
      }
      self.logger.trace("finished".underline);
      done(err, self);
    });
  }

  getContract(className) {
    return this.contracts[className];
  }

  sortContracts(contractList) {
    let converted_dependencies = [], i;

    for (let contract in this.contractDependencies) {
      let dependencies = this.contractDependencies[contract];
      for (i = 0; i < dependencies.length; i++) {
        converted_dependencies.push([contract, dependencies[i]]);
      }
    }

    let orderedDependencies;

    try {
      orderedDependencies =  toposort(converted_dependencies.filter((x) => x[0] != x[1])).reverse();
    } catch(e) {
      this.logger.error(("Error: " + e.message).red);
      this.logger.error("there are two or more contracts that depend on each other in a cyclic manner".bold.red);
      this.logger.error("Embark couldn't determine which one to deploy first".red);
      throw new Error("CyclicDependencyError");
      //process.exit(0);
    }

    let newList = contractList.sort(function (a, b) {
      let order_a = orderedDependencies.indexOf(a.className);
      let order_b = orderedDependencies.indexOf(b.className);
      return order_a - order_b;
    });

    return newList;
  }

  // TODO: should be built contracts
  listContracts() {
    let contracts = [];
    for (let className in this.contracts) {
      let contract = this.contracts[className];
      contracts.push(contract);
    }
    return this.sortContracts(contracts);
  }

  contractsState() {
    let data = [];

    for (let className in this.contracts) {
      let contract = this.contracts[className];

      let contractData;

      if (contract.deploy === false) {
        contractData = [
          className.green,
          'Interface or set to not deploy'.green,
          "\t\tn/a".green
        ];
      } else if (contract.error) {
        contractData = [
          className.green,
          (contract.error).split("\n")[0].replace(/Error: /g, '').substring(0, 32).red,
          '\t\tError'.red
        ];
      } else {
        contractData = [
          className.green,
          (contract.deployedAddress || '...').green,
          ((contract.deployedAddress !== undefined) ? "\t\tDeployed".green : "\t\tPending".magenta)
        ];
      }

      data.push(contractData);
    }

    return data;
  }
}

module.exports = ContractsManager;
<|endoftext|>


<commit_before>var fs = require('graceful-fs')

var BUF_LENGTH = 64 * 1024
var _buff = new Buffer(BUF_LENGTH)

var copyFileSync = function (srcFile, destFile, clobber) {
  if (fs.existsSync(destFile) && !clobber) {
    throw Error('EEXIST')
  }

  var fdr = fs.openSync(srcFile, 'r')
  var stat = fs.fstatSync(fdr)
  var fdw = fs.openSync(destFile, 'w', stat.mode)
  var bytesRead = 1
  var pos = 0

  while (bytesRead > 0) {
    bytesRead = fs.readSync(fdr, _buff, 0, BUF_LENGTH, pos)
    fs.writeSync(fdw, _buff, 0, bytesRead)
    pos += bytesRead
  }

  fs.closeSync(fdr)
  fs.closeSync(fdw)
}

module.exports = copyFileSync
<commit_msg>lib/copy/copy-file-sync: cleanup from CoffeeScript days<commit_after>var fs = require('graceful-fs')

var BUF_LENGTH = 64 * 1024
var _buff = new Buffer(BUF_LENGTH)

function copyFileSync (srcFile, destFile, clobber) {
  if (fs.existsSync(destFile) && !clobber) {
    throw Error('EEXIST')
  }

  var fdr = fs.openSync(srcFile, 'r')
  var stat = fs.fstatSync(fdr)
  var fdw = fs.openSync(destFile, 'w', stat.mode)
  var bytesRead = 1
  var pos = 0

  while (bytesRead > 0) {
    bytesRead = fs.readSync(fdr, _buff, 0, BUF_LENGTH, pos)
    fs.writeSync(fdw, _buff, 0, bytesRead)
    pos += bytesRead
  }

  fs.closeSync(fdr)
  fs.closeSync(fdw)
}

module.exports = copyFileSync
<|endoftext|>


<commit_before>'use strict';
const Msg = require('../connection/msg').Msg;
const KillCursor = require('../connection/commands').KillCursor;
const GetMore = require('../connection/commands').GetMore;
const calculateDurationInMs = require('../utils').calculateDurationInMs;

/** Commands that we want to redact because of the sensitive nature of their contents */
const SENSITIVE_COMMANDS = new Set([
  'authenticate',
  'saslStart',
  'saslContinue',
  'getnonce',
  'createUser',
  'updateUser',
  'copydbgetnonce',
  'copydbsaslstart',
  'copydb'
]);

// helper methods
const extractCommandName = commandDoc => Object.keys(commandDoc)[0];
const namespace = command => command.ns;
const databaseName = command => command.ns.split('.')[0];
const collectionName = command => command.ns.split('.')[1];
const generateConnectionId = pool =>
  pool.options ? `${pool.options.host}:${pool.options.port}` : pool.id;
const maybeRedact = (commandName, result) => (SENSITIVE_COMMANDS.has(commandName) ? {} : result);

const LEGACY_FIND_QUERY_MAP = {
  $query: 'filter',
  $orderby: 'sort',
  $hint: 'hint',
  $comment: 'comment',
  $maxScan: 'maxScan',
  $max: 'max',
  $min: 'min',
  $returnKey: 'returnKey',
  $showDiskLoc: 'showRecordId',
  $maxTimeMS: 'maxTimeMS',
  $snapshot: 'snapshot'
};

const LEGACY_FIND_OPTIONS_MAP = {
  numberToSkip: 'skip',
  numberToReturn: 'batchSize',
  returnFieldsSelector: 'projection'
};

const OP_QUERY_KEYS = [
  'tailable',
  'oplogReplay',
  'noCursorTimeout',
  'awaitData',
  'partial',
  'exhaust'
];

/**
 * Extract the actual command from the query, possibly upconverting if it's a legacy
 * format
 *
 * @param {Object} command the command
 */
const extractCommand = command => {
  if (command instanceof GetMore) {
    return {
      getMore: command.cursorId,
      collection: collectionName(command),
      batchSize: command.numberToReturn
    };
  }

  if (command instanceof KillCursor) {
    return {
      killCursors: collectionName(command),
      cursors: command.cursorIds
    };
  }

  if (command instanceof Msg) {
    return command.command;
  }

  if (command.query && command.query.$query) {
    let result;
    if (command.ns === 'admin.$cmd') {
      // upconvert legacy command
      result = Object.assign({}, command.query.$query);
    } else {
      // upconvert legacy find command
      result = { find: collectionName(command) };
      Object.keys(LEGACY_FIND_QUERY_MAP).forEach(key => {
        if (typeof command.query[key] !== 'undefined')
          result[LEGACY_FIND_QUERY_MAP[key]] = command.query[key];
      });
    }

    Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach(key => {
      if (typeof command[key] !== 'undefined') result[LEGACY_FIND_OPTIONS_MAP[key]] = command[key];
    });

    OP_QUERY_KEYS.forEach(key => {
      if (command[key]) result[key] = command[key];
    });

    if (typeof command.pre32Limit !== 'undefined') {
      result.limit = command.pre32Limit;
    }

    if (command.query.$explain) {
      return { explain: result };
    }

    return result;
  }

  return command.query ? command.query : command;
};

const extractReply = (command, reply) => {
  if (command instanceof GetMore) {
    return {
      ok: 1,
      cursor: {
        id: reply.message.cursorId,
        ns: namespace(command),
        nextBatch: reply.message.documents
      }
    };
  }

  if (command instanceof KillCursor) {
    return {
      ok: 1,
      cursorsUnknown: command.cursorIds
    };
  }

  // is this a legacy find command?
  if (command.query && typeof command.query.$query !== 'undefined') {
    return {
      ok: 1,
      cursor: {
        id: reply.message.cursorId,
        ns: namespace(command),
        firstBatch: reply.message.documents
      }
    };
  }

  return reply && reply.result ? reply.result : reply;
};

/** An event indicating the start of a given command */
class CommandStartedEvent {
  /**
   * Create a started event
   *
   * @param {Pool} pool the pool that originated the command
   * @param {Object} command the command
   */
  constructor(pool, command) {
    const cmd = extractCommand(command);
    const commandName = extractCommandName(cmd);

    // NOTE: remove in major revision, this is not spec behavior
    if (SENSITIVE_COMMANDS.has(commandName)) {
      this.commandObj = {};
      this.commandObj[commandName] = true;
    }

    Object.assign(this, {
      connectionId: generateConnectionId(pool),
      requestId: command.requestId,
      databaseName: databaseName(command),
      commandName,
      command: cmd
    });
  }
}

/** An event indicating the success of a given command */
class CommandSucceededEvent {
  /**
   * Create a succeeded event
   *
   * @param {Pool} pool the pool that originated the command
   * @param {Object} command the command
   * @param {Object} reply the reply for this command from the server
   * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration
   */
  constructor(pool, command, reply, started) {
    const cmd = extractCommand(command);
    const commandName = extractCommandName(cmd);

    Object.assign(this, {
      connectionId: generateConnectionId(pool),
      requestId: command.requestId,
      commandName,
      duration: calculateDurationInMs(started),
      reply: maybeRedact(commandName, extractReply(command, reply))
    });
  }
}

/** An event indicating the failure of a given command */
class CommandFailedEvent {
  /**
   * Create a failure event
   *
   * @param {Pool} pool the pool that originated the command
   * @param {Object} command the command
   * @param {MongoError|Object} error the generated error or a server error response
   * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration
   */
  constructor(pool, command, error, started) {
    const cmd = extractCommand(command);
    const commandName = extractCommandName(cmd);

    Object.assign(this, {
      connectionId: generateConnectionId(pool),
      requestId: command.requestId,
      commandName,
      duration: calculateDurationInMs(started),
      failure: maybeRedact(commandName, error)
    });
  }
}

module.exports = {
  CommandStartedEvent,
  CommandSucceededEvent,
  CommandFailedEvent
};
<commit_msg>refactor: use the connection's address for monitoring events<commit_after>'use strict';
const Msg = require('../connection/msg').Msg;
const KillCursor = require('../connection/commands').KillCursor;
const GetMore = require('../connection/commands').GetMore;
const calculateDurationInMs = require('../utils').calculateDurationInMs;

/** Commands that we want to redact because of the sensitive nature of their contents */
const SENSITIVE_COMMANDS = new Set([
  'authenticate',
  'saslStart',
  'saslContinue',
  'getnonce',
  'createUser',
  'updateUser',
  'copydbgetnonce',
  'copydbsaslstart',
  'copydb'
]);

// helper methods
const extractCommandName = commandDoc => Object.keys(commandDoc)[0];
const namespace = command => command.ns;
const databaseName = command => command.ns.split('.')[0];
const collectionName = command => command.ns.split('.')[1];
const generateConnectionId = pool =>
  pool.options ? `${pool.options.host}:${pool.options.port}` : pool.address;
const maybeRedact = (commandName, result) => (SENSITIVE_COMMANDS.has(commandName) ? {} : result);

const LEGACY_FIND_QUERY_MAP = {
  $query: 'filter',
  $orderby: 'sort',
  $hint: 'hint',
  $comment: 'comment',
  $maxScan: 'maxScan',
  $max: 'max',
  $min: 'min',
  $returnKey: 'returnKey',
  $showDiskLoc: 'showRecordId',
  $maxTimeMS: 'maxTimeMS',
  $snapshot: 'snapshot'
};

const LEGACY_FIND_OPTIONS_MAP = {
  numberToSkip: 'skip',
  numberToReturn: 'batchSize',
  returnFieldsSelector: 'projection'
};

const OP_QUERY_KEYS = [
  'tailable',
  'oplogReplay',
  'noCursorTimeout',
  'awaitData',
  'partial',
  'exhaust'
];

/**
 * Extract the actual command from the query, possibly upconverting if it's a legacy
 * format
 *
 * @param {Object} command the command
 */
const extractCommand = command => {
  if (command instanceof GetMore) {
    return {
      getMore: command.cursorId,
      collection: collectionName(command),
      batchSize: command.numberToReturn
    };
  }

  if (command instanceof KillCursor) {
    return {
      killCursors: collectionName(command),
      cursors: command.cursorIds
    };
  }

  if (command instanceof Msg) {
    return command.command;
  }

  if (command.query && command.query.$query) {
    let result;
    if (command.ns === 'admin.$cmd') {
      // upconvert legacy command
      result = Object.assign({}, command.query.$query);
    } else {
      // upconvert legacy find command
      result = { find: collectionName(command) };
      Object.keys(LEGACY_FIND_QUERY_MAP).forEach(key => {
        if (typeof command.query[key] !== 'undefined')
          result[LEGACY_FIND_QUERY_MAP[key]] = command.query[key];
      });
    }

    Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach(key => {
      if (typeof command[key] !== 'undefined') result[LEGACY_FIND_OPTIONS_MAP[key]] = command[key];
    });

    OP_QUERY_KEYS.forEach(key => {
      if (command[key]) result[key] = command[key];
    });

    if (typeof command.pre32Limit !== 'undefined') {
      result.limit = command.pre32Limit;
    }

    if (command.query.$explain) {
      return { explain: result };
    }

    return result;
  }

  return command.query ? command.query : command;
};

const extractReply = (command, reply) => {
  if (command instanceof GetMore) {
    return {
      ok: 1,
      cursor: {
        id: reply.message.cursorId,
        ns: namespace(command),
        nextBatch: reply.message.documents
      }
    };
  }

  if (command instanceof KillCursor) {
    return {
      ok: 1,
      cursorsUnknown: command.cursorIds
    };
  }

  // is this a legacy find command?
  if (command.query && typeof command.query.$query !== 'undefined') {
    return {
      ok: 1,
      cursor: {
        id: reply.message.cursorId,
        ns: namespace(command),
        firstBatch: reply.message.documents
      }
    };
  }

  return reply && reply.result ? reply.result : reply;
};

/** An event indicating the start of a given command */
class CommandStartedEvent {
  /**
   * Create a started event
   *
   * @param {Pool} pool the pool that originated the command
   * @param {Object} command the command
   */
  constructor(pool, command) {
    const cmd = extractCommand(command);
    const commandName = extractCommandName(cmd);

    // NOTE: remove in major revision, this is not spec behavior
    if (SENSITIVE_COMMANDS.has(commandName)) {
      this.commandObj = {};
      this.commandObj[commandName] = true;
    }

    Object.assign(this, {
      connectionId: generateConnectionId(pool),
      requestId: command.requestId,
      databaseName: databaseName(command),
      commandName,
      command: cmd
    });
  }
}

/** An event indicating the success of a given command */
class CommandSucceededEvent {
  /**
   * Create a succeeded event
   *
   * @param {Pool} pool the pool that originated the command
   * @param {Object} command the command
   * @param {Object} reply the reply for this command from the server
   * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration
   */
  constructor(pool, command, reply, started) {
    const cmd = extractCommand(command);
    const commandName = extractCommandName(cmd);

    Object.assign(this, {
      connectionId: generateConnectionId(pool),
      requestId: command.requestId,
      commandName,
      duration: calculateDurationInMs(started),
      reply: maybeRedact(commandName, extractReply(command, reply))
    });
  }
}

/** An event indicating the failure of a given command */
class CommandFailedEvent {
  /**
   * Create a failure event
   *
   * @param {Pool} pool the pool that originated the command
   * @param {Object} command the command
   * @param {MongoError|Object} error the generated error or a server error response
   * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration
   */
  constructor(pool, command, error, started) {
    const cmd = extractCommand(command);
    const commandName = extractCommandName(cmd);

    Object.assign(this, {
      connectionId: generateConnectionId(pool),
      requestId: command.requestId,
      commandName,
      duration: calculateDurationInMs(started),
      failure: maybeRedact(commandName, error)
    });
  }
}

module.exports = {
  CommandStartedEvent,
  CommandSucceededEvent,
  CommandFailedEvent
};
<|endoftext|>


<commit_before>'use strict';

var makeComposition = require('./composition').makeComposition;

var regex = /(.*?)(?:\s+?)(extends\s+?)((?:.|\n)*?){(?:(?:.|\n)*?)}/g;

module.exports = function extractExtends(css, hashed) {
  var extensions = {}; // to be filled with extensions
  var match; // match placeholder for the following while loop

  // begin extracting and replacing all extensions
  while ((match = regex.exec(css)) !== null) {
    var extendee = getClassName(match[1]);
    var keyword = match[2];
    var extended = match[3];

    var substr = css.substr(match.index);
    var replaced = substr.replace(keyword, '').replace(extended, '');
    var replacedLen = extended.length + keyword.length;
    regex.lastIndex -= replacedLen;
    css = css.substring(0, match.index) + replaced;

    var classes = [extendee].concat(splitter(extended));
    var unscoped = classes.map(name => hashed[name] ? hashed[name] : name);

    extensions[extendee] = makeComposition(classes, unscoped);
  }
  // all extensions have now been extracted and replaced

  return {
    css: css,
    extensions: extensions
  }
}

function splitter(match) {
  return match.split(',').map(getClassName);
}

function getClassName(str) {
  var trimmed = str.trim();
  return trimmed[0] === '.' ? trimmed.substr(1) : trimmed;
}
<commit_msg>more functional extension extraction<commit_after>'use strict';

var makeComposition = require('./composition').makeComposition;

var regex = /(.*?)(?:\s+?)(extends\s+?)((?:.|\n)*?){(?:(?:.|\n)*?)}/g;

module.exports = function extractExtends(css, hashed) {
  var found, matches = [];
  while (found = regex.exec(css)) {
    matches.unshift(found);
  }

  function reduceMatch(acc, match) {
    var extendee = getClassName(match[1]);
    var keyword = match[2];
    var extended = match[3];

    // remove from output css
    var index = acc.css.indexOf(keyword, match.index);
    var len = keyword.length + extended.length;
    acc.css = acc.css.slice(0, index) + acc.css.slice(index + len);

    // add to output extensions
    var classes = [extendee].concat(splitter(extended));
    var unscoped = classes.map(name => hashed[name] ? hashed[name] : name);
    acc.extensions[extendee] = makeComposition(classes, unscoped);

    return acc;
  }

  return matches.reduce(reduceMatch, {
    css: css,
    extensions: {}
  });
}

function splitter(match) {
  return match.split(',').map(getClassName);
}

function getClassName(str) {
  var trimmed = str.trim();
  return trimmed[0] === '.' ? trimmed.substr(1) : trimmed;
}
<|endoftext|>