(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
(function (process,global){
/*!
 * @overview es6-promise - a tiny implementation of Promises/A+.
 * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
 * @license   Licensed under MIT license
 *            See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
 * @version   v4.2.4+314e4831
 */

(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
	typeof define === 'function' && define.amd ? define(factory) :
	(global.ES6Promise = factory());
}(this, (function () { 'use strict';

function objectOrFunction(x) {
  var type = typeof x;
  return x !== null && (type === 'object' || type === 'function');
}

function isFunction(x) {
  return typeof x === 'function';
}



var _isArray = void 0;
if (Array.isArray) {
  _isArray = Array.isArray;
} else {
  _isArray = function (x) {
    return Object.prototype.toString.call(x) === '[object Array]';
  };
}

var isArray = _isArray;

var len = 0;
var vertxNext = void 0;
var customSchedulerFn = void 0;

var asap = function asap(callback, arg) {
  queue[len] = callback;
  queue[len + 1] = arg;
  len += 2;
  if (len === 2) {
    // If len is 2, that means that we need to schedule an async flush.
    // If additional callbacks are queued before the queue is flushed, they
    // will be processed by this flush that we are scheduling.
    if (customSchedulerFn) {
      customSchedulerFn(flush);
    } else {
      scheduleFlush();
    }
  }
};

function setScheduler(scheduleFn) {
  customSchedulerFn = scheduleFn;
}

function setAsap(asapFn) {
  asap = asapFn;
}

var browserWindow = typeof window !== 'undefined' ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';

// test for web worker but not in IE10
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';

// node
function useNextTick() {
  // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  // see https://github.com/cujojs/when/issues/410 for details
  return function () {
    return process.nextTick(flush);
  };
}

// vertx
function useVertxTimer() {
  if (typeof vertxNext !== 'undefined') {
    return function () {
      vertxNext(flush);
    };
  }

  return useSetTimeout();
}

function useMutationObserver() {
  var iterations = 0;
  var observer = new BrowserMutationObserver(flush);
  var node = document.createTextNode('');
  observer.observe(node, { characterData: true });

  return function () {
    node.data = iterations = ++iterations % 2;
  };
}

// web worker
function useMessageChannel() {
  var channel = new MessageChannel();
  channel.port1.onmessage = flush;
  return function () {
    return channel.port2.postMessage(0);
  };
}

function useSetTimeout() {
  // Store setTimeout reference so es6-promise will be unaffected by
  // other code modifying setTimeout (like sinon.useFakeTimers())
  var globalSetTimeout = setTimeout;
  return function () {
    return globalSetTimeout(flush, 1);
  };
}

var queue = new Array(1000);
function flush() {
  for (var i = 0; i < len; i += 2) {
    var callback = queue[i];
    var arg = queue[i + 1];

    callback(arg);

    queue[i] = undefined;
    queue[i + 1] = undefined;
  }

  len = 0;
}

function attemptVertx() {
  try {
    var vertx = Function('return this')().require('vertx');
    vertxNext = vertx.runOnLoop || vertx.runOnContext;
    return useVertxTimer();
  } catch (e) {
    return useSetTimeout();
  }
}

var scheduleFlush = void 0;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
  scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
  scheduleFlush = useMutationObserver();
} else if (isWorker) {
  scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && typeof require === 'function') {
  scheduleFlush = attemptVertx();
} else {
  scheduleFlush = useSetTimeout();
}

function then(onFulfillment, onRejection) {
  var parent = this;

  var child = new this.constructor(noop);

  if (child[PROMISE_ID] === undefined) {
    makePromise(child);
  }

  var _state = parent._state;


  if (_state) {
    var callback = arguments[_state - 1];
    asap(function () {
      return invokeCallback(_state, child, callback, parent._result);
    });
  } else {
    subscribe(parent, child, onFulfillment, onRejection);
  }

  return child;
}

/**
  `Promise.resolve` returns a promise that will become resolved with the
  passed `value`. It is shorthand for the following:

  ```javascript
  let promise = new Promise(function(resolve, reject){
    resolve(1);
  });

  promise.then(function(value){
    // value === 1
  });
  ```

  Instead of writing the above, your code now simply becomes the following:

  ```javascript
  let promise = Promise.resolve(1);

  promise.then(function(value){
    // value === 1
  });
  ```

  @method resolve
  @static
  @param {Any} value value that the returned promise will be resolved with
  Useful for tooling.
  @return {Promise} a promise that will become fulfilled with the given
  `value`
*/
function resolve$1(object) {
  /*jshint validthis:true */
  var Constructor = this;

  if (object && typeof object === 'object' && object.constructor === Constructor) {
    return object;
  }

  var promise = new Constructor(noop);
  resolve(promise, object);
  return promise;
}

var PROMISE_ID = Math.random().toString(36).substring(2);

function noop() {}

var PENDING = void 0;
var FULFILLED = 1;
var REJECTED = 2;

var TRY_CATCH_ERROR = { error: null };

function selfFulfillment() {
  return new TypeError("You cannot resolve a promise with itself");
}

function cannotReturnOwn() {
  return new TypeError('A promises callback cannot return that same promise.');
}

function getThen(promise) {
  try {
    return promise.then;
  } catch (error) {
    TRY_CATCH_ERROR.error = error;
    return TRY_CATCH_ERROR;
  }
}

function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
  try {
    then$$1.call(value, fulfillmentHandler, rejectionHandler);
  } catch (e) {
    return e;
  }
}

function handleForeignThenable(promise, thenable, then$$1) {
  asap(function (promise) {
    var sealed = false;
    var error = tryThen(then$$1, thenable, function (value) {
      if (sealed) {
        return;
      }
      sealed = true;
      if (thenable !== value) {
        resolve(promise, value);
      } else {
        fulfill(promise, value);
      }
    }, function (reason) {
      if (sealed) {
        return;
      }
      sealed = true;

      reject(promise, reason);
    }, 'Settle: ' + (promise._label || ' unknown promise'));

    if (!sealed && error) {
      sealed = true;
      reject(promise, error);
    }
  }, promise);
}

function handleOwnThenable(promise, thenable) {
  if (thenable._state === FULFILLED) {
    fulfill(promise, thenable._result);
  } else if (thenable._state === REJECTED) {
    reject(promise, thenable._result);
  } else {
    subscribe(thenable, undefined, function (value) {
      return resolve(promise, value);
    }, function (reason) {
      return reject(promise, reason);
    });
  }
}

function handleMaybeThenable(promise, maybeThenable, then$$1) {
  if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
    handleOwnThenable(promise, maybeThenable);
  } else {
    if (then$$1 === TRY_CATCH_ERROR) {
      reject(promise, TRY_CATCH_ERROR.error);
      TRY_CATCH_ERROR.error = null;
    } else if (then$$1 === undefined) {
      fulfill(promise, maybeThenable);
    } else if (isFunction(then$$1)) {
      handleForeignThenable(promise, maybeThenable, then$$1);
    } else {
      fulfill(promise, maybeThenable);
    }
  }
}

function resolve(promise, value) {
  if (promise === value) {
    reject(promise, selfFulfillment());
  } else if (objectOrFunction(value)) {
    handleMaybeThenable(promise, value, getThen(value));
  } else {
    fulfill(promise, value);
  }
}

function publishRejection(promise) {
  if (promise._onerror) {
    promise._onerror(promise._result);
  }

  publish(promise);
}

function fulfill(promise, value) {
  if (promise._state !== PENDING) {
    return;
  }

  promise._result = value;
  promise._state = FULFILLED;

  if (promise._subscribers.length !== 0) {
    asap(publish, promise);
  }
}

function reject(promise, reason) {
  if (promise._state !== PENDING) {
    return;
  }
  promise._state = REJECTED;
  promise._result = reason;

  asap(publishRejection, promise);
}

function subscribe(parent, child, onFulfillment, onRejection) {
  var _subscribers = parent._subscribers;
  var length = _subscribers.length;


  parent._onerror = null;

  _subscribers[length] = child;
  _subscribers[length + FULFILLED] = onFulfillment;
  _subscribers[length + REJECTED] = onRejection;

  if (length === 0 && parent._state) {
    asap(publish, parent);
  }
}

function publish(promise) {
  var subscribers = promise._subscribers;
  var settled = promise._state;

  if (subscribers.length === 0) {
    return;
  }

  var child = void 0,
      callback = void 0,
      detail = promise._result;

  for (var i = 0; i < subscribers.length; i += 3) {
    child = subscribers[i];
    callback = subscribers[i + settled];

    if (child) {
      invokeCallback(settled, child, callback, detail);
    } else {
      callback(detail);
    }
  }

  promise._subscribers.length = 0;
}

function tryCatch(callback, detail) {
  try {
    return callback(detail);
  } catch (e) {
    TRY_CATCH_ERROR.error = e;
    return TRY_CATCH_ERROR;
  }
}

function invokeCallback(settled, promise, callback, detail) {
  var hasCallback = isFunction(callback),
      value = void 0,
      error = void 0,
      succeeded = void 0,
      failed = void 0;

  if (hasCallback) {
    value = tryCatch(callback, detail);

    if (value === TRY_CATCH_ERROR) {
      failed = true;
      error = value.error;
      value.error = null;
    } else {
      succeeded = true;
    }

    if (promise === value) {
      reject(promise, cannotReturnOwn());
      return;
    }
  } else {
    value = detail;
    succeeded = true;
  }

  if (promise._state !== PENDING) {
    // noop
  } else if (hasCallback && succeeded) {
    resolve(promise, value);
  } else if (failed) {
    reject(promise, error);
  } else if (settled === FULFILLED) {
    fulfill(promise, value);
  } else if (settled === REJECTED) {
    reject(promise, value);
  }
}

function initializePromise(promise, resolver) {
  try {
    resolver(function resolvePromise(value) {
      resolve(promise, value);
    }, function rejectPromise(reason) {
      reject(promise, reason);
    });
  } catch (e) {
    reject(promise, e);
  }
}

var id = 0;
function nextId() {
  return id++;
}

function makePromise(promise) {
  promise[PROMISE_ID] = id++;
  promise._state = undefined;
  promise._result = undefined;
  promise._subscribers = [];
}

function validationError() {
  return new Error('Array Methods must be provided an Array');
}

var Enumerator = function () {
  function Enumerator(Constructor, input) {
    this._instanceConstructor = Constructor;
    this.promise = new Constructor(noop);

    if (!this.promise[PROMISE_ID]) {
      makePromise(this.promise);
    }

    if (isArray(input)) {
      this.length = input.length;
      this._remaining = input.length;

      this._result = new Array(this.length);

      if (this.length === 0) {
        fulfill(this.promise, this._result);
      } else {
        this.length = this.length || 0;
        this._enumerate(input);
        if (this._remaining === 0) {
          fulfill(this.promise, this._result);
        }
      }
    } else {
      reject(this.promise, validationError());
    }
  }

  Enumerator.prototype._enumerate = function _enumerate(input) {
    for (var i = 0; this._state === PENDING && i < input.length; i++) {
      this._eachEntry(input[i], i);
    }
  };

  Enumerator.prototype._eachEntry = function _eachEntry(entry, i) {
    var c = this._instanceConstructor;
    var resolve$$1 = c.resolve;


    if (resolve$$1 === resolve$1) {
      var _then = getThen(entry);

      if (_then === then && entry._state !== PENDING) {
        this._settledAt(entry._state, i, entry._result);
      } else if (typeof _then !== 'function') {
        this._remaining--;
        this._result[i] = entry;
      } else if (c === Promise$1) {
        var promise = new c(noop);
        handleMaybeThenable(promise, entry, _then);
        this._willSettleAt(promise, i);
      } else {
        this._willSettleAt(new c(function (resolve$$1) {
          return resolve$$1(entry);
        }), i);
      }
    } else {
      this._willSettleAt(resolve$$1(entry), i);
    }
  };

  Enumerator.prototype._settledAt = function _settledAt(state, i, value) {
    var promise = this.promise;


    if (promise._state === PENDING) {
      this._remaining--;

      if (state === REJECTED) {
        reject(promise, value);
      } else {
        this._result[i] = value;
      }
    }

    if (this._remaining === 0) {
      fulfill(promise, this._result);
    }
  };

  Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) {
    var enumerator = this;

    subscribe(promise, undefined, function (value) {
      return enumerator._settledAt(FULFILLED, i, value);
    }, function (reason) {
      return enumerator._settledAt(REJECTED, i, reason);
    });
  };

  return Enumerator;
}();

/**
  `Promise.all` accepts an array of promises, and returns a new promise which
  is fulfilled with an array of fulfillment values for the passed promises, or
  rejected with the reason of the first passed promise to be rejected. It casts all
  elements of the passed iterable to promises as it runs this algorithm.

  Example:

  ```javascript
  let promise1 = resolve(1);
  let promise2 = resolve(2);
  let promise3 = resolve(3);
  let promises = [ promise1, promise2, promise3 ];

  Promise.all(promises).then(function(array){
    // The array here would be [ 1, 2, 3 ];
  });
  ```

  If any of the `promises` given to `all` are rejected, the first promise
  that is rejected will be given as an argument to the returned promises's
  rejection handler. For example:

  Example:

  ```javascript
  let promise1 = resolve(1);
  let promise2 = reject(new Error("2"));
  let promise3 = reject(new Error("3"));
  let promises = [ promise1, promise2, promise3 ];

  Promise.all(promises).then(function(array){
    // Code here never runs because there are rejected promises!
  }, function(error) {
    // error.message === "2"
  });
  ```

  @method all
  @static
  @param {Array} entries array of promises
  @param {String} label optional string for labeling the promise.
  Useful for tooling.
  @return {Promise} promise that is fulfilled when all `promises` have been
  fulfilled, or rejected if any of them become rejected.
  @static
*/
function all(entries) {
  return new Enumerator(this, entries).promise;
}

/**
  `Promise.race` returns a new promise which is settled in the same way as the
  first passed promise to settle.

  Example:

  ```javascript
  let promise1 = new Promise(function(resolve, reject){
    setTimeout(function(){
      resolve('promise 1');
    }, 200);
  });

  let promise2 = new Promise(function(resolve, reject){
    setTimeout(function(){
      resolve('promise 2');
    }, 100);
  });

  Promise.race([promise1, promise2]).then(function(result){
    // result === 'promise 2' because it was resolved before promise1
    // was resolved.
  });
  ```

  `Promise.race` is deterministic in that only the state of the first
  settled promise matters. For example, even if other promises given to the
  `promises` array argument are resolved, but the first settled promise has
  become rejected before the other promises became fulfilled, the returned
  promise will become rejected:

  ```javascript
  let promise1 = new Promise(function(resolve, reject){
    setTimeout(function(){
      resolve('promise 1');
    }, 200);
  });

  let promise2 = new Promise(function(resolve, reject){
    setTimeout(function(){
      reject(new Error('promise 2'));
    }, 100);
  });

  Promise.race([promise1, promise2]).then(function(result){
    // Code here never runs
  }, function(reason){
    // reason.message === 'promise 2' because promise 2 became rejected before
    // promise 1 became fulfilled
  });
  ```

  An example real-world use case is implementing timeouts:

  ```javascript
  Promise.race([ajax('foo.json'), timeout(5000)])
  ```

  @method race
  @static
  @param {Array} promises array of promises to observe
  Useful for tooling.
  @return {Promise} a promise which settles in the same way as the first passed
  promise to settle.
*/
function race(entries) {
  /*jshint validthis:true */
  var Constructor = this;

  if (!isArray(entries)) {
    return new Constructor(function (_, reject) {
      return reject(new TypeError('You must pass an array to race.'));
    });
  } else {
    return new Constructor(function (resolve, reject) {
      var length = entries.length;
      for (var i = 0; i < length; i++) {
        Constructor.resolve(entries[i]).then(resolve, reject);
      }
    });
  }
}

/**
  `Promise.reject` returns a promise rejected with the passed `reason`.
  It is shorthand for the following:

  ```javascript
  let promise = new Promise(function(resolve, reject){
    reject(new Error('WHOOPS'));
  });

  promise.then(function(value){
    // Code here doesn't run because the promise is rejected!
  }, function(reason){
    // reason.message === 'WHOOPS'
  });
  ```

  Instead of writing the above, your code now simply becomes the following:

  ```javascript
  let promise = Promise.reject(new Error('WHOOPS'));

  promise.then(function(value){
    // Code here doesn't run because the promise is rejected!
  }, function(reason){
    // reason.message === 'WHOOPS'
  });
  ```

  @method reject
  @static
  @param {Any} reason value that the returned promise will be rejected with.
  Useful for tooling.
  @return {Promise} a promise rejected with the given `reason`.
*/
function reject$1(reason) {
  /*jshint validthis:true */
  var Constructor = this;
  var promise = new Constructor(noop);
  reject(promise, reason);
  return promise;
}

function needsResolver() {
  throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}

function needsNew() {
  throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}

/**
  Promise objects represent the eventual result of an asynchronous operation. The
  primary way of interacting with a promise is through its `then` method, which
  registers callbacks to receive either a promise's eventual value or the reason
  why the promise cannot be fulfilled.

  Terminology
  -----------

  - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  - `thenable` is an object or function that defines a `then` method.
  - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  - `exception` is a value that is thrown using the throw statement.
  - `reason` is a value that indicates why a promise was rejected.
  - `settled` the final resting state of a promise, fulfilled or rejected.

  A promise can be in one of three states: pending, fulfilled, or rejected.

  Promises that are fulfilled have a fulfillment value and are in the fulfilled
  state.  Promises that are rejected have a rejection reason and are in the
  rejected state.  A fulfillment value is never a thenable.

  Promises can also be said to *resolve* a value.  If this value is also a
  promise, then the original promise's settled state will match the value's
  settled state.  So a promise that *resolves* a promise that rejects will
  itself reject, and a promise that *resolves* a promise that fulfills will
  itself fulfill.


  Basic Usage:
  ------------

  ```js
  let promise = new Promise(function(resolve, reject) {
    // on success
    resolve(value);

    // on failure
    reject(reason);
  });

  promise.then(function(value) {
    // on fulfillment
  }, function(reason) {
    // on rejection
  });
  ```

  Advanced Usage:
  ---------------

  Promises shine when abstracting away asynchronous interactions such as
  `XMLHttpRequest`s.

  ```js
  function getJSON(url) {
    return new Promise(function(resolve, reject){
      let xhr = new XMLHttpRequest();

      xhr.open('GET', url);
      xhr.onreadystatechange = handler;
      xhr.responseType = 'json';
      xhr.setRequestHeader('Accept', 'application/json');
      xhr.send();

      function handler() {
        if (this.readyState === this.DONE) {
          if (this.status === 200) {
            resolve(this.response);
          } else {
            reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
          }
        }
      };
    });
  }

  getJSON('/posts.json').then(function(json) {
    // on fulfillment
  }, function(reason) {
    // on rejection
  });
  ```

  Unlike callbacks, promises are great composable primitives.

  ```js
  Promise.all([
    getJSON('/posts'),
    getJSON('/comments')
  ]).then(function(values){
    values[0] // => postsJSON
    values[1] // => commentsJSON

    return values;
  });
  ```

  @class Promise
  @param {Function} resolver
  Useful for tooling.
  @constructor
*/

var Promise$1 = function () {
  function Promise(resolver) {
    this[PROMISE_ID] = nextId();
    this._result = this._state = undefined;
    this._subscribers = [];

    if (noop !== resolver) {
      typeof resolver !== 'function' && needsResolver();
      this instanceof Promise ? initializePromise(this, resolver) : needsNew();
    }
  }

  /**
  The primary way of interacting with a promise is through its `then` method,
  which registers callbacks to receive either a promise's eventual value or the
  reason why the promise cannot be fulfilled.
   ```js
  findUser().then(function(user){
    // user is available
  }, function(reason){
    // user is unavailable, and you are given the reason why
  });
  ```
   Chaining
  --------
   The return value of `then` is itself a promise.  This second, 'downstream'
  promise is resolved with the return value of the first promise's fulfillment
  or rejection handler, or rejected if the handler throws an exception.
   ```js
  findUser().then(function (user) {
    return user.name;
  }, function (reason) {
    return 'default name';
  }).then(function (userName) {
    // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
    // will be `'default name'`
  });
   findUser().then(function (user) {
    throw new Error('Found user, but still unhappy');
  }, function (reason) {
    throw new Error('`findUser` rejected and we're unhappy');
  }).then(function (value) {
    // never reached
  }, function (reason) {
    // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
    // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  });
  ```
  If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
   ```js
  findUser().then(function (user) {
    throw new PedagogicalException('Upstream error');
  }).then(function (value) {
    // never reached
  }).then(function (value) {
    // never reached
  }, function (reason) {
    // The `PedgagocialException` is propagated all the way down to here
  });
  ```
   Assimilation
  ------------
   Sometimes the value you want to propagate to a downstream promise can only be
  retrieved asynchronously. This can be achieved by returning a promise in the
  fulfillment or rejection handler. The downstream promise will then be pending
  until the returned promise is settled. This is called *assimilation*.
   ```js
  findUser().then(function (user) {
    return findCommentsByAuthor(user);
  }).then(function (comments) {
    // The user's comments are now available
  });
  ```
   If the assimliated promise rejects, then the downstream promise will also reject.
   ```js
  findUser().then(function (user) {
    return findCommentsByAuthor(user);
  }).then(function (comments) {
    // If `findCommentsByAuthor` fulfills, we'll have the value here
  }, function (reason) {
    // If `findCommentsByAuthor` rejects, we'll have the reason here
  });
  ```
   Simple Example
  --------------
   Synchronous Example
   ```javascript
  let result;
   try {
    result = findResult();
    // success
  } catch(reason) {
    // failure
  }
  ```
   Errback Example
   ```js
  findResult(function(result, err){
    if (err) {
      // failure
    } else {
      // success
    }
  });
  ```
   Promise Example;
   ```javascript
  findResult().then(function(result){
    // success
  }, function(reason){
    // failure
  });
  ```
   Advanced Example
  --------------
   Synchronous Example
   ```javascript
  let author, books;
   try {
    author = findAuthor();
    books  = findBooksByAuthor(author);
    // success
  } catch(reason) {
    // failure
  }
  ```
   Errback Example
   ```js
   function foundBooks(books) {
   }
   function failure(reason) {
   }
   findAuthor(function(author, err){
    if (err) {
      failure(err);
      // failure
    } else {
      try {
        findBoooksByAuthor(author, function(books, err) {
          if (err) {
            failure(err);
          } else {
            try {
              foundBooks(books);
            } catch(reason) {
              failure(reason);
            }
          }
        });
      } catch(error) {
        failure(err);
      }
      // success
    }
  });
  ```
   Promise Example;
   ```javascript
  findAuthor().
    then(findBooksByAuthor).
    then(function(books){
      // found books
  }).catch(function(reason){
    // something went wrong
  });
  ```
   @method then
  @param {Function} onFulfilled
  @param {Function} onRejected
  Useful for tooling.
  @return {Promise}
  */

  /**
  `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  as the catch block of a try/catch statement.
  ```js
  function findAuthor(){
  throw new Error('couldn't find that author');
  }
  // synchronous
  try {
  findAuthor();
  } catch(reason) {
  // something went wrong
  }
  // async with promises
  findAuthor().catch(function(reason){
  // something went wrong
  });
  ```
  @method catch
  @param {Function} onRejection
  Useful for tooling.
  @return {Promise}
  */


  Promise.prototype.catch = function _catch(onRejection) {
    return this.then(null, onRejection);
  };

  /**
    `finally` will be invoked regardless of the promise's fate just as native
    try/catch/finally behaves
  
    Synchronous example:
  
    ```js
    findAuthor() {
      if (Math.random() > 0.5) {
        throw new Error();
      }
      return new Author();
    }
  
    try {
      return findAuthor(); // succeed or fail
    } catch(error) {
      return findOtherAuther();
    } finally {
      // always runs
      // doesn't affect the return value
    }
    ```
  
    Asynchronous example:
  
    ```js
    findAuthor().catch(function(reason){
      return findOtherAuther();
    }).finally(function(){
      // author was either found, or not
    });
    ```
  
    @method finally
    @param {Function} callback
    @return {Promise}
  */


  Promise.prototype.finally = function _finally(callback) {
    var promise = this;
    var constructor = promise.constructor;

    return promise.then(function (value) {
      return constructor.resolve(callback()).then(function () {
        return value;
      });
    }, function (reason) {
      return constructor.resolve(callback()).then(function () {
        throw reason;
      });
    });
  };

  return Promise;
}();

Promise$1.prototype.then = then;
Promise$1.all = all;
Promise$1.race = race;
Promise$1.resolve = resolve$1;
Promise$1.reject = reject$1;
Promise$1._setScheduler = setScheduler;
Promise$1._setAsap = setAsap;
Promise$1._asap = asap;

/*global self*/
function polyfill() {
  var local = void 0;

  if (typeof global !== 'undefined') {
    local = global;
  } else if (typeof self !== 'undefined') {
    local = self;
  } else {
    try {
      local = Function('return this')();
    } catch (e) {
      throw new Error('polyfill failed because global object is unavailable in this environment');
    }
  }

  var P = local.Promise;

  if (P) {
    var promiseToString = null;
    try {
      promiseToString = Object.prototype.toString.call(P.resolve());
    } catch (e) {
      // silently ignored
    }

    if (promiseToString === '[object Promise]' && !P.cast) {
      return;
    }
  }

  local.Promise = Promise$1;
}

// Strange compat..
Promise$1.polyfill = polyfill;
Promise$1.Promise = Promise$1;

return Promise$1;

})));





}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":7}],2:[function(require,module,exports){
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _cnnConfig = require('../configs/cnn-config');

