<commit_before>'use strict';

var Lab = require('lab');
var lab = exports.lab = Lab.script();
var describe = lab.describe;
var it = lab.it;
var afterEach = lab.afterEach;
var beforeEach = lab.beforeEach;
var Code = require('code');
var expect = Code.expect;
var sinon = require('sinon');

var Hermes = require('../../index');
var connectionOpts = require('../fixtures/connection-opts');
var amqplib = require('amqplib/callback_api');

describe('index.js unit test', function () {
  describe('connect', function () {
    var testHermes;
    beforeEach(function (done) {
      sinon.stub(amqplib, 'connect');
      sinon.stub(Hermes.prototype, '_createChannel');
      testHermes = Hermes.hermesSingletonFactory(connectionOpts.standard);
      done();
    });

    afterEach(function (done) {
      amqplib.connect.restore();
      Hermes.prototype._createChannel.restore();
      done();
    });

    it('should call _createChannel and setup error', function (done) {
      var stubOn = sinon.stub();
      amqplib.connect.yieldsAsync(null, {
        on: stubOn
      });
      Hermes.prototype._createChannel.yieldsAsync();

      testHermes.connect(function (err) {
        expect(err).to.not.exist();
        expect(Hermes.prototype._createChannel.called).to.be.true();
        expect(stubOn.withArgs('error').called).to.be.true();
        expect(testHermes._eventJobs).to.exist();
        done();
      });
    });
  }); // end connect

  describe('_createChannel', function () {
    var testHermes;
    beforeEach(function (done) {
      testHermes = Hermes.hermesSingletonFactory(connectionOpts.standard);
      testHermes._connection = {
        createChannel: sinon.stub()
      };
      sinon.stub(Hermes.prototype, '_populateChannel');
      done();
    });

    afterEach(function (done) {
      Hermes.prototype._populateChannel.restore();
      done();
    });

    it('should call _populateChannel and setup error', function (done) {
      var stubOn = sinon.stub();
      testHermes._connection.createChannel.yieldsAsync(null, {
        on: stubOn
      });
      Hermes.prototype._populateChannel.yieldsAsync();

      testHermes._createChannel(function (err) {
        expect(err).to.not.exist();
        expect(Hermes.prototype._populateChannel.called).to.be.true();
        expect(stubOn.withArgs('error').called).to.be.true();
        done();
      });
    });
  }); // end _createChannel

  describe('_assertQueue', function () {
    var testHermes;
    beforeEach(function (done) {
      testHermes = Hermes.hermesSingletonFactory(connectionOpts.standard)
      testHermes._channel = {
        assertQueue: function () {}
      }
      sinon.stub(testHermes._channel, 'assertQueue').yieldsAsync()
      done()
    })

    it('should work when queueDef was passed', function (done) {
      var queDef = {
        name: 'expiring-queue',
        opts: {
          expires: 10
        }
      }
      testHermes._assertQueue(queDef, function (err) {
        expect(err).to.not.exist()
        sinon.assert.calledOnce(testHermes._channel.assertQueue)
        sinon.assert.calledWith(
          testHermes._channel.assertQueue,
          'expiring-queue',
          { expires: 10 },
          sinon.match.func)
        done()
      })
    })

    it('should be able to override durable param', function (done) {
      var queDef = {
        name: 'expiring-queue',
        opts: {
          expires: 10,
          durable: false
        }
      }
      testHermes._assertQueue(queDef, function (err) {
        expect(err).to.not.exist()
        sinon.assert.calledOnce(testHermes._channel.assertQueue)
        sinon.assert.calledWith(
          testHermes._channel.assertQueue,
          'expiring-queue',
          { durable: false, expires: 10 },
          sinon.match.func)
        done()
      })
    })
  })

  describe('_populateChannel', function () {
    var testHermes;
    beforeEach(function (done) {
      testHermes = Hermes.hermesSingletonFactory(connectionOpts.standard);
      testHermes._channel = {
        assertQueue: sinon.stub()
      };
      testHermes._eventJobs = {
        assertAndBindQueues: sinon.stub(),
        assertExchanges: sinon.stub()
      };
      testHermes.emit = sinon.stub();
      done();
    });

    it('should add all queues and exchanges', function (done) {
      testHermes._channel.assertQueue.yieldsAsync();
      testHermes._eventJobs.assertAndBindQueues.yieldsAsync();
      testHermes._eventJobs.assertExchanges.yieldsAsync();
      testHermes.emit.returns();

      testHermes._populateChannel(function (err) {
        expect(err).to.not.exist();
        expect(testHermes._channel.assertQueue.called).to.be.true();
        expect(testHermes._eventJobs.assertAndBindQueues.called).to.be.true();
        expect(testHermes._eventJobs.assertExchanges.called).to.be.true();
        expect(testHermes.emit.withArgs('ready').called).to.be.true();
        done();
      });
    });

    it('should cb err if assertExchanges failed', function (done) {
      testHermes._channel.assertQueue.yieldsAsync();
      testHermes._eventJobs.assertExchanges.yieldsAsync();
      testHermes._eventJobs.assertAndBindQueues.yieldsAsync('err');

      testHermes._populateChannel(function (err) {
        expect(err).to.exist();
        expect(testHermes._channel.assertQueue.called).to.be.true();
        expect(testHermes._eventJobs.assertExchanges.called).to.be.true();
        expect(testHermes._eventJobs.assertAndBindQueues.called).to.be.true();
        expect(testHermes.emit.withArgs('ready').called).to.be.false();
        done();
      });
    });

    it('should cb err if assertAndBindQueues failed', function (done) {
      testHermes._channel.assertQueue.yieldsAsync();
      testHermes._eventJobs.assertExchanges.yieldsAsync('err');

      testHermes._populateChannel(function (err) {
        expect(err).to.exist();
        expect(testHermes._channel.assertQueue.called).to.be.true();
        expect(testHermes._eventJobs.assertExchanges.called).to.be.true();
        expect(testHermes._eventJobs.assertAndBindQueues.called).to.be.false();
        expect(testHermes.emit.withArgs('ready').called).to.be.false();
        done();
      });
    });

    it('should cb err if assertQueue failed', function (done) {
      testHermes._channel.assertQueue.yieldsAsync('err');

      testHermes._populateChannel(function (err) {
        expect(err).to.exist();
        expect(testHermes._channel.assertQueue.called).to.be.true();
        expect(testHermes._eventJobs.assertExchanges.called).to.be.false();
        expect(testHermes._eventJobs.assertAndBindQueues.called).to.be.false();
        expect(testHermes.emit.withArgs('ready').called).to.be.false();
        done();
      });
    });
  }); // end _populateChannel
  describe('_normalizeQueue', function () {
    it('should return queueDef if name is provided', function (done) {
      var def = Hermes._normalizeQueue('some.queue')
      expect(def).to.deep.equal({ name: 'some.queue', opts: { durable: true }})
      done()
    })
    it('should return queueDef if queueDef is provided', function (done) {
      var def = Hermes._normalizeQueue({ name: 'some.queue' })
      expect(def).to.deep.equal({ name: 'some.queue', opts: { durable: true }})
      done()
    })
    it('should apply additional options', function (done) {
      var def = Hermes._normalizeQueue({ name: 'some.queue', opts: { expires: 2 }})
      expect(def).to.deep.equal({ name: 'some.queue', opts: { durable: true, expires: 2 }})
      done()
    })
    it('should be able to override default options', function (done) {
      var def = Hermes._normalizeQueue({ name: 'some.queue', opts: { expires: 2, durable: false }})
      expect(def).to.deep.equal({ name: 'some.queue', opts: { durable: false, expires: 2 }})
      done()
    })
    describe('use process.env.HERMES_QUEUE_EXPIRES', function () {
      beforeEach(function (done) {
        process.env.HERMES_QUEUE_EXPIRES = 3
        done()
      })
      afterEach(function (done) {
        delete process.env.HERMES_QUEUE_EXPIRES
        done()
      })
      it('should return queueDef if name is provided and use default expires', function (done) {
        var def = Hermes._normalizeQueue('some.queue')
        expect(def).to.deep.equal({ name: 'some.queue', opts: { durable: true, expires: 3 }})
        done()
      })
      it('should return queueDef if queueDef is provided and use default expire', function (done) {
        var def = Hermes._normalizeQueue({ name: 'some.queue' })
        expect(def).to.deep.equal({ name: 'some.queue', opts: { durable: true, expires: 3 }})
        done()
      })
      it('should not override per queue expires with default one', function (done) {
        var def = Hermes._normalizeQueue({ name: 'some.queue', opts: { expires: 20 }})
        expect(def).to.deep.equal({ name: 'some.queue', opts: { durable: true, expires: 20 }})
        done()
      })
    })
  })
});
<commit_msg>updates<commit_after>'use strict';

var Lab = require('lab');
var lab = exports.lab = Lab.script();
var describe = lab.describe;
var it = lab.it;
var afterEach = lab.afterEach;
var beforeEach = lab.beforeEach;
var Code = require('code');
var expect = Code.expect;
var sinon = require('sinon');

var Hermes = require('../../index');
var connectionOpts = require('../fixtures/connection-opts');
var amqplib = require('amqplib/callback_api');

