<commit_before>/**
*	@class Object class from which every Era classes derives.
*	It handles inheritance, serialization, dump function, manages events connections.
*/
Core.Object = function() {
};

Core.Object.prototype.classType = 'Core.Object';

/**
*	Change default object toString
*/
Core.Object.prototype.toString = function() {
	return "[object "+this.classType+"]";
};

/**
*	Add dump method to objects to allow object
*	content to be displayed in the console
*	@param {String} filter Regex filter of the dump
*/
Core.Object.prototype.dump = function(filter) {
	if(filter != undefined)
		filter = new RegExp(filter,'i');
	console.log(this+':');
	for(var prop in this) {
		try {
			var test = true;
			if(filter != undefined)
				test = filter.test(prop);
			if(test)
				console.log(prop+' => '+this[prop]);
		} catch(err) {}
	}
};

/**
*	Display all objects properties
*	@param {mixed} obj Object to dump
*	@param {String} filter Regex filter of the dump
*/
Core.Object.dump = function(obj, filter) {
	if(filter != undefined)
		filter = new RegExp(filter,'i');
	console.log(obj+':');
	for(var prop in obj) {
		try {
			var test = true;
			if(filter != undefined)
				test = filter.test(prop);
			if(test)
				console.log(prop+' => '+obj[prop]);
		} catch(err) {}
	}
};

/**
*	Serialize a javascript object into a string
*	to deserialize, just use JSON.parse
*/
Core.Object.prototype.serialize = function() {
	return JSON.stringify(this);
};

/**
*	@private
* 	INTERNAL: dont use. Usefull function for the object constructor.
*/
Core.Object.prototype.constructorHelper = function(config, proto) {
	if(proto == undefined)
		proto = this.__proto__;
	if(proto == undefined)
		return;
	if(config == undefined)
		config = {};
	if(proto.__baseclass__ != undefined)
		this.constructorHelper.call(this, config, proto.__baseclass__);
	else
		if(proto.__proto__ != undefined)
			this.constructorHelper.call(this, config, proto.__proto__);
	if(proto.__constructor != undefined)
		proto.__constructor.call(this, config);
};

/**
*	Extend a Class to create a new class.
*	@param {String} classType The full class name with the namespace
*	@param {String} classDefine The object with the class members (methods, properties and constructor)
*	@param {String} classOverride An object with the members (fields and methods) that need to be overrided in parents classes. It will trow an error if overrided members are not declare here.
*	@param {String} classStatic An object with all the static members.
*/
Function.prototype.extend = function(classType, classDefine, classOverride, classStatic) {
	var tab = classType.split('.');
	var namespace = "";
	var current = window;
	for(var i = 0; i < tab.length-1; i++) {
		if(namespace != "")
			namespace += ".";
		namespace += tab[i];
		if(current[tab[i]] == undefined)
			current[tab[i]] = {};
		current = current[tab[i]];
	}
	var func = eval("( "+classType+" = function(config, noscope) { if(noscope !== true) Core.Object.currentScopes.push(this); var nconfig = Core.Util.clone(config); this.constructorHelper.call(this, nconfig); this.autoConfig(nconfig); if(noscope !== true) Core.Object.currentScopes.pop(); } )");
	if(navigator.isIE) {
		for(var prop in this.prototype) {
			func.prototype[prop] = this.prototype[prop];
		}
		func.prototype['__proto__'] = func.prototype;
	}
	else {
		func.prototype.__proto__ = this.prototype;
	}
	func.prototype['__baseclass__'] = this.prototype;
	func['base'] = this.prototype;

	// inherit static methods
	for(var prop in func['base'].constructor) {
		if(typeof(func['base'].constructor[prop]) == 'function') {
			func[prop] = func['base'].constructor[prop];
		}
	}

	if(classStatic != undefined) {
		for(var prop in classStatic)
			func[prop] = classStatic[prop];
	}

	for(var prop in classDefine) {
		if(prop == 'constructor')
			func.prototype['__constructor'] = classDefine[prop];
		else {
			if((typeof(classDefine[prop]) == 'object') && (classDefine[prop] != null))
				throw('object are not allowed in classDefine ('+prop+'). Create object in the constructor');

			if(prop in func.prototype)
				throw('Try to override '+prop+' on class '+classType+'. Use classOverride you want to do it');

			func.prototype[prop] = classDefine[prop];
		}
	}
	if(classDefine['constructor'] === Object.prototype.constructor)
		 func.prototype['__constructor'] = undefined;
	if((navigator.isIE) && (classDefine.constructor !== Object.prototype.constructor))
			func.prototype['__constructor'] = classDefine.constructor;
	if(classOverride != undefined) {
		for(var prop in classOverride) {
			if((typeof(classOverride[prop]) == 'object') && (classOverride[prop] != null))
				throw('object are not allowed in classOverride ('+prop+'). Create object in the constructor');
			func.prototype[prop] = classOverride[prop];
		}
	}
	func.prototype.classType = classType;

	if((classStatic != undefined) && ('constructor' in classStatic))
		classStatic.constructor.call(func);

	return func;
};

/**
*	@return {Boolean} Whether or not an object is or derives from the class Type of the calling instance.
*/
Function.prototype.hasInstance = function(obj) {
	if((typeof(obj) != 'object') || (obj == null) || (obj.constructorHelper != Core.Object.prototype.constructorHelper))
		return false;

	var current = obj;
	while(current != undefined) {
		if(current.classType == this.prototype.classType)
			return true;
		current = current.__baseclass__;
	}
	return false;
};

/**
* @return true if the current object is class or subclass of
* the given class name
*/
Core.Object.prototype.isSubclassOf = function(parentClassName) {
	var current = this;
	while(current != undefined) {
		if(current.classType == parentClassName)
			return true;
		current = current.__baseclass__;
	}
	return false;
};

/**
*	Declare supported events on this class
*	@param {String} events List of all class events
*	@example this.addEvents('press', 'down', 'up');
*/
Core.Object.prototype.addEvents = function() {
	if(this.events == undefined)
		this.events = [];
	for(var i = 0; i < arguments.length; i++)
		this.events[arguments[i]] = [];
};

/**
*	Fire the eventName event. All given arguments are passed to the
*	registered methods.
*	@param {String} eventName Name of the event to fire. Must have been registred with {@link Core.Object#addEvents} before.
*/
Core.Object.prototype.fireEvent = function(eventName) {
	var args = [];
	for(var i = 1; i < arguments.length; i++)
		args[i-1] = arguments[i];
	var handled = false;
	for(var i = 0; (i < this.events[eventName].length) && !handled; i++) {
		handled = this.events[eventName][i].method.apply(this.events[eventName][i].scope, args);
		if(handled == undefined)
			handled = false;
	}
	return handled;
};

/**
* Connect a method to the eventName event of the obj object. The method will
* be called in the current element scope.
*	@param {mixed} obj
*	@param {String} eventName
*	@param {function} method
*	@param capture
*/
Core.Object.prototype.connect = function(obj, eventName, method, capture) {
	/**#nocode+ Avoid Jsdoc warnings...*/
	if(capture == undefined)
		capture = false;
	if('addEventListener' in obj) {
		var wrapper = function() {
			return arguments.callee.callback.apply(arguments.callee.scope, arguments);
		}
		wrapper.scope = this;
		wrapper.callback = method;
		wrapper.eventName = eventName;
		wrapper.capture = capture;
		obj.addEventListener(eventName, wrapper, capture);
		if(obj.events == undefined)
			obj.events = [];
		obj.events.push(wrapper);
	}
	else if('attachEvent' in obj) {
		var wrapper = function() {
			return arguments.callee.callback.apply(arguments.callee.scope, arguments);
		}
		wrapper.scope = this;
		wrapper.callback = method;
		wrapper.eventName = eventName;
		wrapper.capture = capture;
		obj.attachEvent(eventName, wrapper);
		if(obj.events == undefined)
			obj.events = [];
		obj.events.push(wrapper);
	}
	else {
		var signal = { scope: this, method: method, capture: capture };
		obj.events[eventName].push(signal);
	}
	/**#nocode-*/
};

/**
* Disconnect the current object from the eventName event on obj.
*	@param {mixed} obj
*	@param {String} eventName
*	@param {function} method
*/
Core.Object.prototype.disconnect = function(obj, eventName, method) {
	if('removeEventListener' in obj) {
		for(var i = 0; (obj.events != undefined) && (i < obj.events.length); i++) {
			var wrapper = obj.events[i];
			if((wrapper.scope == this) && (wrapper.eventName == eventName)) {
				if((method != undefined) && (wrapper.callback != method))
					continue;
				obj.removeEventListener(wrapper.eventName, wrapper, wrapper.capture);
				obj.events.splice(i, 1);
				i--;
			}
		}
	}
	else if('detachEvent' in obj) {
		for(var i = 0; (obj.events != undefined) && (i < obj.events.length); i++) {
			var wrapper = obj.events[i];
			if((wrapper.scope == this) && (wrapper.eventName == eventName)) {
				if((method != undefined) && (wrapper.callback != method))
					continue;
				obj.detachEvent(wrapper.eventName, wrapper);
				obj.events.splice(i, 1);
				i--;
			}
		}
	}
	else {
		for(var i = 0; (obj.events != undefined) && (i < obj.events[eventName].length); i++) {
			var signal = obj.events[eventName][i];
			if(signal.scope == this) {
				if((method != undefined) && (signal.method != method))
					continue;
				obj.events[eventName].splice(i, 1);
				i--;
			}
		}
	}
};

Core.Object.currentScopes = [];

Core.Object.prototype.autoConfig = function(config) {
	if(config == undefined)
		return;
	var scope;
	var pushScope = false;

	if('scope' in config) {
		scope = config.scope;
		Core.Object.currentScopes.push(scope);
		pushScope = true;
	}
	else if(Core.Object.currentScopes.length > 0)
		scope = Core.Object.currentScopes[Core.Object.currentScopes.length-1];
	else {
		scope = this;
		Core.Object.currentScopes.push(scope);
		pushScope = true;
	}
	for(var prop in config) {
		// look for name
		if(prop === 'name') {
			console.log(this+'.autoConfig NAME: '+config.name+', SCOPE: '+scope);
			scope[config.name] = this;
			delete(config.name);
			continue;
		}
		// look for normal properties
		var func = 'set'+prop.charAt(0).toUpperCase()+prop.substr(1);
		if((func in this) && (typeof(this[func]) == 'function')) {
			this[func].call(this, config[prop]);
			delete(config[prop]);
		}
		// look for attached properties
		else if(prop.indexOf('.') != -1) {
			var props = prop.split('.');
			var current = window;
			for(var i = 0; i < props.length - 1; i++) {
				current = current[props[i]];
			}
			var c = props[props.length-1];
			var func = 'set'+c.charAt(0).toUpperCase()+c.substr(1);
			if((func in current) && (typeof(current[func] == 'function'))) {
				current[func].call(current, this, config[prop]);
				delete(config[prop]);
			}
//#if DEBUG
			else
				throw('Attached property \''+prop+'\' not found');
//#end
		}
		else if(prop.indexOf('on') == 0) {
			var eventName = prop.charAt(2).toLowerCase()+prop.substr(3);
			if((this.events != undefined) && (eventName in this.events)) {
//#if DEBUG
				if(typeof(config[prop]) != 'function')
					throw('function is need to connect to the \''+eventName+'\' on '+this.classType);
//#end
				scope.connect(this, eventName, config[prop]);
				delete(config[prop]);
			}
//#if DEBUG
			else
				throw('event \''+eventName+'\' not found on '+this.classType);
//#end
		}
//#if DEBUG
		else if(prop !== 'scope')
			throw('Property \''+prop+'\' not found on '+this.classType);
//#end
	}
	if(pushScope)
		Core.Object.currentScopes.pop();
};