var _cnnConfig2 = _interopRequireDefault(_cnnConfig);

var _coreA = require('../core-a9-1.0');

var _coreA2 = _interopRequireDefault(_coreA);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

_coreA2.default.init(_cnnConfig2.default.A9);

exports.default = _coreA2.default;

},{"../configs/cnn-config":4,"../core-a9-1.0":5}],3:[function(require,module,exports){
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.default = {

    DEFAULT_MODULE_TIMEOUT: 1200,

    A9: {
        // Amazon A9 Settings
        A9_DOMESTIC_PUB_ID: '3159',
        A9_INTERNATIONAL_PUB_ID: '3288',
        A9_DEFAULT_DISPLAY_TIMEOUT: 1200,
        A9_DEFAULT_DISPLAY_REFRESH_TIMEOUT: 1200,
        A9_DEFAULT_VIDEO_TIMEOUT: 500, // 500ms default timeout
        A9_DEFAULT_VIDEO_REFRESH_TIMEOUT: 1000 // 1000ms default refresh timeout
    },

    BEEMRAY: {
        // Beemray Settings
        BEEMRAY_CUSTOMER_ID: '',
        BEEMRAY_API_KEY: ''
    },

    CONSOLE_TOOL: {
        CONSOLE_TOOL_HOTKEY: 'ctrl shift z',
        CREATIVE_REVIEW_HOTKEY: '^ d o h $'
    },

    CRITEO: {
        CRITEO_MULTISIZE_FIRST: 'F',
        CRITEO_MULTISIZE_LARGEST: 'L',
        CRITEO_MULTISIZE_ALL: 'A',
        CRITEO_MULTISIZE_METHOD: 'L',
        CRITEO_DESKTOP_ZONES: {},
        CRITEO_MOBILE_ZONES: {},
        CRITEO_DISPLAY_TIMEOUT: 1200
    },

    FASTLANE: {
        FASTLANE_DOMESTIC_ACCOUNT_ID: 11078,
        FASTLANE_INTERNATIONAL_ACCOUNT_ID: 11016,
        FASTLANE_DISPLAY_TIMEOUT: 1200
    },

    GUID: {},

    IAS: {
        IAS_DOMESTIC_PUB_ID: 928108,
        IAS_INTERNATIONAL_PUB_ID: 925660
    },

    IX: {
        INDEX_EXCHANGE_DOMESTIC_SCRIPT_MAP: {}
    },

    IVR: {
        IVR_DEFAULT_DISPLAY_MILLISECONDS: 35 * 1000,
        IVR_DEFAULT_DISPLAY_PERCENT: 50
    },

    KRUX: {
        KRUX_DOMESTIC_CONTROLTAG: '',
        KRUX_INTERNATIONAL_CONTROLTAG: ''
    },

    PROXIMIC: {},

    SOURCEPOINT: {},

    TRANSACTION_ID: {}
};

},{}],4:[function(require,module,exports){
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _baseConfig = require('./base-config');

var _baseConfig2 = _interopRequireDefault(_baseConfig);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

console.log(_baseConfig2.default); // import default configuration


var OPTIONS = {
    // start with default configuration

    BEEMRAY: {
        BEEMRAY_CUSTOMER_ID: 'cnn',
        BEEMRAY_API_KEY: '39a34d8d-dd1d-4fbf-aa96-fdc5f0329451'
    },
    CRITEO: {
        CRITEO_DESKTOP_ZONES: {
            '160x600': 1047134,
            '300x250': 1047135,
            '300x600': 1047136,
            '728x90': 1047137,
            'HP_970x90': 1128528,
            'HP_970x250': 1128527,
            'ROS_970x90': 1047140,
            'ROS_970x250': 1047139,
            '320x50': 1047138
        },
        CRITEO_MOBILE_ZONES: {
            '300x250': 1090825,
            '320x50': 1090883
        },
        CRITEO_MULTISIZE_METHOD: 'L',
        CRITEO_DISPLAY_TIMEOUT: 1200
    },
    IX: {
        INDEX_EXCHANGE_SCRIPT_MAP: {
            '^(.*\\.)?(www\\.)?cnn\\.com': {
                intl: '186370-96070407099023',
                dom: '186948-60896576130421'
            },
            '^(.*\\.)?edition\\.cnn\\.com': '186370-129055748395673',
            '^(.*\\.)?us\\.cnn\\.com': '186370-96070407099023'
        }
    },
    KRUX: {
        KRUX_DOMESTIC_CONTROLTAG: 'ITb_4eqO',
        KRUX_INTERNATIONAL_CONTROLTAG: 'ITb_9Zup'
    }
};
exports.default = Object.assign(_baseConfig2.default, OPTIONS);

},{"./base-config":3}],5:[function(require,module,exports){

'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _core = require('./core');

require('es6-promise');

var MODULE_NAME = 'Amazon A9';
var MODULE_VERSION = 'v1.3.12';

var blocked = false;

var a9bids = void 0; // display a9 bid cache
var bidSlots = []; // slots sent to a9 for auction
var videoBid = null; // cached video bid
var defaultTimeout = 500; // 500ms default timeout
var defaultRefreshTimeout = 1000; // 1000ms default refresh timeout
var targetingPromise = null;
var logger = (0, _core.getLogger)(MODULE_NAME, MODULE_VERSION);

var storeVideoBid = function storeVideoBid(bid) {
    videoBid = Object.assign({}, bid);
};

var getTargetingData = function getTargetingData(timeout) {
    timeout = timeout || defaultTimeout;
    var timeoutOverride = (0, _core.getURLParam)('mdt');
    if (timeoutOverride) {
        timeout = timeoutOverride;
        logger.log('Overriding Max Duration Time: ', timeout);
    }
    if (videoBid !== null) return new Promise(function (resolve) {
        resolve(videoBid);
    });
    var timeoutFunction = function timeoutFunction(resolve, reject) {
        window.targetingTimeoutId = setTimeout(function () {
            logger.log('getTargetingData timed out after ' + timeout + 'ms.');
            clearTimeout(window.targetingTimeoutId);
            reject('getTargetingData timed out after ' + timeout + 'ms.');
        }, timeout);
    };
    var wrappedFunction = function wrappedFunction(resolve) {
        logger.log('Getting A9 Video targeting...');
        var innerFunction = function innerFunction(bids) {
            clearTimeout(window.targetingTimeoutId);
            var targetBid = {};
            bids.forEach(function (bid) {
                if (bid.slotID.startsWith('aps-')) {
                    targetBid = bid;
                }
            });
            var result = {
                'amznbid': targetBid.amznbid || '',
                'amzniid': targetBid.amzniid || ''
            };
            storeVideoBid(result);
            return result;
        };
        targetingPromise.then(function (bids) {
            resolve(innerFunction(bids));
        });
    };
    var wrappedCallback = new Promise(wrappedFunction);
    var timeoutCallback = new Promise(timeoutFunction);

    // Returns a race between the timeout and the passed in promise
    return Promise.race([timeoutCallback, wrappedCallback]);
};

var getRefreshedTargetingData = function getRefreshedTargetingData(slotName, timeout) {
    timeout = timeout || defaultRefreshTimeout;
    slotName = slotName || 'aps-midroll';
    var timeoutOverride = (0, _core.getURLParam)('mdt');
    var slotNameOverride = (0, _core.getURLParam)('slotname');
    if (timeoutOverride) {
        timeout = timeoutOverride;
        logger.log('Overriding Max Duration Time: ', timeout);
    }
    if (slotNameOverride) {
        slotName = slotNameOverride;
        logger.log('Overriding Slot Name: ', slotName);
    }
    var timeoutFunction = function timeoutFunction(resolve, reject) {
        window.targetingTimeoutId = setTimeout(function () {
            logger.log('getRefreshedTargetingData timed out after ' + timeout + 'ms.');
            clearTimeout(window.targetingTimeoutId);
            reject('getRefreshedTargetingData timed out after ' + timeout + 'ms.');
        }, timeout);
    };
    var wrappedFunction = function wrappedFunction(resolve) {
        targetingPromise = new Promise(function (resolve) {
            window.apstag.fetchBids({
                slots: [{
                    slotID: slotName,
                    mediaType: 'video'
                }]
            }, resolve);
        });
        var innerFunction = function innerFunction(bids) {
            clearTimeout(window.targetingTimeoutId);
            var targetBid = {};
            bids.forEach(function (bid) {
                if (bid.slotID === slotName) {
                    targetBid = bid;
                }
            });
            var result = {
                'amznbid': targetBid.amznbid || '',
                'amzniid': targetBid.amzniid || ''
            };
            storeVideoBid(result);
            resolve(result);
        };
        logger.log('Refreshing A9 Video targeting...');
        targetingPromise.then(innerFunction);
    };
    var wrappedCallback = new Promise(wrappedFunction);
    var timeoutCallback = new Promise(timeoutFunction);

    // Returns a race between the timeout and the passed in promise
    return Promise.race([timeoutCallback, wrappedCallback]);
};

var keyGPTSlots = function keyGPTSlots(slots) {
    return slots.reduce(function (o, slot) {
        var slotId = slot.getSlotElementId();
        o[slotId] = slot;
        return o;
    }, {});
};

var handleA9Bids = function handleA9Bids(bids, gptSlots, done) {
    logger.log('Handling A9 Bids:', bids, gptSlots);
    logger.time('Handling A9 Bids');
    window.googletag.cmd.push(function () {
        var slots = keyGPTSlots(gptSlots);
        bids.forEach(function (bid) {
            var gptSlot = slots[bid.slotID] || null;
            if (gptSlot !== null) {
                var targets = {};
                window.apstag.targetingKeys('display').forEach(function (key) {
                    if ((0, _core.getURLParam)('debug') === 'true') {
                        logger.log('[AdFuelModule - Amazon A9] Setting A9 Targeting: ', { key: key, value: bid[key] });
                    }
                    targets[key] = bid[key];
                    gptSlot.setTargeting(key, bid[key]);
                });
                _core.metricApi.addMetric({
                    type: 'vendor',
                    id: 'Amazon A9',
                    data: { targeting: targets }
                });
            }
        });
        window.googletag.pubads().addEventListener('slotRenderEnded', function (e) {
            var gptSlots = keyGPTSlots(window.googletag.pubads().getSlots());
            var gptSlot = gptSlots[e.slot.getSlotElementId()];
            window.apstag.targetingKeys('display').forEach(function (key) {
                gptSlot.setTargeting(key, '');
            });
        });
    });
    logger.timeEnd('Handling A9 Bids');
    done();
};

var preQueueCallback = function preQueueCallback(assets, done) {
    logger.time('A9 Slot Building');
    var browser = (0, _core.getViewport)();
    logger.log('Browser Dimensions: ', browser);
    assets.forEach(function (asset) {
        var slotId = asset.originalElementId || asset.rktr_slot_id;
        var pieces = slotId.split('_');
        pieces.splice(0, 1);
        slotId = pieces.join('_');
        logger.log('Checking slot and sizes for validity: ', slotId);
        var isValid = (0, _core.isMonetized)(asset);
        if (isValid) {
            logger.log('Valid Slot: ', asset);
            var obj = { slotID: asset.rktr_slot_id, sizes: asset.sizes };
            bidSlots.push(obj);
        }
    });
    logger.timeEnd('A9 Slot Building');
    var processBids = function processBids(bids) {
        a9bids = bids;
        bidSlots = [];
        done();
    };
    if (bidSlots.length > 0) {
        window.apstag.fetchBids({
            slots: bidSlots
        }, processBids);
    } else {
        logger.log('No valid slots.');
    }
};

var preDispatchCallback = function preDispatchCallback(asset, done) {
    window.googletag.cmd.push(function () {
        var gptSlots = window.googletag.pubads().getSlots();
        if (a9bids) handleA9Bids(a9bids, gptSlots, done);
        if (!a9bids) {
            logger.log('No Bids.');
            done();
        }
    });
};

var preRefreshCallback = function preRefreshCallback(asset, done) {
    a9bids = null;
    logger.time('Refreshing A9 Bids');
    window.apstag.fetchBids({
        slots: bidSlots
    }, function (bids) {
        a9bids = bids;
        logger.timeEnd('Refreshing A9 Bids');
        var gptSlots = window.googletag.pubads().getSlots();
        handleA9Bids(a9bids, gptSlots, done);
    });
};

var registerModuleWithAdFuel = function registerModuleWithAdFuel() {
    if (!blocked) {
        logger.log('Registering ' + MODULE_NAME + ' module with AdFuel');
        window.AdFuel.setOptions({
            queueCallbackTimeoutInMilliseconds: 1000,
            dispatchCallbackTimeoutInMilliseconds: 1000,
            refreshCallbackTimeoutInMilliseconds: 2000
        });
        window.AdFuel.registerModule(MODULE_NAME, {
            preQueueCallback: preQueueCallback,
            preDispatchCallback: preDispatchCallback,
            preRefreshCallback: preRefreshCallback
        });
    }
};

var configureA9Library = function configureA9Library(OPTIONS) {
    var pubId = OPTIONS.A9_DOMESTIC_PUB_ID;
    defaultTimeout = OPTIONS.A9_DEFAULT_VIDEO_TIMEOUT;
    defaultRefreshTimeout = OPTIONS.A9_DEFAULT_VIDEO_REFRESH_TIMEOUT;
    logger.log('Defaulting to Domestic PubId.');
    if (_core.isIntl) {
        logger.log('Is International... Using International PubId.');
        pubId = OPTIONS.A9_INTERNATIONAL_PUB_ID;
    }
    logger.log('Final Pub ID: ', pubId);
    !function (a9, a, p, s, t, A, g) {
        if (a[a9]) return;function q(c, r) {
            a[a9]._Q.push([c, r]);
        }a[a9] = { init: function init() {
                q('i', arguments);
            }, fetchBids: function fetchBids() {
                q('f', arguments);
            }, _Q: [] };A = p.createElement(s);A.async = !0;A.src = t;g = p.getElementsByTagName(s)[0];g.parentNode.insertBefore(A, g);
    }('apstag', window, document, 'script', '//c.amazon-adsystem.com/aax2/apstag.js');
    var bidTimeout = OPTIONS.A9_DEFAULT_VIDEO_TIMEOUT;
    var timeoutOverride = (0, _core.getURLParam)('mdt');
    if (timeoutOverride) {
        bidTimeout = timeoutOverride;
        logger.log('Overriding Max Duration Time: ', bidTimeout);
    }
    var slotName = 'aps-preroll';
    var slotNameOverride = (0, _core.getURLParam)('slotname');
    if (slotNameOverride) {
        slotName = slotNameOverride;
        logger.log('Overriding Slot Name: ', slotName);
    }
    window.apstag.init({
        pubID: pubId,
        adServer: 'googletag',
        videoAdServer: 'freeWheel',
        bidTimeout: bidTimeout
    });
    targetingPromise = new Promise(function (resolve) {
        window.apstag.fetchBids({
            slots: [{
                slotID: slotName,
                mediaType: 'video'
            }]
        }, resolve);
    });
};

var init = function init(OPTIONS) {
    logger.log('Initializing ' + MODULE_NAME + ' Module...');
    configureA9Library(OPTIONS);
    if (window.AdFuel && window.AdFuel.cmd) {
        //AdFuel loaded first
        window.AdFuel.cmd.push(registerModuleWithAdFuel);
    } else if (window.AdFuel) {
        registerModuleWithAdFuel();
    } else {
        (0, _core.addEvent)(document, 'AdFuelCreated', registerModuleWithAdFuel);
    }
    window.A9VideoAPI = {
        getTargetingData: getTargetingData,
        getRefreshedTargetingData: getRefreshedTargetingData
    };
};

exports.default = { init: init };

},{"./core":6,"es6-promise":1}],6:[function(require,module,exports){
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

if (!String.prototype.startsWith) {
    String.prototype.startsWith = function (search, pos) {
        return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
    };
}

var countryCode = (readCookie('CG') ? readCookie('CG').substr(0, 2) : '') || readCookie('countryCode');
var selectedEdition = readCookie('SelectedEdition') ? readCookie('SelectedEdition') : 'www';

var monetizedSizes = ['160x600', '300x250', '300x600', '320x50', '728x90', '970x90', '970x250'];
var invalidMappings = ['_ns_', '_nfs_'];
var invalidAdUnitSegments = ['super-ad-zone', 'super_ad_zone'];
var invalidAdUnits = ['CNN/health', 'CNN/health/healthgrades', 'CNN/health/leaf', 'CNN/health/list', 'CNN/health/photos', 'CNN/health/specials', 'CNN/health/video', 'CNN/student-news'];

function getLogger(moduleName, moduleVersion) {
    var log = noop;
    var info = noop;
    var warn = noop;
    var time = noop;
    var timeEnd = noop;
    var group = noop;
    var groupEnd = noop;
    var error = noop;
    var inGroup = false;
    var args = void 0;

    if (isObject(window.console) && isFunction(window.console.log) && getURLParam('debug') === 'true') {
        log = function log() /* arguments */{
            if (!inGroup) {
                var _args, _window$console;

                args = ['[AdFuelModule - ' + moduleName + ' ' + moduleVersion + ']'];
                (_args = args).push.apply(_args, arguments);
                (_window$console = window.console).log.apply(_window$console, _toConsumableArray(args));
            } else {
                var _window$console2;

                (_window$console2 = window.console).log.apply(_window$console2, arguments);
            }
        };

        info = function info() /* arguments */{
            if (!inGroup) {
                var _args2, _window$console3;

                args = ['[AdFuelModule - ' + moduleName + ' ' + moduleVersion + ']'];
                (_args2 = args).push.apply(_args2, arguments);
                (_window$console3 = window.console).info.apply(_window$console3, _toConsumableArray(args));
            } else {
                var _window$console4;

                (_window$console4 = window.console).info.apply(_window$console4, arguments);
            }
        };

        warn = function warn() /* arguments */{
            if (!inGroup) {
                var _args3, _window$console5;

                args = ['[AdFuelModule - ' + moduleName + ' ' + moduleVersion + ']'];
                (_args3 = args).push.apply(_args3, arguments);
                (_window$console5 = window.console).warn.apply(_window$console5, _toConsumableArray(args));
            } else {
                var _window$console6;

                (_window$console6 = window.console).warn.apply(_window$console6, arguments);
            }
        };

        error = function error() /* arguments */{
            if (!inGroup) {
                var _args4, _window$console7;

                args = ['[AdFuelModule - ' + moduleName + ' ' + moduleVersion + ']'];
                (_args4 = args).push.apply(_args4, arguments);
                (_window$console7 = window.console).error.apply(_window$console7, _toConsumableArray(args));
            } else {
                var _window$console8;

                (_window$console8 = window.console).error.apply(_window$console8, arguments);
            }
        };

        time = function time() /* arguments */{
            var timeKey = void 0;
            if (!inGroup) {
                var _args5, _window$console9;

                args = ['[AdFuelModule - ' + moduleName + ' ' + moduleVersion + ']'];
                (_args5 = args).push.apply(_args5, arguments);
                timeKey = args.join('');
                (_window$console9 = window.console).time.apply(_window$console9, [timeKey]);
            } else {
                var _window$console10;

                timeKey = arguments.join('');
                (_window$console10 = window.console).time.apply(_window$console10, [timeKey]);
            }
        };

        timeEnd = function timeEnd() /* arguments */{
            var timeKey = void 0;
            if (!inGroup) {
                var _args6, _window$console11;

                args = ['[AdFuelModule - ' + moduleName + ' ' + moduleVersion + ']'];
                (_args6 = args).push.apply(_args6, arguments);
                timeKey = args.join('');
                (_window$console11 = window.console).timeEnd.apply(_window$console11, [timeKey]);
            } else {
                var _window$console12;

                timeKey = arguments.join('');
                (_window$console12 = window.console).timeEnd.apply(_window$console12, [timeKey]);
            }
        };

        group = function group(groupName) {
            var tag = '[' + moduleName + ' ' + moduleVersion + '] - ' + groupName;
            inGroup = true;
            window.console.groupCollapsed(tag);
        };

        groupEnd = function groupEnd(groupName) {
            var tag = '[' + moduleName + ' ' + moduleVersion + '] - ' + groupName;
            inGroup = false;
            window.console.groupEnd(tag);
        };
    }

    var logger = {
        log: log,
        info: info,
        warn: warn,
        error: error,
        time: time,
        timeEnd: timeEnd,
        group: group,
        groupEnd: groupEnd
    };

    return logger;
}

var re = /(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})/i;

function piiIsPresentInQueryString() {
    if (document.location.search) {
        var dirtyResults = document.location.search.search(re) + 1;
        var cleanResults = void 0;
        try {
            cleanResults = decodeURIComponent(document.location.search).search(re) + 1;
        } catch (err) {
            cleanResults = dirtyResults;
        }
        return dirtyResults || cleanResults;
    } else {
        return false;
    }
}

function piiIsPresentInHash() {
    if (document.location.hash) {
        var dirtyResults = document.location.hash.search(re) + 1;
        var cleanResults = void 0;
        try {
            cleanResults = decodeURIComponent(document.location.hash).search(re) + 1;
        } catch (err) {
            cleanResults = dirtyResults;
        }
        return dirtyResults || cleanResults;
    } else {
        return false;
    }
}

function piiIsPresentInReferrer() {
    if (document.referrer) {
        var dirtyResults = document.referrer.search(re) + 1;
        var cleanResults = void 0;
        try {
            cleanResults = decodeURIComponent(document.location.referrer).search(re) + 1;
        } catch (err) {
            cleanResults = dirtyResults;
        }
        return dirtyResults || cleanResults;
    } else {
        return false;
    }
}

function filterDFPRequest() {
    if (piiIsPresentInQueryString() || piiIsPresentInHash() || piiIsPresentInReferrer()) {
        console.log('[AdFuelModule - ' + MODULE_NAME + '] Filtering DFP Request due to PII in query string.');
        var AdFuelMethods = Object.getOwnPropertyNames(window.AdFuel);
        for (var x = 0; x < AdFuelMethods.length; x++) {
            window.AdFuel[AdFuelMethods[x]] = function () {};
        }
        window.googletag = null;
    }
}

var piiFilter = {
    qs: piiIsPresentInQueryString,
    hash: piiIsPresentInHash,
    ref: piiIsPresentInReferrer,
    filter: filterDFPRequest
};

var MODULE_NAME = 'AdFuel Core Utilities';
var MODULE_VERSION = 'v1.0.3';

var objectProto = Object.prototype;
var toString = objectProto.toString;
var noop = function noop() {};
var isIntl = false;

var parser = document.createElement('a');
parser.href = document.location.href;

var hostname = parser.hostname;
var pathname = parser.pathname;

var logger = getLogger(MODULE_NAME, MODULE_VERSION);

function addEvent(element, event, fn) {
    if (element.addEventListener) {
        element.addEventListener(event, fn, true);
    } else if (element.attachEvent) {
        element.attachEvent('on' + event, fn);
    }
}

function isFunction(object) {
    return toString.call(object) === '[object Function]';
}

function isObject(object) {
    var type = typeof object === 'undefined' ? 'undefined' : _typeof(object);
    return type === 'function' || type === 'object' && !!object;
}

function getURLParam(name) {
    name = name.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]');
    var regexS = '[\\?&]' + name + '=([^&#]*)';
    var regex = new RegExp(regexS);
    if (document.location.search) {
        var results = regex.exec(document.location.search);
        if (results) {
            return results[1];
        } else {
            return '';
        }
    } else {
        return '';
    }
}

