<commit_before>module.exports = [
	{
		description: 'transpiles a class declaration',

		input: `
			class Foo {
				constructor ( answer ) {
					this.answer = answer;
				}
			}`,

		output: `
			var Foo = function Foo ( answer ) {
				this.answer = answer;
			};`
	},

	{
		description: 'transpiles a class declaration with a non-constructor method',

		input: `
			class Foo {
				constructor ( answer ) {
					this.answer = answer;
				}

				bar ( str ) {
					return str + 'bar';
				}
			}`,

		output: `
			var Foo = function Foo ( answer ) {
				this.answer = answer;
			};

			Foo.prototype.bar = function bar ( str ) {
				return str + 'bar';
			};`
	},

	{
		description: 'transpiles a class declaration without a constructor function',

		input: `
			class Foo {
				bar ( str ) {
					return str + 'bar';
				}
			}`,

		output: `
			var Foo = function Foo () {};

			Foo.prototype.bar = function bar ( str ) {
				return str + 'bar';
			};`
	},

	{
		description: 'deshadows method names',

		input: `
			var bar = 'x';

			class Foo {
				bar ( str ) {
					return str + 'bar';
				}
			}`,

		output: `
			var bar = 'x';

			var Foo = function Foo () {};

			Foo.prototype.bar = function bar$1 ( str ) {
				return str + 'bar';
			};`
	},

	{
		description: 'transpiles a class declaration with a static method',

		input: `
			class Foo {
				bar ( str ) {
					return str + 'bar';
				}

				static baz ( str ) {
					return str + 'baz';
				}
			}`,

		output: `
			var Foo = function Foo () {};

			Foo.prototype.bar = function bar ( str ) {
				return str + 'bar';
			};

			Foo.baz = function baz ( str ) {
				return str + 'baz';
			};`
	},

	{
		description: 'transpiles a subclass',

		input: `
			class Foo extends Bar {
				baz ( str ) {
					return str + 'baz';
				}
			}`,

		output: `
			var Foo = (function (Bar) {
				function Foo () {
					Bar.apply(this, arguments);
				}

				if ( Bar ) Foo.__proto__ = Bar;
				Foo.prototype = Object.create( Bar && Bar.prototype );
				Foo.prototype.constructor = Foo;

				Foo.prototype.baz = function baz ( str ) {
					return str + 'baz';
				};

				return Foo;
			}(Bar));`
	},

	{
		description: 'transpiles a subclass with super calls',

		input: `
			class Foo extends Bar {
				constructor ( x ) {
					super( x );
					this.y = 'z';
				}

				baz ( a, b, c ) {
					super.baz( a, b, c );
				}
			}`,

		output: `
			var Foo = (function (Bar) {
				function Foo ( x ) {
					Bar.call( this, x );
					this.y = 'z';
				}

				if ( Bar ) Foo.__proto__ = Bar;
				Foo.prototype = Object.create( Bar && Bar.prototype );
				Foo.prototype.constructor = Foo;

				Foo.prototype.baz = function baz ( a, b, c ) {
					Bar.prototype.baz.call( this, a, b, c );
				};

				return Foo;
			}(Bar));`
	},

	{
		description: 'transpiles export default class',
		options: { transforms: { moduleExport: false } },

		input: `
			export default class Foo {
				bar () {}
			}`,

		output: `
			var Foo = function Foo () {};

			Foo.prototype.bar = function bar () {};

			export default Foo;`
	},

	{
		description: 'transpiles export default subclass',
		options: { transforms: { moduleExport: false } },

		input: `
			export default class Foo extends Bar {
				bar () {}
			}`,

		output: `
			var Foo = (function (Bar) {
				function Foo () {
					Bar.apply(this, arguments);
				}

				if ( Bar ) Foo.__proto__ = Bar;
				Foo.prototype = Object.create( Bar && Bar.prototype );
				Foo.prototype.constructor = Foo;

				Foo.prototype.bar = function bar () {};

				return Foo;
			}(Bar));

			export default Foo;`
	},

	{
		description: 'transpiles export default subclass with subsequent statement',
		options: { transforms: { moduleExport: false } },

		input: `
			export default class Foo extends Bar {
				bar () {}
			}

			new Foo().bar();`,

		output: `
			var Foo = (function (Bar) {
				function Foo () {
					Bar.apply(this, arguments);
				}

				if ( Bar ) Foo.__proto__ = Bar;
				Foo.prototype = Object.create( Bar && Bar.prototype );
				Foo.prototype.constructor = Foo;

				Foo.prototype.bar = function bar () {};

				return Foo;
			}(Bar));

			export default Foo;

			new Foo().bar();`
	},

	{
		description: 'transpiles empty class',

		input: `class Foo {}`,
		output: `var Foo = function Foo () {};`
	},

	{
		description: 'transpiles an anonymous empty class expression',

		input: `
			var Foo = class {};`,

		output: `
			var Foo = (function () {
				function Foo () {}

				return Foo;
			}());`
	},

	{
		description: 'transpiles an anonymous class expression with a constructor',

		input: `
			var Foo = class {
				constructor ( x ) {
					this.x = x;
				}
			};`,

		output: `
			var Foo = (function () {
				function Foo ( x ) {
					this.x = x;
				}

				return Foo;
			}());`
	},

	{
		description: 'transpiles an anonymous class expression with a non-constructor method',

		input: `
			var Foo = class {
				bar ( x ) {
					console.log( x );
				}
			};`,

		output: `
			var Foo = (function () {
				function Foo () {}

				Foo.prototype.bar = function bar ( x ) {
					console.log( x );
				};

				return Foo;
			}());`
	},

	{
		description: 'allows constructor to be in middle of body',

		input: `
			class Foo {
				before () {
					// code goes here
				}

				constructor () {
					// constructor goes here
				}

				after () {
					// code goes here
				}
			}`,

		output: `
			var Foo = function Foo () {
				// constructor goes here
			};

			Foo.prototype.before = function before () {
				// code goes here
			};

			Foo.prototype.after = function after () {
				// code goes here
			};`
	},

	{
		description: 'allows constructor to be at end of body',

		input: `
			class Foo {
				before () {
					// code goes here
				}

				constructor () {
					// constructor goes here
				}
			}`,

		output: `
			var Foo = function Foo () {
				// constructor goes here
			};

			Foo.prototype.before = function before () {
				// code goes here
			};`
	},

	{
		description: 'transpiles getters and setters',

		input: `
			class Circle {
				constructor ( radius ) {
					this.radius = radius;
				}

				get area () {
					return Math.PI * Math.pow( this.radius, 2 );
				}

				set area ( area ) {
					this.radius = Math.sqrt( area / Math.PI );
				}

				static get description () {
					return 'round';
				}
			}`,

		output: `
			var Circle = function Circle ( radius ) {
				this.radius = radius;
			};

			var prototypeAccessors = { area: {} };
			var staticAccessors = { description: {} };

			prototypeAccessors.area.get = function () {
				return Math.PI * Math.pow( this.radius, 2 );
			};

			prototypeAccessors.area.set = function ( area ) {
				this.radius = Math.sqrt( area / Math.PI );
			};

			staticAccessors.description.get = function () {
				return 'round';
			};

			Object.defineProperties( Circle.prototype, prototypeAccessors );
			Object.defineProperties( Circle, staticAccessors );`
	},

	{
		description: 'transpiles getters and setters in subclass',

		input: `
			class Circle extends Shape {
				constructor ( radius ) {
					super();
					this.radius = radius;
				}

				get area () {
					return Math.PI * Math.pow( this.radius, 2 );
				}

				set area ( area ) {
					this.radius = Math.sqrt( area / Math.PI );
				}

				static get description () {
					return 'round';
				}
			}`,

		output: `
			var Circle = (function (Shape) {
				function Circle ( radius ) {
					Shape.call(this);
					this.radius = radius;
				}

				if ( Shape ) Circle.__proto__ = Shape;
				Circle.prototype = Object.create( Shape && Shape.prototype );
				Circle.prototype.constructor = Circle;

				var prototypeAccessors = { area: {} };
				var staticAccessors = { description: {} };

				prototypeAccessors.area.get = function () {
					return Math.PI * Math.pow( this.radius, 2 );
				};

				prototypeAccessors.area.set = function ( area ) {
					this.radius = Math.sqrt( area / Math.PI );
				};

				staticAccessors.description.get = function () {
					return 'round';
				};

				Object.defineProperties( Circle.prototype, prototypeAccessors );
				Object.defineProperties( Circle, staticAccessors );

				return Circle;
			}(Shape));`
	},

	{
		description: 'can be disabled with `transforms.classes: false`',
		options: { transforms: { classes: false } },

		input: `
			class Foo extends Bar {
				constructor ( answer ) {
					super();
					this.answer = answer;
				}
			}`,

		output: `
			class Foo extends Bar {
				constructor ( answer ) {
					super();
					this.answer = answer;
				}
			}`
	},

	{
		description: 'declaration extends from an expression (#15)',

		input: `
			const q = {a: class {}};

			class b extends q.a {
				c () {}
			}`,

		output: `
			var q = {a: (function () {
				function anonymous () {}

				return anonymous;
			}())};

			var b = (function (superclass) {
				function b () {
					superclass.apply(this, arguments);
				}

				if ( superclass ) b.__proto__ = superclass;
				b.prototype = Object.create( superclass && superclass.prototype );
				b.prototype.constructor = b;

				b.prototype.c = function c () {};

				return b;
			}(q.a));`
	},

	{
		description: 'expression extends from an expression (#15)',

		input: `
			const q = {a: class {}};

			const b = class b extends q.a {
				c () {}
			};`,

		output: `
			var q = {a: (function () {
				function anonymous () {}

				return anonymous;
			}())};

			var b = (function (superclass) {
				function b () {
					superclass.apply(this, arguments);
				}

				if ( superclass ) b.__proto__ = superclass;
				b.prototype = Object.create( superclass && superclass.prototype );
				b.prototype.constructor = b;

				b.prototype.c = function c () {};

				return b;
			}(q.a));`
	},

	{
		description: 'expression extends from an expression with super calls (#31)',

		input: `
			class b extends x.y.z {
				constructor() {
					super();
				}
			}`,

		output: `
			var b = (function (superclass) {
				function b() {
					superclass.call(this);
				}

				if ( superclass ) b.__proto__ = superclass;
				b.prototype = Object.create( superclass && superclass.prototype );
				b.prototype.constructor = b;

				return b;
			}(x.y.z));`
	},

	{
		description: 'anonymous expression extends named class (#31)',

		input: `
			SubClass = class extends SuperClass {
				constructor() {
					super();
				}
			};`,

		output: `
			SubClass = (function (SuperClass) {
				function SubClass() {
					SuperClass.call(this);
				}

				if ( SuperClass ) SubClass.__proto__ = SuperClass;
				SubClass.prototype = Object.create( SuperClass && SuperClass.prototype );
				SubClass.prototype.constructor = SubClass;

				return SubClass;
			}(SuperClass));`
	},

	{
		description: 'deindents a function body with destructuring (#22)',

		input: `
			class Foo {
				constructor ( options ) {
					const {
						a,
						b
					} = options;
				}
			}`,

		output: `
			var Foo = function Foo ( options ) {
				var a = options.a;
					var b = options.b;
			};`
	},

	{
		description: 'allows super in static methods',

		input: `
			class Foo extends Bar {
				static baz () {
					super.baz();
				}
			}`,

		output: `
			var Foo = (function (Bar) {
				function Foo () {
					Bar.apply(this, arguments);
				}

				if ( Bar ) Foo.__proto__ = Bar;
				Foo.prototype = Object.create( Bar && Bar.prototype );
				Foo.prototype.constructor = Foo;

				Foo.baz = function baz () {
					Bar.baz.call(this);
				};

				return Foo;
			}(Bar));`
	},

	{
		description: 'allows zero space between class id and body (#46)',

		input: `
			class A{
				x(){}
			}

			var B = class B{
				x(){}
			};

			class C extends D{
				x(){}
			}

			var E = class E extends F{
				x(){}
			}`,

		output: `
			var A = function A () {};

			A.prototype.x = function x(){};

			var B = (function () {
				function B () {}

				B.prototype.x = function x(){};

				return B;
			}());

			var C = (function (D) {
				function C () {
					D.apply(this, arguments);
				}

				if ( D ) C.__proto__ = D;
				C.prototype = Object.create( D && D.prototype );
				C.prototype.constructor = C;

				C.prototype.x = function x(){};

				return C;
			}(D));

			var E = (function (F) {
				function E () {
					F.apply(this, arguments);
				}

				if ( F ) E.__proto__ = F;
				E.prototype = Object.create( F && F.prototype );
				E.prototype.constructor = E;

				E.prototype.x = function x(){};

				return E;
			}(F))`
	}

	// TODO more tests. e.g. getters and setters. computed method names
	// 'super.*' is not allowed before super()
];
<commit_msg>failing test for #48<commit_after>module.exports = [
	{
		description: 'transpiles a class declaration',

		input: `
			class Foo {
				constructor ( answer ) {
					this.answer = answer;
				}
			}`,

		output: `
			var Foo = function Foo ( answer ) {
				this.answer = answer;
			};`
	},

	{
		description: 'transpiles a class declaration with a non-constructor method',

		input: `
			class Foo {
				constructor ( answer ) {
					this.answer = answer;
				}

				bar ( str ) {
					return str + 'bar';
				}
			}`,

		output: `
			var Foo = function Foo ( answer ) {
				this.answer = answer;
			};

			Foo.prototype.bar = function bar ( str ) {
				return str + 'bar';
			};`
	},

	{
		description: 'transpiles a class declaration without a constructor function',

		input: `
			class Foo {
				bar ( str ) {
					return str + 'bar';
				}
			}`,

		output: `
			var Foo = function Foo () {};

			Foo.prototype.bar = function bar ( str ) {
				return str + 'bar';
			};`
	},

	{
		description: 'deshadows method names',

		input: `
			var bar = 'x';

			class Foo {
				bar ( str ) {
					return str + 'bar';
				}
			}`,

		output: `
			var bar = 'x';

			var Foo = function Foo () {};

			Foo.prototype.bar = function bar$1 ( str ) {
				return str + 'bar';
			};`
	},

	{
		description: 'transpiles a class declaration with a static method',

		input: `
			class Foo {
				bar ( str ) {
					return str + 'bar';
				}

				static baz ( str ) {
					return str + 'baz';
				}
			}`,

		output: `
			var Foo = function Foo () {};

			Foo.prototype.bar = function bar ( str ) {
				return str + 'bar';
			};

			Foo.baz = function baz ( str ) {
				return str + 'baz';
			};`
	},

	{
		description: 'transpiles a subclass',

		input: `
			class Foo extends Bar {
				baz ( str ) {
					return str + 'baz';
				}
			}`,

		output: `
			var Foo = (function (Bar) {
				function Foo () {
					Bar.apply(this, arguments);
				}

				if ( Bar ) Foo.__proto__ = Bar;
				Foo.prototype = Object.create( Bar && Bar.prototype );
				Foo.prototype.constructor = Foo;

				Foo.prototype.baz = function baz ( str ) {
					return str + 'baz';
				};

				return Foo;
			}(Bar));`
	},

	{
		description: 'transpiles a subclass with super calls',

		input: `
			class Foo extends Bar {
				constructor ( x ) {
					super( x );
					this.y = 'z';
				}

				baz ( a, b, c ) {
					super.baz( a, b, c );
				}
			}`,

		output: `
			var Foo = (function (Bar) {
				function Foo ( x ) {
					Bar.call( this, x );
					this.y = 'z';
				}

				if ( Bar ) Foo.__proto__ = Bar;
				Foo.prototype = Object.create( Bar && Bar.prototype );
				Foo.prototype.constructor = Foo;

				Foo.prototype.baz = function baz ( a, b, c ) {
					Bar.prototype.baz.call( this, a, b, c );
				};

				return Foo;
			}(Bar));`
	},

	{
		description: 'transpiles export default class',
		options: { transforms: { moduleExport: false } },

		input: `
			export default class Foo {
				bar () {}
			}`,

		output: `
			var Foo = function Foo () {};

			Foo.prototype.bar = function bar () {};

			export default Foo;`
	},

	{
		description: 'transpiles export default subclass',
		options: { transforms: { moduleExport: false } },

		input: `
			export default class Foo extends Bar {
				bar () {}
			}`,

		output: `
			var Foo = (function (Bar) {
				function Foo () {
					Bar.apply(this, arguments);
				}

				if ( Bar ) Foo.__proto__ = Bar;
				Foo.prototype = Object.create( Bar && Bar.prototype );
				Foo.prototype.constructor = Foo;

				Foo.prototype.bar = function bar () {};

				return Foo;
			}(Bar));

			export default Foo;`
	},

	{
		description: 'transpiles export default subclass with subsequent statement',
		options: { transforms: { moduleExport: false } },

		input: `
			export default class Foo extends Bar {
				bar () {}
			}

			new Foo().bar();`,

		output: `
			var Foo = (function (Bar) {
				function Foo () {
					Bar.apply(this, arguments);
				}

				if ( Bar ) Foo.__proto__ = Bar;
				Foo.prototype = Object.create( Bar && Bar.prototype );
				Foo.prototype.constructor = Foo;

				Foo.prototype.bar = function bar () {};

				return Foo;
			}(Bar));

			export default Foo;

			new Foo().bar();`
	},

	{
		description: 'transpiles empty class',

		input: `class Foo {}`,
		output: `var Foo = function Foo () {};`
	},

	{
		description: 'transpiles an anonymous empty class expression',

		input: `
			var Foo = class {};`,

		output: `
			var Foo = (function () {
				function Foo () {}

				return Foo;
			}());`
	},

	{
		description: 'transpiles an anonymous class expression with a constructor',

		input: `
			var Foo = class {
				constructor ( x ) {
					this.x = x;
				}
			};`,

		output: `
			var Foo = (function () {
				function Foo ( x ) {
					this.x = x;
				}

				return Foo;
			}());`
	},

	{
		description: 'transpiles an anonymous class expression with a non-constructor method',

		input: `
			var Foo = class {
				bar ( x ) {
					console.log( x );
				}
			};`,

		output: `
			var Foo = (function () {
				function Foo () {}

				Foo.prototype.bar = function bar ( x ) {
					console.log( x );
				};

				return Foo;
			}());`
	},

	{
		description: 'allows constructor to be in middle of body',

		input: `
			class Foo {
				before () {
					// code goes here
				}

				constructor () {
					// constructor goes here
				}

				after () {
					// code goes here
				}
			}`,

		output: `
			var Foo = function Foo () {
				// constructor goes here
			};

			Foo.prototype.before = function before () {
				// code goes here
			};

			Foo.prototype.after = function after () {
				// code goes here
			};`
	},

	{
		description: 'allows constructor to be at end of body',

		input: `
			class Foo {
				before () {
					// code goes here
				}

				constructor () {
					// constructor goes here
				}
			}`,

		output: `
			var Foo = function Foo () {
				// constructor goes here
			};

			Foo.prototype.before = function before () {
				// code goes here
			};`
	},

	{
		description: 'transpiles getters and setters',

		input: `
			class Circle {
				constructor ( radius ) {
					this.radius = radius;
				}

				get area () {
					return Math.PI * Math.pow( this.radius, 2 );
				}

				set area ( area ) {
					this.radius = Math.sqrt( area / Math.PI );
				}

				static get description () {
					return 'round';
				}
			}`,

		output: `
			var Circle = function Circle ( radius ) {
				this.radius = radius;
			};

			var prototypeAccessors = { area: {} };
			var staticAccessors = { description: {} };

			prototypeAccessors.area.get = function () {
				return Math.PI * Math.pow( this.radius, 2 );
			};

			prototypeAccessors.area.set = function ( area ) {
				this.radius = Math.sqrt( area / Math.PI );
			};

			staticAccessors.description.get = function () {
				return 'round';
			};

			Object.defineProperties( Circle.prototype, prototypeAccessors );
			Object.defineProperties( Circle, staticAccessors );`
	},

	{
		description: 'transpiles getters and setters in subclass',

		input: `
			class Circle extends Shape {
				constructor ( radius ) {
					super();
					this.radius = radius;
				}

				get area () {
					return Math.PI * Math.pow( this.radius, 2 );
				}

				set area ( area ) {
					this.radius = Math.sqrt( area / Math.PI );
				}

				static get description () {
					return 'round';
				}
			}`,

		output: `
			var Circle = (function (Shape) {
				function Circle ( radius ) {
					Shape.call(this);
					this.radius = radius;
				}

				if ( Shape ) Circle.__proto__ = Shape;
				Circle.prototype = Object.create( Shape && Shape.prototype );
				Circle.prototype.constructor = Circle;

				var prototypeAccessors = { area: {} };
				var staticAccessors = { description: {} };

				prototypeAccessors.area.get = function () {
					return Math.PI * Math.pow( this.radius, 2 );
				};

				prototypeAccessors.area.set = function ( area ) {
					this.radius = Math.sqrt( area / Math.PI );
				};

				staticAccessors.description.get = function () {
					return 'round';
				};

				Object.defineProperties( Circle.prototype, prototypeAccessors );
				Object.defineProperties( Circle, staticAccessors );

				return Circle;
			}(Shape));`
	},

	{
		description: 'can be disabled with `transforms.classes: false`',
		options: { transforms: { classes: false } },

		input: `
			class Foo extends Bar {
				constructor ( answer ) {
					super();
					this.answer = answer;
				}
			}`,

		output: `
			class Foo extends Bar {
				constructor ( answer ) {
					super();
					this.answer = answer;
				}
			}`
	},

	{
		description: 'declaration extends from an expression (#15)',

		input: `
			const q = {a: class {}};

			class b extends q.a {
				c () {}
			}`,

		output: `
			var q = {a: (function () {
				function anonymous () {}

				return anonymous;
			}())};

			var b = (function (superclass) {
				function b () {
					superclass.apply(this, arguments);
				}

				if ( superclass ) b.__proto__ = superclass;
				b.prototype = Object.create( superclass && superclass.prototype );
				b.prototype.constructor = b;

				b.prototype.c = function c () {};

				return b;
			}(q.a));`
	},

	{
		description: 'expression extends from an expression (#15)',

		input: `
			const q = {a: class {}};

			const b = class b extends q.a {
				c () {}
			};`,

		output: `
			var q = {a: (function () {
				function anonymous () {}

				return anonymous;
			}())};

			var b = (function (superclass) {
				function b () {
					superclass.apply(this, arguments);
				}

				if ( superclass ) b.__proto__ = superclass;
				b.prototype = Object.create( superclass && superclass.prototype );
				b.prototype.constructor = b;

				b.prototype.c = function c () {};

				return b;
			}(q.a));`
	},

	{
		description: 'expression extends from an expression with super calls (#31)',

		input: `
			class b extends x.y.z {
				constructor() {
					super();
				}
			}`,

		output: `
			var b = (function (superclass) {
				function b() {
					superclass.call(this);
				}

				if ( superclass ) b.__proto__ = superclass;
				b.prototype = Object.create( superclass && superclass.prototype );
				b.prototype.constructor = b;

				return b;
			}(x.y.z));`
	},

	{
		description: 'anonymous expression extends named class (#31)',

		input: `
			SubClass = class extends SuperClass {
				constructor() {
					super();
				}
			};`,

		output: `
			SubClass = (function (SuperClass) {
				function SubClass() {
					SuperClass.call(this);
				}

				if ( SuperClass ) SubClass.__proto__ = SuperClass;
				SubClass.prototype = Object.create( SuperClass && SuperClass.prototype );
				SubClass.prototype.constructor = SubClass;

				return SubClass;
			}(SuperClass));`
	},

	{
		description: 'deindents a function body with destructuring (#22)',

		input: `
			class Foo {
				constructor ( options ) {
					const {
						a,
						b
					} = options;
				}
			}`,

		output: `
			var Foo = function Foo ( options ) {
				var a = options.a;
					var b = options.b;
			};`
	},

	{
		description: 'allows super in static methods',

		input: `
			class Foo extends Bar {
				static baz () {
					super.baz();
				}
			}`,

		output: `
			var Foo = (function (Bar) {
				function Foo () {
					Bar.apply(this, arguments);
				}

				if ( Bar ) Foo.__proto__ = Bar;
				Foo.prototype = Object.create( Bar && Bar.prototype );
				Foo.prototype.constructor = Foo;

				Foo.baz = function baz () {
					Bar.baz.call(this);
				};

				return Foo;
			}(Bar));`
	},

	{
		description: 'allows zero space between class id and body (#46)',

		input: `
			class A{
				x(){}
			}

			var B = class B{
				x(){}
			};

			class C extends D{
				x(){}
			}

			var E = class E extends F{
				x(){}
			}`,

		output: `
			var A = function A () {};

			A.prototype.x = function x(){};

			var B = (function () {
				function B () {}

				B.prototype.x = function x(){};

				return B;
			}());

			var C = (function (D) {
				function C () {
					D.apply(this, arguments);
				}

				if ( D ) C.__proto__ = D;
				C.prototype = Object.create( D && D.prototype );
				C.prototype.constructor = C;

				C.prototype.x = function x(){};

				return C;
			}(D));

			var E = (function (F) {
				function E () {
					F.apply(this, arguments);
				}

				if ( F ) E.__proto__ = F;
				E.prototype = Object.create( F && F.prototype );
				E.prototype.constructor = E;

				E.prototype.x = function x(){};

				return E;
			}(F))`
	},

	{
		description: 'transpiles a class with an accessor and no constructor (#48)',

		input: `
			class Foo {
				static get bar() { return 'baz' }
			}`,

		output: `
			var Foo = function Foo () {};

			var staticAccessors = { bar: {} };

			staticAccessors.bar.get = function() { return 'baz' };

			Object.defineProperties( Foo, staticAccessors );`
	}

	// TODO more tests. e.g. getters and setters. computed method names
	// 'super.*' is not allowed before super()
];
<|endoftext|>