Core.Object.create = function(element, scope) {
	if(scope === undefined)
		scope = this;
	if(element === undefined)
		return undefined;
	else if(typeof(element) == 'string') {
		if('parse' in this)
			return this.parse(element);
		else
			throw('static parse need to be defined in class '+this.prototype.classType+' to create from a string');
	}
	else if(Core.Object.hasInstance(element))
		return element;
	else {
		var pushScope = false;

		if(Core.Object.currentScopes.length === 0) {
			Core.Object.currentScopes.push(scope);
			pushScope = true;
		}
		var type = element.type;
//#if DEBUG
		if('type' in element && type === undefined)
			throw('Cannot create object of type undefined');
//#end
		if(type === undefined)
			type = this;
//#if DEBUG
		else {
			var current = type;
			while((current !== undefined) && (current !== this)) {
				if(current.base == undefined)
					throw('Expecting class '+this.prototype.classType+' got '+type.prototype.classType);
				current = current.base.constructor;
			}
		}
//#end
		delete(element.type);
		var res = new type(element, true);

		if(pushScope)
			Core.Object.currentScopes.pop();
		return res;
	}
};

<commit_msg>try to correct a complex problem with auto scope and anto config<commit_after>/**
*	@class Object class from which every Era classes derives.
*	It handles inheritance, serialization, dump function, manages events connections.
*/
Core.Object = function() {
};

Core.Object.prototype.classType = 'Core.Object';

/**
*	Change default object toString
*/
Core.Object.prototype.toString = function() {
	return "[object "+this.classType+"]";
};

/**
*	Add dump method to objects to allow object
*	content to be displayed in the console
*	@param {String} filter Regex filter of the dump
*/
Core.Object.prototype.dump = function(filter) {
	if(filter != undefined)
		filter = new RegExp(filter,'i');
	console.log(this+':');
	for(var prop in this) {
		try {
			var test = true;
			if(filter != undefined)
				test = filter.test(prop);
			if(test)
				console.log(prop+' => '+this[prop]);
		} catch(err) {}
	}
};

/**
*	Display all objects properties
*	@param {mixed} obj Object to dump
*	@param {String} filter Regex filter of the dump
*/
Core.Object.dump = function(obj, filter) {
	if(filter != undefined)
		filter = new RegExp(filter,'i');
	console.log(obj+':');
	for(var prop in obj) {
		try {
			var test = true;
			if(filter != undefined)
				test = filter.test(prop);
			if(test)
				console.log(prop+' => '+obj[prop]);
		} catch(err) {}
	}
};

/**
*	Serialize a javascript object into a string
*	to deserialize, just use JSON.parse
*/
Core.Object.prototype.serialize = function() {
	return JSON.stringify(this);
};

/**
*	@private
* 	INTERNAL: dont use. Usefull function for the object constructor.
*/
Core.Object.prototype.constructorHelper = function(config, proto) {
	if(proto == undefined)
		proto = this.__proto__;
	if(proto == undefined)
		return;
	if(config == undefined)
		config = {};
	if(proto.__baseclass__ != undefined)
		this.constructorHelper.call(this, config, proto.__baseclass__);
	else
		if(proto.__proto__ != undefined)
			this.constructorHelper.call(this, config, proto.__proto__);
	if(proto.__constructor != undefined)
		proto.__constructor.call(this, config);
};

/**
*	Extend a Class to create a new class.
*	@param {String} classType The full class name with the namespace
*	@param {String} classDefine The object with the class members (methods, properties and constructor)
*	@param {String} classOverride An object with the members (fields and methods) that need to be overrided in parents classes. It will trow an error if overrided members are not declare here.
*	@param {String} classStatic An object with all the static members.
*/
Function.prototype.extend = function(classType, classDefine, classOverride, classStatic) {
	var tab = classType.split('.');
	var namespace = "";
	var current = window;
	for(var i = 0; i < tab.length-1; i++) {
		if(namespace != "")
			namespace += ".";
		namespace += tab[i];
		if(current[tab[i]] == undefined)
			current[tab[i]] = {};
		current = current[tab[i]];
	}
	var func = eval("( "+classType+" = function(config, noscope) { if(noscope !== true) Core.Object.currentScopes.push(this); var nconfig = Core.Util.clone(config); this.constructorHelper.call(this, nconfig); this.autoConfig(nconfig); if(noscope !== true) Core.Object.currentScopes.pop(); } )");
	if(navigator.isIE) {
		for(var prop in this.prototype) {
			func.prototype[prop] = this.prototype[prop];
		}
		func.prototype['__proto__'] = func.prototype;
	}
	else {
		func.prototype.__proto__ = this.prototype;
	}
	func.prototype['__baseclass__'] = this.prototype;
	func['base'] = this.prototype;

	// inherit static methods
	for(var prop in func['base'].constructor) {
		if(typeof(func['base'].constructor[prop]) == 'function') {
			func[prop] = func['base'].constructor[prop];
		}
	}

	if(classStatic != undefined) {
		for(var prop in classStatic)
			func[prop] = classStatic[prop];
	}

	for(var prop in classDefine) {
		if(prop == 'constructor')
			func.prototype['__constructor'] = classDefine[prop];
		else {
			if((typeof(classDefine[prop]) == 'object') && (classDefine[prop] != null))
				throw('object are not allowed in classDefine ('+prop+'). Create object in the constructor');

			if(prop in func.prototype)
				throw('Try to override '+prop+' on class '+classType+'. Use classOverride you want to do it');

			func.prototype[prop] = classDefine[prop];
		}
	}
	if(classDefine['constructor'] === Object.prototype.constructor)
		 func.prototype['__constructor'] = undefined;
	if((navigator.isIE) && (classDefine.constructor !== Object.prototype.constructor))
			func.prototype['__constructor'] = classDefine.constructor;
	if(classOverride != undefined) {
		for(var prop in classOverride) {
			if((typeof(classOverride[prop]) == 'object') && (classOverride[prop] != null))
				throw('object are not allowed in classOverride ('+prop+'). Create object in the constructor');
			func.prototype[prop] = classOverride[prop];
		}
	}
	func.prototype.classType = classType;

	if((classStatic != undefined) && ('constructor' in classStatic))
		classStatic.constructor.call(func);

	return func;
};

/**
*	@return {Boolean} Whether or not an object is or derives from the class Type of the calling instance.
*/
Function.prototype.hasInstance = function(obj) {
	if((typeof(obj) != 'object') || (obj == null) || (obj.constructorHelper != Core.Object.prototype.constructorHelper))
		return false;

	var current = obj;
	while(current != undefined) {
		if(current.classType == this.prototype.classType)
			return true;
		current = current.__baseclass__;
	}
	return false;
};

/**
* @return true if the current object is class or subclass of
* the given class name
*/
Core.Object.prototype.isSubclassOf = function(parentClassName) {
	var current = this;
	while(current != undefined) {
		if(current.classType == parentClassName)
			return true;
		current = current.__baseclass__;
	}
	return false;
};

/**
*	Declare supported events on this class
*	@param {String} events List of all class events
*	@example this.addEvents('press', 'down', 'up');
*/
Core.Object.prototype.addEvents = function() {
	if(this.events == undefined)
		this.events = [];
	for(var i = 0; i < arguments.length; i++)
		this.events[arguments[i]] = [];
};

/**
*	Fire the eventName event. All given arguments are passed to the
*	registered methods.
*	@param {String} eventName Name of the event to fire. Must have been registred with {@link Core.Object#addEvents} before.
*/
Core.Object.prototype.fireEvent = function(eventName) {
	var args = [];
	for(var i = 1; i < arguments.length; i++)
		args[i-1] = arguments[i];
	var handled = false;
	for(var i = 0; (i < this.events[eventName].length) && !handled; i++) {
		handled = this.events[eventName][i].method.apply(this.events[eventName][i].scope, args);
		if(handled == undefined)
			handled = false;
	}
	return handled;
};

/**
* Connect a method to the eventName event of the obj object. The method will
* be called in the current element scope.
*	@param {mixed} obj
*	@param {String} eventName
*	@param {function} method
*	@param capture
*/
Core.Object.prototype.connect = function(obj, eventName, method, capture) {
	/**#nocode+ Avoid Jsdoc warnings...*/
	if(capture == undefined)
		capture = false;
	if('addEventListener' in obj) {
		var wrapper = function() {
			return arguments.callee.callback.apply(arguments.callee.scope, arguments);
		}
		wrapper.scope = this;
		wrapper.callback = method;
		wrapper.eventName = eventName;
		wrapper.capture = capture;
		obj.addEventListener(eventName, wrapper, capture);
		if(obj.events == undefined)
			obj.events = [];
		obj.events.push(wrapper);
	}
	else if('attachEvent' in obj) {
		var wrapper = function() {
			return arguments.callee.callback.apply(arguments.callee.scope, arguments);
		}
		wrapper.scope = this;
		wrapper.callback = method;
		wrapper.eventName = eventName;
		wrapper.capture = capture;
		obj.attachEvent(eventName, wrapper);
		if(obj.events == undefined)
			obj.events = [];
		obj.events.push(wrapper);
	}
	else {
		var signal = { scope: this, method: method, capture: capture };
		obj.events[eventName].push(signal);
	}
	/**#nocode-*/
};

/**
* Disconnect the current object from the eventName event on obj.
*	@param {mixed} obj
*	@param {String} eventName
*	@param {function} method
*/
Core.Object.prototype.disconnect = function(obj, eventName, method) {
	if('removeEventListener' in obj) {
		for(var i = 0; (obj.events != undefined) && (i < obj.events.length); i++) {
			var wrapper = obj.events[i];
			if((wrapper.scope == this) && (wrapper.eventName == eventName)) {
				if((method != undefined) && (wrapper.callback != method))
					continue;
				obj.removeEventListener(wrapper.eventName, wrapper, wrapper.capture);
				obj.events.splice(i, 1);
				i--;
			}
		}
	}
	else if('detachEvent' in obj) {
		for(var i = 0; (obj.events != undefined) && (i < obj.events.length); i++) {
			var wrapper = obj.events[i];
			if((wrapper.scope == this) && (wrapper.eventName == eventName)) {
				if((method != undefined) && (wrapper.callback != method))
					continue;
				obj.detachEvent(wrapper.eventName, wrapper);
				obj.events.splice(i, 1);
				i--;
			}
		}
	}
	else {
		for(var i = 0; (obj.events != undefined) && (i < obj.events[eventName].length); i++) {
			var signal = obj.events[eventName][i];
			if(signal.scope == this) {
				if((method != undefined) && (signal.method != method))
					continue;
				obj.events[eventName].splice(i, 1);
				i--;
			}
		}
	}
};

Core.Object.currentScopes = [];