function hasCookie(name) {
    if (typeof window === 'undefined') return;
    return document.cookie && (document.cookie.includes('; ' + name + '=') || document.cookie.indexOf(name + '=') === 0);
}

function readCookie(name) {

    var lsSupport = false;
    var data = null;
    // Check for native support
    if (localStorage) {
        lsSupport = true;
    }

    // No value supplied, return value
    if (typeof value === 'undefined') {
        // Get value
        if (lsSupport) {
            // Native support
            data = localStorage.getItem(name);
        }
        if (!lsSupport || data === null) {
            // Use cookie
            data = readTheCookie(name);
        }

        // Try to parse JSON...
        try {
            data = JSON.parse(data);
        } catch (e) {}

        return data;
    }

    function readTheCookie(key) {
        if (!document.cookie) {
            // there is no cookie, so go no further
            return null;
        } else {
            // there is a cookie
            var ca = document.cookie.split(';');
            var nameEQ = key + '=';
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) === ' ') {
                    //delete spaces
                    c = c.substring(1, c.length);
                }
                if (c.indexOf(nameEQ) === 0) {
                    return c.substring(nameEQ.length, c.length);
                }
            }
            return null;
        }
    }
}

function getViewport() {
    var viewportWidth = void 0;
    var viewportHeight = void 0;
    if (typeof window.innerWidth !== 'undefined') {
        viewportWidth = window.innerWidth, viewportHeight = window.innerHeight;
    } else if (typeof document.documentElement !== 'undefined' && typeof document.documentElement.clientWidth !== 'undefined' && document.documentElement.clientWidth !== 0) {
        viewportWidth = document.documentElement.clientWidth, viewportHeight = document.documentElement.clientHeight;
    } else {
        viewportWidth = document.getElementsByTagName('body')[0].clientWidth, viewportHeight = document.getElementsByTagName('body')[0].clientHeight;
    }
    return [viewportWidth, viewportHeight];
}