describe('index.js unit test', function () {
  describe('connect', function () {
    var testHermes;
    beforeEach(function (done) {
      sinon.stub(amqplib, 'connect');
      sinon.stub(Hermes.prototype, '_createChannel');
      testHermes = Hermes.hermesSingletonFactory(connectionOpts.standard);
      done();
    });

    afterEach(function (done) {
      amqplib.connect.restore();
      Hermes.prototype._createChannel.restore();
      done();
    });

    it('should call _createChannel and setup error', function (done) {
      var stubOn = sinon.stub();
      amqplib.connect.yieldsAsync(null, {
        on: stubOn
      });
      Hermes.prototype._createChannel.yieldsAsync();

      testHermes.connect(function (err) {
        expect(err).to.not.exist();
        expect(Hermes.prototype._createChannel.called).to.be.true();
        expect(stubOn.withArgs('error').called).to.be.true();
        expect(testHermes._eventJobs).to.exist();
        done();
      });
    });
  }); // end connect

  describe('_createChannel', function () {
    var testHermes;
    beforeEach(function (done) {
      testHermes = Hermes.hermesSingletonFactory(connectionOpts.standard);
      testHermes._connection = {
        createChannel: sinon.stub()
      };
      sinon.stub(Hermes.prototype, '_populateChannel');
      done();
    });

    afterEach(function (done) {
      Hermes.prototype._populateChannel.restore();
      done();
    });

    it('should call _populateChannel and setup error', function (done) {
      var stubOn = sinon.stub();
      testHermes._connection.createChannel.yieldsAsync(null, {
        on: stubOn
      });
      Hermes.prototype._populateChannel.yieldsAsync();

      testHermes._createChannel(function (err) {
        expect(err).to.not.exist();
        expect(Hermes.prototype._populateChannel.called).to.be.true();
        expect(stubOn.withArgs('error').called).to.be.true();
        done();
      });
    });
  }); // end _createChannel

  describe('_assertQueue', function () {
    var testHermes;
    beforeEach(function (done) {
      testHermes = Hermes.hermesSingletonFactory(connectionOpts.standard)
      testHermes._channel = {
        assertQueue: function () {}
      }
      sinon.stub(testHermes._channel, 'assertQueue').yieldsAsync()
      done()
    })

    it('should work when queueDef was passed', function (done) {
      var queDef = {
        name: 'expiring-queue',
        opts: {
          expires: 10
        }
      }
      testHermes._assertQueue(queDef, function (err) {
        expect(err).to.not.exist()
        sinon.assert.calledOnce(testHermes._channel.assertQueue)
        sinon.assert.calledWith(
          testHermes._channel.assertQueue,
          'expiring-queue',
          { expires: 10 },
          sinon.match.func)
        done()
      })
    })

    it('should be able to override durable param', function (done) {
      var queDef = {
        name: 'expiring-queue',
        opts: {
          expires: 10,
          durable: false
        }
      }
      testHermes._assertQueue(queDef, function (err) {
        expect(err).to.not.exist()
        sinon.assert.calledOnce(testHermes._channel.assertQueue)
        sinon.assert.calledWith(
          testHermes._channel.assertQueue,
          'expiring-queue',
          { durable: false, expires: 10 },
          sinon.match.func)
        done()
      })
    })
  })

  describe('_populateChannel', function () {
    var testHermes;
    beforeEach(function (done) {
      testHermes = Hermes.hermesSingletonFactory(connectionOpts.standard);
      testHermes._channel = {
        assertQueue: sinon.stub()
      };
      testHermes._eventJobs = {
        assertAndBindQueues: sinon.stub(),
        assertExchanges: sinon.stub()
      };
      testHermes.emit = sinon.stub();
      done();
    });

    it('should add all queues and exchanges', function (done) {
      testHermes._channel.assertQueue.yieldsAsync();
      testHermes._eventJobs.assertAndBindQueues.yieldsAsync();
      testHermes._eventJobs.assertExchanges.yieldsAsync();
      testHermes.emit.returns();

      testHermes._populateChannel(function (err) {
        expect(err).to.not.exist();
        expect(testHermes._channel.assertQueue.called).to.be.true();
        expect(testHermes._eventJobs.assertAndBindQueues.called).to.be.true();
        expect(testHermes._eventJobs.assertExchanges.called).to.be.true();
        expect(testHermes.emit.withArgs('ready').called).to.be.true();
        done();
      });
    });

    it('should cb err if assertExchanges failed', function (done) {
      testHermes._channel.assertQueue.yieldsAsync();
      testHermes._eventJobs.assertExchanges.yieldsAsync();
      testHermes._eventJobs.assertAndBindQueues.yieldsAsync('err');

      testHermes._populateChannel(function (err) {
        expect(err).to.exist();
        expect(testHermes._channel.assertQueue.called).to.be.true();
        expect(testHermes._eventJobs.assertExchanges.called).to.be.true();
        expect(testHermes._eventJobs.assertAndBindQueues.called).to.be.true();
        expect(testHermes.emit.withArgs('ready').called).to.be.false();
        done();
      });
    });

    it('should cb err if assertAndBindQueues failed', function (done) {
      testHermes._channel.assertQueue.yieldsAsync();
      testHermes._eventJobs.assertExchanges.yieldsAsync('err');

      testHermes._populateChannel(function (err) {
        expect(err).to.exist();
        expect(testHermes._channel.assertQueue.called).to.be.true();
        expect(testHermes._eventJobs.assertExchanges.called).to.be.true();
        expect(testHermes._eventJobs.assertAndBindQueues.called).to.be.false();
        expect(testHermes.emit.withArgs('ready').called).to.be.false();
        done();
      });
    });

    it('should cb err if assertQueue failed', function (done) {
      testHermes._channel.assertQueue.yieldsAsync('err');

      testHermes._populateChannel(function (err) {
        expect(err).to.exist();
        expect(testHermes._channel.assertQueue.called).to.be.true();
        expect(testHermes._eventJobs.assertExchanges.called).to.be.false();
        expect(testHermes._eventJobs.assertAndBindQueues.called).to.be.false();
        expect(testHermes.emit.withArgs('ready').called).to.be.false();
        done();
      });
    });
  }); // end _populateChannel
  describe('_normalizeQueue', function () {
    it('should return queueDef if name is provided', function (done) {
      var def = Hermes._normalizeQueue('some.queue')
      expect(def).to.deep.equal({ name: 'some.queue', opts: { durable: true }})
      done()
    })
    it('should return queueDef if queueDef is provided', function (done) {
      var def = Hermes._normalizeQueue({ name: 'some.queue' })
      expect(def).to.deep.equal({ name: 'some.queue', opts: { durable: true }})
      done()
    })
    it('should apply additional options', function (done) {
      var def = Hermes._normalizeQueue({ name: 'some.queue', opts: { expires: 2 }})
      expect(def).to.deep.equal({ name: 'some.queue', opts: { durable: true, expires: 2 }})
      done()
    })
    it('should be able to override default options', function (done) {
      var def = Hermes._normalizeQueue({ name: 'some.queue', opts: { expires: 2, durable: false }})
      expect(def).to.deep.equal({ name: 'some.queue', opts: { durable: false, expires: 2 }})
      done()
    })
    describe('use process.env.HERMES_QUEUE_EXPIRES', function () {
      beforeEach(function (done) {
        process.env.HERMES_QUEUE_EXPIRES = 3
        done()
      })
      afterEach(function (done) {
        delete process.env.HERMES_QUEUE_EXPIRES
        done()
      })
      it('should return queueDef if name is provided and use default expires', function (done) {
        var def = Hermes._normalizeQueue('some.queue')
        expect(def).to.deep.equal({ name: 'some.queue', opts: { durable: true, expires: 3 }})
        done()
      })
      it('should return queueDef if queueDef is provided and use default expire', function (done) {
        var def = Hermes._normalizeQueue({ name: 'some.queue' })
        expect(def).to.deep.equal({ name: 'some.queue', opts: { durable: true, expires: 3 }})
        done()
      })
      it('should not override per queue expires with default one', function (done) {
        var def = Hermes._normalizeQueue({ name: 'some.queue', opts: { expires: 20 }})
        expect(def).to.deep.equal({ name: 'some.queue', opts: { durable: true, expires: 20 }})
        done()
      })
    })
  })

  describe('_normalizeQueues', function () {
    it('should work with array of strings', function (done) {
      var defs = Hermes._normalizeQueues(['a', 'b', 'c'])
      expect(defs).to.deep.equal([
        { name: 'a', opts: { durable: true } },
        { name: 'b', opts: { durable: true } },
        { name: 'c', opts: { durable: true } }
      ])
      done()
    })

    it('should work with array of objects', function (done) {
      var defs = Hermes._normalizeQueues([{ name: 'a' }, { name: 'b' }, { name: 'c' }])
      expect(defs).to.deep.equal([
        { name: 'a', opts: { durable: true } },
        { name: 'b', opts: { durable: true } },
        { name: 'c', opts: { durable: true } }
      ])
      done()
    })

    it('should work with array of mixed defs', function (done) {
      var defs = Hermes._normalizeQueues(['a', { name: 'b' }, { name: 'c' }])
      expect(defs).to.deep.equal([
        { name: 'a', opts: { durable: true } },
        { name: 'b', opts: { durable: true } },
        { name: 'c', opts: { durable: true } }
      ])
      done()
    })
  })

  describe('_doesQueueExists', function () {
    it('should return true if queue exists', function (done) {
      var queues = [
        { name: 'a', opts: { durable: true } },
        { name: 'b', opts: { durable: true } },
        { name: 'c', opts: { durable: true } }
      ]
      expect(Hermes._doesQueueExists(queues, 'b')).to.be.true()
      done()
    })

    it('should return false if queue does not exist', function (done) {
      var queues = [
        { name: 'a', opts: { durable: true } },
        { name: 'b', opts: { durable: true } },
        { name: 'c', opts: { durable: true } }
      ]
      expect(Hermes._doesQueueExists(queues, 'd')).to.be.false()
      done()
    })
  })
});
<|endoftext|>


<commit_before>var buster = require('buster');
var assert = buster.assert;
var refute = buster.refute;
var when = require('when');

var utils = require('../tasks/buster/utils');

buster.testCase('utils', {
  '.sequence': {
    'resolves scalar directly': function (done) {
      var spy = this.spy();

      utils.sequence([ null ]).then(spy);

      setTimeout(function () {
        assert.calledOnceWith(spy, [ null ]);
        done();
      }, 10);
    },

    'accepts tasks as deferreds': function (done) {
      var spy = this.spy();
      var deferred = when.defer();

      utils.sequence([ deferred.promise ]).then(spy);

      setTimeout(function () {
        refute.called(spy);
        deferred.resolve('foo');
        setTimeout(function () {
          assert.calledOnceWith(spy, [ 'foo' ]);
          done();
        }, 0);
      }, 0);
    },

    'accepts tasks as functions': function (done) {
      var spy = this.spy();

      utils.sequence([
        function () {
          return 'foo';
        }
      ]).then(spy);

      setTimeout(function () {
        assert.calledOnceWith(spy, [ 'foo' ]);
        done();
      }, 0);
    },

    'accepts tasks as functions returning promises': function (done) {
      var spy = this.spy();
      var deferred = when.defer();

      utils.sequence([
        function () {
          return deferred.promise;
        }
      ]).then(spy);

      setTimeout(function () {
        refute.called(spy);
        deferred.resolve('foo');
        setTimeout(function () {
          assert.calledOnceWith(spy, [ 'foo' ]);
          done();
        }, 0);
      }, 0);
    },

    'does not evaluate second task before the first is resolved': function (done) {
      var deferred1 = when.defer();
      var deferred2 = when.defer();
      var stub1 = this.stub().returns(deferred1.promise);
      var stub2 = this.stub().returns(deferred2.promise);
      var spy = this.spy();

      utils.sequence([ stub1, stub2 ]).then(spy);

      setTimeout(function () {
        assert.calledOnce(stub1);
        refute.called(stub2);
        refute.called(spy);

        deferred1.resolve('foo');

        setTimeout(function () {
          assert.calledOnce(stub2);
          refute.called(spy);

          deferred2.resolve('bar');

          setTimeout(function () {
            assert.calledOnceWith(spy, [ 'foo', 'bar' ]);
            assert.callOrder(stub1, stub2, spy);
            done();
          }, 0);
        }, 0);
      }, 0);
    },

    'does not evaluate second task if the first is rejected': function (done) {
      var deferred1 = when.defer();
      var deferred2 = when.defer();
      var stub1 = this.stub().returns(deferred1.promise);
      var stub2 = this.stub().returns(deferred2.promise);
      var success = this.spy();
      var failure = this.spy();

      utils.sequence([ stub1, stub2 ]).then(success, failure);

      setTimeout(function () {
        assert.calledOnce(stub1);
        refute.called(stub2);
        refute.called(success);
        refute.called(failure);

        deferred1.reject('foo');

        setTimeout(function () {
          refute.calledOnce(stub2);
          refute.called(success);
          assert.calledOnceWith(failure, [ 'foo' ]);
          done();
        }, 0);
      }, 0);
    }
  }
});
<commit_msg>Fix tests for Node v0.8.x<commit_after>var buster = require('buster');
var assert = buster.assert;
var refute = buster.refute;
var when = require('when');