<commit_before>var fs = require('fs');
var _  = require('lodash');

var DEFAULTS = {
  intro:  null,
  styles: [],
  output: './tmp'
};

exports.read = function() {
  try {
    var content = fs.readFileSync('supersamples.opts').toString();
    var opts = JSON.parse(content);
    return _.defaults(opts, DEFAULTS);
  } catch (ex) {
    return DEFAULTS;
  }
};
<commit_msg>Complain if “supersamples.opts” file exists but format is wrong<commit_after>var fs   = require('fs');
var path = require('path');
var _    = require('lodash');

var DEFAULTS = {
  title: null,
  intro:  null,
  styles: [],
  output: './tmp'
};

exports.read = function() {
  var content = null;
  try {
    content = fs.readFileSync('supersamples.opts').toString();
  } catch (ex) {
    return DEFAULTS;
  }
  try {
    var opts = JSON.parse(content);
    return _.defaults(opts, DEFAULTS);
  } catch (ex) {
    console.error('Invalid config file: ' + path.resolve('supersamples.opts'));
    process.exit(1);
  }
};
<|endoftext|>


<commit_before>'use babel';

export default {
    apply: function(){
        root = document.documentElement;
        styleTimer = null;

        var hideInactiveFiles = function(hideStatus){
            if( hideStatus == 'Enabled [Dark]' ){
                root.classList.add('hide-idle-tree-items');
                root.classList.remove('light-tree-on-hover');
            }
            else if( hideStatus == 'Enabled [Light]' ){
                root.classList.add('hide-idle-tree-items');
                root.classList.add('light-tree-on-hover');
            }
            else {
                root.classList.remove('hide-idle-tree-items');
                root.classList.remove('light-tree-on-hover');
            }
        }

        hideInactiveFiles(atom.config.get('climate-ui.btreeView.bhideInactiveFiles'));

        atom.config.onDidChange( 'climate-ui.btreeView.bhideInactiveFiles', function(){
            hideInactiveFiles(atom.config.get('climate-ui.btreeView.bhideInactiveFiles'));
        });

        var showOpenFiles = function(openFileStatus){
            if( openFileStatus === true ){
                root.classList.add('always-show-open-files-in-tree-view');
            }
            else{
                root.classList.remove('always-show-open-files-in-tree-view');
            }
        }

        showOpenFiles(atom.config.get('climate-ui.btreeView.cshowOpenFiles'));

        atom.config.onDidChange( 'climate-ui.btreeView.cshowOpenFiles', function(){
            showOpenFiles(atom.config.get('climate-ui.btreeView.cshowOpenFiles'));
        });

        var compactHeaders = function(boolean){
            if( boolean === true ){
                root.classList.add('compact-tree-view-headers');
            }
            else{
                root.classList.remove('compact-tree-view-headers');
            }
        }

        compactHeaders(atom.config.get('climate-ui.btreeView.dcompactHeaders'));

        atom.config.onDidChange( 'climate-ui.btreeView.dcompactHeaders', function(){
            compactHeaders(atom.config.get('climate-ui.btreeView.dcompactHeaders'));
        });

        var treeTab = function(boolean){
            var treeView = document.querySelector('.tree-view-resizer');

            if( treeView ){
                var treeTab = document.createElement('div');
                var title = document.createElement('span');
                var treeTabEl = treeView.querySelector('.tree-tab');

                if( treeTabEl ){
                    treeView.removeChild(treeTabEl);
                }

                if( boolean === true ){
                    treeTab.classList.add('tree-tab');
                    treeTab.appendChild(title);
                    treeView.insertBefore(treeTab, treeView.firstChild);
                    root.classList.add('tree-tab-shadows');
                }
                else{
                    root.classList.remove('tree-tab-shadows');
                }
            }
        }

        treeTab(atom.config.get('climate-ui.btreeView.etreeTab'));

        atom.config.onDidChange( 'climate-ui.btreeView.etreeTab', function(){
            treeTab(atom.config.get('climate-ui.btreeView.etreeTab'));
        });

        var hideGitStatus = function(hideStatus){
            if( hideStatus == 'Enabled [Dimmed]' ){
                root.classList.add('dim-git-status-in-tree-view');
                root.classList.remove('hide-git-status-in-tree-view');
            }
            else if( hideStatus == 'Enabled [Hidden]' ){
                root.classList.add('hide-git-status-in-tree-view');
                root.classList.remove('dim-git-status-in-tree-view');
            }
            else {
                root.classList.remove('hide-git-status-in-tree-view');
                root.classList.remove('dim-git-status-in-tree-view');
            }
        }

        hideGitStatus(atom.config.get('climate-ui.btreeView.ahideGitStatus'));

        atom.config.onDidChange( 'climate-ui.btreeView.ahideGitStatus', function(){
            hideGitStatus(atom.config.get('climate-ui.btreeView.ahideGitStatus'));
        });

        var isHexCode = function(hexCode){
            return /^#(?:[0-9a-fA-F]{3}){1,2}$/.test(hexCode);
        }

        var writeCustomStyles = function(colors, options){
            colors = colors.split(',');

            var custom = '';

            for (var i = 0; i < colors.length; i++) {
                color = colors[i];
                color = color.split(':');

                if( color.length == 2 && color[0] && color[1] && isHexCode(color[1]) ){
                    custom += '.color-to-filetype("'+color[0]+'", '+color[1]+');\n';
                }
            }

            fs.writeFile(`${__dirname}/../styles/color-variances.less`, custom, 'utf8', () => {
                if (!options || !options.noReload) {
                    var themePack = atom.packages.getLoadedPackage('climate-ui');

                    if (themePack) {
                        themePack.deactivate();
                        setImmediate(() => themePack.activate());
                    }
                }
            });
        }

        writeCustomStyles(atom.config.get('climate-ui.acolors.themeColors'),{ noReload: true });

        atom.config.onDidChange( 'climate-ui.acolors.themeColors', function(){
            if( styleTimer ){
                clearTimeout(styleTimer);
            }
            styleTimer = setTimeout(function(){
                styleTimer = false;
                writeCustomStyles(atom.config.get('climate-ui.acolors.themeColors'));
            }, 1000);
        });
    }
};<commit_msg>Issue #1<commit_after>'use babel';