Core.Object.prototype.autoConfig = function(config) {
	if(config == undefined)
		return;
	var scope;
	var pushScope = false;

	if('scope' in config) {
		scope = config.scope;
		Core.Object.currentScopes.push(scope);
		pushScope = true;
	}
	else if(Core.Object.currentScopes.length > 0)
		scope = Core.Object.currentScopes[Core.Object.currentScopes.length-1];
	else {
		scope = this;
		Core.Object.currentScopes.push(scope);
		pushScope = true;
	}
	for(var prop in config) {
		// look for name
		if(prop === 'name') {
//			console.log(this+'.autoConfig NAME: '+config.name+', SCOPE: '+scope);
			scope[config.name] = this;
			delete(config.name);
			continue;
		}
		// look for normal properties
		var func = 'set'+prop.charAt(0).toUpperCase()+prop.substr(1);
		if((func in this) && (typeof(this[func]) == 'function')) {
			this[func].call(this, config[prop]);
			delete(config[prop]);
		}
		// look for attached properties
		else if(prop.indexOf('.') != -1) {
			var props = prop.split('.');
			var current = window;
			for(var i = 0; i < props.length - 1; i++) {
				current = current[props[i]];
			}
			var c = props[props.length-1];
			var func = 'set'+c.charAt(0).toUpperCase()+c.substr(1);
			if((func in current) && (typeof(current[func] == 'function'))) {
				current[func].call(current, this, config[prop]);
				delete(config[prop]);
			}
//#if DEBUG
			else
				throw('Attached property \''+prop+'\' not found');
//#end
		}
		else if(prop.indexOf('on') == 0) {
			var eventName = prop.charAt(2).toLowerCase()+prop.substr(3);
			if((this.events != undefined) && (eventName in this.events)) {
//#if DEBUG
				if(typeof(config[prop]) != 'function')
					throw('function is need to connect to the \''+eventName+'\' on '+this.classType);
//#end
				scope.connect(this, eventName, config[prop]);
				delete(config[prop]);
			}
//#if DEBUG
			else
				throw('event \''+eventName+'\' not found on '+this.classType);
//#end
		}
//#if DEBUG
		else if(prop !== 'scope')
			throw('Property \''+prop+'\' not found on '+this.classType);
//#end
	}
	if(pushScope)
		Core.Object.currentScopes.pop();
};

Core.Object.create = function(element, scope) {
	if(scope === undefined)
		scope = this;
	if(element === undefined)
		return undefined;
	else if(typeof(element) == 'string') {
		if('parse' in this)
			return this.parse(element);
		else
			throw('static parse need to be defined in class '+this.prototype.classType+' to create from a string');
	}
	else if(Core.Object.hasInstance(element))
		return element;
	else {
		var pushScope = false;

		if(Core.Object.currentScopes.length === 0) {
			Core.Object.currentScopes.push(scope);
			pushScope = true;
		}
		var type = element.type;
//#if DEBUG
		if('type' in element && type === undefined)
			throw('Cannot create object of type undefined');
//#end
		if(type === undefined)
			type = this;
//#if DEBUG
		else {
			var current = type;
			while((current !== undefined) && (current !== this)) {
				if(current.base == undefined)
					throw('Expecting class '+this.prototype.classType+' got '+type.prototype.classType);
				current = current.base.constructor;
			}
		}
//#end
		delete(element.type);
		var res = new type(element, true);

		if(pushScope)
			Core.Object.currentScopes.pop();
		return res;
	}
};

<|endoftext|>


<commit_before>/**
 * A collection of objects from Gansoi.
 * @constructor
 * @param {!string} identifier THe name of the member used to identify an
 *        object.
 */
g.Collection = function(identifier) {
    var self = this;

    self.data = new Array();

    self.insert = function(obj) {
        self.data.push(obj);
    };

    self.deleteId = function(id) {
        self.data = self.data.filter(function(obj) {
            return obj[identifier] !== id;
        });
    };

    self.upsert = function(obj) {
        var index = self.data.findIndex(function(element) {
            if (element[identifier] === obj[identifier]) {
                return true;
            }

            return false;
        });

        if (index >= 0) {
            // We must use splice, if we simply replace the element Vue will
            // never notice.
            // https://vuejs.org/v2/guide/list.html#Caveats
            self.data.splice(index, 1, obj);
        } else {
            self.insert(obj);
        }
    };

    self.get = function(id) {
        var ret = self.data.find(function(element) {
            if (element[identifier] === id) {
                return true;
            }
        });

        return ret;
    };

    self.log = function(log) {
        switch (log.command) {
            case 'delete':
                self.deleteId(log.data[identifier]);
                break;
            case 'save':
                self.upsert(log.data);
                break;
            default:
                console.dir(log);
        }
    };
};
<commit_msg>Added very simple query function to g.Collection.<commit_after>/**
 * A collection of objects from Gansoi.
 * @constructor
 * @param {!string} identifier THe name of the member used to identify an
 *        object.
 */
g.Collection = function(identifier) {
    var self = this;

    self.data = new Array();

    self.insert = function(obj) {
        self.data.push(obj);
    };

    self.deleteId = function(id) {
        self.data = self.data.filter(function(obj) {
            return obj[identifier] !== id;
        });
    };

    self.upsert = function(obj) {
        var index = self.data.findIndex(function(element) {
            if (element[identifier] === obj[identifier]) {
                return true;
            }

            return false;
        });

        if (index >= 0) {
            // We must use splice, if we simply replace the element Vue will
            // never notice.
            // https://vuejs.org/v2/guide/list.html#Caveats
            self.data.splice(index, 1, obj);
        } else {
            self.insert(obj);
        }
    };

    self.get = function(id) {
        var ret = self.data.find(function(element) {
            if (element[identifier] === id) {
                return true;
            }
        });

        return ret;
    };

    self.query = function(key, value) {
        var ret = [];

        self.data.find(function(element) {
            if (element[key] === value) {
                ret.push(element);
            }
        });

        return ret;
    };

    self.log = function(log) {
        switch (log.command) {
            case 'delete':
                self.deleteId(log.data[identifier]);
                break;
            case 'save':
                self.upsert(log.data);
                break;
            default:
                console.dir(log);
        }
    };
};
<|endoftext|>


<commit_before>/*
 * table.js
 * Copyright (C) 2014 Sébastien Diemer <sebastien.diemer@mines-paristech.fr>
 *
 * Distributed under terms of the MIT license.
 *
 */

SERVER_URL = 'http://localhost:5000/dataiku'

function ask_column(column) {
    $.ajax({
        cache: false,
        url: SERVER_URL+'/columns/'+column,
        type: "GET",
        contentType: "application/json"
    }).done(function(json) {
        $('#thetable tr').not(':first').not(':last').remove();
        var html = '';
        for(var i = 0; i < json['column'].length; i++)
                    html += '
' + json['column'][i]['value'] +
                            '	' + json['column'][i]['count'] +
                            '	' + json['column'][i]['average age'] + '
';
        $('#thetable tr').first().after(html);
        if (json['ignored'] == 0) {
            $('#ignored').html('');
        } else {
            $('#ignored').html(json['ignored'] + ' values clipped');
        }
    });
}

$(document).ajaxError(function( event, request, settings ) {
      $( "#content" ).css("color", "red");
      $( "#content" ).html("Error server unavailable");
});

$(document).ready(
    function get_columns() {
        $.ajax({
            cache: false,
            url: SERVER_URL+'/columns',
            type: "GET",
            contentType: "application/json"
        }).done(function(json) {
            var $inputColumns = $("select[name='inputColumns']")
            var columns = json['columns']
            $(columns).each(function(i, v) {
                    $inputColumns.append($("<option>", { value: v, html: v }));
            });
        });
    });
<commit_msg>corrected small bug with last row<commit_after>/*
 * table.js
 * Copyright (C) 2014 Sébastien Diemer <sebastien.diemer@mines-paristech.fr>
 *
 * Distributed under terms of the MIT license.
 *
 */

SERVER_URL = 'http://localhost:5000/dataiku'

function ask_column(column) {
    $.ajax({
        cache: false,
        url: SERVER_URL+'/columns/'+column,
        type: "GET",
        contentType: "application/json"
    }).done(function(json) {
        $('#thetable tr').not(':first').remove();
        var html = '';
        for(var i = 0; i < json['column'].length; i++)
                    html += '
' + json['column'][i]['value'] +
                            '	' + json['column'][i]['count'] +
                            '	' + json['column'][i]['average age'] + '
';
        $('#thetable tr').first().after(html);
        if (json['ignored'] == 0) {
            $('#ignored').html('');
        } else {
            $('#ignored').html(json['ignored'] + ' values clipped');
        }
    });
}

$(document).ajaxError(function( event, request, settings ) {
      $( "#content" ).css("color", "red");
      $( "#content" ).html("Error server unavailable");
});

$(document).ready(
    function get_columns() {
        $.ajax({
            cache: false,
            url: SERVER_URL+'/columns',
            type: "GET",
            contentType: "application/json"
        }).done(function(json) {
            var $inputColumns = $("select[name='inputColumns']")
            var columns = json['columns']
            $(columns).each(function(i, v) {
                    $inputColumns.append($("<option>", { value: v, html: v }));
            });
        });
    });
<|endoftext|>


<commit_before>/* global __dirname */

let path = require('path');
let webpack = require('webpack');

let LodashModuleReplacementPlugin = require('lodash-webpack-plugin');

let babelSettings = JSON.stringify({
    plugins: ['lodash', 'babel-plugin-transform-function-bind', 'transform-object-rest-spread'],
    presets: ['es2015'],
    cacheDirectory: true
});

module.exports = {
    entry: {
        index: ['./src/index.js']
    },
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: 'vuex-model-template.dev.js',
        libraryTarget: 'umd'
    },
    externals: {
        // "lodash": "lodash",
        "vue": "vue",
        "vuex": "vuex"
    },
    resolve: {
        modules: [
            path.resolve('.'),
            path.resolve('./src'),
            'node_modules'
        ],
        alias: {
            vue: 'vue/dist/vue.js'
        },
        extensions: ['.js']
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /(node_modules|bower_components)/,
                loader: `babel-loader?${babelSettings}`
            }
        ]
    },
    'plugins': [
        new LodashModuleReplacementPlugin,
        new webpack.optimize.OccurrenceOrderPlugin
    ]
};<commit_msg>no message<commit_after>/* global __dirname */

let path = require('path');
let webpack = require('webpack');

let LodashModuleReplacementPlugin = require('lodash-webpack-plugin');

let babelSettings = JSON.stringify({
    plugins: ['lodash', 'babel-plugin-transform-function-bind', 'transform-object-rest-spread'],
    presets: ['es2015'],
    cacheDirectory: true
});

module.exports = {
    entry: {
        index: ['./src/index.js']
    },
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: 'vuex-model-template.dev.js',
        libraryTarget: 'umd'
    },
    externals: {
        "vue": "vue",
        "vuex": "vuex"
    },
    resolve: {
        modules: [
            path.resolve('.'),
            path.resolve('./src'),
            'node_modules'
        ],
        alias: {
            vue: 'vue/dist/vue.js'
        },
        extensions: ['.js']
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /(node_modules|bower_components)/,
                loader: `babel-loader?${babelSettings}`
            }
        ]
    },
    'plugins': [
        new LodashModuleReplacementPlugin,
        new webpack.optimize.OccurrenceOrderPlugin
    ]
};<|endoftext|>


