<commit_before>var fs = require('fs');
var csv = require('csv');
var path = require('path');
var util = require('util');
var utils = require('../util/utils');
var Tbl = require('../common/tbl');
var EventEmitter = require('events').EventEmitter;
var logger = require('pomelo-logger').getLogger('pomelo-data', __filename);

var instance = null;

module.exports = function(app, opts) {
  // singleton
  if(instance) {
    return instance;
  }

	instance = new Component(app, opts);
  app.set('dataService', instance);
	return instance;
};

var Component = function(app, opts) {
  this.app = app;
  this.dir = opts.dir;
  this.idx = opts.idx;
  this.interval = opts.interval;
  this.numDict = {cur: 0, total: 0}; // config files' amount
  this.tmpConfigDataTbl = {};
  this.configDataTbl = {};
  this.csvParsers = {};

  if(!fs.existsSync(this.dir)) {
    logger.error('Dir %s not exist!', this.dir);
    return;
  }
};

util.inherits(Component, EventEmitter);

Component.prototype.start = function(cb) {
  this.loadAll(cb);
};

Component.prototype.stop = function(force, cb) {
  this.tmpConfigDataTbl = null;
  this.configDataTbl = null;
  this.csvParsers = null;
  utils.invokeCallback(cb);
};

Component.prototype.loadFileFunc = function(filename, isLoadAll, cb) {
  var self = this;
  var curFileIdx = path.basename(filename, '.csv');
  self.tmpConfigDataTbl[curFileIdx] = [];

  self.csvParsers[curFileIdx] = csv();
  var tmpParser = self.csvParsers[curFileIdx];

  tmpParser.from.path(filename, {comment: '#'});

  tmpParser.on('record', function(row, index){
    var tmpL = self.tmpConfigDataTbl[curFileIdx];
    if(tmpL) {
      tmpL.push(row);
    }
  });

  tmpParser.on('end', function(){
    self.configDataTbl[curFileIdx] = new Tbl(self.tmpConfigDataTbl[curFileIdx], self.idx);
    if(isLoadAll) {
      self.numDict.cur++;
      if(self.numDict.cur === self.numDict.total) {
        utils.invokeCallback(cb);
        self.tmpConfigDataTbl = {}; // release temp data
      }
    }
  });

  tmpParser.on('error', function(err){
    logger.error(err.message);
    utils.invokeCallback(cb, err);
  });
};

Component.prototype.listener4watch = function(filename) {
  var self = this;
  return function(curr, prev) {
    if(curr.mtime.getTime() > prev.mtime.getTime()) {
      self.loadFileFunc(filename);
    }
  };
};

Component.prototype.loadAll = function(cb) {
  var self = this;
  self.tmpConfigDataTbl = {};
  self.configDataTbl = {};

  fs.readdirSync(self.dir).forEach(function(filename) {
    if (!/\.csv$/.test(filename)) {
      return;
    }
    var absolutePath = path.join(self.dir, filename);
    if(fs.existsSync(absolutePath)) {
      self.numDict.total++;
    }
  });

  fs.readdirSync(self.dir).forEach(function(filename) {
    if (!/\.csv$/.test(filename)) {
      return;
    }
    var absolutePath = path.join(self.dir, filename);
    if(!fs.existsSync(absolutePath)) {
      logger.error('Config file %s not exist at %s!', filename, absolutePath);
    } else {
      // invoke cb(start next component) when all files have been loaded
      self.loadFileFunc(absolutePath, true, cb);
      fs.watchFile(absolutePath, { persistent: true, interval: self.interval }, self.listener4watch(absolutePath));
    }
  });
};

Component.prototype.get = function(tblName) {
  return this.configDataTbl[tblName];
};

<commit_msg>添加onLoad函数<commit_after>var fs = require('fs');
var csv = require('csv');
var path = require('path');
var util = require('util');
var utils = require('../util/utils');
var Tbl = require('../common/tbl');
var EventEmitter = require('events').EventEmitter;
var logger = require('pomelo-logger').getLogger('pomelo-data', __filename);

var instance = null;

module.exports = function(app, opts) {
  // singleton
  if(instance) {
    return instance;
  }

  instance = new Component(app, opts);
  app.set('dataService', instance);
  return instance;
};

var Component = function(app, opts) {
  this.app = app;
  this.dir = opts.dir;
  this.idx = opts.idx;
  this.interval = opts.interval;
  this.numDict = {cur: 0, total: 0}; // config files' amount
  this.tmpConfigDataTbl = {};
  this.configDataTbl = {};
  this.csvParsers = {};
  this.onLoad = opts.onLoad;

  if(!fs.existsSync(this.dir)) {
    logger.error('Dir %s not exist!', this.dir);
    return;
  }
};

util.inherits(Component, EventEmitter);

Component.prototype.start = function(cb) {
  this.loadAll(cb);
};

Component.prototype.stop = function(force, cb) {
  this.tmpConfigDataTbl = null;
  this.configDataTbl = null;
  this.csvParsers = null;
  utils.invokeCallback(cb);
};

Component.prototype.loadFileFunc = function(filename, isLoadAll, cb) {
  var self = this;
  var curFileIdx = path.basename(filename, '.csv');
  self.tmpConfigDataTbl[curFileIdx] = [];

  self.csvParsers[curFileIdx] = csv();
  var tmpParser = self.csvParsers[curFileIdx];

  tmpParser.from.path(filename, {comment: '#'});

  tmpParser.on('record', function(row, index){
    // console.log('#' + index + ' ' + JSON.stringify(row));
    var tmpL = self.tmpConfigDataTbl[curFileIdx];
    if(tmpL) {
      tmpL.push(row);
    }
  });

  tmpParser.on('end', function(){
    // console.log('csvParsers ~ on.end is running ...');
    self.configDataTbl[curFileIdx] = new Tbl(self.tmpConfigDataTbl[curFileIdx], self.idx);
    if(isLoadAll) {
      self.numDict.cur++;
      if(self.numDict.cur === self.numDict.total) {
        utils.invokeCallback(cb);
        self.tmpConfigDataTbl = {}; // release temp data
      }
    }

    if (self.onLoad) {
      self.onLoad(filename);
    }
  });

  tmpParser.on('error', function(err){
    logger.error(err.message);
    utils.invokeCallback(cb, err);
  });
};

Component.prototype.listener4watch = function(filename) {
  var self = this;
  return function(curr, prev) {
    if(curr.mtime.getTime() > prev.mtime.getTime()) {
      self.loadFileFunc(filename);
      /*
      setTimeout(function() {
        console.warn('\n', Date(), ': Listener4watch ~ configDataTbl = ', util.inspect(self.configDataTbl, {showHidden: true, depth: null}))
      }, 2000);
      */
    }
  };
};

Component.prototype.loadAll = function(cb) {
  var self = this;
  self.tmpConfigDataTbl = {};
  self.configDataTbl = {};

  fs.readdirSync(self.dir).forEach(function(filename) {
    if (!/\.csv$/.test(filename)) {
      return;
    }
    var absolutePath = path.join(self.dir, filename);
    if(fs.existsSync(absolutePath)) {
      self.numDict.total++;
    }
  });
  // console.log('self.numDict.total = ', self.numDict.total);

  fs.readdirSync(self.dir).forEach(function(filename) {
    if (!/\.csv$/.test(filename)) {
      return;
    }
    var absolutePath = path.join(self.dir, filename);
    if(!fs.existsSync(absolutePath)) {
      logger.error('Config file %s not exist at %s!', filename, absolutePath);
    } else {
      // console.warn('!!! filename = %s, absolutePath = %s', filename, absolutePath);
      // invoke cb(start next component) when all files have been loaded
      self.loadFileFunc(absolutePath, true, cb);
      fs.watchFile(absolutePath, { persistent: true, interval: self.interval }, self.listener4watch(absolutePath));
    }
  });
  /*
  setTimeout(function() {
    console.warn('\n', Date(), ': LoadAll ~ configDataTbl = ', util.inspect(self.configDataTbl, {showHidden: true, depth: null}))
  }, 2000);
  */
};

Component.prototype.get = function(tblName) {
  return this.configDataTbl[tblName];
};

<|endoftext|>


<commit_before>jstd = jstestdriver;
dump = bind(jstd.console, jstd.console.log);

function nakedExpect(obj) {
  return expect(angular.fromJson(angular.toJson(obj)));
}

function childNode(element, index) {
  return jqLite(element[0].childNodes[index]);
}

extend(angular, {
  'element': jqLite,
  'compile': compile,
  'scope': createScope,
  'copy': copy,
  'extend': extend,
  'foreach': foreach,
  'noop':noop,
  'identity':identity,
  'isUndefined': isUndefined,
  'isDefined': isDefined,
  'isString': isString,
  'isFunction': isFunction,
  'isNumber': isNumber,
  'isArray': isArray
});

