<commit_before>// Abstract Persistence driver

'use strict';

var aFrom               = require('es5-ext/array/from')
  , clear               = require('es5-ext/array/#/clear')
  , isCopy              = require('es5-ext/array/#/is-copy')
  , ensureArray         = require('es5-ext/array/valid-array')
  , assign              = require('es5-ext/object/assign')
  , ensureCallable      = require('es5-ext/object/valid-callable')
  , ensureObject        = require('es5-ext/object/valid-object')
  , ensureString        = require('es5-ext/object/validate-stringifiable-value')
  , isSet               = require('es6-set/is-set')
  , deferred            = require('deferred')
  , emitError           = require('event-emitter/emit-error')
  , d                   = require('d')
  , autoBind            = require('d/auto-bind')
  , lazy                = require('d/lazy')
  , debug               = require('debug-ext')('db')
  , ee                  = require('event-emitter')
  , getStamp            = require('time-uuid/time')
  , ensureObservableSet = require('observable-set/valid-observable-set')
  , ensureDatabase      = require('dbjs/valid-dbjs')
  , Event               = require('dbjs/_setup/event')
  , unserialize         = require('dbjs/_setup/unserialize/value')
  , serialize           = require('dbjs/_setup/serialize/value')
  , resolveKeyPath      = require('dbjs/_setup/utils/resolve-property-path')
  , once                = require('timers-ext/once')
  , ensureDriver        = require('./ensure')

  , isArray = Array.isArray
  , isModelId = RegExp.prototype.test.bind(/^[A-Z]/)
  , tokenize = resolveKeyPath.tokenize, resolveObject = resolveKeyPath.resolveObject
  , create = Object.create;

var PersistenceDriver = module.exports = Object.defineProperties(function (dbjs/*, options*/) {
	var autoSaveFilter, options;
	if (!(this instanceof PersistenceDriver)) return new PersistenceDriver(dbjs, arguments[1]);
	options = Object(arguments[1]);
	this.db = ensureDatabase(dbjs);
	autoSaveFilter = (options.autoSaveFilter != null)
		? ensureCallable(options.autoSaveFilter) : this.constructor.defaultAutoSaveFilter;
	dbjs.objects.on('update', function (event) {
		if (event.sourceId === 'persistentLayer') return;
		if (!autoSaveFilter(event)) return;
		debug("persistent update %s %s", event.object.__valueId__, event.stamp);
		this._cueEvent(event);
	}.bind(this));
}, {
	defaultAutoSaveFilter: d(function (event) { return !isModelId(event.object.master.__id__); })
});

var notImplemented = function () { throw new Error("Not implemented"); };

ee(Object.defineProperties(PersistenceDriver.prototype, assign({
	// Database data
	_importValue: d(function (id, value, stamp) {
		var proto;
		if (this._loadedEventsMap[id + '.' + stamp]) return;
		this._loadedEventsMap[id + '.' + stamp] = true;
		value = unserialize(value, this.db.objects);
		if (value && value.__id__ && (value.constructor.prototype === value)) proto = value.constructor;
		return new Event(this.db.objects.unserialize(id, proto), value, stamp, 'persistentLayer');
	}),
	loadValue: d(function (id) {
		id = ensureString(id);
		this._ensureOpen();
		++this._runningOperations;
		return this._loadValue(id).finally(this._onOperationEnd);
	}),
	loadObject: d(function (id) {
		id = ensureString(id);
		this._ensureOpen();
		++this._runningOperations;
		return this._loadObject(id).finally(this._onOperationEnd);
	}),
	loadAll: d(function () {
		this._ensureOpen();
		++this._runningOperations;
		return this._loadAll().finally(this._onOperationEnd);
	}),
	storeEvent: d(function (event) {
		event = ensureObject(event);
		this._ensureOpen();
		++this._runningOperations;
		return this._storeEvent(event).finally(this._onOperationEnd);
	}),
	storeEvents: d(function (events) {
		events = ensureArray(events);
		this._ensureOpen();
		++this._runningOperations;
		return this._storeEvents(events).finally(this._onOperationEnd);
	}),
	_cueEvent: d(function (event) {
		if (!this._eventsToStore.length) {
			++this._runningOperations;
			this._exportEvents();
		}
		this._eventsToStore.push(event);
	}),
	_loadValue: d(notImplemented),
	_loadObject: d(notImplemented),
	_loadAll: d(notImplemented),
	_storeEvent: d(notImplemented),
	_storeEvents: d(notImplemented),

	// Indexed database data
	indexKeyPath: d(function (keyPath/*, set*/) {
		var names, key, onAdd, onDelete, eventName, listener, set = arguments[1];
		if (set != null) ensureObservableSet(set);
		else set = this.db.Object.instances;
		names = tokenize(ensureString(keyPath));
		this._ensureOpen();
		key = names[names.length - 1];
		eventName = 'computed:' + keyPath;
		++this._runningOperations;
		return this._getIndexedMap(keyPath)(function (map) {
			listener = function (event) {
				var sValue, stamp, objId = event.target.object.master.__id__;
				if (event.target.object.constructor === event.target.object.database.Base) return;
				if (isSet(event.target)) {
					sValue = [];
					event.target.forEach(function (value) { sValue.push(serialize(value)); });
				} else {
					sValue = serialize(event.newValue);
				}
				stamp = event.dbjs ? event.dbjs.stamp : getStamp();
				map[objId].value = sValue;
				map[objId].stamp = stamp;
				this.emit(eventName, map[objId]);
				++this._runningOperations;
				this._storeIndexedValue(objId, keyPath, map[objId]).finally(this._onOperationEnd).done();
			}.bind(this);
			onAdd = function (obj) {
				var observable, value, stamp, objId, sValue, old;
				obj = resolveObject(obj, names);
				if (!obj) return null;
				objId = obj.__id__;
				if (obj.isKeyStatic(key)) {
					value = obj[key];
					stamp = 0;
				} else {
					value = obj._get_(key);
					observable = obj._getObservable_(key);
					stamp = observable.lastModified;
					if (isSet(value)) value.on('change', listener);
					else observable.on('change', listener);
				}
				if (isSet(value)) {
					sValue = [];
					value.forEach(function (value) { sValue.push(serialize(value)); });
				} else {
					sValue = serialize(value);
				}
				old = map[objId];
				if (old) {
					if (old.stamp === stamp) {
						if (isArray(sValue)) {
							if (isCopy.call(old.value, sValue)) return;
						} else {
							if (old.value === sValue) return;
						}
						++stamp; // most likely model update
					} else if (old.stamp > stamp) {
						stamp = old.stamp + 1;
					}
					old.value = sValue;
					old.stamp = stamp;
				} else {
					map[objId] = {
						value: sValue,
						stamp: stamp
					};
				}
				this.emit(eventName, map[objId]);
				return this._storeIndexedValue(objId, keyPath, map[objId]);
			}.bind(this);
			onDelete = function (obj) {
				obj = resolveObject(obj, names);
				if (!obj) return null;
				if (obj.isKeyStatic(key)) return;
				obj._getObservable_(key).off('change', listener);
			}.bind(this);
			set.on('change', function (event) {
				if (event.type === 'add') {
					++this._runningOperations;
					onAdd(event.value).finally(this._onOperationEnd).done();
					return;
				}
				if (event.type === 'delete') {
					onDelete(event.value);
					return;
				}
				if (event.type === 'batch') {
					if (event.added) {
						++this._runningOperations;
						deferred.map(event.added, onAdd).finally(this._onOperationEnd).done();
					}
					if (event.deleted) event.deleted.forEach(onDelete);
				}
			}.bind(this));
			return deferred.map(aFrom(set), onAdd)(map);
		}.bind(this)).finally(this._onOperationEnd);
	}),
	_getIndexedValue: d(notImplemented),
	_getIndexedMap: d(notImplemented),
	_storeIndexedValue: d(notImplemented),

	// Custom data
	getCustom: d(function (key) {
		key = ensureString(key);
		this._ensureOpen();
		++this._runningOperations;
		return this._getCustom(key).finally(this._onOperationEnd);
	}),
	storeCustom: d(function (key, value) {
		key = ensureString(key);
		this._ensureOpen();
		++this._runningOperations;
		return this._storeCustom(ensureString(key), value).finally(this._onOperationEnd);
	}),
	_storeCustom: d(notImplemented),
	_getCustom: d(notImplemented),

	// Storage export/import
	export: d(function (externalStore) {
		ensureDriver(externalStore);
		this._ensureOpen();
		++this._runningOperations;
		return this._exportAll(externalStore).finally(this._onOperationEnd);
	}),
	_exportAll: d(notImplemented),
	_storeRaw: d(notImplemented),

	// Clonnection related
	isClosed: d(false),
	close: d(function () {
		this._ensureOpen();
		this.isClosed = true;
		if (this._runningOperations) {
			this._closeDeferred = deferred();
			return this._closeDeferred.promise;
		}
		return this._close();
	}),
	_ensureOpen: d(function () {
		if (this.isClosed) throw new Error("Database not accessible");
	}),
	_runningOperations: d(0),
	_close: d(notImplemented)
}, autoBind({
	emitError: d(emitError),
	_onOperationEnd: d(function () {
		if (--this._runningOperations) return;
		if (!this._closeDeferred) return;
		this._closeDeferred.resolve(this._close());
	})
}), lazy({
	_loadedEventsMap: d(function () { return create(null); }),
	_eventsToStore: d(function () { return []; }),
	_exportEvents: d(function () {
		return once(function () {
			var promise = this._storeEvents(this._eventsToStore);
			clear.call(this._eventsToStore);
			promise.finally(this._onOperationEnd).done();
		}.bind(this));
	})
}))));
<commit_msg>Cleanup<commit_after>// Abstract Persistence driver

'use strict';

var aFrom               = require('es5-ext/array/from')
  , clear               = require('es5-ext/array/#/clear')
  , isCopy              = require('es5-ext/array/#/is-copy')
  , ensureArray         = require('es5-ext/array/valid-array')
  , assign              = require('es5-ext/object/assign')
  , ensureCallable      = require('es5-ext/object/valid-callable')
  , ensureObject        = require('es5-ext/object/valid-object')
  , ensureString        = require('es5-ext/object/validate-stringifiable-value')
  , isSet               = require('es6-set/is-set')
  , deferred            = require('deferred')
  , emitError           = require('event-emitter/emit-error')
  , d                   = require('d')
  , autoBind            = require('d/auto-bind')
  , lazy                = require('d/lazy')
  , debug               = require('debug-ext')('db')
  , ee                  = require('event-emitter')
  , getStamp            = require('time-uuid/time')
  , ensureObservableSet = require('observable-set/valid-observable-set')
  , ensureDatabase      = require('dbjs/valid-dbjs')
  , Event               = require('dbjs/_setup/event')
  , unserialize         = require('dbjs/_setup/unserialize/value')
  , serialize           = require('dbjs/_setup/serialize/value')
  , resolveKeyPath      = require('dbjs/_setup/utils/resolve-property-path')
  , once                = require('timers-ext/once')
  , ensureDriver        = require('./ensure')

  , isArray = Array.isArray
  , isModelId = RegExp.prototype.test.bind(/^[A-Z]/)
  , tokenize = resolveKeyPath.tokenize, resolveObject = resolveKeyPath.resolveObject
  , create = Object.create;

var PersistenceDriver = module.exports = Object.defineProperties(function (dbjs/*, options*/) {
	var autoSaveFilter, options;
	if (!(this instanceof PersistenceDriver)) return new PersistenceDriver(dbjs, arguments[1]);
	options = Object(arguments[1]);
	this.db = ensureDatabase(dbjs);
	autoSaveFilter = (options.autoSaveFilter != null)
		? ensureCallable(options.autoSaveFilter) : this.constructor.defaultAutoSaveFilter;
	dbjs.objects.on('update', function (event) {
		if (event.sourceId === 'persistentLayer') return;
		if (!autoSaveFilter(event)) return;
		debug("persistent update %s %s", event.object.__valueId__, event.stamp);
		this._cueEvent(event);
	}.bind(this));
}, {
	defaultAutoSaveFilter: d(function (event) { return !isModelId(event.object.master.__id__); })
});

