<commit_before>'use strict';
/* eslint-env mocha */
var assert = require('assert');

Object.assign = undefined;
var objectAssign = require('./');

it('should have the correct length', function () {
	assert.equal(objectAssign.length, 2);
});

it('should throw when target is not an object', function () {
	assert.throws(function () {
		objectAssign(null);
	}, TypeError);
	assert.throws(function () {
		objectAssign(undefined);
	}, TypeError);
});

it('should objectAssign own enumerable properties from source to target object', function () {
	assert.deepEqual(objectAssign({foo: 0}, {bar: 1}), {
		foo: 0,
		bar: 1
	});
	assert.deepEqual(objectAssign({foo: 0}, null, undefined), {foo: 0});
	assert.deepEqual(objectAssign({foo: 0}, null, undefined, {bar: 1}, null), {
		foo: 0,
		bar: 1
	});
});

it('should throw on null/undefined target', function () {
	assert.throws(function () {
		objectAssign(null, {});
	});

	assert.throws(function () {
		objectAssign(undefined, {});
	});

	assert.throws(function () {
		objectAssign(undefined, undefined);
	});
});

it('should not throw on null/undefined sources', function () {
	assert.doesNotThrow(function () {
		objectAssign({}, null);
	});

	assert.doesNotThrow(function () {
		objectAssign({}, undefined);
	});

	assert.doesNotThrow(function () {
		objectAssign({}, undefined, null);
	});
});

it('should support multiple sources', function () {
	assert.deepEqual(objectAssign({foo: 0}, {bar: 1}, {bar: 2}), {
		foo: 0,
		bar: 2
	});
	assert.deepEqual(objectAssign({}, {}, {foo: 1}), {foo: 1});
});

it('should only iterate own keys', function () {
	var Unicorn = function () {};
	Unicorn.prototype.rainbows = 'many';
	var unicorn = new Unicorn();
	unicorn.bar = 1;

	assert.deepEqual(objectAssign({foo: 1}, unicorn), {
		foo: 1,
		bar: 1
	});
});

it('should return the modified target object', function () {
	var target = {};
	var returned = objectAssign(target, {a: 1});
	assert.equal(returned, target);
});

it('should support `Object.create(null)` objects', function () {
	var obj = Object.create(null);
	obj.foo = true;
	assert.deepEqual(objectAssign({}, obj), {foo: true});
});

it('should preserve property order', function () {
	var letters = 'abcdefghijklmnopqrst';
	var source = {};
	letters.split('').forEach(function (letter) {
		source[letter] = letter;
	});
	var target = objectAssign({}, source);
	assert.equal(Object.keys(target).join(''), letters);
});

if (typeof Symbol !== 'undefined') {
	it('should support symbol properties', function () {
		var target = {};
		var source = {};
		var sym = Symbol('foo');
		source[sym] = 'bar';
		objectAssign(target, source);
		assert.equal(target[sym], 'bar');
	});

	it('should only copy enumerable symbols', function () {
		var target = {};
		var source = {};
		var sym = Symbol('foo');
		Object.defineProperty(source, sym, {
			enumerable: false,
			value: 'bar'
		});
		objectAssign(target, source);
		assert.equal(target[sym], undefined);
	});
}
<commit_msg>add missing test for target being a primitive (#34)<commit_after>'use strict';
/* eslint-env mocha */
var assert = require('assert');

Object.assign = undefined;
var objectAssign = require('./');

it('should have the correct length', function () {
	assert.equal(objectAssign.length, 2);
});

it('should throw when target is not an object', function () {
	assert.throws(function () {
		objectAssign(null);
	}, TypeError);
	assert.throws(function () {
		objectAssign(undefined);
	}, TypeError);
});

it('should objectAssign own enumerable properties from source to target object', function () {
	assert.deepEqual(objectAssign({foo: 0}, {bar: 1}), {
		foo: 0,
		bar: 1
	});
	assert.deepEqual(objectAssign({foo: 0}, null, undefined), {foo: 0});
	assert.deepEqual(objectAssign({foo: 0}, null, undefined, {bar: 1}, null), {
		foo: 0,
		bar: 1
	});
});

it('should throw on null/undefined target', function () {
	assert.throws(function () {
		objectAssign(null, {});
	});

	assert.throws(function () {
		objectAssign(undefined, {});
	});

	assert.throws(function () {
		objectAssign(undefined, undefined);
	});
});

it('should not throw on null/undefined sources', function () {
	assert.doesNotThrow(function () {
		objectAssign({}, null);
	});

	assert.doesNotThrow(function () {
		objectAssign({}, undefined);
	});

	assert.doesNotThrow(function () {
		objectAssign({}, undefined, null);
	});
});

it('should support multiple sources', function () {
	assert.deepEqual(objectAssign({foo: 0}, {bar: 1}, {bar: 2}), {
		foo: 0,
		bar: 2
	});
	assert.deepEqual(objectAssign({}, {}, {foo: 1}), {foo: 1});
});

it('should only iterate own keys', function () {
	var Unicorn = function () {};
	Unicorn.prototype.rainbows = 'many';
	var unicorn = new Unicorn();
	unicorn.bar = 1;

	assert.deepEqual(objectAssign({foo: 1}, unicorn), {
		foo: 1,
		bar: 1
	});
});

it('should return the modified target object', function () {
	var target = {};
	var returned = objectAssign(target, {a: 1});
	assert.equal(returned, target);
});

it('should support `Object.create(null)` objects', function () {
	var obj = Object.create(null);
	obj.foo = true;
	assert.deepEqual(objectAssign({}, obj), {foo: true});
});

it('should preserve property order', function () {
	var letters = 'abcdefghijklmnopqrst';
	var source = {};
	letters.split('').forEach(function (letter) {
		source[letter] = letter;
	});
	var target = objectAssign({}, source);
	assert.equal(Object.keys(target).join(''), letters);
});

it('should accept primitives as target', function () {
	var target = objectAssign('abcdefg', {foo: 'bar'});
	var strObj = Object('abcdefg');
	strObj.foo = 'bar';
	assert.deepEqual(target, strObj);
});

if (typeof Symbol !== 'undefined') {
	it('should support symbol properties', function () {
		var target = {};
		var source = {};
		var sym = Symbol('foo');
		source[sym] = 'bar';
		objectAssign(target, source);
		assert.equal(target[sym], 'bar');
	});

	it('should only copy enumerable symbols', function () {
		var target = {};
		var source = {};
		var sym = Symbol('foo');
		Object.defineProperty(source, sym, {
			enumerable: false,
			value: 'bar'
		});
		objectAssign(target, source);
		assert.equal(target[sym], undefined);
	});
}
<|endoftext|>


<commit_before>var mocha = require('mocha');
var chai = require('chai');
var assert = require('chai').assert;
var hello = require('../src/hello');

describe('hello', function() {
  it("Returns a string of hello plus the name that was passed.", function() {
    var output = hello.sayHello("Dave");
    assert.equal(output, "Hello Johnny.");
  });
});
<commit_msg>Resolving conflict in hell-test.<commit_after>var mocha = require('mocha');
var chai = require('chai');
var assert = require('chai').assert;
var hello = require('../src/hello');

describe('hello', function() {
  it("Returns a string of hello plus the name that was passed.", function() {
    var output = hello.sayHello("Dave");
    assert.equal(output, "Hello Dave.");
  });
});
<|endoftext|>


<commit_before>test('text node 0', function() {
    var node = htmlToJson('a').children[0]
    addIds(node)
    equal(node.name, '#text', 'node name')
    equal(node.text, 'a', 'node text')
    equal(node.id, 123798090, 'node id')
})

test('text node 1', function() {
    var node = htmlToJson(' abc ').children[0]
    addIds(node)
    equal(node.name, '#text', 'node name')
    equal(node.text, ' abc ', 'node text')
    equal(node.id, 315884367, 'node id')
})

test('empty node 0', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 6422626, 'node id')
})

test('empty node 1', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 6422626, 'node id')
})

test('empty node 2', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 6422626, 'node id')
})

test('empty node 3', function() {
    var node = htmlToJson('<\na\n/\n>').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 6422626, 'node id')
})

test('closing tag', function() {
    deepEqual(htmlToJson(''), {})
    deepEqual(htmlToJson(''), {})
    deepEqual(htmlToJson('<\n/\n a\n >'), {})
})

test('attributes 0', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    deepEqual(node.attributes, {id: ''}, 'attributes')
    equal(node.id, 39584047, 'node id')
})

test('attributes 1', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    deepEqual(node.attributes, {id: ''}, 'attributes')
    equal(node.id, 39584047, 'node id')
})

test('attributes 2', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    deepEqual(node.attributes, {id: ''}, 'attribtues')
    equal(node.id, 39584047, 'node id')
})

test('attributes 3', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    deepEqual(node.attributes, {id: 'a'}, 'attributes')
    equal(node.id, 65798544, 'node id')
})

test('attributes 4', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    deepEqual(node.attributes, {id: 'a'}, 'attributes')
    equal(node.id, 65798544, 'node id')
})

test('attributes 5', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    deepEqual(node.attributes, {id: "a'"}, 'attributes')
    equal(node.id, 94568887, 'node id')
})

test('attributes 6', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    deepEqual(node.attributes, {id: "a='b'"}, 'attributes')
    equal(node.id, 209715837, 'node id')
})

test('attributes 7', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    deepEqual(node.attributes, {id: 'a', class: '\nb '}, 'attributes')
    equal(node.id, 499844146, 'node id')
})

test('attributes 8', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    deepEqual(node.attributes, {attr1: 'first', attr2: 'second'}, 'attributes')
    equal(node.id, 1708460255, 'node id')
})

test('attributes 9', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    deepEqual(node.attributes, {attr: '
'}, 'attributes')
    equal(node.id, 239928071, 'node id')
})

test('children 0', function() {
    var node = htmlToJson('a').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 168362667, 'node id')
    equal(node.children[0].name, '#text', 'child name')
    equal(node.children[0].text, 'a', 'child text')
    equal(node.children.length, 1, 'children length')
})

test('children 1', function() {
    var node = htmlToJson('\n').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 162660948, 'node id')
    equal(node.children[0].name, '#text', 'child 0 name')
    equal(node.children[0].text, '\n', 'child 0 text')
    equal(node.children[0].id, 118096371, 'child 0 id')
    equal(node.children.length, 1, 'children length')
})