function isMonetized(_ref) {
    var rktr_slot_id = _ref.rktr_slot_id,
        rktr_ad_id = _ref.rktr_ad_id,
        responsive = _ref.responsive,
        sizes = _ref.sizes;

    logger.group('Checking Monetization for: ' + rktr_slot_id);
    var slotId = rktr_slot_id;
    var monetized = true;
    var viewportChecked = false;
    var browser = getViewport();
    var responsiveSizes = [];
    var filteredSizes = [];
    invalidMappings.forEach(function (invalidMapping) {
        if (slotId.includes(invalidMapping)) {
            logger.log('Slot includes invalid mapping: ', invalidMapping);
            monetized = false;
        }
    });
    invalidAdUnitSegments.map(function (invalidAdUnitSegment) {
        if (rktr_ad_id.includes(invalidAdUnitSegment)) {
            logger.log('Slot contains an invalid Ad Unit segment: ', invalidAdUnitSegment);
            monetized = false;
        }
        return invalidAdUnitSegment;
    });
    invalidAdUnits.map(function (invalidAdUnit) {
        if (rktr_ad_id === invalidAdUnit) {
            logger.log('Slot uses an invalid Ad Unit: ', invalidAdUnit);
            monetized = false;
        }
        return invalidAdUnit;
    });
    if (responsive && responsive.length > 0) responsive.map(function (viewport) {
        if (!viewportChecked && parseInt(viewport[0][0], 10) < browser[0] && parseInt(viewport[0][1], 10) < browser[1]) {
            viewportChecked = true;
            logger.log('Checking Responsive Sizes: ', viewport, browser);
            responsiveSizes = viewport[1];
            if (viewport[1][0] === 'suppress' || responsiveSizes === 'suppress') {
                logger.log('Slot is suppressed: ', viewport[1][0], responsiveSizes);
                monetized = false;
            }
        }
        return viewport;
    });
    filteredSizes = monetized && responsiveSizes.length > 0 ? responsiveSizes : sizes;
    if (monetized) {
        filteredSizes = filteredSizes.filter(function (size) {
            if (size !== 'suppress') {
                size = size.join('x');
            }
            return monetizedSizes.includes(size);
        });
    }
    if (filteredSizes.length === 0) {
        logger.log('Slot contains no monetized sizes.', filteredSizes);
        monetized = false;
    }
    logger.log('Slot is Monetized: ', monetized);
    logger.groupEnd('Checking Monetization for: ' + slotId);
    return monetized;
}