var notImplemented = function () { throw new Error("Not implemented"); };

ee(Object.defineProperties(PersistenceDriver.prototype, assign({
	// Database data
	_importValue: d(function (id, value, stamp) {
		var proto;
		if (this._loadedEventsMap[id + '.' + stamp]) return;
		this._loadedEventsMap[id + '.' + stamp] = true;
		value = unserialize(value, this.db.objects);
		if (value && value.__id__ && (value.constructor.prototype === value)) proto = value.constructor;
		return new Event(this.db.objects.unserialize(id, proto), value, stamp, 'persistentLayer');
	}),
	loadValue: d(function (id) {
		id = ensureString(id);
		this._ensureOpen();
		++this._runningOperations;
		return this._loadValue(id).finally(this._onOperationEnd);
	}),
	loadObject: d(function (id) {
		id = ensureString(id);
		this._ensureOpen();
		++this._runningOperations;
		return this._loadObject(id).finally(this._onOperationEnd);
	}),
	loadAll: d(function () {
		this._ensureOpen();
		++this._runningOperations;
		return this._loadAll().finally(this._onOperationEnd);
	}),
	storeEvent: d(function (event) {
		event = ensureObject(event);
		this._ensureOpen();
		++this._runningOperations;
		return this._storeEvent(event).finally(this._onOperationEnd);
	}),
	storeEvents: d(function (events) {
		events = ensureArray(events);
		this._ensureOpen();
		++this._runningOperations;
		return this._storeEvents(events).finally(this._onOperationEnd);
	}),
	_cueEvent: d(function (event) {
		if (!this._eventsToStore.length) {
			++this._runningOperations;
			this._exportEvents();
		}
		this._eventsToStore.push(event);
	}),
	_loadValue: d(notImplemented),
	_loadObject: d(notImplemented),
	_loadAll: d(notImplemented),
	_storeEvent: d(notImplemented),
	_storeEvents: d(notImplemented),

	// Indexed database data
	indexKeyPath: d(function (keyPath/*, set*/) {
		var names, key, onAdd, onDelete, eventName, listener, set = arguments[1];
		if (set != null) ensureObservableSet(set);
		else set = this.db.Object.instances;
		names = tokenize(ensureString(keyPath));
		this._ensureOpen();
		key = names[names.length - 1];
		eventName = 'computed:' + keyPath;
		++this._runningOperations;
		return this._getIndexedMap(keyPath)(function (map) {
			listener = function (event) {
				var sValue, stamp, objId = event.target.object.master.__id__;
				if (event.target.object.constructor === event.target.object.database.Base) return;
				if (isSet(event.target)) {
					sValue = [];
					event.target.forEach(function (value) { sValue.push(serialize(value)); });
				} else {
					sValue = serialize(event.newValue);
				}
				stamp = event.dbjs ? event.dbjs.stamp : getStamp();
				map[objId].value = sValue;
				map[objId].stamp = stamp;
				this.emit(eventName, map[objId]);
				++this._runningOperations;
				this._storeIndexedValue(objId, keyPath, map[objId]).finally(this._onOperationEnd).done();
			}.bind(this);
			onAdd = function (obj) {
				var observable, value, stamp, objId, sValue, old;
				obj = resolveObject(obj, names);
				if (!obj) return null;
				objId = obj.__id__;
				if (obj.isKeyStatic(key)) {
					value = obj[key];
					stamp = 0;
				} else {
					value = obj._get_(key);
					observable = obj._getObservable_(key);
					stamp = observable.lastModified;
					if (isSet(value)) value.on('change', listener);
					else observable.on('change', listener);
				}
				if (isSet(value)) {
					sValue = [];
					value.forEach(function (value) { sValue.push(serialize(value)); });
				} else {
					sValue = serialize(value);
				}
				old = map[objId];
				if (old) {
					if (old.stamp === stamp) {
						if (isArray(sValue)) {
							if (isCopy.call(old.value, sValue)) return;
						} else {
							if (old.value === sValue) return;
						}
						++stamp; // most likely model update
					} else if (old.stamp > stamp) {
						stamp = old.stamp + 1;
					}
					old.value = sValue;
					old.stamp = stamp;
				} else {
					map[objId] = {
						value: sValue,
						stamp: stamp
					};
				}
				this.emit(eventName, map[objId]);
				return this._storeIndexedValue(objId, keyPath, map[objId]);
			}.bind(this);
			onDelete = function (obj) {
				obj = resolveObject(obj, names);
				if (!obj) return null;
				if (obj.isKeyStatic(key)) return;
				obj._getObservable_(key).off('change', listener);
			}.bind(this);
			set.on('change', function (event) {
				if (event.type === 'add') {
					++this._runningOperations;
					onAdd(event.value).finally(this._onOperationEnd).done();
					return;
				}
				if (event.type === 'delete') {
					onDelete(event.value);
					return;
				}
				if (event.type === 'batch') {
					if (event.added) {
						++this._runningOperations;
						deferred.map(event.added, onAdd).finally(this._onOperationEnd).done();
					}
					if (event.deleted) event.deleted.forEach(onDelete);
				}
			}.bind(this));
			return deferred.map(aFrom(set), onAdd)(map);
		}.bind(this)).finally(this._onOperationEnd);
	}),
	_getIndexedValue: d(notImplemented),
	_getIndexedMap: d(notImplemented),
	_storeIndexedValue: d(notImplemented),

	// Custom data
	getCustom: d(function (key) {
		key = ensureString(key);
		this._ensureOpen();
		++this._runningOperations;
		return this._getCustom(key).finally(this._onOperationEnd);
	}),
	storeCustom: d(function (key, value) {
		key = ensureString(key);
		this._ensureOpen();
		++this._runningOperations;
		return this._storeCustom(ensureString(key), value).finally(this._onOperationEnd);
	}),
	_getCustom: d(notImplemented),
	_storeCustom: d(notImplemented),

	// Any data
	_storeRaw: d(notImplemented),

	// Storage export/import
	export: d(function (externalStore) {
		ensureDriver(externalStore);
		this._ensureOpen();
		++this._runningOperations;
		return this._exportAll(externalStore).finally(this._onOperationEnd);
	}),
	_exportAll: d(notImplemented),

	// Clonnection related
	isClosed: d(false),
	close: d(function () {
		this._ensureOpen();
		this.isClosed = true;
		if (this._runningOperations) {
			this._closeDeferred = deferred();
			return this._closeDeferred.promise;
		}
		return this._close();
	}),
	_ensureOpen: d(function () {
		if (this.isClosed) throw new Error("Database not accessible");
	}),
	_runningOperations: d(0),
	_close: d(notImplemented)
}, autoBind({
	emitError: d(emitError),
	_onOperationEnd: d(function () {
		if (--this._runningOperations) return;
		if (!this._closeDeferred) return;
		this._closeDeferred.resolve(this._close());
	})
}), lazy({
	_loadedEventsMap: d(function () { return create(null); }),
	_eventsToStore: d(function () { return []; }),
	_exportEvents: d(function () {
		return once(function () {
			var promise = this._storeEvents(this._eventsToStore);
			clear.call(this._eventsToStore);
			promise.finally(this._onOperationEnd).done();
		}.bind(this));
	})
}))));
<|endoftext|>


<commit_before>const { Swal, SwalWithoutAnimation } = require('../helpers')

const isIE11 = !!window.MSInputMethodContext && !!document.documentMode

QUnit.test('tall modal', (assert) => {
  SwalWithoutAnimation.fire({
    imageUrl: 'https://placeholder.pics/svg/300x1500',
    imageHeight: 1500
  })

  if (isIE11) {
    assert.equal(Swal.getContainer().style.alignItems, 'flex-start')
  } else {
    assert.equal(Swal.getContainer().style.alignItems, '')
  }
})
<commit_msg>chore: use isIE from helpers<commit_after>const { Swal, SwalWithoutAnimation, isIE } = require('../helpers')

QUnit.test('tall modal', (assert) => {
  SwalWithoutAnimation.fire({
    imageUrl: 'https://placeholder.pics/svg/300x1500',
    imageHeight: 1500
  })

  if (isIE) {
    assert.equal(Swal.getContainer().style.alignItems, 'flex-start')
  } else {
    assert.equal(Swal.getContainer().style.alignItems, '')
  }
})
<|endoftext|>


<commit_before>
var express = require('../')
  , request = require('./support/http');

describe('req', function(){
  describe('.signedCookies', function(){
    it('should return a signed JSON cookie', function(done){
      var app = express();

      app.use(express.cookieParser('secret'));

      app.use(function(req, res){
        if ('/set' == req.path) {
          res.cookie('obj', { foo: 'bar' }, { signed: true });
          res.end();
        } else {
          res.send(req.signedCookies);
        }
      });

      request(app)
      .get('/set')
      .end(function(err, res){
        if (err) return done(err);
        var cookie = res.header['set-cookie'];

        request(app)
        .get('/')
        .set('Cookie', cookie)
        .end(function(err, res){
          if (err) return don(err);
          res.body.should.eql({ obj: { foo: 'bar' } });
          done();
        });
      });
    })

    it('should return a signed cookie', function(done){
      var app = express();

      var replacer = app.get('json replacer');
      var spaces = app.get('json spaces');

      app.use(express.cookieParser('secret'));

      app.use(function(req, res){
        res.send(req.signedCookies);
      });

      app.response.req = { secret: 'secret' };
      app.response.cookie('foo', 'bar', { signed: true });
      var cookie = app.response.get('set-cookie');

      var val = JSON.stringify({ foo: 'bar' }, replacer, spaces);

      request(app)
      .get('/')
      .set('Cookie', cookie)
      .expect(val, done);
    })
  })
})

<commit_msg>remove second signed cookie test<commit_after>
var express = require('../')
  , request = require('./support/http');

describe('req', function(){
  describe('.signedCookies', function(){
    it('should return a signed JSON cookie', function(done){
      var app = express();

      app.use(express.cookieParser('secret'));

      app.use(function(req, res){
        if ('/set' == req.path) {
          res.cookie('obj', { foo: 'bar' }, { signed: true });
          res.end();
        } else {
          res.send(req.signedCookies);
        }
      });

      request(app)
      .get('/set')
      .end(function(err, res){
        if (err) return done(err);
        var cookie = res.header['set-cookie'];

        request(app)
        .get('/')
        .set('Cookie', cookie)
        .end(function(err, res){
          if (err) return don(err);
          res.body.should.eql({ obj: { foo: 'bar' } });
          done();
        });
      });
    })
  })
})

<|endoftext|>


<commit_before>var dgram = require('dgram')
var url = require('url')

var stringify = require('prolific.stringify')
var delta = require('delta')
var cadence = require('cadence')
var Turnstile = require('turnstile')
Turnstile.Queue = require('turnstile/queue')

var Evaluator = require('prolific.evaluator')

var host = require('./host')

var youHaveGotToBeKiddingMe = require('./error')

function Processor (turnstile, parameters, nextProcessor) {
    this._queue = new Turnstile.Queue(this, '_process', turnstile)
    if (parameters.url != null) {
        var parsed = host(parameters.url)
        this._select = function () { return parsed }
    } else {
        var select = Evaluator.create(parameters.select)
        this._select = function (entry) { return host(select(entry)) }
    }
    this._nextProcessor = nextProcessor
}

Processor.prototype.process = function (entry) {
    var server = this._select.call(null, entry)
    if (server != null) {
        this._queue.push({
            server: server,
            stringified: stringify(entry)
        })
    }
    this._nextProcessor.process(entry)
}

Processor.prototype._process = cadence(function (async, envelope) {
    var client = dgram.createSocket('udp4')
    var body = envelope.body
    async(function () {
        var buffer = Buffer.from(body.stringified)
        var server = body.server
        client.send(buffer, 0, buffer.length, server.port, server.hostname, youHaveGotToBeKiddingMe(async()))
    }, function () {
// ACHTUNG Node.js 0.10 does not accept a callback to `close()`, you must set a handler.
        delta(async()).ee(client).on('close')
        client.close()
    })
})