test('children 2', function() {
    var node = htmlToJson(' a \n b ').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 479593367, 'node id')
    equal(node.children[0].name, '#text', 'child 0 name')
    equal(node.children[0].text, ' a \n b ', 'child 0 text')
    equal(node.children[0].id, 396886838, 'child 0 id')
    equal(node.children.length, 1, 'children length')
})

test('children 3', function() {
    var node = htmlToJson('\n').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 208143030, 'node id')
    equal(node.children[0].name, '#text', 'child 0 name')
    equal(node.children[0].text, '\n', 'child 0 text')
    equal(node.children[0].id, 118096371, 'child 0 id')
    equal(node.children[1].name, 'b', 'child 1 name')
    equal(node.children[1].id, 6488163, 'child 1 id')
    equal(node.children.length, 2, 'children length')
})

test('children 4', function() {
    var node = htmlToJson('\n\n\n<c/>').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 762774805, 'node id')
    equal(node.children[0].name, '#text', 'child 0 name')
    equal(node.children[0].text, '\n', 'child 0 text')
    equal(node.children[0].id, 118096371, 'child 0 id')
    equal(node.children[1].name, 'b', 'child 1 name')
    equal(node.children[1].id, 6488163, 'child 1 id')
    equal(node.children[2].name, '#text', 'child 2 name')
    equal(node.children[2].text, '\n\n', 'child 2 text')
    equal(node.children[2].id, 151454205, 'child 2 id')
    equal(node.children[3].name, 'c', 'child 3 name')
    equal(node.children[3].id, 6553700, 'child 3 id')
    equal(node.children.length, 4, 'children length')
})

test('children 5', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 19202243, 'node id')
    equal(node.children[0].name, 'a', 'child 0 name')
    equal(node.children[0].id, 6422626, 'child 0 id')
    equal(node.children.length, 1, 'children length')
})

test('children 5', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 19267780, 'node id')
    equal(node.children[0].name, 'b', 'child 0 name')
    equal(node.children[0].id, 6488163, 'child 0 id')
    equal(node.children.length, 1, 'children length')
})

test('children 6', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 240255805, 'node id')
    equal(node.children[0].name, 'b', 'child 0 name')
    equal(node.children[0].id, 189334236, 'child 0 id')
    deepEqual(node.children[0].attributes, {class: 'c'}, 'child 0 attributes')
    equal(node.children.length, 1, 'children length')
})

test('collection 0', function() {
    var nodes = htmlToJson('').children
    addIds(nodes)
    equal(nodes[0].name, 'a', 'node 0 name')
    equal(nodes[0].id, 6422626, 'node 0 id')
    equal(nodes[1].name, 'b', 'node 1 name')
    equal(nodes[1].id, 6488163, 'node 1 id')
    equal(nodes.length, 2, 'nodes length')
})

test('collection 1', function() {
    var node = htmlToJson('<c/>').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 38600999, 'node id')
    equal(node.children[0].name, 'b', 'child 0 name')
    equal(node.children[0].id, 6488163, 'child 0 id')
    equal(node.children[1].name, 'c', 'child 1 name')
    equal(node.children[1].id, 6553700, 'child 1 id')
    equal(node.children.length, 2, 'children length')
})

test('collection 2', function() {
    var node = htmlToJson('<c/>').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 38600999, 'node id')
    equal(node.children[0].name, 'b', 'child 0 name')
    equal(node.children[0].id, 6488163, 'child 0 id')
    equal(node.children[1].name, 'c', 'child 1 name')
    equal(node.children[1].id, 6553700, 'child 1 id')
    equal(node.children.length, 2, 'children length')
})
<commit_msg>test names<commit_after>test('text node 0', function() {
    var node = htmlToJson('a').children[0]
    addIds(node)
    equal(node.name, '#text', 'node name')
    equal(node.text, 'a', 'node text')
    equal(node.id, 123798090, 'node id')
})

test('text node 1', function() {
    var node = htmlToJson(' abc ').children[0]
    addIds(node)
    equal(node.name, '#text', 'node name')
    equal(node.text, ' abc ', 'node text')
    equal(node.id, 315884367, 'node id')
})

test('empty node 0', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 6422626, 'node id')
})

test('empty node 1', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 6422626, 'node id')
})

test('empty node 2', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 6422626, 'node id')
})

test('empty node 3', function() {
    var node = htmlToJson('<\na\n/\n>').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 6422626, 'node id')
})

test('closing tag', function() {
    deepEqual(htmlToJson(''), {})
    deepEqual(htmlToJson(''), {})
    deepEqual(htmlToJson('<\n/\n a\n >'), {})
})

test('attributes 0', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    deepEqual(node.attributes, {id: ''}, 'attributes')
    equal(node.id, 39584047, 'node id')
})

test('attributes 1', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    deepEqual(node.attributes, {id: ''}, 'attributes')
    equal(node.id, 39584047, 'node id')
})

test('attributes 2', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    deepEqual(node.attributes, {id: ''}, 'attribtues')
    equal(node.id, 39584047, 'node id')
})

test('attributes 3', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    deepEqual(node.attributes, {id: 'a'}, 'attributes')
    equal(node.id, 65798544, 'node id')
})

test('attributes 4', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    deepEqual(node.attributes, {id: 'a'}, 'attributes')
    equal(node.id, 65798544, 'node id')
})

test('attributes 5', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    deepEqual(node.attributes, {id: "a'"}, 'attributes')
    equal(node.id, 94568887, 'node id')
})

test('attributes 6', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    deepEqual(node.attributes, {id: "a='b'"}, 'attributes')
    equal(node.id, 209715837, 'node id')
})

test('attributes 7', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    deepEqual(node.attributes, {id: 'a', class: '\nb '}, 'attributes')
    equal(node.id, 499844146, 'node id')
})

test('attributes 8', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    deepEqual(node.attributes, {attr1: 'first', attr2: 'second'}, 'attributes')
    equal(node.id, 1708460255, 'node id')
})

test('attributes 9', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    deepEqual(node.attributes, {attr: '
'}, 'attributes')
    equal(node.id, 239928071, 'node id')
})

test('children 0', function() {
    var node = htmlToJson('a').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 168362667, 'node id')
    equal(node.children[0].name, '#text', 'child name')
    equal(node.children[0].text, 'a', 'child text')
    equal(node.children.length, 1, 'children length')
})

test('children 1', function() {
    var node = htmlToJson('\n').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 162660948, 'node id')
    equal(node.children[0].name, '#text', 'child 0 name')
    equal(node.children[0].text, '\n', 'child 0 text')
    equal(node.children[0].id, 118096371, 'child 0 id')
    equal(node.children.length, 1, 'children length')
})

test('children 2', function() {
    var node = htmlToJson(' a \n b ').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 479593367, 'node id')
    equal(node.children[0].name, '#text', 'child 0 name')
    equal(node.children[0].text, ' a \n b ', 'child 0 text')
    equal(node.children[0].id, 396886838, 'child 0 id')
    equal(node.children.length, 1, 'children length')
})

test('children 3', function() {
    var node = htmlToJson('\n').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 208143030, 'node id')
    equal(node.children[0].name, '#text', 'child 0 name')
    equal(node.children[0].text, '\n', 'child 0 text')
    equal(node.children[0].id, 118096371, 'child 0 id')
    equal(node.children[1].name, 'b', 'child 1 name')
    equal(node.children[1].id, 6488163, 'child 1 id')
    equal(node.children.length, 2, 'children length')
})

test('children 4', function() {
    var node = htmlToJson('\n\n\n<c/>').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 762774805, 'node id')
    equal(node.children[0].name, '#text', 'child 0 name')
    equal(node.children[0].text, '\n', 'child 0 text')
    equal(node.children[0].id, 118096371, 'child 0 id')
    equal(node.children[1].name, 'b', 'child 1 name')
    equal(node.children[1].id, 6488163, 'child 1 id')
    equal(node.children[2].name, '#text', 'child 2 name')
    equal(node.children[2].text, '\n\n', 'child 2 text')
    equal(node.children[2].id, 151454205, 'child 2 id')
    equal(node.children[3].name, 'c', 'child 3 name')
    equal(node.children[3].id, 6553700, 'child 3 id')
    equal(node.children.length, 4, 'children length')
})

test('children 5', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 19202243, 'node id')
    equal(node.children[0].name, 'a', 'child 0 name')
    equal(node.children[0].id, 6422626, 'child 0 id')
    equal(node.children.length, 1, 'children length')
})

test('children 6', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 19267780, 'node id')
    equal(node.children[0].name, 'b', 'child 0 name')
    equal(node.children[0].id, 6488163, 'child 0 id')
    equal(node.children.length, 1, 'children length')
})

test('children 7', function() {
    var node = htmlToJson('').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 240255805, 'node id')
    equal(node.children[0].name, 'b', 'child 0 name')
    equal(node.children[0].id, 189334236, 'child 0 id')
    deepEqual(node.children[0].attributes, {class: 'c'}, 'child 0 attributes')
    equal(node.children.length, 1, 'children length')
})

test('collection 0', function() {
    var nodes = htmlToJson('').children
    addIds(nodes)
    equal(nodes[0].name, 'a', 'node 0 name')
    equal(nodes[0].id, 6422626, 'node 0 id')
    equal(nodes[1].name, 'b', 'node 1 name')
    equal(nodes[1].id, 6488163, 'node 1 id')
    equal(nodes.length, 2, 'nodes length')
})

test('collection 1', function() {
    var node = htmlToJson('<c/>').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 38600999, 'node id')
    equal(node.children[0].name, 'b', 'child 0 name')
    equal(node.children[0].id, 6488163, 'child 0 id')
    equal(node.children[1].name, 'c', 'child 1 name')
    equal(node.children[1].id, 6553700, 'child 1 id')
    equal(node.children.length, 2, 'children length')
})

test('collection 2', function() {
    var node = htmlToJson('<c/>').children[0]
    addIds(node)
    equal(node.name, 'a', 'node name')
    equal(node.id, 38600999, 'node id')
    equal(node.children[0].name, 'b', 'child 0 name')
    equal(node.children[0].id, 6488163, 'child 0 id')
    equal(node.children[1].name, 'c', 'child 1 name')
    equal(node.children[1].id, 6553700, 'child 1 id')
    equal(node.children.length, 2, 'children length')
})
<|endoftext|>


<commit_before>var iconv = require('iconv-lite');
var zlib = require('zlib');
var MAX_REQ_SIZE = 128 * 1024;
var MAX_RES_SIZE = 256 * 1024;
var TIMEOUT = 10000;
var MAX_LENGTH = 512;
var MIN_LENGTH = 412;
var COUNT = 100;
var count = 0;
var ids = [];
var data = {};
var proxy, binded, timeout, interval, util;