var utils = require('../tasks/buster/utils');

buster.testCase('utils', {
  '.sequence': {
    'resolves scalar directly': function (done) {
      var spy = this.spy();

      utils.sequence([ null ]).then(spy);

      setTimeout(function () {
        assert.calledOnceWith(spy, [ null ]);
        done();
      }, 10);
    },

    'accepts tasks as deferreds': function (done) {
      var spy = this.spy();
      var deferred = when.defer();

      utils.sequence([ deferred.promise ]).then(spy);

      setTimeout(function () {
        refute.called(spy);
        deferred.resolve('foo');
        setTimeout(function () {
          assert.calledOnceWith(spy, [ 'foo' ]);
          done();
        }, 10);
      }, 10);
    },

    'accepts tasks as functions': function (done) {
      var spy = this.spy();

      utils.sequence([
        function () {
          return 'foo';
        }
      ]).then(spy);

      setTimeout(function () {
        assert.calledOnceWith(spy, [ 'foo' ]);
        done();
      }, 0);
    },

    'accepts tasks as functions returning promises': function (done) {
      var spy = this.spy();
      var deferred = when.defer();

      utils.sequence([
        function () {
          return deferred.promise;
        }
      ]).then(spy);

      setTimeout(function () {
        refute.called(spy);
        deferred.resolve('foo');
        setTimeout(function () {
          assert.calledOnceWith(spy, [ 'foo' ]);
          done();
        }, 10);
      }, 10);
    },

    'does not evaluate second task before the first is resolved': function (done) {
      var deferred1 = when.defer();
      var deferred2 = when.defer();
      var stub1 = this.stub().returns(deferred1.promise);
      var stub2 = this.stub().returns(deferred2.promise);
      var spy = this.spy();

      utils.sequence([ stub1, stub2 ]).then(spy);

      setTimeout(function () {
        assert.calledOnce(stub1);
        refute.called(stub2);
        refute.called(spy);

        deferred1.resolve('foo');

        setTimeout(function () {
          assert.calledOnce(stub2);
          refute.called(spy);

          deferred2.resolve('bar');

          setTimeout(function () {
            assert.calledOnceWith(spy, [ 'foo', 'bar' ]);
            assert.callOrder(stub1, stub2, spy);
            done();
          }, 10);
        }, 10);
      }, 10);
    },

    'does not evaluate second task if the first is rejected': function (done) {
      var deferred1 = when.defer();
      var deferred2 = when.defer();
      var stub1 = this.stub().returns(deferred1.promise);
      var stub2 = this.stub().returns(deferred2.promise);
      var success = this.spy();
      var failure = this.spy();

      utils.sequence([ stub1, stub2 ]).then(success, failure);

      setTimeout(function () {
        assert.calledOnce(stub1);
        refute.called(stub2);
        refute.called(success);
        refute.called(failure);

        deferred1.reject('foo');

        setTimeout(function () {
          refute.calledOnce(stub2);
          refute.called(success);
          assert.calledOnceWith(failure, [ 'foo' ]);
          done();
        }, 10);
      }, 10);
    }
  }
});
<|endoftext|>


<commit_before>var should = require('should');
var PassStream = require('pass-stream');
var jayson = require('./..');
var utils = jayson.utils;

describe('jayson.utils', function() {

  describe('request', function() {

    it('exists', function() {
      utils.should.have.property('request');
      utils.request.should.be.a.Function;
    });

    it('should throw a TypeError on an invalid method argument', function() {
      (function() {
        utils.request(null, [1, 2,], null);
      }).should.throw(TypeError);
    });

    it('should throw a TypeError on an invalid params argument', function() {
      (function() {
        utils.request('a_method', true);
      }).should.throw(TypeError);
    });

    it('should omit the params argument when not given', function() {
      var request = utils.request('a_method', null);
      request.should.have.property('method', 'a_method');
      request.should.not.have.property('params');
    });

  });

  describe('getParameterNames', function() {

    it('should return an empty array when passed a parameter-less function', function() {
      var func = function() { return true; };
      var result = utils.getParameterNames(func);
      should.exist(result);
      result.should.be.instanceof(Array);
      result.should.have.length(func.length);
    });

    it('should return the correct names when passed a single-parameter function', function() {
      var func = function(a) { return a; };
      var result = utils.getParameterNames(func);
      should.exist(result);
      result.should.be.instanceof(Array);
      result.should.have.length(func.length);
      result.should.containDeep(['a']);
    });

    it('should return the correct names when passed a simple function', function() {
      var func = function(a, b) { return a + b; };
      var result = utils.getParameterNames(func);
      should.exist(result);
      result.should.be.instanceof(Array);
      result.should.have.length(func.length);
      result.should.containDeep(['a', 'b']);
    });

    it('should return the correct names when passed a odd-formatted function', function() {
      var func = function     (a, b            , __b) {
        func(2, 3, 55, 4);
        return a + b;
      };
      var result = utils.getParameterNames(func);
      should.exist(result);
      result.should.be.instanceof(Array);
      result.should.have.length(func.length);
      result.should.containDeep(['a', 'b', '__b']);
    });

    it('should return the correct names when passed a function with complex parameters', function() {
      var func = function(_$foo, $$, FOO, $F00, _) { return false; };
      var result = utils.getParameterNames(func);
      should.exist(result);
      result.should.be.instanceof(Array);
      result.should.have.length(func.length);
      result.should.containDeep(['_$foo', '$$', 'FOO', '$F00', '_']);
    });

    it('should return the correct names in the right order', function() {
      var func = function(b, c, a) { return false; };
      var result = utils.getParameterNames(func);
      should.exist(result);
      result.should.be.instanceof(Array);
      result.should.have.length(func.length);
      result.should.containDeep(['b', 'c', 'a']);
      result[0].should.equal('b');
      result[1].should.equal('c');
      result[2].should.equal('a');
    });

    it('should return the correct parameters when passed a simple named function', function() {
      var func = function named(b, c, a) {};
      var result = utils.getParameterNames(func);
      should.exist(result);
      result.should.be.instanceof(Array).and.have.length(func.length);
      result.should.containDeep(['b', 'c', 'a']);
    });

    it('should return the correct parameters when passed a complex named function', function() {
      var func = function named_complex$(b, c, a) {};
      var result = utils.getParameterNames(func);
      should.exist(result);
      result.should.be.instanceof(Array).and.have.length(func.length);
      result.should.containDeep(['b', 'c', 'a']);
    });

    it('should return the correct paremters when passed an ES6 style function with zero parameters', function() {
      var func = () => {};
      var result = utils.getParameterNames(func);
      should.exist(result);
      result.should.be.instanceof(Array).and.have.length(0);
    });

    it('should return the correct paremters when passed an ES6 style function with more than zero parameters', function() {
      var func = (b, c, a) => {};
      var result = utils.getParameterNames(func);
      should.exist(result);
      result.should.be.instanceof(Array).and.have.length(func.length);
      result.should.containDeep(['b', 'c', 'a']);
    });

  });

  describe('parseBody', function() {

    var parseBody = utils.parseBody;

    it('should parse a valid json object', function(done) {
      var stream = new PassStream();
      var obj = {asdf: true, complex: {value: 2, a: 3}};

      parseBody(stream, {}, function(err, result) {
        if(err) return done(err);
        obj.should.eql(result);
        done();
      });

      stream.end(JSON.stringify(obj));
    });

    it('should parse a valid json array', function(done) {
      var stream = new PassStream();
      var arr = [{first: true}, {asdf: true, complex: {value: 2, a: 3}}];

      parseBody(stream, {}, function(err, result) {
        if(err) return done(err);
        arr.should.eql(result);
        done();
      });

      stream.end(JSON.stringify(arr));
    });

    it('should return an error on bad input', function(done) {
      var stream = new PassStream();

      parseBody(stream, {}, function(err, result) {
        should(err).be.instanceof(Error);
        done();
      });

      stream.end("\"");
    });

  });

  describe('stringify', function(done) {

    it('should not throw with circular JSON reference', function(done) {

      var foo = {};
      var bar = { foo: foo };
      foo.bar = bar;

      var fn = utils.JSON.stringify(bar, {}, function(err, str) {
        should(err).not.exist;
        done();
      });

      should(fn).not.throw();
    });

  });

});
<commit_msg>add a test for multi-line arguments. It fails with prior code, passes with these changes<commit_after>var should = require('should');
var PassStream = require('pass-stream');
var jayson = require('./..');
var utils = jayson.utils;