import fs from 'fs';

export default {
    apply: function(){
        root = document.documentElement;
        styleTimer = null;

        var hideInactiveFiles = function(hideStatus){
            if( hideStatus == 'Enabled [Dark]' ){
                root.classList.add('hide-idle-tree-items');
                root.classList.remove('light-tree-on-hover');
            }
            else if( hideStatus == 'Enabled [Light]' ){
                root.classList.add('hide-idle-tree-items');
                root.classList.add('light-tree-on-hover');
            }
            else {
                root.classList.remove('hide-idle-tree-items');
                root.classList.remove('light-tree-on-hover');
            }
        }

        hideInactiveFiles(atom.config.get('climate-ui.btreeView.bhideInactiveFiles'));

        atom.config.onDidChange( 'climate-ui.btreeView.bhideInactiveFiles', function(){
            hideInactiveFiles(atom.config.get('climate-ui.btreeView.bhideInactiveFiles'));
        });

        var showOpenFiles = function(openFileStatus){
            if( openFileStatus === true ){
                root.classList.add('always-show-open-files-in-tree-view');
            }
            else{
                root.classList.remove('always-show-open-files-in-tree-view');
            }
        }

        showOpenFiles(atom.config.get('climate-ui.btreeView.cshowOpenFiles'));

        atom.config.onDidChange( 'climate-ui.btreeView.cshowOpenFiles', function(){
            showOpenFiles(atom.config.get('climate-ui.btreeView.cshowOpenFiles'));
        });

        var compactHeaders = function(boolean){
            if( boolean === true ){
                root.classList.add('compact-tree-view-headers');
            }
            else{
                root.classList.remove('compact-tree-view-headers');
            }
        }

        compactHeaders(atom.config.get('climate-ui.btreeView.dcompactHeaders'));

        atom.config.onDidChange( 'climate-ui.btreeView.dcompactHeaders', function(){
            compactHeaders(atom.config.get('climate-ui.btreeView.dcompactHeaders'));
        });

        var treeTab = function(boolean){
            var treeView = document.querySelector('.tree-view-resizer');

            if( treeView ){
                var treeTab = document.createElement('div');
                var title = document.createElement('span');
                var treeTabEl = treeView.querySelector('.tree-tab');

                if( treeTabEl ){
                    treeView.removeChild(treeTabEl);
                }

                if( boolean === true ){
                    treeTab.classList.add('tree-tab');
                    treeTab.appendChild(title);
                    treeView.insertBefore(treeTab, treeView.firstChild);
                    root.classList.add('tree-tab-shadows');
                }
                else{
                    root.classList.remove('tree-tab-shadows');
                }
            }
        }

        treeTab(atom.config.get('climate-ui.btreeView.etreeTab'));

        atom.config.onDidChange( 'climate-ui.btreeView.etreeTab', function(){
            treeTab(atom.config.get('climate-ui.btreeView.etreeTab'));
        });

        var hideGitStatus = function(hideStatus){
            if( hideStatus == 'Enabled [Dimmed]' ){
                root.classList.add('dim-git-status-in-tree-view');
                root.classList.remove('hide-git-status-in-tree-view');
            }
            else if( hideStatus == 'Enabled [Hidden]' ){
                root.classList.add('hide-git-status-in-tree-view');
                root.classList.remove('dim-git-status-in-tree-view');
            }
            else {
                root.classList.remove('hide-git-status-in-tree-view');
                root.classList.remove('dim-git-status-in-tree-view');
            }
        }

        hideGitStatus(atom.config.get('climate-ui.btreeView.ahideGitStatus'));

        atom.config.onDidChange( 'climate-ui.btreeView.ahideGitStatus', function(){
            hideGitStatus(atom.config.get('climate-ui.btreeView.ahideGitStatus'));
        });

        var isHexCode = function(hexCode){
            return /^#(?:[0-9a-fA-F]{3}){1,2}$/.test(hexCode);
        }

        var writeCustomStyles = function(colors, options){
            colors = colors.split(',');

            var custom = '';

            for (var i = 0; i < colors.length; i++) {
                color = colors[i];
                color = color.split(':');

                if( color.length == 2 && color[0] && color[1] && isHexCode(color[1]) ){
                    custom += '.color-to-filetype("'+color[0]+'", '+color[1]+');\n';
                }
            }

            fs.writeFile(`${__dirname}/../styles/color-variances.less`, custom, 'utf8', () => {
                if (!options || !options.noReload) {
                    var themePack = atom.packages.getLoadedPackage('climate-ui');

                    if (themePack) {
                        themePack.deactivate();
                        setImmediate(() => themePack.activate());
                    }
                }
            });
        }

        writeCustomStyles(atom.config.get('climate-ui.acolors.themeColors'),{ noReload: true });

        atom.config.onDidChange( 'climate-ui.acolors.themeColors', function(){
            if( styleTimer ){
                clearTimeout(styleTimer);
            }
            styleTimer = setTimeout(function(){
                styleTimer = false;
                writeCustomStyles(atom.config.get('climate-ui.acolors.themeColors'));
            }, 1000);
        });
    }
};<|endoftext|>