function disable() {
	proxy.removeListener('request', handleRequest);
	ids = [];
	data = {};
	interval && clearInterval(interval);
	interval = null;
	binded = false;
}

function enable() {
	!binded && proxy.on('request', handleRequest);
	binded = true;
	clearTimeout(timeout);
	timeout = setTimeout(disable, TIMEOUT);
	if (!interval) {
		interval = setInterval(clearCache, 3000);
	}
}

/**
 * 如果超过最大缓存数，清理如下请求数据：
 * 1. 已经请求结束且结束时间超过10秒
 * 2. 请求#1前面的未结束且未被ui读取过的请求
 */
function clearCache() {
	var len = ids.length;
	if (len <= MAX_LENGTH) {
		return;
	}

	var index = -1; //已经完成，且缓存超过10s的最后一个请求
	var now = Date.now();
	for (var i = len - 1; i >= 0; i--) {
		var curData = data[ids[i]];
		if (curData.endTime && now - curData.endTime > TIMEOUT) {
			index = i;
			break;
		}
	}

	if (index < 0) {
		return;
	}

	var _ids = [];
	var end;
	++index;
	for (var i = 0; i < index; i++) {
		var id = ids[i];
		var curData = data[id];
		if (curData.read && !curData.endTime) {
			_ids.push(id);
		} else {
			delete data[id];
			if (--len <= MIN_LENGTH) {
				_ids.push.apply(_ids, ids.slice(i + 1, index));
				break;
			}
		}
	}
	ids = _ids.concat(ids.slice(index));
}

function passThrough(chunk, encoding, callback) {
	callback(null, chunk);
}

function decode(body) {
	if (body) {
		var _body = body + '';
		if (_body.indexOf('�') != -1) {
			_body = iconv.decode(body, 'gbk');
		}
		body = _body;
	}

	return body;
}

function get(options) {
	enable();
	options = options || {};
	var data = {};
	var newIds = options.startTime == -1 ? [] : getIds(options.startTime, options.count);
	var list = getList(newIds).concat(getList(options.ids));
	for (var i = 0, len = list.length; i < len; i++) {
		var item = list[i];
		if (item) {
			data[item.id] = item;
		}
	}

	return {
		ids: options.ids || [],
		newIds: newIds,
		data: data
	};
}

function getIds(startTime, count) {
	var len = ids.length;
	if (!len) {
		return [];
	}

	startTime = (startTime || Date.now() - 2000) + '';
	count = Math.min(count || COUNT, len);
	if (ids[0] > startTime) {

		return ids.slice(0, count);
	}

	if (len === 1 || ids[len - 1] <= startTime) {

		return  [];
	}

	var index = getIndex(startTime, 0, len - 1);
	return ids.slice(index, index + count);
}

function getIndex(startTime, start, end) {
	if (end - start <= 1) {
		return end;
	}

	var mid = Math.floor((start + end) / 2);
	return ids[mid] <= startTime ? getIndex(startTime, mid + 1, end)
			: getIndex(startTime, start, mid);
}

function getList(ids) {
	var result = [];
	for (var i = 0, len = ids && ids.length; i < len; i++) {
		var id = ids[i];
		var curData = data[id];
		if (curData) {
			curData.read = true;
			result[i] = curData;
		}
	}

	return result;
}

function handleRequest(req) {
	var dnsTime = req.dnsTime || 0;
	req.dnsTime = Date.now();
	var startTime = req.dnsTime - dnsTime;
	var id = startTime + '-' + ++count;
	var reqData = {
			method: req.method || 'GET',
			httpVersion: req.httpVersion || '1.1',
            ip: req.ip || '::ffff:127.0.0.1',
            headers: req.headers
		};
	var resData = {
			ip: req.host
	};

	var curData = data[id] = {
			id: id,
			url: req.url,
			startTime: startTime,
			dnsTime: req.dnsTime,
			req: reqData,
			res: resData,
			rules: req.rules
	};

	ids.push(id);
	req.on('response', handleResponse);
	req.on('error', function(err) {
		reqData.body = err && err.stack;
		curData.endTime = reqData.requestTime = Date.now();
		curData.reqError = true;
		req.removeListener('response', handleResponse);
		req._transform = passThrough;
	});

	var reqBody;

	if (util.hasRequestBody(req)) {
		reqBody = false;
	}
	req._transform = function(chunk, encoding, callback) {

		if (chunk && (reqBody || reqBody === false)) {
			reqBody = reqBody ? Buffer.concat([reqBody, chunk]) : chunk;
		}

		if (reqBody && reqBody.length > MAX_REQ_SIZE) {
			reqBody = null;
		}

		if (!chunk) {
			curData.requestTime = Date.now();
			curData.reqEnd = true;
			reqData.body = decode(reqBody);
		}

		callback(null, chunk);
	};

	function handleResponse(res) {
		curData.responseTime = Date.now();
		resData.headers = res.headers;
		resData.statusCode = res.statusCode;
		resData.ip = res.ip;
		res.on('error', function(err) {
			resData.body = err && err.stack;
			curData.endTime = Date.now();
			curData.resError = true;
			res._transform = passThrough;
		});

		var resBody;
		var contentType = util.getContentType(res.headers);
		if (contentType && contentType != 'IMG' && util.hasBody(res)) {
			resBody = false;
		}

		res._transform = function(chunk, encoding, callback) {
			if (chunk && (resBody || resBody === false)) {
				resBody = resBody ? Buffer.concat([resBody, chunk]) : chunk;
			}

			if (resBody && resBody.length > MAX_RES_SIZE) {
				resBody = null;
			}

			if (!chunk) {
				curData.endTime = Date.now();
				curData.resEnd = true;
				if (resBody) {
					var unzip;
					switch (util.toLowerCase(res.headers['content-encoding'])) {
					    case 'gzip':
					    	unzip = zlib.gunzip.bind(zlib);
					      break;
					    case 'deflate':
					    	unzip = zlib.inflate.bind(zlib);
					      break;
					}

					if (unzip) {
						unzip(resBody, function(err, body) {
							if (err) {
								callback(err, chunk);
								return;
							}
							resData.body = decode(body);
							callback(null, chunk);
						});
						return;
					}
				}
				resData.body = decode(resBody);
			}

			callback(null, chunk);
		};
	}

}

module.exports = function init(_proxy) {
	proxy = _proxy;
	util = proxy.util;
	enable();
	module.exports = get;
};<commit_msg>delay 3000<commit_after>var iconv = require('iconv-lite');
var zlib = require('zlib');
var MAX_REQ_SIZE = 128 * 1024;
var MAX_RES_SIZE = 256 * 1024;
var TIMEOUT = 10000;
var MAX_LENGTH = 512;
var MIN_LENGTH = 412;
var COUNT = 100;
var count = 0;
var ids = [];
var data = {};
var proxy, binded, timeout, interval, util;

function disable() {
	proxy.removeListener('request', handleRequest);
	ids = [];
	data = {};
	interval && clearInterval(interval);
	interval = null;
	binded = false;
}

function enable() {
	!binded && proxy.on('request', handleRequest);
	binded = true;
	clearTimeout(timeout);
	timeout = setTimeout(disable, TIMEOUT);
	if (!interval) {
		interval = setInterval(clearCache, 3000);
	}
}

/**
 * 如果超过最大缓存数，清理如下请求数据：
 * 1. 已经请求结束且结束时间超过10秒
 * 2. 请求#1前面的未结束且未被ui读取过的请求
 */
function clearCache() {
	var len = ids.length;
	if (len <= MAX_LENGTH) {
		return;
	}

	var index = -1; //已经完成，且缓存超过10s的最后一个请求
	var now = Date.now();
	for (var i = len - 1; i >= 0; i--) {
		var curData = data[ids[i]];
		if (curData.endTime && now - curData.endTime > TIMEOUT) {
			index = i;
			break;
		}
	}

	if (index < 0) {
		return;
	}

	var _ids = [];
	var end;
	++index;
	for (var i = 0; i < index; i++) {
		var id = ids[i];
		var curData = data[id];
		if (curData.read && !curData.endTime) {
			_ids.push(id);
		} else {
			delete data[id];
			if (--len <= MIN_LENGTH) {
				_ids.push.apply(_ids, ids.slice(i + 1, index));
				break;
			}
		}
	}
	ids = _ids.concat(ids.slice(index));
}

function passThrough(chunk, encoding, callback) {
	callback(null, chunk);
}

function decode(body) {
	if (body) {
		var _body = body + '';
		if (_body.indexOf('�') != -1) {
			_body = iconv.decode(body, 'gbk');
		}
		body = _body;
	}

	return body;
}

function get(options) {
	enable();
	options = options || {};
	var data = {};
	var newIds = options.startTime == -1 ? [] : getIds(options.startTime, options.count);
	var list = getList(newIds).concat(getList(options.ids));
	for (var i = 0, len = list.length; i < len; i++) {
		var item = list[i];
		if (item) {
			data[item.id] = item;
		}
	}

	return {
		ids: options.ids || [],
		newIds: newIds,
		data: data
	};
}

function getIds(startTime, count) {
	var len = ids.length;
	if (!len) {
		return [];
	}

	startTime = (startTime || Date.now() - 3000) + '';
	count = Math.min(count || COUNT, len);
	if (ids[0] > startTime) {

		return ids.slice(0, count);
	}

	if (len === 1 || ids[len - 1] <= startTime) {

		return  [];
	}

	var index = getIndex(startTime, 0, len - 1);
	return ids.slice(index, index + count);
}

function getIndex(startTime, start, end) {
	if (end - start <= 1) {
		return end;
	}

	var mid = Math.floor((start + end) / 2);
	return ids[mid] <= startTime ? getIndex(startTime, mid + 1, end)
			: getIndex(startTime, start, mid);
}

function getList(ids) {
	var result = [];
	for (var i = 0, len = ids && ids.length; i < len; i++) {
		var id = ids[i];
		var curData = data[id];
		if (curData) {
			curData.read = true;
			result[i] = curData;
		}
	}

	return result;
}