describe('jayson.utils', function() {

  describe('request', function() {

    it('exists', function() {
      utils.should.have.property('request');
      utils.request.should.be.a.Function;
    });

    it('should throw a TypeError on an invalid method argument', function() {
      (function() {
        utils.request(null, [1, 2,], null);
      }).should.throw(TypeError);
    });

    it('should throw a TypeError on an invalid params argument', function() {
      (function() {
        utils.request('a_method', true);
      }).should.throw(TypeError);
    });

    it('should omit the params argument when not given', function() {
      var request = utils.request('a_method', null);
      request.should.have.property('method', 'a_method');
      request.should.not.have.property('params');
    });

  });

  describe('getParameterNames', function() {

    it('should return an empty array when passed a parameter-less function', function() {
      var func = function() { return true; };
      var result = utils.getParameterNames(func);
      should.exist(result);
      result.should.be.instanceof(Array);
      result.should.have.length(func.length);
    });

    it('should return the correct names when passed a single-parameter function', function() {
      var func = function(a) { return a; };
      var result = utils.getParameterNames(func);
      should.exist(result);
      result.should.be.instanceof(Array);
      result.should.have.length(func.length);
      result.should.containDeep(['a']);
    });

    it('should return the correct names when passed a simple function', function() {
      var func = function(a, b) { return a + b; };
      var result = utils.getParameterNames(func);
      should.exist(result);
      result.should.be.instanceof(Array);
      result.should.have.length(func.length);
      result.should.containDeep(['a', 'b']);
    });

    it('should return the correct names when passed a odd-formatted function', function() {
      var func = function     (a, b            , __b) {
        func(2, 3, 55, 4);
        return a + b;
      };
      var result = utils.getParameterNames(func);
      should.exist(result);
      result.should.be.instanceof(Array);
      result.should.have.length(func.length);
      result.should.containDeep(['a', 'b', '__b']);
    });

    it('should return the correct names when passed multi-line arguments', function() {
      var func = function (
        a,
        b , __b) {
        func(2, 3, 55, 4);
        return a + b;
      };
      var result = utils.getParameterNames(func);
      should.exist(result);
      result.should.be.instanceof(Array);
      result.should.have.length(func.length);
      result.should.containDeep(['a', 'b', '__b']);
    });

    it('should return the correct names when passed a function with complex parameters', function() {
      var func = function(_$foo, $$, FOO, $F00, _) { return false; };
      var result = utils.getParameterNames(func);
      should.exist(result);
      result.should.be.instanceof(Array);
      result.should.have.length(func.length);
      result.should.containDeep(['_$foo', '$$', 'FOO', '$F00', '_']);
    });

    it('should return the correct names in the right order', function() {
      var func = function(b, c, a) { return false; };
      var result = utils.getParameterNames(func);
      should.exist(result);
      result.should.be.instanceof(Array);
      result.should.have.length(func.length);
      result.should.containDeep(['b', 'c', 'a']);
      result[0].should.equal('b');
      result[1].should.equal('c');
      result[2].should.equal('a');
    });

    it('should return the correct parameters when passed a simple named function', function() {
      var func = function named(b, c, a) {};
      var result = utils.getParameterNames(func);
      should.exist(result);
      result.should.be.instanceof(Array).and.have.length(func.length);
      result.should.containDeep(['b', 'c', 'a']);
    });

    it('should return the correct parameters when passed a complex named function', function() {
      var func = function named_complex$(b, c, a) {};
      var result = utils.getParameterNames(func);
      should.exist(result);
      result.should.be.instanceof(Array).and.have.length(func.length);
      result.should.containDeep(['b', 'c', 'a']);
    });

    it('should return the correct paremters when passed an ES6 style function with zero parameters', function() {
      var func = () => {};
      var result = utils.getParameterNames(func);
      should.exist(result);
      result.should.be.instanceof(Array).and.have.length(0);
    });

    it('should return the correct paremters when passed an ES6 style function with more than zero parameters', function() {
      var func = (b, c, a) => {};
      var result = utils.getParameterNames(func);
      should.exist(result);
      result.should.be.instanceof(Array).and.have.length(func.length);
      result.should.containDeep(['b', 'c', 'a']);
    });

  });

  describe('parseBody', function() {

    var parseBody = utils.parseBody;

    it('should parse a valid json object', function(done) {
      var stream = new PassStream();
      var obj = {asdf: true, complex: {value: 2, a: 3}};

      parseBody(stream, {}, function(err, result) {
        if(err) return done(err);
        obj.should.eql(result);
        done();
      });

      stream.end(JSON.stringify(obj));
    });

    it('should parse a valid json array', function(done) {
      var stream = new PassStream();
      var arr = [{first: true}, {asdf: true, complex: {value: 2, a: 3}}];

      parseBody(stream, {}, function(err, result) {
        if(err) return done(err);
        arr.should.eql(result);
        done();
      });

      stream.end(JSON.stringify(arr));
    });

    it('should return an error on bad input', function(done) {
      var stream = new PassStream();

      parseBody(stream, {}, function(err, result) {
        should(err).be.instanceof(Error);
        done();
      });

      stream.end("\"");
    });

  });

  describe('stringify', function(done) {

    it('should not throw with circular JSON reference', function(done) {

      var foo = {};
      var bar = { foo: foo };
      foo.bar = bar;

      var fn = utils.JSON.stringify(bar, {}, function(err, str) {
        should(err).not.exist;
        done();
      });

      should(fn).not.throw();
    });

  });

});
<|endoftext|>


<commit_before>module.exports = {
  projects: {
    25: {
      pid: '25',
      name: 'Writing a Book on Web Dev Tools',
      descr: 'Tasks required to write a book on the tools required to develop a web application',
      tids: ['1', '2', '3']
    },
    34: {
      pid: '34',
      name: 'Cook a Spanish omelette',
      descr: 'Steps to cook a Spanish omelette or "tortilla"',
      tids: ['4', '5', '6', '7', '8', '9']
    }
  },
  tasks: {
    1: {
      tid: '1',
      descr: 'Figure out what kind of application to develop',
      completed: true
    },
    2: {
      tid: '2',
      descr: 'Decide what tools to use',
      completed: false
    },
    3: {
      tid: '3',
      descr: 'Create repositories for text and samples',
      completed: true
    },
    4: {
      tid: '4',
      descr: 'Peel and dice the potatoes',
      completed: true
    },
    5: {
      tid: '5',
      descr: 'Fry the potatoes',
      completed: true
    },
    6: {
      tid: '6',
      descr: 'Peel and chop the onions',
      completed: false
    },
    7: {
      tid: '7',
      descr: 'Saute the onions',
      completed: false
    },
    8: {
      tid: '8',
      descr: 'Beat the eggs',
      completed: false
    },
    9: {
      tid: '9',
      descr: 'Mix everything and fry',
      completed: false
    }
  },
  requests: {
    pending: 0,
    errors: []
  },
  misc: {
    editTid: null
  }
};
<commit_msg>project state image was missing pending field<commit_after>module.exports = {
  projects: {
    25: {
      pid: '25',
      name: 'Writing a Book on Web Dev Tools',
      descr: 'Tasks required to write a book on the tools required to develop a web application',
      tids: ['1', '2', '3'],
      pending: 1
    },
    34: {
      pid: '34',
      name: 'Cook a Spanish omelette',
      descr: 'Steps to cook a Spanish omelette or "tortilla"',
      tids: ['4', '5', '6', '7', '8', '9'],
      pending: 4
    }
  },
  tasks: {
    1: {
      tid: '1',
      descr: 'Figure out what kind of application to develop',
      completed: true
    },
    2: {
      tid: '2',
      descr: 'Decide what tools to use',
      completed: false
    },
    3: {
      tid: '3',
      descr: 'Create repositories for text and samples',
      completed: true
    },
    4: {
      tid: '4',
      descr: 'Peel and dice the potatoes',
      completed: true
    },
    5: {
      tid: '5',
      descr: 'Fry the potatoes',
      completed: true
    },
    6: {
      tid: '6',
      descr: 'Peel and chop the onions',
      completed: false
    },
    7: {
      tid: '7',
      descr: 'Saute the onions',
      completed: false
    },
    8: {
      tid: '8',
      descr: 'Beat the eggs',
      completed: false
    },
    9: {
      tid: '9',
      descr: 'Mix everything and fry',
      completed: false
    }
  },
  requests: {
    pending: 0,
    errors: []
  },
  misc: {
    editTid: null
  }
};
<|endoftext|>


<commit_before>var validate = require('../../lib/middleware.js'),
  express = require('express'),
  bodyParser = require('body-parser');

// We build a simple express test in order to test the middleware
//
var app = express();

app.use(bodyParser.json());

app.param('testParam', validate.param({
  type: Number, required: true
}));

app.get('/param/:testParam', function(req, res) {
  res.sendStatus(200);
});

app.get('/query',
  validate.query({
    'test': { type: String, match: /^.*?test$/i }
  }),
  function(req, res) {
    res.status(200).json(req.query);
  }
);

app.post('/post',
  validate.body({
    'test': [ { type: String, match: /^.*?test$/i } ]
  }),
  function(req, res) {
    res.status(200).json(req.body);
  }
);

// Not found route
app.use(function(req, res, next) {
  res.status(400).json({ error: 'not-found' });
});

// Error handler
app.use(function(err, req, res, next) {
  if (err.constructor.name == 'ValidationError') {
    return res.status(400).json({error: 'validation-error', keyPath: err.keyPath.join('.'), message: err.message});
  }
  res.status(500).json({error: 'internal-server-error'});
});

exports = module.exports = app;
<commit_msg>Removed unused file.<commit_after><|endoftext|>


<commit_before>// ==UserScript==
// @name         Ads DOM Remover Runner
// @namespace    sagiegurari
// @version      0.11
// @author       Sagie Gur-Ari
// @description  Library - Removes Ad Containers from DOM (doesn't replace adblocker extension, but blocks dynamic content which the adblocker fails to block by removing whole sections from the HTML DOM.)
// @homepage     https://github.com/sagiegurari/userscripts-ads-dom-remover
// @supportURL   https://github.com/sagiegurari/userscripts-ads-dom-remover/issues
// @grant        none
// @license      MIT License
// ==/UserScript==
/*global console*/