module.exports = cadence(function (async, destructible, configuration, nextProcessor) {
    var turnstile = new Turnstile
    // TODO We're probably doing this wrong. We don't want to just stop the
    // turnstile, we want to wait for it to empty.
    /*
    destructible.destruct.wait(turnstile, 'close')
    turnstile.listen(destructible.monitor('turnstile'))
     */
    return [ new Processor(turnstile, configuration, nextProcessor) ]
})
<commit_msg>Add `isProlificProcessor` flag.<commit_after>var dgram = require('dgram')
var url = require('url')

var stringify = require('prolific.stringify')
var delta = require('delta')
var cadence = require('cadence')
var Turnstile = require('turnstile')
Turnstile.Queue = require('turnstile/queue')

var Evaluator = require('prolific.evaluator')

var host = require('./host')

var youHaveGotToBeKiddingMe = require('./error')

function Processor (turnstile, parameters, nextProcessor) {
    this._queue = new Turnstile.Queue(this, '_process', turnstile)
    if (parameters.url != null) {
        var parsed = host(parameters.url)
        this._select = function () { return parsed }
    } else {
        var select = Evaluator.create(parameters.select)
        this._select = function (entry) { return host(select(entry)) }
    }
    this._nextProcessor = nextProcessor
}

Processor.prototype.process = function (entry) {
    var server = this._select.call(null, entry)
    if (server != null) {
        this._queue.push({
            server: server,
            stringified: stringify(entry)
        })
    }
    this._nextProcessor.process(entry)
}

Processor.prototype._process = cadence(function (async, envelope) {
    var client = dgram.createSocket('udp4')
    var body = envelope.body
    async(function () {
        var buffer = Buffer.from(body.stringified)
        var server = body.server
        client.send(buffer, 0, buffer.length, server.port, server.hostname, youHaveGotToBeKiddingMe(async()))
    }, function () {
// ACHTUNG Node.js 0.10 does not accept a callback to `close()`, you must set a handler.
        delta(async()).ee(client).on('close')
        client.close()
    })
})

module.exports = cadence(function (async, destructible, configuration, nextProcessor) {
    var turnstile = new Turnstile
    // TODO We're probably doing this wrong. We don't want to just stop the
    // turnstile, we want to wait for it to empty.
    /*
    destructible.destruct.wait(turnstile, 'close')
    turnstile.listen(destructible.monitor('turnstile'))
     */
    return [ new Processor(turnstile, configuration, nextProcessor) ]
})

module.exports.isProlificProcessor = true
<|endoftext|>


<commit_before>module.exports = function(app, router, logger, event, fs) {
    logger.info('module file');

    var path = require('path');

    router.get('/list', function(req, res) {
        var direction = req.body.direction;
        var filelist = [];
        fs.readdirAsync(direction + "/")
            .then(function(list) {
                list.forEach(function(filename) {
                    if (!/\.js$/.test(filename)) {
                        return;
                    }
                    filelist.push(filename);
                })
                res.json({
                    script: filelist
                });
            })
            .catch(function(error) {
                res.json({
                    error: error
                });
            })

    });

    router.get('/read', function(req, res) {
        var direction = req.body.direction;
        var filename = req.body.filename;
        fs.readFileAsync(direction + "/" + filename, "utf8")
            .then(function(file) {
                res.send(file);
            })
            .catch(function(error) {
                res.json({
                    error: error
                });
            })
    });

    router.post('/write', function(req, res) {
        var direction = req.body.direction;
        var filename = req.params.filename;
        var data = req.params.data;
        var ret = fs.writeFileSync(direction + "/" + filename, data);
        fs.writeFileAsync(direction + "/" + filename, data)
            .then(function() {
                res.json({
                    message: 'write success'
                });
            })
            .catch(function(error) {
                res.json({
                    error: error
                });
            })
    });

    router.delete('/delete', function(req, res) {
        var direction = req.body.direction;
        var filename = req.body.filename;
        fs.unlinkAsync(direction + "/" + filename)
            .then(function() {
                res.json({
                    message: 'delete success'
                });
            })
            .catch(function(error) {
                res.json({
                    error: error
                });
            })
    });

    app.use('/file', router);
}<commit_msg>fix express issue<commit_after>module.exports = function(app, express, logger, event, fs) {
    logger.info('module file');

    var path = require('path');
    var router = express.Router();

    router.get('/list', function(req, res) {
        var direction = req.body.direction;
        var filelist = [];
        fs.readdirAsync(direction + "/")
            .then(function(list) {
                list.forEach(function(filename) {
                    if (!/\.js$/.test(filename)) {
                        return;
                    }
                    filelist.push(filename);
                })
                res.json({
                    script: filelist
                });
            })
            .catch(function(error) {
                res.json({
                    error: error
                });
            })

    });

    router.get('/read', function(req, res) {
        var direction = req.body.direction;
        var filename = req.body.filename;
        fs.readFileAsync(direction + "/" + filename, "utf8")
            .then(function(file) {
                res.send(file);
            })
            .catch(function(error) {
                res.json({
                    error: error
                });
            })
    });

    router.post('/write', function(req, res) {
        var direction = req.body.direction;
        var filename = req.params.filename;
        var data = req.params.data;
        var ret = fs.writeFileSync(direction + "/" + filename, data);
        fs.writeFileAsync(direction + "/" + filename, data)
            .then(function() {
                res.json({
                    message: 'write success'
                });
            })
            .catch(function(error) {
                res.json({
                    error: error
                });
            })
    });

    router.delete('/delete', function(req, res) {
        var direction = req.body.direction;
        var filename = req.body.filename;
        fs.unlinkAsync(direction + "/" + filename)
            .then(function() {
                res.json({
                    message: 'delete success'
                });
            })
            .catch(function(error) {
                res.json({
                    error: error
                });
            })
    });

    app.use('/file', router);
}<|endoftext|>


<commit_before>module.exports = function(app, router, logger, event) {
    logger.info('module file');

    var fs = require('fs');
    var path = require('path');

    router.get('/list', function(req, res) {
        var direction = req.body.direction;
        var filelist = [];
        fs.readdirSync(direction + "/").forEach(function(filename) {
            if (!/\.js$/.test(filename)) {
                return;
            }
            filelist.push(filename);
        });
        res.json({
            script: filelist
        });
    });

    router.get('/read', function(req, res) {
        var direction = req.body.direction;
        var filename = req.body.filename;
        var ret = fs.readFileSync(direction + "/" + filename, "utf8");
        res.send(ret);
    });

    router.post('/write', function(req, res) {
        var direction = req.body.direction;
        var filename = req.params.filename;
        var data = req.params.data;
        var ret = fs.writeFileSync(direction + "/" + filename, data);
        res.send(ret);
    });

    router.delete('/delete', function(req, res) {
        var direction = req.body.direction;
        var filename = req.body.filename;
        var code = fs.unlinkSync(direction + "/" + filename);
        res.send(code);
    });

    app.use('/file', router);
}<commit_msg>update the file part<commit_after>module.exports = function(app, router, logger, event, fs) {
    logger.info('module file');

    var path = require('path');

    router.get('/list', function(req, res) {
        var direction = req.body.direction;
        var filelist = [];
        fs.readdirAsync(direction + "/")
            .then(function(list) {
                list.forEach(function(filename) {
                    if (!/\.js$/.test(filename)) {
                        return;
                    }
                    filelist.push(filename);
                })
                res.json({
                    script: filelist
                });
            })
            .catch(function(error) {
                res.json({
                    error: error
                });
            })

    });

    router.get('/read', function(req, res) {
        var direction = req.body.direction;
        var filename = req.body.filename;
        fs.readFileAsync(direction + "/" + filename, "utf8")
            .then(function(file) {
                res.send(file);
            })
            .catch(function(error) {
                res.json({
                    error: error
                });
            })
    });

    router.post('/write', function(req, res) {
        var direction = req.body.direction;
        var filename = req.params.filename;
        var data = req.params.data;
        var ret = fs.writeFileSync(direction + "/" + filename, data);
        fs.writeFileAsync(direction + "/" + filename, data)
            .then(function() {
                res.json({
                    message: 'write success'
                });
            })
            .catch(function(error) {
                res.json({
                    error: error
                });
            })
    });

    router.delete('/delete', function(req, res) {
        var direction = req.body.direction;
        var filename = req.body.filename;
        fs.unlinkAsync(direction + "/" + filename)
            .then(function() {
                res.json({
                    message: 'delete success'
                });
            })
            .catch(function(error) {
                res.json({
                    error: error
                });
            })
    });

    app.use('/file', router);
}<|endoftext|>


<commit_before>#!/usr/bin/env node
"use strict";

const program = require("commander");
const SemVer = require("semver");
const inquirer = require("inquirer");
const chalk = require("chalk");
const api = require("../");

program
  .version(require("../package").version)
  .option("--major", "Increase major version")
  .option("--minor", "Increase minor version")
  .option("--patch", "Increase patch version")
  .option("--premajor", "Increase major version, pre-release")
  .option("--preminor", "Increase preminor version, pre-release")
  .option("--prepatch", "Increase prepatch version, pre-release")
  .option("--prerelease", "Increase prerelease version")
  .option("--prompt", "Prompt for type of bump (patch, minor, major, premajor, prerelase, etc.)")
  .option("--preid <name>", 'The identifier for prerelease versions (default is "beta")')
  .option("--commit [message]", 'Commit changed files to Git (default message is "release vX.X.X")')
  .option("--tag", "Tag the commit in Git")
  .option("--push", "Push the Git commit")
  .option("--all", "Commit/tag/push ALL pending files, not just the ones changed by bump")
  .option("--grep <filespec...>", "Files and/or globs to do a text-replace of the old version number with the new one")
  .option("--lock", "Also update the package-lock.json")
  .on("--help", () => {
    console.log(
      "\n  Examples:\n" +
      "\n" +
      "    $ bump --patch\n" +
      "    $ bump --major --tag\n" +
      "    $ bump --patch --tag --all --grep README.md\n" +
      "    $ bump --prompt --tag --push --all\n"
    );
  })
  .parse(process.argv);

// Show help if no options were given
if (program.rawArgs.length < 3) {
  program.help();
}
else {
  let options = program;

  if (options.grep && program.args) {
    // If multiple --grep files are specified, then they are parsed as separate args
    options.grep = program.args.concat(options.grep);
  }

  if (typeof options.commit === "string") {
    options.commitMessage = options.commit;
    options.commit = true;
  }

  let manifests = api.manifests(options.lock);
  bumpManifests(manifests, options)
    .then(() => {
      api.grep(manifests, options);
      manifests.forEach((manifest) => {
        api.runNpmScriptIfExists(manifest, "version");
      });
    })
    .then(() => {
      if (options.commit || options.tag || options.push) {
        api.git(manifests, options);
      }
      else {
        manifests.forEach((manifest) => {
          api.runNpmScriptIfExists(manifest, "postversion");
        });
      }
    })
    .catch((err) => {
      console.error(chalk.red(err.message));
      process.exit(err.status || 1);
    });
}

/**
 * Bumps each manifest sequentially
 *
 * @param {string[]} manifests - An array of manifest files to bump
 * @param {object} options - CLI options
 * @returns {Promise}
 */
function bumpManifests (manifests, options) {
  let i = 0;

  return bumpNext("patch");

  function bumpNext (defaultBumpType) {
    let manifest = manifests[i++];
    if (manifest) {
      return bumpManifest(manifest, defaultBumpType, options).then(bumpNext);
    }
    else {
      return Promise.resolve(defaultBumpType);
    }
  }
}

/**
 * Bumps the given manifest
 *
 * @param {string} manifest - The manifest name (e.g. "package.json", "bower.json", etc.)
 * @param {string} defaultBumpType - The default type of bump to perform
 * @param {object} options - CLI options
 * @returns {Promise}
 */