function handleRequest(req) {
	var dnsTime = req.dnsTime || 0;
	req.dnsTime = Date.now();
	var startTime = req.dnsTime - dnsTime;
	var id = startTime + '-' + ++count;
	var reqData = {
			method: req.method || 'GET',
			httpVersion: req.httpVersion || '1.1',
            ip: req.ip || '::ffff:127.0.0.1',
            headers: req.headers
		};
	var resData = {
			ip: req.host
	};

	var curData = data[id] = {
			id: id,
			url: req.url,
			startTime: startTime,
			dnsTime: req.dnsTime,
			req: reqData,
			res: resData,
			rules: req.rules
	};

	ids.push(id);
	req.on('response', handleResponse);
	req.on('error', function(err) {
		reqData.body = err && err.stack;
		curData.endTime = reqData.requestTime = Date.now();
		curData.reqError = true;
		req.removeListener('response', handleResponse);
		req._transform = passThrough;
	});

	var reqBody;

	if (util.hasRequestBody(req)) {
		reqBody = false;
	}
	req._transform = function(chunk, encoding, callback) {

		if (chunk && (reqBody || reqBody === false)) {
			reqBody = reqBody ? Buffer.concat([reqBody, chunk]) : chunk;
		}

		if (reqBody && reqBody.length > MAX_REQ_SIZE) {
			reqBody = null;
		}

		if (!chunk) {
			curData.requestTime = Date.now();
			curData.reqEnd = true;
			reqData.body = decode(reqBody);
		}

		callback(null, chunk);
	};

	function handleResponse(res) {
		curData.responseTime = Date.now();
		resData.headers = res.headers;
		resData.statusCode = res.statusCode;
		resData.ip = res.ip;
		res.on('error', function(err) {
			resData.body = err && err.stack;
			curData.endTime = Date.now();
			curData.resError = true;
			res._transform = passThrough;
		});

		var resBody;
		var contentType = util.getContentType(res.headers);
		if (contentType && contentType != 'IMG' && util.hasBody(res)) {
			resBody = false;
		}

		res._transform = function(chunk, encoding, callback) {
			if (chunk && (resBody || resBody === false)) {
				resBody = resBody ? Buffer.concat([resBody, chunk]) : chunk;
			}

			if (resBody && resBody.length > MAX_RES_SIZE) {
				resBody = null;
			}

			if (!chunk) {
				curData.endTime = Date.now();
				curData.resEnd = true;
				if (resBody) {
					var unzip;
					switch (util.toLowerCase(res.headers['content-encoding'])) {
					    case 'gzip':
					    	unzip = zlib.gunzip.bind(zlib);
					      break;
					    case 'deflate':
					    	unzip = zlib.inflate.bind(zlib);
					      break;
					}

					if (unzip) {
						unzip(resBody, function(err, body) {
							if (err) {
								callback(err, chunk);
								return;
							}
							resData.body = decode(body);
							callback(null, chunk);
						});
						return;
					}
				}
				resData.body = decode(resBody);
			}

			callback(null, chunk);
		};
	}

}

module.exports = function init(_proxy) {
	proxy = _proxy;
	util = proxy.util;
	enable();
	module.exports = get;
};<|endoftext|>


<commit_before>/**
 * @file Landing.js
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {useState, useCallback, useEffect, useRef} from 'react';
import {findDOMNode} from 'react-dom';

// Components
import LandingNav from './LandingNav';
import LandingIntro from './sections/LandingIntro';
import LandingComponentCount from './sections/LandingComponentCount';
import LandingGetStarted from './sections/LandingGetStarted';
import LandingUsage from './sections/LandingUsage';
import LandingExamples from './sections/LandingExamples';
import LandingFoot from './LandingFoot';

// Vendors
import Event from 'vendors/Event';

// Styles
import 'scss/containers/landing/Landing.scss';

function Landing() {

    const MENU = [{
            name: 'Intro',
            hash: '#landing-intro'
        }, {
            name: 'Get Started',
            hash: '#landing-get-started'
        }, {
            name: 'Usage',
            hash: '#landing-usage'
        }, {
            name: 'Examples',
            hash: '#landing-examples'
        }],

        nav = useRef(null),

        [bodyScrollTop, setBodyScrollTop] = useState(0),
        [activatedMenu, setActivatedMenu] = useState(MENU[0]),
        [isNavFixed, setIsNavFixed] = useState(false),
        [navHeight, setNavHeight] = useState(0),

        getIsNavFixed = useCallback(bodyScrollTop => {
            const introEl = document.querySelector(MENU[0].hash);
            return !!(introEl && (bodyScrollTop > introEl.clientHeight - navHeight));
        }, [navHeight]),

        getActivatedMenu = useCallback(bodyScrollTop => {

            let activatedMenu = MENU[0];

            for (let i = 0, len = MENU.length; i < len; i++) {
                const el = document.querySelector(MENU[i].hash);
                if (el && bodyScrollTop >= el.offsetTop - navHeight) {
                    activatedMenu = MENU[i];
                }
            }

            return activatedMenu;

        }),

        handleScroll = useCallback(() => {

            const nextBodyScrollTop = document.body.scrollTop || document.documentElement.scrollTop;

            if (nextBodyScrollTop !== bodyScrollTop) {
                setBodyScrollTop(nextBodyScrollTop);
                setActivatedMenu(getActivatedMenu(nextBodyScrollTop));
                setIsNavFixed(getIsNavFixed(nextBodyScrollTop));
            }

        }, [bodyScrollTop]);

    useEffect(() => {

        // mount
        Event.addEvent(document, 'scroll', handleScroll);

        const navEl = findDOMNode(nav?.current);
        setNavHeight(navEl?.offsetHeight || 80);
        handleScroll();

        // unmount
        return () => {
            Event.removeEvent(document, 'scroll', handleScroll);
        };

    }, [navHeight]);

    return (

            <LandingNav ref={nav}
                        menu={MENU}
                        activatedMenu={activatedMenu}
                        isFixed={isNavFixed}/>

            <LandingIntro/>

            <LandingComponentCount bodyScrollTop={bodyScrollTop}/>

            <LandingGetStarted/>

            <LandingUsage/>

            <LandingExamples/>

            <LandingFoot/>

    );

}

export default Landing;
<commit_msg>update Landing<commit_after>/**
 * @file Landing.js
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {useState, useCallback, useEffect, useRef} from 'react';
import {findDOMNode} from 'react-dom';

// Components
import LandingNav from './LandingNav';
import LandingIntro from './sections/LandingIntro';
import LandingComponentCount from './sections/LandingComponentCount';
import LandingGetStarted from './sections/LandingGetStarted';
import LandingUsage from './sections/LandingUsage';
import LandingExamples from './sections/LandingExamples';
import LandingFoot from './LandingFoot';

// Vendors
import Event from 'vendors/Event';

// Styles
import 'scss/containers/landing/Landing.scss';

function Landing() {

    const MENU = [{
            name: 'Intro',
            hash: '#landing-intro'
        }, {
            name: 'Get Started',
            hash: '#landing-get-started'
        }, {
            name: 'Usage',
            hash: '#landing-usage'
        }, {
            name: 'Examples',
            hash: '#landing-examples'
        }],

        nav = useRef(null),

        [bodyScrollTop, setBodyScrollTop] = useState(0),
        [activatedMenu, setActivatedMenu] = useState(MENU[0]),
        [isNavFixed, setIsNavFixed] = useState(false),
        [navHeight, setNavHeight] = useState(0),

        getIsNavFixed = useCallback(bodyScrollTop => {
            const introEl = document.querySelector(MENU[0].hash);
            return !!(introEl && (bodyScrollTop > introEl.clientHeight - navHeight));
        }, [navHeight]),

        getActivatedMenu = useCallback(bodyScrollTop => {

            let activatedMenu = MENU[0];

            for (let i = 0, len = MENU.length; i < len; i++) {
                const el = document.querySelector(MENU[i].hash);
                if (el && bodyScrollTop >= el.offsetTop - navHeight) {
                    activatedMenu = MENU[i];
                }
            }

            return activatedMenu;

        }),

        handleScroll = useCallback(() => {

            const nextBodyScrollTop = document.body.scrollTop || document.documentElement.scrollTop;

            if (nextBodyScrollTop !== bodyScrollTop) {
                setBodyScrollTop(nextBodyScrollTop);
                setActivatedMenu(getActivatedMenu(nextBodyScrollTop));
                setIsNavFixed(getIsNavFixed(nextBodyScrollTop));
            }

        }, [bodyScrollTop]);

    useEffect(() => {

        // mount
        Event.addEvent(document, 'scroll', handleScroll);

        const navEl = findDOMNode(nav?.current);
        setNavHeight(navEl?.offsetHeight || 80);
        handleScroll();

        // unmount
        return () => {
            Event.removeEvent(document, 'scroll', handleScroll);
        };

    }, [bodyScrollTop, navHeight]);

    return (

            <LandingNav ref={nav}
                        menu={MENU}
                        activatedMenu={activatedMenu}
                        isFixed={isNavFixed}/>

            <LandingIntro/>

            <LandingComponentCount bodyScrollTop={bodyScrollTop}/>

            <LandingGetStarted/>

            <LandingUsage/>

            <LandingExamples/>

            <LandingFoot/>

    );

}

export default Landing;
<|endoftext|>


<commit_before>
/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 */

CLASS({
  name: 'Pong',
  package: 'foam.flow',
  extendsModel: 'foam.flow.Section',

  requires: [
    'foam.flow.CodeView',
    'foam.flow.QuoteCode',
    'foam.flow.ExpandableSection',
    'foam.ui.md.SectionView'
  ],

  properties: [
    {
      name: 'mode',
      defaultValue: 'read-only'
    }
  ],

  imports: [
    'FOAMWindow'
  ],

  methods: {
    init: function() {
      this.SUPER.apply(this, arguments);
      this.X.registerModel(this.CodeView.xbind({
        readOnlyMinLines: 1,
        readOnlyMaxLines: 100
      }), 'foam.flow.CodeView');
      this.X.registerModel(this.SectionView.xbind({
        expandedIconUrl: 'https://www.gstatic.com/images/icons/material/system/1x/expand_less_black_36dp.png'
      }), 'foam.ui.md.SectionView');

      // TODO: Remove this stuff once the template parser understand unknown tags
      // better
      this.CodeView.getProperty('registerElement').documentInstallFn.call(
        this.CodeView.getPrototype(), this.X);
      this.QuoteCode.getProperty('registerElement').documentInstallFn.call(
        this.QuoteCode.getPrototype(), this.X);
      this.ExpandableSection.getProperty('registerElement').documentInstallFn.call(
        this.ExpandableSection.getPrototype(), this.X);
    }
  },

  templates: [
    { name: 'toInnerHTML' },
    {
      name: 'CSS',
      template: multiline(function() {/*
        pong p { padding: 10px; }
        pong code, pong code-view {
          font: 12px/normal 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
        }
        pong expandable-section {
          padding: 0px 30px;
        }
        pong li, pong heading, pong heading * {
          font-size: 30px;
          margin: 4px 0px 2px 0px;
        }
        pong p, pong li * {
          font-size: 14px;
          font-family: arial, sans-serif;
        }
      */})
    }
  ]
});
<commit_msg>Patch for Pong in preso2<commit_after>
/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 */