<commit_before>var util = require('util'),
    EventEmitter = require('events').EventEmitter,
    /**
     * shorthand for
     * Array.prototype.slice.call(object, ...)
     */
    slice = (function (slice) {
        return function (object) {
            return slice.apply(object, slice.call(arguments, 1));
        };
    }([].slice));

/**
 * A helper function to tell the world we are done flushing
 */
exports.tell = function (toEvent, data, error, cares) {
    if (cares instanceof EventEmitter) {
        (!error                                  ?
            cares.emit(toEvent, data)            :
            cares.emit('error', error, data));
    } else if (typeof cares === 'function') {
        cares(error, data);
    } else if (Array.isArray(cares)) {
        return cares.forEach(exports.tell.bind(null, toEvent, data, error));
    }
}

/**
 *
 */
exports.newOp = function(options) {
    var op = {},
        setString = function (name, value) {
            if (typeof value === 'string') {
                options[name] = value;
            }
            return op.getSelf();
        },
        setArray = function(name, data) {

            if (arguments.length === 1 && !options.hasOwnProperty(name)) {
                options[name] = data;
            } else if (options.hasOwnProperty(name)) {
                if (Array.isArray(options[name])) {
                    options[name] = options[name].concat(slice(arguments));
                } else {
                    options[name] = [options[name]].concat(slice(arguments));
                }

            } else {
                options[name] = slice(arguments);
            }

            return op.getSelf();
        },
        setFn =  function (name, fn) {
            if (typeof value === 'function') {
                options[name] = fn;
            }
            return op.getSelf();
        },
        setEmitter = function(name, value){
            if (value instanceof EventEmitter){
                options.self = value;
            } else {
                options.self = new EventEmitter();
            }
            return op.getSelf();
        };

    /**
     *
     */
    op.getSelf = function () {
        return op;
    };

    return {
        'op'        : op,
        'string'    : setString,
        'array'     : setArray,
        'emitter'   : setEmitter,
        'fn'        : setFn
    };

};<commit_msg>a number setter for options<commit_after>var util = require('util'),
    EventEmitter = require('events').EventEmitter,
    /**
     * shorthand for
     * Array.prototype.slice.call(object, ...)
     */
    slice = (function (slice) {
        return function (object) {
            return slice.apply(object, slice.call(arguments, 1));
        };
    }([].slice));

/**
 * A helper function to tell the world we are done flushing
 */
exports.tell = function (toEvent, data, error, cares) {
    if (cares instanceof EventEmitter) {
        (!error                                  ?
            cares.emit(toEvent, data)            :
            cares.emit('error', error, data));
    } else if (typeof cares === 'function') {
        cares(error, data);
    } else if (Array.isArray(cares)) {
        return cares.forEach(exports.tell.bind(null, toEvent, data, error));
    }
}

/**
 *
 */
exports.newOp = function(options) {
    var op = {},
        setString = function (name, value) {
            if (typeof value === 'string') {
                options[name] = value;
            }
            return op.getSelf();
        },
        setNumber = function(name, value){
            if (!isNaN(intValue(value, 10))) {
                options[name] = value;
            }
            return op.getSelf();
        },
        setArray = function(name, data) {

            if (arguments.length === 1 && !options.hasOwnProperty(name)) {
                options[name] = data;
            } else if (options.hasOwnProperty(name)) {
                if (Array.isArray(options[name])) {
                    options[name] = options[name].concat(slice(arguments));
                } else {
                    options[name] = [options[name]].concat(slice(arguments));
                }

            } else {
                options[name] = slice(arguments);
            }

            return op.getSelf();
        },
        setFn =  function (name, fn) {
            if (typeof value === 'function') {
                options[name] = fn;
            }
            return op.getSelf();
        },
        setEmitter = function(name, value){
            if (value instanceof EventEmitter){
                options.self = value;
            } else {
                options.self = new EventEmitter();
            }
            return op.getSelf();
        };

    /**
     *
     */
    op.getSelf = function () {
        return op;
    };

    return {
        'op'        : op,
        'string'    : setString,
        'number'    : setNumber,
        'array'     : setArray,
        'emitter'   : setEmitter,
        'fn'        : setFn
    };

};<|endoftext|>


<commit_before>const fixme = `
/*
  FIXME(polymer-modulizer): the above comments were extracted
  from HTML and may be out of place here. Review them and
  then delete this comment!
*/
;`