function bumpManifest (manifest, defaultBumpType, options) {
  return new Promise((resolve, reject) => {
    api.runNpmScriptIfExists(manifest, "preversion");

    if (options.prompt) {
      // Prompt the user for the type of bump to perform
      let version = api.versionInfo(manifest, options);
      console.log("\nCurrent version in %s is %s", manifest, version.current);

      inquirer.prompt([
        {
          type: "list",
          name: "bumpType",
          message: "How would you like to bump it?",
          default: defaultBumpType,
          choices: [
            { value: "major", name: "major (" + version.nextMajor + ")" },
            { value: "minor", name: "minor (" + version.nextMinor + ")" },
            { value: "patch", name: "patch (" + version.nextPatch + ")" },
            { value: "premajor", name: "pre-release major (" + version.nextPreMajor + ")" },
            { value: "preminor", name: "pre-release minor (" + version.nextPreMinor + ")" },
            { value: "prepatch", name: "pre-release patch (" + version.nextPrePatch + ")" },
            { value: "prerelease", name: "pre-release (" + version.nextPreRelease + ")" },
            new inquirer.Separator(),
            { value: "custom", name: "custom..." },
          ]
        },
        {
          type: "input",
          name: "newVersion",
          message: "Enter the new version number:",
          default: version.current,
          when: answers => answers.bumpType === "custom",
          filter: SemVer.clean,
          validate: answer => {
            return SemVer.valid(answer) ? true : "That's not a valid version number";
          },
        }
      ])
        .then((answers) => {
          bump(answers.bumpType, answers.newVersion);
        });
    }
    else {
      let bumpType =
            options.major ? "major"
              : options.minor ? "minor"
                : options.patch ? "patch"
                  : options.premajor ? "premajor"
                    : options.preminor ? "preminor"
                      : options.prepatch ? "prepatch"
                        : options.prerelease ? "prerelease"
                          : defaultBumpType;

      bump(bumpType);
    }

    function bump (bumpType, newVersion) {
      try {
        options.newVersion = newVersion;
        api.bump(manifest, bumpType, options);
      }
      catch (ex) {
        reject(ex);
      }
      resolve(bumpType);
    }
  });
}
<commit_msg>Set the `pageSize` option so that all of the `--prompt` options are displayed without requiring scrolling<commit_after>#!/usr/bin/env node
"use strict";

const program = require("commander");
const SemVer = require("semver");
const inquirer = require("inquirer");
const chalk = require("chalk");
const api = require("../");

program
  .version(require("../package").version)
  .option("--major", "Increase major version")
  .option("--minor", "Increase minor version")
  .option("--patch", "Increase patch version")
  .option("--premajor", "Increase major version, pre-release")
  .option("--preminor", "Increase preminor version, pre-release")
  .option("--prepatch", "Increase prepatch version, pre-release")
  .option("--prerelease", "Increase prerelease version")
  .option("--prompt", "Prompt for type of bump (patch, minor, major, premajor, prerelase, etc.)")
  .option("--preid <name>", 'The identifier for prerelease versions (default is "beta")')
  .option("--commit [message]", 'Commit changed files to Git (default message is "release vX.X.X")')
  .option("--tag", "Tag the commit in Git")
  .option("--push", "Push the Git commit")
  .option("--all", "Commit/tag/push ALL pending files, not just the ones changed by bump")
  .option("--grep <filespec...>", "Files and/or globs to do a text-replace of the old version number with the new one")
  .option("--lock", "Also update the package-lock.json")
  .on("--help", () => {
    console.log(
      "\n  Examples:\n" +
      "\n" +
      "    $ bump --patch\n" +
      "    $ bump --major --tag\n" +
      "    $ bump --patch --tag --all --grep README.md\n" +
      "    $ bump --prompt --tag --push --all\n"
    );
  })
  .parse(process.argv);

// Show help if no options were given
if (program.rawArgs.length < 3) {
  program.help();
}
else {
  let options = program;

  if (options.grep && program.args) {
    // If multiple --grep files are specified, then they are parsed as separate args
    options.grep = program.args.concat(options.grep);
  }

  if (typeof options.commit === "string") {
    options.commitMessage = options.commit;
    options.commit = true;
  }

  let manifests = api.manifests(options.lock);
  bumpManifests(manifests, options)
    .then(() => {
      api.grep(manifests, options);
      manifests.forEach((manifest) => {
        api.runNpmScriptIfExists(manifest, "version");
      });
    })
    .then(() => {
      if (options.commit || options.tag || options.push) {
        api.git(manifests, options);
      }
      else {
        manifests.forEach((manifest) => {
          api.runNpmScriptIfExists(manifest, "postversion");
        });
      }
    })
    .catch((err) => {
      console.error(chalk.red(err.message));
      process.exit(err.status || 1);
    });
}

/**
 * Bumps each manifest sequentially
 *
 * @param {string[]} manifests - An array of manifest files to bump
 * @param {object} options - CLI options
 * @returns {Promise}
 */
function bumpManifests (manifests, options) {
  let i = 0;

  return bumpNext("patch");

  function bumpNext (defaultBumpType) {
    let manifest = manifests[i++];
    if (manifest) {
      return bumpManifest(manifest, defaultBumpType, options).then(bumpNext);
    }
    else {
      return Promise.resolve(defaultBumpType);
    }
  }
}

/**
 * Bumps the given manifest
 *
 * @param {string} manifest - The manifest name (e.g. "package.json", "bower.json", etc.)
 * @param {string} defaultBumpType - The default type of bump to perform
 * @param {object} options - CLI options
 * @returns {Promise}
 */
function bumpManifest (manifest, defaultBumpType, options) {
  return new Promise((resolve, reject) => {
    api.runNpmScriptIfExists(manifest, "preversion");

    if (options.prompt) {
      // Prompt the user for the type of bump to perform
      let version = api.versionInfo(manifest, options);
      console.log("\nCurrent version in %s is %s", manifest, version.current);

      inquirer.prompt([
        {
          type: "list",
          name: "bumpType",
          message: "How would you like to bump it?",
          default: defaultBumpType,
          pageSize: 9,
          choices: [
            { value: "major", name: "major (" + version.nextMajor + ")" },
            { value: "minor", name: "minor (" + version.nextMinor + ")" },
            { value: "patch", name: "patch (" + version.nextPatch + ")" },
            { value: "premajor", name: "pre-release major (" + version.nextPreMajor + ")" },
            { value: "preminor", name: "pre-release minor (" + version.nextPreMinor + ")" },
            { value: "prepatch", name: "pre-release patch (" + version.nextPrePatch + ")" },
            { value: "prerelease", name: "pre-release (" + version.nextPreRelease + ")" },
            new inquirer.Separator(),
            { value: "custom", name: "custom..." },
          ]
        },
        {
          type: "input",
          name: "newVersion",
          message: "Enter the new version number:",
          default: version.current,
          when: answers => answers.bumpType === "custom",
          filter: SemVer.clean,
          validate: answer => {
            return SemVer.valid(answer) ? true : "That's not a valid version number";
          },
        }
      ])
        .then((answers) => {
          bump(answers.bumpType, answers.newVersion);
        });
    }
    else {
      let bumpType =
            options.major ? "major"
              : options.minor ? "minor"
                : options.patch ? "patch"
                  : options.premajor ? "premajor"
                    : options.preminor ? "preminor"
                      : options.prepatch ? "prepatch"
                        : options.prerelease ? "prerelease"
                          : defaultBumpType;

      bump(bumpType);
    }

    function bump (bumpType, newVersion) {
      try {
        options.newVersion = newVersion;
        api.bump(manifest, bumpType, options);
      }
      catch (ex) {
        reject(ex);
      }
      resolve(bumpType);
    }
  });
}
<|endoftext|>


<commit_before>"use strict";

const assert = require('assert');
const fs = require('fs');

const lib = require('../index.js');
const SchemaRegistry = require('../index.js').SchemaRegistry;
const Schema = require('../index.js').Schema;
const Parser = require('../index.js').StreamParser;

const metaschemas = [
	require('json-metaschema/draft-2019-09-schema.json'),
	require('json-metaschema/draft-2019-09-hyper-schema.json'),
	require('json-metaschema/draft-2019-09-meta-applicator.json'),
	require('json-metaschema/draft-2019-09-meta-content.json'),
	require('json-metaschema/draft-2019-09-meta-core.json'),
	require('json-metaschema/draft-2019-09-meta-format.json'),
	require('json-metaschema/draft-2019-09-meta-meta-data.json'),
	require('json-metaschema/draft-2019-09-meta-validation.json'),
	require('json-metaschema/draft-2019-09-schema.json'),
];

var validationTestFiles = [
	'draft2019-09/additionalItems.json',
	'draft2019-09/additionalProperties.json',
	'draft2019-09/allOf.json',
	'draft2019-09/anchor.json',
	'draft2019-09/anyOf.json',
	'draft2019-09/boolean_schema.json',
	'draft2019-09/const.json',
	// 'draft2019-09/contains.json',
	'draft2019-09/default.json',
	'draft2019-09/defs.json',
	// 'draft2019-09/dependentRequired.json',
	// 'draft2019-09/dependentSchemas.json',
	'draft2019-09/enum.json',
	'draft2019-09/exclusiveMaximum.json',
	'draft2019-09/exclusiveMinimum.json',
	'draft2019-09/format.json',
	'draft2019-09/if-then-else.json',
	'draft2019-09/items.json',
	'draft2019-09/maxItems.json',
	'draft2019-09/maxLength.json',
	'draft2019-09/maxProperties.json',
	'draft2019-09/maximum.json',
	'draft2019-09/minItems.json',
	'draft2019-09/minLength.json',
	'draft2019-09/minProperties.json',
	'draft2019-09/minimum.json',
	'draft2019-09/multipleOf.json',
	'draft2019-09/not.json',
	'draft2019-09/oneOf.json',
	'draft2019-09/pattern.json',
	'draft2019-09/patternProperties.json',
	'draft2019-09/properties.json',
	// 'draft2019-09/propertyNames.json',
	'draft2019-09/ref.json',
	// 'draft2019-09/refRemote.json',
	'draft2019-09/required.json',
	'draft2019-09/type.json',
	// 'draft2019-09/unevaluatedItems.json',
	'draft2019-09/unevaluatedProperties.json',
	// 'draft2019-09/uniqueItems.json',
	'draft2019-09/optional/bignum.json',
	// 'draft2019-09/optional/content.json',
	'draft2019-09/optional/non-bmp-regex.json',
	// 'draft2019-09/optional/refOfUnknownKeyword.json',
	// 'draft2019-09/optional/format/date-time.json',
	// 'draft2019-09/optional/format/date.json',
	// 'draft2019-09/optional/format/email.json',
	// 'draft2019-09/optional/format/hostname.json',
	// 'draft2019-09/optional/format/idn-email.json',
	// 'draft2019-09/optional/format/idn-hostname.json',
	// 'draft2019-09/optional/format/ipv4.json',
	// 'draft2019-09/optional/format/ipv6.json',
	// 'draft2019-09/optional/format/iri-reference.json',
	// 'draft2019-09/optional/format/iri.json',
	// 'draft2019-09/optional/format/json-pointer.json',
	// 'draft2019-09/optional/format/regex.json',
	// 'draft2019-09/optional/format/relative-json-pointer.json',
	// 'draft2019-09/optional/format/time.json',
	// 'draft2019-09/optional/format/uri-reference.json',
	// 'draft2019-09/optional/format/uri-template.json',
	// 'draft2019-09/optional/format/uri.json',
];

function markPending(dir){
	fs.readdirSync(__dirname+'/vendor-schema-suite/tests/'+dir).forEach(function(filename){
		const filepath = dir + filename;
		if(filepath.match(/\.json$/) && validationTestFiles.indexOf(filepath)<0){
			it(filepath);
		}
	});
}