CLASS({
  name: 'Pong',
  package: 'foam.flow',
  extendsModel: 'foam.flow.Section',

  requires: [
    'foam.flow.CodeView',
    'foam.flow.QuoteCode',
    'foam.flow.ExpandableSection',
    'foam.ui.md.SectionView'
  ],

  properties: [
    {
      name: 'mode',
      defaultValue: 'read-only'
    }
  ],

  imports: [
    'FOAMWindow'
  ],

  methods: {
    init: function() {
      this.SUPER.apply(this, arguments);
      this.X.registerModel(this.CodeView.xbind({
        readOnlyMinLines: 1,
        readOnlyMaxLines: 100
      }), 'foam.flow.CodeView');
      this.X.registerModel(this.SectionView.xbind({
        expandedIconUrl: 'https://www.gstatic.com/images/icons/material/system/1x/expand_less_black_36dp.png'
      }), 'foam.ui.md.SectionView');

      // TODO: Remove this stuff once the template parser understand unknown tags
      // better
      this.CodeView.getProperty('registerElement').documentInstallFn.call(
        this.CodeView.getPrototype(), this.X);
      this.QuoteCode.getProperty('registerElement').documentInstallFn.call(
        this.QuoteCode.getPrototype(), this.X);
      this.ExpandableSection.getProperty('registerElement').documentInstallFn.call(
        this.ExpandableSection.getPrototype(), this.X);
    }
  },

  templates: [
    { name: 'toInnerHTML' },
    {
      name: 'CSS',
      template: multiline(function() {/*
        pong { position: absolute; top: 0px }
        pong p { padding: 10px; }
        pong code, pong code-view {
          font: 12px/normal 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
        }
        pong expandable-section {
          padding: 0px 30px;
        }
        pong li, pong heading, pong heading * {
          font-size: 30px;
          margin: 4px 0px 2px 0px;
        }
        pong p, pong li * {
          font-size: 14px;
          font-family: arial, sans-serif;
        }
      */})
    }
  ]
});
<|endoftext|>


<commit_before>import test from 'ava';
import chalk from 'chalk';
import hasAnsi from 'has-ansi';
import stripAnsi from 'strip-ansi';
import fn from './';

// when "hard" is false

const fixture = 'The quick brown ' + chalk.red('fox jumped over ') + 'the lazy ' + chalk.green('dog and then ran away with the unicorn.');
const fixture2 = '12345678\n901234567890';

test('wraps string at 20 characters', t => {
	const res20 = fn(fixture, 20);

	t.is(res20, 'The quick brown \u001b[31mfox\u001b[39m\n\u001b[31mjumped over \u001b[39mthe lazy\n\u001b[32mdog and then ran\u001b[39m\n\u001b[32maway with the\u001b[39m\n\u001b[32municorn.\u001b[39m');
	t.true(stripAnsi(res20).split('\n').every(x => x.length <= 20));
});

test('wraps string at 30 characters', t => {
	const res30 = fn(fixture, 30);

	t.is(res30, 'The quick brown \u001b[31mfox jumped\u001b[39m\n\u001b[31mover \u001b[39mthe lazy \u001b[32mdog and then ran\u001b[39m\n\u001b[32maway with the unicorn.\u001b[39m');
	t.true(stripAnsi(res30).split('\n').every(function (x) {
		return x.length <= 30;
	}));
});

test('does not break strings longer than "cols" characters', t => {
	const res5 = fn(fixture, 5, {hard: false});

	t.is(res5, 'The\nquick\nbrown\n\u001b[31mfox\u001b[39m\n\u001b[31mjumped\u001b[39m\n\u001b[31mover\u001b[39m\n\u001b[31m\u001b[39mthe\nlazy\n\u001b[32mdog\u001b[39m\n\u001b[32mand\u001b[39m\n\u001b[32mthen\u001b[39m\n\u001b[32mran\u001b[39m\n\u001b[32maway\u001b[39m\n\u001b[32mwith\u001b[39m\n\u001b[32mthe\u001b[39m\n\u001b[32municorn.\u001b[39m');
	t.true(stripAnsi(res5).split('\n').filter(x => x.length > 5).length > 0);
});

test('handles colored string that wraps on to multiple lines', t => {
	const res = fn(chalk.green('hello world') + ' hey!', 5, {hard: false});
	const lines = res.split('\n');
	t.true(hasAnsi(lines[0]));
	t.true(hasAnsi(lines[1]));
	t.false(hasAnsi(lines[2]));
});

test('does not prepend newline if first string is greater than "cols"', t => {
	const res = fn(chalk.green('hello') + '-world', 5, {hard: false});
	t.is(res.split('\n').length, 1);
});

// when "hard" is true

test('breaks strings longer than "cols" characters', t => {
	const res5 = fn(fixture, 5, {hard: true});

	t.is(res5, 'The\nquick\nbrown\n\u001b[31mfox\u001b[39m\n\u001b[31mjumpe\u001b[39m\n\u001b[31md\u001b[39m\n\u001b[31mover\u001b[39m\n\u001b[31m\u001b[39mthe\nlazy\n\u001b[32mdog\u001b[39m\n\u001b[32mand\u001b[39m\n\u001b[32mthen\u001b[39m\n\u001b[32mran\u001b[39m\n\u001b[32maway\u001b[39m\n\u001b[32mwith\u001b[39m\n\u001b[32mthe\u001b[39m\n\u001b[32munico\u001b[39m\n\u001b[32mrn.\u001b[39m');
	t.true(stripAnsi(res5).split('\n').every(x => x.length <= 5));
});

test('removes last row if it contained only ansi escape codes', t => {
	const res = fn(chalk.green('helloworld'), 2, {hard: true});
	t.true(stripAnsi(res).split('\n').every(x => x.length === 2));
});

test('does not prepend newline if first word is split', t => {
	const res = fn(chalk.green('hello') + 'world', 5, {hard: true});
	t.is(res.split('\n').length, 2);
});

test('takes into account line returns inside input', t => {
	const res20 = fn(fixture2, 10, {hard: true});
	t.is(res20, '12345678\n9012345678\n90');
});
<commit_msg>add skipped test for support for fullwidth characters<commit_after>import test from 'ava';
import chalk from 'chalk';
import hasAnsi from 'has-ansi';
import stripAnsi from 'strip-ansi';
import fn from './';

// when "hard" is false

const fixture = 'The quick brown ' + chalk.red('fox jumped over ') + 'the lazy ' + chalk.green('dog and then ran away with the unicorn.');
const fixture2 = '12345678\n901234567890';

test('wraps string at 20 characters', t => {
	const res20 = fn(fixture, 20);

	t.is(res20, 'The quick brown \u001b[31mfox\u001b[39m\n\u001b[31mjumped over \u001b[39mthe lazy\n\u001b[32mdog and then ran\u001b[39m\n\u001b[32maway with the\u001b[39m\n\u001b[32municorn.\u001b[39m');
	t.true(stripAnsi(res20).split('\n').every(x => x.length <= 20));
});

test('wraps string at 30 characters', t => {
	const res30 = fn(fixture, 30);

	t.is(res30, 'The quick brown \u001b[31mfox jumped\u001b[39m\n\u001b[31mover \u001b[39mthe lazy \u001b[32mdog and then ran\u001b[39m\n\u001b[32maway with the unicorn.\u001b[39m');
	t.true(stripAnsi(res30).split('\n').every(function (x) {
		return x.length <= 30;
	}));
});

test('does not break strings longer than "cols" characters', t => {
	const res5 = fn(fixture, 5, {hard: false});

	t.is(res5, 'The\nquick\nbrown\n\u001b[31mfox\u001b[39m\n\u001b[31mjumped\u001b[39m\n\u001b[31mover\u001b[39m\n\u001b[31m\u001b[39mthe\nlazy\n\u001b[32mdog\u001b[39m\n\u001b[32mand\u001b[39m\n\u001b[32mthen\u001b[39m\n\u001b[32mran\u001b[39m\n\u001b[32maway\u001b[39m\n\u001b[32mwith\u001b[39m\n\u001b[32mthe\u001b[39m\n\u001b[32municorn.\u001b[39m');
	t.true(stripAnsi(res5).split('\n').filter(x => x.length > 5).length > 0);
});

test('handles colored string that wraps on to multiple lines', t => {
	const res = fn(chalk.green('hello world') + ' hey!', 5, {hard: false});
	const lines = res.split('\n');
	t.true(hasAnsi(lines[0]));
	t.true(hasAnsi(lines[1]));
	t.false(hasAnsi(lines[2]));
});

test('does not prepend newline if first string is greater than "cols"', t => {
	const res = fn(chalk.green('hello') + '-world', 5, {hard: false});
	t.is(res.split('\n').length, 1);
});

// when "hard" is true

test('breaks strings longer than "cols" characters', t => {
	const res5 = fn(fixture, 5, {hard: true});

	t.is(res5, 'The\nquick\nbrown\n\u001b[31mfox\u001b[39m\n\u001b[31mjumpe\u001b[39m\n\u001b[31md\u001b[39m\n\u001b[31mover\u001b[39m\n\u001b[31m\u001b[39mthe\nlazy\n\u001b[32mdog\u001b[39m\n\u001b[32mand\u001b[39m\n\u001b[32mthen\u001b[39m\n\u001b[32mran\u001b[39m\n\u001b[32maway\u001b[39m\n\u001b[32mwith\u001b[39m\n\u001b[32mthe\u001b[39m\n\u001b[32munico\u001b[39m\n\u001b[32mrn.\u001b[39m');
	t.true(stripAnsi(res5).split('\n').every(x => x.length <= 5));
});

test('removes last row if it contained only ansi escape codes', t => {
	const res = fn(chalk.green('helloworld'), 2, {hard: true});
	t.true(stripAnsi(res).split('\n').every(x => x.length === 2));
});

test('does not prepend newline if first word is split', t => {
	const res = fn(chalk.green('hello') + 'world', 5, {hard: true});
	t.is(res.split('\n').length, 2);
});