function hasOwn(object, key) {
    return object !== null && Object.prototype.hasOwnProperty.call(object, key);
}

function once(fn) {
    return function () {
        if (fn) {
            for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
                args[_key] = arguments[_key];
            }

            fn.apply(this, args);
            fn = null;
        }
    };
}

var keyMap = function () {
    var map = {};

    var has = function has(id) {
        return id in map;
    };

    var addKey = function addKey(id, key) {
        if (!has(id)) {
            map[id] = [];
        }
        map[id].push(key);
    };

    var getKeys = function getKeys(id) {
        return has(id) ? Array.prototype.slice.call(map[id]) : [];
    };

    var clearKeys = function clearKeys(id) {
        if (has(id)) {
            map[id].length = 0;
            return true;
        }
        return false;
    };

    return {
        has: has,
        clearKeys: clearKeys,
        getKeys: getKeys,
        addKey: addKey
    };
}();

function roundFloat(value, toNearest, fixed) {
    return (Math.ceil(value / toNearest) * toNearest).toFixed(fixed);
}

function generateCacheBuster() {
    // return_<9-digit-random-hex>
    var cb = '';
    for (var i = 0; i < 10; i++) {
        cb += Math.floor(Math.random() * 9).toString();
    }
    return cb;
}

var debounce = function debounce(func, wait, immediate) {
    var timeout = void 0;
    return function () {
        var context = this;
        var args = arguments;
        var later = function later() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

if (hostname.search(/^(.*)?(edition|arabic)\./) >= 0) {
    logger.log('Full international site. Using International PubId.');
    exports.isIntl = isIntl = true;
} else if (hostname.search(/^(.*)?money/) >= 0 && pathname === '/' && selectedEdition === 'edition') {
    logger.log('International CNN Money Homepage. Using International PubId.');
    exports.isIntl = isIntl = true;
} else if (countryCode === '' || countryCode === null) {
    if (hostname.search(/^(.*)?(cnnespanol|cnne\-test)\./) >= 0) {
        logger.log('No country code. Using International PubId.');
        exports.isIntl = isIntl = true;
    } else {
        logger.log('No country code. Domestic Site.');
    }
} else if (countryCode !== 'US' && countryCode !== 'CA') {
    if (hostname.search(/^(.*)?(money|cnnespanol|cnne\-test|www\.cnn)\./) >= 0) {
        logger.log('International country code. Using International PubId.');
        exports.isIntl = isIntl = true;
    } else {
        logger.log('International country code but domestic site.');
    }
} else {
    logger.log('Domestic site.');
}

function merge(source, mods) {
    var dest = {};
    var attrname = void 0;
    for (attrname in source) {
        if (source.hasOwnProperty(attrname)) {
            dest[attrname] = source[attrname];
        }
    }
    for (attrname in mods) {
        if (mods.hasOwnProperty(attrname)) {
            dest[attrname] = mods[attrname];
        }
    }
    return dest;
}

var metrics = {};

function getMetricTypes() {
    return Object.getOwnPropertyNames(metrics);
}

function getMetricsByType(type) {
    return metrics[type] || {};
}

function getMetricById(type, id) {
    if (type === 'counts' && !metrics[type][id]) {
        return 0;
    } else if (type === 'timeline' && id === 'request_to_dfp') {
        if (!metrics[type][id]) {
            return [];
        }
    }
    return metrics[type][id] || {};
}

function addMetric(metricObject) {
    /*
        Sample Metric Object
        {
        type: timeline|counts|configuration|requests|page|registries|modules|slots
        id: <STRING>
        data: <ANY> For type=counts this should be '+' or '-' to increment or decrement current count.
            For timeline metrics, data should be an object with an index property to use for updates.
            ie: { index: 1, options: { <some options> }, slots: [ 'ad_bnr_atf_01' ], start: <timestamp> }
            On update, the indexes should match:
            ie: { index: 1, end: <timestamp> }
        }
        */
    logger.log('Adding Metric: ', JSON.parse(JSON.stringify(metricObject)));

    var metric = void 0;
    var newMetric = false;
    var data = void 0;

    if (!metrics[metricObject.type]) {
        // Metric type doesn't exist... create it.
        metrics[metricObject.type] = {};
    }
    if (!metrics[metricObject.type][metricObject.id]) {
        metrics[metricObject.type][metricObject.id] = [];
        newMetric = true;
    }

    if (!newMetric) {
        metric = getMetricById(metricObject.type, metricObject.id);
    } else {
        metric = [];
    }

    var currentCount = parseInt(metric);
    var metricIndex = metricObject.data.id || 1;
    switch (metricObject.type) {
        case 'counts':
            if (metric.length === 0) {
                metric = 0;
            }
            if (metricObject.data === '+') {
                currentCount = currentCount + 1;
            } else if (metricObject.data === '-') {
                currentCount = currentCount - 1;
            } else {
                logger.log('Metric data contains no operator for counting metrics.', metricObject);
                return false;
            }
            metrics[metricObject.type][metricObject.id] = currentCount;
            logger.log('Metrics updated with: ', metricObject, metrics);
            break;
        case 'modules':
            if (metricObject.data.callback) {
                var module = window.AdFuel.registeredModules.filter(function (_ref2) {
                    var name = _ref2.name;

                    name === metricObject.id;
                });
                if (Array.isArray(module)) {
                    module = module[0];
                }
                if (metric.length === 0) {
                    metric = {};
                }
                var callbackNames = Object.getOwnPropertyNames(module.callbacks);
                var callbackNameFromData = metricObject.data.callback + 'Callback';
                if (callbackNames.includes(callbackNameFromData)) {
                    for (var name = 0; name < callbackNames.length; name++) {
                        if (!metric[callbackNames[name]]) {
                            metric[callbackNames[name]] = {};
                        }
                        delete metricObject.data.callback;
                        metric[callbackNames[name]] = merge(metric[callbackNames[name]], metricObject.data);
                    }
                }
                metrics[metricObject.type][metricObject.id] = metric;
            } else {
                data = merge(metric, metricObject.data);
                metrics[metricObject.type][metricObject.id] = data;
                logger.log('Metrics updated with: ', metricObject, metrics);
            }
            break;
        case 'requests':
        case 'timeline':
            data = {};
            if (metric.length > 0) {
                data = metric[metricIndex - 1];
            }
            data = merge(data, metricObject.data);
            metrics[metricObject.type][metricObject.id][metricIndex - 1] = data;
            logger.log('Metrics updated with: ', metricObject, metrics);
            break;
        case 'slots':
        default:
            data = merge(metric, metricObject.data);
            metrics[metricObject.type][metricObject.id] = data;
            logger.log('Metrics updated with: ', metricObject, metrics);
            break;

    }
    return true;
}

// return this API object to modules when they register.
var metricApi = { metrics: metrics, getMetricTypes: getMetricTypes, getMetricsByType: getMetricsByType, getMetricById: getMetricById, addMetric: addMetric };

/**
 * isMobile.js v0.4.1
 *
 * A simple library to detect Apple phones and tablets,
 * Android phones and tablets, other mobile devices (like blackberry, mini-opera and windows phone),
 * and any kind of seven inch device, via user agent sniffing.
 *
 * @author: Kai Mallea (kmallea@gmail.com)
 *
 * @license: http://creativecommons.org/publicdomain/zero/1.0/
 */
var apple_phone = /iPhone/i; // Case-insensitive matching

var apple_ipod = /iPod/i;
var apple_tablet = /iPad/i;

var // Match 'Android' AND 'Mobile'
android_phone = /(?=.*\bAndroid\b)(?=.*\bMobile\b)/i;

var android_tablet = /Android/i;
var amazon_phone = /(?=.*\bAndroid\b)(?=.*\bSD4930UR\b)/i;
var amazon_tablet = /(?=.*\bAndroid\b)(?=.*\b(?:KFOT|KFTT|KFJWI|KFJWA|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|KFARWI|KFASWI|KFSAWI|KFSAWA)\b)/i;
var windows_phone = /Windows Phone/i;

var // Match 'Windows' AND 'ARM'
windows_tablet = /(?=.*\bWindows\b)(?=.*\bARM\b)/i;

var other_blackberry = /BlackBerry/i;
var other_blackberry_10 = /BB10/i;
var other_opera = /Opera Mini/i;
var other_chrome = /(CriOS|Chrome)(?=.*\bMobile\b)/i;

var // Match 'Firefox' AND 'Mobile'
other_firefox = /(?=.*\bFirefox\b)(?=.*\bMobile\b)/i;

var seven_inch = new RegExp('(?:' + // Non-capturing group
'Nexus 7' + // Nexus 7
'|' + // OR
'BNTV250' + // B&N Nook Tablet 7 inch
'|' + // OR
'Kindle Fire' + // Kindle Fire
'|' + // OR
'Silk' + // Kindle Fire, Silk Accelerated
'|' + // OR
'GT-P1000' + // Galaxy Tab 7 inch
')', // End non-capturing group
'i');

var match = function match(regex, userAgent) {
    return regex.test(userAgent);
};

var IsMobileClass = function IsMobileClass(userAgent) {
    var ua = userAgent || navigator.userAgent;

    // Facebook mobile app's integrated browser adds a bunch of strings that
    // match everything. Strip it out if it exists.
    var tmp = ua.split('[FBAN');
    if (typeof tmp[1] !== 'undefined') {
        ua = tmp[0];
    }

    // Twitter mobile app's integrated browser on iPad adds a "Twitter for
    // iPhone" string. Same probable happens on other tablet platforms.
    // This will confuse detection so strip it out if it exists.
    tmp = ua.split('Twitter');
    if (typeof tmp[1] !== 'undefined') {
        ua = tmp[0];
    }

    this.apple = {
        phone: match(apple_phone, ua),
        ipod: match(apple_ipod, ua),
        tablet: !match(apple_phone, ua) && match(apple_tablet, ua),
        device: match(apple_phone, ua) || match(apple_ipod, ua) || match(apple_tablet, ua)
    };
    this.amazon = {
        phone: match(amazon_phone, ua),
        tablet: !match(amazon_phone, ua) && match(amazon_tablet, ua),
        device: match(amazon_phone, ua) || match(amazon_tablet, ua)
    };
    this.android = {
        phone: match(amazon_phone, ua) || match(android_phone, ua),
        tablet: !match(amazon_phone, ua) && !match(android_phone, ua) && (match(amazon_tablet, ua) || match(android_tablet, ua)),
        device: match(amazon_phone, ua) || match(amazon_tablet, ua) || match(android_phone, ua) || match(android_tablet, ua)
    };
    this.windows = {
        phone: match(windows_phone, ua),
        tablet: match(windows_tablet, ua),
        device: match(windows_phone, ua) || match(windows_tablet, ua)
    };
    this.other = {
        blackberry: match(other_blackberry, ua),
        blackberry10: match(other_blackberry_10, ua),
        opera: match(other_opera, ua),
        firefox: match(other_firefox, ua),
        chrome: match(other_chrome, ua),
        device: match(other_blackberry, ua) || match(other_blackberry_10, ua) || match(other_opera, ua) || match(other_firefox, ua) || match(other_chrome, ua)
    };
    this.seven_inch = match(seven_inch, ua);
    this.any = this.apple.device || this.android.device || this.windows.device || this.other.device || this.seven_inch;

    // excludes 'other' devices and ipods, targeting touchscreen phones
    this.phone = this.apple.phone || this.android.phone || this.windows.phone;

    // excludes 7 inch devices, classifying as phone or tablet is left to the user
    this.tablet = this.apple.tablet || this.android.tablet || this.windows.tablet;

    if (typeof window === 'undefined') {
        return this;
    }
};

var instantiate = function instantiate() {
    var IM = new IsMobileClass();
    IM.Class = IsMobileClass;
    return IM;
};

var isMobile = instantiate();

addEvent(document, 'AdFuelCreated', filterDFPRequest);

var AdFuelUtils = {
    noop: noop,
    addEvent: addEvent,
    isFunction: isFunction,
    isObject: isObject,
    getURLParam: getURLParam,
    debounce: debounce,
    hasCookie: hasCookie,
    readCookie: readCookie,
    getViewport: getViewport,
    countryCode: countryCode,
    selectedEdition: selectedEdition,
    isMonetized: isMonetized,
    isIntl: isIntl,
    once: once,
    hasOwn: hasOwn,
    keyMap: keyMap,
    merge: merge,
    roundFloat: roundFloat,
    generateCacheBuster: generateCacheBuster,
    metricApi: metricApi,
    isMobile: isMobile,
    getLogger: getLogger,
    piiFilter: piiFilter
};

exports.noop = noop;
exports.addEvent = addEvent;
exports.isFunction = isFunction;
exports.isObject = isObject;
exports.getURLParam = getURLParam;
exports.debounce = debounce;
exports.hasCookie = hasCookie;
exports.readCookie = readCookie;
exports.getViewport = getViewport;
exports.countryCode = countryCode;
exports.selectedEdition = selectedEdition;
exports.isMonetized = isMonetized;
exports.isIntl = isIntl;
exports.once = once;
exports.hasOwn = hasOwn;
exports.keyMap = keyMap;
exports.merge = merge;
exports.roundFloat = roundFloat;
exports.generateCacheBuster = generateCacheBuster;
exports.metricApi = metricApi;
exports.isMobile = isMobile;
exports.getLogger = getLogger;
exports.piiFilter = piiFilter;
exports.default = AdFuelUtils;

},{}],7:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};