<commit_before>const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')

module.exports = {
  devtool: false,
  output: {
    filename: 'js/[name].[chunkhash:8].js',
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production'),
      },
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
      },
      output: {
        comments: false,
      },
      sourceMap: true,
      dead_code: true,
    }),
    new ExtractTextPlugin('css/[name].[contenthash:8].css'),
  ],
}
<commit_msg>chore: remove uglifiy config as it is now default behaviour<commit_after>const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')

module.exports = {
  devtool: false,
  output: {
    filename: 'js/[name].[chunkhash:8].js',
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production'),
      },
    }),
    new ExtractTextPlugin('css/[name].[contenthash:8].css'),
  ],
}
<|endoftext|>


<commit_before>const path = require('path');
const webpack = require('webpack');
const CopyWebpackPlugin = require("copy-webpack-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const banner =
`Copyright (C) 2022 jobsta

This file is part of ReportBro, a library to generate PDF and Excel reports.
Demos can be found at https://www.reportbro.com

Dual licensed under AGPLv3 and ReportBro commercial license:
https://www.reportbro.com/license

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see https://www.gnu.org/licenses/

Details for ReportBro commercial license can be found at
https://www.reportbro.com/license/agreement
`;

module.exports = {
  mode: 'production',
  entry: ['./src/main.js', './src/main.css', './src/iconfonts/style.css', './src/toggle-switch.css', './src/quill.reportbro.css'],
  output: {
    filename: 'reportbro.js',
    path: __dirname + '/dist'
  },
  devtool: 'source-map',
  performance : {
    hints : false // disable warning for asset size limit (generated js file)
  },
  module: {
    rules: [
      { test: /\.css$/, use: [MiniCssExtractPlugin.loader, 'css-loader'], },
      {
        test: /\.(png|gif)([\?]?.*)$/,
        type: 'asset/resource',
        generator: {
          filename: '[path][name][ext]'
        }
      },
      {
        test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
        type: 'asset/resource',
        generator: {
          filename: '[path][name][ext]?[hash]'
        }
      },
      {
        test: /\.js$/,
        include: [path.resolve(__dirname, "src")],
        loader: "babel-loader",
        options: {
          plugins: ['@babel/plugin-transform-runtime'],
          presets: ['@babel/preset-env']
        },
      }
    ]
  },
  plugins: [
    new webpack.BannerPlugin({ banner: banner, test: 'reportbro.js' }),
    new MiniCssExtractPlugin({filename: "reportbro.css"}),
    new CopyWebpackPlugin({
      patterns: [
        { from: 'node_modules/jquery/dist/jquery.js', to: 'ext/jquery.js' }
      ]
    }),
  ]
};
<commit_msg>Remove jquery from build process<commit_after>const path = require('path');
const webpack = require('webpack');
const CopyWebpackPlugin = require("copy-webpack-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const banner =
`Copyright (C) 2022 jobsta

This file is part of ReportBro, a library to generate PDF and Excel reports.
Demos can be found at https://www.reportbro.com

Dual licensed under AGPLv3 and ReportBro commercial license:
https://www.reportbro.com/license

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see https://www.gnu.org/licenses/

Details for ReportBro commercial license can be found at
https://www.reportbro.com/license/agreement
`;

module.exports = {
  mode: 'production',
  entry: ['./src/main.js', './src/main.css', './src/iconfonts/style.css', './src/toggle-switch.css', './src/quill.reportbro.css'],
  output: {
    filename: 'reportbro.js',
    path: __dirname + '/dist'
  },
  devtool: 'source-map',
  performance : {
    hints : false // disable warning for asset size limit (generated js file)
  },
  module: {
    rules: [
      { test: /\.css$/, use: [MiniCssExtractPlugin.loader, 'css-loader'], },
      {
        test: /\.(png|gif)([\?]?.*)$/,
        type: 'asset/resource',
        generator: {
          filename: '[path][name][ext]'
        }
      },
      {
        test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
        type: 'asset/resource',
        generator: {
          filename: '[path][name][ext]?[hash]'
        }
      },
      {
        test: /\.js$/,
        include: [path.resolve(__dirname, "src")],
        loader: "babel-loader",
        options: {
          plugins: ['@babel/plugin-transform-runtime'],
          presets: ['@babel/preset-env']
        },
      }
    ]
  },
  plugins: [
    new webpack.BannerPlugin({ banner: banner, test: 'reportbro.js' }),
    new MiniCssExtractPlugin({filename: "reportbro.css"}),
  ]
};
<|endoftext|>


<commit_before>var path              = require('path')
var webpack           = require('webpack')
var autoprefixer      = require('autoprefixer')
var ExtractTextPlugin = require('extract-text-webpack-plugin')

module.exports = {
  devtool: 'cheap-module-source-map',
  entry: [
    './src/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'zooid-ui.js',
    libraryTarget: 'umd',
    library: 'ZooidUI'
  },
  externals: {
    react: {
      root: 'React',
      commonjs2: 'react',
      commonjs: 'react',
      amd: 'react'
    }
  },
  plugins: [
    new webpack.NoErrorsPlugin(),

    new ExtractTextPlugin("[name].css"),

    // This plugin looks for similar chunks and files
    // and merges them for better caching by the user
    new webpack.optimize.DedupePlugin(),

    // This plugins optimizes chunks and modules by
    // how much they are used in your app
    new webpack.optimize.OccurenceOrderPlugin(),

    // This plugin minifies all the Javascript code of the final bundle
    // new webpack.optimize.UglifyJsPlugin({
    //   mangle: true,
    //   sourceMap: false,
    //   compress: {
    //     warnings: false, // Suppress uglification warnings
    //   },
    // }),

    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('production')
      }
    })
  ],
  module: {
    loaders: [
      {
        test:   /\.css$/,
        loader: ExtractTextPlugin.extract('style-loader', 'css-loader', 'postcss-loader')
      },
      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /(node_modules|example)/
      },
    ]
  },
  postcss: function () {
    return [autoprefixer]
  }
}
<commit_msg>Fix build filename<commit_after>var path              = require('path')
var webpack           = require('webpack')
var autoprefixer      = require('autoprefixer')
var ExtractTextPlugin = require('extract-text-webpack-plugin')

module.exports = {
  devtool: 'cheap-module-source-map',
  entry: [
    './src/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'index.js',
    libraryTarget: 'umd',
    library: 'ZooidUI'
  },
  externals: {
    react: {
      root: 'React',
      commonjs2: 'react',
      commonjs: 'react',
      amd: 'react'
    }
  },
  plugins: [
    new webpack.NoErrorsPlugin(),

    new ExtractTextPlugin("[name].css"),

    // This plugin looks for similar chunks and files
    // and merges them for better caching by the user
    new webpack.optimize.DedupePlugin(),

    // This plugins optimizes chunks and modules by
    // how much they are used in your app
    new webpack.optimize.OccurenceOrderPlugin(),

    // This plugin minifies all the Javascript code of the final bundle
    // new webpack.optimize.UglifyJsPlugin({
    //   mangle: true,
    //   sourceMap: false,
    //   compress: {
    //     warnings: false, // Suppress uglification warnings
    //   },
    // }),

    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('production')
      }
    })
  ],
  module: {
    loaders: [
      {
        test:   /\.css$/,
        loader: ExtractTextPlugin.extract('style-loader', 'css-loader', 'postcss-loader')
      },
      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /(node_modules|example)/
      },
    ]
  },
  postcss: function () {
    return [autoprefixer]
  }
}
<|endoftext|>


<commit_before>/**
 * import common webpack settings
 */
const commonSettings = require("./webpack.config.common.js")("/site", "/build", "__test__", "/src");

/**
 * Json Server
 * @type {config|exports|module.exports}
 */
const ConfigUtils = require("./ConfigUtil");

/**
 * @link https://webpack.github.io/docs/configuration.html#cache
 * Cache generated modules and chunks to improve performance for multiple incremental builds.
 This is enabled by default in watch mode.
 * @type {boolean}
 */
commonSettings.cache = true;

/**
 * @link https://webpack.github.io/docs/configuration.html#debug
 * Switch loaders to debug mode.
 * @type {boolean}
 */
commonSettings.debug = true;

/**
 * @link https://webpack.github.io/docs/configuration.html#devtool
 * Choose a developer tool to enhance debugging.
 * source-map - A SourceMap is emitted. See also output.sourceMapFilename.
 * @type {string}
 */
/**
 * @link https://webpack.github.io/docs/configuration.html#devtool
 * Choose a developer tool to enhance debugging.
 * source-map - A SourceMap is emitted. See also output.sourceMapFilename.
 * @type {string}
 */
commonSettings.devtool = "source-map";

commonSettings.module.preLoaders.push({ test: /.jsx?$/, loader: "eslint", exclude: /node_modules/ });
commonSettings.module.loaders.push({
        test: /\.jsx?/,
        exclude: /(__test__|node_modules|bower_components)\//,
        loader: "isparta"
    }
);

// *optional* isparta options: istanbul behind isparta will use it
commonSettings.isparta = {
    embedSource: true,
    noAutoWrap: true,
    // these babel options will be passed only to isparta and not to babel-loader
    babel: {
        presets: ["es2015", "stage-0", "react"]
    }
};

ConfigUtils.createJsonServer(3000, commonSettings.paths.root + "/testdb.json");
module.exports = function configure(config) {
    config.set({
        captureTimeout: 3000,
        browserDisconnectTimeout: 3000,
        browserDisconnectTolerance: 1,
        browserNoActivityTimeout: 60000,
        browsers: ["Chrome_travis_ci"],
        customLaunchers: {
            Chrome_travis_ci: {
                base: "Chrome",
                flags: ["--no-sandbox"]
            }
        },
        singleRun: true,
        frameworks: ["mocha"],
        plugins: [
            "karma-chrome-launcher",
            "karma-chai",
            "karma-mocha",
            "karma-sourcemap-loader",
            "karma-webpack",
            "karma-coverage",
            "karma-mocha-reporter"
        ],
        files: [
            "__test__/index.js"
        ],
        preprocessors: {
            "__test__/index.js": ["webpack", "sourcemap"]
        },
        webpack: commonSettings,
        webpackServer: {
            noInfo: true
        },
        reporters: ["mocha", "coverage"],
        coverageReporter: {
            // specify a common output directory
            dir: "coverage",
            reporters: [
                { type: "lcov", subdir: "report-lcov" }
            ]
        },
        client: {
            mocha: {
                timeout: 15000
            }
        }
    });
};
<commit_msg>json extension is excluded from isparta<commit_after>/**
 * import common webpack settings
 */
const commonSettings = require("./webpack.config.common.js")("/site", "/build", "__test__", "/src");

/**
 * Json Server
 * @type {config|exports|module.exports}
 */
const ConfigUtils = require("./ConfigUtil");

/**
 * @link https://webpack.github.io/docs/configuration.html#cache
 * Cache generated modules and chunks to improve performance for multiple incremental builds.
 This is enabled by default in watch mode.
 * @type {boolean}
 */
commonSettings.cache = true;

/**
 * @link https://webpack.github.io/docs/configuration.html#debug
 * Switch loaders to debug mode.
 * @type {boolean}
 */
commonSettings.debug = true;