test('takes into account line returns inside input', t => {
	const res20 = fn(fixture2, 10, {hard: true});
	t.is(res20, '12345678\n9012345678\n90');
});

test.skip('supports fullwidth characters', t => {
	t.is(fn('안녕하세', 4, {hard: true}), '안녕\n하세');
});
<|endoftext|>


<commit_before>/*global Pusher*/

import { extend } from 'flarum/extend';
import app from 'flarum/app';
import DiscussionList from 'flarum/components/DiscussionList';
import DiscussionPage from 'flarum/components/DiscussionPage';
import IndexPage from 'flarum/components/IndexPage';
import Button from 'flarum/components/Button';

app.initializers.add('flarum-pusher', () => {
  const loadPusher = m.deferred();

  $.getScript('//js.pusher.com/3.0/pusher.min.js', () => {
    const socket = new Pusher(app.forum.attribute('pusherKey'), {
      authEndpoint: app.forum.attribute('apiUrl') + '/pusher/auth',
      auth: {
        headers: {
          'Authorization': 'Token ' + app.session.token
        }
      }
    });

    loadPusher.resolve({
      main: socket.subscribe('public'),
      user: app.session.user ? socket.subscribe('private-user' + app.session.user.id()) : null
    });
  });

  app.pusher = loadPusher.promise;
  app.pushedUpdates = [];

  extend(DiscussionList.prototype, 'config', function(x, isInitialized, context) {
    if (isInitialized) return;

    app.pusher.then(channels => {
      channels.main.bind('newPost', data => {
        const params = this.props.params;

        if (!params.q && !params.sort && !params.filter) {
          if (params.tags) {
            const tag = app.store.getBy('tags', 'slug', params.tags);

            if (data.tagIds.indexOf(tag.id()) === -1) return;
          }

          const id = String(data.discussionId);

          if ((!app.current.discussion || id !== app.current.discussion.id()) && app.pushedUpdates.indexOf(id) === -1) {
            app.pushedUpdates.push(id);

            if (app.current instanceof IndexPage) {
              app.setTitleCount(app.pushedUpdates.length);
            }

            m.redraw();
          }
        }
      });

      extend(context, 'onunload', () => channels.main.unbind());
    });
  });

  extend(DiscussionList.prototype, 'view', function(vdom) {
    if (app.pushedUpdates) {
      const count = app.pushedUpdates.length;

      if (count) {
        vdom.children.unshift(
          Button.component({
            className: 'Button Button--block DiscussionList-update',
            onclick: () => {
              this.refresh(false).then(() => {
                this.loadingUpdated = false;
                app.pushedUpdates = [];
                app.setTitleCount(0);
                m.redraw();
              });
              this.loadingUpdated = true;
            },
            loading: this.loadingUpdated,
            children: app.translator.transChoice('flarum-pusher.forum.discussion_list.show_updates_text', count, {count})
          })
        );
      }
    }
  });

  // Prevent any newly-created discussions from triggering the discussion list
  // update button showing.
  // TODO: Might be better pause the response to the push updates while the
  // composer is loading? idk
  extend(DiscussionList.prototype, 'addDiscussion', function(returned, discussion) {
    const index = app.pushedUpdates.indexOf(discussion.id());

    if (index !== -1) {
      app.pushedUpdates.splice(index, 1);
    }

    if (app.current instanceof IndexPage) {
      app.setTitleCount(app.pushedUpdates.length);
    }

    m.redraw();
  });

  extend(DiscussionPage.prototype, 'config', function(x, isInitialized, context) {
    if (isInitialized) return;

    app.pusher.then(channels => {
      channels.main.bind('newPost', data => {
        const id = String(data.discussionId);

        if (this.discussion && this.discussion.id() === id && this.stream) {
          const oldCount = this.discussion.commentsCount();

          app.store.find('discussions', this.discussion.id()).then(() => {
            this.stream.update();

            if (!document.hasFocus()) {
              app.setTitleCount(Math.max(0, this.discussion.commentsCount() - oldCount));

              $(window).one('focus', () => app.setTitleCount(0));
            }
          });
        }
      });

      extend(context, 'onunload', () => channels.main.unbind());
    });
  });

  extend(IndexPage.prototype, 'actionItems', items => {
    delete items.refresh;
  });

  app.pusher.then(channels => {
    if (channels.user) {
      channels.user.bind('notification', () => {
        app.session.user.pushAttributes({
          unreadNotificationsCount: app.session.user.unreadNotificationsCount() + 1,
          newNotificationsCount: app.session.user.newNotificationsCount() + 1
        });
        delete app.cache.notifications;
        m.redraw();
      });
    }
  });
});
<commit_msg>Update ItemList API<commit_after>/*global Pusher*/

import { extend } from 'flarum/extend';
import app from 'flarum/app';
import DiscussionList from 'flarum/components/DiscussionList';
import DiscussionPage from 'flarum/components/DiscussionPage';
import IndexPage from 'flarum/components/IndexPage';
import Button from 'flarum/components/Button';

app.initializers.add('flarum-pusher', () => {
  const loadPusher = m.deferred();

  $.getScript('//js.pusher.com/3.0/pusher.min.js', () => {
    const socket = new Pusher(app.forum.attribute('pusherKey'), {
      authEndpoint: app.forum.attribute('apiUrl') + '/pusher/auth',
      auth: {
        headers: {
          'Authorization': 'Token ' + app.session.token
        }
      }
    });

    loadPusher.resolve({
      main: socket.subscribe('public'),
      user: app.session.user ? socket.subscribe('private-user' + app.session.user.id()) : null
    });
  });

  app.pusher = loadPusher.promise;
  app.pushedUpdates = [];

  extend(DiscussionList.prototype, 'config', function(x, isInitialized, context) {
    if (isInitialized) return;

    app.pusher.then(channels => {
      channels.main.bind('newPost', data => {
        const params = this.props.params;

        if (!params.q && !params.sort && !params.filter) {
          if (params.tags) {
            const tag = app.store.getBy('tags', 'slug', params.tags);

            if (data.tagIds.indexOf(tag.id()) === -1) return;
          }

          const id = String(data.discussionId);

          if ((!app.current.discussion || id !== app.current.discussion.id()) && app.pushedUpdates.indexOf(id) === -1) {
            app.pushedUpdates.push(id);

            if (app.current instanceof IndexPage) {
              app.setTitleCount(app.pushedUpdates.length);
            }

            m.redraw();
          }
        }
      });

      extend(context, 'onunload', () => channels.main.unbind());
    });
  });

  extend(DiscussionList.prototype, 'view', function(vdom) {
    if (app.pushedUpdates) {
      const count = app.pushedUpdates.length;

      if (count) {
        vdom.children.unshift(
          Button.component({
            className: 'Button Button--block DiscussionList-update',
            onclick: () => {
              this.refresh(false).then(() => {
                this.loadingUpdated = false;
                app.pushedUpdates = [];
                app.setTitleCount(0);
                m.redraw();
              });
              this.loadingUpdated = true;
            },
            loading: this.loadingUpdated,
            children: app.translator.transChoice('flarum-pusher.forum.discussion_list.show_updates_text', count, {count})
          })
        );
      }
    }
  });

  // Prevent any newly-created discussions from triggering the discussion list
  // update button showing.
  // TODO: Might be better pause the response to the push updates while the
  // composer is loading? idk
  extend(DiscussionList.prototype, 'addDiscussion', function(returned, discussion) {
    const index = app.pushedUpdates.indexOf(discussion.id());

    if (index !== -1) {
      app.pushedUpdates.splice(index, 1);
    }

    if (app.current instanceof IndexPage) {
      app.setTitleCount(app.pushedUpdates.length);
    }

    m.redraw();
  });

  extend(DiscussionPage.prototype, 'config', function(x, isInitialized, context) {
    if (isInitialized) return;

    app.pusher.then(channels => {
      channels.main.bind('newPost', data => {
        const id = String(data.discussionId);

        if (this.discussion && this.discussion.id() === id && this.stream) {
          const oldCount = this.discussion.commentsCount();

          app.store.find('discussions', this.discussion.id()).then(() => {
            this.stream.update();

            if (!document.hasFocus()) {
              app.setTitleCount(Math.max(0, this.discussion.commentsCount() - oldCount));

              $(window).one('focus', () => app.setTitleCount(0));
            }
          });
        }
      });

      extend(context, 'onunload', () => channels.main.unbind());
    });
  });

  extend(IndexPage.prototype, 'actionItems', items => {
    items.remove('refresh');
  });

  app.pusher.then(channels => {
    if (channels.user) {
      channels.user.bind('notification', () => {
        app.session.user.pushAttributes({
          unreadNotificationsCount: app.session.user.unreadNotificationsCount() + 1,
          newNotificationsCount: app.session.user.newNotificationsCount() + 1
        });
        delete app.cache.notifications;
        m.redraw();
      });
    }
  });
});
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var Mustache = require('mustache');
//var beautify = require('js-beautify').js_beautify;
//var Linter = require('tslint');
var _ = require('lodash');