(function initADR() {
    'use strict';

    /**
     * This class invokes the ads removing process based on provided options.
     *
     * @author Sagie Gur-Ari
     * @class ADRService
     * @public
     * @param {object} $ - The jquery library
     * @param {object} [options] - The process options
     * @param {function} [options.getSelectorDefinitions] - Returns all selector definitions per host
     * @param {number} [options.loops=10] - The amount of loops to run (will be invoked twice)
     * @param {number} [options.interval=250] - Time in millies between each loop
     */
    var Service = function ($, options) {
        /*eslint-disable no-invalid-this*/
        this.$ = $;
        options = options || {};
        this.loops = options.loops || 10;
        this.interval = options.interval || 250;

        var getSelectorDefinitions = options.getSelectorDefinitions || this.noop;
        this.selectorDefinitions = getSelectorDefinitions() || {};

        //find default selectors
        this.defaultSelectors = null;
        var index;
        var id;
        this.ids = Object.keys(this.selectorDefinitions);
        for (index = 0; index < this.ids.length; index++) {
            id = this.ids[index];

            this.selectorDefinitions[id].id = id;

            if (this.selectorDefinitions[id].hostNames === true) {
                this.defaultSelectors = this.selectorDefinitions[id];
            }
        }

        this.defaultSelectors = this.defaultSelectors || [];

        this.state = {
            intervalID: null,
            counter: 0,
            secondLoop: false
        };
        /*eslint-enable no-invalid-this*/
    };

    /**
     * Empty function
     *
     * @function
     * @memberof! ADRService
     * @private
     * @returns {undefined} Always undefined
     */
    Service.prototype.noop = function () {
        return undefined;
    };

    /**
     * Returns the selectors to remove based on the provided host name.
     *
     * @function
     * @memberof! ADRService
     * @private
     * @param {string} hostName - The current host name
     * @returns {Array} Array of selectors (or objects) to remove from the DOM
     */
    Service.prototype.getSelectors = function (hostName) {
        var selectors;

        try {
            var definitionIndex;
            var hostNameIndex;
            var id;
            var hostNames;
            for (definitionIndex = 0; definitionIndex < this.ids.length; definitionIndex++) {
                id = this.ids[definitionIndex];
                hostNames = this.selectorDefinitions[id].hostNames;

                if ((typeof hostNames === 'string') && (hostName.indexOf(hostNames) !== -1)) {
                    selectors = this.selectorDefinitions[id];
                } else if (Array.isArray(hostNames)) {
                    for (hostNameIndex = 0; hostNameIndex < hostNames.length; hostNameIndex++) {
                        if (hostName.indexOf(hostNames[hostNameIndex]) !== -1) {
                            selectors = this.selectorDefinitions[id];
                            break;
                        }
                    }
                }

                if (selectors) {
                    break;
                }
            }
        } catch (error) {
            console.error('[user script][Ads DOM Remover][getSelectors] Error:', error);
        }

        if (!selectors) {
            selectors = this.defaultSelectors;
        }

        selectors = selectors || [];

        return selectors;
    };

    /**
     * Hides the elements by removing them from the DOM completely.
     *
     * @function
     * @memberof! ADRService
     * @private
     * @returns {boolean} True if any element was removed during this invocation
     */
    Service.prototype.hideElements = function () {
        var self = this;
        var found = false;

        var selectors = self.getSelectors(document.location.hostname);
        if (selectors) {
            if ((!Array.isArray(selectors)) && selectors.selectors) {
                if (selectors.id) {
                    console.debug('[user script][Ads DOM Remover][hideElements] Using Selectors:', selectors.id);
                }

                selectors = selectors.selectors;
            }

            selectors.forEach(function (selector) {
                var selectorString = selector.selector || selector;

                var $element;
                try {
                    $element = self.$(selectorString);
                } catch (error) {
                    console.error('[user script][Ads DOM Remover][hideElements] Error while running selector:', selectorString, error);
                }

                if ($element && $element.length) {
                    found = true;

                    if (selector.fineTuneSelector && (typeof selector.fineTuneSelector === 'function')) {
                        $element = selector.fineTuneSelector($element);
                    }

                    if (selector.pre && (typeof selector.pre === 'function')) {
                        selector.pre($element);
                    }

                    var remove = true;
                    if (selector.filter && (typeof selector.filter === 'function')) {
                        remove = selector.filter($element);
                    }

                    if (remove) {
                        $element.removeAttr('style');
                        $element.css('display', 'none !important');

                        $element.remove();

                        console.debug('[user script][Ads DOM Remover][hideElements] Found:', selector, 'count:', $element.length, 'in website and removed it.');
                    } else {
                        console.debug('[user script][Ads DOM Remover][hideElements] Found:', selector, 'count:', $element.length, 'in website but not removing.');
                    }
                }
            });
        }

        return found;
    };

    /**
     * Invoked each interval to run the main library logic.
     *
     * @function
     * @memberof! ADRService
     * @private
     */
    Service.prototype.actionLoop = function () {
        this.state.counter++;
        var stopInterval = this.state.intervalID && (this.state.counter > this.loops);
        console.debug('[user script][Ads DOM Remover][actionLoop] Running loop:', this.state.counter, 'state:', this.state, 'stop interval:', stopInterval);

        this.hideElements();

        if (stopInterval) {
            console.debug('[user script][Ads DOM Remover][actionLoop] Clearing interval ID:', this.state.intervalID);
            clearInterval(this.state.intervalID);
            this.state.intervalID = null;

            if (!this.state.secondLoop) {
                this.startActionLoop(false, 2500);
            }
        }
    };

    /**
     * Starts the interval invocations.
     *
     * @function
     * @memberof! ADRService
     * @private
     * @param {boolean} firstTime - If this function was called for the first time
     * @param {number} delay - The delay to wait before setting the interval
     */
    Service.prototype.startActionLoop = function (firstTime, delay) {
        var self = this;

        self.state.secondLoop = !firstTime;
        self.state.counter = 0;

        setTimeout(function () {
            self.state.intervalID = setInterval(function () {
                self.actionLoop();
            }, self.interval);

            setTimeout(function () {
                self.hideElements();
            }, 15000);
        }, delay);
    };

    /**
     * Starts the service run.
     *
     * @function
     * @memberof! ADRService
     * @private
     */
    Service.prototype.start = function () {
        this.startActionLoop(true, 0);
    };

    /**
     * Starts the service run.
     *
     * @function
     * @namespace ADRRunner
     * @public
     * @param {object} $ - The jquery library
     * @param {object} options - The process options
     * @param {function} options.getSelectorDefinitions - Returns all selector definitions per host
     * @param {number} [options.loops=10] - The amount of loops to run (will be invoked twice)
     * @param {number} [options.interval=250] - Time in millies between each loop
     */
    window.adrRunner = function adrRunner($, options) {
        if ($ && (typeof $ === 'function') && options && options.getSelectorDefinitions && (typeof options.getSelectorDefinitions === 'function')) {
            var service = new Service($, options);
            service.start();
        }
    };
}());
<commit_msg>bump version<commit_after>// ==UserScript==
// @name         Ads DOM Remover Runner
// @namespace    sagiegurari
// @version      0.12
// @author       Sagie Gur-Ari
// @description  Library - Removes Ad Containers from DOM (doesn't replace adblocker extension, but blocks dynamic content which the adblocker fails to block by removing whole sections from the HTML DOM.)
// @homepage     https://github.com/sagiegurari/userscripts-ads-dom-remover
// @supportURL   https://github.com/sagiegurari/userscripts-ads-dom-remover/issues
// @grant        none
// @license      MIT License
// ==/UserScript==
/*global console*/

(function initADR() {
    'use strict';

    /**
     * This class invokes the ads removing process based on provided options.
     *
     * @author Sagie Gur-Ari
     * @class ADRService
     * @public
     * @param {object} $ - The jquery library
     * @param {object} [options] - The process options
     * @param {function} [options.getSelectorDefinitions] - Returns all selector definitions per host
     * @param {number} [options.loops=10] - The amount of loops to run (will be invoked twice)
     * @param {number} [options.interval=250] - Time in millies between each loop
     */
    var Service = function ($, options) {
        /*eslint-disable no-invalid-this*/
        this.$ = $;
        options = options || {};
        this.loops = options.loops || 10;
        this.interval = options.interval || 250;

        var getSelectorDefinitions = options.getSelectorDefinitions || this.noop;
        this.selectorDefinitions = getSelectorDefinitions() || {};

        //find default selectors
        this.defaultSelectors = null;
        var index;
        var id;
        this.ids = Object.keys(this.selectorDefinitions);
        for (index = 0; index < this.ids.length; index++) {
            id = this.ids[index];

            this.selectorDefinitions[id].id = id;

            if (this.selectorDefinitions[id].hostNames === true) {
                this.defaultSelectors = this.selectorDefinitions[id];
            }
        }

        this.defaultSelectors = this.defaultSelectors || [];

        this.state = {
            intervalID: null,
            counter: 0,
            secondLoop: false
        };
        /*eslint-enable no-invalid-this*/
    };

    /**
     * Empty function
     *
     * @function
     * @memberof! ADRService
     * @private
     * @returns {undefined} Always undefined
     */
    Service.prototype.noop = function () {
        return undefined;
    };

    /**
     * Returns the selectors to remove based on the provided host name.
     *
     * @function
     * @memberof! ADRService
     * @private
     * @param {string} hostName - The current host name
     * @returns {Array} Array of selectors (or objects) to remove from the DOM
     */
    Service.prototype.getSelectors = function (hostName) {
        var selectors;

        try {
            var definitionIndex;
            var hostNameIndex;
            var id;
            var hostNames;
            for (definitionIndex = 0; definitionIndex < this.ids.length; definitionIndex++) {
                id = this.ids[definitionIndex];
                hostNames = this.selectorDefinitions[id].hostNames;

                if ((typeof hostNames === 'string') && (hostName.indexOf(hostNames) !== -1)) {
                    selectors = this.selectorDefinitions[id];
                } else if (Array.isArray(hostNames)) {
                    for (hostNameIndex = 0; hostNameIndex < hostNames.length; hostNameIndex++) {
                        if (hostName.indexOf(hostNames[hostNameIndex]) !== -1) {
                            selectors = this.selectorDefinitions[id];
                            break;
                        }
                    }
                }

                if (selectors) {
                    break;
                }
            }
        } catch (error) {
            console.error('[user script][Ads DOM Remover][getSelectors] Error:', error);
        }

        if (!selectors) {
            selectors = this.defaultSelectors;
        }

        selectors = selectors || [];

        return selectors;
    };

    /**
     * Hides the elements by removing them from the DOM completely.
     *
     * @function
     * @memberof! ADRService
     * @private
     * @returns {boolean} True if any element was removed during this invocation
     */
    Service.prototype.hideElements = function () {
        var self = this;
        var found = false;

        var selectors = self.getSelectors(document.location.hostname);
        if (selectors) {
            if ((!Array.isArray(selectors)) && selectors.selectors) {
                if (selectors.id) {
                    console.debug('[user script][Ads DOM Remover][hideElements] Using Selectors:', selectors.id);
                }

                selectors = selectors.selectors;
            }

            selectors.forEach(function (selector) {
                var selectorString = selector.selector || selector;

                var $element;
                try {
                    $element = self.$(selectorString);
                } catch (error) {
                    console.error('[user script][Ads DOM Remover][hideElements] Error while running selector:', selectorString, error);
                }

                if ($element && $element.length) {
                    found = true;

                    if (selector.fineTuneSelector && (typeof selector.fineTuneSelector === 'function')) {
                        $element = selector.fineTuneSelector($element);
                    }

                    if (selector.pre && (typeof selector.pre === 'function')) {
                        selector.pre($element);
                    }

                    var remove = true;
                    if (selector.filter && (typeof selector.filter === 'function')) {
                        remove = selector.filter($element);
                    }

                    if (remove) {
                        $element.removeAttr('style');
                        $element.css('display', 'none !important');

                        $element.remove();

                        console.debug('[user script][Ads DOM Remover][hideElements] Found:', selector, 'count:', $element.length, 'in website and removed it.');
                    } else {
                        console.debug('[user script][Ads DOM Remover][hideElements] Found:', selector, 'count:', $element.length, 'in website but not removing.');
                    }
                }
            });
        }

        return found;
    };

    /**
     * Invoked each interval to run the main library logic.
     *
     * @function
     * @memberof! ADRService
     * @private
     */
    Service.prototype.actionLoop = function () {
        this.state.counter++;
        var stopInterval = this.state.intervalID && (this.state.counter > this.loops);
        console.debug('[user script][Ads DOM Remover][actionLoop] Running loop:', this.state.counter, 'state:', this.state, 'stop interval:', stopInterval);

        this.hideElements();

        if (stopInterval) {
            console.debug('[user script][Ads DOM Remover][actionLoop] Clearing interval ID:', this.state.intervalID);
            clearInterval(this.state.intervalID);
            this.state.intervalID = null;

            if (!this.state.secondLoop) {
                this.startActionLoop(false, 2500);
            }
        }
    };

    /**
     * Starts the interval invocations.
     *
     * @function
     * @memberof! ADRService
     * @private
     * @param {boolean} firstTime - If this function was called for the first time
     * @param {number} delay - The delay to wait before setting the interval
     */
    Service.prototype.startActionLoop = function (firstTime, delay) {
        var self = this;

        self.state.secondLoop = !firstTime;
        self.state.counter = 0;

        setTimeout(function () {
            self.state.intervalID = setInterval(function () {
                self.actionLoop();
            }, self.interval);

            setTimeout(function () {
                self.hideElements();
            }, 15000);
        }, delay);
    };

    /**
     * Starts the service run.
     *
     * @function
     * @memberof! ADRService
     * @private
     */
    Service.prototype.start = function () {
        this.startActionLoop(true, 0);
    };

    /**
     * Starts the service run.
     *
     * @function
     * @namespace ADRRunner
     * @public
     * @param {object} $ - The jquery library
     * @param {object} options - The process options
     * @param {function} options.getSelectorDefinitions - Returns all selector definitions per host
     * @param {number} [options.loops=10] - The amount of loops to run (will be invoked twice)
     * @param {number} [options.interval=250] - Time in millies between each loop
     */
    window.adrRunner = function adrRunner($, options) {
        if ($ && (typeof $ === 'function') && options && options.getSelectorDefinitions && (typeof options.getSelectorDefinitions === 'function')) {
            var service = new Service($, options);
            service.start();
        }
    };
}());
<|endoftext|>