describe('Schema tests', function(){
	it('meta', function(){
		assert(validationTestFiles.length);
	});
	// Mark disabled files as pending
	markPending('draft2019-09/');
	markPending('draft2019-09/optional/');
	validationTestFiles.forEach(function(filename){
		var label = filename;
		var filepath = __dirname+'/vendor-schema-suite/tests/' + filename;
		describe(label, function(){
			var schemas = require(filepath);
			schemas.forEach(function(schemaTest){
				var tests = schemaTest.tests;
				describe(schemaTest.description, function(){
					tests.forEach(function(t, i){
						it(t.description, function(){
							var tjson = JSON.stringify(t.data, null, "\t");
							var registry = new SchemaRegistry;
							// This passes just one test
							metaschemas.forEach(function(v){ registry.scan(v); });
							var schema = registry.import('http://localhost/'+filename+'/'+i+'/schema', schemaTest.schema);
							assert(schema instanceof Schema);
							if(t.valid){
								var p = lib.parseInfo(tjson, schema);
								if(p.errors.length) console.error(p.errors.map(function(v){ return v.toString(); }));
								assert.strictEqual(p.errors.length, 0, 'Unexpected validation failure');
							}else{
								assert.throws(function(){
									lib.parse(tjson, schema);
								});
								// assert.notEqual(p.errors.length, 0);
							}
						});
					});
				});
			});
		});
	});
});
<commit_msg>Supress unevaluatedProperties tests until it's implemented<commit_after>"use strict";

const assert = require('assert');
const fs = require('fs');

const lib = require('../index.js');
const SchemaRegistry = require('../index.js').SchemaRegistry;
const Schema = require('../index.js').Schema;
const Parser = require('../index.js').StreamParser;

const metaschemas = [
	require('json-metaschema/draft-2019-09-schema.json'),
	require('json-metaschema/draft-2019-09-hyper-schema.json'),
	require('json-metaschema/draft-2019-09-meta-applicator.json'),
	require('json-metaschema/draft-2019-09-meta-content.json'),
	require('json-metaschema/draft-2019-09-meta-core.json'),
	require('json-metaschema/draft-2019-09-meta-format.json'),
	require('json-metaschema/draft-2019-09-meta-meta-data.json'),
	require('json-metaschema/draft-2019-09-meta-validation.json'),
	require('json-metaschema/draft-2019-09-schema.json'),
];

var validationTestFiles = [
	'draft2019-09/additionalItems.json',
	'draft2019-09/additionalProperties.json',
	'draft2019-09/allOf.json',
	'draft2019-09/anchor.json',
	'draft2019-09/anyOf.json',
	'draft2019-09/boolean_schema.json',
	'draft2019-09/const.json',
	// 'draft2019-09/contains.json',
	'draft2019-09/default.json',
	'draft2019-09/defs.json',
	// 'draft2019-09/dependentRequired.json',
	// 'draft2019-09/dependentSchemas.json',
	'draft2019-09/enum.json',
	'draft2019-09/exclusiveMaximum.json',
	'draft2019-09/exclusiveMinimum.json',
	'draft2019-09/format.json',
	'draft2019-09/if-then-else.json',
	'draft2019-09/items.json',
	'draft2019-09/maxItems.json',
	'draft2019-09/maxLength.json',
	'draft2019-09/maxProperties.json',
	'draft2019-09/maximum.json',
	'draft2019-09/minItems.json',
	'draft2019-09/minLength.json',
	'draft2019-09/minProperties.json',
	'draft2019-09/minimum.json',
	'draft2019-09/multipleOf.json',
	'draft2019-09/not.json',
	'draft2019-09/oneOf.json',
	'draft2019-09/pattern.json',
	'draft2019-09/patternProperties.json',
	'draft2019-09/properties.json',
	// 'draft2019-09/propertyNames.json',
	'draft2019-09/ref.json',
	// 'draft2019-09/refRemote.json',
	'draft2019-09/required.json',
	'draft2019-09/type.json',
	// 'draft2019-09/unevaluatedItems.json',
	// 'draft2019-09/unevaluatedProperties.json',
	// 'draft2019-09/uniqueItems.json',
	'draft2019-09/optional/bignum.json',
	// 'draft2019-09/optional/content.json',
	'draft2019-09/optional/non-bmp-regex.json',
	// 'draft2019-09/optional/refOfUnknownKeyword.json',
	// 'draft2019-09/optional/format/date-time.json',
	// 'draft2019-09/optional/format/date.json',
	// 'draft2019-09/optional/format/email.json',
	// 'draft2019-09/optional/format/hostname.json',
	// 'draft2019-09/optional/format/idn-email.json',
	// 'draft2019-09/optional/format/idn-hostname.json',
	// 'draft2019-09/optional/format/ipv4.json',
	// 'draft2019-09/optional/format/ipv6.json',
	// 'draft2019-09/optional/format/iri-reference.json',
	// 'draft2019-09/optional/format/iri.json',
	// 'draft2019-09/optional/format/json-pointer.json',
	// 'draft2019-09/optional/format/regex.json',
	// 'draft2019-09/optional/format/relative-json-pointer.json',
	// 'draft2019-09/optional/format/time.json',
	// 'draft2019-09/optional/format/uri-reference.json',
	// 'draft2019-09/optional/format/uri-template.json',
	// 'draft2019-09/optional/format/uri.json',
];

function markPending(dir){
	fs.readdirSync(__dirname+'/vendor-schema-suite/tests/'+dir).forEach(function(filename){
		const filepath = dir + filename;
		if(filepath.match(/\.json$/) && validationTestFiles.indexOf(filepath)<0){
			it(filepath);
		}
	});
}

describe('Schema tests', function(){
	it('meta', function(){
		assert(validationTestFiles.length);
	});
	// Mark disabled files as pending
	markPending('draft2019-09/');
	markPending('draft2019-09/optional/');
	validationTestFiles.forEach(function(filename){
		var label = filename;
		var filepath = __dirname+'/vendor-schema-suite/tests/' + filename;
		describe(label, function(){
			var schemas = require(filepath);
			schemas.forEach(function(schemaTest){
				var tests = schemaTest.tests;
				describe(schemaTest.description, function(){
					tests.forEach(function(t, i){
						it(t.description, function(){
							var tjson = JSON.stringify(t.data, null, "\t");
							var registry = new SchemaRegistry;
							// This passes just one test
							metaschemas.forEach(function(v){ registry.scan(v); });
							var schema = registry.import('http://localhost/'+filename+'/'+i+'/schema', schemaTest.schema);
							assert(schema instanceof Schema);
							if(t.valid){
								var p = lib.parseInfo(tjson, schema);
								if(p.errors.length) console.error(p.errors.map(function(v){ return v.toString(); }));
								assert.strictEqual(p.errors.length, 0, 'Unexpected validation failure');
							}else{
								assert.throws(function(){
									lib.parse(tjson, schema);
								});
								// assert.notEqual(p.errors.length, 0);
							}
						});
					});
				});
			});
		});
	});
});
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var fs = require('fs')
  , path = require('path')
  , join = path.join
  , dirname = path.dirname
  , exists = fs.existsSync || path.existsSync
  , defaults = {
        arrow: process.env.NODE_BINDINGS_ARROW || ' → '
      , compiled: process.env.NODE_BINDINGS_COMPILED_DIR || 'compiled'
      , platform: process.platform
      , arch: process.arch
      , version: process.versions.node
      , bindings: 'bindings.node'
      , try: [
          // node-gyp's linked version in the "build" dir
          [ 'module_root', 'build', 'bindings' ]
          // node-waf and gyp_addon (a.k.a node-gyp)
        , [ 'module_root', 'build', 'Debug', 'bindings' ]
        , [ 'module_root', 'build', 'Release', 'bindings' ]
          // Debug files, for development (legacy behavior, remove for node v0.9)
        , [ 'module_root', 'out', 'Debug', 'bindings' ]
        , [ 'module_root', 'Debug', 'bindings' ]
          // Release files, but manually compiled (legacy behavior, remove for node v0.9)
        , [ 'module_root', 'out', 'Release', 'bindings' ]
        , [ 'module_root', 'Release', 'bindings' ]
          // Legacy from node-waf, node <= 0.4.x
        , [ 'module_root', 'build', 'default', 'bindings' ]
          // Production "Release" buildtype binary (meh...)
        , [ 'module_root', 'compiled', 'version', 'platform', 'arch', 'bindings' ]
        ]
    }

/**
 * The main `bindings()` function loads the compiled bindings for a given module.
 * It uses V8's Error API to determine the parent filename that this function is
 * being invoked from, which is then used to find the root directory.
 */

function bindings (opts) {

  // Argument surgery
  if (typeof opts == 'string') {
    opts = { bindings: opts }
  } else if (!opts) {
    opts = {}
  }
  opts.__proto__ = defaults

  // Get the module root
  if (!opts.module_root) {
    opts.module_root = exports.getRoot(exports.getFileName())
  }

  // Ensure the given bindings name ends with .node
  if (path.extname(opts.bindings) != '.node') {
    opts.bindings += '.node'
  }

  var tries = []
    , i = 0
    , l = opts.try.length
    , n

  for (; i<l; i++) {
    n = join.apply(null, opts.try[i].map(function (p) {
      return opts[p] || p
    }))
    tries.push(n)
    try {
      var b = require(n)
      b.path = n
      return b
    } catch (e) {
      if (!/not find/i.test(e.message)) {
        throw e
      }
    }
  }

  var err = new Error('Could not load the bindings file. Tried:\n'
    + tries.map(function (a) { return opts.arrow + a }).join('\n'))
  err.tries = tries
  throw err
}
module.exports = exports = bindings

/**
 * Gets the filename of the JavaScript file that invokes this function.
 * Used to help find the root directory of a module.
 */

exports.getFileName = function getFileName () {
  var origPST = Error.prepareStackTrace
    , dummy = {}
    , fileName

  Error.prepareStackTrace = function (e, st) {
    for (var i=0, l=st.length; i<l; i++) {
      fileName = st[i].getFileName()
      if (fileName !== __filename) {
        return
      }
    }
  }

  // run the 'prepareStackTrace' function above
  Error.captureStackTrace(dummy)
  dummy.stack

  // cleanup
  Error.prepareStackTrace = origPST

  return fileName
}

/**
 * Gets the root directory of a module, given an arbitrary filename
 * somewhere in the module tree. The "root directory" is the directory
 * containing the `package.json` file.
 *
 *   In:  /home/nate/node-native-module/lib/index.js
 *   Out: /home/nate/node-native-module
 */

exports.getRoot = function getRoot (file) {
  var dir = dirname(file)
    , prev
  while (true) {
    if (dir === '.') {
      // Avoids an infinite loop in rare cases, like the REPL
      dir = process.cwd()
    }
    if (exists(join(dir, 'package.json')) || exists(join(dir, 'node_modules'))) {
      // Found the 'package.json' file or 'node_modules' dir; we're done
      return dir
    }
    if (prev === dir) {
      // Got to the top
      throw new Error('Could not find module root given file: "' + file
                    + '". Do you have a `package.json` file? ')
    }
    // Try the parent dir next
    prev = dir
    dir = join(dir, '..')
  }
}
<commit_msg>add `path` option to require.resolve instead<commit_after>
/**
 * Module dependencies.
 */

var fs = require('fs')
  , path = require('path')
  , join = path.join
  , dirname = path.dirname
  , exists = fs.existsSync || path.existsSync
  , defaults = {
        arrow: process.env.NODE_BINDINGS_ARROW || ' → '
      , compiled: process.env.NODE_BINDINGS_COMPILED_DIR || 'compiled'
      , platform: process.platform
      , arch: process.arch
      , version: process.versions.node
      , bindings: 'bindings.node'
      , try: [
          // node-gyp's linked version in the "build" dir
          [ 'module_root', 'build', 'bindings' ]
          // node-waf and gyp_addon (a.k.a node-gyp)
        , [ 'module_root', 'build', 'Debug', 'bindings' ]
        , [ 'module_root', 'build', 'Release', 'bindings' ]
          // Debug files, for development (legacy behavior, remove for node v0.9)
        , [ 'module_root', 'out', 'Debug', 'bindings' ]
        , [ 'module_root', 'Debug', 'bindings' ]
          // Release files, but manually compiled (legacy behavior, remove for node v0.9)
        , [ 'module_root', 'out', 'Release', 'bindings' ]
        , [ 'module_root', 'Release', 'bindings' ]
          // Legacy from node-waf, node <= 0.4.x
        , [ 'module_root', 'build', 'default', 'bindings' ]
          // Production "Release" buildtype binary (meh...)
        , [ 'module_root', 'compiled', 'version', 'platform', 'arch', 'bindings' ]
        ]
    }