const tsDefs = `"scripts": {
  "generate-typings": "gen-typescript-declarations --outDir . --verify"
},
"devDependencies": {
  "@web-padawan/gen-typescript-declarations": "^1.6.2",`;

 module.exports = {
  files: [
    "package.json",
    "theme/**/*-styles.js"
  ],
  from: [
    '"devDependencies": {',
    "const $_documentContainer = document.createElement('template');",
    "$_documentContainer.innerHTML = `",
    fixme
  ],
  to: [
    tsDefs,
    "import { html } from '@polymer/polymer/lib/utils/html-tag.js';",
    "const $_documentContainer = html`",
    ""
  ]
}
<commit_msg>fix: update resolutions for yarn flat (#118)<commit_after>const fixme = `
/*
  FIXME(polymer-modulizer): the above comments were extracted
  from HTML and may be out of place here. Review them and
  then delete this comment!
*/
;`

const tsDefs = `"scripts": {
  "generate-typings": "gen-typescript-declarations --outDir . --verify"
},
"devDependencies": {
  "@web-padawan/gen-typescript-declarations": "^1.6.2",`;

const resolutions = `"resolutions": {
    "es-abstract": "1.17.6",
    "@types/doctrine": "0.0.3",`;

 module.exports = {
  files: [
    "package.json",
    "theme/**/*-styles.js"
  ],
  from: [
    '"devDependencies": {',
    '"resolutions": {',
    "const $_documentContainer = document.createElement('template');",
    "$_documentContainer.innerHTML = `",
    fixme
  ],
  to: [
    tsDefs,
    resolutions,
    "import { html } from '@polymer/polymer/lib/utils/html-tag.js';",
    "const $_documentContainer = html`",
    ""
  ]
}
<|endoftext|>


<commit_before>'use strict'

var url = require('url')
var util = require('util')
var stringify = require('json-stringify-safe')
var stackman = require('stackman')()

exports._MAX_HTTP_BODY_CHARS = 2048 // expose for testing purposes

var mysqlErrorMsg = /(ER_[A-Z_]+): /

exports.parseMessage = function (message, payload) {
  if (typeof message === 'object') {
    // if `captureError` is parsed an object instead of a string we except
    // it to be in the format of `{ message: '...', params: [] }` and it will
    // be used as `param_message`.
    if (message.message) {
      payload.param_message = message.message
      message = util.format.apply(this, [message.message].concat(message.params))
    } else {
      message = util.inspect(message)
    }
  }

  payload.message = message
}

exports.parseError = function (err, payload, cb) {
  stackman(err, function (stack) {
    setMessage(payload, err)
    setException(payload, err)
    setStacktrace(payload, stack.frames)
    setCulprit(payload, stack.frames)
    setModule(payload)
    setExtraProperties(payload, stack.properties)
    cb(payload)
  })
}

exports.parseRequest = function (req) {
  var protocol = req.socket.encrypted ? 'https' : 'http'
  var host = req.headers.host || '<no host>'
  var userAgent = req.headers['user-agent']
  var httpObj = {
    method: req.method,
    url: protocol + '://' + host + req.url,
    query_string: url.parse(req.url).query,
    headers: req.headers,
    secure: !!req.socket.encrypted,
    remote_host: req.socket.remoteAddress
  }

  var body = req.json || req.body || req.payload
  if (body !== undefined) {
    if (typeof body !== 'string') body = stringify(body)
    if (typeof body === 'string') body = body.slice(0, exports._MAX_HTTP_BODY_CHARS)
    httpObj.data = body
  }

  if (req.cookies) httpObj.cookies = req.cookies
  if (userAgent) httpObj.user_agent = userAgent
  return httpObj
}

exports.parseCallsite = function (callsite) {
  var filename = callsite.getFileName()
  var frame = {
    filename: callsite.getRelativeFileName() || '',
    lineno: callsite.getLineNumber(),
    function: callsite.getFunctionNameSanitized(),
    in_app: callsite.isApp()
  }
  if (!Number.isFinite(frame.lineno)) frame.lineno = 0 // this should be an int, but sometimes it's not?!
  if (filename) frame.abs_path = filename

  if ('context' in callsite) {
    frame.pre_context = callsite.context.pre
    frame.context_line = callsite.context.line
    frame.post_context = callsite.context.post
  }

  return frame
}

function setMessage (payload, err) {
  // If the message have already been set, for instance when calling
  // `captureError` with a string or an object-literal, just return without
  // overwriting it
  if (payload.message) return
  // TODO: Normally err.name is just "Error", maybe we should omit it in that case?
  payload.message = err.name + ': ' + (err.message || '<no message>')
}

function setException (payload, err) {
  var type = err.name

  // To provide better grouping of mysql errors that happens after the async
  // boundery, we modify to exception type to include the custom mysql error
  // type (e.g. ER_PARSE_ERROR)
  var match = (err.message || '').match(mysqlErrorMsg)
  if (match) type += ': ' + match[1]

  payload.exception = {
    type: type,
    value: err.message
  }
}

function setStacktrace (payload, frames) {
  if (!frames) return
  payload.stacktrace = {
    frames: frames.map(exports.parseCallsite)
  }
}

// Default `culprit` to the top of the stack or the highest `in_app` frame if such exists
function setCulprit (payload, frames) {
  if (payload.culprit) return // skip if user provided a custom culprit
  if (!frames || !frames.length) return
  var filename = frames[0].getRelativeFileName()
  var fnName = frames[0].getFunctionNameSanitized()
  for (var n = 0, l = frames.length; n < l; n++) {
    if (frames[n].in_app) {
      filename = frames[n].getRelativeFileName()
      fnName = frames[n].getFunctionNameSanitized()
      break
    }
  }
  payload.culprit = filename ? fnName + ' (' + filename + ')' : fnName
}

function setModule (payload) {
  if (!payload.stacktrace) return
  var frame = payload.stacktrace.frames[0]
  if (!frame || frame.in_app) return
  var match = frame.filename.match(/node_modules\/([^\/]*)/)
  if (!match) return
  payload.exception.module = match[1]
}

function setExtraProperties (payload, properties) {
  var keys = Object.keys(properties || {})
  if (!keys.length) return
  payload.extra = payload.extra || {}

  // handle if user gives us stuff like { extra: 404 }
  if (typeof payload.extra !== 'object') payload.extra = { value: String(payload.extra) }

  keys.forEach(function (key) {
    if (key in payload.extra) return
    payload.extra[key] = properties[key]
  })
}
<commit_msg>core: clean up parseRequest function<commit_after>'use strict'

var url = require('url')
var util = require('util')
var stringify = require('json-stringify-safe')
var stackman = require('stackman')()

exports._MAX_HTTP_BODY_CHARS = 2048 // expose for testing purposes

var mysqlErrorMsg = /(ER_[A-Z_]+): /

exports.parseMessage = function (message, payload) {
  if (typeof message === 'object') {
    // if `captureError` is parsed an object instead of a string we except
    // it to be in the format of `{ message: '...', params: [] }` and it will
    // be used as `param_message`.
    if (message.message) {
      payload.param_message = message.message
      message = util.format.apply(this, [message.message].concat(message.params))
    } else {
      message = util.inspect(message)
    }
  }

  payload.message = message
}

exports.parseError = function (err, payload, cb) {
  stackman(err, function (stack) {
    setMessage(payload, err)
    setException(payload, err)
    setStacktrace(payload, stack.frames)
    setCulprit(payload, stack.frames)
    setModule(payload)
    setExtraProperties(payload, stack.properties)
    cb(payload)
  })
}

exports.parseRequest = function (req) {
  var protocol = req.socket.encrypted ? 'https' : 'http'
  var host = req.headers.host || '<no host>'
  var httpObj = {
    method: req.method,
    url: protocol + '://' + host + req.url,
    query_string: url.parse(req.url).query,
    headers: req.headers,
    secure: !!req.socket.encrypted,
    remote_host: req.socket.remoteAddress
  }

  if (req.headers['user-agent']) httpObj.user_agent = req.headers['user-agent']
  if (req.cookies) httpObj.cookies = req.cookies

  var body = req.json || req.body || req.payload
  if (body !== undefined) {
    if (typeof body !== 'string') body = stringify(body)
    if (typeof body === 'string') body = body.slice(0, exports._MAX_HTTP_BODY_CHARS)
    httpObj.data = body
  }

  return httpObj
}

exports.parseCallsite = function (callsite) {
  var filename = callsite.getFileName()
  var frame = {
    filename: callsite.getRelativeFileName() || '',
    lineno: callsite.getLineNumber(),
    function: callsite.getFunctionNameSanitized(),
    in_app: callsite.isApp()
  }
  if (!Number.isFinite(frame.lineno)) frame.lineno = 0 // this should be an int, but sometimes it's not?!
  if (filename) frame.abs_path = filename

  if ('context' in callsite) {
    frame.pre_context = callsite.context.pre
    frame.context_line = callsite.context.line
    frame.post_context = callsite.context.post
  }

  return frame
}

function setMessage (payload, err) {
  // If the message have already been set, for instance when calling
  // `captureError` with a string or an object-literal, just return without
  // overwriting it
  if (payload.message) return
  // TODO: Normally err.name is just "Error", maybe we should omit it in that case?
  payload.message = err.name + ': ' + (err.message || '<no message>')
}

function setException (payload, err) {
  var type = err.name

  // To provide better grouping of mysql errors that happens after the async
  // boundery, we modify to exception type to include the custom mysql error
  // type (e.g. ER_PARSE_ERROR)
  var match = (err.message || '').match(mysqlErrorMsg)
  if (match) type += ': ' + match[1]

  payload.exception = {
    type: type,
    value: err.message
  }
}

function setStacktrace (payload, frames) {
  if (!frames) return
  payload.stacktrace = {
    frames: frames.map(exports.parseCallsite)
  }
}

// Default `culprit` to the top of the stack or the highest `in_app` frame if such exists
function setCulprit (payload, frames) {
  if (payload.culprit) return // skip if user provided a custom culprit
  if (!frames || !frames.length) return
  var filename = frames[0].getRelativeFileName()
  var fnName = frames[0].getFunctionNameSanitized()
  for (var n = 0, l = frames.length; n < l; n++) {
    if (frames[n].in_app) {
      filename = frames[n].getRelativeFileName()
      fnName = frames[n].getFunctionNameSanitized()
      break
    }
  }
  payload.culprit = filename ? fnName + ' (' + filename + ')' : fnName
}

function setModule (payload) {
  if (!payload.stacktrace) return
  var frame = payload.stacktrace.frames[0]
  if (!frame || frame.in_app) return
  var match = frame.filename.match(/node_modules\/([^\/]*)/)
  if (!match) return
  payload.exception.module = match[1]
}

function setExtraProperties (payload, properties) {
  var keys = Object.keys(properties || {})
  if (!keys.length) return
  payload.extra = payload.extra || {}

  // handle if user gives us stuff like { extra: 404 }
  if (typeof payload.extra !== 'object') payload.extra = { value: String(payload.extra) }

  keys.forEach(function (key) {
    if (key in payload.extra) return
    payload.extra[key] = properties[key]
  })
}
<|endoftext|>


<commit_before>//////////////////////////////////////////
// Defines mappings between content-type
// and the appropriate parsers.
//////////////////////////////////////////

var Transform = require('stream').Transform;
var sax = require('sax');

function parseXML(str, cb) {
  var obj, current, parser = sax.parser(true, { trim: true, lowercase: true })
  parser.onerror = parser.onend = done;

  function start() {
    try {
      parser.write(str).close()
    } catch(e) {
      done(e)
    }
  }

  function done(err) {
    cb(err, obj)
    done = function() { };
  }

  function newElement(name, attributes) {
    return {
      name: name || '',
      text: '',
      attributes: attributes || {},
      children: []
    }
  }

  parser.ontext = function(t) {
    if (current) current.text += t
  }

  parser.onopentag = function(node) {
    var element = newElement(node.name, node.attributes)
    if (current) {
      element.parent = current
      current.children.push(element)
    } else {
      obj = element
    }

    current = element
  };

  parser.onclosetag = function() {
    if (typeof current.parent !== 'undefined') {
      var just_closed = current
      current = current.parent
      delete just_closed.parent
    }
  }

  start()
}

function parserFactory(name, fn) {

  function parser() {
    var chunks = [],
        stream = new Transform({ objectMode: true });

    // Buffer all our data
    stream._transform = function(chunk, encoding, done) {
      chunks.push(chunk);
      done();
    }

    // And call the parser when all is there.
    stream._flush = function(done) {
      var self = this,
          data = Buffer.concat(chunks);

      try {
        fn(data, function(err, result) {
          if (err) throw err;
          self.push(result);
        });
      } catch (err) {
        self.push(data); // just pass the original data
      } finally {
        done();
      }
    }

    return stream;
  }

  return { fn: parser, name: name };
}

var json = parserFactory('json', function(buffer, cb) {
  var err, data;
  try { data = JSON.parse(buffer); } catch (e) { err = e; }
  cb(err, data);
});

module.exports['application/json'] = json;
module.exports['text/javascript']  = json;

var xml = parserFactory('xml', function(buffer, cb) {
  parseXML(buffer.toString(), function(err, obj) {
    cb(err, data)
  })
});

module.exports['text/xml']             = xml;
module.exports['application/xml']      = xml;
module.exports['application/rdf+xml']  = xml;
module.exports['application/rss+xml']  = xml;
module.exports['application/atom+xml'] = xml;<commit_msg>Small comment<commit_after>//////////////////////////////////////////
// Defines mappings between content-type
// and the appropriate parsers.
//////////////////////////////////////////

var Transform = require('stream').Transform;
var sax = require('sax');

function parseXML(str, cb) {
  var obj, current, parser = sax.parser(true, { trim: true, lowercase: true })
  parser.onerror = parser.onend = done;

  function start() {
    try {
      parser.write(str).close()
    } catch(e) {
      done(e)
    }
  }

  function done(err) {
    cb(err, obj)
    done = function() { };
  }

  function newElement(name, attributes) {
    return {
      name: name || '',
      text: '',
      attributes: attributes || {},
      children: []
    }
  }

  parser.ontext = function(t) {
    if (current) current.text += t
  }

  parser.onopentag = function(node) {
    var element = newElement(node.name, node.attributes)
    if (current) {
      element.parent = current
      current.children.push(element)
    } else { // root object
      obj = element
    }

    current = element
  };

  parser.onclosetag = function() {
    if (typeof current.parent !== 'undefined') {
      var just_closed = current
      current = current.parent
      delete just_closed.parent
    }
  }

  start()
}

function parserFactory(name, fn) {

  function parser() {
    var chunks = [],
        stream = new Transform({ objectMode: true });

    // Buffer all our data
    stream._transform = function(chunk, encoding, done) {
      chunks.push(chunk);
      done();
    }

    // And call the parser when all is there.
    stream._flush = function(done) {
      var self = this,
          data = Buffer.concat(chunks);

      try {
        fn(data, function(err, result) {
          if (err) throw err;
          self.push(result);
        });
      } catch (err) {
        self.push(data); // just pass the original data
      } finally {
        done();
      }
    }

    return stream;
  }

  return { fn: parser, name: name };
}

var json = parserFactory('json', function(buffer, cb) {
  var err, data;
  try { data = JSON.parse(buffer); } catch (e) { err = e; }
  cb(err, data);
});

module.exports['application/json'] = json;
module.exports['text/javascript']  = json;

var xml = parserFactory('xml', function(buffer, cb) {
  parseXML(buffer.toString(), function(err, obj) {
    cb(err, data)
  })
});

module.exports['text/xml']             = xml;
module.exports['application/xml']      = xml;
module.exports['application/rdf+xml']  = xml;
module.exports['application/rss+xml']  = xml;
module.exports['application/atom+xml'] = xml;<|endoftext|>


<commit_before>(function(factory){

	'use strict';

	if (typeof module === 'object' && module.exports) {
		module.exports = factory( require('axios') );
	} else {
		factory(axios);
	}

})(function PersonaFactory(axios){

	'use strict';

	function Persona(data){

		var self = this;

		this.dataValues = data || {}

		function get(key){
			if (key === undefined) {
				return self.dataValues;
			}
			return self.dataValues[key];
		}

		this.get = get;

	}

	Persona.find = function find(code){
		return axios.get('https://soa.afip.gob.ar/sr-padron/v2/persona/' + code).then(function(response){

			var json = response.data;
			if (!json.success) { return null; }
			var data = json.data;

			return new Persona(Object.assign(data, {}));

		});
	}

	return Persona;

});<commit_msg>normalized attributes<commit_after>(function(factory){

	'use strict';

	if (typeof module === 'object' && module.exports) {
		module.exports = factory( require('axios') );
	} else {
		factory(axios);
	}

})(function PersonaFactory(axios){

	'use strict';

	function Persona(data){

		var self = this;

		this.dataValues = data || {}

		function get(key){
			if (key === undefined) {
				return self.dataValues;
			}
			return self.dataValues[key];
		}

		this.get = get;
		this.geoLocation = geoLocation;

	}

	Persona.find = function find(code){
		return axios.get('https://soa.afip.gob.ar/sr-padron/v2/persona/' + code).then(function(response){

			var json = response.data;
			if (!json.success) { return null; }
			var data = json.data;

			var address = (function(data){
				return data.direccion + ', ' + (data.localidad||'') + ', Argentina';
			})(data.domicilioFiscal);

			return new Persona(Object.assign(data, {
				name : data.nombre,
				type : data.tipoPersona,
				address : address
			}));

		});
	}

	return Persona;

});<|endoftext|>


<commit_before>var fs = require('fs');

var Phrases = module.exports = {};
var words = {};
var index = [];

//Loads files into memory, prepares hash/cache
Phrases.load = function(file,callback) {
	parsePhrases(file, callback);
};

Phrases.get = function(word) {
	var idx = words[word.toLowerCase()]||[];
	var phs = [];
	for(var i=0;i<idx.length;i++) {
		phs.push(index[idx[i]]);
	}

	if(!phs.length) {
		for(var w in words) {
			if (w.indexOf(word)>-1){
				idx = words[w];
				for(var i=0;i<idx.length;i++) {
					phs.push(index[idx[i]]);
				}
			}
		}
	}
	return phs;
};

//Loads an phrase list file from disk into memory
function parsePhrases(filename,callback) {

	fs.readFile(filename,'utf8',function(err,raw){
		if (err) { callback(err); return; }
		index = raw.split('\n');
		for(var i=0;i<index.length;i++) {
			var phs = index[i].split('_');
			for(var p=0;p<phs.length;p++) {
				words[phs[p]]=words[phs[p]]||[];
				words[phs[p]].push(i);
			}
		}
		if(callback) callback(null);
	});

};<commit_msg>Phrase load fix<commit_after>var fs = require('fs');

var Phrases = module.exports = {};
var words = {};
var index = [];

//Loads files into memory, prepares hash/cache
Phrases.load = function(file,callback) {
	parsePhrases(file, callback);
};

Phrases.get = function(word) {
	var idx = words[word.toLowerCase()]||[];
	var phs = [];
	for(var i=0;i<idx.length;i++) {
		phs.push(index[idx[i]]);
	}

	if(!phs.length) {
		for(var w in words) {
			if (w.indexOf(word)>-1){
				idx = words[w];
				for(var i=0;i<idx.length;i++) {
					phs.push(index[idx[i]]);
				}
			}
		}
	}
	return phs;
};

//Loads an phrase list file from disk into memory
function parsePhrases(filename,callback) {

	fs.readFile(filename,'utf8',function(err,raw){
		if (err) { callback(err); return; }
		index = raw.split('\n');
		for(var i=0;i<index.length;i++) {
			var phs = index[i].split('_');
			for(var p=0;p<phs.length;p++) {
				if(!(words[phs[p]] instanceof Array)) words[phs[p]] = [];
				words[phs[p]].push(i);
			}
		}
		if(callback) callback(null);
	});

};<|endoftext|>


<commit_before>/* global fetch */

import React from 'react';
import 'whatwg-fetch';

export default class UserStatisticPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = { successRate: 0 };
    this.getUserStatistics();
  }
  getUserStatistics() {
    fetch(`api/statistics/${this.props.username}`, { credentials: 'same-origin' })
      .then(response => response.json())
      .then(data => this.setState({ successRate: data }))
      .catch(ex => console.log('Fel vid hämtning av användarstatistik', ex));
  }
  render() {
    return (

Din totala svarsprocent är {this.state.successRate}%

    );
  }
}