<commit_before>"use strict";
module.exports =
{
	"env"   : { "es6" : true },
	"parserOptions" :
	{
		"ecmaVersion" : "2018",
		"sourceType"  : "script"
	},
	// Use this comment to disable a rule in a file:	/* eslint-disable <rule> */
	// Use this comment to disable a rule for a block:	/* eslint-disable <rule> */   <YOUR BLOCK HERE, MULTIPLE LINES FINE>    /* eslint-enable <rule> */
	// Use this comment to disable a rule on a line:	// eslint-disable-line <rule>

	// 0 == off
	// 1 == warn
	// 2 == error

	"plugins" : ["sembiance"],

	"rules" :
	{
		// Plugins
		"sembiance/disfavor-array-concat"       : 2,
		"sembiance/favor-includes"              : 2,
		"sembiance/tiptoe-suffix-code"          : 2,
		"sembiance/no-useless-variables"        : 2,
		"sembiance/no-accounting-format-number" : 2,

		// New
		"multiline-comment-style"     : 0,
		"implicit-arrow-linebreak"    : 0,

		// Possible Errors
		"for-direction"                 : 2,
		"getter-return"                 : 0,
		"no-async-promise-executor"     : 2,
		"no-await-in-loop"              : 2,
		"no-compare-neg-zero"           : 2,
		"no-cond-assign"                : [2, "always"],
		"no-console"                    : 0,
		"no-constant-condition"         : [2, {"checkLoops" : false}],
		"no-control-regex"              : 2,
		"no-debugger"                   : 2,
		"no-dupe-args"                  : 2,
		"no-dupe-keys"                  : 2,
		"no-duplicate-case"             : 2,
		"no-empty"                      : [2, {"allowEmptyCatch" : true}],
		"no-empty-character-class"      : 2,
		"no-ex-assign"                  : 2,
		"no-extra-boolean-cast"         : 2,
		"no-extra-parens"               : 0,
		"no-extra-semi"                 : 2,
		"no-func-assign"                : 2,
		"no-inner-declarations"         : [2, "functions"],
		"no-invalid-regexp"             : 2,
		"no-irregular-whitespace"       : [2, {"skipStrings" : true, "skipTemplates" : true}],
		"no-obj-calls"                  : 2,
		"no-misleading-character-class" : 2,
		"no-prototype-builtins"         : 0,
		"no-regex-spaces"               : 2,
		"no-sparse-arrays"              : 2,
		"no-template-curly-in-string"   : 2,
		"no-unexpected-multiline"       : 2,
		"no-unreachable"                : 2,
		"no-unsafe-finally"             : 2,
		"no-unsafe-negation"            : 2,
		"require-atomic-updates"        : 2,
		"use-isnan"                     : 2,
		"valid-jsdoc"                   : 0,
		"valid-typeof"                  : 2,

		// Best Practices
		"accessor-pairs"               : 0,
		"array-callback-return"        : 2,
		"block-scoped-var"             : 2,
		"class-methods-use-this"       : 0,
		"complexity"                   : 0,
		"consistent-return"            : 0,
		"curly"                        : [2, "multi-or-nest", "consistent"],
		"default-case"                 : 0,
		"dot-location"                 : [2, "object"],
		"dot-notation"                 : [2, {"allowKeywords" : false}],
		"eqeqeq"                       : [2, "always"],
		"guard-for-in"                 : 2,
		"max-classes-per-file"         : 0,
		"no-alert"                     : 2,
		"no-caller"                    : 2,
		"no-case-declarations"         : 2,
		"no-div-regex"                 : 2,
		"no-else-return"               : 2,
		"no-empty-function"            : 0,
		"no-empty-pattern"             : 2,
		"no-eq-null"                   : 2,
		"no-eval"                      : 2,
		"no-extend-native"             : 0,
		"no-extra-bind"                : 2,
		"no-extra-label"               : 2,
		"no-fallthrough"               : 2,
		"no-floating-decimal"          : 2,
		"no-global-assign"             : 2,
		"no-implicit-coercion"         : 0,
		// "no-implicit-globals" : Handled in parents "node", "browser", "both"
		"no-implied-eval"              : 2,
		"no-invalid-this"              : 0,
		"no-iterator"                  : 2,
		"no-labels"                    : 2,
		"no-lone-blocks"               : 2,
		"no-loop-func"                 : 2,
		"no-magic-numbers"             : 0,
		"no-multi-spaces"              : 2,
		"no-multi-str"                 : 2,
		"no-new"                       : 2,
		"no-new-func"                  : 2,
		"no-new-wrappers"              : 2,
		"no-octal"                     : 2,
		"no-octal-escape"              : 2,
		"no-param-reassign"            : 2,
		"no-proto"                     : 2,
		"no-redeclare"                 : 2,
		"no-restricted-properties"     : 0,
		"no-return-assign"             : 2,
		"no-return-await"              : 2,
		"no-script-url"                : 2,
		"no-self-assign"               : 2,
		"no-self-compare"              : 2,
		"no-sequences"                 : 0,
		"no-throw-literal"             : 2,
		"no-unmodified-loop-condition" : 2,
		"no-unused-expressions"        : 2,
		"no-unused-labels"             : 2,
		"no-useless-call"              : 2,
		"no-useless-catch"             : 2,
		"no-useless-concat"            : 2,
		"no-useless-escape"            : 2,
		"no-useless-return"            : 2,
		"no-void"                      : 2,
		"no-warning-comments"          : 2,
		"no-with"                      : 2,
		"prefer-named-capture-group"   : 0,
		"prefer-promise-reject-errors" : 0,
		"radix"                        : 2,
		"require-await"                : 2,
		"require-unicode-regexp"       : 0,
		"vars-on-top"                  : 2,
		"wrap-iife"                    : [2, "inside"],
		"yoda"                         : 2,

		// Strict Mode
		"strict" : [2, "global"],

		// Variables
		"init-declarations"          : [2, "always"],
		"no-catch-shadow"            : 0,
		"no-delete-var"              : 2,
		"no-label-var"               : 2,
		"no-restricted-globals"      : 0,
		"no-shadow"                  : 2,
		"no-shadow-restricted-names" : 2,
		"no-undef"                   : [2, {"typeof" : true}],
		"no-undef-init"              : 0,
		"no-undefined"               : 0,
		"no-unused-vars"             : [2, {"argsIgnorePattern" : "^[iI]gnored$|^e$|^err$", "varsIgnorePattern" : "^XU$" }],
		"no-use-before-define"       : [2, {"functions" : false}],

		// Node.js and CommonJS : Handled in parents "node", "browser", "both"

		// Stylistic Issues
		"array-bracket-newline"            : 0,
		"array-bracket-spacing"            : [2, "never"],
		"array-element-newline"            : 0,
		"block-spacing"                    : 2,
		"brace-style"                      : [2, "allman", {"allowSingleLine" : true}],
		"camelcase"                        : [2, {properties : "always"}],
		"capitalized-comments"             : 0,
		"comma-dangle"                     : [2, "never"],
		"comma-spacing"                    : [2, { "before" : false, "after" : true }],
		"comma-style"                      : [2, "last"],
		"computed-property-spacing"        : [2, "never"],
		"consistent-this"                  : [2, "self"],
		"eol-last"                         : [2, "always"],
		"func-call-spacing"                : [2, "never"],
		"func-name-matching"               : 0,
		"func-names"                       : [2, "as-needed"],
		"func-style"                       : 0,
		"function-paren-newline"           : [2, "consistent"],
		"id-blacklist"                     : 0,
		"id-length"                        : 0,
		"id-match"                         : 0,
		"indent"                           : [2, "tab", {"SwitchCase" : 1}],
		"jsx-quotes"                       : 0,
		"key-spacing"                      : [2, {"beforeColon" : true, "afterColon" : true, "mode" : "minimum"}],
		"keyword-spacing"                  : 0,
		"line-comment-position"            : 0,
		"linebreak-style"                  : [2, "unix"],
		"lines-around-comment"             : 0,
		"max-depth"                        : [2, 5],
		"max-len"                          : [2, 271],
		"max-lines"                        : 0,
		"max-lines-per-function"           : 0,
		"max-nested-callbacks"             : [2, 5],
		"max-params"                       : [2, 7],
		"max-statements"                   : 0,
		"max-statements-per-line"          : 0,
		"multiline-ternary"                : [2, "never"],
		"new-cap"                          : 2,
		"new-parens"                       : 2,
		"newline-per-chained-call"         : 0,
		"no-array-constructor"             : 2,
		"no-bitwise"                       : 2,
		"no-continue"                      : 0,
		"no-inline-comments"               : 0,
		"no-lonely-if"                     : 2,
		"no-mixed-operators"               : 2,
		"no-mixed-spaces-and-tabs"         : [2, "smart-tabs"],
		"no-multi-assign"                  : 0,
		"no-multiple-empty-lines"          : 2,
		"no-negated-condition"             : 0,
		"no-nested-ternary"                : 0,
		"no-new-object"                    : 2,
		"no-plusplus"                      : 0,
		"no-restricted-syntax"             : 0,
		"no-tabs"                          : 0,
		"no-ternary"                       : 0,
		"no-trailing-spaces"               : [2, {"skipBlankLines" : true}],
		"no-underscore-dangle"             : [2, { "allow" : ["_gsTransform"]}],
		"no-unneeded-ternary"              : 2,
		"no-whitespace-before-property"    : 2,
		"nonblock-statement-body-position" : [2, "below"],
		"object-curly-newline"             : 0,
		"object-curly-spacing"             : 0,
		"object-property-newline"          : 0,
		"one-var"                          : 0,
		"one-var-declaration-per-line"     : 0,
		"operator-assignment"              : 0,
		"operator-linebreak"               : 0,
		"padded-blocks"                    : [2, "never"],
		"padding-line-between-statements"  : 0,
		"prefer-object-spread"             : 0,
		"quote-props"                      : 0,
		"quotes"                           : [2, "double", {"avoidEscape" : true}],
		"require-jsdoc"                    : 0,
		"semi"                             : [2, "always"],
		"semi-spacing"                     : 0,
		"semi-style"                       : [2, "last"],
		"sort-keys"                        : 0,
		"sort-vars"                        : 0,
		"space-before-blocks"              : [2, "always"],
		"space-before-function-paren"      : [2, "never"],
		"space-in-parens"                  : 0,
		"space-infix-ops"                  : 0,
		"space-unary-ops"                  : 2,
		"spaced-comment"                   : 0,
		"switch-colon-spacing"             : [2, {"after" : true, "before" : false}],
		"template-tag-spacing"             : 2,
		"unicode-bom"                      : 0,
		"wrap-regex"                       : 2,

		// ECMAScript 6
		"arrow-body-style"        : [2, "as-needed"],
		"arrow-parens"            : [2, "as-needed"],
		"arrow-spacing"           : [2, {"before" : true, "after" : true}],
		"constructor-super"       : 2,
		"generator-star-spacing"  : 0,
		"no-class-assign"         : 2,
		"no-confusing-arrow"      : [2, {"allowParens" : true}],
		"no-const-assign"         : 2,
		"no-dupe-class-members"   : 2,
		"no-duplicate-imports"    : 2,
		"no-new-symbol"           : 2,
		"no-restricted-imports"   : 0,
		"no-this-before-super"    : 2,
		"no-useless-computed-key" : 2,
		"no-useless-constructor"  : 2,
		"no-useless-rename"       : 0,
		"no-var"                  : 2,
		"object-shorthand"        : [2, "always"],
		"prefer-arrow-callback"   : [2, {"allowNamedFunctions" : true}],
		"prefer-const"            : 2,
		"prefer-destructuring"    : 0,
		"prefer-numeric-literals" : 2,
		"prefer-rest-params"      : 2,
		"prefer-spread"           : 2,
		"prefer-template"         : 0,
		"require-yield"           : 2,
		"rest-spread-spacing"     : [2, "never"],
		"sort-imports"            : 0,
		"symbol-description"      : 0,
		"template-curly-spacing"  : [2, "never"],
		"yield-star-spacing"      : 0
	}
};
<commit_msg>Enabled my 2 new rules<commit_after>"use strict";
module.exports =
{
	"env"   : { "es6" : true },
	"parserOptions" :
	{
		"ecmaVersion" : "2018",
		"sourceType"  : "script"
	},
	// Use this comment to disable a rule in a file:	/* eslint-disable <rule> */
	// Use this comment to disable a rule for a block:	/* eslint-disable <rule> */   <YOUR BLOCK HERE, MULTIPLE LINES FINE>    /* eslint-enable <rule> */
	// Use this comment to disable a rule on a line:	// eslint-disable-line <rule>

	// 0 == off
	// 1 == warn
	// 2 == error

	"plugins" : ["sembiance"],

	"rules" :
	{
		// Plugins
		"sembiance/disfavor-array-concat"       : 2,
		"sembiance/favor-includes"              : 2,
		"sembiance/tiptoe-suffix-code"          : 2,
		"sembiance/no-useless-variables"        : 2,
		"sembiance/no-accounting-format-number" : 2,
		"sembiance/no-return-setImmediate-this" : 2,
		"sembiance/prefer-array-force"          : 2,

		// New
		"multiline-comment-style"     : 0,
		"implicit-arrow-linebreak"    : 0,

		// Possible Errors
		"for-direction"                 : 2,
		"getter-return"                 : 0,
		"no-async-promise-executor"     : 2,
		"no-await-in-loop"              : 2,
		"no-compare-neg-zero"           : 2,
		"no-cond-assign"                : [2, "always"],
		"no-console"                    : 0,
		"no-constant-condition"         : [2, {"checkLoops" : false}],
		"no-control-regex"              : 2,
		"no-debugger"                   : 2,
		"no-dupe-args"                  : 2,
		"no-dupe-keys"                  : 2,
		"no-duplicate-case"             : 2,
		"no-empty"                      : [2, {"allowEmptyCatch" : true}],
		"no-empty-character-class"      : 2,
		"no-ex-assign"                  : 2,
		"no-extra-boolean-cast"         : 2,
		"no-extra-parens"               : 0,
		"no-extra-semi"                 : 2,
		"no-func-assign"                : 2,
		"no-inner-declarations"         : [2, "functions"],
		"no-invalid-regexp"             : 2,
		"no-irregular-whitespace"       : [2, {"skipStrings" : true, "skipTemplates" : true}],
		"no-obj-calls"                  : 2,
		"no-misleading-character-class" : 2,
		"no-prototype-builtins"         : 0,
		"no-regex-spaces"               : 2,
		"no-sparse-arrays"              : 2,
		"no-template-curly-in-string"   : 2,
		"no-unexpected-multiline"       : 2,
		"no-unreachable"                : 2,
		"no-unsafe-finally"             : 2,
		"no-unsafe-negation"            : 2,
		"require-atomic-updates"        : 2,
		"use-isnan"                     : 2,
		"valid-jsdoc"                   : 0,
		"valid-typeof"                  : 2,

		// Best Practices
		"accessor-pairs"               : 0,
		"array-callback-return"        : 2,
		"block-scoped-var"             : 2,
		"class-methods-use-this"       : 0,
		"complexity"                   : 0,
		"consistent-return"            : 0,
		"curly"                        : [2, "multi-or-nest", "consistent"],
		"default-case"                 : 0,
		"dot-location"                 : [2, "object"],
		"dot-notation"                 : [2, {"allowKeywords" : false}],
		"eqeqeq"                       : [2, "always"],
		"guard-for-in"                 : 2,
		"max-classes-per-file"         : 0,
		"no-alert"                     : 2,
		"no-caller"                    : 2,
		"no-case-declarations"         : 2,
		"no-div-regex"                 : 2,
		"no-else-return"               : 2,
		"no-empty-function"            : 0,
		"no-empty-pattern"             : 2,
		"no-eq-null"                   : 2,
		"no-eval"                      : 2,
		"no-extend-native"             : 0,
		"no-extra-bind"                : 2,
		"no-extra-label"               : 2,
		"no-fallthrough"               : 2,
		"no-floating-decimal"          : 2,
		"no-global-assign"             : 2,
		"no-implicit-coercion"         : 0,
		// "no-implicit-globals" : Handled in parents "node", "browser", "both"
		"no-implied-eval"              : 2,
		"no-invalid-this"              : 0,
		"no-iterator"                  : 2,
		"no-labels"                    : 2,
		"no-lone-blocks"               : 2,
		"no-loop-func"                 : 2,
		"no-magic-numbers"             : 0,
		"no-multi-spaces"              : 2,
		"no-multi-str"                 : 2,
		"no-new"                       : 2,
		"no-new-func"                  : 2,
		"no-new-wrappers"              : 2,
		"no-octal"                     : 2,
		"no-octal-escape"              : 2,
		"no-param-reassign"            : 2,
		"no-proto"                     : 2,
		"no-redeclare"                 : 2,
		"no-restricted-properties"     : 0,
		"no-return-assign"             : 2,
		"no-return-await"              : 2,
		"no-script-url"                : 2,
		"no-self-assign"               : 2,
		"no-self-compare"              : 2,
		"no-sequences"                 : 0,
		"no-throw-literal"             : 2,
		"no-unmodified-loop-condition" : 2,
		"no-unused-expressions"        : 2,
		"no-unused-labels"             : 2,
		"no-useless-call"              : 2,
		"no-useless-catch"             : 2,
		"no-useless-concat"            : 2,
		"no-useless-escape"            : 2,
		"no-useless-return"            : 2,
		"no-void"                      : 2,
		"no-warning-comments"          : 2,
		"no-with"                      : 2,
		"prefer-named-capture-group"   : 0,
		"prefer-promise-reject-errors" : 0,
		"radix"                        : 2,
		"require-await"                : 2,
		"require-unicode-regexp"       : 0,
		"vars-on-top"                  : 2,
		"wrap-iife"                    : [2, "inside"],
		"yoda"                         : 2,

		// Strict Mode
		"strict" : [2, "global"],

		// Variables
		"init-declarations"          : [2, "always"],
		"no-catch-shadow"            : 0,
		"no-delete-var"              : 2,
		"no-label-var"               : 2,
		"no-restricted-globals"      : 0,
		"no-shadow"                  : 2,
		"no-shadow-restricted-names" : 2,
		"no-undef"                   : [2, {"typeof" : true}],
		"no-undef-init"              : 0,
		"no-undefined"               : 0,
		"no-unused-vars"             : [2, {"argsIgnorePattern" : "^[iI]gnored$|^e$|^err$", "varsIgnorePattern" : "^XU$" }],
		"no-use-before-define"       : [2, {"functions" : false}],

		// Node.js and CommonJS : Handled in parents "node", "browser", "both"

		// Stylistic Issues
		"array-bracket-newline"            : 0,
		"array-bracket-spacing"            : [2, "never"],
		"array-element-newline"            : 0,
		"block-spacing"                    : 2,
		"brace-style"                      : [2, "allman", {"allowSingleLine" : true}],
		"camelcase"                        : [2, {properties : "always"}],
		"capitalized-comments"             : 0,
		"comma-dangle"                     : [2, "never"],
		"comma-spacing"                    : [2, { "before" : false, "after" : true }],
		"comma-style"                      : [2, "last"],
		"computed-property-spacing"        : [2, "never"],
		"consistent-this"                  : [2, "self"],
		"eol-last"                         : [2, "always"],
		"func-call-spacing"                : [2, "never"],
		"func-name-matching"               : 0,
		"func-names"                       : [2, "as-needed"],
		"func-style"                       : 0,
		"function-paren-newline"           : [2, "consistent"],
		"id-blacklist"                     : 0,
		"id-length"                        : 0,
		"id-match"                         : 0,
		"indent"                           : [2, "tab", {"SwitchCase" : 1}],
		"jsx-quotes"                       : 0,
		"key-spacing"                      : [2, {"beforeColon" : true, "afterColon" : true, "mode" : "minimum"}],
		"keyword-spacing"                  : 0,
		"line-comment-position"            : 0,
		"linebreak-style"                  : [2, "unix"],
		"lines-around-comment"             : 0,
		"max-depth"                        : [2, 5],
		"max-len"                          : [2, 271],
		"max-lines"                        : 0,
		"max-lines-per-function"           : 0,
		"max-nested-callbacks"             : [2, 5],
		"max-params"                       : [2, 7],
		"max-statements"                   : 0,
		"max-statements-per-line"          : 0,
		"multiline-ternary"                : [2, "never"],
		"new-cap"                          : 2,
		"new-parens"                       : 2,
		"newline-per-chained-call"         : 0,
		"no-array-constructor"             : 2,
		"no-bitwise"                       : 2,
		"no-continue"                      : 0,
		"no-inline-comments"               : 0,
		"no-lonely-if"                     : 2,
		"no-mixed-operators"               : 2,
		"no-mixed-spaces-and-tabs"         : [2, "smart-tabs"],
		"no-multi-assign"                  : 0,
		"no-multiple-empty-lines"          : 2,
		"no-negated-condition"             : 0,
		"no-nested-ternary"                : 0,
		"no-new-object"                    : 2,
		"no-plusplus"                      : 0,
		"no-restricted-syntax"             : 0,
		"no-tabs"                          : 0,
		"no-ternary"                       : 0,
		"no-trailing-spaces"               : [2, {"skipBlankLines" : true}],
		"no-underscore-dangle"             : [2, { "allow" : ["_gsTransform"]}],
		"no-unneeded-ternary"              : 2,
		"no-whitespace-before-property"    : 2,
		"nonblock-statement-body-position" : [2, "below"],
		"object-curly-newline"             : 0,
		"object-curly-spacing"             : 0,
		"object-property-newline"          : 0,
		"one-var"                          : 0,
		"one-var-declaration-per-line"     : 0,
		"operator-assignment"              : 0,
		"operator-linebreak"               : 0,
		"padded-blocks"                    : [2, "never"],
		"padding-line-between-statements"  : 0,
		"prefer-object-spread"             : 0,
		"quote-props"                      : 0,
		"quotes"                           : [2, "double", {"avoidEscape" : true}],
		"require-jsdoc"                    : 0,
		"semi"                             : [2, "always"],
		"semi-spacing"                     : 0,
		"semi-style"                       : [2, "last"],
		"sort-keys"                        : 0,
		"sort-vars"                        : 0,
		"space-before-blocks"              : [2, "always"],
		"space-before-function-paren"      : [2, "never"],
		"space-in-parens"                  : 0,
		"space-infix-ops"                  : 0,
		"space-unary-ops"                  : 2,
		"spaced-comment"                   : 0,
		"switch-colon-spacing"             : [2, {"after" : true, "before" : false}],
		"template-tag-spacing"             : 2,
		"unicode-bom"                      : 0,
		"wrap-regex"                       : 2,

		// ECMAScript 6
		"arrow-body-style"        : [2, "as-needed"],
		"arrow-parens"            : [2, "as-needed"],
		"arrow-spacing"           : [2, {"before" : true, "after" : true}],
		"constructor-super"       : 2,
		"generator-star-spacing"  : 0,
		"no-class-assign"         : 2,
		"no-confusing-arrow"      : [2, {"allowParens" : true}],
		"no-const-assign"         : 2,
		"no-dupe-class-members"   : 2,
		"no-duplicate-imports"    : 2,
		"no-new-symbol"           : 2,
		"no-restricted-imports"   : 0,
		"no-this-before-super"    : 2,
		"no-useless-computed-key" : 2,
		"no-useless-constructor"  : 2,
		"no-useless-rename"       : 0,
		"no-var"                  : 2,
		"object-shorthand"        : [2, "always"],
		"prefer-arrow-callback"   : [2, {"allowNamedFunctions" : true}],
		"prefer-const"            : 2,
		"prefer-destructuring"    : 0,
		"prefer-numeric-literals" : 2,
		"prefer-rest-params"      : 2,
		"prefer-spread"           : 2,
		"prefer-template"         : 0,
		"require-yield"           : 2,
		"rest-spread-spacing"     : [2, "never"],
		"sort-imports"            : 0,
		"symbol-description"      : 0,
		"template-curly-spacing"  : [2, "never"],
		"yield-star-spacing"      : 0
	}
};
<|endoftext|>