/**
 * The main `bindings()` function loads the compiled bindings for a given module.
 * It uses V8's Error API to determine the parent filename that this function is
 * being invoked from, which is then used to find the root directory.
 */

function bindings (opts) {

  // Argument surgery
  if (typeof opts == 'string') {
    opts = { bindings: opts }
  } else if (!opts) {
    opts = {}
  }
  opts.__proto__ = defaults

  // Get the module root
  if (!opts.module_root) {
    opts.module_root = exports.getRoot(exports.getFileName())
  }

  // Ensure the given bindings name ends with .node
  if (path.extname(opts.bindings) != '.node') {
    opts.bindings += '.node'
  }

  var tries = []
    , i = 0
    , l = opts.try.length
    , n
    , b
    , err

  for (; i<l; i++) {
    n = join.apply(null, opts.try[i].map(function (p) {
      return opts[p] || p
    }))
    tries.push(n)
    try {
      b = opts.path ? require.resolve(n) : require(n)
      if (!opts.path) {
        b.path = n
      }
      return b
    } catch (e) {
      if (!/not find/i.test(e.message)) {
        throw e
      }
    }
  }

  err = new Error('Could not locate the bindings file. Tried:\n'
    + tries.map(function (a) { return opts.arrow + a }).join('\n'))
  err.tries = tries
  throw err
}
module.exports = exports = bindings

/**
 * Gets the filename of the JavaScript file that invokes this function.
 * Used to help find the root directory of a module.
 */

exports.getFileName = function getFileName () {
  var origPST = Error.prepareStackTrace
    , dummy = {}
    , fileName

  Error.prepareStackTrace = function (e, st) {
    for (var i=0, l=st.length; i<l; i++) {
      fileName = st[i].getFileName()
      if (fileName !== __filename) {
        return
      }
    }
  }

  // run the 'prepareStackTrace' function above
  Error.captureStackTrace(dummy)
  dummy.stack

  // cleanup
  Error.prepareStackTrace = origPST

  return fileName
}

/**
 * Gets the root directory of a module, given an arbitrary filename
 * somewhere in the module tree. The "root directory" is the directory
 * containing the `package.json` file.
 *
 *   In:  /home/nate/node-native-module/lib/index.js
 *   Out: /home/nate/node-native-module
 */

exports.getRoot = function getRoot (file) {
  var dir = dirname(file)
    , prev
  while (true) {
    if (dir === '.') {
      // Avoids an infinite loop in rare cases, like the REPL
      dir = process.cwd()
    }
    if (exists(join(dir, 'package.json')) || exists(join(dir, 'node_modules'))) {
      // Found the 'package.json' file or 'node_modules' dir; we're done
      return dir
    }
    if (prev === dir) {
      // Got to the top
      throw new Error('Could not find module root given file: "' + file
                    + '". Do you have a `package.json` file? ')
    }
    // Try the parent dir next
    prev = dir
    dir = join(dir, '..')
  }
}
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var fs = require('fs')
  , path = require('path')
  , fileURLToPath = require('file-uri-to-path')
  , join = path.join
  , dirname = path.dirname
  , exists = ((fs.accessSync && function (path) { try { fs.accessSync(path); } catch (e) { return false; } return true; })
      || fs.existsSync || path.existsSync)
  , defaults = {
        arrow: process.env.NODE_BINDINGS_ARROW || ' → '
      , compiled: process.env.NODE_BINDINGS_COMPILED_DIR || 'compiled'
      , platform: process.platform
      , arch: process.arch
      , version: process.versions.node
      , bindings: 'bindings.node'
      , try: [
          // node-gyp's linked version in the "build" dir
          [ 'module_root', 'build', 'bindings' ]
          // node-waf and gyp_addon (a.k.a node-gyp)
        , [ 'module_root', 'build', 'Debug', 'bindings' ]
        , [ 'module_root', 'build', 'Release', 'bindings' ]
          // Debug files, for development (legacy behavior, remove for node v0.9)
        , [ 'module_root', 'out', 'Debug', 'bindings' ]
        , [ 'module_root', 'Debug', 'bindings' ]
          // Release files, but manually compiled (legacy behavior, remove for node v0.9)
        , [ 'module_root', 'out', 'Release', 'bindings' ]
        , [ 'module_root', 'Release', 'bindings' ]
          // Legacy from node-waf, node <= 0.4.x
        , [ 'module_root', 'build', 'default', 'bindings' ]
          // Production "Release" buildtype binary (meh...)
        , [ 'module_root', 'compiled', 'version', 'platform', 'arch', 'bindings' ]
          // node-qbs builds
        , [ 'module_root', 'addon-build', 'release', 'install-root', 'bindings' ]
        , [ 'module_root', 'addon-build', 'debug', 'install-root', 'bindings' ]
        , [ 'module_root', 'addon-build', 'default', 'install-root', 'bindings' ]
        ]
    }

/**
 * The main `bindings()` function loads the compiled bindings for a given module.
 * It uses V8's Error API to determine the parent filename that this function is
 * being invoked from, which is then used to find the root directory.
 */

function bindings (opts) {

  // Argument surgery
  if (typeof opts == 'string') {
    opts = { bindings: opts }
  } else if (!opts) {
    opts = {}
  }

  // maps `defaults` onto `opts` object
  Object.keys(defaults).map(function(i) {
    if (!(i in opts)) opts[i] = defaults[i];
  });

  // Get the module root
  if (!opts.module_root) {
    opts.module_root = exports.getRoot(exports.getFileName())
  }

  // Ensure the given bindings name ends with .node
  if (path.extname(opts.bindings) != '.node') {
    opts.bindings += '.node'
  }

  // https://github.com/webpack/webpack/issues/4175#issuecomment-342931035
  var requireFunc = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require

  var tries = []
    , i = 0
    , l = opts.try.length
    , n
    , b
    , err

  for (; i<l; i++) {
    n = join.apply(null, opts.try[i].map(function (p) {
      return opts[p] || p
    }))
    tries.push(n)
    try {
      b = opts.path ? requireFunc.resolve(n) : requireFunc(n)
      if (!opts.path) {
        b.path = n
      }
      return b
    } catch (e) {
      if (!/not find/i.test(e.message)) {
        throw e
      }
    }
  }

  err = new Error('Could not locate the bindings file. Tried:\n'
    + tries.map(function (a) { return opts.arrow + a }).join('\n'))
  err.tries = tries
  throw err
}
module.exports = exports = bindings

/**
 * Gets the filename of the JavaScript file that invokes this function.
 * Used to help find the root directory of a module.
 * Optionally accepts an filename argument to skip when searching for the invoking filename
 */

exports.getFileName = function getFileName (calling_file) {
  var origPST = Error.prepareStackTrace
    , origSTL = Error.stackTraceLimit
    , dummy = {}
    , fileName

  Error.stackTraceLimit = 10

  Error.prepareStackTrace = function (e, st) {
    for (var i=0, l=st.length; i<l; i++) {
      fileName = st[i].getFileName()
      if (fileName !== __filename) {
        if (calling_file) {
            if (fileName !== calling_file) {
              return
            }
        } else {
          return
        }
      }
    }
  }

  // run the 'prepareStackTrace' function above
  Error.captureStackTrace(dummy)
  dummy.stack

  // cleanup
  Error.prepareStackTrace = origPST
  Error.stackTraceLimit = origSTL

  // handle filename that starts with "file://"
  var fileSchema = "file://";
  if (fileName.indexOf(fileSchema) === 0) {
    fileName = fileURLToPath(fileName);
  }

  return fileName
}

/**
 * Gets the root directory of a module, given an arbitrary filename
 * somewhere in the module tree. The "root directory" is the directory
 * containing the `package.json` file.
 *
 *   In:  /home/nate/node-native-module/lib/index.js
 *   Out: /home/nate/node-native-module
 */

exports.getRoot = function getRoot (file) {
  var dir = dirname(file)
    , prev
  while (true) {
    if (dir === '.') {
      // Avoids an infinite loop in rare cases, like the REPL
      dir = process.cwd()
    }
    if (exists(join(dir, 'package.json')) || exists(join(dir, 'node_modules'))) {
      // Found the 'package.json' file or 'node_modules' dir; we're done
      return dir
    }
    if (prev === dir) {
      // Got to the top
      throw new Error('Could not find module root given file: "' + file
                    + '". Do you have a `package.json` file? ')
    }
    // Try the parent dir next
    prev = dir
    dir = join(dir, '..')
  }
}
<commit_msg>Add `node-pre-gyp` path to search paths<commit_after>
/**
 * Module dependencies.
 */

var fs = require('fs')
  , path = require('path')
  , fileURLToPath = require('file-uri-to-path')
  , join = path.join
  , dirname = path.dirname
  , exists = ((fs.accessSync && function (path) { try { fs.accessSync(path); } catch (e) { return false; } return true; })
      || fs.existsSync || path.existsSync)
  , defaults = {
        arrow: process.env.NODE_BINDINGS_ARROW || ' → '
      , compiled: process.env.NODE_BINDINGS_COMPILED_DIR || 'compiled'
      , platform: process.platform
      , arch: process.arch
      , nodePreGyp: 'node-v' + process.versions.modules + '-' + process.platform + '-' + process.arch
      , version: process.versions.node
      , bindings: 'bindings.node'
      , try: [
          // node-gyp's linked version in the "build" dir
          [ 'module_root', 'build', 'bindings' ]
          // node-waf and gyp_addon (a.k.a node-gyp)
        , [ 'module_root', 'build', 'Debug', 'bindings' ]
        , [ 'module_root', 'build', 'Release', 'bindings' ]
          // Debug files, for development (legacy behavior, remove for node v0.9)
        , [ 'module_root', 'out', 'Debug', 'bindings' ]
        , [ 'module_root', 'Debug', 'bindings' ]
          // Release files, but manually compiled (legacy behavior, remove for node v0.9)
        , [ 'module_root', 'out', 'Release', 'bindings' ]
        , [ 'module_root', 'Release', 'bindings' ]
          // Legacy from node-waf, node <= 0.4.x
        , [ 'module_root', 'build', 'default', 'bindings' ]
          // Production "Release" buildtype binary (meh...)
        , [ 'module_root', 'compiled', 'version', 'platform', 'arch', 'bindings' ]
          // node-qbs builds
        , [ 'module_root', 'addon-build', 'release', 'install-root', 'bindings' ]
        , [ 'module_root', 'addon-build', 'debug', 'install-root', 'bindings' ]
        , [ 'module_root', 'addon-build', 'default', 'install-root', 'bindings' ]
          // node-pre-gyp path ./lib/binding/{node_abi}-{platform}-{arch}
        , [ 'module_root', 'lib', 'binding', 'nodePreGyp', 'bindings' ]
        ]
    }

/**
 * The main `bindings()` function loads the compiled bindings for a given module.
 * It uses V8's Error API to determine the parent filename that this function is
 * being invoked from, which is then used to find the root directory.
 */

function bindings (opts) {

  // Argument surgery
  if (typeof opts == 'string') {
    opts = { bindings: opts }
  } else if (!opts) {
    opts = {}
  }

  // maps `defaults` onto `opts` object
  Object.keys(defaults).map(function(i) {
    if (!(i in opts)) opts[i] = defaults[i];
  });

  // Get the module root
  if (!opts.module_root) {
    opts.module_root = exports.getRoot(exports.getFileName())
  }

  // Ensure the given bindings name ends with .node
  if (path.extname(opts.bindings) != '.node') {
    opts.bindings += '.node'
  }

  // https://github.com/webpack/webpack/issues/4175#issuecomment-342931035
  var requireFunc = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require

  var tries = []
    , i = 0
    , l = opts.try.length
    , n
    , b
    , err

  for (; i<l; i++) {
    n = join.apply(null, opts.try[i].map(function (p) {
      return opts[p] || p
    }))
    tries.push(n)
    try {
      b = opts.path ? requireFunc.resolve(n) : requireFunc(n)
      if (!opts.path) {
        b.path = n
      }
      return b
    } catch (e) {
      if (!/not find/i.test(e.message)) {
        throw e
      }
    }
  }

  err = new Error('Could not locate the bindings file. Tried:\n'
    + tries.map(function (a) { return opts.arrow + a }).join('\n'))
  err.tries = tries
  throw err
}
module.exports = exports = bindings