/**
 * @link https://webpack.github.io/docs/configuration.html#devtool
 * Choose a developer tool to enhance debugging.
 * source-map - A SourceMap is emitted. See also output.sourceMapFilename.
 * @type {string}
 */
/**
 * @link https://webpack.github.io/docs/configuration.html#devtool
 * Choose a developer tool to enhance debugging.
 * source-map - A SourceMap is emitted. See also output.sourceMapFilename.
 * @type {string}
 */
commonSettings.devtool = "source-map";

commonSettings.module.preLoaders.push({ test: /.jsx?$/, loader: "eslint", exclude: /node_modules/ });
commonSettings.module.loaders.push({
        test: /\.jsx?$/,
        exclude: /(__test__|node_modules|bower_components)\//,
        loader: "isparta"
    }
);

// *optional* isparta options: istanbul behind isparta will use it
commonSettings.isparta = {
    embedSource: true,
    noAutoWrap: true,
    // these babel options will be passed only to isparta and not to babel-loader
    babel: {
        presets: ["es2015", "stage-0", "react"]
    }
};

ConfigUtils.createJsonServer(3000, commonSettings.paths.root + "/testdb.json");
module.exports = function configure(config) {
    config.set({
        captureTimeout: 3000,
        browserDisconnectTimeout: 3000,
        browserDisconnectTolerance: 1,
        browserNoActivityTimeout: 60000,
        browsers: ["Chrome_travis_ci"],
        customLaunchers: {
            Chrome_travis_ci: {
                base: "Chrome",
                flags: ["--no-sandbox"]
            }
        },
        singleRun: true,
        frameworks: ["mocha"],
        plugins: [
            "karma-chrome-launcher",
            "karma-chai",
            "karma-mocha",
            "karma-sourcemap-loader",
            "karma-webpack",
            "karma-coverage",
            "karma-mocha-reporter"
        ],
        files: [
            "__test__/index.js"
        ],
        preprocessors: {
            "__test__/index.js": ["webpack", "sourcemap"]
        },
        webpack: commonSettings,
        webpackServer: {
            noInfo: true
        },
        reporters: ["mocha", "coverage"],
        coverageReporter: {
            // specify a common output directory
            dir: "coverage",
            reporters: [
                { type: "lcov", subdir: "report-lcov" }
            ]
        },
        client: {
            mocha: {
                timeout: 15000
            }
        }
    });
};
<|endoftext|>


<commit_before>const path = require('path')
const webpack = require('webpack')

module.exports = {
  devtool: 'source-map',

  entry: [
    './public/app/index.js'
  ],

  output: {
    path: path.join(__dirname, 'public'),
    filename: 'bundle.js',
    publicPath: '/public/'
  },

  plugins: [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
      minimize: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('production')
      }
    })
  ],

  module: {
    loaders: [
      { test: /\.js?$/,
        loader: 'babel',
        exclude: /node_modules/ },
      { test: /\.scss?$/,
        loader: 'style!css!sass',
        include: path.join(__dirname, 'src', 'styles') },
      { test: /\.png$/,
        loader: 'file' },
      { test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
        loader: 'file'}
    ]
  }
}
<commit_msg>Add resolveLoader to config file<commit_after>const path = require('path')
const webpack = require('webpack')

module.exports = {
  devtool: 'source-map',

  entry: [
    './public/app/index.js'
  ],

  output: {
    path: path.join(__dirname, 'public'),
    filename: 'bundle.js',
    publicPath: '/public/'
  },

  plugins: [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
      minimize: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('production')
      }
    })
  ],

  module: {
    loaders: [
      { test: /\.js?$/,
        loader: 'babel',
        exclude: /node_modules/ },
      { test: /\.scss?$/,
        loader: 'style!css!sass',
        include: path.join(__dirname, 'src', 'styles') },
      { test: /\.png$/,
        loader: 'file' },
      { test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
        loader: 'file'}
    ]
  },

  resolveLoader: {
      modulesDirectories: [
          '/node_modules'
      ]
},
}
<|endoftext|>


<commit_before>var config = require('./webpack.config.js'),
    path = require('path'),
    webpack = require('webpack'),
    BundleTracker = require('webpack-bundle-tracker');

config.output.path = path.resolve('./coc_war_planner/static/js/dist/');
config.output.pathName = '/static/js/dist'; // This will override the url generated by django's staticfiles

config.plugins = [
    new BundleTracker({filename: './webpack-stats-prod.json'}),

    // removes a lot of debugging code in React
    new webpack.DefinePlugin({
        'process.env': {
            'NODE_ENV': JSON.stringify('production')
        }
    }),

    // keeps hashes consistent between compilations
    new webpack.optimize.OccurenceOrderPlugin(),

    // minifies your code
    new webpack.optimize.UglifyJsPlugin({
        compressor: {
            warnings: false
        }
    })
];

module.exports = config;
<commit_msg>update prod settings for webpack<commit_after>var config = require('./webpack.config.js'),
    path = require('path'),
    webpack = require('webpack'),
    BundleTracker = require('webpack-bundle-tracker');

config.output.path = path.resolve('./coc_war_planner/static/js/dist/');
config.output.publicPath = '/static/js/dist/';

config.plugins = [
    new BundleTracker({filename: './webpack-stats-prod.json'}),

    // removes a lot of debugging code in React
    new webpack.DefinePlugin({
        'process.env': {
            'NODE_ENV': JSON.stringify('production')
        }
    }),

    // keeps hashes consistent between compilations
    new webpack.optimize.OccurenceOrderPlugin(),

    // minifies your code
    new webpack.optimize.UglifyJsPlugin({
        compressor: {
            warnings: false
        }
    })
];

module.exports = config;
<|endoftext|>


<commit_before>var webpack = require("webpack");
var webpackMerge = require("webpack-merge");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var commonConfig = require("./webpack.common.js");
var helpers = require("./helpers");
var targetUrl = require("./target.js");

const ENV = process.env.NODE_ENV = process.env.ENV = "dev";

module.exports = webpackMerge(commonConfig, {
	devtool: "cheap-module-eval-source-map",

	output: {
		path: helpers.root("public_html"),
		publicPath: "http://localhost:7272",
		filename: "[name].js",
		chunkFilename: "[id].chunk.js"
	},

	plugins: [
		new ExtractTextPlugin("[name].css"),
		new webpack.DefinePlugin({
			"process.env": {
				"ENV": JSON.stringify(ENV)
			}
		})
	],

	devServer: {
		contentBase: helpers.root("public_html"),
		historyApiFallback: true,
		stats: "minimal",
		proxy: {
			"/api": {
				target: targetUrl(),
				secure: false
			}
		}
	}
});<commit_msg>added base href to dev<commit_after>var webpack = require("webpack");
var webpackMerge = require("webpack-merge");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var commonConfig = require("./webpack.common.js");
var helpers = require("./helpers");
var targetUrl = require("./target.js");

const ENV = process.env.NODE_ENV = process.env.ENV = "dev";

module.exports = webpackMerge(commonConfig, {
	devtool: "cheap-module-eval-source-map",

	output: {
		path: helpers.root("public_html"),
		publicPath: "http://localhost:7272",
		filename: "[name].js",
		chunkFilename: "[id].chunk.js"
	},

	plugins: [
		new ExtractTextPlugin("[name].css"),
		new webpack.DefinePlugin({
			"process.env": {
				"BASE_HREF": JSON.stringify("/"),
				"ENV": JSON.stringify(ENV)
			}
		})
	],

	devServer: {
		contentBase: helpers.root("public_html"),
		historyApiFallback: true,
		stats: "minimal",
		proxy: {
			"/api": {
				target: targetUrl(),
				secure: false
			}
		}
	}
});<|endoftext|>


<commit_before>var expect = require('expect.js');
var simple = require('simple-mock');
var fs = require('fs');

// Placeholders for stubbing built-in Sync Gateway support functions.
// More info: http://developer.couchbase.com/mobile/develop/guides/sync-gateway/sync-function-api-guide/index.html
var requireAccess;
var channel;

var syncFunction;

var defaultWriteChannel = 'write';

function init(syncFunctionPath) {
  // Load the contents of the sync function file into a global variable called syncFunction
  /*jslint evil: true */
  eval('syncFunction = ' + fs.readFileSync(syncFunctionPath).toString());
  /*jslint evil: false */

  requireAccess = simple.stub();
  channel = simple.stub();
}

function verifyRequireAccess(expectedChannels) {
  expect(requireAccess.callCount).to.be(1);

  checkChannels(expectedChannels, requireAccess.calls[0].arg);
}

function verifyChannelAssignment(expectedChannels) {
  expect(channel.callCount).to.be(1);

  checkChannels(expectedChannels, channel.calls[0].arg);
}

function checkChannels(expectedChannels, actualChannels) {
  if (!(expectedChannels instanceof Array)) {
    expectedChannels = [ expectedChannels ];
  }

  if (!(actualChannels instanceof Array)) {
    actualChannels = [ actualChannels ];
  }

  expect(actualChannels.length).to.equal(expectedChannels.length);

  for (var channelIndex = 0; channelIndex < expectedChannels.length; channelIndex++) {
    expect(actualChannels).to.contain(expectedChannels[channelIndex]);
  }
}

function verifyDocumentAccepted(doc, oldDoc, expectedChannels) {
  syncFunction(doc, oldDoc);

  verifyRequireAccess(expectedChannels);

  expect(channel.callCount).to.equal(1);

  var actualChannels = channel.calls[0].arg;
  if (expectedChannels instanceof Array && actualChannels instanceof Array) {
    for (var channelIndex = 0; channelIndex < expectedChannels.length; channelIndex++) {
      expect(actualChannels).to.contain(expectedChannels[channelIndex]);
    }
  } else {
    expect(actualChannels).to.contain(expectedChannels);
  }
}

function verifyDocumentCreated(doc, expectedChannels) {
  verifyDocumentAccepted(doc, undefined, expectedChannels || defaultWriteChannel);
}

function verifyDocumentReplaced(doc, oldDoc, expectedChannels) {
  verifyDocumentAccepted(doc, oldDoc, expectedChannels || defaultWriteChannel);
}

function verifyDocumentDeleted(oldDoc, expectedChannels) {
  verifyDocumentAccepted({ _id: oldDoc._id, _deleted: true }, oldDoc, expectedChannels || defaultWriteChannel);
}

function verifyDocumentRejected(doc, oldDoc, docType, expectedErrorMessages, expectedChannels) {
  expect(syncFunction).withArgs(doc, oldDoc).to.throwException(function(ex) {
    verifyValidationErrors(docType, expectedErrorMessages, ex);
  });

  verifyRequireAccess(expectedChannels);

  expect(channel.callCount).to.equal(0);
}

function verifyDocumentNotCreated(doc, docType, expectedErrorMessages, expectedChannels) {
  verifyDocumentRejected(doc, undefined, docType, expectedErrorMessages, expectedChannels || defaultWriteChannel);
}

function verifyDocumentNotReplaced(doc, oldDoc, docType, expectedErrorMessages, expectedChannels) {
  verifyDocumentRejected(doc, oldDoc, docType, expectedErrorMessages, expectedChannels || defaultWriteChannel);
}