<commit_before>'use strict';

const AnnouncementType = {
    SURVEY: 'survey',
    FUNDRAISING: 'fundraising'
};

const type = AnnouncementType.FUNDRAISING;
const activeWiki = 'en.wikipedia.org';
const startTime = '2017-11-30T16:00:00Z';
const endTime = '2017-12-31T00:00:00Z';
const idPrefix = 'EN1217';
const androidDestinationUrl
    = 'https://donate.wikimedia.org/?uselang=en&utm_medium=WikipediaAppFeed&utm_campaign=Android&utm_source=app_201712_6C_control';
const iosDestinationUrl
    = 'https://donate.wikimedia.org/?uselang=en&utm_medium=WikipediaAppFeed&utm_campaign=iOS&utm_source=app_201712_6C_control';
// TODO: consider removing jshint
// const imageUrl = undefined; // no image this time
const buttonLabel = 'Donate now';
const disclaimerHtml
    = 'By submitting, you are agreeing to our donor privacy policy.';

const countryVariants = [ {
    countryCode: 'US',
    country: 'the U.S.',
    currency: '$',
    average: 15,
    coffee: 3
}, {
    countryCode: 'GB',
    country: 'the UK',
    currency: '£',
    average: 10,
    coffee: 2
}, {
    countryCode: 'AU',
    country: 'Australia',
    currency: '$',
    average: 15,
    coffee: 3
}, {
    countryCode: 'CA',
    country: 'Canada',
    currency: '$',
    average: 15,
    coffee: 3
}, {
    countryCode: 'NZ',
    country: 'New Zealand',
    currency: '$',
    average: 15,
    coffee: 3
}, {
    countryCode: 'IE',
    country: 'Ireland',
    currency: '€',
    average: 10,
    coffee: 2
}];