/**
 * Gets the filename of the JavaScript file that invokes this function.
 * Used to help find the root directory of a module.
 * Optionally accepts an filename argument to skip when searching for the invoking filename
 */

exports.getFileName = function getFileName (calling_file) {
  var origPST = Error.prepareStackTrace
    , origSTL = Error.stackTraceLimit
    , dummy = {}
    , fileName

  Error.stackTraceLimit = 10

  Error.prepareStackTrace = function (e, st) {
    for (var i=0, l=st.length; i<l; i++) {
      fileName = st[i].getFileName()
      if (fileName !== __filename) {
        if (calling_file) {
            if (fileName !== calling_file) {
              return
            }
        } else {
          return
        }
      }
    }
  }

  // run the 'prepareStackTrace' function above
  Error.captureStackTrace(dummy)
  dummy.stack

  // cleanup
  Error.prepareStackTrace = origPST
  Error.stackTraceLimit = origSTL

  // handle filename that starts with "file://"
  var fileSchema = "file://";
  if (fileName.indexOf(fileSchema) === 0) {
    fileName = fileURLToPath(fileName);
  }

  return fileName
}

/**
 * Gets the root directory of a module, given an arbitrary filename
 * somewhere in the module tree. The "root directory" is the directory
 * containing the `package.json` file.
 *
 *   In:  /home/nate/node-native-module/lib/index.js
 *   Out: /home/nate/node-native-module
 */

exports.getRoot = function getRoot (file) {
  var dir = dirname(file)
    , prev
  while (true) {
    if (dir === '.') {
      // Avoids an infinite loop in rare cases, like the REPL
      dir = process.cwd()
    }
    if (exists(join(dir, 'package.json')) || exists(join(dir, 'node_modules'))) {
      // Found the 'package.json' file or 'node_modules' dir; we're done
      return dir
    }
    if (prev === dir) {
      // Got to the top
      throw new Error('Could not find module root given file: "' + file
                    + '". Do you have a `package.json` file? ')
    }
    // Try the parent dir next
    prev = dir
    dir = join(dir, '..')
  }
}
<|endoftext|>


<commit_before>var _ = require('lodash');
var Promise = require('bluebird');
var Client = require('bitfinex');
var util = require('util');

module.exports = function(conf, trader){
    _.extend(this, conf);
    var self = this;

    var initDeferred = Promise.defer();
    this.initialized = initDeferred.promise;

    this.client = new Client(this.key, this.secret);
    ['orderbook', 'new_order', 'order_status' /*, 'wallet_balances'*/].forEach(function(command){
        self.client[command] = Promise.promisify(self.client[command]);
    })
    this.spreadAdapter = function(indata){
        var outdata = {
            exchange : 'bitfinex',
            bids : [],
            asks : []
        };

        var bids = indata.bids;
        var asks  = indata.asks;

        for (var i = 0; i < 5; i++) {
            outdata.bids.push([bids[i].price, bids[i].amount]);
            outdata.asks.push([asks[i].price, asks[i].amount]);
        };
        return outdata;
    };

    this.getSpread = function(currency){ // only USD ATM.
        return self.client.orderbook('btcusd').then(function(response){
            var data = self.spreadAdapter(response);
            _.extend(data, {exchange: 'bitfinex', currency: currency});
            trader.emit('spread_data', data);
            return data;
        });
    }

    this.getBalance = function(){

        // keeping this function intact in case I forget how deferreds work ;) / SK. 21 mars
        var deferred = Promise.defer();

        self.client.wallet_balances(function(error, data) {
            if(error) {
                console.error(error);
                return deferred.reject(error);
            }

            self.balance = {
                'USD' : parseFloat(_.find(data, {type: 'exchange', currency :'usd'}).available),
                'BTC' : parseFloat(_.find(data, {type: 'exchange', currency :'btc'}).available)
            };
            console.log('bitfinex.balance: ', self.balance);
            if(_.isNaN(self.balance.USD) || _.isNaN(self.balance.BTC)){
                deferred.reject('Bitfinex balance isNaN');
            }
            deferred.resolve(self.balance);
        });

        return deferred.promise;
    }
    this.tradeCommand = function(options){
        console.log('executing bitfinex trade: ', options);

        return this.client.new_order('btcusd', options.volume, options.price, 'all', options.buySell.toLowerCase(), 'limit').then(function(response){
            console.log('add order sent: ', response);
            return response;
        });
    }
    this.trade = function(options){
        var tradeResolver = Promise.defer();

        var neededOptions = ['currency', 'buySell', 'price', 'volume'];
        for (var i = neededOptions.length - 1; i >= 0; i--) {
            if(!_.has(options, neededOptions[i])){
                return tradeResolver.throw('Input data error').promise;
            }
        };

        this.tradeCommand(options).then(function(response){
            var id = response.order_id;
            var i = 0;

            console.log('bitfinex order id: ', id);

            function tradeChecker(response){
                if(tradeResolver.promise.isResolved()){ return ; } // quit the loop

                if(response.remaining_amount == 0){
                    console.log('order is completed!');
                    tradeResolver.resolve(response);
                    return true;
                } else if (response.is_cancelled){
                    console.log('order is cancelled!');
                    tradeResolver.reject(response);
                    return false;
                } else if(response.is_live){
                    console.log('order ', id, 'is still running, iteration', i++);
                    Promise.delay(1000).then(function(){
                        return self.client.order_status(id); // here is where the request happens
                    }).then(tradeChecker); // keep looping this baby
                } else {
                    throw new Error('Unclear bitfinex trade situation: ', response);
                }
            }
            tradeChecker(response); // verify original response
        });

        return tradeResolver.promise;
    };

    this.getBalance().then(function(){
        initDeferred.resolve();
    });

}
<commit_msg>Add cancel func to bitfinex.<commit_after>var _ = require('lodash');
var Promise = require('bluebird');
var Client = require('bitfinex');
var util = require('util');

module.exports = function(conf, trader){
    _.extend(this, conf);
    var self = this;

    var initDeferred = Promise.defer();
    this.initialized = initDeferred.promise;

    this.client = new Client(this.key, this.secret);
    ['orderbook', 'new_order', 'order_status', 'cancel_order' /*, 'wallet_balances'*/].forEach(function(command){
        self.client[command] = Promise.promisify(self.client[command]);
    })
    this.spreadAdapter = function(indata){
        var outdata = {
            exchange : 'bitfinex',
            bids : [],
            asks : []
        };

        var bids = indata.bids;
        var asks  = indata.asks;

        for (var i = 0; i < 5; i++) {
            outdata.bids.push([bids[i].price, bids[i].amount]);
            outdata.asks.push([asks[i].price, asks[i].amount]);
        };
        return outdata;
    };

    this.getSpread = function(currency){ // only USD ATM.
        return self.client.orderbook('btcusd').then(function(response){
            var data = self.spreadAdapter(response);
            _.extend(data, {exchange: 'bitfinex', currency: currency});
            trader.emit('spread_data', data);
            return data;
        });
    }

    this.getBalance = function(){

        // keeping this function intact in case I forget how deferreds work ;) / SK. 21 mars
        var deferred = Promise.defer();

        self.client.wallet_balances(function(error, data) {
            if(error) {
                console.error(error);
                return deferred.reject(error);
            }

            self.balance = {
                'USD' : parseFloat(_.find(data, {type: 'exchange', currency :'usd'}).available),
                'BTC' : parseFloat(_.find(data, {type: 'exchange', currency :'btc'}).available)
            };
            console.log('bitfinex.balance: ', self.balance);
            if(_.isNaN(self.balance.USD) || _.isNaN(self.balance.BTC)){
                deferred.reject('Bitfinex balance isNaN');
            }
            deferred.resolve(self.balance);
        });

        return deferred.promise;
    }
    this.cancel = function(id){
        return this.client.cancel_order(id);
    };

    this.tradeCommand = function(options){
        console.log('executing bitfinex trade: ', options);

        return this.client.new_order('btcusd', options.volume, options.price, 'all', options.buySell.toLowerCase(), 'limit').then(function(response){
            console.log('add order sent: ', response);
            return response;
        });
    }
    this.trade = function(options){
        var tradeResolver = Promise.defer();

        var neededOptions = ['currency', 'buySell', 'price', 'volume'];
        for (var i = neededOptions.length - 1; i >= 0; i--) {
            if(!_.has(options, neededOptions[i])){
                return tradeResolver.throw('Input data error').promise;
            }
        };

        this.tradeCommand(options).then(function(response){
            var id = response.order_id;
            var i = 0;

            console.log('bitfinex order id: ', id);

            function tradeChecker(response){
                if(tradeResolver.promise.isResolved()){ return ; } // quit the loop

                if(response.remaining_amount == 0){
                    console.log('order is completed!');
                    tradeResolver.resolve(response);
                    return true;
                } else if (response.is_cancelled){
                    console.log('order is cancelled!');
                    tradeResolver.reject(response);
                    return false;
                } else if(response.is_live){
                    console.log('order ', id, 'is still running, iteration', i++);
                    Promise.delay(1000).then(function(){
                        return self.client.order_status(id); // here is where the request happens
                    }).then(tradeChecker); // keep looping this baby
                } else {
                    throw new Error('Unclear bitfinex trade situation: ', response);
                }
            }
            tradeChecker(response); // verify original response
        });

        return tradeResolver.promise;
    };

    this.getBalance().then(function(){
        initDeferred.resolve();
    });

}
<|endoftext|>