function verifyDocumentNotDeleted(oldDoc, docType, expectedErrorMessages, expectedChannels) {
  verifyDocumentRejected({ _id: oldDoc._id, _deleted: true }, oldDoc, docType, expectedErrorMessages, expectedChannels || defaultWriteChannel);
}

function verifyValidationErrors(docType, expectedErrorMessages, exception) {
  if (!(expectedErrorMessages instanceof Array)) {
    expectedErrorMessages = [ expectedErrorMessages ];
  }

  // Used to split the leading component (e.g. "Invalid foobar document") from the validation error messages, which are separated by a colon
  var validationErrorRegex = /^([^:]+):\s*(.+)$/;

  var exceptionMessageMatches = validationErrorRegex.exec(exception.forbidden);
  expect(exceptionMessageMatches.length).to.be(3);

  var invalidDocMessage = exceptionMessageMatches[1].trim();
  expect(invalidDocMessage).to.equal('Invalid ' + docType + ' document');

  var actualErrorMessages = exceptionMessageMatches[2].trim().split(/;\s*/);
  expect(expectedErrorMessages.length).to.equal(actualErrorMessages.length);

  for (var errorIndex = 0; errorIndex < expectedErrorMessages.length; errorIndex++) {
    var expectedError = expectedErrorMessages[errorIndex];
    expect(actualErrorMessages).to.contain(expectedError);
  }
}

function verifyAccessDenied(doc, oldDoc, expectedChannels) {
  var expectedError = new Error('access denied');
  requireAccess = simple.stub().throwWith(expectedError);

  expect(syncFunction).withArgs(doc, oldDoc).to.throwException(function(ex) {
    expect(ex.message).to.equal(expectedError.message);
  });

  verifyRequireAccess(expectedChannels);
}

/**
 * Initializes the module with the sync function at the specified file path.
 *
 * @param {string} syncFunctionPath The path to the sync function to load
 */
exports.init = init;

/**
 * Attempts to write the specified doc and then verifies that it completed successfully with the expected channels.
 *
 * @param {Object} doc The document to write. May include property "_deleted=true" to simulate a delete operation.
 * @param {Object} oldDoc The document to replace or delete. May be null or undefined or include property "_deleted=true" to simulate a
 *                        create operation.
 * @param {string[]} expectedChannels The list of channels that are required to perform the operation. May be a string if only one channel
 *                                    is expected.
 */
exports.verifyDocumentAccepted = verifyDocumentAccepted;

/**
 * Attempts to create the specified doc and then verifies that it completed successfully with the expected channels.
 *
 * @param {Object} doc The new document
 * @param {string[]} [expectedChannels] The list of channels that are required to perform the operation. May be a string if only one channel
 *                                      is expected. Set to "write" by default if omitted.
 */
exports.verifyDocumentCreated = verifyDocumentCreated;

/**
 * Attempts to replace the specified doc and then verifies that it completed successfully with the expected channels.
 *
 * @param {Object} doc The updated document
 * @param {Object} oldDoc The document to replace
 * @param {string[]} [expectedChannels] The list of channels that are required to perform the operation. May be a string if only one channel
 *                                      is expected. Set to "write" by default if omitted.
 */
exports.verifyDocumentReplaced = verifyDocumentReplaced;

/**
 * Attempts to delete the specified doc and then verifies that it completed successfully with the expected channels.
 *
 * @param {Object} oldDoc The document to delete
 * @param {string[]} [expectedChannels] The list of channels that are required to perform the operation. May be a string if only one channel
 *                                      is expected. Set to "write" by default if omitted.
 */
exports.verifyDocumentDeleted = verifyDocumentDeleted;

/**
 * Attempts to write the specified doc and then verifies that it failed validation with the expected channels.
 *
 * @param {Object} doc The document to write. May include property "_deleted=true" to simulate a delete operation.
 * @param {Object} oldDoc The document to replace or delete. May be null or undefined or include property "_deleted=true" to simulate a
 *                        create operation.
 * @param {string} docType The document's type as specified in the document definition
 * @param {string[]} expectedErrorMessages The list of validation error messages that should be generated by the operation. May be a string
 *                                         if only one validation error is expected.
 * @param {string[]} expectedChannels The list of channels that are required to perform the operation. May be a string if only one channel
 *                                    is expected.
 */
exports.verifyDocumentRejected = verifyDocumentRejected;

/**
 * Attempts to create the specified doc and then verifies that it failed validation with the expected channels.
 *
 * @param {Object} doc The new document
 * @param {string} docType The document's type as specified in the document definition
 * @param {string[]} expectedErrorMessages The list of validation error messages that should be generated by the operation. May be a string
 *                                         if only one validation error is expected.
 * @param {string[]} [expectedChannels] The list of channels that are required to perform the operation. May be a string if only one channel
 *                                      is expected. Set to "write" by default if omitted.
 */
exports.verifyDocumentNotCreated = verifyDocumentNotCreated;

/**
 * Attempts to replace the specified doc and then verifies that it failed validation with the expected channels.
 *
 * @param {Object} doc The updated document
 * @param {Object} oldDoc The document to replace
 * @param {string} docType The document's type as specified in the document definition
 * @param {string[]} expectedErrorMessages The list of validation error messages that should be generated by the operation. May be a string
 *                                         if only one validation error is expected.
 * @param {string[]} [expectedChannels] The list of channels that are required to perform the operation. May be a string if only one channel
 *                                      is expected. Set to "write" by default if omitted.
 */
exports.verifyDocumentNotReplaced = verifyDocumentNotReplaced;

/**
 * Attempts to delete the specified doc and then verifies that it failed validation with the expected channels.
 *
 * @param {Object} oldDoc The document to delete
 * @param {string} docType The document's type as specified in the document definition
 * @param {string[]} expectedErrorMessages The list of validation error messages that should be generated by the operation. May be a string
 *                                         if only one validation error is expected.
 * @param {string[]} [expectedChannels] The list of channels that are required to perform the operation. May be a string if only one channel
 *                                      is expected. Set to "write" by default if omitted.
 */
exports.verifyDocumentNotDeleted = verifyDocumentNotDeleted;

/**
 * Verifies that the given exception result of a document write operation includes the specified validation error messages.
 *
 * @param {Object} docType The document's type as specified in the document definition
 * @param {string[]} expectedErrorMessages The list of validation error messages that should be contained in the exception. May be a string
 *                                         if only one validation error is expected.
 * @param {Object} exception The exception that was thrown by the sync function. Should include a "forbidden" property of type string.
 */
exports.verifyValidationErrors = verifyValidationErrors;

/**
 * Verifies that the specified the document that was created, replaced or deleted required the specified channels for access.
 *
 * @param {string[]} expectedChannels The list of channels that are required to perform the operation. May be a string if only one channel
 *                                    is expected.
 */
exports.verifyRequireAccess = verifyRequireAccess;

/**
 * Verifies that the specified channels were all assigned to a document that was created, replaced or deleted.
 *
 * @param {string[]} expectedChannels The list of channels that should have been assigned to the document. May be a string if only one
 *                                    channel is expected.
 */
exports.verifyChannelAssignment = verifyChannelAssignment;

/**
 * Verifies that authorization to write the document was denied.
 *
 * @param {Object} doc The document to attempt to write. May include property "_deleted=true" to simulate a delete operation.
 * @param {Object} oldDoc The document to replace or delete. May be null or undefined or include property "_deleted=true" to simulate a
 *                        create operation.
 * @param {string[]} expectedChannels The list of channels that are required to perform the operation. May be a string if only one channel
 *                                    is expected.
 */
exports.verifyAccessDenied = verifyAccessDenied;
<commit_msg>Minor update to test helper documentation<commit_after>var expect = require('expect.js');
var simple = require('simple-mock');
var fs = require('fs');

// Placeholders for stubbing built-in Sync Gateway support functions.
// More info: http://developer.couchbase.com/mobile/develop/guides/sync-gateway/sync-function-api-guide/index.html
var requireAccess;
var channel;

var syncFunction;

var defaultWriteChannel = 'write';

function init(syncFunctionPath) {
  // Load the contents of the sync function file into a global variable called syncFunction
  /*jslint evil: true */
  eval('syncFunction = ' + fs.readFileSync(syncFunctionPath).toString());
  /*jslint evil: false */

  requireAccess = simple.stub();
  channel = simple.stub();
}

function verifyRequireAccess(expectedChannels) {
  expect(requireAccess.callCount).to.be(1);

  checkChannels(expectedChannels, requireAccess.calls[0].arg);
}

function verifyChannelAssignment(expectedChannels) {
  expect(channel.callCount).to.be(1);

  checkChannels(expectedChannels, channel.calls[0].arg);
}

function checkChannels(expectedChannels, actualChannels) {
  if (!(expectedChannels instanceof Array)) {
    expectedChannels = [ expectedChannels ];
  }

  if (!(actualChannels instanceof Array)) {
    actualChannels = [ actualChannels ];
  }

  expect(actualChannels.length).to.equal(expectedChannels.length);

  for (var channelIndex = 0; channelIndex < expectedChannels.length; channelIndex++) {
    expect(actualChannels).to.contain(expectedChannels[channelIndex]);
  }
}

function verifyDocumentAccepted(doc, oldDoc, expectedChannels) {
  syncFunction(doc, oldDoc);

  verifyRequireAccess(expectedChannels);

  expect(channel.callCount).to.equal(1);

  var actualChannels = channel.calls[0].arg;
  if (expectedChannels instanceof Array && actualChannels instanceof Array) {
    for (var channelIndex = 0; channelIndex < expectedChannels.length; channelIndex++) {
      expect(actualChannels).to.contain(expectedChannels[channelIndex]);
    }
  } else {
    expect(actualChannels).to.contain(expectedChannels);
  }
}

function verifyDocumentCreated(doc, expectedChannels) {
  verifyDocumentAccepted(doc, undefined, expectedChannels || defaultWriteChannel);
}

function verifyDocumentReplaced(doc, oldDoc, expectedChannels) {
  verifyDocumentAccepted(doc, oldDoc, expectedChannels || defaultWriteChannel);
}

function verifyDocumentDeleted(oldDoc, expectedChannels) {
  verifyDocumentAccepted({ _id: oldDoc._id, _deleted: true }, oldDoc, expectedChannels || defaultWriteChannel);
}

function verifyDocumentRejected(doc, oldDoc, docType, expectedErrorMessages, expectedChannels) {
  expect(syncFunction).withArgs(doc, oldDoc).to.throwException(function(ex) {
    verifyValidationErrors(docType, expectedErrorMessages, ex);
  });

  verifyRequireAccess(expectedChannels);

  expect(channel.callCount).to.equal(0);
}

function verifyDocumentNotCreated(doc, docType, expectedErrorMessages, expectedChannels) {
  verifyDocumentRejected(doc, undefined, docType, expectedErrorMessages, expectedChannels || defaultWriteChannel);
}

function verifyDocumentNotReplaced(doc, oldDoc, docType, expectedErrorMessages, expectedChannels) {
  verifyDocumentRejected(doc, oldDoc, docType, expectedErrorMessages, expectedChannels || defaultWriteChannel);
}

function verifyDocumentNotDeleted(oldDoc, docType, expectedErrorMessages, expectedChannels) {
  verifyDocumentRejected({ _id: oldDoc._id, _deleted: true }, oldDoc, docType, expectedErrorMessages, expectedChannels || defaultWriteChannel);
}

