<commit_before>// Copyright 2014-2018, University of Colorado Boulder

/**
 * Node that represents a "beaker container" in the view.  A beaker container is a beaker that contains fluid, and in
 * which other objects can be placed, which generally displaces the fluid.
 *
 * See the header comments in the parent class for some important information about how this class is used on the
 * canvas.
 *
 * @author John Blanco
 * @author Jesse Greenberg
 * @author Andrew Adare
 */
define( function( require ) {
  'use strict';

  // modules
  var BeakerView = require( 'ENERGY_FORMS_AND_CHANGES/common/view/BeakerView' );
  var EFACConstants = require( 'ENERGY_FORMS_AND_CHANGES/common/EFACConstants' );
  var energyFormsAndChanges = require( 'ENERGY_FORMS_AND_CHANGES/energyFormsAndChanges' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Shape = require( 'KITE/Shape' );
  var ThermalElementDragHandler = require( 'ENERGY_FORMS_AND_CHANGES/intro/view/ThermalElementDragHandler' );
  var Vector2 = require( 'DOT/Vector2' );

  // constants
  var BLOCK_PERSPECTIVE_ANGLE = EFACConstants.BLOCK_PERSPECTIVE_ANGLE;

  /**
   * @param {Beaker} beaker
   * @param {EFACIntroModel} model
   * @param {ModelViewTransform2} modelViewTransform
   * @param {function} constrainPosition
   * @param {Object} [options]
   */
  function BeakerContainerView( beaker, model, modelViewTransform, constrainPosition, options ) {

    var self = this;
    BeakerView.call( this, beaker, model.energyChunksVisibleProperty, modelViewTransform, options );

    // For each block that can go in the beaker we need to add a listener that will update the clipping area when that
    // block is moved.  The clipping area hides energy chunks that overlap with blocks, making it look much less
    // visually distracting, as though the energy chunks in the beaker are behind the blocks.
    model.blocks.forEach( function( block ) {
      block.positionProperty.link( function() {
        self.updateEnergyChunkClipArea( beaker, model.blocks, modelViewTransform );
      } );
    } );

    // update the clipping mask when the position of the beaker moves
    beaker.positionProperty.link( function() {
      self.updateEnergyChunkClipArea( beaker, model.blocks, modelViewTransform );
    } );

    this.grabNode.addInputListener( new ThermalElementDragHandler(
      beaker,
      this.grabNode,
      modelViewTransform,
      constrainPosition
    ) );
  }

  energyFormsAndChanges.register( 'BeakerContainerView', BeakerContainerView );

  return inherit( BeakerView, BeakerContainerView, {

    /**
     * Update the clipping area that is used to hide energy chunks that are in the beaker but occluded by blocks that
     * are ALSO in the beaker.
     * @param {Beaker} beaker
     * @param {Block[]} blocks
     * @param {ModelViewTransform2} modelViewTransform
     * @private
     */
    updateEnergyChunkClipArea: function( beaker, blocks, modelViewTransform ) {

      var beakerPosition = beaker.positionProperty.get();

      var beakerUpperLeftInViewCoords = modelViewTransform.modelToViewXY(
        beakerPosition.x - beaker.width / 2,
        beakerPosition.y + beaker.height
      );

      // The clip area is defined by an outer rectangle that is basically the entire beaker area and then some inner
      // rectangles for the blocks if they overlap with the beaker.  The inner pieces have to be drawn with the opposite
      // winding order from the outer ones in order to create the "hole" effect.  The outer shape extends above and
      // below the basic beaker model rectangle in order to prevent clipping of energy chunks that are positioned at
      // the upper and lower rim of the beaker and energy chunks moving between the beaker and the heater/cooler.
      var beakerRectangleHeightInView = -modelViewTransform.modelToViewDeltaY( beaker.height );
      var clipArea = new Shape.rect(
        beakerUpperLeftInViewCoords.x,
        beakerUpperLeftInViewCoords.y - beakerRectangleHeightInView * 0.5,
        modelViewTransform.modelToViewDeltaX( beaker.width ),
        beakerRectangleHeightInView * 2
      );

      // c-style loop for best performance
      for ( var i = 0; i < blocks.length; i++ ) {
        this.addProjectedBlockToShape( blocks[ i ], clipArea, modelViewTransform );
      }

      // set the updated clip area
      this.energyChunkRootNode.clipArea = clipArea;
    },

    /**
     * Add a projected and transformed block shape to the provided shape.  This is a convenience method for essentially
     * making "holes" that match the block in the clip area inside the beaker.
     * @param {Block} block
     * @param {Shape} shape
     * @param {ModelViewTransform2} modelViewTransform
     * @private
     */
    addProjectedBlockToShape: function( block, shape, modelViewTransform ) {

      var blockPositionInView = modelViewTransform.modelToViewPosition( block.positionProperty.value );
      var blockWidthInView = modelViewTransform.modelToViewDeltaX( block.width );
      var blockHeightInView = -modelViewTransform.modelToViewDeltaY( block.height );
      var shapeBounds = shape.bounds;

      var perspectiveEdgeSize = modelViewTransform.modelToViewDeltaX(
        block.width * EFACConstants.BLOCK_PERSPECTIVE_EDGE_PROPORTION
      );
      var forwardProjectionVector = new Vector2( -perspectiveEdgeSize / 2, 0 ).rotated( -BLOCK_PERSPECTIVE_ANGLE );

      // The following code makes some assumptions that are known to be true for the EFAC simulation but which wouldn't
      // necessarily true for a generalized version of this.  Those assumptions are that the provided shape is
      // rectangular and that the position of the block is the bottom center.
      if ( shapeBounds.containsPoint( blockPositionInView ) ) {
        shape.moveTo(
          blockPositionInView.x - blockWidthInView / 2 + forwardProjectionVector.x,
          blockPositionInView.y + forwardProjectionVector.y
        );
        shape.lineToRelative( blockWidthInView, 0 );
        shape.lineToRelative( -forwardProjectionVector.x * 2, -forwardProjectionVector.y * 2 );
        shape.lineToRelative( 0, -blockHeightInView );
        shape.lineToRelative( -blockWidthInView, 0 );
        shape.lineToRelative( forwardProjectionVector.x * 2, forwardProjectionVector.y * 2 );
        shape.lineToRelative( 0, blockHeightInView );
      }
    }
  } );
} );

<commit_msg>added handling for special case of clip area when blocks overlap in beaker, see https://github.com/phetsims/energy-forms-and-changes/issues/114<commit_after>// Copyright 2014-2018, University of Colorado Boulder

/**
 * Node that represents a "beaker container" in the view.  A beaker container is a beaker that contains fluid, and in
 * which other objects can be placed, which generally displaces the fluid.
 *
 * See the header comments in the parent class for some important information about how this class is used on the
 * canvas.
 *
 * @author John Blanco
 * @author Jesse Greenberg
 * @author Andrew Adare
 */
define( function( require ) {
  'use strict';

  // modules
  var BeakerView = require( 'ENERGY_FORMS_AND_CHANGES/common/view/BeakerView' );
  var EFACConstants = require( 'ENERGY_FORMS_AND_CHANGES/common/EFACConstants' );
  var energyFormsAndChanges = require( 'ENERGY_FORMS_AND_CHANGES/energyFormsAndChanges' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Shape = require( 'KITE/Shape' );
  var ThermalElementDragHandler = require( 'ENERGY_FORMS_AND_CHANGES/intro/view/ThermalElementDragHandler' );
  var Vector2 = require( 'DOT/Vector2' );

  // constants
  var BLOCK_PERSPECTIVE_ANGLE = EFACConstants.BLOCK_PERSPECTIVE_ANGLE;

  /**
   * @param {Beaker} beaker
   * @param {EFACIntroModel} model
   * @param {ModelViewTransform2} modelViewTransform
   * @param {function} constrainPosition
   * @param {Object} [options]
   */
  function BeakerContainerView( beaker, model, modelViewTransform, constrainPosition, options ) {

    var self = this;
    BeakerView.call( this, beaker, model.energyChunksVisibleProperty, modelViewTransform, options );

    // For each block that can go in the beaker we need to add a listener that will update the clipping area when that
    // block is moved.  The clipping area hides energy chunks that overlap with blocks, making it look much less
    // visually distracting, as though the energy chunks in the beaker are behind the blocks.
    model.blocks.forEach( function( block ) {
      block.positionProperty.link( function() {
        self.updateEnergyChunkClipArea( beaker, model.blocks, modelViewTransform );
      } );
    } );

    // update the clipping mask when the position of the beaker moves
    beaker.positionProperty.link( function() {
      self.updateEnergyChunkClipArea( beaker, model.blocks, modelViewTransform );
    } );

    this.grabNode.addInputListener( new ThermalElementDragHandler(
      beaker,
      this.grabNode,
      modelViewTransform,
      constrainPosition
    ) );
  }

  energyFormsAndChanges.register( 'BeakerContainerView', BeakerContainerView );

  return inherit( BeakerView, BeakerContainerView, {

    /**
     * Update the clipping area that is used to hide energy chunks that are in the beaker but occluded by blocks that
     * are ALSO in the beaker.
     * @param {Beaker} beaker
     * @param {Block[]} blocks
     * @param {ModelViewTransform2} modelViewTransform
     * @private
     */
    updateEnergyChunkClipArea: function( beaker, blocks, modelViewTransform ) {

      var beakerPosition = beaker.positionProperty.get();

      var beakerUpperLeftInViewCoords = modelViewTransform.modelToViewXY(
        beakerPosition.x - beaker.width / 2,
        beakerPosition.y + beaker.height
      );

      // The clip area is defined by an outer rectangle that is basically the entire beaker area and then some inner
      // rectangles for the blocks if they overlap with the beaker.  The inner pieces have to be drawn with the opposite
      // winding order from the outer ones in order to create the "hole" effect.  The outer shape extends above and
      // below the basic beaker model rectangle in order to prevent clipping of energy chunks that are positioned at
      // the upper and lower rim of the beaker and energy chunks moving between the beaker and the heater/cooler.
      var beakerRectangleHeightInView = -modelViewTransform.modelToViewDeltaY( beaker.height );
      var clipArea = new Shape.rect(
        beakerUpperLeftInViewCoords.x,
        beakerUpperLeftInViewCoords.y - beakerRectangleHeightInView * 0.5,
        modelViewTransform.modelToViewDeltaX( beaker.width ),
        beakerRectangleHeightInView * 2
      );

      // add the "holes" in the clip mask that correspond to the blocks
      this.addProjectedBlocksToClipArea( blocks, clipArea, modelViewTransform );

      // set the updated clip area
      this.energyChunkRootNode.clipArea = clipArea;
    },

    /**
     * Add shapes corresponded to the provided blocks to the provide clip area shape, accounting for any 3D projection
     * used for the blocks.  This essentially creates "holes" in the clip mask preventing anything in the parent node
     * (generally energy chunks) from being rendered in the same place as the blocks.
     * @param {Block[]} blocks
     * @param {Shape} shape
     * @param {ModelViewTransform2} modelViewTransform
     * @private
     */
    addProjectedBlocksToClipArea: function( blocks, shape, modelViewTransform ) {

      // Make sure there aren't more blocks than this method can deal with.  There are some assumptions built in that
      // would not work for more than two blocks, see the code and comments below for details.
      assert && assert( blocks.length <= 2, 'number of blocks exceeds what this method is designed to handle' );

      // use the bounds of the shape for faster tests, assumes that it is rectangular
      var shapeBounds = shape.bounds;

      // vars used for projections, only calculated if needed
      var perspectiveEdgeSize;
      var forwardProjectionVector;
      var blockWidthInView;
      var blockHeightInView;

      // determine whether the blocks are stacked upon each other
      var blocksAreStacked = blocks[ 0 ].isStackedUpon( blocks[ 1 ] ) || blocks[ 1 ].isStackedUpon( blocks[ 0 ] );

      if ( blocksAreStacked ) {

        // When the blocks are stacked, draw a single shape the encompasses both.  This is necessary because if the
        // shapes overlap in the clipping area, a space is created where the energy chunks aren't occluded.
        var bottomBlock;
        if ( blocks[ 0 ].isStackedUpon( blocks[ 1 ] ) ) {
          bottomBlock = blocks[ 1 ];
        }
        else {
          bottomBlock = blocks[ 0 ];
        }

        var bottomBlockPositionInView = modelViewTransform.modelToViewPosition( bottomBlock.positionProperty.value );
        blockWidthInView = modelViewTransform.modelToViewDeltaX( bottomBlock.width );
        blockHeightInView = -modelViewTransform.modelToViewDeltaY( bottomBlock.height );
        perspectiveEdgeSize = blockWidthInView * EFACConstants.BLOCK_PERSPECTIVE_EDGE_PROPORTION;
        forwardProjectionVector = new Vector2( -perspectiveEdgeSize / 2, 0 ).rotated( -BLOCK_PERSPECTIVE_ANGLE );

        if ( shapeBounds.containsPoint( bottomBlockPositionInView ) ) {
          shape.moveTo(
            bottomBlockPositionInView.x - blockWidthInView / 2 + forwardProjectionVector.x,
            bottomBlockPositionInView.y + forwardProjectionVector.y
          );
          shape.lineToRelative( blockWidthInView, 0 );
          shape.lineToRelative( -forwardProjectionVector.x * 2, -forwardProjectionVector.y * 2 );
          shape.lineToRelative( 0, -blockHeightInView * 2 );
          shape.lineToRelative( -blockWidthInView, 0 );
          shape.lineToRelative( forwardProjectionVector.x * 2, forwardProjectionVector.y * 2 );
          shape.lineToRelative( 0, blockHeightInView * 2 );
        }
      }
      else {

        // C-style loop for best performance
        for ( var i = 0; i < blocks.length; i++ ) {
          var block = blocks[ i ];
          var blockPositionInView = modelViewTransform.modelToViewPosition( block.positionProperty.value );
          blockWidthInView = modelViewTransform.modelToViewDeltaX( block.width );
          blockHeightInView = -modelViewTransform.modelToViewDeltaY( block.height );
          perspectiveEdgeSize = blockWidthInView * EFACConstants.BLOCK_PERSPECTIVE_EDGE_PROPORTION;
          forwardProjectionVector = new Vector2( -perspectiveEdgeSize / 2, 0 ).rotated( -BLOCK_PERSPECTIVE_ANGLE );

          // The following code makes some assumptions that are known to be true for the EFAC simulation but which wouldn't
          // necessarily true for a generalized version of this.  Those assumptions are that the provided shape is
          // rectangular and that the position of the block is the bottom center.
          if ( shapeBounds.containsPoint( blockPositionInView ) ) {
            shape.moveTo(
              blockPositionInView.x - blockWidthInView / 2 + forwardProjectionVector.x,
              blockPositionInView.y + forwardProjectionVector.y
            );
            shape.lineToRelative( blockWidthInView, 0 );
            shape.lineToRelative( -forwardProjectionVector.x * 2, -forwardProjectionVector.y * 2 );
            shape.lineToRelative( 0, -blockHeightInView );
            shape.lineToRelative( -blockWidthInView, 0 );
            shape.lineToRelative( forwardProjectionVector.x * 2, forwardProjectionVector.y * 2 );
            shape.lineToRelative( 0, blockHeightInView );
          }
        }
      }
    }
  } );
} );

<|endoftext|>


<commit_before>/**
 * Copyright 2013 IBM Corp.
 *
 * 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.
 **/
var util = require("util");
var EventEmitter = require("events").EventEmitter;
var fs = require("fs");
var path = require("path");
var clone = require("clone");
var events = require("./events");
var storage = null;

function getCallerFilename(type) {
    //if (type == "summary") {
    //    var err = new Error();
    //    console.log(err.stack);
    //    return null;
    //}
    // Save original Error.prepareStackTrace
    var origPrepareStackTrace = Error.prepareStackTrace;
    // Override with function that just returns `stack`
    Error.prepareStackTrace = function (_, stack) {
        return stack;
    }
    // Create a new `Error`, which automatically gets `stack`
    var err = new Error();
    // Evaluate `err.stack`, which calls our new `Error.prepareStackTrace`
    var stack = err.stack;
    // Restore original `Error.prepareStackTrace`
    Error.prepareStackTrace = origPrepareStackTrace;
    // Remove superfluous function call on stack
    stack.shift();
    stack.shift();
    return stack[0].getFileName();
}

var registry = (function() {
        var nodes = {};
        var logHandlers = [];
        var obj = {
            add: function(n) {
                nodes[n.id] = n;
                n.on("log",function(msg) {
                    for (var i in logHandlers) {
                        logHandlers[i].emit("log",msg);
                    }
                });
            },
            get: function(i) {
                return nodes[i];
            },
            clear: function() {
                events.emit("nodes-stopping");
                for (var n in nodes) {
                    nodes[n].close();
                }
                events.emit("nodes-stopped");
                nodes = {};
            },
            each: function(cb) {
                for (var n in nodes) {
                    cb(nodes[n]);
                }
            },
            addLogHandler: function(handler) {
                logHandlers.push(handler);
            }
        }
        return obj;
})();

var ConsoleLogHandler = new EventEmitter();
ConsoleLogHandler.on("log",function(msg) {
        util.log("["+msg.level+"] ["+msg.type+":"+(msg.name||msg.id)+"] "+msg.msg);
});

registry.addLogHandler(ConsoleLogHandler);

var node_type_registry = (function() {
        var node_types = {};
        var node_configs = {};
        var obj = {
            register: function(type,node) {
                util.inherits(node, Node);
                var callerFilename = getCallerFilename(type);
                if (callerFilename == null) {
                    util.log("["+type+"] unable to determine filename");
                } else {
                    var configFilename = callerFilename.replace(/\.js$/,".html");
                    if (fs.existsSync(configFilename)) {
                        node_types[type] = node;
                        if (! node_configs[configFilename]) {
                            node_configs[configFilename] = fs.readFileSync(configFilename,'utf8');
                        }
                        events.emit("type-registered",type);
                    } else {
                        util.log("["+type+"] missing template file: "+configFilename);
                    }
                }
            },
            get: function(type) {
                return node_types[type];
            },
            getNodeConfigs: function() {
                var result = "";
                for (var nt in node_configs) {
                    result += node_configs[nt];
                }
                return result;
            }
        }
        return obj;
})();

function Node(n) {
    this.id = n.id;
    registry.add(this);
    this.type = n.type;
    if (n.name) {
        this.name = n.name;
    }
    this.wires = n.wires||[];
}
util.inherits(Node,EventEmitter);

Node.prototype.close = function() {
    // called when a node is removed
    this.emit("close");
}

Node.prototype.send = function(msg) {
    // instanceof doesn't work for some reason here
    if (msg == null) {
        msg = [];
    } else if (!util.isArray(msg)) {
        msg = [msg];
    }
    for (var i in this.wires) {
        var wires = this.wires[i];
        if (i < msg.length) {
            if (msg[i] != null) {
                var msgs = msg[i];
                if (!util.isArray(msg[i])) {
                    msgs = [msg[i]];
                }
                if (wires.length == 1) {
                    // Single recipient, don't need to clone the message
                    var node = registry.get(wires[0]);
                    if (node) {
                        for (var k in msgs) {
                            var mm = msgs[k];
                            node.receive(mm);
                        }
                    }
                } else {
                    // Multiple recipients, must send message copies
                    for (var j in wires) {
                        var node = registry.get(wires[j]);
                        if (node) {
                            for (var k in msgs) {
                                var mm = msgs[k];
                                var m = clone(mm);
                                node.receive(m);
                            }
                        }
                    }
                }
            }
        }
    }
}
module.exports.Node = Node;

Node.prototype.receive = function(msg) {
    this.emit("input",msg);
}

Node.prototype.log = function(msg) {
    var o = {level:'log',id:this.id, type:this.type, msg:msg};
    if (this.name) o.name = this.name;
    this.emit("log",o);
}
Node.prototype.warn = function(msg) {
    var o = {level:'warn',id:this.id, type:this.type, msg:msg};
    if (this.name) o.name = this.name;
    this.emit("log",o);
}
Node.prototype.error = function(msg) {
    var o = {level:'error',id:this.id, type:this.type, msg:msg};
    if (this.name) o.name = this.name;
    this.emit("log",o);
}

var credentials = {};

module.exports.addCredentials = function(id,creds) {
    credentials[id] = creds;
    storage.saveCredentials(credentials);
}
module.exports.getCredentials = function(id) {
    return credentials[id];
}
module.exports.deleteCredentials = function(id) {
    delete credentials[id];
    storage.saveCredentials(credentials);
}
module.exports.createNode = function(node,def) {
    Node.call(node,def);
}

module.exports.registerType = node_type_registry.register;
module.exports.getNodeConfigs = node_type_registry.getNodeConfigs;
module.exports.addLogHandler = registry.addLogHandler;

module.exports.load = function(settings) {
    function loadNodes(dir) {
        fs.readdirSync(dir).sort().filter(function(fn){
                var stats = fs.statSync(path.join(dir,fn));
                if (stats.isFile()) {
                    if (/\.js$/.test(fn)) {
                        try {
                            require(path.join(dir,fn));
                        } catch(err) {
                            util.log("["+fn+"] "+err);
                            //console.log(err.stack);
                        }
                    }
                } else if (stats.isDirectory()) {
                    // Ignore /.dirs/, /lib/ /node_modules/
                    if (!/^(\..*|lib|icons|node_modules)$/.test(fn)) {
                        loadNodes(path.join(dir,fn));
                    } else if (fn === "icons") {
                        events.emit("node-icon-dir",path.join(dir,fn));
                    }
                }
        });
    }
    loadNodes(__dirname+"/../nodes");
    if (settings.nodesDir) {
        loadNodes(settings.nodesDir);
    }
    //events.emit("nodes-loaded");
}

var activeConfig = [];
var missingTypes = [];

events.on('type-registered',function(type) {
        if (missingTypes.length > 0) {
            var i = missingTypes.indexOf(type);
            if (i != -1) {
                missingTypes.splice(i,1);
                util.log("[red] Missing type registered: "+type);
            }
            if (missingTypes.length == 0) {
                parseConfig();
            }
        }
});

module.exports.getNode = function(nid) {
    return registry.get(nid);
}

function stopFlows() {
    if (activeConfig&&activeConfig.length > 0) {
        util.log("[red] Stopping flows");
    }
    registry.clear();
}

module.exports.stopFlows = stopFlows;

module.exports.setConfig = function(conf) {
    stopFlows();
    activeConfig = conf;

    if (!storage) {
        // Do this lazily to ensure the storage provider as been initialised
        storage = require("./storage");
    }
    storage.getCredentials().then(function(creds) {
        credentials = creds;
        parseConfig();
    }).otherwise(function(err) {
        util.log("[red] Error loading credentials : "+err);
    });
}

module.exports.getConfig = function() {
    return activeConfig;
}

var parseConfig = function() {
    missingTypes = [];
    for (var i in activeConfig) {
        var type = activeConfig[i].type;
        // TODO: remove workspace in next release+1
        if (type != "workspace" && type != "tab") {
            var nt = node_type_registry.get(type);
            if (!nt && missingTypes.indexOf(type) == -1) {
                missingTypes.push(type);
            }
        }
    };
    if (missingTypes.length > 0) {
        util.log("[red] Waiting for missing types to be registered:");
        for (var i in missingTypes) {
            util.log("[red]  - "+missingTypes[i]);
        }
        return;
    }

    util.log("[red] Starting flows");
    events.emit("nodes-starting");
    for (var i in activeConfig) {
        var nn = null;
        // TODO: remove workspace in next release+1
        if (activeConfig[i].type != "workspace" && activeConfig[i].type != "tab") {
            var nt = node_type_registry.get(activeConfig[i].type);
            if (nt) {
                try {
                    nn = new nt(activeConfig[i]);
                }
                catch (err) {
                    util.log("[red] "+activeConfig[i].type+" : "+err);
                }
            }
            // console.log(nn);
            if (nn == null) {
                util.log("[red] unknown type: "+activeConfig[i].type);
            }
        }
    }
    // Clean up any orphaned credentials
    var deletedCredentials = false;
    for (var c in credentials) {
        var n = registry.get(c);
        if (!n) {
            deletedCredentials = true;
            delete credentials[c];
        }
    }
    if (deletedCredentials) {
        storage.saveCredentials(credentials);
    }
    events.emit("nodes-started");
}
<commit_msg>Storage object null when adding twitter credentials as first ever node<commit_after>/**
 * Copyright 2013 IBM Corp.
 *
 * 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.
 **/
var util = require("util");
var EventEmitter = require("events").EventEmitter;
var fs = require("fs");
var path = require("path");
var clone = require("clone");
var events = require("./events");
var storage = null;

function getCallerFilename(type) {
    //if (type == "summary") {
    //    var err = new Error();
    //    console.log(err.stack);
    //    return null;
    //}
    // Save original Error.prepareStackTrace
    var origPrepareStackTrace = Error.prepareStackTrace;
    // Override with function that just returns `stack`
    Error.prepareStackTrace = function (_, stack) {
        return stack;
    }
    // Create a new `Error`, which automatically gets `stack`
    var err = new Error();
    // Evaluate `err.stack`, which calls our new `Error.prepareStackTrace`
    var stack = err.stack;
    // Restore original `Error.prepareStackTrace`
    Error.prepareStackTrace = origPrepareStackTrace;
    // Remove superfluous function call on stack
    stack.shift();
    stack.shift();
    return stack[0].getFileName();
}

var registry = (function() {
        var nodes = {};
        var logHandlers = [];
        var obj = {
            add: function(n) {
                nodes[n.id] = n;
                n.on("log",function(msg) {
                    for (var i in logHandlers) {
                        logHandlers[i].emit("log",msg);
                    }
                });
            },
            get: function(i) {
                return nodes[i];
            },
            clear: function() {
                events.emit("nodes-stopping");
                for (var n in nodes) {
                    nodes[n].close();
                }
                events.emit("nodes-stopped");
                nodes = {};
            },
            each: function(cb) {
                for (var n in nodes) {
                    cb(nodes[n]);
                }
            },
            addLogHandler: function(handler) {
                logHandlers.push(handler);
            }
        }
        return obj;
})();

var ConsoleLogHandler = new EventEmitter();
ConsoleLogHandler.on("log",function(msg) {
        util.log("["+msg.level+"] ["+msg.type+":"+(msg.name||msg.id)+"] "+msg.msg);
});

registry.addLogHandler(ConsoleLogHandler);

var node_type_registry = (function() {
        var node_types = {};
        var node_configs = {};
        var obj = {
            register: function(type,node) {
                util.inherits(node, Node);
                var callerFilename = getCallerFilename(type);
                if (callerFilename == null) {
                    util.log("["+type+"] unable to determine filename");
                } else {
                    var configFilename = callerFilename.replace(/\.js$/,".html");
                    if (fs.existsSync(configFilename)) {
                        node_types[type] = node;
                        if (! node_configs[configFilename]) {
                            node_configs[configFilename] = fs.readFileSync(configFilename,'utf8');
                        }
                        events.emit("type-registered",type);
                    } else {
                        util.log("["+type+"] missing template file: "+configFilename);
                    }
                }
            },
            get: function(type) {
                return node_types[type];
            },
            getNodeConfigs: function() {
                var result = "";
                for (var nt in node_configs) {
                    result += node_configs[nt];
                }
                return result;
            }
        }
        return obj;
})();

function Node(n) {
    this.id = n.id;
    registry.add(this);
    this.type = n.type;
    if (n.name) {
        this.name = n.name;
    }
    this.wires = n.wires||[];
}
util.inherits(Node,EventEmitter);

Node.prototype.close = function() {
    // called when a node is removed
    this.emit("close");
}

Node.prototype.send = function(msg) {
    // instanceof doesn't work for some reason here
    if (msg == null) {
        msg = [];
    } else if (!util.isArray(msg)) {
        msg = [msg];
    }
    for (var i in this.wires) {
        var wires = this.wires[i];
        if (i < msg.length) {
            if (msg[i] != null) {
                var msgs = msg[i];
                if (!util.isArray(msg[i])) {
                    msgs = [msg[i]];
                }
                if (wires.length == 1) {
                    // Single recipient, don't need to clone the message
                    var node = registry.get(wires[0]);
                    if (node) {
                        for (var k in msgs) {
                            var mm = msgs[k];
                            node.receive(mm);
                        }
                    }
                } else {
                    // Multiple recipients, must send message copies
                    for (var j in wires) {
                        var node = registry.get(wires[j]);
                        if (node) {
                            for (var k in msgs) {
                                var mm = msgs[k];
                                var m = clone(mm);
                                node.receive(m);
                            }
                        }
                    }
                }
            }
        }
    }
}
module.exports.Node = Node;

Node.prototype.receive = function(msg) {
    this.emit("input",msg);
}

Node.prototype.log = function(msg) {
    var o = {level:'log',id:this.id, type:this.type, msg:msg};
    if (this.name) o.name = this.name;
    this.emit("log",o);
}
Node.prototype.warn = function(msg) {
    var o = {level:'warn',id:this.id, type:this.type, msg:msg};
    if (this.name) o.name = this.name;
    this.emit("log",o);
}
Node.prototype.error = function(msg) {
    var o = {level:'error',id:this.id, type:this.type, msg:msg};
    if (this.name) o.name = this.name;
    this.emit("log",o);
}

var credentials = {};

module.exports.addCredentials = function(id,creds) {
    credentials[id] = creds;
    if (!storage) {
        // Do this lazily to ensure the storage provider as been initialised
        storage = require("./storage");
    }
    storage.saveCredentials(credentials);
}
module.exports.getCredentials = function(id) {
    return credentials[id];
}
module.exports.deleteCredentials = function(id) {
    delete credentials[id];
    storage.saveCredentials(credentials);
}
module.exports.createNode = function(node,def) {
    Node.call(node,def);
}

module.exports.registerType = node_type_registry.register;
module.exports.getNodeConfigs = node_type_registry.getNodeConfigs;
module.exports.addLogHandler = registry.addLogHandler;

module.exports.load = function(settings) {
    function loadNodes(dir) {
        fs.readdirSync(dir).sort().filter(function(fn){
                var stats = fs.statSync(path.join(dir,fn));
                if (stats.isFile()) {
                    if (/\.js$/.test(fn)) {
                        try {
                            require(path.join(dir,fn));
                        } catch(err) {
                            util.log("["+fn+"] "+err);
                            //console.log(err.stack);
                        }
                    }
                } else if (stats.isDirectory()) {
                    // Ignore /.dirs/, /lib/ /node_modules/
                    if (!/^(\..*|lib|icons|node_modules)$/.test(fn)) {
                        loadNodes(path.join(dir,fn));
                    } else if (fn === "icons") {
                        events.emit("node-icon-dir",path.join(dir,fn));
                    }
                }
        });
    }
    loadNodes(__dirname+"/../nodes");
    if (settings.nodesDir) {
        loadNodes(settings.nodesDir);
    }
    //events.emit("nodes-loaded");
}

var activeConfig = [];
var missingTypes = [];

events.on('type-registered',function(type) {
        if (missingTypes.length > 0) {
            var i = missingTypes.indexOf(type);
            if (i != -1) {
                missingTypes.splice(i,1);
                util.log("[red] Missing type registered: "+type);
            }
            if (missingTypes.length == 0) {
                parseConfig();
            }
        }
});

module.exports.getNode = function(nid) {
    return registry.get(nid);
}

function stopFlows() {
    if (activeConfig&&activeConfig.length > 0) {
        util.log("[red] Stopping flows");
    }
    registry.clear();
}

module.exports.stopFlows = stopFlows;

module.exports.setConfig = function(conf) {
    stopFlows();
    activeConfig = conf;

    if (!storage) {
        // Do this lazily to ensure the storage provider as been initialised
        storage = require("./storage");
    }
    storage.getCredentials().then(function(creds) {
        credentials = creds;
        parseConfig();
    }).otherwise(function(err) {
        util.log("[red] Error loading credentials : "+err);
    });
}

module.exports.getConfig = function() {
    return activeConfig;
}

var parseConfig = function() {
    missingTypes = [];
    for (var i in activeConfig) {
        var type = activeConfig[i].type;
        // TODO: remove workspace in next release+1
        if (type != "workspace" && type != "tab") {
            var nt = node_type_registry.get(type);
            if (!nt && missingTypes.indexOf(type) == -1) {
                missingTypes.push(type);
            }
        }
    };
    if (missingTypes.length > 0) {
        util.log("[red] Waiting for missing types to be registered:");
        for (var i in missingTypes) {
            util.log("[red]  - "+missingTypes[i]);
        }
        return;
    }

    util.log("[red] Starting flows");
    events.emit("nodes-starting");
    for (var i in activeConfig) {
        var nn = null;
        // TODO: remove workspace in next release+1
        if (activeConfig[i].type != "workspace" && activeConfig[i].type != "tab") {
            var nt = node_type_registry.get(activeConfig[i].type);
            if (nt) {
                try {
                    nn = new nt(activeConfig[i]);
                }
                catch (err) {
                    util.log("[red] "+activeConfig[i].type+" : "+err);
                }
            }
            // console.log(nn);
            if (nn == null) {
                util.log("[red] unknown type: "+activeConfig[i].type);
            }
        }
    }
    // Clean up any orphaned credentials
    var deletedCredentials = false;
    for (var c in credentials) {
        var n = registry.get(c);
        if (!n) {
            deletedCredentials = true;
            delete credentials[c];
        }
    }
    if (deletedCredentials) {
        storage.saveCredentials(credentials);
    }
    events.emit("nodes-started");
}
<|endoftext|>


<commit_before>define( function( require, exports, module ){
    var Nested   = require( '../nestedtypes' ),
        Backbone = require( 'backbone' );

    describe( 'Flat models', function(){
        this.timeout( 100000 );

        describe( 'primitive types', function(){
            var NLarge, BLarge, NSmall, BSmall;

            function makeDefinitions(){
                NLarge = Nested.Model.extend({
                    defaults : {
                        a1 : 1, a2 : 2, a3 : 3, a4: 4, a5 : 5, a6: 6, a7: 7, a8: 8, a9: 9, a10 : 10,
                        b1 : 1, b2 : 2, b3 : 3, b4: 4, b5 : 5, b6: 6, b7: 7, b8: 8, b9: 9, b10 : 10
                    },

                    updateSet : function(){
                        this.set({
                            a1 : this.a1 + 1,
                            a2 : this.a2 + 1,
                            a3 : this.a3 + 1,
                            a4 : this.a4 + 1,
                            a5 : this.a5 + 1
                        });
                    },

                    updateTransaction : Nested.transaction(function(){
                        this.a1 = this.a1 + 1;
                        this.a2 = this.a2 + 1;
                        this.a3 = this.a3 + 1;
                        this.a4 = this.a4 + 1;
                        this.a5 = this.a5 + 1;
                    }),

                    updateAdHocTransaction : function(){
                        this.transaction( function(){
                            this.a1 = this.a1 + 1;
                            this.a2 = this.a2 + 1;
                            this.a3 = this.a3 + 1;
                            this.a4 = this.a4 + 1;
                            this.a5 = this.a5 + 1;
                        }, {} );
                    }
                });

                BLarge = Backbone.Model.extend({
                    defaults : {
                        a1 : 1, a2 : 2, a3 : 3, a4: 4, a5 : 5, a6: 6, a7: 7, a8: 8, a9: 9, a10 : 10,
                        b1 : 1, b2 : 2, b3 : 3, b4: 4, b5 : 5, b6: 6, b7: 7, b8: 8, b9: 9, b10 : 10
                    },

                    updateSet : function(){
                        this.set({
                            a1 : this.get( 'a1' ) + 1,
                            a2 : this.get( 'a2' ) + 1,
                            a3 : this.get( 'a3' ) + 1,
                            a4 : this.get( 'a4' ) + 1,
                            a5 : this.get( 'a5' ) + 1
                        });
                    }
                });

                NSmall = Nested.Model.extend({
                    defaults : {
                        a1 : 1
                    }
                });

                BSmall = Backbone.Model.extend({
                    defaults : {
                        a1 : 1
                    }
                });
            }

            var n, b;

            describe( '1-attr model, 1M create', function(){
                makeDefinitions();

                it( 'Backbone', function(){
                    for( var i = 0; i < 1000000; i++ ){
                        b = new BSmall();
                    }
                });

                it( 'Nested', function(){
                    for( var i = 0; i < 1000000; i++ ){
                        n = new NSmall();
                    }
                });
            });

            describe( '20-attrs model, 1M create', function(){
                makeDefinitions();

                it( 'Backbone', function(){
                    for( var i = 0; i < 1000000; i++ ){
                        b = new BLarge();
                    }
                });

                it( 'Nested', function(){
                    for( var i = 0; i < 1000000; i++ ){
                        n = new NLarge();
                    }
                });
            });

            describe( '1-attr model, 1M .set( "a1", number )', function(){
                makeDefinitions();

                var b = new BSmall();

                it( 'Backbone', function(){
                    for( var i = 0; i < 1000000; i++ ){
                        b.set( 'a1', i );
                    }
                });

                var n = new NSmall();

                it( 'Nested', function(){
                    for( var i = 0; i < 1000000; i++ ){
                        n.set( 'a1', i );
                    }
                });

                var n = new NSmall();

                it( 'Nested native property', function(){
                    for( var i = 0; i < 1000000; i++ ){
                        n.a1 = i;
                    }
                });
            });

            describe( '20-attrs model, 1M .set( "a1", number )', function(){
                makeDefinitions();

                var b = new BLarge();

                it( 'Backbone', function(){
                    for( var i = 0; i < 1000000; i++ ){
                        b.set( 'a1', i );
                    }
                });

                var n = new NLarge();

                it( 'Nested', function(){
                    for( var i = 0; i < 1000000; i++ ){
                        n.set( 'a1', i );
                    }
                });

                var n = new NLarge();

                it( 'Nested native property', function(){
                    for( var i = 0; i < 1000000; i++ ){
                        n.a1 = i;
                    }
                });
            });

            describe( '20-attrs model, 10M .get( "a1" )', function(){
                makeDefinitions();

                var b = new BLarge({ a1: 1 }), x;

                it( 'Backbone', function(){
                    for( var i = 0; i < 10000000; i++ ){
                        x = b.get( 'a1' );
                    }
                });

                var n = new NLarge({ a1: 1 });

                it( 'Nested', function(){
                    for( var i = 0; i < 10000000; i++ ){
                        x = n.get( 'a1' );
                    }
                });

                var n = new NLarge({ a1: 1 });

                it( 'Nested native property', function(){
                    for( var i = 0; i < 10000000; i++ ){
                        x = n.a1;
                    }
                });
            });

            describe( 'both models, 1M read and write', function(){
                makeDefinitions();

                it( 'Backbone', function(){
                    var l = new BLarge(), s = new BSmall();

                    for( var i = 0; i < 1000000; i++ ){
                        l.set( 'a1', l.get( 'a1' ) + 1 );
                        s.set( 'a1', l.get( 'a1' ) + 1 );
                    }
                });

                it( 'Nested', function(){
                    var l = new NLarge(), s = new NSmall();

                    for( var i = 0; i < 1000000; i++ ){
                        l.set( 'a1', l.get( 'a1' ) + 1 );
                        s.set( 'a1', l.get( 'a1' ) + 1 );
                    }
                });

                it( 'Nested native', function(){
                    var l = new NLarge(), s = new NSmall();

                    for( var i = 0; i < 1000000; i++ ){
                        l.a1 = l.a1 + 1;
                        s.a1 = l.a1 + 1;
                    }
                });
            });

            describe( '1M 5-attr transactional updates', function(){
                makeDefinitions();

                it( 'Backbone', function(){
                    var l = new BLarge();

                    for( var i = 0; i < 1000000; i++ ){
                        l.updateSet();
                    }
                });

                it( 'Nested', function(){
                    var l = new NLarge();

                    for( var i = 0; i < 1000000; i++ ){
                        l.updateSet();
                    }
                });

                it( 'Nested transaction', function(){
                    var l = new NLarge();

                    for( var i = 0; i < 1000000; i++ ){
                        l.updateTransaction();
                    }
                });

                it( 'Nested AdHoc transaction', function(){
                    var l = new NLarge();

                    for( var i = 0; i < 1000000; i++ ){
                        l.updateAdHocTransaction();
                    }
                });
            });
        });
    });
});
<commit_msg>updated performance tests<commit_after>define( function( require, exports, module ){
    var Nested   = require( '../nestedtypes' ),
        Backbone = require( 'backbone' );

    var NLarge = Nested.Model.extend({
        defaults : {
            a1 : 1, a2 : 2, a3 : 3, a4: 4, a5 : 5, a6: 6, a7: 7, a8: 8, a9: 9, a10 : 10,
            b1 : 1, b2 : 2, b3 : 3, b4: 4, b5 : 5, b6: 6, b7: 7, b8: 8, b9: 9, b10 : 10
        },

        updateSet : function(){
            this.set({
                a1 : this.a1 + 1,
                a2 : this.a2 + 1,
                a3 : this.a3 + 1,
                a4 : this.a4 + 1,
                a5 : this.a5 + 1
            });
        },

        updateTransaction : Nested.transaction(function(){
            this.a1 = this.a1 + 1;
            this.a2 = this.a2 + 1;
            this.a3 = this.a3 + 1;
            this.a4 = this.a4 + 1;
            this.a5 = this.a5 + 1;
        }),

        updateAdHocTransaction : function(){
            this.transaction( function(){
                this.a1 = this.a1 + 1;
                this.a2 = this.a2 + 1;
                this.a3 = this.a3 + 1;
                this.a4 = this.a4 + 1;
                this.a5 = this.a5 + 1;
            }, {} );
        },

        save(){}
    });

    var BLarge = Backbone.Model.extend({
        defaults : {
            a1 : 1, a2 : 2, a3 : 3, a4: 4, a5 : 5, a6: 6, a7: 7, a8: 8, a9: 9, a10 : 10,
            b1 : 1, b2 : 2, b3 : 3, b4: 4, b5 : 5, b6: 6, b7: 7, b8: 8, b9: 9, b10 : 10
        },

        updateSet : function(){
            this.set({
                a1 : this.get( 'a1' ) + 1,
                a2 : this.get( 'a2' ) + 1,
                a3 : this.get( 'a3' ) + 1,
                a4 : this.get( 'a4' ) + 1,
                a5 : this.get( 'a5' ) + 1
            });
        },

        save(){}
    });

    var BLargeCollection = Backbone.Collection.extend({
        model : BLarge
    });

    var NSmall = Nested.Model.extend({
        defaults : {
            a1 : 1
        },

        save(){}
    });

    var BSmall = Backbone.Model.extend({
        defaults : {
            a1 : 1
        },

        save(){}
    });

    var BSmallCollection = Backbone.Collection.extend({
        model : BSmall
    });

    describe( 'Flat models', function(){
        this.timeout( 100000 );

        describe( 'Create performance', function(){
            var n, b;

            describe( '1-attr model, 50K new', function(){
                it( 'Backbone', function(){
                    for( var i = 0; i < 50000; i++ ){
                        b = new BSmall();
                    }
                } );

                it( 'Nested', function(){
                    for( var i = 0; i < 50000; i++ ){
                        n = new NSmall();
                    }
                } );
            } );

            describe( '20-attrs model, 50K new', function(){

                it( 'Backbone', function(){
                    for( var i = 0; i < 50000; i++ ){
                        b = new BLarge();
                    }
                } );

                it( 'Nested', function(){
                    for( var i = 0; i < 50000; i++ ){
                        n = new NLarge();
                    }
                } );
            } );

            describe( '1-attr model, 50K collection.create', function(){
                it( 'Backbone', function(){
                    var c = new BSmallCollection();
                    for( var i = 0; i < 50000; i++ ){
                        c.create();
                    }
                } );

                it( 'Nested', function(){
                    var c = new NSmall.Collection();

                    for( var i = 0; i < 50000; i++ ){
                        c.create();
                    }
                } );
            } );

            describe( '20-attr model, 50K collection.create', function(){
                it( 'Backbone', function(){
                    var c = new BLargeCollection();
                    for( var i = 0; i < 50000; i++ ){
                        c.create();
                    }
                } );

                it( 'Nested', function(){
                    var c = new NLarge.Collection();

                    for( var i = 0; i < 50000; i++ ){
                        c.create();
                    }
                } );
            } );

            describe( '1-attr model, 50K collection reset', function(){
                var arr = [];
                for( var i = 0; i < 50000; i++ ){
                    arr.push({ a1 : i });
                }

                it( 'Backbone', function(){
                    var c = new BSmallCollection();
                    c.reset( arr );
                } );

                it( 'Nested', function(){
                    var c = new NSmall.Collection();
                    c.reset( arr );
                } );
            } );

            describe( '20-attr model, 50K collection reset', function(){
                var arr = [];
                for( var i = 0; i < 50000; i++ ){
                    arr.push({ a1 : i, a2 : i, a3: i, a4 : i, a5 : i, a6 : i, a7 : i, a8: i, a9 : i, a10 : i});
                }

                it( 'Backbone', function(){
                    var c = new BLargeCollection();
                    c.reset( arr );
                } );

                it( 'Nested', function(){
                    var c = new NLarge.Collection();
                    c.reset( arr );
                } );
            } );

            describe( '1-attr model, 50K collection set/update', function(){
                var arr = [], update = [];
                for( var i = 0; i < 50000; i++ ){
                    arr.push({ id: i, a1 : i });
                    update.push({ id: i, a1 : i + 1 });
                }

                it( 'Backbone', function(){
                    var c = new BSmallCollection();
                    c.set( arr );
                    c.set( update );
                } );

                it( 'Nested', function(){
                    var c = new NSmall.Collection();
                    c.set( arr );
                    c.set( update );
                } );

            } );

            describe( '20-attr model, 50K collection set/update', function(){
                var arr = [], update = [];
                for( var i = 0; i < 100000; i++ ){
                    arr.push({ id : i, a1 : i, a2 : i, a3: i, a4 : i, a5 : i, a6 : i, a7 : i, a8: i, a9 : i, a10 : i});
                    i++;
                    update.push({ id : i - 1, a1 : i, a2 : i, a3: i, a4 : i, a5 : i, a6 : i, a7 : i, a8: i, a9 : i, a10 : i});
                }

                it( 'Backbone', function(){
                    var c = new BLargeCollection();
                    c.set( arr );
                    c.set( update );
                } );

                it( 'Nested', function(){
                    var c = new NLarge.Collection();
                    c.set( arr );
                    c.set( update );
                } );
            } );
        });

        describe( 'Update performance', function(){
            var n, b;

            describe( '1-attr model, 100K collection.create', function(){
                it( 'Backbone', function(){
                    var c = new BSmallCollection();
                    for( var i = 0; i < 100000; i++ ){
                        c.create();
                    }
                } );

                it( 'Nested', function(){
                    var c = new NSmall.Collection();

                    for( var i = 0; i < 100000; i++ ){
                        c.create();
                    }
                } );
            } );

            describe( '20-attr model, 100K collection.create', function(){
                it( 'Backbone', function(){
                    var c = new BLargeCollection();
                    for( var i = 0; i < 100000; i++ ){
                        c.create();
                    }
                } );

                it( 'Nested', function(){
                    var c = new NLarge.Collection();

                    for( var i = 0; i < 100000; i++ ){
                        c.create();
                    }
                } );
            } );

            describe( '1-attr model, 100K collection reset', function(){
                var arr = [];
                for( var i = 0; i < 100000; i++ ){
                    arr.push({ a1 : i });
                }

                it( 'Backbone', function(){
                    var c = new BSmallCollection();
                    c.reset( arr );
                } );

                it( 'Nested', function(){
                    var c = new NSmall.Collection();
                    c.reset( arr );
                } );
            } );

            describe( '20-attr model, 100K collection reset', function(){
                var arr = [];
                for( var i = 0; i < 100000; i++ ){
                    arr.push({ a1 : i, a2 : i, a3: i, a4 : i, a5 : i, a6 : i, a7 : i, a8: i, a9 : i, a10 : i});
                }

                it( 'Backbone', function(){
                    var c = new BLargeCollection();
                    c.reset( arr );
                } );

                it( 'Nested', function(){
                    var c = new NLarge.Collection();
                    c.reset( arr );
                } );
            } );

            describe( '1-attr model, 100K collection set/update', function(){
                var arr = [], update = [];
                for( var i = 0; i < 100000; i++ ){
                    arr.push({ id: i, a1 : i });
                    update.push({ id: i, a1 : i + 1 });
                }

                it( 'Backbone', function(){
                    var c = new BSmallCollection();
                    c.set( arr );
                    c.set( update );
                } );

                it( 'Nested', function(){
                    var c = new NSmall.Collection();
                    c.set( arr );
                    c.set( update );
                } );

            } );

            describe( '20-attr model, 100K collection set/update', function(){
                var arr = [], update = [];
                for( var i = 0; i < 200000; i++ ){
                    arr.push({ id : i, a1 : i, a2 : i, a3: i, a4 : i, a5 : i, a6 : i, a7 : i, a8: i, a9 : i, a10 : i});
                    i++;
                    update.push({ id : i - 1, a1 : i, a2 : i, a3: i, a4 : i, a5 : i, a6 : i, a7 : i, a8: i, a9 : i, a10 : i});
                }

                it( 'Backbone', function(){
                    var c = new BLargeCollection();
                    c.set( arr );
                    c.set( update );
                } );

                it( 'Nested', function(){
                    var c = new NLarge.Collection();
                    c.set( arr );
                    c.set( update );
                } );
            } );
        });

        describe( 'Update performance', function(){
            var n, b;

            describe( '1-attr model, 1M .set( "a1", number )', function(){

                var b = new BSmall();

                it( 'Backbone', function(){
                    for( var i = 0; i < 1000000; i++ ){
                        b.set( 'a1', i );
                    }
                });

                var n = new NSmall();

                it( 'Nested', function(){
                    for( var i = 0; i < 1000000; i++ ){
                        n.set( 'a1', i );
                    }
                });

                var n = new NSmall();

                it( 'Nested native property', function(){
                    for( var i = 0; i < 1000000; i++ ){
                        n.a1 = i;
                    }
                });
            });

            describe( '20-attrs model, 1M .set( "a1", number )', function(){

                var b = new BLarge();

                it( 'Backbone', function(){
                    for( var i = 0; i < 1000000; i++ ){
                        b.set( 'a1', i );
                    }
                });

                var n = new NLarge();

                it( 'Nested', function(){
                    for( var i = 0; i < 1000000; i++ ){
                        n.set( 'a1', i );
                    }
                });

                var n = new NLarge();

                it( 'Nested native property', function(){
                    for( var i = 0; i < 1000000; i++ ){
                        n.a1 = i;
                    }
                });
            });

            describe( '20-attrs model, 10M .get( "a1" )', function(){

                var b = new BLarge({ a1: 1 }), x;

                it( 'Backbone', function(){
                    for( var i = 0; i < 10000000; i++ ){
                        x = b.get( 'a1' );
                    }
                });

                var n = new NLarge({ a1: 1 });

                it( 'Nested', function(){
                    for( var i = 0; i < 10000000; i++ ){
                        x = n.get( 'a1' );
                    }
                });

                var n = new NLarge({ a1: 1 });

                it( 'Nested native property', function(){
                    for( var i = 0; i < 10000000; i++ ){
                        x = n.a1;
                    }
                });
            });

            describe( 'both models, 1M read and write', function(){

                it( 'Backbone', function(){
                    var l = new BLarge(), s = new BSmall();

                    for( var i = 0; i < 1000000; i++ ){
                        l.set( 'a1', l.get( 'a1' ) + 1 );
                        s.set( 'a1', l.get( 'a1' ) + 1 );
                    }
                });

                it( 'Nested', function(){
                    var l = new NLarge(), s = new NSmall();

                    for( var i = 0; i < 1000000; i++ ){
                        l.set( 'a1', l.get( 'a1' ) + 1 );
                        s.set( 'a1', l.get( 'a1' ) + 1 );
                    }
                });

                it( 'Nested native', function(){
                    var l = new NLarge(), s = new NSmall();

                    for( var i = 0; i < 1000000; i++ ){
                        l.a1 = l.a1 + 1;
                        s.a1 = l.a1 + 1;
                    }
                });
            });

            describe( '1M 5-attr transactional updates', function(){

                it( 'Backbone', function(){
                    var l = new BLarge();

                    for( var i = 0; i < 1000000; i++ ){
                        l.updateSet();
                    }
                });

                it( 'Nested', function(){
                    var l = new NLarge();

                    for( var i = 0; i < 1000000; i++ ){
                        l.updateSet();
                    }
                });

                it( 'Nested transaction', function(){
                    var l = new NLarge();

                    for( var i = 0; i < 1000000; i++ ){
                        l.updateTransaction();
                    }
                });

                it( 'Nested AdHoc transaction', function(){
                    var l = new NLarge();

                    for( var i = 0; i < 1000000; i++ ){
                        l.updateAdHocTransaction();
                    }
                });
            });
        });

    });
});
<|endoftext|>


<commit_before>Rooms = new Meteor.Collection('rooms');

Meteor.methods({
  getARoom : function (targetUser) {
    var roomId, existingRoom;

    //Find an existing private room that only has booth
    //participants, if there is one
    /**
    TODO: change to this, when minimongo supports it:
    {participants: {
        $and: [
          {$all: [Meteor.userId(), targetUser._id]},
          {$size: 2}
        ]
      }}
    */
    existingRoom = Rooms.findOne({$and: [
      {isPrivate: true},
      {participants: {$all: [Meteor.userId(), targetUser._id]}}
    ]});

    if (existingRoom) {
      roomId = existingRoom._id;
    } else {
      //If there is no room yet, create it
      roomId = Rooms.insert({
        isPrivate: true,
        participants: [Meteor.userId(), targetUser._id]
      });
    }

    Meteor.call("createNotification", roomId, targetUser._id);

    return roomId;
  }
});<commit_msg>The open chat notifications are no longer sent<commit_after>Rooms = new Meteor.Collection('rooms');

Meteor.methods({
  getARoom : function (targetUser) {
    var roomId, existingRoom;

    //Find an existing private room that only has booth
    //participants, if there is one
    /**
    TODO: change to this, when minimongo supports it:
    {participants: {
        $and: [
          {$all: [Meteor.userId(), targetUser._id]},
          {$size: 2}
        ]
      }}
    */
    existingRoom = Rooms.findOne({$and: [
      {isPrivate: true},
      {participants: {$all: [Meteor.userId(), targetUser._id]}}
    ]});

    if (existingRoom) {
      roomId = existingRoom._id;
    } else {
      //If there is no room yet, create it
      roomId = Rooms.insert({
        isPrivate: true,
        participants: [Meteor.userId(), targetUser._id]
      });
    }

    return roomId;
  }
});<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

const ConcatSource = require("webpack-sources").ConcatSource;
const OriginalSource = require("webpack-sources").OriginalSource;
const Template = require("./Template");

function accessorToObjectAccess(accessor) {
	return accessor.map(a => `[${JSON.stringify(a)}]`).join("");
}

function accessorAccess(base, accessor) {
	accessor = [].concat(accessor);
	return accessor.map((a, idx) => {
		a = base + accessorToObjectAccess(accessor.slice(0, idx + 1));
		if(idx === accessor.length - 1) return a;
		return `${a} = ${a} || {}`;
	}).join(", ");
}

class UmdMainTemplatePlugin {
	constructor(name, options) {
		this.name = name;
		this.optionalAmdExternalAsGlobal = options.optionalAmdExternalAsGlobal;
		this.namedDefine = options.namedDefine;
		this.auxiliaryComment = options.auxiliaryComment;
	}

	apply(compilation) {
		const mainTemplate = compilation.mainTemplate;
		compilation.templatesPlugin("render-with-entry", function(source, chunk, hash) {
			let externals = chunk.modules.filter(m => m.external);
			const optionalExternals = [];
			let requiredExternals = [];
			if(this.optionalAmdExternalAsGlobal) {
				externals.forEach(m => {
					if(m.optional) {
						optionalExternals.push(m);
					} else {
						requiredExternals.push(m);
					}
				});
				externals = requiredExternals.concat(optionalExternals);
			} else {
				requiredExternals = externals;
			}

			function replaceKeys(str) {
				return mainTemplate.applyPluginsWaterfall("asset-path", str, {
					hash,
					chunk
				});
			}

			function externalsDepsArray(modules) {
				return `[${replaceKeys(modules.map(m => JSON.stringify(typeof m.request === "object" ? m.request.amd : m.request)).join(", "))}]`;
			}

			function externalsRootArray(modules) {
				return replaceKeys(modules.map(m => {
					let request = m.request;
					if(typeof request === "object") request = request.root;
					return `root${accessorToObjectAccess([].concat(request))}`;
				}).join(", "));
			}

			function externalsRequireArray(type) {
				return replaceKeys(externals.map(m => {
					let expr;
					let request = m.request;
					if(typeof request === "object") request = request[type];
					if(Array.isArray(request)) {
						expr = `require(${JSON.stringify(request[0])})${accessorToObjectAccess(request.slice(1))}`;
					} else
						expr = `require(${JSON.stringify(request)})`;
					if(m.optional) {
						expr = `(function webpackLoadOptionalExternalModule() { try { return ${expr}; } catch(e) {} }())`;
					}
					return expr;
				}).join(", "));
			}

      function externalsArguments(modules) {
		    return modules.map(m => Template.toIdentifier(`__WEBPACK_EXTERNAL_MODULE_${m.id}__`).join(", "));
		  }

			function libraryName(library) {
				return JSON.stringify(replaceKeys([].concat(library).pop()));
			}

			let amdFactory;
			if(optionalExternals.length > 0) {
				const wrapperArguments = externalsArguments(requiredExternals);
				const factoryArguments = requiredExternals.length > 0 ?
					externalsArguments(requiredExternals) + ", " + externalsRootArray(optionalExternals) :
					externalsRootArray(optionalExternals);
				amdFactory = `function webpackLoadOptionalExternalModuleAmd(${wrapperArguments}) {\n` +
					`			return factory(${factoryArguments});\n` +
					"		}";
			} else {
				amdFactory = "factory";
			}

			return new ConcatSource(new OriginalSource(
				"(function webpackUniversalModuleDefinition(root, factory) {\n" +
				(this.auxiliaryComment &&
					typeof this.auxiliaryComment === "string" ?
					"   //" + this.auxiliaryComment + "\n" :
					this.auxiliaryComment.commonjs2 ?
					"   //" + this.auxiliaryComment.commonjs2 + "\n" :
					""
				) +
				"	if(typeof exports === 'object' && typeof module === 'object')\n" +
				"		module.exports = factory(" + externalsRequireArray("commonjs2") + ");\n" +
				(this.auxiliaryComment &&
					typeof this.auxiliaryComment === "string" ?
					"   //" + this.auxiliaryComment + "\n" :
					this.auxiliaryComment.amd ?
					"   //" + this.auxiliaryComment.amd + "\n" :
					""
				) +
				"	else if(typeof define === 'function' && define.amd)\n" +
				(requiredExternals.length > 0 ?
					(this.name && this.namedDefine === true ?
						"		define(" + libraryName(this.name) + ", " + externalsDepsArray(requiredExternals) + ", " + amdFactory + ");\n" :
						"		define(" + externalsDepsArray(requiredExternals) + ", " + amdFactory + ");\n"
					) :
					(this.name && this.namedDefine === true ?
						"		define(" + libraryName(this.name) + ", [], " + amdFactory + ");\n" :
						"		define([], " + amdFactory + ");\n"
					)
				) +
				(this.name ?
					(this.auxiliaryComment &&
						typeof this.auxiliaryComment === "string" ?
						"   //" + this.auxiliaryComment + "\n" :
						this.auxiliaryComment.commonjs ?
						"   //" + this.auxiliaryComment.commonjs + "\n" :
						""
					) +
					"	else if(typeof exports === 'object')\n" +
					"		exports[" + libraryName(this.name) + "] = factory(" + externalsRequireArray("commonjs") + ");\n" +
					(this.auxiliaryComment &&
						typeof this.auxiliaryComment === "string" ?
						"   //" + this.auxiliaryComment + "\n" :
						this.auxiliaryComment.root ?
						"   //" + this.auxiliaryComment.root + "\n" :
						""
					) +
					"	else\n" +
					"		" + replaceKeys(accessorAccess("root", this.name)) + " = factory(" + externalsRootArray(externals) + ");\n" :
					"	else {\n" +
					(externals.length > 0 ?
						"		var a = typeof exports === 'object' ? factory(" + externalsRequireArray("commonjs") + ") : factory(" + externalsRootArray(externals) + ");\n" :
						"		var a = factory();\n"
					) +
					"		for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n" +
					"	}\n"
				) +
				"})(this, function(" + externalsArguments(externals) + ") {\nreturn ", "webpack/universalModuleDefinition"), source, ";\n})");
		}.bind(this));
		mainTemplate.plugin("global-hash-paths", function(paths) {
			if(this.name) paths = paths.concat(this.name);
			return paths;
		}.bind(this));
		mainTemplate.plugin("hash", function(hash) {
			hash.update("umd");
			hash.update(`${this.name}`);
		}.bind(this));
	}
}

module.exports = UmdMainTemplatePlugin;
<commit_msg>fixes spacing and typo<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

const ConcatSource = require("webpack-sources").ConcatSource;
const OriginalSource = require("webpack-sources").OriginalSource;
const Template = require("./Template");

function accessorToObjectAccess(accessor) {
	return accessor.map(a => `[${JSON.stringify(a)}]`).join("");
}

function accessorAccess(base, accessor) {
	accessor = [].concat(accessor);
	return accessor.map((a, idx) => {
		a = base + accessorToObjectAccess(accessor.slice(0, idx + 1));
		if(idx === accessor.length - 1) return a;
		return `${a} = ${a} || {}`;
	}).join(", ");
}

class UmdMainTemplatePlugin {
	constructor(name, options) {
		this.name = name;
		this.optionalAmdExternalAsGlobal = options.optionalAmdExternalAsGlobal;
		this.namedDefine = options.namedDefine;
		this.auxiliaryComment = options.auxiliaryComment;
	}

	apply(compilation) {
		const mainTemplate = compilation.mainTemplate;
		compilation.templatesPlugin("render-with-entry", function(source, chunk, hash) {
			let externals = chunk.modules.filter(m => m.external);
			const optionalExternals = [];
			let requiredExternals = [];
			if(this.optionalAmdExternalAsGlobal) {
				externals.forEach(m => {
					if(m.optional) {
						optionalExternals.push(m);
					} else {
						requiredExternals.push(m);
					}
				});
				externals = requiredExternals.concat(optionalExternals);
			} else {
				requiredExternals = externals;
			}

			function replaceKeys(str) {
				return mainTemplate.applyPluginsWaterfall("asset-path", str, {
					hash,
					chunk
				});
			}

			function externalsDepsArray(modules) {
				return `[${replaceKeys(modules.map(m => JSON.stringify(typeof m.request === "object" ? m.request.amd : m.request)).join(", "))}]`;
			}

			function externalsRootArray(modules) {
				return replaceKeys(modules.map(m => {
					let request = m.request;
					if(typeof request === "object") request = request.root;
					return `root${accessorToObjectAccess([].concat(request))}`;
				}).join(", "));
			}

			function externalsRequireArray(type) {
				return replaceKeys(externals.map(m => {
					let expr;
					let request = m.request;
					if(typeof request === "object") request = request[type];
					if(Array.isArray(request)) {
						expr = `require(${JSON.stringify(request[0])})${accessorToObjectAccess(request.slice(1))}`;
					} else
						expr = `require(${JSON.stringify(request)})`;
					if(m.optional) {
						expr = `(function webpackLoadOptionalExternalModule() { try { return ${expr}; } catch(e) {} }())`;
					}
					return expr;
				}).join(", "));
			}

			function externalsArguments(modules) {
				return modules.map(m => Template.toIdentifier(`__WEBPACK_EXTERNAL_MODULE_${m.id}__`)).join(", ");
			}

			function libraryName(library) {
				return JSON.stringify(replaceKeys([].concat(library).pop()));
			}

			let amdFactory;
			if(optionalExternals.length > 0) {
				const wrapperArguments = externalsArguments(requiredExternals);
				const factoryArguments = requiredExternals.length > 0 ?
					externalsArguments(requiredExternals) + ", " + externalsRootArray(optionalExternals) :
					externalsRootArray(optionalExternals);
				amdFactory = `function webpackLoadOptionalExternalModuleAmd(${wrapperArguments}) {\n` +
					`			return factory(${factoryArguments});\n` +
					"		}";
			} else {
				amdFactory = "factory";
			}

			return new ConcatSource(new OriginalSource(
				"(function webpackUniversalModuleDefinition(root, factory) {\n" +
				(this.auxiliaryComment &&
					typeof this.auxiliaryComment === "string" ?
					"   //" + this.auxiliaryComment + "\n" :
					this.auxiliaryComment.commonjs2 ?
					"   //" + this.auxiliaryComment.commonjs2 + "\n" :
					""
				) +
				"	if(typeof exports === 'object' && typeof module === 'object')\n" +
				"		module.exports = factory(" + externalsRequireArray("commonjs2") + ");\n" +
				(this.auxiliaryComment &&
					typeof this.auxiliaryComment === "string" ?
					"   //" + this.auxiliaryComment + "\n" :
					this.auxiliaryComment.amd ?
					"   //" + this.auxiliaryComment.amd + "\n" :
					""
				) +
				"	else if(typeof define === 'function' && define.amd)\n" +
				(requiredExternals.length > 0 ?
					(this.name && this.namedDefine === true ?
						"		define(" + libraryName(this.name) + ", " + externalsDepsArray(requiredExternals) + ", " + amdFactory + ");\n" :
						"		define(" + externalsDepsArray(requiredExternals) + ", " + amdFactory + ");\n"
					) :
					(this.name && this.namedDefine === true ?
						"		define(" + libraryName(this.name) + ", [], " + amdFactory + ");\n" :
						"		define([], " + amdFactory + ");\n"
					)
				) +
				(this.name ?
					(this.auxiliaryComment &&
						typeof this.auxiliaryComment === "string" ?
						"   //" + this.auxiliaryComment + "\n" :
						this.auxiliaryComment.commonjs ?
						"   //" + this.auxiliaryComment.commonjs + "\n" :
						""
					) +
					"	else if(typeof exports === 'object')\n" +
					"		exports[" + libraryName(this.name) + "] = factory(" + externalsRequireArray("commonjs") + ");\n" +
					(this.auxiliaryComment &&
						typeof this.auxiliaryComment === "string" ?
						"   //" + this.auxiliaryComment + "\n" :
						this.auxiliaryComment.root ?
						"   //" + this.auxiliaryComment.root + "\n" :
						""
					) +
					"	else\n" +
					"		" + replaceKeys(accessorAccess("root", this.name)) + " = factory(" + externalsRootArray(externals) + ");\n" :
					"	else {\n" +
					(externals.length > 0 ?
						"		var a = typeof exports === 'object' ? factory(" + externalsRequireArray("commonjs") + ") : factory(" + externalsRootArray(externals) + ");\n" :
						"		var a = factory();\n"
					) +
					"		for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n" +
					"	}\n"
				) +
				"})(this, function(" + externalsArguments(externals) + ") {\nreturn ", "webpack/universalModuleDefinition"), source, ";\n})");
		}.bind(this));
		mainTemplate.plugin("global-hash-paths", function(paths) {
			if(this.name) paths = paths.concat(this.name);
			return paths;
		}.bind(this));
		mainTemplate.plugin("hash", function(hash) {
			hash.update("umd");
			hash.update(`${this.name}`);
		}.bind(this));
	}
}

module.exports = UmdMainTemplatePlugin;
<|endoftext|>