<commit_before>describe('iD.actionFlip', function() {

     it('flips horizontally - does not change graph length', function () {
        var graph = iD.Graph([
                iD.Node({id: 'a', loc: [0, 0]}),
                iD.Node({id: 'b', loc: [2, 0]}),
                iD.Node({id: 'c', loc: [2, 2]}),
                iD.Node({id: 'd', loc: [0, 2]}),
                iD.Way({id: '-', nodes: ['a', 'b', 'c', 'd', 'a'], tags: { area: 'yes'}})
            ]);

        graph = iD.actionFlip('-', false)(graph);

        expect(graph.entity('-').nodes).to.have.length(5);
     });

     it('flips horizontally - alters x value', function () {
        var graph = iD.Graph([
                iD.Node({id: 'a', loc: [0, 0]}),
                iD.Node({id: 'b', loc: [2, 0]}),
                iD.Node({id: 'c', loc: [2, 2]}),
                iD.Node({id: 'd', loc: [0, 2]}),
                iD.Way({id: '-', nodes: ['a', 'b', 'c', 'd', 'a'], tags: { area: 'yes'}})
            ]);
        graph = iD.actionFlip('-', false)(graph);
        expect(graph.entity('a').loc[0]).to.equal(2); // A should be 2,0 now
        expect(graph.entity('b').loc[0]).to.equal(0); // B should be 0,0 now
        expect(graph.entity('c').loc[0]).to.equal(0); // C should be 0,2 now
        expect(graph.entity('d').loc[0]).to.equal(2); // D should be 2,2 now
    });

     it('flips horizontally - does not alter y value', function () {
        var graph = iD.Graph([
                iD.Node({id: 'a', loc: [0, 0]}),
                iD.Node({id: 'b', loc: [2, 0]}),
                iD.Node({id: 'c', loc: [2, 2]}),
                iD.Node({id: 'd', loc: [0, 2]}),
                iD.Way({id: '-', nodes: ['a', 'b', 'c', 'd', 'a'], tags: { area: 'yes'}})
            ]);
        graph = iD.actionFlip('-', false)(graph);
        expect(graph.entity('a').loc[1]).to.equal(0); // A should be 2,0 now
        expect(graph.entity('b').loc[1]).to.equal(0); // B should be 0,0 now
        expect(graph.entity('c').loc[1]).to.equal(2); // C should be 0,2 now
        expect(graph.entity('d').loc[1]).to.equal(2); // D should be 2,2 now
    });

     it('flips vertically - alters y value', function () {
        var graph = iD.Graph([
                iD.Node({id: 'a', loc: [0, 0]}),
                iD.Node({id: 'b', loc: [2, 0]}),
                iD.Node({id: 'c', loc: [2, 2]}),
                iD.Node({id: 'd', loc: [0, 2]}),
                iD.Way({id: '-', nodes: ['a', 'b', 'c', 'd', 'a'], tags: { area: 'yes'}})
            ]);
        graph = iD.actionFlip('-', true)(graph);
        expect(graph.entity('a').loc[1]).to.equal(2); // A should be 0,2 now
        expect(graph.entity('b').loc[1]).to.equal(2); // B should be 2,2 now
        expect(graph.entity('c').loc[1]).to.equal(0); // C should be 2,0 now
        expect(graph.entity('d').loc[1]).to.equal(0); // D should be 0,0 now
    });

     it('flips vertically - does not alter x value', function () {
        var graph = iD.Graph([
                iD.Node({id: 'a', loc: [0, 0]}),
                iD.Node({id: 'b', loc: [2, 0]}),
                iD.Node({id: 'c', loc: [2, 2]}),
                iD.Node({id: 'd', loc: [0, 2]}),
                iD.Way({id: '-', nodes: ['a', 'b', 'c', 'd', 'a'], tags: { area: 'yes'}})
            ]);
        graph = iD.actionFlip('-', true)(graph);
        expect(graph.entity('a').loc[0]).to.equal(0); // A should be 0,2 now
        expect(graph.entity('b').loc[0]).to.equal(2); // B should be 2,2 now
        expect(graph.entity('c').loc[0]).to.equal(2); // C should be 2,0 now
        expect(graph.entity('d').loc[0]).to.equal(0); // D should be 0,0 now
    });
});
<commit_msg>More tests<commit_after>describe('iD.actionFlip', function() {

     it('flips horizontally - does not change graph length', function () {
        var graph = iD.Graph([
                iD.Node({id: 'a', loc: [0, 0]}),
                iD.Node({id: 'b', loc: [2, 0]}),
                iD.Node({id: 'c', loc: [2, 2]}),
                iD.Node({id: 'd', loc: [0, 2]}),
                iD.Way({id: '-', nodes: ['a', 'b', 'c', 'd', 'a'], tags: { area: 'yes'}})
            ]);

        graph = iD.actionFlip('-', false)(graph);

        expect(graph.entity('-').nodes).to.have.length(5);
     });

     it('flips horizontally - alters x value', function () {
        var graph = iD.Graph([
                iD.Node({id: 'a', loc: [0, 0]}),
                iD.Node({id: 'b', loc: [2, 0]}),
                iD.Node({id: 'c', loc: [2, 2]}),
                iD.Node({id: 'd', loc: [0, 2]}),
                iD.Way({id: '-', nodes: ['a', 'b', 'c', 'd', 'a'], tags: { area: 'yes'}})
            ]);
        graph = iD.actionFlip('-', false)(graph);
        expect(graph.entity('a').loc[0]).to.equal(2); // A should be 2,0 now
        expect(graph.entity('b').loc[0]).to.equal(0); // B should be 0,0 now
        expect(graph.entity('c').loc[0]).to.equal(0); // C should be 0,2 now
        expect(graph.entity('d').loc[0]).to.equal(2); // D should be 2,2 now
    });

     it('flips horizontally - does not alter y value', function () {
        var graph = iD.Graph([
                iD.Node({id: 'a', loc: [0, 0]}),
                iD.Node({id: 'b', loc: [2, 0]}),
                iD.Node({id: 'c', loc: [2, 2]}),
                iD.Node({id: 'd', loc: [0, 2]}),
                iD.Way({id: '-', nodes: ['a', 'b', 'c', 'd', 'a'], tags: { area: 'yes'}})
            ]);
        graph = iD.actionFlip('-', false)(graph);
        expect(graph.entity('a').loc[1]).to.equal(0); // A should be 2,0 now
        expect(graph.entity('b').loc[1]).to.equal(0); // B should be 0,0 now
        expect(graph.entity('c').loc[1]).to.equal(2); // C should be 0,2 now
        expect(graph.entity('d').loc[1]).to.equal(2); // D should be 2,2 now
    });

     it('flips vertically - alters y value', function () {
        var graph = iD.Graph([
                iD.Node({id: 'a', loc: [0, 0]}),
                iD.Node({id: 'b', loc: [2, 0]}),
                iD.Node({id: 'c', loc: [2, 2]}),
                iD.Node({id: 'd', loc: [0, 2]}),
                iD.Way({id: '-', nodes: ['a', 'b', 'c', 'd', 'a'], tags: { area: 'yes'}})
            ]);
        graph = iD.actionFlip('-', true)(graph);
        expect(graph.entity('a').loc[1]).to.equal(2); // A should be 0,2 now
        expect(graph.entity('b').loc[1]).to.equal(2); // B should be 2,2 now
        expect(graph.entity('c').loc[1]).to.equal(0); // C should be 2,0 now
        expect(graph.entity('d').loc[1]).to.equal(0); // D should be 0,0 now
    });

     it('flips vertically - does not alter x value', function () {
        var graph = iD.Graph([
                iD.Node({id: 'a', loc: [0, 0]}),
                iD.Node({id: 'b', loc: [2, 0]}),
                iD.Node({id: 'c', loc: [2, 2]}),
                iD.Node({id: 'd', loc: [0, 2]}),
                iD.Way({id: '-', nodes: ['a', 'b', 'c', 'd', 'a'], tags: { area: 'yes'}})
            ]);
        graph = iD.actionFlip('-', true)(graph);
        expect(graph.entity('a').loc[0]).to.equal(0); // A should be 0,2 now
        expect(graph.entity('b').loc[0]).to.equal(2); // B should be 2,2 now
        expect(graph.entity('c').loc[0]).to.equal(2); // C should be 2,0 now
        expect(graph.entity('d').loc[0]).to.equal(0); // D should be 0,0 now
    });

    it('does not flip horizontally if not an area - does not alter x value', function () {
        var graph = iD.Graph([
                iD.Node({id: 'a', loc: [0, 0]}),
                iD.Node({id: 'b', loc: [2, 0]}),
                iD.Node({id: 'c', loc: [2, 2]}),
                iD.Node({id: 'd', loc: [0, 2]}),
                iD.Way({id: '-', nodes: ['a', 'b', 'c', 'd', 'a']})
            ]);
        graph = iD.actionFlip('-', false)(graph);
        // should be no change
        expect(graph.entity('a').loc[0]).to.equal(0);
        expect(graph.entity('b').loc[0]).to.equal(2);
        expect(graph.entity('c').loc[0]).to.equal(2);
        expect(graph.entity('d').loc[0]).to.equal(0);
    });

     it('does not flip horizontally if not an area - does not alter y value', function () {
        var graph = iD.Graph([
                iD.Node({id: 'a', loc: [0, 0]}),
                iD.Node({id: 'b', loc: [2, 0]}),
                iD.Node({id: 'c', loc: [2, 2]}),
                iD.Node({id: 'd', loc: [0, 2]}),
                iD.Way({id: '-', nodes: ['a', 'b', 'c', 'd', 'a']})
            ]);
        graph = iD.actionFlip('-', false)(graph);
        // should be no change
        expect(graph.entity('a').loc[1]).to.equal(0);
        expect(graph.entity('b').loc[1]).to.equal(0);
        expect(graph.entity('c').loc[1]).to.equal(2);
        expect(graph.entity('d').loc[1]).to.equal(2);
    });

    it('does not flip vertically if not an area - does not alter x value', function () {
        var graph = iD.Graph([
                iD.Node({id: 'a', loc: [0, 0]}),
                iD.Node({id: 'b', loc: [2, 0]}),
                iD.Node({id: 'c', loc: [2, 2]}),
                iD.Node({id: 'd', loc: [0, 2]}),
                iD.Way({id: '-', nodes: ['a', 'b', 'c', 'd', 'a']})
            ]);
        graph = iD.actionFlip('-', true)(graph);
        // should be no change
        expect(graph.entity('a').loc[0]).to.equal(0);
        expect(graph.entity('b').loc[0]).to.equal(2);
        expect(graph.entity('c').loc[0]).to.equal(2);
        expect(graph.entity('d').loc[0]).to.equal(0);
    });

    it('does not flip vertically if not an area - does not alter y value', function () {
        var graph = iD.Graph([
                iD.Node({id: 'a', loc: [0, 0]}),
                iD.Node({id: 'b', loc: [2, 0]}),
                iD.Node({id: 'c', loc: [2, 2]}),
                iD.Node({id: 'd', loc: [0, 2]}),
                iD.Way({id: '-', nodes: ['a', 'b', 'c', 'd', 'a']})
            ]);
        graph = iD.actionFlip('-', true)(graph);
        // should be no change
        expect(graph.entity('a').loc[1]).to.equal(0);
        expect(graph.entity('b').loc[1]).to.equal(0);
        expect(graph.entity('c').loc[1]).to.equal(2);
        expect(graph.entity('d').loc[1]).to.equal(2);
    });
});
<|endoftext|>


<commit_before>'use strict';

var innie       = require('../../src/innie');
var utils       = require('../../src/utils');
var patterns    = require('./test-patterns/markup.js');
var expect      = require('chai').expect;

describe('Create html file: create-html-file.js', function() {

});

describe('Create html node: create-html-node.js', function() {

    it('Should return a string', function(){

        expect( utils.createHtmlNode( patterns.htmlNodeToken() ) )
            .to.be.a('string');

    });

    it('Should be matching', function(){

        expect( utils.createHtmlNode( patterns.htmlNodeToken() ) )
            .to.be.a('string')
            .to.eql( patterns.htmlNodeTokenExpected() );

    });
});

describe('Create react node: create-react-node.js', function() {

    it('Should return a string', function(){

        expect( utils.createReactNode( patterns.reactNodeToken() ) )
            .to.be.a('string');

    });

    it('Should be matching', function(){

        expect( utils.createReactNode( patterns.reactNodeToken() ) )
            .to.be.a('string')
            .to.eql( patterns.reactNodeTokenExpected() );

    });
});

describe('Split React File: split-react.js', function() {

    it('Should return an array', function(){

        expect( utils.splitReact( patterns.reactFile() ) )
            .to.be.an('array');

    });

    it('Should be matching', function(){

        expect( utils.splitReact( patterns.reactFile() ) )
            .to.be.an('array')
            .to.eql( patterns.reactSplitFileExpected() );

    });
});
<commit_msg>cleaned up the test<commit_after>'use strict';

var innie       = require('../../src/innie');
var utils       = require('../../src/utils');
var patterns    = require('./test-patterns/markup.js');
var expect      = require('chai').expect;

describe('Create html file: create-html-file.js', function() {

});

describe('Create html node: create-html-node.js', function() {

    it('Should return a string', function(){

        expect( utils.markup.createHtmlNode( patterns.htmlNodeToken() ) )
            .to.be.a('string');

    });

    it('Should be matching', function(){

        expect( utils.markup.createHtmlNode( patterns.htmlNodeToken() ) )
            .to.be.a('string')
            .to.eql( patterns.htmlNodeTokenExpected() );

    });
});

describe('Create react node: create-react-node.js', function() {

    it('Should return a string', function(){

        expect( utils.markup.createReactNode( patterns.reactNodeToken() ) )
            .to.be.a('string');

    });

    it('Should be matching', function(){

        expect( utils.markup.createReactNode( patterns.reactNodeToken() ) )
            .to.be.a('string')
            .to.eql( patterns.reactNodeTokenExpected() );

    });
});

describe('Split React File: split-react.js', function() {

    it('Should return an array', function(){

        expect( utils.markup.splitReact( patterns.reactFile() ) )
            .to.be.an('array');

    });

    it('Should be matching', function(){

        expect( utils.markup.splitReact( patterns.reactFile() ) )
            .to.be.an('array')
            .to.eql( patterns.reactSplitFileExpected() );

    });
});
<|endoftext|>