var Generator = (function () {

    function Generator(swaggerfile, outputpath) {
        this._swaggerfile = swaggerfile;
        this._outputPath = outputpath;
    }

    Generator.prototype.Debug = false;

    Generator.prototype.initialize = function () {
        this.LogMessage('Reading Swagger file', this._swaggerfile);
        var swaggerfilecontent = fs.readFileSync(this._swaggerfile, 'UTF-8');

        this.LogMessage('Parsing Swagger JSON');
        this.swaggerParsed = JSON.parse(swaggerfilecontent);

        this.LogMessage('Reading Mustache templates');

        this.templates = {
            'class': fs.readFileSync(__dirname + "/../templates/angular2-service.mustache", 'utf-8'),
            'model': fs.readFileSync(__dirname + "/../templates/angular2-model.mustache", 'utf-8'),
            'models_export': fs.readFileSync(__dirname + "/../templates/angular2-models-export.mustache", 'utf-8')
        };

        this.LogMessage('Creating Mustache viewModel');
        this.viewModel = this.createMustacheViewModel();

        this.initialized = true;
    }

    Generator.prototype.generateAPIClient = function () {
        if (this.initialized !== true)
            this.initialize();

        this.generateClient();
        this.generateModels();
        this.generateCommonModelsExportDefinition();

        this.LogMessage('API client generated successfully');
    };

    Generator.prototype.generateClient = function () {
        if (this.initialized !== true)
            this.initialize();

        // generate main API client class
        this.LogMessage('Rendering template for API');
        var result = this.renderLintAndBeautify(this.templates.class, this.viewModel, this.templates);

        var outfile = this._outputPath + "/" + "client.ts";
        this.LogMessage('Creating output file', outfile);
        fs.writeFileSync(outfile, result, 'utf-8')
    };

    Generator.prototype.generateModels = function () {
        var that = this;

        if (this.initialized !== true)
            this.initialize();

        var outputdir = this._outputPath + '/models';

        if (!fs.existsSync(outputdir))
            fs.mkdirSync(outputdir);

        // generate API models
        _.forEach(this.viewModel.definitions, function (definition, defName) {
            that.LogMessage('Rendering template for model: ', definition.name);
            var result = that.renderLintAndBeautify(that.templates.model, definition, that.templates);

            var outfile = outputdir + "/" + definition.name + ".ts";

            that.LogMessage('Creating output file', outfile);
            fs.writeFileSync(outfile, result, 'utf-8')
        });
    };

    Generator.prototype.generateCommonModelsExportDefinition = function () {
        if (this.initialized !== true)
            this.initialize();

        var outputdir = this._outputPath;

        if (!fs.existsSync(outputdir))
            fs.mkdirSync(outputdir);

        this.LogMessage('Rendering common models export');
        var result = this.renderLintAndBeautify(this.templates.models_export, this.viewModel, this.templates);

        var outfile = outputdir + "/models.ts";

        this.LogMessage('Creating output file', outfile);
        fs.writeFileSync(outfile, result, 'utf-8')
    };

    Generator.prototype.renderLintAndBeautify = function (tempalte, model) {

        // Render *****
        var result = Mustache.render(tempalte, model);

        // Lint *****
        // var ll = new Linter("noname", rendered, {});
        // var lintResult = ll.lint();
        // lintResult.errors.forEach(function (error) {
        //     if (error.code[0] === 'E')
        //         throw new Error(error.reason + ' in ' + error.evidence + ' (' + error.code + ')');
        // });

        // Beautify *****
        // NOTE: this has been commented because of curly braces were added on newline after beaufity
        //result = beautify(result, { indent_size: 4, max_preserve_newlines: 2 });

        return result;
    }

    Generator.prototype.createMustacheViewModel = function () {
        var that = this;
        var swagger = this.swaggerParsed;
        var authorizedMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'];
        var data = {
            isNode: false,
            description: swagger.info.description,
            isSecure: swagger.securityDefinitions !== undefined,
            swagger: swagger,
            domain: (swagger.schemes && swagger.schemes.length > 0 && swagger.host && swagger.basePath) ? swagger.schemes[0] + '://' + swagger.host + swagger.basePath : '',
            methods: [],
            definitions: []
        };

        _.forEach(swagger.paths, function (api, path) {
            var globalParams = [];

            _.forEach(api, function (op, m) {
                if (m.toLowerCase() === 'parameters') {
                    globalParams = op;
                }
            });

            _.forEach(api, function (op, m) {
                if (authorizedMethods.indexOf(m.toUpperCase()) === -1){
                    return;
                }

                var summaryLines = op.description.split('\n');
                summaryLines.splice(summaryLines.length-1, 1);

                var method = {
                    path: path,
                    className: CLASS_NAME,
                    methodName: op['x-swagger-js-method-name'] ? op['x-swagger-js-method-name'] : (op.operationId ? op.operationId : that.getPathToMethodName(m, path)),
                    method: m.toUpperCase(),
                    angular2httpMethod: m.toLowerCase(),
                    isGET: m.toUpperCase() === 'GET',
                    hasPayload: !_.includes(['GET','DELETE','HEAD'], m.toUpperCase()),
                    summaryLines: summaryLines,
                    isSecure: swagger.security !== undefined || op.security !== undefined,
                    parameters: [],
                    hasJsonResponse: _.some(_.defaults([], swagger.produces, op.produces), function (response) { // TODO PREROBIT
                        return response.indexOf('/json') != -1;
                    })
                };

                var params = [];

                if (_.isArray(op.parameters))
                    params = op.parameters;

                params = params.concat(globalParams);

                _.forEach(params, function (parameter) {
                    // Ignore headers which are injected by proxies & app servers
                    // eg: https://cloud.google.com/appengine/docs/go/requests#Go_Request_headers

                    if (parameter['x-proxy-header'] && !data.isNode)
                        return;

                    if (_.has(parameter, 'schema') && _.isString(parameter.schema.$ref))
                        parameter.type = that.camelCase(that.getRefType(parameter.schema.$ref));

                    parameter.camelCaseName = that.camelCase(parameter.name);

                    if (parameter.type === 'integer' || parameter.type === 'double')
                        parameter.typescriptType = 'number';
                    else
                        parameter.typescriptType = parameter.type;

                    if (parameter.enum && parameter.enum.length === 1) {
                        parameter.isSingleton = true;
                        parameter.singleton = parameter.enum[0];
                    }

                    if (parameter.in === 'body')
                        parameter.isBodyParameter = true;

                    else if (parameter.in === 'path')
                        parameter.isPathParameter = true;

                    else if (parameter.in === 'query') {
                        parameter.isQueryParameter = true;
                        if (parameter['x-name-pattern'])
                            parameter.isPatternType = true;
                    }
                    else if (parameter.in === 'header')
                        parameter.isHeaderParameter = true;

                    else if (parameter.in === 'formData')
                        parameter.isFormParameter = true;

                    method.parameters.push(parameter);
                });

                if (method.parameters.length > 0)
                    method.parameters[method.parameters.length - 1].last = true;

                data.methods.push(method);
            });

        });

        _.forEach(swagger.definitions, function (defin, defVal) {
            var defName = that.camelCase(defVal);

            var definition = {
                name: defName,
                properties: [],
                refs: [],
            };

            _.forEach(defin.properties, function (propin, propVal) {

                var property = {
                    name: propVal,
                    isRef: _.has(propin, '$ref') || (propin.type === 'array' && _.has(propin.items, '$ref')),
                    isArray: propin.type === 'array',
                    type: null,
                    typescriptType: null
                };

                if (property.isArray)
                    property.type = _.has(propin.items, '$ref') ? that.camelCase(propin.items["$ref"].replace("#/definitions/", "")) : propin.type;
                else
                    property.type = _.has(propin, '$ref') ? that.camelCase(propin["$ref"].replace("#/definitions/", "")) : propin.type;

                if (property.type === 'integer' || property.type === 'double')
                    property.typescriptType = 'number';
                else
                    property.typescriptType = property.type;

                if (property.isRef)
                    definition.refs.push(property);
                else
                    definition.properties.push(property);
            });

            data.definitions.push(definition);
        });

        if (data.definitions.length > 0)
            data.definitions[data.definitions.length - 1].last = true;

        return data;
    }

    Generator.prototype.getRefType = function (refString) {
        var segments = refString.split('/');
        return segments.length === 3 ? segments[2] : segments[0];
    }

    Generator.prototype.getPathToMethodName = function (m, path) {
        if (path === '/' || path === '')
            return m;

        // clean url path for requests ending with '/'
        var cleanPath = path;

        if (cleanPath.indexOf('/', cleanPath.length - 1) !== -1)
            cleanPath = cleanPath.substring(0, cleanPath.length - 1);

        var segments = cleanPath.split('/').slice(1);

        segments = _.transform(segments, function (result, segment) {
            if (segment[0] === '{' && segment[segment.length - 1] === '}')
                segment = 'by' + segment[1].toUpperCase() + segment.substring(2, segment.length - 1);

            result.push(segment);
        });

        var result = this.camelCase(segments.join('-'));

        return m.toLowerCase() + result[0].toUpperCase() + result.substring(1);
    }

    Generator.prototype.camelCase = function (text) {
        if (!text)
            return text;

        if (text.indexOf('-') === -1 && text.indexOf('.') === -1)
            return text;

        var tokens = [];

        text.split('-').forEach(function (token, index) {
            tokens.push(token[0].toUpperCase() + token.substring(1));
        });

        var partialres = tokens.join('');
        tokens = [];

        partialres.split('.').forEach(function (token, index) {
            tokens.push(token[0].toUpperCase() + token.substring(1));
        });

        return tokens.join('');
    }

    Generator.prototype.LogMessage = function (text, param) {
        if (this.Debug)
            console.log(text, param || '');
    }

    return Generator;
})();

module.exports.Generator = Generator;
<commit_msg>Removed CLASS_NAME<commit_after>'use strict';

var fs = require('fs');
var Mustache = require('mustache');
//var beautify = require('js-beautify').js_beautify;
//var Linter = require('tslint');
var _ = require('lodash');