/**
 * Builds the body text. No HTML here since iOS doesn't support it.
 * @param {!object} vars an Object holding the variables for text substitution
 */
const buildBaseBodyText = ({ country, currency, average, coffee }) => {
    // replaced %COUNTRY% with ${country}, ...
    /* eslint-disable max-len */
    return `Hi reader in ${country}, it seems you use Wikipedia a lot; I think that’s great and hope you find it useful.

It’s a little awkward to ask, but today we need your help. We depend on donations averaging ${currency}${average}, but fewer than 1% of readers choose to give. If you donate just ${currency}${coffee}, you would help keep Wikipedia thriving for years. That’s right, the price of a cup of coffee is all I ask. Please take a minute to keep Wikipedia growing.

Thank you. — Jimmy Wales, Wikipedia Founder`;
    /* eslint-enable max-len */
};

module.exports = {
    activeWiki,
    startTime,
    endTime,
    idPrefix,
    type,
    androidDestinationUrl,
    iosDestinationUrl,
    // imageUrl,
    buttonLabel,
    disclaimerHtml,
    countryVariants,
    buildBaseBodyText
};
<commit_msg>Adjust end time for fundraising announcements<commit_after>'use strict';

const AnnouncementType = {
    SURVEY: 'survey',
    FUNDRAISING: 'fundraising'
};

const type = AnnouncementType.FUNDRAISING;
const activeWiki = 'en.wikipedia.org';
const startTime = '2017-11-30T16:00:00Z';
const endTime = '2017-12-20T23:59:00Z';
const idPrefix = 'EN1217';
const androidDestinationUrl
    = 'https://donate.wikimedia.org/?uselang=en&utm_medium=WikipediaAppFeed&utm_campaign=Android&utm_source=app_201712_6C_control';
const iosDestinationUrl
    = 'https://donate.wikimedia.org/?uselang=en&utm_medium=WikipediaAppFeed&utm_campaign=iOS&utm_source=app_201712_6C_control';
// TODO: consider removing jshint
// const imageUrl = undefined; // no image this time
const buttonLabel = 'Donate now';
const disclaimerHtml
    = 'By submitting, you are agreeing to our donor privacy policy.';

const countryVariants = [ {
    countryCode: 'US',
    country: 'the U.S.',
    currency: '$',
    average: 15,
    coffee: 3
}, {
    countryCode: 'GB',
    country: 'the UK',
    currency: '£',
    average: 10,
    coffee: 2
}, {
    countryCode: 'AU',
    country: 'Australia',
    currency: '$',
    average: 15,
    coffee: 3
}, {
    countryCode: 'CA',
    country: 'Canada',
    currency: '$',
    average: 15,
    coffee: 3
}, {
    countryCode: 'NZ',
    country: 'New Zealand',
    currency: '$',
    average: 15,
    coffee: 3
}, {
    countryCode: 'IE',
    country: 'Ireland',
    currency: '€',
    average: 10,
    coffee: 2
}];

/**
 * Builds the body text. No HTML here since iOS doesn't support it.
 * @param {!object} vars an Object holding the variables for text substitution
 */
const buildBaseBodyText = ({ country, currency, average, coffee }) => {
    // replaced %COUNTRY% with ${country}, ...
    /* eslint-disable max-len */
    return `Hi reader in ${country}, it seems you use Wikipedia a lot; I think that’s great and hope you find it useful.

It’s a little awkward to ask, but today we need your help. We depend on donations averaging ${currency}${average}, but fewer than 1% of readers choose to give. If you donate just ${currency}${coffee}, you would help keep Wikipedia thriving for years. That’s right, the price of a cup of coffee is all I ask. Please take a minute to keep Wikipedia growing.

Thank you. — Jimmy Wales, Wikipedia Founder`;
    /* eslint-enable max-len */
};

module.exports = {
    activeWiki,
    startTime,
    endTime,
    idPrefix,
    type,
    androidDestinationUrl,
    iosDestinationUrl,
    // imageUrl,
    buttonLabel,
    disclaimerHtml,
    countryVariants,
    buildBaseBodyText
};
<|endoftext|>