UserStatisticPage.propTypes = {
  username: React.PropTypes.string.isRequired
};
<commit_msg>Fix typo after file renaming<commit_after>/* global fetch */

import React from 'react';
import 'whatwg-fetch';

export default class UserStatisticsPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = { successRate: 0 };
    this.getUserStatistics();
  }
  getUserStatistics() {
    fetch(`api/statistics/${this.props.username}`, { credentials: 'same-origin' })
      .then(response => response.json())
      .then(data => this.setState({ successRate: data }))
      .catch(ex => console.log('Fel vid hämtning av användarstatistik', ex));
  }
  render() {
    return (

Din totala svarsprocent är {this.state.successRate}%

    );
  }
}

UserStatisticsPage.propTypes = {
  username: React.PropTypes.string.isRequired
};
<|endoftext|>


<commit_before>var utils = require('./utils'),
    path = require('path'),
    semver = require('semver'),
    async = require('async'),
    mkdirp = require('mkdirp'),
    ncp = require('ncp').ncp,
    fs = require('fs');

var pathExists = fs.exists || path.exists;

/**
 * Looks for a project's package.json file. Walks up the directory tree until
 * it finds a package.json file or hits the root. Does not throw when no
 * packages.json is found, just returns null.
 *
 * @param {String} p - The starting path to search upwards from
 * @param {Function} callback(err, path)
 */

exports.findPackageJSON = function (p, callback) {
    var filename = path.resolve(p, 'package.json');
    pathExists(filename, function (exists) {
        if (exists) {
            return callback(null, filename);
        }
        var newpath = path.dirname(p);
        if (newpath === p) { // root directory
            return callback(null, null);
        }
        else {
            return exports.findPackageJSON(newpath, callback);
        }
    });
};

/**
 * Searches for package.json and returns an object with it's contents,
 * returns a default empty package.json object if no file found. Final
 * argument of the callback is the matching file path for package.json,
 * or null if none were found.
 *
 * @param {String} cwd - directory to search upwards from for package.json
 * @param {Function} callback(err, package_obj, path)
 */

exports.loadPackageJSON = async.memoize(function (cwd, callback) {
    exports.findPackageJSON(cwd, function (err, p) {
        if (err) {
            return callback(err, null, p);
        }
        if (!p) {
            // no package.json found, return default object
            // TODO: change the default to use jam.dependnecies
            return callback(null, {dependencies: {}}, p);
        }
        utils.readJSON(p, function (err, pkg) {
            if (err) {
                return callback(err, null, p);
            }
            try {
                exports.validate(pkg, p);
            }
            catch (e) {
                return callback(e);
            }
            return callback(null, pkg, p);
        });
    });
});

exports.validate = function (settings, filename) {
    // nothing to validate yet
};

/*
exports.createMeta = function (callback) {
    utils.getJamVersion(function (err, version) {
        if (err) {
            return callback(err);
        }
        callback(null, {
            jam_version: version,
            dependencies: {}
        });
    });
};

exports.writeMeta = function (package_dir, data, callback) {
    // TODO: add _rev field to meta file and check if changed since last read
    // before writing
    var filename = path.resolve(package_dir, 'jam.json');
    try {
        var str = JSON.stringify(data, null, 4);
    }
    catch (e) {
        return callback(e);
    }
    mkdirp(package_dir, function (err) {
        if (err) {
            return callback(err);
        }
        logger.info('updating', path.relative(process.cwd(), filename));
        fs.writeFile(filename, str, function (err) {
            // TODO: after adding _rev field, return updated _rev value in data here
            return callback(err, data);
        });
    });
};
*/

// adds RequireJS to project directory
exports.makeRequireJS = function (package_dir, config, callback) {
    var source = path.resolve(__dirname,'../node_modules/requirejs/require.js');
    var dest = path.resolve(package_dir, 'require.js');
    logger.info('updating', path.relative(process.cwd(), dest));
    fs.readFile(source, function (err, content) {
        var src = content.toString() + '\n' + config;
        fs.writeFile(dest, src, callback);
    });
};

exports.updateRequireConfig = function (package_dir, tree, callback) {
    console.log(['updateRequireConfig', package_dir, tree]);
    var packages = [];
    var shims = {};

    var dir = package_dir.split('/').map(encodeURIComponent).join('/');

    for (var name in tree) {
        if (name !== '_root') {
            var pkg = tree[name];
            var cfg = pkg.versions[pkg.current_version].config;
            var val = {
                name: name,
                location: dir + '/' + encodeURIComponent(name)
            };
            var main = (cfg.browser && cfg.browser.main) || cfg.main
            if (main) {
                val.main = main;
            }
            packages.push(val);
            if (cfg.shim) {
                shims[name] = cfg.shim;
            }
        }
    }

    utils.getJamVersion(function (err, version) {
        if (err) {
            return callback(err);
        }
        var data = {
            // TODO: useful option for cache-busting
            //urlArgs: '_jam_build=' + (new Date().getTime()),
            packages: packages,
            version: version,
            shim: shims
        }
        var src = 'var jam = ' + JSON.stringify(data, null, 4) + ';\n' +
            '\n' +
            'if (typeof require !== "undefined" && require.config) {\n' +
            '    require.config({packages: jam.packages, shim: jam.shim});\n' +
            '}\n' +
            'else {\n' +
            '    var require = {packages: jam.packages, shim: jam.shim};\n' +
            '}\n' +
            '\n' +
            'if (typeof exports !== "undefined" && ' +
                'typeof module !== "undefined") {\n' +
            '    module.exports = jam;\n' +
            '}';

        var filename = path.resolve(package_dir, 'require.config.js');
        mkdirp(package_dir, function (err) {
            if (err) {
                return callback(err);
            }
            logger.info('updating', path.relative(process.cwd(), filename));
            async.parallel([
                async.apply(fs.writeFile, filename, src),
                async.apply(exports.makeRequireJS, package_dir, src)
            ], callback);
        });
    });
};
<commit_msg>remove debug console.log<commit_after>var utils = require('./utils'),
    path = require('path'),
    semver = require('semver'),
    async = require('async'),
    mkdirp = require('mkdirp'),
    ncp = require('ncp').ncp,
    fs = require('fs');