var Generator = (function () {

    function Generator(swaggerfile, outputpath) {
        this._swaggerfile = swaggerfile;
        this._outputPath = outputpath;
    }

    Generator.prototype.Debug = false;

    Generator.prototype.initialize = function () {
        this.LogMessage('Reading Swagger file', this._swaggerfile);
        var swaggerfilecontent = fs.readFileSync(this._swaggerfile, 'UTF-8');

        this.LogMessage('Parsing Swagger JSON');
        this.swaggerParsed = JSON.parse(swaggerfilecontent);

        this.LogMessage('Reading Mustache templates');

        this.templates = {
            'class': fs.readFileSync(__dirname + "/../templates/angular2-service.mustache", 'utf-8'),
            'model': fs.readFileSync(__dirname + "/../templates/angular2-model.mustache", 'utf-8'),
            'models_export': fs.readFileSync(__dirname + "/../templates/angular2-models-export.mustache", 'utf-8')
        };

        this.LogMessage('Creating Mustache viewModel');
        this.viewModel = this.createMustacheViewModel();

        this.initialized = true;
    }

    Generator.prototype.generateAPIClient = function () {
        if (this.initialized !== true)
            this.initialize();

        this.generateClient();
        this.generateModels();
        this.generateCommonModelsExportDefinition();

        this.LogMessage('API client generated successfully');
    };

    Generator.prototype.generateClient = function () {
        if (this.initialized !== true)
            this.initialize();

        // generate main API client class
        this.LogMessage('Rendering template for API');
        var result = this.renderLintAndBeautify(this.templates.class, this.viewModel, this.templates);

        var outfile = this._outputPath + "/" + "client.ts";
        this.LogMessage('Creating output file', outfile);
        fs.writeFileSync(outfile, result, 'utf-8')
    };

    Generator.prototype.generateModels = function () {
        var that = this;

        if (this.initialized !== true)
            this.initialize();

        var outputdir = this._outputPath + '/models';

        if (!fs.existsSync(outputdir))
            fs.mkdirSync(outputdir);

        // generate API models
        _.forEach(this.viewModel.definitions, function (definition, defName) {
            that.LogMessage('Rendering template for model: ', definition.name);
            var result = that.renderLintAndBeautify(that.templates.model, definition, that.templates);

            var outfile = outputdir + "/" + definition.name + ".ts";

            that.LogMessage('Creating output file', outfile);
            fs.writeFileSync(outfile, result, 'utf-8')
        });
    };

    Generator.prototype.generateCommonModelsExportDefinition = function () {
        if (this.initialized !== true)
            this.initialize();

        var outputdir = this._outputPath;

        if (!fs.existsSync(outputdir))
            fs.mkdirSync(outputdir);

        this.LogMessage('Rendering common models export');
        var result = this.renderLintAndBeautify(this.templates.models_export, this.viewModel, this.templates);

        var outfile = outputdir + "/models.ts";

        this.LogMessage('Creating output file', outfile);
        fs.writeFileSync(outfile, result, 'utf-8')
    };

    Generator.prototype.renderLintAndBeautify = function (tempalte, model) {

        // Render *****
        var result = Mustache.render(tempalte, model);

        // Lint *****
        // var ll = new Linter("noname", rendered, {});
        // var lintResult = ll.lint();
        // lintResult.errors.forEach(function (error) {
        //     if (error.code[0] === 'E')
        //         throw new Error(error.reason + ' in ' + error.evidence + ' (' + error.code + ')');
        // });

        // Beautify *****
        // NOTE: this has been commented because of curly braces were added on newline after beaufity
        //result = beautify(result, { indent_size: 4, max_preserve_newlines: 2 });

        return result;
    }

    Generator.prototype.createMustacheViewModel = function () {
        var that = this;
        var swagger = this.swaggerParsed;
        var authorizedMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'];
        var data = {
            isNode: false,
            description: swagger.info.description,
            isSecure: swagger.securityDefinitions !== undefined,
            swagger: swagger,
            domain: (swagger.schemes && swagger.schemes.length > 0 && swagger.host && swagger.basePath) ? swagger.schemes[0] + '://' + swagger.host + swagger.basePath : '',
            methods: [],
            definitions: []
        };

        _.forEach(swagger.paths, function (api, path) {
            var globalParams = [];

            _.forEach(api, function (op, m) {
                if (m.toLowerCase() === 'parameters') {
                    globalParams = op;
                }
            });

            _.forEach(api, function (op, m) {
                if (authorizedMethods.indexOf(m.toUpperCase()) === -1){
                    return;
                }

                var summaryLines = op.description.split('\n');
                summaryLines.splice(summaryLines.length-1, 1);

                var method = {
                    path: path,
                    methodName: op['x-swagger-js-method-name'] ? op['x-swagger-js-method-name'] : (op.operationId ? op.operationId : that.getPathToMethodName(m, path)),
                    method: m.toUpperCase(),
                    angular2httpMethod: m.toLowerCase(),
                    isGET: m.toUpperCase() === 'GET',
                    hasPayload: !_.includes(['GET','DELETE','HEAD'], m.toUpperCase()),
                    summaryLines: summaryLines,
                    isSecure: swagger.security !== undefined || op.security !== undefined,
                    parameters: [],
                    hasJsonResponse: _.some(_.defaults([], swagger.produces, op.produces), function (response) { // TODO PREROBIT
                        return response.indexOf('/json') != -1;
                    })
                };

                var params = [];

                if (_.isArray(op.parameters))
                    params = op.parameters;

                params = params.concat(globalParams);

                _.forEach(params, function (parameter) {
                    // Ignore headers which are injected by proxies & app servers
                    // eg: https://cloud.google.com/appengine/docs/go/requests#Go_Request_headers

                    if (parameter['x-proxy-header'] && !data.isNode)
                        return;

                    if (_.has(parameter, 'schema') && _.isString(parameter.schema.$ref))
                        parameter.type = that.camelCase(that.getRefType(parameter.schema.$ref));

                    parameter.camelCaseName = that.camelCase(parameter.name);

                    if (parameter.type === 'integer' || parameter.type === 'double')
                        parameter.typescriptType = 'number';
                    else
                        parameter.typescriptType = parameter.type;

                    if (parameter.enum && parameter.enum.length === 1) {
                        parameter.isSingleton = true;
                        parameter.singleton = parameter.enum[0];
                    }

                    if (parameter.in === 'body')
                        parameter.isBodyParameter = true;

                    else if (parameter.in === 'path')
                        parameter.isPathParameter = true;

                    else if (parameter.in === 'query') {
                        parameter.isQueryParameter = true;
                        if (parameter['x-name-pattern'])
                            parameter.isPatternType = true;
                    }
                    else if (parameter.in === 'header')
                        parameter.isHeaderParameter = true;

                    else if (parameter.in === 'formData')
                        parameter.isFormParameter = true;

                    method.parameters.push(parameter);
                });

                if (method.parameters.length > 0)
                    method.parameters[method.parameters.length - 1].last = true;

                data.methods.push(method);
            });

        });

        _.forEach(swagger.definitions, function (defin, defVal) {
            var defName = that.camelCase(defVal);

            var definition = {
                name: defName,
                properties: [],
                refs: [],
            };

            _.forEach(defin.properties, function (propin, propVal) {

                var property = {
                    name: propVal,
                    isRef: _.has(propin, '$ref') || (propin.type === 'array' && _.has(propin.items, '$ref')),
                    isArray: propin.type === 'array',
                    type: null,
                    typescriptType: null
                };

                if (property.isArray)
                    property.type = _.has(propin.items, '$ref') ? that.camelCase(propin.items["$ref"].replace("#/definitions/", "")) : propin.type;
                else
                    property.type = _.has(propin, '$ref') ? that.camelCase(propin["$ref"].replace("#/definitions/", "")) : propin.type;

                if (property.type === 'integer' || property.type === 'double')
                    property.typescriptType = 'number';
                else
                    property.typescriptType = property.type;

                if (property.isRef)
                    definition.refs.push(property);
                else
                    definition.properties.push(property);
            });

            data.definitions.push(definition);
        });

        if (data.definitions.length > 0)
            data.definitions[data.definitions.length - 1].last = true;

        return data;
    }

    Generator.prototype.getRefType = function (refString) {
        var segments = refString.split('/');
        return segments.length === 3 ? segments[2] : segments[0];
    }

    Generator.prototype.getPathToMethodName = function (m, path) {
        if (path === '/' || path === '')
            return m;

        // clean url path for requests ending with '/'
        var cleanPath = path;

        if (cleanPath.indexOf('/', cleanPath.length - 1) !== -1)
            cleanPath = cleanPath.substring(0, cleanPath.length - 1);

        var segments = cleanPath.split('/').slice(1);

        segments = _.transform(segments, function (result, segment) {
            if (segment[0] === '{' && segment[segment.length - 1] === '}')
                segment = 'by' + segment[1].toUpperCase() + segment.substring(2, segment.length - 1);

            result.push(segment);
        });

        var result = this.camelCase(segments.join('-'));

        return m.toLowerCase() + result[0].toUpperCase() + result.substring(1);
    }

    Generator.prototype.camelCase = function (text) {
        if (!text)
            return text;

        if (text.indexOf('-') === -1 && text.indexOf('.') === -1)
            return text;

        var tokens = [];

        text.split('-').forEach(function (token, index) {
            tokens.push(token[0].toUpperCase() + token.substring(1));
        });

        var partialres = tokens.join('');
        tokens = [];

        partialres.split('.').forEach(function (token, index) {
            tokens.push(token[0].toUpperCase() + token.substring(1));
        });

        return tokens.join('');
    }

    Generator.prototype.LogMessage = function (text, param) {
        if (this.Debug)
            console.log(text, param || '');
    }

    return Generator;
})();

module.exports.Generator = Generator;
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-12-4 02:17:59<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>(function() {
  var main;
  game.PlayScreen = me.ScreenObject.extend({
    onResetEvent: function() {
      // tell the entity pool what classes it needs to work with
      me.pool.register('main', game.MainEntity, true);
      me.pool.register('renderable', game.RenderableEntity, true);

      // create the main
      main = me.pool.pull('main', 100, 100);
      me.game.world.addChild(new game.Background());
      me.game.world.addChild(main);

      me.game.world.addChild(new (me.Renderable.extend({
        init: function() {
            this._super(me.Renderable, 'init', [0, 0, 100, 100]);
            this.drawn = false;
            this.elapsed = 0;
        },
        update: function(dt) {
            this.elapsed += dt;
            if(!this.drawn && this.elapsed > 3000) {
                this.drawn = true;
                this.elapsed = 0;
                // purge the main
                me.game.world.removeChild(main);
                // main will get re-used but initialized elsewhere.
                main = me.pool.pull('main', 20, 20);
                // create the renderable
                var renderable = me.pool.pull('renderable', 120, 120);
                me.game.world.addChild(main);
                me.game.world.addChild(renderable);
            }
            return true;
        }
      })));
    }
  });
}).call(this);<commit_msg>Improved the example to be a bit more stressful<commit_after>(function() {
  var main;
  var renderable;
  game.PlayScreen = me.ScreenObject.extend({
    onResetEvent: function() {
      // tell the entity pool what classes it needs to work with
      me.pool.register('main', game.MainEntity, true);
      me.pool.register('renderable', game.RenderableEntity, true);

      // create the main
      main = me.pool.pull('main', 100, 100);
      renderable = me.pool.pull('renderable', 120, 120);
      me.game.world.addChild(new game.Background());
      me.game.world.addChild(main);
      me.game.world.addChild(renderable);

      me.game.world.addChild(new (me.Renderable.extend({
        init: function() {
            this._super(me.Renderable, 'init', [0, 0, 100, 100]);
            this.elapsed = 0;
            this.odd = true;

        },
        update: function(dt) {
            this.elapsed += dt;
            if(this.elapsed > 1000) {
                this.elapsed = 0;
                this.odd = !this.odd;
                // purge the main
                me.game.world.removeChild(main);
                me.game.world.removeChild(renderable);
                // main will get re-used but initialized elsewhere
                main = me.pool.pull('main', this.odd ? 100 : 200, this.odd ? 100 : 200);
                // create the renderable
                renderable = me.pool.pull('renderable', this.odd ? 120 : 220, this.odd ? 120 : 220);
                me.game.world.addChild(main);
                me.game.world.addChild(renderable);
            }
            return true;
        }
      })));
    }
  });
}).call(this);<|endoftext|>