// cached from whatever global is present so that test runners that stub it
// don't break things.  But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals.  It's inside a
// function because try/catches deoptimize in certain engines.

var cachedSetTimeout;
var cachedClearTimeout;

function defaultSetTimout() {
    throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
    throw new Error('clearTimeout has not been defined');
}
(function () {
    try {
        if (typeof setTimeout === 'function') {
            cachedSetTimeout = setTimeout;
        } else {
            cachedSetTimeout = defaultSetTimout;
        }
    } catch (e) {
        cachedSetTimeout = defaultSetTimout;
    }
    try {
        if (typeof clearTimeout === 'function') {
            cachedClearTimeout = clearTimeout;
        } else {
            cachedClearTimeout = defaultClearTimeout;
        }
    } catch (e) {
        cachedClearTimeout = defaultClearTimeout;
    }
} ())
function runTimeout(fun) {
    if (cachedSetTimeout === setTimeout) {
        //normal enviroments in sane situations
        return setTimeout(fun, 0);
    }
    // if setTimeout wasn't available but was latter defined
    if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
        cachedSetTimeout = setTimeout;
        return setTimeout(fun, 0);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedSetTimeout(fun, 0);
    } catch(e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
            return cachedSetTimeout.call(null, fun, 0);
        } catch(e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
            return cachedSetTimeout.call(this, fun, 0);
        }
    }


}
function runClearTimeout(marker) {
    if (cachedClearTimeout === clearTimeout) {
        //normal enviroments in sane situations
        return clearTimeout(marker);
    }
    // if clearTimeout wasn't available but was latter defined
    if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
        cachedClearTimeout = clearTimeout;
        return clearTimeout(marker);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedClearTimeout(marker);
    } catch (e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
            return cachedClearTimeout.call(null, marker);
        } catch (e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
            // Some versions of I.E. have different rules for clearTimeout vs setTimeout
            return cachedClearTimeout.call(this, marker);
        }
    }



}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;