var pathExists = fs.exists || path.exists;

/**
 * Looks for a project's package.json file. Walks up the directory tree until
 * it finds a package.json file or hits the root. Does not throw when no
 * packages.json is found, just returns null.
 *
 * @param {String} p - The starting path to search upwards from
 * @param {Function} callback(err, path)
 */

exports.findPackageJSON = function (p, callback) {
    var filename = path.resolve(p, 'package.json');
    pathExists(filename, function (exists) {
        if (exists) {
            return callback(null, filename);
        }
        var newpath = path.dirname(p);
        if (newpath === p) { // root directory
            return callback(null, null);
        }
        else {
            return exports.findPackageJSON(newpath, callback);
        }
    });
};

/**
 * Searches for package.json and returns an object with it's contents,
 * returns a default empty package.json object if no file found. Final
 * argument of the callback is the matching file path for package.json,
 * or null if none were found.
 *
 * @param {String} cwd - directory to search upwards from for package.json
 * @param {Function} callback(err, package_obj, path)
 */

exports.loadPackageJSON = async.memoize(function (cwd, callback) {
    exports.findPackageJSON(cwd, function (err, p) {
        if (err) {
            return callback(err, null, p);
        }
        if (!p) {
            // no package.json found, return default object
            // TODO: change the default to use jam.dependnecies
            return callback(null, {dependencies: {}}, p);
        }
        utils.readJSON(p, function (err, pkg) {
            if (err) {
                return callback(err, null, p);
            }
            try {
                exports.validate(pkg, p);
            }
            catch (e) {
                return callback(e);
            }
            return callback(null, pkg, p);
        });
    });
});

exports.validate = function (settings, filename) {
    // nothing to validate yet
};

/*
exports.createMeta = function (callback) {
    utils.getJamVersion(function (err, version) {
        if (err) {
            return callback(err);
        }
        callback(null, {
            jam_version: version,
            dependencies: {}
        });
    });
};

exports.writeMeta = function (package_dir, data, callback) {
    // TODO: add _rev field to meta file and check if changed since last read
    // before writing
    var filename = path.resolve(package_dir, 'jam.json');
    try {
        var str = JSON.stringify(data, null, 4);
    }
    catch (e) {
        return callback(e);
    }
    mkdirp(package_dir, function (err) {
        if (err) {
            return callback(err);
        }
        logger.info('updating', path.relative(process.cwd(), filename));
        fs.writeFile(filename, str, function (err) {
            // TODO: after adding _rev field, return updated _rev value in data here
            return callback(err, data);
        });
    });
};
*/

// adds RequireJS to project directory
exports.makeRequireJS = function (package_dir, config, callback) {
    var source = path.resolve(__dirname,'../node_modules/requirejs/require.js');
    var dest = path.resolve(package_dir, 'require.js');
    logger.info('updating', path.relative(process.cwd(), dest));
    fs.readFile(source, function (err, content) {
        var src = content.toString() + '\n' + config;
        fs.writeFile(dest, src, callback);
    });
};

exports.updateRequireConfig = function (package_dir, tree, callback) {
    var packages = [];
    var shims = {};

    var dir = package_dir.split('/').map(encodeURIComponent).join('/');

    for (var name in tree) {
        if (name !== '_root') {
            var pkg = tree[name];
            var cfg = pkg.versions[pkg.current_version].config;
            var val = {
                name: name,
                location: dir + '/' + encodeURIComponent(name)
            };
            var main = (cfg.browser && cfg.browser.main) || cfg.main
            if (main) {
                val.main = main;
            }
            packages.push(val);
            if (cfg.shim) {
                shims[name] = cfg.shim;
            }
        }
    }

    utils.getJamVersion(function (err, version) {
        if (err) {
            return callback(err);
        }
        var data = {
            // TODO: useful option for cache-busting
            //urlArgs: '_jam_build=' + (new Date().getTime()),
            packages: packages,
            version: version,
            shim: shims
        }
        var src = 'var jam = ' + JSON.stringify(data, null, 4) + ';\n' +
            '\n' +
            'if (typeof require !== "undefined" && require.config) {\n' +
            '    require.config({packages: jam.packages, shim: jam.shim});\n' +
            '}\n' +
            'else {\n' +
            '    var require = {packages: jam.packages, shim: jam.shim};\n' +
            '}\n' +
            '\n' +
            'if (typeof exports !== "undefined" && ' +
                'typeof module !== "undefined") {\n' +
            '    module.exports = jam;\n' +
            '}';

        var filename = path.resolve(package_dir, 'require.config.js');
        mkdirp(package_dir, function (err) {
            if (err) {
                return callback(err);
            }
            logger.info('updating', path.relative(process.cwd(), filename));
            async.parallel([
                async.apply(fs.writeFile, filename, src),
                async.apply(exports.makeRequireJS, package_dir, src)
            ], callback);
        });
    });
};
<|endoftext|>


<commit_before>'use strict'

const BrowserSync = require('browser-sync')
const Chokidar = require('chokidar')
const Fs = require('fs')
const Path = require('path')
const Mkdirp = require('mkdirp')

const Glob = require('./glob')
const Type = require('./enum').changes
const _ = require('./utils')

const ONCE = false
const CONTINOUSLY = true

function Project(target, _options) {

  this.options =  _.merge({
  }, _options)

  function fileLink(change, stats, cb) {
    // const cwd = process.cwd()
    // const src = Path.join(cwd, change.path)
    const dst = Path.join(target, change.path)
    Fs.link(change.orig, dst, function(err) {
      if (err) {
        cb(err)
      } else {
        console.log('# ~', dst, 'nlmod:', change.lmod, 'olmod:', stats.mtime.getTime())
        cb(null, true)
      }
    })
  }

  function fileWrite(change, stats, doc, cb) {
    // const cwd = process.cwd()
    // const src = Path.join(cwd, change.path)
    const dst = Path.join(target, change.path)
    Fs.writeFile(dst, doc.body, function(err) {
      if(err) {
        cb(err)
      } else {
        const mtime = change.lmod / 1000
        Fs.utimes(dst, mtime, mtime , function() {

          if (stats) {
            console.log('# >', dst, 'nlmod:', change.lmod, 'olmod:', stats.mtime.getTime())
          } else {
            console.log('# +', dst, 'nlmod:', change.lmod)
          }

          cb(null, true)
        })
      }
    })
  }

  function modifyChange(change, collection) {
    return new Promise(function(resolve, reject) {
      // const cwd = process.cwd()
      // const src = Path.join(cwd, change.path)
      const dst = Path.join(target, change.path)
      _.stats(dst, function(stats) {

        const unmodified = stats && stats.mtime.getTime() === change.lmod

        if (unmodified) {

          console.log('# =', dst)
          resolve(false)

        } else {

          const file = collection.get(change.path)
          // const link = file.load.isFulfilled === false
          const link = false

          file.load.then(function(doc) {

            Mkdirp(Path.dirname(dst), function(dirErr) {
              if (dirErr) throw dirErr

              if (link) {

                fileLink(change, stats, function(linkErr, res) {
                  if (linkErr) throw linkErr
                  resolve(res)
                })

              } else {

                fileWrite(change, stats, doc, function(writeErr, res) {
                  if (writeErr) throw writeErr
                  resolve(res)
                })

              }
            })

          }).catch(function(err) {
            reject(err)
          })

        }
      })
    })
  }

  function deleteChange(change, collection) {
    return new Promise(function(resolve, reject) {
      // const cwd = process.cwd()
      // const src = Path.join(cwd, change.path)
      const dst = Path.join(target, change.path)
      Fs.unlink(dst, function(err) {
        if(err) {
          reject(err)
        } else {
          // rm_empty_dirs(basedir(changes.path))
          console.log('# -', dst)
          resolve(true)
        }
      })
    })
  }

  function applyChange(change, collection) {
    if (change.type === Type.D) {
      return deleteChange(change, collection)
    } else {
      return modifyChange(change, collection)
    }
  }

  function updateCollection(collection, changesIn, cb) {

    console.time('changes')

    return collection.update(changesIn).then(function(changesOut) {
      return Promise.all(changesOut.map(function(change) { return applyChange(change, collection) })).then(function(applied) {
        return changesOut.filter(function(changes, i) { return applied[i] })
      }).then(function(applied) {

        console.timeEnd('changes')

        if (cb && applied.length > 0) {
          // notify about what files were changed
          cb(applied.map(function(f) { return f.path }))
        }

      })
    })
  }

  function watch(continues, cb) {

    let changes = []
    let ready = false

    function update() {
      if (ready) {
        try {
          cb(changes)
          changes = []
        } catch(err) {
          console.error('ERROR2', err, err.stack)
        }
      }
    }

    Chokidar.watch('.', {
      cwd: '.',
      ignored: [ /[\/\\]\./, /node_modules/, /build/ ],
      ignoreInitial: false,
      depth: undefined,
      alwaysStat: true,
      interval: 100,
      persistent: continues,
    }).on('ready', function() {
      ready = true
      update()
    }).on('add', function(path, stats) {
      changes.push({
        type: Type.A,
        path: path,
        lmod: stats.mtime.getTime(),
      })
      update()
    }).on('change', function(path, stats) {
      changes.push({
        type: Type.M,
        path: path,
        lmod: stats.mtime.getTime(),
      })
      update()
    }).on('unlink', function(path) {
      changes.push({
        type: Type.D,
        path: path,
        lmod: new Date().getTime()
      })
      update()
    }).on('error', function(err) {
      console.error('ERROR3', err, err.stack)
    })
  }

  this.glob = function(pattern, options) {
    return new Glob(pattern, options)
  }

  // this.plugin = function(name) {
  //   return require(name)(this)
  // }

  this.build = function(collection) {
    return new Promise(function(resolve){
      watch(ONCE, function(changes) {
        resolve(updateCollection(collection, changes))
      }).catch(function(err) {

        console.error('ERROR4', err, err.stack)

      })
    })
  }

  this.watch = function(collection, options) {

    const bs = options && options.browsersync ? BrowserSync.create() : null

    if (bs) {
      bs.init({
        server: target,
        port: 8080,
        open: false,
        logLevel: 'silent'
        // middleware: [app]
      })
      console.log('listening on port 8080')
    }

    watch(CONTINOUSLY, function(changes) {
      return updateCollection(collection, changes, function(files) {
        console.log('reloading', files)
        if (bs) {
          bs.reload(files)
        }
      }).catch(function(err) {

        bs.notify(err.message, 5000)
        console.error('ERROR5', err, err.stack)
      })
    })
  }
}

module.exports = Project
<commit_msg>fixed resolve/reject behaviour on builds<commit_after>'use strict'

const BrowserSync = require('browser-sync')
const Chokidar = require('chokidar')
const Fs = require('fs')
const Path = require('path')
const Mkdirp = require('mkdirp')

const Glob = require('./glob')
const Type = require('./enum').changes
const _ = require('./utils')

const ONCE = false
const CONTINOUSLY = true