function verifyValidationErrors(docType, expectedErrorMessages, exception) {
  if (!(expectedErrorMessages instanceof Array)) {
    expectedErrorMessages = [ expectedErrorMessages ];
  }

  // Used to split the leading component (e.g. "Invalid foobar document") from the validation error messages, which are separated by a colon
  var validationErrorRegex = /^([^:]+):\s*(.+)$/;

  var exceptionMessageMatches = validationErrorRegex.exec(exception.forbidden);
  expect(exceptionMessageMatches.length).to.be(3);

  var invalidDocMessage = exceptionMessageMatches[1].trim();
  expect(invalidDocMessage).to.equal('Invalid ' + docType + ' document');

  var actualErrorMessages = exceptionMessageMatches[2].trim().split(/;\s*/);
  expect(expectedErrorMessages.length).to.equal(actualErrorMessages.length);

  for (var errorIndex = 0; errorIndex < expectedErrorMessages.length; errorIndex++) {
    var expectedError = expectedErrorMessages[errorIndex];
    expect(actualErrorMessages).to.contain(expectedError);
  }
}

function verifyAccessDenied(doc, oldDoc, expectedChannels) {
  var expectedError = new Error('access denied');
  requireAccess = simple.stub().throwWith(expectedError);

  expect(syncFunction).withArgs(doc, oldDoc).to.throwException(function(ex) {
    expect(ex.message).to.equal(expectedError.message);
  });

  verifyRequireAccess(expectedChannels);
}

/**
 * Initializes the module with the sync function at the specified file path.
 *
 * @param {string} syncFunctionPath The path to the sync function to load
 */
exports.init = init;

/**
 * Attempts to write the specified doc and then verifies that it completed successfully with the expected channels.
 *
 * @param {Object} doc The document to write. May include property "_deleted=true" to simulate a delete operation.
 * @param {Object} oldDoc The document to replace or delete. May be null or undefined or include property "_deleted=true" to simulate a
 *                        create operation.
 * @param {string[]} expectedChannels The list of channels that are required to perform the operation. May be a string if only one channel
 *                                    is expected.
 */
exports.verifyDocumentAccepted = verifyDocumentAccepted;

/**
 * Attempts to create the specified doc and then verifies that it completed successfully with the expected channels.
 *
 * @param {Object} doc The new document
 * @param {string[]} [expectedChannels] The list of channels that are required to perform the operation. May be a string if only one channel
 *                                      is expected. Set to "write" by default if omitted.
 */
exports.verifyDocumentCreated = verifyDocumentCreated;

/**
 * Attempts to replace the specified doc and then verifies that it completed successfully with the expected channels.
 *
 * @param {Object} doc The updated document
 * @param {Object} oldDoc The document to replace
 * @param {string[]} [expectedChannels] The list of channels that are required to perform the operation. May be a string if only one channel
 *                                      is expected. Set to "write" by default if omitted.
 */
exports.verifyDocumentReplaced = verifyDocumentReplaced;

/**
 * Attempts to delete the specified doc and then verifies that it completed successfully with the expected channels.
 *
 * @param {Object} oldDoc The document to delete
 * @param {string[]} [expectedChannels] The list of channels that are required to perform the operation. May be a string if only one channel
 *                                      is expected. Set to "write" by default if omitted.
 */
exports.verifyDocumentDeleted = verifyDocumentDeleted;

/**
 * Attempts to write the specified doc and then verifies that it failed validation with the expected channels.
 *
 * @param {Object} doc The document to write. May include property "_deleted=true" to simulate a delete operation.
 * @param {Object} oldDoc The document to replace or delete. May be null or undefined or include property "_deleted=true" to simulate a
 *                        create operation.
 * @param {string} docType The document's type as specified in the document definition
 * @param {string[]} expectedErrorMessages The list of validation error messages that should be generated by the operation. May be a string
 *                                         if only one validation error is expected.
 * @param {string[]} expectedChannels The list of channels that are required to perform the operation. May be a string if only one channel
 *                                    is expected.
 */
exports.verifyDocumentRejected = verifyDocumentRejected;

/**
 * Attempts to create the specified doc and then verifies that it failed validation with the expected channels.
 *
 * @param {Object} doc The new document
 * @param {string} docType The document's type as specified in the document definition
 * @param {string[]} expectedErrorMessages The list of validation error messages that should be generated by the operation. May be a string
 *                                         if only one validation error is expected.
 * @param {string[]} [expectedChannels] The list of channels that are required to perform the operation. May be a string if only one channel
 *                                      is expected. Set to "write" by default if omitted.
 */
exports.verifyDocumentNotCreated = verifyDocumentNotCreated;

/**
 * Attempts to replace the specified doc and then verifies that it failed validation with the expected channels.
 *
 * @param {Object} doc The updated document
 * @param {Object} oldDoc The document to replace
 * @param {string} docType The document's type as specified in the document definition
 * @param {string[]} expectedErrorMessages The list of validation error messages that should be generated by the operation. May be a string
 *                                         if only one validation error is expected.
 * @param {string[]} [expectedChannels] The list of channels that are required to perform the operation. May be a string if only one channel
 *                                      is expected. Set to "write" by default if omitted.
 */
exports.verifyDocumentNotReplaced = verifyDocumentNotReplaced;

/**
 * Attempts to delete the specified doc and then verifies that it failed validation with the expected channels.
 *
 * @param {Object} oldDoc The document to delete
 * @param {string} docType The document's type as specified in the document definition
 * @param {string[]} expectedErrorMessages The list of validation error messages that should be generated by the operation. May be a string
 *                                         if only one validation error is expected.
 * @param {string[]} [expectedChannels] The list of channels that are required to perform the operation. May be a string if only one channel
 *                                      is expected. Set to "write" by default if omitted.
 */
exports.verifyDocumentNotDeleted = verifyDocumentNotDeleted;

/**
 * Verifies that the given exception result of a document write operation includes the specified validation error messages.
 *
 * @param {Object} docType The document's type as specified in the document definition
 * @param {string[]} expectedErrorMessages The list of validation error messages that should be contained in the exception. May be a string
 *                                         if only one validation error is expected.
 * @param {Object} exception The exception that was thrown by the sync function. Should include a "forbidden" property of type string.
 */
exports.verifyValidationErrors = verifyValidationErrors;

/**
 * Verifies that the specified the document that was created, replaced or deleted required the specified channels for access.
 *
 * @param {string[]} expectedChannels The list of channels that are required to perform the operation. May be a string if only one channel
 *                                    is expected.
 */
exports.verifyRequireAccess = verifyRequireAccess;

/**
 * Verifies that the specified channels were all assigned to a document that was created, replaced or deleted.
 *
 * @param {string[]} expectedChannels The list of channels that should have been assigned to the document. May be a string if only one
 *                                    channel is expected.
 */
exports.verifyChannelAssignment = verifyChannelAssignment;

/**
 * Verifies that the sync function throws an error when authorization to create/replace/delete a document is denied.
 *
 * @param {Object} doc The document to attempt to write. May include property "_deleted=true" to simulate a delete operation.
 * @param {Object} oldDoc The document to replace or delete. May be null or undefined or include property "_deleted=true" to simulate a
 *                        create operation.
 * @param {string[]} expectedChannels The list of channels that are required to perform the operation. May be a string if only one channel
 *                                    is expected.
 */
exports.verifyAccessDenied = verifyAccessDenied;
<|endoftext|>


<commit_before>// This config is used in both the
// frontend as well as the web server.

// see https://github.com/askmike/gekko/blob/stable/docs/installing_gekko_on_a_server.md

const CONFIG = {
  headless: false,
  api: {
    host: '127.0.0.1',
    port: 3000,
  },
  ui: {
    ssl: false,
    host: 'v22017105055054583.bestsrv.de',
    port: 443,
    path: '/'
  },
  adapter: 'sqlite'
}

if(typeof window === 'undefined')
  module.exports = CONFIG;
else
  window.CONFIG = CONFIG;
<commit_msg>Update UIconfig.js<commit_after>// This config is used in both the
// frontend as well as the web server.

// see https://github.com/askmike/gekko/blob/stable/docs/installing_gekko_on_a_server.md

const CONFIG = {
  headless: true,
  api: {
    host: '127.0.0.1',
    port: 3000,
  },
  ui: {
    ssl: false,
    host: 'v22017105055054583.bestsrv.de',
    port: 443,
    path: '/'
  },
  adapter: 'sqlite'
}

if(typeof window === 'undefined')
  module.exports = CONFIG;
else
  window.CONFIG = CONFIG;
<|endoftext|>


<commit_before>Package.describe({
  summary: "Password support for accounts",
  version: "1.1.11"
});

Package.onUse(function(api) {
  api.use('npm-bcrypt@0.8.6_1');

  api.use([
    'accounts-base',
    'srp',
    'sha',
    'ejson',
    'ddp'
  ], ['client', 'server']);

  // Export Accounts (etc) to packages using this one.
  api.imply('accounts-base', ['client', 'server']);

  api.use('email', ['server']);
  api.use('random', ['server']);
  api.use('check');
  api.use('underscore');
  api.use('ecmascript');

  api.addFiles('email_templates.js', 'server');
  api.addFiles('password_server.js', 'server');
  api.addFiles('password_client.js', 'client');
});

Package.onTest(function(api) {
  api.use(['accounts-password', 'tinytest', 'test-helpers', 'tracker',
           'accounts-base', 'random', 'email', 'underscore', 'check',
           'ddp', 'ecmascript']);
  api.addFiles('password_tests_setup.js', 'server');
  api.addFiles('password_tests.js', ['client', 'server']);
  api.addFiles('email_tests_setup.js', 'server');
  api.addFiles('email_tests.js', 'client');
});
<commit_msg>Use npm-bcrypt@0.8.6_2 in accounts-password.<commit_after>Package.describe({
  summary: "Password support for accounts",
  version: "1.1.12"
});

Package.onUse(function(api) {
  api.use('npm-bcrypt@0.8.6_2');

  api.use([
    'accounts-base',
    'srp',
    'sha',
    'ejson',
    'ddp'
  ], ['client', 'server']);

  // Export Accounts (etc) to packages using this one.
  api.imply('accounts-base', ['client', 'server']);

  api.use('email', ['server']);
  api.use('random', ['server']);
  api.use('check');
  api.use('underscore');
  api.use('ecmascript');

  api.addFiles('email_templates.js', 'server');
  api.addFiles('password_server.js', 'server');
  api.addFiles('password_client.js', 'client');
});

Package.onTest(function(api) {
  api.use(['accounts-password', 'tinytest', 'test-helpers', 'tracker',
           'accounts-base', 'random', 'email', 'underscore', 'check',
           'ddp', 'ecmascript']);
  api.addFiles('password_tests_setup.js', 'server');
  api.addFiles('password_tests.js', ['client', 'server']);
  api.addFiles('email_tests_setup.js', 'server');
  api.addFiles('email_tests.js', 'client');
});
<|endoftext|>


<commit_before>const CONTROL_GROUP = '
 \

 \
		 \
		 \
		<input type="text" class="input-nano abbreviation" placeholder="" maxlength="2"> \

 \
			 \

 \
		<input type="color" class="color"> \
		<button class="btn reset">Reset Color</button> \
		<input type="hidden" name="customColorSet" value="false"> \

 \