function trigger(element, type) {
  var evnt = document.createEvent('MouseEvent');
  evnt.initMouseEvent(type, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  (element[0] || element).dispatchEvent(evnt);
}

function sortedHtml(element) {
  var html = "";
  foreach(element, function toString(node) {
    if (node.nodeName == "#text") {
      html += escapeHtml(node.nodeValue);
    } else {
      html += '<' + node.nodeName.toLowerCase();
      var attributes = node.attributes || [];
      var attrs = [];
      for(var i=0; i<attributes.length; i++) {
        var attr = attributes[i];
        if(attr.name.match(/^ng-/) ||
            attr.value &&
            attr.value !='null' &&
            attr.value !='auto' &&
            attr.value !='false' &&
            attr.value !='inherit' &&
            attr.value !='0' &&
            attr.name !='loop' &&
            attr.name !='maxLength' &&
            attr.name !='size' &&
            attr.name !='start' &&
            attr.name !='tabIndex' &&
            attr.name !='style' &&
            attr.name.substr(0, 6) != 'jQuery') {
          // in IE we need to check for all of these.
          attrs.push(' ' + attr.name + '="' + attr.value + '"');
        }
      }
      attrs.sort();
      html += attrs.join('');
      var style = [];
      for(var name in node.style) {
        var value = node.style[name];
        if (value && isString(value) && (name != 1*name) && (name != 'cssText')) {
          style.push(name + ': ' + value + ';');
        }
      }
      style.sort();
      if (style.length) {
        html += ' style="' + style.join(' ') + '"';
      }
      html += '>';
      var children = node.childNodes;
      for(var j=0; j<children.length; j++) {
        toString(children[j]);
      }
      html += '</' + node.nodeName.toLowerCase() + '>';
    }
  });
  return html;
}

function isCssVisible(node) {
  var display = node.css('display');
  if (display == 'block') display = "";
  return display != 'none';
}

function assertHidden(node) {
  assertFalse("Node should be hidden but vas visible: " + sortedHtml(node), isCssVisible(node));
}

function assertVisible(node) {
  assertTrue("Node should be visible but vas hidden: " + sortedHtml(node), isCssVisible(node));
}

function assertJsonEquals(expected, actual) {
  assertEquals(toJson(expected), toJson(actual));
}

function assertUndefined(value) {
  assertEquals('undefined', typeof value);
}

function assertDefined(value) {
  assertTrue(toJson(value), !!value);
}

function assertThrows(error, fn){
  var exception = null;
  try {
    fn();
  } catch(e) {
    exception = e;
  }
  if (!exception) {
    fail("Expecting exception, none thrown");
  }
  assertEquals(error, exception);
}

log = noop;
error = noop;
<commit_msg>tests pass on chrome<commit_after>jstd = jstestdriver;
dump = bind(jstd.console, jstd.console.log);

function nakedExpect(obj) {
  return expect(angular.fromJson(angular.toJson(obj)));
}

function childNode(element, index) {
  return jqLite(element[0].childNodes[index]);
}

extend(angular, {
  'element': jqLite,
  'compile': compile,
  'scope': createScope,
  'copy': copy,
  'extend': extend,
  'foreach': foreach,
  'noop':noop,
  'identity':identity,
  'isUndefined': isUndefined,
  'isDefined': isDefined,
  'isString': isString,
  'isFunction': isFunction,
  'isNumber': isNumber,
  'isArray': isArray
});

function trigger(element, type) {
  var evnt = document.createEvent('MouseEvent');
  evnt.initMouseEvent(type, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  (element[0] || element).dispatchEvent(evnt);
}

function sortedHtml(element) {
  var html = "";
  foreach(element, function toString(node) {
    if (node.nodeName == "#text") {
      html += escapeHtml(node.nodeValue);
    } else {
      html += '<' + node.nodeName.toLowerCase();
      var attributes = node.attributes || [];
      var attrs = [];
      for(var i=0; i<attributes.length; i++) {
        var attr = attributes[i];
        if(attr.name.match(/^ng-/) ||
            attr.value &&
            attr.value !='null' &&
            attr.value !='auto' &&
            attr.value !='false' &&
            attr.value !='inherit' &&
            attr.value !='0' &&
            attr.name !='loop' &&
            attr.name !='maxLength' &&
            attr.name !='size' &&
            attr.name !='start' &&
            attr.name !='tabIndex' &&
            attr.name !='style' &&
            attr.name.substr(0, 6) != 'jQuery') {
          // in IE we need to check for all of these.
          attrs.push(' ' + attr.name + '="' + attr.value + '"');
        }
      }
      attrs.sort();
      html += attrs.join('');
      if (node.style && node.style.cssText) {
        var style = node.style.cssText.split('; ');
        style.sort();
        if (style[0] == '')
          style.shift();
        html += ' style="' + style.join('; ') + ';"';
      }
      html += '>';
      var children = node.childNodes;
      for(var j=0; j<children.length; j++) {
        toString(children[j]);
      }
      html += '</' + node.nodeName.toLowerCase() + '>';
    }
  });
  return html;
}

function isCssVisible(node) {
  var display = node.css('display');
  if (display == 'block') display = "";
  return display != 'none';
}

function assertHidden(node) {
  assertFalse("Node should be hidden but vas visible: " + sortedHtml(node), isCssVisible(node));
}

function assertVisible(node) {
  assertTrue("Node should be visible but vas hidden: " + sortedHtml(node), isCssVisible(node));
}

function assertJsonEquals(expected, actual) {
  assertEquals(toJson(expected), toJson(actual));
}

function assertUndefined(value) {
  assertEquals('undefined', typeof value);
}

function assertDefined(value) {
  assertTrue(toJson(value), !!value);
}

function assertThrows(error, fn){
  var exception = null;
  try {
    fn();
  } catch(e) {
    exception = e;
  }
  if (!exception) {
    fail("Expecting exception, none thrown");
  }
  assertEquals(error, exception);
}

log = noop;
error = noop;
<|endoftext|>


<commit_before>var ComputeBreakdowns = {
  stock_details: {},
  breakdown_totals: {},
  total_portfolio_value: 0.0,
  total_weighted_cost: 0.0,

  init: function(stock_summaries, stocks) {
    this.stock_details = {};
    this.breakdown_totals = {};
    this.total_portfolio_value = 0.0;
    this.total_weighted_cost = 0.0;

    for (var i = 0; i < stocks.length; i++) {
      var stock = stocks[i];
      this.stock_details[stock.symbol] = stock;
    }

    for (var symbol in stock_summaries) {
      matching_keys = this.getMatchingKeys(this.stock_details[symbol])
      this.total_portfolio_value += stock_summaries[symbol].total_value;
      this.total_weighted_cost += stock_summaries[symbol].weighted_cost;
      for (var i = 0; i < matching_keys.length; i++) {
        key = matching_keys[i];
        this.addToKey(key, stock_summaries[symbol]);
      }
    }

    for (var symbol in this.breakdown_totals) {
      this.breakdown_totals[symbol].portion = this.breakdown_totals[symbol].total_value * 100.0 / this.total_portfolio_value;
    }

    this.breakdown_totals[Constants.STOCK_ALL].weighted_cost = this.total_weighted_cost;
  },

  getMatchingKeys: function(stock) {
    var keys = [];
    if (stock.is_us) {
      keys.push("US");
    } else {
      keys.push("INT");
    }

    keys.push(stock.stock_type);
    keys.push(keys[0] + keys[1]);
    keys.push(Constants.STOCK_ALL);

    return keys;
  },

  addToKey: function(key, stock_summary) {
      if (key in this.breakdown_totals) {
        this.breakdown_totals[key].total_value += stock_summary.total_value;
        this.breakdown_totals[key].unrealized_pl += stock_summary.unrealized_pl;
        if (!isNaN(stock_summary.realized_pl)){
          if (("realized_pl" in this.breakdown_totals[key])){
            this.breakdown_totals[key].realized_pl += stock_summary.realized_pl;
          } else {
            this.breakdown_totals[key].realized_pl = stock_summary.realized_pl;
          }
        }
      } else {
        this.breakdown_totals[key] = {
          total_value: stock_summary.total_value,
          unrealized_pl: stock_summary.unrealized_pl,
        };
        if (!isNaN(stock_summary.realized_pl)){
          this.breakdown_totals[key].realized_pl = stock_summary.realized_pl;
        }
      }
  },

  getStockBreakdowns: function() {
    return this.breakdown_totals;
  }
};
<commit_msg>Adding the requested changes to the code<commit_after>var ComputeBreakdowns = {
  stock_details: {},
  breakdown_totals: {},
  total_portfolio_value: 0.0,
  total_weighted_cost: 0.0,

  init: function(stock_summaries, stocks) {
    this.stock_details = {};
    this.breakdown_totals = {};
    this.total_portfolio_value = 0.0;
    this.total_weighted_cost = 0.0;

    for (var i = 0; i < stocks.length; i++) {
      var stock = stocks[i];
      this.stock_details[stock.symbol] = stock;
    }

    for (var symbol in stock_summaries) {
      matching_keys = this.getMatchingKeys(this.stock_details[symbol])
      this.total_portfolio_value += stock_summaries[symbol].total_value;
      this.total_weighted_cost += stock_summaries[symbol].weighted_cost;
      for (var i = 0; i < matching_keys.length; i++) {
        key = matching_keys[i];
        this.addToKey(key, stock_summaries[symbol]);
      }
    }

    for (var symbol in this.breakdown_totals) {
      this.breakdown_totals[symbol].portion = this.breakdown_totals[symbol].total_value * 100.0 / this.total_portfolio_value;
    }

    this.breakdown_totals[Constants.STOCK_ALL].weighted_cost = this.total_weighted_cost;
  },

  getMatchingKeys: function(stock) {
    var keys = [];
    if (stock.is_us) {
      keys.push("US");
    } else {
      keys.push("INT");
    }

    keys.push(stock.stock_type);
    keys.push(keys[0] + keys[1]);
    keys.push(Constants.STOCK_ALL);

    return keys;
  },

  addToKey: function(key, stock_summary) {
      if (key in this.breakdown_totals) {
        this.breakdown_totals[key].total_value += stock_summary.total_value;
        this.breakdown_totals[key].unrealized_pl += stock_summary.unrealized_pl;
        if (!isNaN(stock_summary.realized_pl)){
          if (("realized_pl" in this.breakdown_totals[key])){
            this.breakdown_totals[key].realized_pl += stock_summary.realized_pl;
          } else {
            this.breakdown_totals[key].realized_pl = stock_summary.realized_pl;
          }
        }
      } else {
        this.breakdown_totals[key] = {
          total_value: stock_summary.total_value,
          unrealized_pl: stock_summary.unrealized_pl,
        }
        if (!isNaN(stock_summary.realized_pl)){
          this.breakdown_totals[key].realized_pl = stock_summary.realized_pl;
        }
      }
  },

  getStockBreakdowns: function() {
    return this.breakdown_totals;
  }
};
<|endoftext|>


<commit_before>/**
 * Here is the problem: http://bugs.jquery.com/ticket/7292
 * basically jQuery treats change event on some browsers (IE) as a
 * special event and changes it form 'change' to 'click/keydown' and
 * few others. This horrible hack removes the special treatment
 */
_jQuery.event.special.change = undefined;

if (window.jstestdriver) {
  jstd = jstestdriver;
  window.dump = function(){
    var args = [];
    forEach(arguments, function(arg){
      if (isElement(arg)) {
        arg = sortedHtml(arg);
      } else if (isObject(arg)) {
        arg = toJson(arg, true);
      }
      args.push(arg);
    });
    jstd.console.log.apply(jstd.console, args);
  };
}

beforeEach(function(){
  // This is to reset parsers global cache of expressions.
  compileCache = {};
  // reset to jQuery or default to us.
  bindJQuery();
  jqLite(document.body).html('');
  this.addMatchers({
    toBeInvalid: function(){
      var element = jqLite(this.actual);
      var hasClass = element.hasClass('ng-validation-error');
      var validationError = element.attr('ng-validation-error');
      this.message = function(){
        if (!hasClass)
          return "Expected class 'ng-validation-error' not found.";
        return "Expected an error message, but none was found.";
      };
      return hasClass && validationError;
    },

    toBeValid: function(){
      var element = jqLite(this.actual);
      var hasClass = element.hasClass('ng-validation-error');
      this.message = function(){
        return "Expected to not have class 'ng-validation-error' but found.";
      };
      return !hasClass;
    },

    toEqualData: function(expected) {
      return equals(this.actual, expected);
    },

    toHaveClass: function(clazz) {
      this.message = function(){
        return "Expected '" + sortedHtml(this.actual) + "' to have class '" + clazz + "'.";
      };
      return this.actual.hasClass ?
              this.actual.hasClass(clazz) :
              jqLite(this.actual).hasClass(clazz);
    },

    toEqualError: function(message) {
      this.message = function() {
        var expected;
        if (this.actual.message && this.actual.name == 'Error') {
          expected = toJson(this.actual.message);
        } else {
          expected = toJson(this.actual);
        }
        return "Expected " + expected + " to be an Error with message " + toJson(message);
      };
      return this.actual.name == 'Error' && this.actual.message == message;
    },

    toMatchError: function(messageRegexp) {
      this.message = function() {
        var expected;
        if (this.actual.message && this.actual.name == 'Error') {
          expected = toJson(this.actual.message);
        } else {
          expected = toJson(this.actual);
        }
        return "Expected " + expected + " to match an Error with message " + toJson(messageRegexp);
      };
      return this.actual.name == 'Error' && messageRegexp.test(this.actual.message);
    }
  });

  $logMock.log.logs = [];
  $logMock.warn.logs = [];
  $logMock.info.logs = [];
  $logMock.error.logs = [];
});

afterEach(function() {
  // check $log mock
  forEach(['error', 'warn', 'info', 'log'], function(logLevel) {
    if ($logMock[logLevel].logs.length) {
      forEach($logMock[logLevel].logs, function(log) {
        forEach(log, function deleteStack(logItem) {
          if (logItem instanceof Error) {
            dump(logItem.stack);
            delete logItem.stack;
            delete logItem.arguments;
          } else {
            dump(logItem);
          }
        });
      });

      throw new Error("Exprected $log." + logLevel + ".logs array to be empty. " +
        "Either a message was logged unexpectedly, or an expected log message was not checked " +
        "and removed. Array contents: " + toJson($logMock[logLevel].logs));
    }
  });

  clearJqCache();
});

function clearJqCache(){
  var count = 0;
  forEachSorted(jqCache, function(value, key){
    count ++;
    delete jqCache[key];
    forEach(value, function(value, key){
      if (value.$element)
        dump(key, sortedHtml(value.$element));
      else
        dump(key, toJson(value));
    });
  });
  if (count) {
    fail('Found jqCache references that were not deallocated!');
  }
}

function nakedExpect(obj) {
  return expect(angular.fromJson(angular.toJson(obj)));
}

function childNode(element, index) {
  return jqLite(element[0].childNodes[index]);
}

function dealoc(obj) {
  if (obj) {
    var element = obj.$element || obj || {};
    if (element.nodeName) element = jqLite(element);
    if (element.dealoc) element.dealoc();
  }
}

extend(angular, {
  'annotate': annotate,
  'element': jqLite,
  'compile': compile,
  'scope': createScope,
  'copy': copy,
  'extend': extend,
  'equals': equals,
  'forEach': forEach,
  'noop':noop,
  'bind':bind,
  'toJson': toJson,
  'fromJson': fromJson,
  'identity':identity,
  'injector': createInjector,
  'isUndefined': isUndefined,
  'isDefined': isDefined,
  'isString': isString,
  'isFunction': isFunction,
  'isObject': isObject,
  'isNumber': isNumber,
  'isArray': isArray,
  'forEach': forEach
});

function sortedHtml(element, showNgClass) {
  var html = "";
  forEach(jqLite(element), function toString(node) {
    if (node.nodeName == "#text") {
      html += node.nodeValue.
        replace(/&(\w+[&;\W])?/g, function(match, entity){return entity?match:'&';}).
        replace(/</g, '<').
        replace(/>/g, '>');
    } else {
      html += '<' + (node.nodeName || '?NOT_A_NODE?').toLowerCase();
      var attributes = node.attributes || [];
      var attrs = [];
      var className = node.className || '';
      if (!showNgClass) {
        className = className.replace(/ng-[\w-]+\s*/g, '');
      }
      className = trim(className);
      if (className) {
        attrs.push(' class="' + className + '"');
      }
      for(var i=0; i<attributes.length; i++) {
        if (i>0 && attributes[i] == attributes[i-1])
          continue; //IE9 creates dupes. Ignore them!

        var attr = attributes[i];
        if(attr.name.match(/^ng:/) ||
            attr.value &&
            attr.value !='null' &&
            attr.value !='auto' &&
            attr.value !='false' &&
            attr.value !='inherit' &&
            (attr.value !='0' || attr.name =='value') &&
            attr.name !='loop' &&
            attr.name !='complete' &&
            attr.name !='maxLength' &&
            attr.name !='size' &&
            attr.name !='class' &&
            attr.name !='start' &&
            attr.name !='tabIndex' &&
            attr.name !='style' &&
            attr.name.substr(0, 6) != 'jQuery') {
          // in IE we need to check for all of these.
          if (!/ng-\d+/.exec(attr.name) &&
              attr.name != 'getElementById' &&
              // IE7 has `selected` in attributes
              attr.name !='selected' &&
              // IE7 adds `value` attribute to all LI tags
              (node.nodeName != 'LI' || attr.name != 'value'))
            attrs.push(' ' + attr.name + '="' + attr.value + '"');
        }
      }
      attrs.sort();
      html += attrs.join('');
      if (node.style) {
        var style = [];
        if (node.style.cssText) {
          forEach(node.style.cssText.split(';'), function(value){
            value = trim(value);
            if (value) {
              style.push(lowercase(value));
            }
          });
        }
        for(var css in node.style){
          var value = node.style[css];
          if (isString(value) && isString(css) && css != 'cssText' && value && (1*css != css)) {
            var text = lowercase(css + ': ' + value);
            if (value != 'false' && indexOf(style, text) == -1) {
              style.push(text);
            }
          }
        }
        style.sort();
        var tmp = style;
        style = [];
        forEach(tmp, function(value){
          if (!value.match(/^max[^\-]/))
            style.push(value);
        });
        if (style.length) {
          html += ' style="' + style.join('; ') + ';"';
        }
      }
      html += '>';
      var children = node.childNodes;
      for(var j=0; j<children.length; j++) {
        toString(children[j]);
      }
      html += '</' + node.nodeName.toLowerCase() + '>';
    }
  });
  return html;
}

function isCssVisible(node) {
  var display = node.css('display');
  if (display == 'block') display = "";
  return display != 'none';
}

function assertHidden(node) {
  assertFalse("Node should be hidden but vas visible: " + sortedHtml(node), isCssVisible(node));
}

function assertVisible(node) {
  assertTrue("Node should be visible but vas hidden: " + sortedHtml(node), isCssVisible(node));
}

function assertJsonEquals(expected, actual) {
  assertEquals(toJson(expected), toJson(actual));
}

function assertUndefined(value) {
  assertEquals('undefined', typeof value);
}

function assertDefined(value) {
  assertTrue(toJson(value), !!value);
}

function assertThrows(error, fn){
  var exception = null;
  try {
    fn();
  } catch(e) {
    exception = e;
  }
  if (!exception) {
    fail("Expecting exception, none thrown");
  }
  assertEquals(error, exception);
}

log = noop;
error = noop;

function rethrow(e) {
  if(e) {
    throw e;
  }
}
<commit_msg>fix:testabilityPatch: remove annotate since it's not public<commit_after>/**
 * Here is the problem: http://bugs.jquery.com/ticket/7292
 * basically jQuery treats change event on some browsers (IE) as a
 * special event and changes it form 'change' to 'click/keydown' and
 * few others. This horrible hack removes the special treatment
 */
_jQuery.event.special.change = undefined;

if (window.jstestdriver) {
  jstd = jstestdriver;
  window.dump = function(){
    var args = [];
    forEach(arguments, function(arg){
      if (isElement(arg)) {
        arg = sortedHtml(arg);
      } else if (isObject(arg)) {
        arg = toJson(arg, true);
      }
      args.push(arg);
    });
    jstd.console.log.apply(jstd.console, args);
  };
}

beforeEach(function(){
  // This is to reset parsers global cache of expressions.
  compileCache = {};
  // reset to jQuery or default to us.
  bindJQuery();
  jqLite(document.body).html('');
  this.addMatchers({
    toBeInvalid: function(){
      var element = jqLite(this.actual);
      var hasClass = element.hasClass('ng-validation-error');
      var validationError = element.attr('ng-validation-error');
      this.message = function(){
        if (!hasClass)
          return "Expected class 'ng-validation-error' not found.";
        return "Expected an error message, but none was found.";
      };
      return hasClass && validationError;
    },

    toBeValid: function(){
      var element = jqLite(this.actual);
      var hasClass = element.hasClass('ng-validation-error');
      this.message = function(){
        return "Expected to not have class 'ng-validation-error' but found.";
      };
      return !hasClass;
    },

    toEqualData: function(expected) {
      return equals(this.actual, expected);
    },

    toHaveClass: function(clazz) {
      this.message = function(){
        return "Expected '" + sortedHtml(this.actual) + "' to have class '" + clazz + "'.";
      };
      return this.actual.hasClass ?
              this.actual.hasClass(clazz) :
              jqLite(this.actual).hasClass(clazz);
    },

    toEqualError: function(message) {
      this.message = function() {
        var expected;
        if (this.actual.message && this.actual.name == 'Error') {
          expected = toJson(this.actual.message);
        } else {
          expected = toJson(this.actual);
        }
        return "Expected " + expected + " to be an Error with message " + toJson(message);
      };
      return this.actual.name == 'Error' && this.actual.message == message;
    },

    toMatchError: function(messageRegexp) {
      this.message = function() {
        var expected;
        if (this.actual.message && this.actual.name == 'Error') {
          expected = toJson(this.actual.message);
        } else {
          expected = toJson(this.actual);
        }
        return "Expected " + expected + " to match an Error with message " + toJson(messageRegexp);
      };
      return this.actual.name == 'Error' && messageRegexp.test(this.actual.message);
    }
  });

  $logMock.log.logs = [];
  $logMock.warn.logs = [];
  $logMock.info.logs = [];
  $logMock.error.logs = [];
});

afterEach(function() {
  // check $log mock
  forEach(['error', 'warn', 'info', 'log'], function(logLevel) {
    if ($logMock[logLevel].logs.length) {
      forEach($logMock[logLevel].logs, function(log) {
        forEach(log, function deleteStack(logItem) {
          if (logItem instanceof Error) {
            dump(logItem.stack);
            delete logItem.stack;
            delete logItem.arguments;
          } else {
            dump(logItem);
          }
        });
      });

      throw new Error("Exprected $log." + logLevel + ".logs array to be empty. " +
        "Either a message was logged unexpectedly, or an expected log message was not checked " +
        "and removed. Array contents: " + toJson($logMock[logLevel].logs));
    }
  });

  clearJqCache();
});

function clearJqCache(){
  var count = 0;
  forEachSorted(jqCache, function(value, key){
    count ++;
    delete jqCache[key];
    forEach(value, function(value, key){
      if (value.$element)
        dump(key, sortedHtml(value.$element));
      else
        dump(key, toJson(value));
    });
  });
  if (count) {
    fail('Found jqCache references that were not deallocated!');
  }
}

function nakedExpect(obj) {
  return expect(angular.fromJson(angular.toJson(obj)));
}

function childNode(element, index) {
  return jqLite(element[0].childNodes[index]);
}

function dealoc(obj) {
  if (obj) {
    var element = obj.$element || obj || {};
    if (element.nodeName) element = jqLite(element);
    if (element.dealoc) element.dealoc();
  }
}

extend(angular, {
  'element': jqLite,
  'compile': compile,
  'scope': createScope,
  'copy': copy,
  'extend': extend,
  'equals': equals,
  'forEach': forEach,
  'noop':noop,
  'bind':bind,
  'toJson': toJson,
  'fromJson': fromJson,
  'identity':identity,
  'injector': createInjector,
  'isUndefined': isUndefined,
  'isDefined': isDefined,
  'isString': isString,
  'isFunction': isFunction,
  'isObject': isObject,
  'isNumber': isNumber,
  'isArray': isArray,
  'forEach': forEach
});

function sortedHtml(element, showNgClass) {
  var html = "";
  forEach(jqLite(element), function toString(node) {
    if (node.nodeName == "#text") {
      html += node.nodeValue.
        replace(/&(\w+[&;\W])?/g, function(match, entity){return entity?match:'&';}).
        replace(/</g, '<').
        replace(/>/g, '>');
    } else {
      html += '<' + (node.nodeName || '?NOT_A_NODE?').toLowerCase();
      var attributes = node.attributes || [];
      var attrs = [];
      var className = node.className || '';
      if (!showNgClass) {
        className = className.replace(/ng-[\w-]+\s*/g, '');
      }
      className = trim(className);
      if (className) {
        attrs.push(' class="' + className + '"');
      }
      for(var i=0; i<attributes.length; i++) {
        if (i>0 && attributes[i] == attributes[i-1])
          continue; //IE9 creates dupes. Ignore them!

        var attr = attributes[i];
        if(attr.name.match(/^ng:/) ||
            attr.value &&
            attr.value !='null' &&
            attr.value !='auto' &&
            attr.value !='false' &&
            attr.value !='inherit' &&
            (attr.value !='0' || attr.name =='value') &&
            attr.name !='loop' &&
            attr.name !='complete' &&
            attr.name !='maxLength' &&
            attr.name !='size' &&
            attr.name !='class' &&
            attr.name !='start' &&
            attr.name !='tabIndex' &&
            attr.name !='style' &&
            attr.name.substr(0, 6) != 'jQuery') {
          // in IE we need to check for all of these.
          if (!/ng-\d+/.exec(attr.name) &&
              attr.name != 'getElementById' &&
              // IE7 has `selected` in attributes
              attr.name !='selected' &&
              // IE7 adds `value` attribute to all LI tags
              (node.nodeName != 'LI' || attr.name != 'value'))
            attrs.push(' ' + attr.name + '="' + attr.value + '"');
        }
      }
      attrs.sort();
      html += attrs.join('');
      if (node.style) {
        var style = [];
        if (node.style.cssText) {
          forEach(node.style.cssText.split(';'), function(value){
            value = trim(value);
            if (value) {
              style.push(lowercase(value));
            }
          });
        }
        for(var css in node.style){
          var value = node.style[css];
          if (isString(value) && isString(css) && css != 'cssText' && value && (1*css != css)) {
            var text = lowercase(css + ': ' + value);
            if (value != 'false' && indexOf(style, text) == -1) {
              style.push(text);
            }
          }
        }
        style.sort();
        var tmp = style;
        style = [];
        forEach(tmp, function(value){
          if (!value.match(/^max[^\-]/))
            style.push(value);
        });
        if (style.length) {
          html += ' style="' + style.join('; ') + ';"';
        }
      }
      html += '>';
      var children = node.childNodes;
      for(var j=0; j<children.length; j++) {
        toString(children[j]);
      }
      html += '</' + node.nodeName.toLowerCase() + '>';
    }
  });
  return html;
}

function isCssVisible(node) {
  var display = node.css('display');
  if (display == 'block') display = "";
  return display != 'none';
}

function assertHidden(node) {
  assertFalse("Node should be hidden but vas visible: " + sortedHtml(node), isCssVisible(node));
}

function assertVisible(node) {
  assertTrue("Node should be visible but vas hidden: " + sortedHtml(node), isCssVisible(node));
}

function assertJsonEquals(expected, actual) {
  assertEquals(toJson(expected), toJson(actual));
}

function assertUndefined(value) {
  assertEquals('undefined', typeof value);
}

function assertDefined(value) {
  assertTrue(toJson(value), !!value);
}

function assertThrows(error, fn){
  var exception = null;
  try {
    fn();
  } catch(e) {
    exception = e;
  }
  if (!exception) {
    fail("Expecting exception, none thrown");
  }
  assertEquals(error, exception);
}

log = noop;
error = noop;

function rethrow(e) {
  if(e) {
    throw e;
  }
}
<|endoftext|>


<commit_before>!function(){"use strict"
function t(t,n,i){this.oldValues=t,this.newValues=n,this.data=i}function n(t,n,i,e,a,o){this._finished=!1,this._startTime=null,this._duration=t,this._easing=n||r,this._onComplete=i,this._chart=e,this._values=a,this._keys=o}function i(){this._animating=!1,this._animations=[],this._onBeforeFrames=[],this._onAfterFrames=[]}function e(t,n,i){return t*(i-n)+n}function r(t){var n=1-t
return n*=n*n*n,1-n}function a(t){return t!==t}function o(t,n){for(var i=t.length,e=0;i>e;++e)n(t[e])}function s(t,n){for(var i=t.length,e=Array(i),r=0;i>r;++r)e[r]=n(t[r])
return e}function u(t,n){for(var i=0;i<t.length;++i)if(t[i]===n)return
t.push(n)}function l(t,n,i){n[i]||(n[i]=!0,t.push(i))}function h(t,n,i,e){o(e,function(e){var r=i[e]
null!=r&&l(t,n,r)})}function f(t,n,i){h(n,i,t,["alphaField","valueField"])}function c(t,n,i){f(t,n,i)}function _(t,n,i){f(t,n,i),h(n,i,t,["labelRadiusField"])}function d(t,n,i){h(n,i,t,["alphaField","bulletSizeField","closeField","dashLengthField","errorField","highField","lowField","openField","valueField"])}function p(t,n,i){o(t,function(t){d(t,n,i)})}function m(t,n,i){h(n,i,t,["widthField"])}function v(t){var n=[],i={}
return"funnel"===t.type?c(t,n,i):"pie"===t.type?_(t,n,i):"serial"===t.type?(m(t.categoryAxis,n,i),p(t.graphs,n,i)):"radar"===t.type&&p(t.graphs,n,i),n}function F(t){return"funnel"===t.type||"pie"===t.type?t.titleField:"serial"===t.type||"radar"===t.type?t.categoryField:void 0}function g(t){return null==t?null:(t=+t,a(t)?null:t)}function y(t,n){return s(n,function(n){return g(t[n])})}function A(t){return""+t}function w(i,e){var r=this,a=F(r),s=v(r),u={},l=[]
o(r.dataProvider,function(t){var n=A(t[a])
u[n]=t}),o(i,function(n){var i=A(n[a])
if(i in u){var e=y(u[i],s),r=y(n,s)
l.push(new t(e,r,n))}}),r.dataProvider=i
var h=new n(e.duration,e.easing,e.complete,r,l,s)
return C.animate(h),h}if("undefined"==typeof requestAnimationFrame)var T=1e3/60,k=function(t){setTimeout(function(){t._onFrame((new Date).getTime())},T)}
else var k=function(t){requestAnimationFrame(function(n){t._onFrame(n)})}
n.prototype.cancel=function(){this._finished=!0,this._startTime=null,this._duration=null,this._easing=null,this._onComplete=null,this._chart=null,this._values=null,this._keys=null},n.prototype._onFrame=function(t){if(this._finished)return!0
if(null===this._startTime)return this._startTime=t,!1
var n=t-this._startTime
return n<this._duration?(this._tick(n/this._duration),!1):(this._end(1),this.cancel(),!0)},n.prototype._tick=function(t){t=this._easing(t)
for(var n=this._values,i=this._keys,r=0;r<n.length;++r)for(var a=n[r],o=a.oldValues,s=a.newValues,l=a.data,h=0;h<i.length;++h){var f=i[h],c=o[h],_=s[h]
null!=c&&null!=_&&(l[f]=e(t,c,_))}u(B,this._chart)},n.prototype._end=function(t){this._tick(t),null!=this._onComplete&&this._onComplete()},i.prototype.animate=function(t){this._animations.push(t),this._animating||(this._animating=!0,k(this))},i.prototype.onBeforeFrame=function(t){this._onBeforeFrames.push(t)},i.prototype.onAfterFrame=function(t){this._onAfterFrames.push(t)},i.prototype._onFrame=function(t){for(var n=this._onBeforeFrames,i=0;i<n.length;++i)n[i](t)
for(var e=this._animations,i=0;i<e.length;++i){var r=e[i]
r._onFrame(t)&&(e.splice(i,1),--i)}for(var a=this._onAfterFrames,i=0;i<a.length;++i)a[i](t)
0===e.length?this._animating=!1:k(this)}
var C=new i,B=[]
C.onAfterFrame(function(){for(var t=0;t<B.length;++t)B[t].validateData()
B.length=0}),AmCharts.addInitHandler(function(t){t.animateData=w},["funnel","pie","serial","radar"])}()
<commit_msg>animateData: Updating minified file<commit_after>!function(){"use strict"
function t(t,n,i){return t*(i-n)+n}function n(t){var n=1-t
return n*=n*n*n,1-n}function i(t,n,i,e){this._object=t,this._key=n,this._from=i,this._to=e}function e(t,i,e,r,o){this._finished=!1,this._startTime=null,this._duration=t,this._easing=null==i?n:i,this._onComplete=e,this._tweens=r,this._chart=o}function r(){this._animating=!1,this._animations=[],this._onBeforeFrames=[],this._onAfterFrames=[]}function o(t){return t!==t}function a(t,n){for(var i=0;i<t.length;++i)n(t[i])}function u(t,n){for(var i=0;i<t.length;++i)if(t[i]===n)return
t.push(n)}function s(t,n,i){n[i]||(n[i]=!0,t.push(i))}function l(t,n,i,e){a(e,function(e){var r=i[e]
null!=r&&s(t,n,r)})}function h(t,n,i){l(n,i,t,["alphaField","valueField"])}function f(t,n,i){h(t,n,i)}function c(t,n,i){h(t,n,i),l(n,i,t,["labelRadiusField"])}function _(t,n,i){l(n,i,t,["alphaField","bulletSizeField","closeField","dashLengthField","errorField","highField","lowField","openField","valueField"])}function p(t,n,i){a(t,function(t){_(t,n,i)})}function m(t,n,i){l(n,i,t,["widthField"])}function d(t){var n=[],i={}
return"funnel"===t.type?f(t,n,i):"pie"===t.type?c(t,n,i):"serial"===t.type?(m(t.categoryAxis,n,i),p(t.graphs,n,i)):"radar"===t.type&&p(t.graphs,n,i),n}function v(t){return"funnel"===t.type||"pie"===t.type?t.titleField:"serial"===t.type||"radar"===t.type?t.categoryField:void 0}function F(t,n){var i=t[n]
return null==i?null:(i=+i,o(i)?null:i)}function g(t,n){var i=t[n]
return null==i?null:""+i}function y(t,n){var i={}
return a(t,function(t){var e=g(t,n)
null!=e&&(i[e]=t)}),i}function w(t,n,e,r){var o=[]
return a(t,function(t){var u=g(t,n)
if(null!=u&&u in e){var s=e[u]
a(r,function(n){var e=F(s,n),r=F(t,n)
null!=e&&null!=r&&o.push(new i(t,n,e,r))})}}),o}function A(t,n){var i=this,r=v(i),o=d(i),a=y(i.dataProvider,r),u=w(t,r,a,o)
i.dataProvider=t
var s=new e(n.duration,n.easing,n.complete,u,i)
return C.animate(s),s}if("undefined"==typeof requestAnimationFrame)var T=1e3/60,k=function(t){setTimeout(function(){t._onFrame((new Date).getTime())},T)}
else var k=function(t){requestAnimationFrame(function(n){t._onFrame(n)})}
i.prototype.interpolate=function(n){this._object[this._key]=t(n,this._from,this._to)},e.prototype.cancel=function(){this._finished=!0,this._startTime=null,this._duration=null,this._easing=null,this._onComplete=null,this._tweens=null,this._chart=null},e.prototype._onFrame=function(t){if(this._finished)return!0
if(null===this._startTime)return this._startTime=t,!1
var n=t-this._startTime
return n<this._duration?(this._tick(n/this._duration),!1):(this._end(1),this.cancel(),!0)},e.prototype._tick=function(t){t=this._easing(t)
for(var n=this._tweens,i=0;i<n.length;++i)n[i].interpolate(t)
u(b,this._chart)},e.prototype._end=function(t){this._tick(t),null!=this._onComplete&&this._onComplete()},r.prototype.animate=function(t){this._animations.push(t),this._animating||(this._animating=!0,k(this))},r.prototype.onBeforeFrame=function(t){this._onBeforeFrames.push(t)},r.prototype.onAfterFrame=function(t){this._onAfterFrames.push(t)},r.prototype._onFrame=function(t){for(var n=this._onBeforeFrames,i=0;i<n.length;++i)n[i](t)
for(var e=this._animations,i=0;i<e.length;++i){var r=e[i]
r._onFrame(t)&&(e.splice(i,1),--i)}for(var o=this._onAfterFrames,i=0;i<o.length;++i)o[i](t)
0===e.length?this._animating=!1:k(this)}
var C=new r,b=[]
C.onAfterFrame(function(){for(var t=0;t<b.length;++t)b[t].validateData()
b.length=0}),AmCharts.addInitHandler(function(t){t.animateData=A},["funnel","pie","serial","radar"])}()
<|endoftext|>


<commit_before>"use strict"; // run code in ES5 strict mode

var fs = require("fs"),
    path = require("path"),
    EventEmitter = require("events").EventEmitter,
    webpack = require("webpack"),
    formatOutput = require("webpack/lib/formatOutput"),
    webpackMiddleware = require("webpack-dev-middleware"),
    fshelpers = require("fshelpers"),
    resolveFilename = require("./resolveFilename.js"),
    renderBootstrapClient = require("./renderer/renderBootstrapClient.js"),
    logger = require("../../shared/logger.js").get("bundle"),
    env = require("../../shared/env.js");

/**
 * get the Webpack Options to work with alamid
 * pass config (paths.root, paths.bundle, isDev have to be defined)
 *
 * @param {!Object} config
 * @return {Object}
 */
function getWebpackOptions(config) {

    var paths = config.paths,
        isDev = env.isDevelopment() || env.isTesting();

    return {
        output: paths.bundle + "/app.js",
        publicPrefix: "/",
        context: paths.root,
        includeFilenames: isDev,
        debug: isDev,
        minimize : !isDev,
        extensions: ["", ".client.js", ".js"],
        profile: true,
        resolve: {
            loaders: [
                { test: /\.html$/i, loader: "raw" }
            ],
            postprocess: {
                normal: [resolveFilename]
            }
        },
        alamidConfig: config
    };
}

/**
 * Create a bundle containing the client
 * pass config (paths.root, paths.bundle, isDev have to be defined)
 * @param {!Object} config
 */
function createBundle(config) {

    var paths = config.paths,
        bundleFolder = paths.bundle,
        bootstrapPath = path.join(__dirname, "bootstrap.client.loader.js") + "!" + bundleFolder + "/index.html";

    var webpackEvents = new EventEmitter();

    var webpackOptions = getWebpackOptions(config);

    //additional settings
    webpackOptions.events = webpackEvents;

    webpack(bootstrapPath, webpackOptions, function onWebpackFinished(err, stats) {

        logger.debug("\n" +
            formatOutput(stats, {
                    colors: true,
                    context: webpackOptions.context
                }
            ));

        if (stats.errors.length === 0) {
            logger.info("Bundle created in " + stats.time/1000 + "s");
        } else {
            logger.error("Bundle creation failed ...");
            throw stats.errors[0];
        }
    });
}

/**
 * get the serveBundleMiddleware to be used with the router
 * this function initializes the bundler and returns the actual middleware-function
 *
 * @param {!options} config
 * @return {Function} webpackMiddleware
 */
function initServeBundleMiddleware(config) {

    var middlewareEvents = new EventEmitter(),
        webpackOptions = getWebpackOptions(config),
        paths = config.paths,
        bundleFolder = paths.bundle,
        bootstrapPath = path.join(__dirname, "bootstrap.client.loader.js") + "!" + bundleFolder + "/index.html";

    middlewareEvents.on("bundle-invalid", function() {
        logger.debug("App change detected. Updating bundle.");
    });

    middlewareEvents.on("bundle",function onBundleReady(stats) {

        logger.debug("Bundle ready." + "\n" +
            formatOutput(stats, {
                    colors: true,
                    context: webpackOptions.context
                }
            ));
    });

    webpackOptions.events = middlewareEvents;
    //we enable watch mode for the dev server
    //per request re-bundling can be enabled by setting "watch : false"
    webpackOptions.watch = true;

    return webpackMiddleware(__dirname, bootstrapPath, {
        quiet: true,
        context: webpackOptions.context,
        webpack: webpackOptions
    });
}

exports.getWebpackOptions = getWebpackOptions;
exports.createBundle = createBundle;
exports.initServeBundleMiddleware = initServeBundleMiddleware;

<commit_msg>- using core-logger now<commit_after>"use strict"; // run code in ES5 strict mode

var fs = require("fs"),
    path = require("path"),
    EventEmitter = require("events").EventEmitter,
    webpack = require("webpack"),
    formatOutput = require("webpack/lib/formatOutput"),
    webpackMiddleware = require("webpack-dev-middleware"),
    fshelpers = require("fshelpers"),
    resolveFilename = require("./resolveFilename.js"),
    renderBootstrapClient = require("./renderer/renderBootstrapClient.js"),
    logger = require("../../shared/logger.js").get("core"),
    env = require("../../shared/env.js");

/**
 * get the Webpack Options to work with alamid
 * pass config (paths.root, paths.bundle, isDev have to be defined)
 *
 * @param {!Object} config
 * @return {Object}
 */
function getWebpackOptions(config) {

    var paths = config.paths,
        isDev = env.isDevelopment() || env.isTesting();

    return {
        output: paths.bundle + "/app.js",
        publicPrefix: "/",
        context: paths.root,
        includeFilenames: isDev,
        debug: isDev,
        minimize : !isDev,
        extensions: ["", ".client.js", ".js"],
        profile: true,
        resolve: {
            loaders: [
                { test: /\.html$/i, loader: "raw" }
            ],
            postprocess: {
                normal: [resolveFilename]
            }
        },
        alamidConfig: config
    };
}

/**
 * Create a bundle containing the client
 * pass config (paths.root, paths.bundle, isDev have to be defined)
 * @param {!Object} config
 */
function createBundle(config) {

    var paths = config.paths,
        bundleFolder = paths.bundle,
        bootstrapPath = path.join(__dirname, "bootstrap.client.loader.js") + "!" + bundleFolder + "/index.html";

    var webpackEvents = new EventEmitter();

    var webpackOptions = getWebpackOptions(config);

    //additional settings
    webpackOptions.events = webpackEvents;

    webpack(bootstrapPath, webpackOptions, function onWebpackFinished(err, stats) {

        logger.debug("\n" +
            formatOutput(stats, {
                    colors: true,
                    context: webpackOptions.context
                }
            ));

        if (stats.errors.length === 0) {
            logger.info("Bundle created in " + stats.time/1000 + "s");
        } else {
            logger.error("Bundle creation failed ...");
            throw stats.errors[0];
        }
    });
}

/**
 * get the serveBundleMiddleware to be used with the router
 * this function initializes the bundler and returns the actual middleware-function
 *
 * @param {!options} config
 * @return {Function} webpackMiddleware
 */
function initServeBundleMiddleware(config) {

    var middlewareEvents = new EventEmitter(),
        webpackOptions = getWebpackOptions(config),
        paths = config.paths,
        bundleFolder = paths.bundle,
        bootstrapPath = path.join(__dirname, "bootstrap.client.loader.js") + "!" + bundleFolder + "/index.html";

    middlewareEvents.on("bundle-invalid", function() {
        logger.debug("App change detected. Updating bundle.");
    });

    middlewareEvents.on("bundle",function onBundleReady(stats) {

        logger.debug("Bundle ready." + "\n" +
            formatOutput(stats, {
                    colors: true,
                    context: webpackOptions.context
                }
            ));
    });

    webpackOptions.events = middlewareEvents;
    //we enable watch mode for the dev server
    //per request re-bundling can be enabled by setting "watch : false"
    webpackOptions.watch = true;

    return webpackMiddleware(__dirname, bootstrapPath, {
        quiet: true,
        context: webpackOptions.context,
        webpack: webpackOptions
    });
}

exports.getWebpackOptions = getWebpackOptions;
exports.createBundle = createBundle;
exports.initServeBundleMiddleware = initServeBundleMiddleware;

<|endoftext|>


<commit_before>/**
 * @module
 * @author Massimiliano Izzo
 * @description this handler works as a context for the transaction strategy
 *
 */
/*jshint node: true */
/*jshint esnext: true */
"use strict";

let PgKnexCrudStrategy = require("./PgCrudStrategies.js").PgKnexCrudStrategy;

/**
 * @class
 * @name PgCrudManager
 */
class PgCrudManager {

    /**
     * @constructor
     */
    constructor(strategy, connection, fileSystemConnection) {
        if (!strategy) {
            strategy = new PgKnexCrudStrategy(connection, fileSystemConnection);
        }
        this.strategy = strategy;
    }

    /**
     * @method
     */
    get strategy() {
        return this._strategy();
    }

    /**
     * @method
     */
    set strategy(strategy) {
        if (strategy) {
            this._strategy = strategy;
        }
    }

    createDataType(dataType) {
        return this.strategy.createDataType(dataType);
    }

    updateDataType(dataType) {
        return this.strategy.updateDataType(dataType);
    }

    createData(data, dataTypeName) {
        return this.strategy.createData(data, dataTypeName);
    }

    updateData(data) {
        return this.strategy.updateData(data);
    }

    createSample(sample, sampleTypeName) {
        return this.strategy.createSample(sample, sampleTypeName);
    }

    updateSample(sample) {
        return this.strategy.updateSample(sample);
    }

    createSubject(subject, subjectTypeName) {
        return this.strategy.createSubject(subject, subjectTypeName);
    }

    updateSubject(subject) {
        return this.strategy.updateSubject(subject);
    }

    putMetadataFieldsIntoEAV(idDataType, metadataField) {
        return this.strategy.putMetadataFieldsIntoEAV(idDataType, metadataField);
    }

    putMetadataValuesIntoEAV(data, eavValueTableMap) {
        console.log("CrudManager.putMetadataValuesIntoEAV - here we are! " + data.id);
        return this.strategy.putMetadataValuesIntoEAV(data, eavValueTableMap);
    }

    /**
     * @method
     * @name query
     * @param{String} statement - the prepared/parametrized statement
     * @param{Array} params - the parameters array
     * @return{Promise} a promise with args an array with retrieved items
     */
    query(statement, params) {
        return this.strategy.query(statement, params);
    }
}

module.exports = PgCrudManager;
<commit_msg>fixed error con crud manager query getter<commit_after>/**
 * @module
 * @author Massimiliano Izzo
 * @description this handler works as a context for the transaction strategy
 *
 */
/*jshint node: true */
/*jshint esnext: true */
"use strict";

let PgKnexCrudStrategy = require("./PgCrudStrategies.js").PgKnexCrudStrategy;

/**
 * @class
 * @name PgCrudManager
 */
class PgCrudManager {

    /**
     * @constructor
     */
    constructor(strategy, connection, fileSystemConnection) {
        if (!strategy) {
            strategy = new PgKnexCrudStrategy(connection, fileSystemConnection);
        }
        this.strategy = strategy;
    }

    /**
     * @method
     */
    get strategy() {
        return this._strategy;
    }

    /**
     * @method
     */
    set strategy(strategy) {
        if (strategy) {
            this._strategy = strategy;
        }
    }

    createDataType(dataType) {
        return this.strategy.createDataType(dataType);
    }

    updateDataType(dataType) {
        return this.strategy.updateDataType(dataType);
    }

    createData(data, dataTypeName) {
        return this.strategy.createData(data, dataTypeName);
    }

    updateData(data) {
        return this.strategy.updateData(data);
    }

    createSample(sample, sampleTypeName) {
        return this.strategy.createSample(sample, sampleTypeName);
    }

    updateSample(sample) {
        return this.strategy.updateSample(sample);
    }

    createSubject(subject, subjectTypeName) {
        return this.strategy.createSubject(subject, subjectTypeName);
    }

    updateSubject(subject) {
        return this.strategy.updateSubject(subject);
    }

    putMetadataFieldsIntoEAV(idDataType, metadataField) {
        return this.strategy.putMetadataFieldsIntoEAV(idDataType, metadataField);
    }

    putMetadataValuesIntoEAV(data, eavValueTableMap) {
        console.log("CrudManager.putMetadataValuesIntoEAV - here we are! " + data.id);
        return this.strategy.putMetadataValuesIntoEAV(data, eavValueTableMap);
    }

    /**
     * @method
     * @name query
     * @param{String} statement - the prepared/parametrized statement
     * @param{Array} params - the parameters array
     * @return{Promise} a promise with args an array with retrieved items
     */
    query(statement, params) {
        return this.strategy.query(statement, params);
    }
}

module.exports = PgCrudManager;
<|endoftext|>


<commit_before>import axios from "axios";

/**
 * @file API for handling activities
 */

const BASE_URL = `/ajax/activities`;

/**
 * Get a page of activities for a project
 *
 * @param {number} projectId - current project identifier
 * @param {number} page - page of activities requested
 * @returns {Promise<AxiosResponse<any>>}
 */
export function getProjectActivities({ projectId, page = 0 }) {
  try {
    return axios
      .get(`${BASE_URL}/project?projectId=${projectId}&page=${page}`)
      .then(({ data }) => data);
  } catch (e) {
    return Promise.reject(i18n("ProjectActivity.error"));
  }
}

/**
 * Get a page of recent activities for all of user's projects
 *
 * @param {number} page - page of activities requested
 * @returns {Promise<AxiosResponse<any>>}
 */
export function getUserActivities({ page = 0 }) {
  try {
    return axios.get(`${BASE_URL}/user?page=${page}`).then(({ data }) => data);
  } catch (e) {
    return Promise.reject(i18n("RecentActivity.loadError"));
  }
}

/**
 * Get a page of recent activities for all projects
 *
 * @param {number} page - page of activities requested
 * @returns {Promise<AxiosResponse<any>>}
 */
export function getAllRecentActivities({ page = 0 }) {
  try {
    return axios.get(`${BASE_URL}/all?page=${page}`).then(({ data }) => data);
  } catch (e) {
    return Promise.reject(i18n("RecentActivity.loadError"));
  }
}
<commit_msg>Fixed base url for activities.js<commit_after>import axios from "axios";
import { setBaseUrl } from "../../utilities/url-utilities";

/**
 * @file API for handling activities
 */

const BASE_URL = setBaseUrl(`/ajax/activities`);

/**
 * Get a page of activities for a project
 *
 * @param {number} projectId - current project identifier
 * @param {number} page - page of activities requested
 * @returns {Promise<AxiosResponse<any>>}
 */
export function getProjectActivities({ projectId, page = 0 }) {
  try {
    return axios
      .get(`${BASE_URL}/project?projectId=${projectId}&page=${page}`)
      .then(({ data }) => data);
  } catch (e) {
    return Promise.reject(i18n("ProjectActivity.error"));
  }
}

/**
 * Get a page of recent activities for all of user's projects
 *
 * @param {number} page - page of activities requested
 * @returns {Promise<AxiosResponse<any>>}
 */
export function getUserActivities({ page = 0 }) {
  try {
    return axios.get(`${BASE_URL}/user?page=${page}`).then(({ data }) => data);
  } catch (e) {
    return Promise.reject(i18n("RecentActivity.loadError"));
  }
}

/**
 * Get a page of recent activities for all projects
 *
 * @param {number} page - page of activities requested
 * @returns {Promise<AxiosResponse<any>>}
 */
export function getAllRecentActivities({ page = 0 }) {
  try {
    return axios.get(`${BASE_URL}/all?page=${page}`).then(({ data }) => data);
  } catch (e) {
    return Promise.reject(i18n("RecentActivity.loadError"));
  }
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// 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.
//
////////////////////////////////////////////////////////////////////////////

/**
 * A Realm instance represents a Realm database.
 * ```js
 * const Realm = require('realm');
 * ```
 */
class Realm {
    /**
     * The path to the file where this Realm is stored.
     * @type {string}
     * @readonly
     * @since 0.12.0
     */
    get path() {}

    /**
     * Indicates if this Realm was opened as read-only.
     * @type {boolean}
     * @readonly
     * @since 0.12.0
     */
    get readOnly() {}

    /**
     * A normalized representation of the schema provided in the
     * {@link Realm~Configuration Configuration} when this Realm was constructed.
     * @type {Realm~ObjectSchema[]}
     * @readonly
     * @since 0.12.0
     */
    get schema() {}

   /**
    * The current schema version of this Realm.
    * @type {number}
    * @readonly
    * @since 0.12.0
    */
    get schemaVersion() {}

    /**
     * Gets the sync session if this is a synced Realm
     * @type {Session}
     */
    get syncSession() {}

    /**
     * Create a new `Realm` instance using the provided `config`. If a Realm does not yet exist
     * at `config.path` (or {@link Realm.defaultPath} if not provided), then this constructor
     * will create it with the provided `config.schema` (which is _required_ in this case).
     * Otherwise, the instance will access the existing Realm from the file at that path.
     * In this case, `config.schema` is _optional_ or not have changed, unless
     * `config.schemaVersion` is incremented, in which case the Realm will be automatically
     * migrated to use the new schema.
     * @param {Realm~Configuration} [config] - **Required** when first creating the Realm.
     * @throws {Error} If anything in the provided `config` is invalid.
     */
    constructor(config) {}

    /**
     * Open a realm asynchronously with a promise. If the realm is synced, it will be fully
     * synchronized before it is available.
     * @param {Realm~Configuration} config
     * @param {function(error, realm)} callback - will be called when the realm is ready.
     * @returns {Promise} - a promise that will be resolved with the realm instance when it's available.
     * @throws {Error} If anything in the provided `config` is invalid.
     */
    static open(config) {}

    /**
     * Open a realm asynchronously with a callback. If the realm is synced, it will be fully
     * synchronized before it is available.
     * @param {Realm~Configuration} config
     * @param {function(error, realm)} callback - will be called when the realm is ready.
     * @throws {Error} If anything in the provided `config` is invalid.
     */
    static openAsync(config, callback) {}

    /**
     * Closes this Realm so it may be re-opened with a newer schema version.
     * All objects and collections from this Realm are no longer valid after calling this method.
     */
    close() {}

    /**
     * Create a new Realm object of the given type and with the specified properties.
     * @param {Realm~ObjectType} type - The type of Realm object to create.
     * @param {Object} properties - Property values for all required properties without a
     *   default value.
     * @param {boolean} [update=false] - Signals that an existing object with matching primary key
     *   should be updated. Only the primary key property and properties which should be updated
     *   need to be specified. All missing property values will remain unchanged.
     * @returns {Realm.Object}
     */
    create(type, properties, update) {}

    /**
     * Deletes the provided Realm object, or each one inside the provided collection.
     * @param {Realm.Object|Realm.Object[]|Realm.List|Realm.Results} object
     */
    delete(object) {}

    /**
     * **WARNING:** This will delete **all** objects in the Realm!
     */
    deleteAll() {}

    /**
     * Returns all objects of the given `type` in the Realm.
     * @param {Realm~ObjectType} type - The type of Realm objects to retrieve.
     * @throws {Error} If type passed into this method is invalid.
     * @returns {Realm.Results} that will live-update as objects are created and destroyed.
     */
    objects(type) {}

    /**
     * Searches for a Realm object by its primary key.
     * @param {Realm~ObjectType} type - The type of Realm object to search for.
     * @param {number|string} key - The primary key value of the object to search for.
     * @throws {Error} If type passed into this method is invalid or if the object type did
     *   not have a `primaryKey` specified in its {@link Realm~ObjectSchema ObjectSchema}.
     * @returns {Realm.Object|undefined} if no object is found.
     * @since 0.14.0
     */
    objectForPrimaryKey(type, key) {}

    /**
     * Add a listener `callback` for the specified event `name`.
     * @param {string} name - The name of event that should cause the callback to be called.
     *   _Currently, only the "change" event supported_.
     * @param {function(Realm, string)} callback - Function to be called when the event occurs.
     *   Each callback will only be called once per event, regardless of the number of times
     *   it was added.
     * @throws {Error} If an invalid event `name` is supplied, or if `callback` is not a function.
     */
    addListener(name, callback) {}

   /**
    * Remove the listener `callback` for the specfied event `name`.
    * @param {string} name - The event name.
    *   _Currently, only the "change" event supported_.
    * @param {function(Realm, string)} callback - Function that was previously added as a
    *   listener for this event through the {@link Realm#addListener addListener} method.
    * @throws {Error} If an invalid event `name` is supplied, or if `callback` is not a function.
    */
    removeListener(name, callback) {}

   /**
    * Remove all event listeners (restricted to the event `name`, if provided).
    * @param {string} [name] - The name of the event whose listeners should be removed.
    *   _Currently, only the "change" event supported_.
    * @throws {Error} When invalid event `name` is supplied
    */
    removeAllListeners(name) {}

   /**
    * Synchronously call the provided `callback` inside a write transaction.
    * @param {function()} callback
    */
    write(callback) {}
}

/**
 * Get the current schema version of the Realm at the given path.
 * @param {string} path - The path to the file where the
 *   Realm database is stored.
 * @param {ArrayBuffer|ArrayBufferView} [encryptionKey] - Required only when
 *   accessing encrypted Realms.
 * @throws {Error} When passing an invalid or non-matching encryption key.
 * @returns {number} version of the schema, or `-1` if no Realm exists at `path`.
 */
Realm.schemaVersion = function(path, encryptionKey) {};

/**
 * The default path where to create and access the Realm file.
 * @type {string}
 */
Realm.defaultPath;

/**
 * This describes the different options used to create a {@link Realm} instance.
 * @typedef Realm~Configuration
 * @type {Object}
 * @property {ArrayBuffer|ArrayBufferView} [encryptionKey] - The 512-bit (64-byte) encryption
 *   key used to encrypt and decrypt all data in the Realm.
 * @property {function(Realm, Realm)} [migration] - The function to run if a migration is needed.
 *   This function should provide all the logic for converting data models from previous schemas
 *   to the new schema.
 *   This function takes two arguments:
 *   - `oldRealm` - The Realm before migration is performed.
 *   - `newRealm` - The Realm that uses the latest `schema`, which should be modified as necessary.
 * @property {string} [path={@link Realm.defaultPath}] - The path to the file where the
 *   Realm database should be stored.
 * @property {boolean} [readOnly=false] - Specifies if this Realm should be opened as read-only.
 * @property {Array<Realm~ObjectClass|Realm~ObjectSchema>} [schema] - Specifies all the
 *   object types in this Realm. **Required** when first creating a Realm at this `path`.
 * @property {number} [schemaVersion] - **Required** (and must be incremented) after
 *   changing the `schema`.
 * @property {Object} [sync] - Sync configuration parameters with the following
 *   child properties:
 *   - `user` - A `User` object obtained by calling `Realm.Sync.User.login`
 *   - `url` - A `string` which contains a valid Realm Sync url
 */

/**
 * Realm objects will inherit methods, getters, and setters from the `prototype` of this
 * constructor. It is **highly recommended** that this constructor inherit from
 * {@link Realm.Object}.
 * @typedef Realm~ObjectClass
 * @type {Class}
 * @property {Realm~ObjectSchema} schema - Static property specifying object schema information.
 */

/**
 * @typedef Realm~ObjectSchema
 * @type {Object}
 * @property {string} name - Represents the object type.
 * @property {string} [primaryKey] - The name of a `"string"` or `"int"` property
 *   that must be unique across all objects of this type within the same Realm.
 * @property {Object<string, (Realm~PropertyType|Realm~ObjectSchemaProperty)>} properties -
 *   An object where the keys are property names and the values represent the property type.
 */

/**
 * @typedef Realm~ObjectSchemaProperty
 * @type {Object}
 * @property {Realm~PropertyType} type - The type of this property.
 * @property {string} [objectType] - **Required**  when `type` is `"list"`, and must match the
 *   type of an object in the same schema.
 * @property {any} [default] - The default value for this property on creation when not
 *   otherwise specified.
 * @property {boolean} [optional] - Signals if this property may be assigned `null` or `undefined`.
 * @property {boolean} [indexed] - Signals if this property should be indexed. Only supported for
 *   `"string"`, `"int"`, and `"bool"` properties.
 */

/**
 * The type of an object may either be specified as a string equal to the `name` in a
 * {@link Realm~ObjectSchema ObjectSchema} definition, **or** a constructor that was specified
 * in the {@link Realm~Configuration configuration} `schema`.
 * @typedef Realm~ObjectType
 * @type {string|Realm~ObjectClass}
 */

/**
 * A property type may be specified as one of the standard builtin types, or as an object type
 * inside the same schema.
 * @typedef Realm~PropertyType
 * @type {("bool"|"int"|"float"|"double"|"string"|"date"|"data"|"list"|"<ObjectType>")}
 * @property {boolean} "bool" - Property value may either be `true` or `false`.
 * @property {number} "int" - Property may be assigned any number, but will be stored as a
 *   round integer, meaning anything after the decimal will be truncated.
 * @property {number} "float" - Property may be assigned any number, but will be stored as a
 *   `float`, which may result in a loss of precision.
 * @property {number} "double" - Property may be assigned any number, and will have no loss
 *   of precision.
 * @property {string} "string" - Property value may be any arbitrary string.
 * @property {Date} "date" - Property may be assigned any `Date` instance.
 * @property {ArrayBuffer} "data" - Property may either be assigned an `ArrayBuffer`
 *   or `ArrayBufferView` (e.g. `DataView`, `Int8Array`, `Float32Array`, etc.) instance,
 *   but will always be returned as an `ArrayBuffer`.
 * @property {Realm.List} "list" - Property may be assigned any ordered collection
 *   (e.g. `Array`, {@link Realm.List}, {@link Realm.Results}) of objects all matching the
 *   `objectType` specified in the {@link Realm~ObjectSchemaProperty ObjectSchemaProperty}.
 * @property {Realm.Object} "<ObjectType>" - A string that matches the `name` of an object in the
 *   same schema (see {@link Realm~ObjectSchema ObjectSchema}) – this property may be assigned
 *   any object of this type from inside the same Realm, and will always be _optional_
 *   (meaning it may also be assigned `null` or `undefined`).
 */
<commit_msg>Fix doc mistake (#1028)<commit_after>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// 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.
//
////////////////////////////////////////////////////////////////////////////

/**
 * A Realm instance represents a Realm database.
 * ```js
 * const Realm = require('realm');
 * ```
 */
class Realm {
    /**
     * The path to the file where this Realm is stored.
     * @type {string}
     * @readonly
     * @since 0.12.0
     */
    get path() {}

    /**
     * Indicates if this Realm was opened as read-only.
     * @type {boolean}
     * @readonly
     * @since 0.12.0
     */
    get readOnly() {}

    /**
     * A normalized representation of the schema provided in the
     * {@link Realm~Configuration Configuration} when this Realm was constructed.
     * @type {Realm~ObjectSchema[]}
     * @readonly
     * @since 0.12.0
     */
    get schema() {}

   /**
    * The current schema version of this Realm.
    * @type {number}
    * @readonly
    * @since 0.12.0
    */
    get schemaVersion() {}

    /**
     * Gets the sync session if this is a synced Realm
     * @type {Session}
     */
    get syncSession() {}

    /**
     * Create a new `Realm` instance using the provided `config`. If a Realm does not yet exist
     * at `config.path` (or {@link Realm.defaultPath} if not provided), then this constructor
     * will create it with the provided `config.schema` (which is _required_ in this case).
     * Otherwise, the instance will access the existing Realm from the file at that path.
     * In this case, `config.schema` is _optional_ or not have changed, unless
     * `config.schemaVersion` is incremented, in which case the Realm will be automatically
     * migrated to use the new schema.
     * @param {Realm~Configuration} [config] - **Required** when first creating the Realm.
     * @throws {Error} If anything in the provided `config` is invalid.
     */
    constructor(config) {}

    /**
     * Open a realm asynchronously with a promise. If the realm is synced, it will be fully
     * synchronized before it is available.
     * @param {Realm~Configuration} config
     * @returns {Promise} - a promise that will be resolved with the realm instance when it's available.
     */
    static open(config) {}

    /**
     * Open a realm asynchronously with a callback. If the realm is synced, it will be fully
     * synchronized before it is available.
     * @param {Realm~Configuration} config
     * @param {function(error, realm)} callback - will be called when the realm is ready.
     * @throws {Error} If anything in the provided `config` is invalid.
     */
    static openAsync(config, callback) {}

    /**
     * Closes this Realm so it may be re-opened with a newer schema version.
     * All objects and collections from this Realm are no longer valid after calling this method.
     */
    close() {}

    /**
     * Create a new Realm object of the given type and with the specified properties.
     * @param {Realm~ObjectType} type - The type of Realm object to create.
     * @param {Object} properties - Property values for all required properties without a
     *   default value.
     * @param {boolean} [update=false] - Signals that an existing object with matching primary key
     *   should be updated. Only the primary key property and properties which should be updated
     *   need to be specified. All missing property values will remain unchanged.
     * @returns {Realm.Object}
     */
    create(type, properties, update) {}

    /**
     * Deletes the provided Realm object, or each one inside the provided collection.
     * @param {Realm.Object|Realm.Object[]|Realm.List|Realm.Results} object
     */
    delete(object) {}

    /**
     * **WARNING:** This will delete **all** objects in the Realm!
     */
    deleteAll() {}

    /**
     * Returns all objects of the given `type` in the Realm.
     * @param {Realm~ObjectType} type - The type of Realm objects to retrieve.
     * @throws {Error} If type passed into this method is invalid.
     * @returns {Realm.Results} that will live-update as objects are created and destroyed.
     */
    objects(type) {}

    /**
     * Searches for a Realm object by its primary key.
     * @param {Realm~ObjectType} type - The type of Realm object to search for.
     * @param {number|string} key - The primary key value of the object to search for.
     * @throws {Error} If type passed into this method is invalid or if the object type did
     *   not have a `primaryKey` specified in its {@link Realm~ObjectSchema ObjectSchema}.
     * @returns {Realm.Object|undefined} if no object is found.
     * @since 0.14.0
     */
    objectForPrimaryKey(type, key) {}

    /**
     * Add a listener `callback` for the specified event `name`.
     * @param {string} name - The name of event that should cause the callback to be called.
     *   _Currently, only the "change" event supported_.
     * @param {function(Realm, string)} callback - Function to be called when the event occurs.
     *   Each callback will only be called once per event, regardless of the number of times
     *   it was added.
     * @throws {Error} If an invalid event `name` is supplied, or if `callback` is not a function.
     */
    addListener(name, callback) {}

   /**
    * Remove the listener `callback` for the specfied event `name`.
    * @param {string} name - The event name.
    *   _Currently, only the "change" event supported_.
    * @param {function(Realm, string)} callback - Function that was previously added as a
    *   listener for this event through the {@link Realm#addListener addListener} method.
    * @throws {Error} If an invalid event `name` is supplied, or if `callback` is not a function.
    */
    removeListener(name, callback) {}

   /**
    * Remove all event listeners (restricted to the event `name`, if provided).
    * @param {string} [name] - The name of the event whose listeners should be removed.
    *   _Currently, only the "change" event supported_.
    * @throws {Error} When invalid event `name` is supplied
    */
    removeAllListeners(name) {}

   /**
    * Synchronously call the provided `callback` inside a write transaction.
    * @param {function()} callback
    */
    write(callback) {}
}

/**
 * Get the current schema version of the Realm at the given path.
 * @param {string} path - The path to the file where the
 *   Realm database is stored.
 * @param {ArrayBuffer|ArrayBufferView} [encryptionKey] - Required only when
 *   accessing encrypted Realms.
 * @throws {Error} When passing an invalid or non-matching encryption key.
 * @returns {number} version of the schema, or `-1` if no Realm exists at `path`.
 */
Realm.schemaVersion = function(path, encryptionKey) {};

/**
 * The default path where to create and access the Realm file.
 * @type {string}
 */
Realm.defaultPath;

/**
 * This describes the different options used to create a {@link Realm} instance.
 * @typedef Realm~Configuration
 * @type {Object}
 * @property {ArrayBuffer|ArrayBufferView} [encryptionKey] - The 512-bit (64-byte) encryption
 *   key used to encrypt and decrypt all data in the Realm.
 * @property {function(Realm, Realm)} [migration] - The function to run if a migration is needed.
 *   This function should provide all the logic for converting data models from previous schemas
 *   to the new schema.
 *   This function takes two arguments:
 *   - `oldRealm` - The Realm before migration is performed.
 *   - `newRealm` - The Realm that uses the latest `schema`, which should be modified as necessary.
 * @property {string} [path={@link Realm.defaultPath}] - The path to the file where the
 *   Realm database should be stored.
 * @property {boolean} [readOnly=false] - Specifies if this Realm should be opened as read-only.
 * @property {Array<Realm~ObjectClass|Realm~ObjectSchema>} [schema] - Specifies all the
 *   object types in this Realm. **Required** when first creating a Realm at this `path`.
 * @property {number} [schemaVersion] - **Required** (and must be incremented) after
 *   changing the `schema`.
 * @property {Object} [sync] - Sync configuration parameters with the following
 *   child properties:
 *   - `user` - A `User` object obtained by calling `Realm.Sync.User.login`
 *   - `url` - A `string` which contains a valid Realm Sync url
 */

/**
 * Realm objects will inherit methods, getters, and setters from the `prototype` of this
 * constructor. It is **highly recommended** that this constructor inherit from
 * {@link Realm.Object}.
 * @typedef Realm~ObjectClass
 * @type {Class}
 * @property {Realm~ObjectSchema} schema - Static property specifying object schema information.
 */

/**
 * @typedef Realm~ObjectSchema
 * @type {Object}
 * @property {string} name - Represents the object type.
 * @property {string} [primaryKey] - The name of a `"string"` or `"int"` property
 *   that must be unique across all objects of this type within the same Realm.
 * @property {Object<string, (Realm~PropertyType|Realm~ObjectSchemaProperty)>} properties -
 *   An object where the keys are property names and the values represent the property type.
 */

/**
 * @typedef Realm~ObjectSchemaProperty
 * @type {Object}
 * @property {Realm~PropertyType} type - The type of this property.
 * @property {string} [objectType] - **Required**  when `type` is `"list"`, and must match the
 *   type of an object in the same schema.
 * @property {any} [default] - The default value for this property on creation when not
 *   otherwise specified.
 * @property {boolean} [optional] - Signals if this property may be assigned `null` or `undefined`.
 * @property {boolean} [indexed] - Signals if this property should be indexed. Only supported for
 *   `"string"`, `"int"`, and `"bool"` properties.
 */

/**
 * The type of an object may either be specified as a string equal to the `name` in a
 * {@link Realm~ObjectSchema ObjectSchema} definition, **or** a constructor that was specified
 * in the {@link Realm~Configuration configuration} `schema`.
 * @typedef Realm~ObjectType
 * @type {string|Realm~ObjectClass}
 */

/**
 * A property type may be specified as one of the standard builtin types, or as an object type
 * inside the same schema.
 * @typedef Realm~PropertyType
 * @type {("bool"|"int"|"float"|"double"|"string"|"date"|"data"|"list"|"<ObjectType>")}
 * @property {boolean} "bool" - Property value may either be `true` or `false`.
 * @property {number} "int" - Property may be assigned any number, but will be stored as a
 *   round integer, meaning anything after the decimal will be truncated.
 * @property {number} "float" - Property may be assigned any number, but will be stored as a
 *   `float`, which may result in a loss of precision.
 * @property {number} "double" - Property may be assigned any number, and will have no loss
 *   of precision.
 * @property {string} "string" - Property value may be any arbitrary string.
 * @property {Date} "date" - Property may be assigned any `Date` instance.
 * @property {ArrayBuffer} "data" - Property may either be assigned an `ArrayBuffer`
 *   or `ArrayBufferView` (e.g. `DataView`, `Int8Array`, `Float32Array`, etc.) instance,
 *   but will always be returned as an `ArrayBuffer`.
 * @property {Realm.List} "list" - Property may be assigned any ordered collection
 *   (e.g. `Array`, {@link Realm.List}, {@link Realm.Results}) of objects all matching the
 *   `objectType` specified in the {@link Realm~ObjectSchemaProperty ObjectSchemaProperty}.
 * @property {Realm.Object} "<ObjectType>" - A string that matches the `name` of an object in the
 *   same schema (see {@link Realm~ObjectSchema ObjectSchema}) – this property may be assigned
 *   any object of this type from inside the same Realm, and will always be _optional_
 *   (meaning it may also be assigned `null` or `undefined`).
 */
<|endoftext|>