function cleanUpNextTick() {
    if (!draining || !currentQueue) {
        return;
    }
    draining = false;
    if (currentQueue.length) {
        queue = currentQueue.concat(queue);
    } else {
        queueIndex = -1;
    }
    if (queue.length) {
        drainQueue();
    }
}

function drainQueue() {
    if (draining) {
        return;
    }
    var timeout = runTimeout(cleanUpNextTick);
    draining = true;

    var len = queue.length;
    while(len) {
        currentQueue = queue;
        queue = [];
        while (++queueIndex < len) {
            if (currentQueue) {
                currentQueue[queueIndex].run();
            }
        }
        queueIndex = -1;
        len = queue.length;
    }
    currentQueue = null;
    draining = false;
    runClearTimeout(timeout);
}

process.nextTick = function (fun) {
    var args = new Array(arguments.length - 1);
    if (arguments.length > 1) {
        for (var i = 1; i < arguments.length; i++) {
            args[i - 1] = arguments[i];
        }
    }
    queue.push(new Item(fun, args));
    if (queue.length === 1 && !draining) {
        runTimeout(drainQueue);
    }
};

// v8 likes predictible objects
function Item(fun, array) {
    this.fun = fun;
    this.array = array;
}
Item.prototype.run = function () {
    this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};

function noop() {}

process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;

process.listeners = function (name) { return [] }

process.binding = function (name) {
    throw new Error('process.binding is not supported');
};

process.cwd = function () { return '/' };
process.chdir = function (dir) {
    throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };

},{}]},{},[2]);