';

const NO_TILES_ADDED_TEXT = "No tiles added.";

const SUBMIT_BUTTON_SAVING_TEXT = "Saving…";
const SUBMIT_BUTTON_SUBMIT_TEXT = "Save";

const FAVICON_LOAD_FAIL_TITLE = "Failed to retrieve favicon!";
const FAVICON_LOAD_FAIL_URL_REPLACE = "#{url}";
const FAVICON_LOAD_FAIL_MESSAGE = "Could not retrieve favicon for #{url}. Check the URL and ensure the site does not redirect.";

$(document).ready(function() {
	chrome.storage.sync.remove("sites");

	chrome.storage.sync.get(null, function(items) {
		console.log(items);
	});

	var sites = [];

	sitesReload();

	chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
		console.log('Message received: ' + request.message);

		if (request.message == "saved") {
			sitesReload();
		}
	});

	$("#color-regenerate-btn").on("click", function(e) {
		e.preventDefault();

		makeSites(true);
	});

	function sitesReload() {
		getSites(function (items) {
			$("#sites").html("");

			if (!items || items.length == 0) {
				$("#sites").prepend(NO_TILES_ADDED_TEXT);
			} else {
				sites = items;

				sites = sites.reverse();

				for (var i = 0; i < sites.length; i++) {
					var newControlGroup = CONTROL_GROUP;
					var site = sites[i];

					newControlGroup = $(newControlGroup);
					newControlGroup.find('span.url').html(site.url);
					newControlGroup.find('input.abbreviation').val(site.abbreviation);
					newControlGroup.find('a.remove').on('click', function(e) {
						removeControlGroup(e.target);
					});

					newControlGroup.find('input.color').on("change", function() {
						newControlGroup.find('button.reset').show();
						newControlGroup.find('input[name="customColorSet"]').val("true");

						makeSites();
					});

					newControlGroup.find('button.reset').on("click", function(e) {
						e.preventDefault();
						newControlGroup.find('input[name="customColorSet"]').val("false");
						$(this).hide();
						newControlGroup.find('input.color').val(rgbToHex(site.color["red"], site.color["green"], site.color["blue"]));

						makeSites();
					});

					if (site.customColor != undefined) {
						newControlGroup.find('button.reset').show();
						newControlGroup.find('input[name="customColorSet"]').val("true");
						newControlGroup.find('input.color').val(rgbToHex(site.customColor["red"], site.customColor["green"], site.customColor["blue"]));
					} else {
						newControlGroup.find('button.reset').hide();
						newControlGroup.find('input[name="customColorSet"]').val("false");
						newControlGroup.find('input.color').val(rgbToHex(site.color["red"], site.color["green"], site.color["blue"]));
					}

					$("#sites").prepend(newControlGroup);
				}
			}

			$("#sites").sortable({
				handle: '.handle',
				axis: 'y',
				update: function(e, ui) {
					makeSites();
				}
			});

			$(".container").removeClass("hidden");
		});
	}

	function removeControlGroup(element) {
		parent = $(element).parents('.control-group');
		chrome.extension.sendMessage({ message: "delete", url:parent.find('span.url').html() }, function(response) { });
	}

	function makeSites(forceColorRegeneration) {
		if (forceColorRegeneration == undefined) {
			forceColorRegeneration = false;
		}

		$("#color-regenerate-btn").attr("disabled", "disabled");

		var fields = [];

		$('#sites .site-controls').each(function(index, element) {
			urlField = $(this).children('span.url').eq(0);
			abbreviationField = $(this).children('input:text.abbreviation').eq(0);

			var url = urlField.html();
			var abbreviation = abbreviationField.val();

			if (!url.match(/^(http|https):\/\//)) {
				url = "http://" + url;

				urlField.html(url);
			}

			if (!abbreviation) {
				abbreviation = makeAbbreviation(getHostname(url));

				abbreviationField.val(abbreviation);
			}

			fields[index] = {};
			fields[index].url = url;
			fields[index].abbreviation = abbreviation;
			if ($(this).children('input[name="customColorSet"]').val() == "true") {
				fields[index].customColor = hexToRgb($(this).children('input[type=color]').val());
			}
		});

		getSites(function(sites) {
			for (var i = 0; i < fields.length; i++) {
				fields[i].color = null;
			}

			var numberOfSitesRequiringColor = 0;

		 	if (!forceColorRegeneration) {
				if (sites != null && sites.length != 0) {
					for (var i = 0; i < sites.length; i++) {
						for (var j = 0; j < fields.length; j++) {
							if (sites[i].url == fields[j].url) {
								fields[j].color = sites[i].color;
							}
						}
					}
				}
			} else {
				numberOfSitesRequiringColor = fields.length;

				console.log(Math.min(numberOfSitesRequiringColor, 0) + " sites require a color check");
			}

			var siteSaved = false;

			function saveIfReady() {
				if (!siteSaved && numberOfSitesRequiringColor <= 0) {
					saveSites(fields);

					siteSaved = true;

					$("#color-regenerate-btn").removeAttr("disabled");
				}
			}

			for (var i = 0; i < fields.length; i++) {
				(function() {
					var site = fields[i];

					if (!site.color) {
						setSiteColor(site, function(site, error) {
							numberOfSitesRequiringColor--;

							console.log((fields.length - numberOfSitesRequiringColor) + " / " + fields.length + " – Got color for " + site.url);

							saveIfReady();
						});
					} else {
						saveIfReady();
					}
				})();
			}
		});
	}
});<commit_msg>Fix changing custom colors for sites other than the first one.<commit_after>const CONTROL_GROUP = '
 \

 \
		 \
		 \
		<input type="text" class="input-nano abbreviation" placeholder="" maxlength="2"> \

 \
			 \

 \
		<input type="color" class="color"> \
		<button class="btn reset">Reset Color</button> \
		<input type="hidden" name="customColorSet" value="false"> \

 \

';

const NO_TILES_ADDED_TEXT = "No tiles added.";

const SUBMIT_BUTTON_SAVING_TEXT = "Saving…";
const SUBMIT_BUTTON_SUBMIT_TEXT = "Save";

const FAVICON_LOAD_FAIL_TITLE = "Failed to retrieve favicon!";
const FAVICON_LOAD_FAIL_URL_REPLACE = "#{url}";
const FAVICON_LOAD_FAIL_MESSAGE = "Could not retrieve favicon for #{url}. Check the URL and ensure the site does not redirect.";

$(document).ready(function() {
	chrome.storage.sync.remove("sites");

	chrome.storage.sync.get(null, function(items) {
		console.log(items);
	});

	var sites = [];

	sitesReload();

	chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
		console.log('Message received: ' + request.message);

		if (request.message == "saved") {
			sitesReload();
		}
	});

	$("#color-regenerate-btn").on("click", function(e) {
		e.preventDefault();

		makeSites(true);
	});

	function sitesReload() {
		getSites(function (items) {
			$("#sites").html("");

			if (!items || items.length == 0) {
				$("#sites").prepend(NO_TILES_ADDED_TEXT);
			} else {
				sites = items;

				sites = sites.reverse();

				for (var i = 0; i < sites.length; i++) {
					(function() {
						var newControlGroup = CONTROL_GROUP;
						var site = sites[i];

						newControlGroup = $(newControlGroup);
						newControlGroup.find('span.url').html(site.url);
						newControlGroup.find('input.abbreviation').val(site.abbreviation);
						newControlGroup.find('a.remove').on('click', function(e) {
							removeControlGroup(e.target);
						});

						newControlGroup.find('input.color').on("change", function() {
							newControlGroup.find('button.reset').show();
							newControlGroup.find('input[name="customColorSet"]').val("true");

							makeSites();
						});

						newControlGroup.find('button.reset').on("click", function(e) {
							e.preventDefault();
							$(this).hide();
							newControlGroup.find('input[name="customColorSet"]').val("false");
							newControlGroup.find('input.color').val(rgbToHex(site.color["red"], site.color["green"], site.color["blue"]));

							makeSites();
						});

						if (site.customColor != undefined) {
							newControlGroup.find('button.reset').show();
							newControlGroup.find('input[name="customColorSet"]').val("true");
							newControlGroup.find('input.color').val(rgbToHex(site.customColor["red"], site.customColor["green"], site.customColor["blue"]));
						} else {
							newControlGroup.find('button.reset').hide();
							newControlGroup.find('input[name="customColorSet"]').val("false");
							newControlGroup.find('input.color').val(rgbToHex(site.color["red"], site.color["green"], site.color["blue"]));
						}

						$("#sites").prepend(newControlGroup);
					})();
				}
			}

			$("#sites").sortable({
				handle: '.handle',
				axis: 'y',
				update: function(e, ui) {
					makeSites();
				}
			});

			$(".container").removeClass("hidden");
		});
	}

	function removeControlGroup(element) {
		parent = $(element).parents('.control-group');
		chrome.extension.sendMessage({ message: "delete", url:parent.find('span.url').html() }, function(response) { });
	}

	function makeSites(forceColorRegeneration) {
		if (forceColorRegeneration == undefined) {
			forceColorRegeneration = false;
		}

		$("#color-regenerate-btn").attr("disabled", "disabled");

		var fields = [];

		$('#sites .site-controls').each(function(index, element) {
			urlField = $(this).children('span.url').eq(0);
			abbreviationField = $(this).children('input:text.abbreviation').eq(0);

			var url = urlField.html();
			var abbreviation = abbreviationField.val();

			if (!url.match(/^(http|https):\/\//)) {
				url = "http://" + url;

				urlField.html(url);
			}

			if (!abbreviation) {
				abbreviation = makeAbbreviation(getHostname(url));

				abbreviationField.val(abbreviation);
			}

			fields[index] = {};
			fields[index].url = url;
			fields[index].abbreviation = abbreviation;
			if ($(this).children('input[name="customColorSet"]').val() == "true") {
				fields[index].customColor = hexToRgb($(this).children('input[type=color]').val());
			}
		});

		getSites(function(sites) {
			for (var i = 0; i < fields.length; i++) {
				fields[i].color = null;
			}

			var numberOfSitesRequiringColor = 0;

		 	if (!forceColorRegeneration) {
				if (sites != null && sites.length != 0) {
					for (var i = 0; i < sites.length; i++) {
						for (var j = 0; j < fields.length; j++) {
							if (sites[i].url == fields[j].url) {
								fields[j].color = sites[i].color;
								break;
							}
						}
					}
				}
			} else {
				numberOfSitesRequiringColor = fields.length;

				console.log(Math.min(numberOfSitesRequiringColor, 0) + " sites require a color check");
			}

			var siteSaved = false;

			function saveIfReady() {
				if (!siteSaved && numberOfSitesRequiringColor <= 0) {
					saveSites(fields);

					siteSaved = true;

					$("#color-regenerate-btn").removeAttr("disabled");
				}
			}

			for (var i = 0; i < fields.length; i++) {
				(function() {
					var site = fields[i];

					if (!site.color) {
						setSiteColor(site, function(site, error) {
							numberOfSitesRequiringColor--;

							console.log((fields.length - numberOfSitesRequiringColor) + " / " + fields.length + " – Got color for " + site.url);

							saveIfReady();
						});
					} else {
						saveIfReady();
					}
				})();
			}
		});
	}
});<|endoftext|>