function Project(target, _options) {

  this.options =  _.merge({
  }, _options)

  function fileLink(change, stats, cb) {
    // const cwd = process.cwd()
    // const src = Path.join(cwd, change.path)
    const dst = Path.join(target, change.path)
    Fs.link(change.orig, dst, function(err) {
      if (err) {
        cb(err)
      } else {
        console.log('# ~', dst, 'nlmod:', change.lmod, 'olmod:', stats.mtime.getTime())
        cb(null, true)
      }
    })
  }

  function fileWrite(change, stats, doc, cb) {
    // const cwd = process.cwd()
    // const src = Path.join(cwd, change.path)
    const dst = Path.join(target, change.path)
    Fs.writeFile(dst, doc.body, function(err) {
      if(err) {
        cb(err)
      } else {
        const mtime = change.lmod / 1000
        Fs.utimes(dst, mtime, mtime , function() {

          if (stats) {
            console.log('# >', dst, 'nlmod:', change.lmod, 'olmod:', stats.mtime.getTime())
          } else {
            console.log('# +', dst, 'nlmod:', change.lmod)
          }

          cb(null, true)
        })
      }
    })
  }

  function modifyChange(change, collection) {
    return new Promise(function(resolve, reject) {
      // const cwd = process.cwd()
      // const src = Path.join(cwd, change.path)
      const dst = Path.join(target, change.path)
      _.stats(dst, function(stats) {

        const unmodified = stats && stats.mtime.getTime() === change.lmod

        if (unmodified) {

          console.log('# =', dst)
          resolve(false)

        } else {

          const file = collection.get(change.path)
          // const link = file.load.isFulfilled === false
          const link = false

          file.load.then(function(doc) {

            Mkdirp(Path.dirname(dst), function(dirErr) {
              if (dirErr) throw dirErr

              if (link) {

                fileLink(change, stats, function(linkErr, res) {
                  if (linkErr) throw linkErr
                  resolve(res)
                })

              } else {

                fileWrite(change, stats, doc, function(writeErr, res) {
                  if (writeErr) throw writeErr
                  resolve(res)
                })

              }
            })

          }).catch(function(err) {
            reject(err)
          })

        }
      })
    })
  }

  function deleteChange(change, collection) {
    return new Promise(function(resolve, reject) {
      // const cwd = process.cwd()
      // const src = Path.join(cwd, change.path)
      const dst = Path.join(target, change.path)
      Fs.unlink(dst, function(err) {
        if(err) {
          reject(err)
        } else {
          // rm_empty_dirs(basedir(changes.path))
          console.log('# -', dst)
          resolve(true)
        }
      })
    })
  }

  function applyChange(change, collection) {
    if (change.type === Type.D) {
      return deleteChange(change, collection)
    } else {
      return modifyChange(change, collection)
    }
  }

  function updateCollection(collection, changesIn, cb) {

    console.time('changes')

    return collection.update(changesIn).then(function(changesOut) {
      return Promise.all(changesOut.map(function(change) { return applyChange(change, collection) })).then(function(applied) {
        return changesOut.filter(function(changes, i) { return applied[i] })
      }).then(function(applied) {

        console.timeEnd('changes')

        if (cb && applied.length > 0) {
          // notify about what files were changed
          cb(applied.map(function(f) { return f.path }))
        }

      })
    })
  }

  function watch(continues, cb) {

    let changes = []
    let ready = false

    function update() {
      if (ready) {
        try {
          cb(changes)
          changes = []
        } catch(err) {
          console.error('ERROR2', err, err.stack)
        }
      }
    }

    Chokidar.watch('.', {
      cwd: '.',
      ignored: [ /[\/\\]\./, /node_modules/, /build/ ],
      ignoreInitial: false,
      depth: undefined,
      alwaysStat: true,
      interval: 100,
      persistent: continues,
    }).on('ready', function() {
      ready = true
      update()
    }).on('add', function(path, stats) {
      changes.push({
        type: Type.A,
        path: path,
        lmod: stats.mtime.getTime(),
      })
      update()
    }).on('change', function(path, stats) {
      changes.push({
        type: Type.M,
        path: path,
        lmod: stats.mtime.getTime(),
      })
      update()
    }).on('unlink', function(path) {
      changes.push({
        type: Type.D,
        path: path,
        lmod: new Date().getTime()
      })
      update()
    }).on('error', function(err) {
      console.error('ERROR3', err, err.stack)
    })
  }

  this.glob = function(pattern, options) {
    return new Glob(pattern, options)
  }

  // this.plugin = function(name) {
  //   return require(name)(this)
  // }

  this.build = function(collection) {
    return new Promise(function(resolve, reject){
      watch(ONCE, function(changes) {
        updateCollection(collection, changes).then(function(results) {
          resolve(results)
        }).catch(function(err) {
          console.error('ERROR4', err, err.stack)
          reject(err)
        })
      })
    })
  }

  this.watch = function(collection, options) {

    const bs = options && options.browsersync ? BrowserSync.create() : null

    if (bs) {
      bs.init({
        server: target,
        port: 8080,
        open: false,
        logLevel: 'silent'
        // middleware: [app]
      })
      console.log('listening on port 8080')
    }

    watch(CONTINOUSLY, function(changes) {
      return updateCollection(collection, changes, function(files) {
        console.log('reloading', files)
        if (bs) {
          bs.reload(files)
        }
      }).catch(function(err) {

        bs.notify(err.message, 5000)
        console.error('ERROR5', err, err.stack)
      })
    })
  }
}

module.exports = Project
<|endoftext|>


<commit_before>'use babel';

import {Emitter} from 'atom';
import _ from 'underscore-plus';
import Settings from './settings';
import DB from './db';

export default class Project {

  constructor(props={}) {
    this.props = {};
    this.emitter = new Emitter();
    this.db = new DB();
    this.updateProps(props);
    this.lookForUpdates();
  }

  get requiredProperties() {
    return ['title', 'paths'];
  }

  get defaultProps() {
    return {
      title: '',
      paths: [],
      icon: 'icon-chevron-right',
      settings: {},
      group: null,
      devMode: false,
      template: null
    };
  }

  updateProps(props) {
    this.props = _.deepExtend(this.defaultProps, props);
  }

  getPropsToSave() {
    let saveProps = {};
    let value;
    for (key in this.props) {
      value = this.props[key];
      if (!this.isDefaultProp(key, value)) {
        saveProps[key] = value;
      }
    }

    return saveProps;
  }

  isDefaultProp(key, value) {
    if (!this.defaultProps[key]) {
      return false;
    }

    if (this.defaultProps[key] === value) {
      return true;
    }

    return false;
  }

  set(key, value) {
    this.props[key] = value;
    this.save();
  }

  unset(key) {
    if (_.has(this.defaultProps, key)) {
      this.props[key] = this.defaultProps[key];
    } else {
      this.props[key] = null;
    }

    this.save();
  }

  lookForUpdates() {
    if (this.props._id) {
      this.db.setSearchQuery('_id', this.props._id);
      this.db.onUpdate((props) => {
        if (props) {
          let updatedProps = _.deepExtend(this.defaultProps, props);
          if (!_.isEqual(this.props, updatedProps)) {
            this.updateProps(props);
            this.emitter.emit('updated');
            if (this.isCurrent()) {
              this.load();
            }
          }
        } else {
          this.db.setSearchQuery('paths', this.props.paths);
          this.db.find((props) => {
            this.updateProps(props);
            this.db.setSearchQuery('_id', this.props._id);
            this.emitter.emit('updated');
            if (this.isCurrent()) {
              this.load();
            }
          });
        }
      });
    }
  }

  isCurrent() {
    let activePath = atom.project.getPaths()[0];
    let mainPath = this.props.paths[0];
    if (activePath === mainPath) {
      return true;
    }

    return false;
  }

  isValid() {
    let valid = true;
    for (key of this.requiredProperties) {
      if (!this.props[key] || !this.props[key].length) {
        valid = false;
      }
    }

    return valid;
  }

  load() {
    if (this.isCurrent()) {
      let projectSettings = new Settings();
      projectSettings.load(this.props.settings);
    }
  }

  save() {
    if (this.isValid()) {
      if (this.props._id) {
        this.db.update(this.getPropsToSave());
      } else {
        this.db.add(this.getPropsToSave(), (id) => {
          this.props._id = id;
          this.lookForUpdates();
        });
      }

      return true;
    }

    return false;
  }

  remove() {
    this.db.delete(this.props._id);
  }

  open() {
    atom.open({
      pathsToOpen: this.props.paths,
      devMode: this.props.devMode
    });
  }

  onUpdate(callback) {
    this.emitter.on('updated', () => {
      callback();
    });
  }
}
<commit_msg>Use inline function<commit_after>'use babel';

import {Emitter} from 'atom';
import _ from 'underscore-plus';
import Settings from './settings';
import DB from './db';

export default class Project {

  constructor(props={}) {
    this.props = {};
    this.emitter = new Emitter();
    this.db = new DB();
    this.updateProps(props);
    this.lookForUpdates();
  }

  get requiredProperties() {
    return ['title', 'paths'];
  }

  get defaultProps() {
    return {
      title: '',
      paths: [],
      icon: 'icon-chevron-right',
      settings: {},
      group: null,
      devMode: false,
      template: null
    };
  }

  updateProps(props) {
    this.props = _.deepExtend(this.defaultProps, props);
  }

  getPropsToSave() {
    let saveProps = {};
    let value;
    for (key in this.props) {
      value = this.props[key];
      if (!this.isDefaultProp(key, value)) {
        saveProps[key] = value;
      }
    }

    return saveProps;
  }

  isDefaultProp(key, value) {
    if (!this.defaultProps[key]) {
      return false;
    }

    if (this.defaultProps[key] === value) {
      return true;
    }

    return false;
  }

  set(key, value) {
    this.props[key] = value;
    this.save();
  }

  unset(key) {
    if (_.has(this.defaultProps, key)) {
      this.props[key] = this.defaultProps[key];
    } else {
      this.props[key] = null;
    }

    this.save();
  }

  lookForUpdates() {
    if (this.props._id) {
      this.db.setSearchQuery('_id', this.props._id);
      this.db.onUpdate((props) => {
        if (props) {
          let updatedProps = _.deepExtend(this.defaultProps, props);
          if (!_.isEqual(this.props, updatedProps)) {
            this.updateProps(props);
            this.emitter.emit('updated');
            if (this.isCurrent()) {
              this.load();
            }
          }
        } else {
          this.db.setSearchQuery('paths', this.props.paths);
          this.db.find((props) => {
            this.updateProps(props);
            this.db.setSearchQuery('_id', this.props._id);
            this.emitter.emit('updated');
            if (this.isCurrent()) {
              this.load();
            }
          });
        }
      });
    }
  }

  isCurrent() {
    let activePath = atom.project.getPaths()[0];
    let mainPath = this.props.paths[0];
    if (activePath === mainPath) {
      return true;
    }

    return false;
  }

  isValid() {
    let valid = true;
    for (key of this.requiredProperties) {
      if (!this.props[key] || !this.props[key].length) {
        valid = false;
      }
    }

    return valid;
  }

  load() {
    if (this.isCurrent()) {
      let projectSettings = new Settings();
      projectSettings.load(this.props.settings);
    }
  }

  save() {
    if (this.isValid()) {
      if (this.props._id) {
        this.db.update(this.getPropsToSave());
      } else {
        this.db.add(this.getPropsToSave(), (id) => {
          this.props._id = id;
          this.lookForUpdates();
        });
      }

      return true;
    }

    return false;
  }

  remove() {
    this.db.delete(this.props._id);
  }

  open() {
    atom.open({
      pathsToOpen: this.props.paths,
      devMode: this.props.devMode
    });
  }

  onUpdate(callback) {
    this.emitter.on('updated', () => callback());
  }
}
<|endoftext|>